├── .gitignore
├── ComplexityScript.py
├── LICENSE
├── README.md
├── complexity
├── ApertureMetric.py
├── EsapiApertureMetric.py
├── PyApertureMetric.py
├── PyComplexityMetric.py
├── __init__.py
├── dicomrt.py
└── misc.py
├── metrics_examples.py
├── requirements.txt
├── setup.py
├── test-requirements.txt
└── tests
├── __init__.py
├── conftest.py
├── test_aperture.py
├── test_apertureIrregularityMetric.py
├── test_jaw.py
├── test_leafPair.py
├── test_leafSequenceVariability.py
├── test_modulationComplexityScore.py
├── test_modulationIndexScore.py
├── test_modulationIndexTotal.py
├── test_pyAperture.py
├── test_pyAperturesFromBeamCreator.py
├── test_pyComplexityMetric.py
├── test_pyMetersetsFromMetersetWeightsCreator.py
└── tests_data
└── RP_FiF.dcm
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### JetBrains template
3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
4 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
5 | ### Python ###
6 | # Byte-compiled / optimized / DLL files
7 | __pycache__/
8 | *.py[cod]
9 | *$py.class
10 | /test.py
11 | /Test2.py
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | pip-wheel-metadata/
30 | share/python-wheels/
31 | *.egg-info/
32 | .installed.cfg
33 | *.egg
34 | MANIFEST
35 | # User-specific stuff
36 | .idea/**/workspace.xml
37 | .idea/**/tasks.xml
38 | .idea/**/usage.statistics.xml
39 | .idea/**/dictionaries
40 | .idea/**/shelf
41 |
42 | # Generated files
43 | .idea/**/contentModel.xml
44 |
45 | # Sensitive or high-churn files
46 | .idea/**/dataSources/
47 | .idea/**/dataSources.ids
48 | .idea/**/dataSources.local.xml
49 | .idea/**/sqlDataSources.xml
50 | .idea/**/dynamic.xml
51 | .idea/**/uiDesigner.xml
52 | .idea/**/dbnavigator.xml
53 |
54 | # Gradle
55 | .idea/**/gradle.xml
56 | .idea/**/libraries
57 |
58 | # Gradle and Maven with auto-import
59 | # When using Gradle or Maven with auto-import, you should exclude module files,
60 | # since they will be recreated, and may cause churn. Uncomment if using
61 | # auto-import.
62 | # .idea/artifacts
63 | # .idea/compiler.xml
64 | # .idea/jarRepositories.xml
65 | # .idea/modules.xml
66 | # .idea/*.iml
67 | # .idea/modules
68 | # *.iml
69 | # *.ipr
70 |
71 | # CMake
72 | cmake-build-*/
73 |
74 | # Mongo Explorer plugin
75 | .idea/**/mongoSettings.xml
76 |
77 | # File-based project format
78 | *.iws
79 |
80 | # IntelliJ
81 | out/
82 |
83 | # mpeltonen/sbt-idea plugin
84 | .idea_modules/
85 |
86 | # JIRA plugin
87 | atlassian-ide-plugin.xml
88 |
89 | # Cursive Clojure plugin
90 | .idea/replstate.xml
91 |
92 | # Crashlytics plugin (for Android Studio and IntelliJ)
93 | com_crashlytics_export_strings.xml
94 | crashlytics.properties
95 | crashlytics-build.properties
96 | fabric.properties
97 |
98 | # Editor-based Rest Client
99 | .idea/httpRequests
100 |
101 | # Android studio 3.1+ serialized cache file
102 | .idea/caches/build_file_checksums.ser
103 |
104 | .idea/.gitignore
105 | .idea/ApertureComplexity.iml
106 | .idea/deployment.xml
107 | .idea/inspectionProfiles/
108 | .idea/misc.xml
109 | .idea/modules.xml
110 | .idea/vcs.xml
111 |
--------------------------------------------------------------------------------
/ComplexityScript.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import time
4 |
5 | from complexity.PyComplexityMetric import PyComplexityMetric
6 | from complexity.dicomrt import RTPlan
7 |
8 | if len(sys.argv) != 2:
9 | print("Usage: %s path to DICOM RT-PLAN file *.dcm" % (sys.argv[0]))
10 | sys.exit(1)
11 |
12 | st = time.time()
13 | plan_info = RTPlan(filename=sys.argv[1])
14 | plan_dict = plan_info.get_plan()
15 | beams = [beam for k, beam in plan_dict["beams"].items()]
16 | complexity_obj = PyComplexityMetric()
17 |
18 | complexity_metric = complexity_obj.CalculateForPlan(None, plan_dict)
19 | ed = time.time()
20 | print("elapsed", ed - st)
21 |
22 | _, plan_file = os.path.split(sys.argv[1])
23 |
24 | print("Reference: https://github.com/umro/Complexity")
25 | print("Python version by Victor Gabriel Leandro Alves, D.Sc. - victorgabr@gmail.com")
26 | print("Plan %s aperture complexity: %1.3f [mm-1]: " % (sys.argv[1], complexity_metric))
27 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Aperture Complexity - IMRT/VMAT Plans
2 |
3 | It is a Python 3.x port of the Eclipse ESAPI plug-in script.
4 | As such, it aims to contain the complete functionality of the aperture complexity analysis.
5 |
6 | Since it uses DICOM standard, this module extends the methodology to any TPS that exports DICOM-RP files.
7 |
8 | More on misc.py file
9 |
10 | ## Getting Started
11 |
12 | Calculating weighed plan complexity - only IMRT or VMAT.
13 |
14 |
15 | python ComplexityScript.py path_to_dicom_RP_file
16 |
17 | Plotting aperture complexity per beam aperture using matplotlib.
18 |
19 | ```python
20 | import matplotlib.pyplot as plt
21 |
22 | from complexity.PyComplexityMetric import (
23 | PyComplexityMetric,
24 | MeanAreaMetricEstimator,
25 | AreaMetricEstimator,
26 | ApertureIrregularityMetric,
27 | )
28 | from complexity.dicomrt import RTPlan
29 |
30 | if __name__ == "__main__":
31 | # Path to DICOM RTPLAN file - IMRT/VMAT
32 | # pfile = "RP.dcm"
33 | path_to_rtplan_file = "RP.dcm"
34 |
35 | # Getting planning data from DICOM file.
36 | plan_info = RTPlan(filename=path_to_rtplan_file)
37 | plan_dict = plan_info.get_plan()
38 |
39 | metrics_list = [
40 | PyComplexityMetric,
41 | MeanAreaMetricEstimator,
42 | AreaMetricEstimator,
43 | ApertureIrregularityMetric,
44 | ]
45 | units = ["CI [mm^-1]", "mm^2", "mm^2", "dimensionless"]
46 |
47 | # plotting results
48 | for unit, cc in zip(units, metrics_list):
49 | cc_obj = cc()
50 | # compute per plan
51 | plan_metric = cc_obj.CalculateForPlan(None, plan_dict)
52 | print(f"{cc.__name__} Plan Metric - {plan_metric} {unit}")
53 | for k, beam in plan_dict["beams"].items():
54 | # skip setup fields
55 | if beam["TreatmentDeliveryType"] == "TREATMENT" and beam["MU"] > 0:
56 | fig = plt.figure(figsize=(6, 6))
57 | # create a subplot
58 | ax = fig.add_subplot(111)
59 | cpx_beam_cp = cc_obj.CalculateForBeamPerAperture(
60 | None, plan_dict, beam
61 | )
62 | ax.plot(cpx_beam_cp)
63 | ax.set_xlabel("Control Point")
64 | ax.set_ylabel(f"${unit}$")
65 | txt = f"{file_name} - Beam name: {beam['BeamName']} - {cc.__name__}"
66 | ax.set_title(txt)
67 | plt.show()
68 |
69 | ```
70 | ## Example result
71 | Beam 1
72 |
73 | 
74 |
75 |
76 | ## Requirements
77 | pydicom, numpy, pandas, pytest for unit testing
78 |
79 | ## Installing
80 | python setup.py install
81 |
82 | ## Contributing
83 |
84 | Any bug fixes or improvements are welcome.
85 |
86 | ## Author
87 | Victor Gabriel Leandro Alves, D.Sc.
88 | Copyright 2017-2018
89 |
90 | ## Acknowledgments
91 |
92 | University of Michigan, Radiation Oncology
93 | [https://github.com/umro/Complexity](https://github.com/umro/Complexity)
94 |
--------------------------------------------------------------------------------
/complexity/ApertureMetric.py:
--------------------------------------------------------------------------------
1 | """
2 | ApertureMetric.py
3 |
4 | This module is a Python port of namespace Complexity.ApertureMetric of the Eclipse plug-in script used in the study:
5 | [Predicting deliverability of volumetric-modulated arc therapy (VMAT) plans using aperture complexity analysis]
6 | (http://www.jacmp.org/index.php/jacmp/article/view/6241).
7 | Also, see the blog post [Calculating Aperture Complexity Metrics]
8 | (http://www.carlosjanderson.com/calculating-aperture-complexity-metrics).
9 |
10 | Notes
11 | -----
12 |
13 | .. Original Code:
14 | https://github.com/umro/Complexity
15 |
16 | Python port by. Victor Gabriel Leandro Alves
17 | victorgabr@gmail.com
18 |
19 | """
20 |
21 |
22 | class Rect:
23 | def __init__(self, left: float, top: float, right: float, bottom: float) -> None:
24 | """
25 | Rectangular dimension (used for leaf and jaw positions)
26 | it is relative to the top of the first leaf and the isocenter
27 | :param left:
28 | :param top:
29 | :param right:
30 | :param bottom:
31 | """
32 | self.Left = left
33 | self.Top = top
34 | self.Right = right
35 | self.Bottom = bottom
36 |
37 | def __repr__(self):
38 | return "Position: left: %1.1f top: %1.1f right: %1.1f botton: %1.1f" % (
39 | self.Left,
40 | self.Top,
41 | self.Right,
42 | self.Bottom,
43 | )
44 |
45 |
46 | class Jaw:
47 | def __init__(self, left: float, top: float, right: float, bottom: float) -> None:
48 | self.jaw_position = Rect(left, top, right, bottom)
49 |
50 | @property
51 | def Position(self):
52 | return self.jaw_position
53 |
54 | @Position.setter
55 | def Position(self, value):
56 | self.jaw_position = value
57 |
58 | @property
59 | def Left(self):
60 | return self.jaw_position.Left
61 |
62 | @property
63 | def Top(self):
64 | return self.jaw_position.Top
65 |
66 | @property
67 | def Right(self):
68 | return self.jaw_position.Right
69 |
70 | @property
71 | def Bottom(self):
72 | return self.jaw_position.Bottom
73 |
74 |
75 | class LeafPair:
76 | def __init__(self, left, right, width, top, jaw):
77 | """
78 | Left and right represent the bank A and B, respectively
79 | :param left: float
80 | :param right: float
81 | :param width: float
82 | :param top: float
83 | :param jaw: Jaw object
84 | """
85 | self.position = Rect(left, top, right, top - width)
86 | self.width = width
87 | self.jaw = jaw
88 |
89 | @property
90 | def Position(self):
91 | return self.position
92 |
93 | @Position.setter
94 | def Position(self, value):
95 | self.position = value
96 |
97 | @property
98 | def Left(self):
99 | return self.position.Left
100 |
101 | @property
102 | def Top(self):
103 | return self.position.Top
104 |
105 | @property
106 | def Right(self):
107 | return self.position.Right
108 |
109 | @property
110 | def Bottom(self):
111 | return self.position.Bottom
112 |
113 | @property
114 | def Width(self):
115 | return self.width
116 |
117 | @Width.setter
118 | def Width(self, value):
119 | self.width = value
120 |
121 | @property
122 | def Jaw(self):
123 | """
124 | Each leaf pair contains a reference to the jaw
125 | :return:
126 | """
127 | return self.jaw
128 |
129 | @Jaw.setter
130 | def Jaw(self, value):
131 | self.jaw = value
132 |
133 | def FieldSize(self):
134 | if self.IsOutsideJaw():
135 | return 0.0
136 |
137 | left = max(self.Jaw.Left, self.Left)
138 | right = min(self.Jaw.Right, self.Right)
139 | return right - left
140 |
141 | def FieldArea(self):
142 | return self.FieldSize() * self.OpenLeafWidth()
143 |
144 | def IsOutsideJaw(self):
145 | """
146 | The reason for <= or >= instead of just < or >
147 | is that if the jaw edge is equal to the leaf edge,
148 | it's as if the jaw edge was the leaf edge,
149 | so it's safer to count the leaf as outside,
150 | so that the edges are not counted twice (leaf and jaw edge)
151 | """
152 | return (
153 | (self.Jaw.Top <= self.Bottom)
154 | or (self.Jaw.Bottom >= self.Top)
155 | or (self.Jaw.Left >= self.Right)
156 | or (self.Jaw.Right <= self.Left)
157 | )
158 |
159 | def IsOpen(self):
160 | return self.FieldSize() > 0.0
161 |
162 | def IsOpenButBehindJaw(self):
163 | """
164 | Used to warn the user that there is a leaf behind the jaws,
165 | even though it is open and within the top and bottom jaw edges
166 | """
167 | return (self.FieldSize() > 0.0) and (
168 | self.Jaw.Left > self.Left or self.Jaw.Right < self.Right
169 | )
170 |
171 | def OpenLeafWidth(self):
172 | """
173 | Returns the amount of leaf width that is open,
174 | considering the Position of the jaw
175 | """
176 | if self.IsOutsideJaw():
177 | return 0.0
178 |
179 | top = min(self.Jaw.Top, self.Top)
180 | bottom = max(self.Jaw.Bottom, self.Bottom)
181 |
182 | return top - bottom
183 |
184 |
185 | class Aperture:
186 | """
187 | The first dimension of leafPositions corresponds to the bank,
188 | and the second dimension corresponds to the leaf pair.
189 | Leaf coordinates follow the IEC 61217 standard:
190 |
191 | Negative Y x = isocenter (0, 0)
192 | -
193 | |
194 | |
195 | |
196 | Negative X |----------x----------| Positive X
197 | |
198 | |
199 | |
200 | -
201 | Positive Y
202 |
203 | leafPositions and leafWidths must not be null,
204 | and they must have the same number of leaves
205 |
206 | jaw is the Position of the jaw (cannot be null),
207 | given as:
208 |
209 | left, top, right, bottom; for a completely open jaw, use:
210 |
211 | new double[] { double.MinValue, double.MinValue,
212 | double.MaxValue, double.MaxValue };
213 | """
214 |
215 | # todo translate this doc to python
216 | def __init__(self, leaf_positions, leaf_widths, jaw):
217 | """
218 | :param leaf_positions: Numpy 2D array of floats
219 | :param leaf_widths: Numpy array 1D
220 | :param jaw: list with jaw positions
221 | """
222 | self.jaw = self.CreateJaw(jaw)
223 | self.leaf_pairs = self.CreateLeafPairs(leaf_positions, leaf_widths, self.Jaw)
224 |
225 | def CreateLeafPairs(self, positions, widths, jaw):
226 | """
227 |
228 | :param positions:
229 | :param widths:
230 | :param jaw:
231 | :return:
232 | """
233 | leaf_tops = self.GetLeafTops(widths)
234 |
235 | pairs = []
236 | for i in range(len(widths)):
237 | lp = LeafPair(
238 | positions[0, i], positions[1, i], widths[i], leaf_tops[i], jaw
239 | )
240 | pairs.append(lp)
241 | return pairs
242 |
243 | @staticmethod
244 | def GetLeafTops(widths):
245 | """
246 | Using the leaf widths, creates an array of the location
247 | of all the leaf tops (relative to the isocenter)
248 |
249 | :param widths:
250 | :return:
251 | """
252 | # Todo add unit test
253 | leaf_tops = [0.0] * len(widths)
254 |
255 | # Leaf index right below isocenter
256 | middle_index = int(len(widths) / 2)
257 |
258 | # Do bottom half
259 | for i in range(middle_index + 1, len(widths)):
260 | leaf_tops[i] = leaf_tops[i - 1] - widths[i - 1]
261 |
262 | # Do top half
263 | i = middle_index - 1
264 | while i >= 0:
265 | leaf_tops[i] = leaf_tops[i + 1] + widths[i]
266 | i -= 1
267 |
268 | return leaf_tops
269 |
270 | @staticmethod
271 | def CreateJaw(pos):
272 | """
273 | Creates Jaw object using x and y positions
274 | :param pos: [] position
275 | :return: Jaw
276 | """
277 | return Jaw(pos[0], pos[1], pos[2], pos[3])
278 |
279 | @property
280 | def Jaw(self):
281 | return self.jaw
282 |
283 | @Jaw.setter
284 | def Jaw(self, value):
285 | self.jaw = value
286 |
287 | @property
288 | def LeafPairs(self):
289 | return self.leaf_pairs
290 |
291 | @LeafPairs.setter
292 | def LeafPairs(self, value):
293 | self.leaf_pairs = value
294 |
295 | def HasOpenLeafBehindJaws(self):
296 | truth = [lp.IsOpenButBehindJaw() for lp in self.LeafPairs]
297 | return any(truth)
298 |
299 | def Area(self):
300 | return sum([lp.FieldArea() for lp in self.LeafPairs])
301 |
302 | def side_perimeter(self):
303 | # Python does not support method overloading
304 | if len(self.LeafPairs) == 0:
305 | return 0.0
306 |
307 | # Top end of first leaf pair
308 | perimeter = self.LeafPairs[0].FieldSize()
309 |
310 | for i in range(len(self.LeafPairs)):
311 | perimeter += self.SidePerimeter(self.LeafPairs[i - 1], self.LeafPairs[i])
312 |
313 | # Bottom end of last leaf pair
314 |
315 | perimeter += self.LeafPairs[-1].FieldSize()
316 |
317 | return perimeter
318 |
319 | def SidePerimeter(self, topLeafPair, bottomLeafPair):
320 |
321 | if self.LeafPairsAreOutsideJaw(topLeafPair, bottomLeafPair):
322 | # _____ ________
323 | # | |
324 | # _____|___ |________
325 | # +-------|------|---+
326 | # _|_______| |___|_
327 |
328 | return 0.0
329 |
330 | if self.JawTopIsBelowTopLeafPair(topLeafPair):
331 | #
332 | # _|___ ______|_
333 | # +---|-------|------+
334 | # _____|___ |________
335 | # | |
336 | # _________| |_____
337 |
338 | return bottomLeafPair.FieldSize()
339 |
340 | if self.JawBottomIsAboveBottomLeafPair(bottomLeafPair):
341 | # At this point, the edge between the top and bottom leaf pairs
342 | # should be fully or partially exposed (depending on the jaw)
343 | # ___ _______________
344 | # +-|--|-------+
345 | # _|_|__|_______|_______
346 | # +-------|----+ |
347 | # _________| |_____
348 | return topLeafPair.FieldSize()
349 |
350 | if self.LeafPairsAreDisjoint(topLeafPair, bottomLeafPair):
351 | # ___ __________
352 | # +-|-------|--+
353 | # _|_|___ |__|_______
354 | # +-----|------+ |
355 | # _______| |_____
356 |
357 | return topLeafPair.FieldSize() + bottomLeafPair.FieldSize()
358 |
359 | topEdgeLeft = max(self.Jaw.Left, topLeafPair.Left)
360 | bottomEdgeLeft = max(self.Jaw.Left, bottomLeafPair.Left)
361 | topEdgeRight = min(self.Jaw.Right, topLeafPair.Right)
362 | bottomEdgeRight = min(self.Jaw.Right, bottomLeafPair.Right)
363 |
364 | return abs(topEdgeLeft - bottomEdgeLeft) + abs(topEdgeRight - bottomEdgeRight)
365 |
366 | def LeafPairsAreOutsideJaw(self, topLeafPair, bottomLeafPair):
367 | return topLeafPair.IsOutsideJaw() and bottomLeafPair.IsOutsideJaw()
368 |
369 | def JawTopIsBelowTopLeafPair(self, topLeafPair):
370 | return self.Jaw.Top <= topLeafPair.Bottom
371 |
372 | def JawBottomIsAboveBottomLeafPair(self, bottomLeafPair):
373 | return self.Jaw.Bottom >= bottomLeafPair.Top
374 |
375 | def LeafPairsAreDisjoint(self, topLeafPair, bottomLeafPair):
376 |
377 | return (bottomLeafPair.Left > topLeafPair.Right) or (
378 | bottomLeafPair.Right < topLeafPair.Left
379 | )
380 |
381 |
382 | class EdgeMetricBase:
383 | def Calculate(self, aperture):
384 | return self.DivisionOrDefault(aperture.SidePerimeter(), aperture.Area())
385 |
386 | @staticmethod
387 | def DivisionOrDefault(a, b):
388 | return a / b if b != 0 else 0
389 |
--------------------------------------------------------------------------------
/complexity/EsapiApertureMetric.py:
--------------------------------------------------------------------------------
1 | """
2 | EsapiApertureMetric.py
3 |
4 | This module is a Python port of namespace Complexity.ApertureMetric of the Eclipse plug-in script used in the study:
5 | [Predicting deliverability of volumetric-modulated arc therapy (VMAT) plans using aperture complexity analysis]
6 | (http://www.jacmp.org/index.php/jacmp/article/view/6241).
7 | Also, see the blog post [Calculating Aperture Complexity Metrics]
8 | (http://www.carlosjanderson.com/calculating-aperture-complexity-metrics).
9 |
10 | Notes
11 | -----
12 |
13 |
14 |
15 | .. Original Code:
16 | https://github.com/umro/Complexity
17 |
18 | Python port by. Victor Gabriel Leandro Alves
19 | victorgabr@gmail.com
20 |
21 | """
22 |
23 | from complexity import ApertureMetric
24 | from complexity.ApertureMetric import Aperture
25 |
26 |
27 | class ComplexityMetric:
28 | """
29 | Abstract class that represents any complexity metric
30 | it implements many common methods, but leaves
31 | the actual metric calculation to subclasses
32 | """
33 |
34 | def CalculateForPlan(self, patient, plan):
35 | """
36 | Returns the complexity metric of a plan, calculated as
37 | the weighted sum of the individual metrics for each beam
38 | :param patient: Patient Class
39 | :param plan: Plan class
40 | :return: metric
41 | """
42 | weights = self.GetWeightsPlan(plan)
43 | metrics = self.GetMetricsPlan(patient, plan)
44 | return self.WeightedSum(weights, metrics)
45 |
46 | def GetWeightsPlan(self, plan):
47 | """
48 | Returns the weights of a plan's beams
49 | by default, the weights are the meterset values per beam
50 | :param plan: DicomParser plan dict
51 | """
52 | return self.GetMeterSetsPlan(plan)
53 |
54 | def GetMeterSetsPlan(self, plan):
55 | """
56 | Returns the total metersets of a plan's beams
57 | :param plan:
58 | :return: metersets of a plan's beams
59 | """
60 | return NotImplementedError
61 |
62 | def GetMetricsPlan(self, patient, plan):
63 | """
64 | Returns the unweighted metrics of a plan's beams
65 | :param patient:
66 | :param plan:
67 | :return:
68 | """
69 | return self.CalculateForPlanPerBeam(patient, plan)
70 |
71 | def CalculateForPlanPerBeam(self, patient, plan):
72 | """
73 | Returns the unweighted metrics of a plan's non-setup beams
74 | :param patient:
75 | :param plan:
76 | :return:
77 | """
78 | return NotImplementedError
79 |
80 | def CalculateForBeam(self, patient, plan, beam):
81 | """
82 | Returns the complexity metric of a beam, calculated as
83 | the weighted sum of the individual metrics for each control point
84 | :param patient:
85 | :param plan:
86 | :param beam:
87 | :return:
88 | """
89 | weights = self.GetWeightsBeam(beam)
90 | values = self.GetMetricsBeam(patient, plan, beam)
91 |
92 | return self.WeightedSum(weights, values)
93 |
94 | def GetWeightsBeam(self, beam):
95 | """
96 | Returns the weights of a beam's control points
97 | by default, the weights are the meterset values per control point
98 | :param beam:
99 | :return:
100 | """
101 | return self.GetMetersetsBeam(beam)
102 |
103 | def GetMetersetsBeam(self, beam):
104 | """
105 | Returns the metersets of a beam's control points
106 | :param beam:
107 | :return:
108 | """
109 |
110 | return MetersetsFromMetersetWeightsCreator().Create(beam)
111 |
112 | def GetMetricsBeam(self, patient, plan, beam):
113 | """
114 | Returns the unweighted metrics of a beam's control points
115 | :param patient:
116 | :param plan:
117 | :param beam:
118 | :return:
119 | """
120 | return self.CalculateForBeamPerAperture(patient, plan, beam)
121 |
122 | def CalculateForBeamPerAperture(self, patient, plan, beam):
123 | apertures = self.CreateApertures(patient, plan, beam)
124 | return self.CalculatePerAperture(apertures)
125 |
126 | def CalculatePerAperture(self, param):
127 | """
128 | Returns the unweighted metrics of a list of apertures
129 | it must be overridden by a subclass
130 | :param param:
131 | :return:
132 | """
133 | return NotImplementedError
134 |
135 | def CreateApertures(self, patient, plan, beam):
136 | """
137 | Returns the apertures created from a beam
138 | :param patient:
139 | :param plan:
140 | :param beam:
141 | :return:
142 | """
143 | return AperturesFromBeamCreator().Create(patient, plan, beam)
144 |
145 | def CalculatePerControlPointWeighted(self, patient, plan, beam):
146 | """
147 | Returns the weighted metrics of a beam's control points
148 | :param patient:
149 | :param plan:
150 | :param beam:
151 | :return:
152 | """
153 | return self.WeightedValues(
154 | self.GetWeightsBeam(beam), self.GetMetricsBeam(patient, plan, beam)
155 | )
156 |
157 | def CalculatePerControlPointUnweighted(self, patient, plan, beam):
158 | """
159 | Returns the unweighted metrics of a beam's control points
160 | :param patient:
161 | :param plan:
162 | :param beam:
163 | :return:
164 | """
165 | return self.GetMetricsBeam(patient, plan, beam)
166 |
167 | def CalculatePerControlPointWeightsOnly(self, beam):
168 | """
169 | Returns the weights of a beam's control points
170 | :param beam:
171 | :return:
172 | """
173 | return self.GetWeightsBeam(beam)
174 |
175 | def WeightedSum(self, weights, values):
176 | """
177 | Returns the weighted sum of the given values and weights
178 | :param weights:
179 | :param values:
180 | :return:
181 | """
182 | return sum(self.WeightedValues(weights, values))
183 |
184 | @staticmethod
185 | def WeightedValues(weights, values):
186 | weightSum = sum(weights)
187 | result = []
188 | for i in range(len(values)):
189 | v = (weights[i] / weightSum) * values[i]
190 | result.append(v)
191 | return result
192 |
193 |
194 | class MetersetsFromMetersetWeightsCreator:
195 | def Create(self, beam):
196 | if beam["PrimaryDosimeterUnit"] != "MU" or "MU" not in beam:
197 | return None
198 |
199 | metersetWeights = self.GetMetersetWeights(beam["ControlPointSequence"])
200 | metersets = self.ConvertMetersetWeightsToMetersets(beam["MU"], metersetWeights)
201 |
202 | return self.UndoCummulativeSum(metersets)
203 |
204 | @staticmethod
205 | def GetMetersetWeights(ControlPoints):
206 | return [float(cp.CumulativeMetersetWeight) for cp in ControlPoints]
207 |
208 | @staticmethod
209 | def ConvertMetersetWeightsToMetersets(beamMeterset, metersetWeights):
210 | finalMetersetWeight = metersetWeights[-1]
211 | return [beamMeterset * x / finalMetersetWeight for x in metersetWeights]
212 |
213 | @staticmethod
214 | def UndoCummulativeSum(cummulativeSum):
215 | """
216 | Returns the values whose cummulative sum is "cummulativeSum"
217 | :param cummulativeSum:
218 | :return:
219 | """
220 | values = [0] * len(cummulativeSum)
221 |
222 | delta_prev = 0.0
223 | for i in range(len(values) - 1):
224 | delta_curr = cummulativeSum[i + 1] - cummulativeSum[i]
225 | values[i] = 0.5 * delta_prev + 0.5 * delta_curr
226 | delta_prev = delta_curr
227 |
228 | values[-1] = 0.5 * delta_prev
229 |
230 | return values
231 |
232 |
233 | class AperturesFromBeamCreator:
234 | def Create(self, patient, plan, beam):
235 | apertures = []
236 | leafWidths = self.GetLeafWidths(patient, plan, beam)
237 |
238 | for controlPoint in beam.ControlPointSequence:
239 | leafPositions = self.GetLeafPositions(controlPoint)
240 | jaw = self.CreateJaw(controlPoint)
241 | apertures.append(Aperture(leafPositions, leafWidths, jaw))
242 |
243 | return apertures
244 |
245 | @staticmethod
246 | def CreateJaw(cp):
247 | left = cp.JawPositions.X1
248 | top = cp.JawPositions.Y2
249 | right = cp.JawPositions.X2
250 | bottom = cp.JawPositions.Y1
251 |
252 | return [left, top, right, bottom]
253 |
254 | def GetLeafWidths(self, patient, plan, beam):
255 | return self.GetLeafWidthsFromAria(patient, plan, beam)
256 |
257 | def GetLeafWidthsFromAria(self, patient, plan, beam):
258 | return NotImplementedError
259 |
260 | def GetLeafPositions(self, controlPoint):
261 | # Leaf positions are given from bottom to top by ESAPI,
262 | # but the Aperture class expects them from top to bottom
263 | # leafPositions[i, j] = controlPoint.LeafPositions[i, n - j - 1]
264 |
265 | # return leafPositions
266 | return NotImplementedError
267 |
268 |
269 | class EdgeMetric(ComplexityMetric):
270 | def CalculatePerAperture(self, apertures):
271 | metric = ApertureMetric.EdgeMetricBase()
272 | return [metric.Calculate(aperture) for aperture in apertures]
273 |
--------------------------------------------------------------------------------
/complexity/PyApertureMetric.py:
--------------------------------------------------------------------------------
1 | # Typing imports
2 | from typing import List, Dict
3 | from pydicom.dataset import Dataset
4 |
5 | import numpy as np
6 |
7 | from complexity.ApertureMetric import Aperture, LeafPair, Jaw
8 |
9 |
10 | class PyLeafPair(LeafPair):
11 | def __init__(
12 | self, left: float, right: float, width: float, top: float, jaw: Jaw
13 | ) -> None:
14 | super().__init__(left, right, width, top, jaw)
15 |
16 | def __repr__(self):
17 | txt = "Leaf Pair: left: %1.1f top: %1.1f right: %1.1f botton: %1.1f" % (
18 | self.Left,
19 | self.Top,
20 | self.Right,
21 | self.Bottom,
22 | )
23 |
24 | return txt
25 |
26 |
27 | class PyAperture(Aperture):
28 | def __init__(
29 | self,
30 | leaf_positions: np.ndarray,
31 | leaf_widths: np.ndarray,
32 | jaw: List[float],
33 | gantry_angle: float,
34 | ) -> None:
35 | super().__init__(leaf_positions, leaf_widths, jaw)
36 | self.gantry_angle = gantry_angle
37 |
38 | def CreateLeafPairs(
39 | self, positions: np.ndarray, widths: np.ndarray, jaw: Jaw
40 | ) -> List[PyLeafPair]:
41 | leaf_tops = self.GetLeafTops(widths)
42 |
43 | pairs = []
44 | for i in range(len(widths)):
45 | lp = PyLeafPair(
46 | positions[0, i], positions[1, i], widths[i], leaf_tops[i], jaw
47 | )
48 | pairs.append(lp)
49 | return pairs
50 |
51 | @property
52 | def LeafPairArea(self) -> List[float]:
53 | return [lp.FieldArea() for lp in self.LeafPairs]
54 |
55 | @property
56 | def GantryAngle(self) -> float:
57 | return self.gantry_angle
58 |
59 | @GantryAngle.setter
60 | def GantryAngle(self, value: float):
61 | self.gantry_angle = value
62 |
63 | def __repr__(self):
64 | txt = "Aperture - Gantry: %1.1f" % self.GantryAngle
65 | return txt
66 |
67 |
68 | class PyAperturesFromBeamCreator:
69 | def Create(self, beam: Dict[str, str]) -> List[PyAperture]:
70 |
71 | apertures = []
72 |
73 | leafWidths = self.GetLeafWidths(beam)
74 | cp_jaw = self.CreateJaw(beam)
75 | for controlPoint in beam["ControlPointSequence"]:
76 | gantry_angle = (
77 | float(controlPoint.GantryAngle)
78 | if "GantryAngle" in controlPoint
79 | else beam["GantryAngle"]
80 | )
81 | leafPositions = self.GetLeafPositions(controlPoint)
82 | new_jaw_position = self.get_jaw_position_per_control_point(controlPoint, leafWidths)
83 | if new_jaw_position:
84 | cp_jaw = new_jaw_position
85 | if leafPositions is not None:
86 | apertures.append(
87 | PyAperture(leafPositions, leafWidths, cp_jaw, gantry_angle)
88 | )
89 |
90 | return apertures
91 |
92 | @staticmethod
93 | def CreateJaw(beam: dict) -> List[float]:
94 | """
95 | but the Aperture class expects cartesian y-axis
96 | :param beam:
97 | :return:
98 | """
99 |
100 | # if there is no X jaws, consider open 400 mm
101 | left = float(beam["ASYMX"][0]) if "ASYMX" in beam else -200.0
102 | right = float(beam["ASYMX"][1]) if "ASYMX" in beam else 200.0
103 | top = float(beam["ASYMY"][0]) if "ASYMY" in beam else -200.0
104 | bottom = float(beam["ASYMY"][1]) if "ASYMY" in beam else 200.0
105 |
106 | # invert y axis to match apperture class -top, -botton that uses Varian standard ESAPI
107 | return [left, -top, right, -bottom]
108 |
109 | def GetLeafWidths(self, beam_dict: Dict) -> np.ndarray:
110 | """
111 | Get MLCX leaf width from BeamLimitingDeviceSequence
112 | (300a, 00be) Leaf Position Boundaries Tag
113 |
114 | #TODO HALCYON leaf widths
115 | :param beam_dict: Dicomparser Beam dict from plan_dict
116 | :return: MLCX leaf width
117 | """
118 |
119 | bs = beam_dict["BeamLimitingDeviceSequence"]
120 | # the script only takes MLCX as parameter
121 | for b in bs:
122 | if b.RTBeamLimitingDeviceType in ["MLCX", "MLCX1", "MLCX2"]:
123 | return np.diff(b.LeafPositionBoundaries)
124 |
125 | def GetLeafTops(self, beam_dict: Dict) -> np.ndarray:
126 | """
127 | Get MLCX leaf Tops from BeamLimitingDeviceSequence
128 | (300a, 00be) Leaf Position Boundaries Tag
129 | :param beam_dict: Dicomparser Beam dict from plan_dict
130 | :return: MLCX leaf width
131 | """
132 | bs = beam_dict["BeamLimitingDeviceSequence"]
133 | for b in bs:
134 | if b.RTBeamLimitingDeviceType == "MLCX":
135 | return np.array(b.LeafPositionBoundaries[:-1], dtype=float)
136 |
137 | def GetLeafPositions(self, control_point: Dataset) -> np.ndarray:
138 | """
139 | Leaf positions are given from bottom to top by ESAPI,
140 | but the Aperture class expects them from top to bottom
141 | Leaf Positions are mechanical boundaries projected onto Isocenter plane
142 | # TODO add halcyon MLC positions
143 | :param control_point:
144 | """
145 | if "BeamLimitingDevicePositionSequence" in control_point:
146 | pos = control_point.BeamLimitingDevicePositionSequence[-1]
147 | mlc_open = pos.LeafJawPositions
148 | n_pairs = int(len(mlc_open) / 2)
149 | bank_a_pos = mlc_open[:n_pairs]
150 | bank_b_pos = mlc_open[n_pairs:]
151 |
152 | return np.vstack((bank_a_pos, bank_b_pos))
153 |
154 | def return_jaw_position_from_mlc(self, positions, leafwidths: np.ndarray):
155 | """
156 | Finding left/right isn't hard, just take min and max when they aren't equal
157 | Finding top/bottom is difficult. We need to find the first and last leaf pairs that are touching
158 | Then use the leaf thicknesses to identify that physical location as a distance from the center
159 | """
160 | left_leaves = np.asarray(positions[:len(positions) // 2])
161 | right_leaves = np.asarray(positions[len(positions) // 2:])
162 | left = np.min(left_leaves[left_leaves != right_leaves])
163 | right = np.max(right_leaves[left_leaves != right_leaves])
164 | center = len(positions)//4
165 | top_bottom = np.where(left_leaves != right_leaves)
166 | diff_bottom = center - top_bottom[0][0]
167 | if diff_bottom > 0:
168 | bottom = np.sum(leafwidths[center-diff_bottom:center])
169 | else:
170 | bottom = -np.sum(leafwidths[center:center-diff_bottom])
171 | diff_top = center - top_bottom[0][-1]
172 | if diff_top > 0:
173 | top = np.sum(leafwidths[center-diff_top:center])
174 | else:
175 | top = -np.sum(leafwidths[center:center-diff_top])
176 | return [left, top, right, bottom]
177 |
178 | def get_jaw_position_per_control_point(self, control_point: Dataset, leafwidths: np.ndarray) -> List[float]:
179 | """
180 | Get jaw positions from control point
181 | :param
182 | """
183 | if "BeamLimitingDevicePositionSequence" in control_point:
184 | sequence = control_point.BeamLimitingDevicePositionSequence
185 | # check if there's a jaw position per control point
186 | mlc_jaws = [s.LeafJawPositions for s in sequence if s.RTBeamLimitingDeviceType.find("MLCX") == 0]
187 | x_jaws = [s.LeafJawPositions for s in sequence if s.RTBeamLimitingDeviceType == "X"]
188 | y_jaws = [s.LeafJawPositions for s in sequence if s.RTBeamLimitingDeviceType == "Y"]
189 | x_jaws_asym = [s.LeafJawPositions for s in sequence if s.RTBeamLimitingDeviceType == "ASYMX"]
190 | y_jaws_asym = [s.LeafJawPositions for s in sequence if s.RTBeamLimitingDeviceType == "ASYMY"]
191 | """
192 | Checking first to see if we have jaw positions, which will be 2 points
193 | """
194 | if ((x_jaws and y_jaws) or (x_jaws_asym and y_jaws_asym)) and len(leafwidths) != 28:
195 | if x_jaws:
196 | left, right = x_jaws[0]
197 | top, bottom = y_jaws[0]
198 | return [float(left), float(-top), float(right), float(-bottom)]
199 | if x_jaws_asym:
200 | left, right = x_jaws_asym[0]
201 | top, bottom = y_jaws_asym[0]
202 | return [float(left), float(-top), float(right), float(-bottom)]
203 | elif mlc_jaws and len(leafwidths) == 28: # Make sure it is a Halcyon MLC
204 | """
205 | If we have halcyon style, which has 2N values, 101, 102, ..., 201, 202, ...
206 | https://dicom.innolitics.com/ciods/rt-image/rt-image/30020030/300a00b6/300a011c
207 | """
208 | for mlc_jaw in mlc_jaws:
209 | left, top, right, bottom = self.return_jaw_position_from_mlc(mlc_jaw, leafwidths)
210 | return [float(left), float(-top), float(right), float(-bottom)]
211 | return []
212 |
213 | class PyMetersetsFromMetersetWeightsCreator:
214 | def Create(self, beam: Dict[str, str]) -> np.ndarray:
215 | if beam["PrimaryDosimeterUnit"] != "MU":
216 | return None
217 |
218 | metersetWeights = self.GetMetersetWeights(beam["ControlPointSequence"])
219 | metersets = self.ConvertMetersetWeightsToMetersets(beam["MU"], metersetWeights)
220 |
221 | return self.UndoCummulativeSum(metersets)
222 |
223 | def GetCumulativeMetersets(self, beam):
224 | metersetWeights = self.GetMetersetWeights(beam["ControlPointSequence"])
225 | metersets = self.ConvertMetersetWeightsToMetersets(beam["MU"], metersetWeights)
226 | return metersets
227 |
228 | @staticmethod
229 | def GetMetersetWeights(ControlPoints):
230 | return np.array(
231 | [cp.CumulativeMetersetWeight for cp in ControlPoints], dtype=float
232 | )
233 |
234 | @staticmethod
235 | def ConvertMetersetWeightsToMetersets(beamMeterset, metersetWeights):
236 | return beamMeterset * metersetWeights / metersetWeights[-1]
237 |
238 | @staticmethod
239 | def UndoCummulativeSum(cummulativeSum):
240 | """
241 | Returns the values whose cummulative sum is "cummulativeSum"
242 | :param cummulativeSum:
243 | :return:
244 | """
245 |
246 | values = np.zeros(len(cummulativeSum))
247 | delta_prev = 0.0
248 | for i in range(len(values) - 1):
249 | delta_curr = cummulativeSum[i + 1] - cummulativeSum[i]
250 | values[i] = 0.5 * delta_prev + 0.5 * delta_curr
251 | delta_prev = delta_curr
252 |
253 | values[-1] = 0.5 * delta_prev
254 |
255 | return values
256 |
--------------------------------------------------------------------------------
/complexity/PyComplexityMetric.py:
--------------------------------------------------------------------------------
1 | import numpy
2 | import numpy as np
3 |
4 | from complexity.ApertureMetric import EdgeMetricBase
5 | from complexity.EsapiApertureMetric import ComplexityMetric
6 | from complexity.PyApertureMetric import (
7 | PyAperturesFromBeamCreator,
8 | PyMetersetsFromMetersetWeightsCreator,
9 | PyAperture,
10 | )
11 |
12 | from typing import Dict, List
13 |
14 |
15 | class PyEdgeMetricBase(EdgeMetricBase):
16 | def Calculate(self, aperture: PyAperture) -> float:
17 | return self.DivisionOrDefault(aperture.side_perimeter(), aperture.Area())
18 |
19 | @staticmethod
20 | def DivisionOrDefault(a: float, b: float) -> float:
21 | return a / b if b != 0 else 0.0
22 |
23 |
24 | class PyComplexityMetric(ComplexityMetric):
25 | # TODO add unit tests
26 |
27 | def CalculateForPlan(
28 | self, patient: None = None, plan: Dict[str, str] = None
29 | ) -> float:
30 | """
31 | Returns the complexity metric of a plan, calculated as
32 | the weighted sum of the individual metrics for each beam
33 | :param patient: Patient Class
34 | :param plan: Plan class
35 | :return: metric
36 | """
37 | weights = self.GetWeightsPlan(plan)
38 | metrics = self.GetMetricsPlan(patient, plan)
39 |
40 | return self.WeightedSum(weights, metrics)
41 |
42 | def GetWeightsPlan(self, plan: Dict[str, str]) -> List[float]:
43 | """
44 | Returns the weights of a plan's beams
45 | by default, the weights are the meterset values per beam
46 | :param plan: DicomParser plan dict
47 | """
48 | return self.GetMeterSetsPlan(plan)
49 |
50 | def GetMeterSetsPlan(self, plan: Dict[str, str]) -> List[float]:
51 | """
52 | Returns the total metersets of a plan's beams
53 | :param plan: DicomParser plan dictionaty
54 | :return: metersets of a plan's beams
55 | """
56 |
57 | metersets = []
58 | for k, beam in plan["beams"].items():
59 | if "MU" in beam:
60 | if beam["MU"] > 0:
61 | metersets.append(float(beam["MU"]))
62 |
63 | return metersets
64 |
65 | def GetMetersetsBeam(self, beam: Dict[str, str]) -> np.ndarray:
66 | """
67 | Returns the metersets of a beam's control points
68 | :param beam:
69 | :return:
70 | """
71 | return PyMetersetsFromMetersetWeightsCreator().Create(beam)
72 |
73 | def CalculateForPlanPerBeam(
74 | self, patient: None, plan: Dict[str, str]
75 | ) -> List[float]:
76 | """
77 | Returns the unweighted metrics of a plan's non-setup beams
78 | :param patient:
79 | :param plan:
80 | :return:
81 | """
82 | values = []
83 | for k, beam in plan["beams"].items():
84 | # check if treatment beam
85 | if beam["TreatmentDeliveryType"] == "TREATMENT":
86 | if beam["MU"] > 0.0:
87 | v = self.CalculateForBeam(patient, plan, beam)
88 | values.append(v)
89 |
90 | return values
91 |
92 | def CalculatePerAperture(self, apertures: List[PyAperture]) -> List[float]:
93 | metric = PyEdgeMetricBase()
94 | return [metric.Calculate(aperture) for aperture in apertures]
95 |
96 | def CalculateForBeamPerAperture(
97 | self, patient: None, plan: Dict[str, str], beam: Dict[str, str]
98 | ) -> List[float]:
99 | apertures = self.CreateApertures(patient, plan, beam)
100 | return self.CalculatePerAperture(apertures)
101 |
102 | def CreateApertures(
103 | self, patient: None, plan: Dict[str, str], beam: Dict[str, str]
104 | ) -> List[PyAperture]:
105 | """
106 | Added default parameter to meet Liskov substitution principle
107 | :param patient:
108 | :param plan:
109 | :param beam:
110 | :return:
111 | """
112 | return PyAperturesFromBeamCreator().Create(beam)
113 |
114 |
115 | class MeanApertureAreaMetric:
116 | def Calculate(self, aperture):
117 | """
118 | Calculates the mean aperture area of all leaf pairs
119 | :param aperture:
120 | :return:
121 | """
122 | areas = np.array(aperture.LeafPairArea)
123 | return areas[np.nonzero(areas)].mean()
124 |
125 |
126 | class MeanAreaMetricEstimator(PyComplexityMetric):
127 | def CalculatePerAperture(self, apertures):
128 | metric = MeanApertureAreaMetric()
129 | return [metric.Calculate(aperture) for aperture in apertures]
130 |
131 |
132 | class ApertureAreaMetric:
133 | def Calculate(self, aperture):
134 | """
135 | return the aperture area.
136 | :param aperture:
137 | :return:
138 | """
139 | return aperture.Area()
140 |
141 |
142 | class AreaMetricEstimator(PyComplexityMetric):
143 | def CalculatePerAperture(self, apertures):
144 | metric = ApertureAreaMetric()
145 | return [metric.Calculate(aperture) for aperture in apertures]
146 |
147 |
148 | class ApertureIrregularity:
149 | def Calculate(self, aperture):
150 | aa = aperture.Area()
151 | ap = aperture.side_perimeter()
152 | return self.DivisionOrDefault(ap ** 2, 4 * np.pi * aa)
153 |
154 | @staticmethod
155 | def DivisionOrDefault(a, b):
156 | return a / b if b != 0 else 0
157 |
158 |
159 | class ApertureIrregularityMetric(PyComplexityMetric):
160 | def CalculatePerAperture(self, apertures):
161 | """
162 | Du W, Cho SH, Zhang X, Hoffman KE, Kudchadker RJ. Quantification of beam
163 | complexity in intensity-modulated radiation therapy treatment plans. Med
164 | Phys 2014;41:21716. http://dx.doi.org/10.1118/1.4861821.
165 | :param apertures: list of beam apertures
166 | :return:
167 | """
168 | metric = ApertureIrregularity()
169 | return [metric.Calculate(aperture) for aperture in apertures]
170 |
--------------------------------------------------------------------------------
/complexity/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/victorgabr/ApertureComplexity/fbb25e756dd2a7b265a77cb6903fe69e868cce6e/complexity/__init__.py
--------------------------------------------------------------------------------
/complexity/dicomrt.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2009-2016 Aditya Panchal
2 | # Copyright (c) 2009-2010 Roy Keyes
3 | # This class is derived from dicomparser.py of dicompyler-core, released under a BSD license.
4 | # See the file license.txt included with this distribution, also
5 | # available at https://github.com/dicompyler/dicompyler-core/
6 | from typing import Dict
7 |
8 | import numpy as np
9 | import pydicom as dicom
10 | from pydicom.valuerep import IS
11 |
12 |
13 | class RTPlan:
14 | """Class that parses and returns formatted DICOM RT Plan data."""
15 |
16 | def __init__(self, filename: str) -> None:
17 |
18 | if filename:
19 | self.plan = dict()
20 | try:
21 | # Only pydicom 0.9.5 and above supports the force read argument
22 | if dicom.__version__ >= "0.9.5":
23 | self.ds = dicom.read_file(filename, defer_size=100, force=True)
24 | else:
25 | self.ds = dicom.read_file(filename, defer_size=100)
26 | except (EOFError, IOError):
27 | # Raise the error for the calling method to handle
28 | raise
29 | else:
30 | # Sometimes DICOM files may not have headers, but they should always
31 | # have a SOPClassUID to declare what type of file it is. If the
32 | # file doesn't have a SOPClassUID, then it probably isn't DICOM.
33 | if "SOPClassUID" not in self.ds:
34 | raise AttributeError
35 | else:
36 | raise AttributeError
37 |
38 | def get_plan(self) -> Dict[str, str]:
39 | """Returns the plan information."""
40 | self.plan["label"] = self.ds.RTPlanLabel
41 | self.plan["date"] = self.ds.RTPlanDate
42 | self.plan["time"] = self.ds.RTPlanTime
43 | self.plan["name"] = ""
44 | self.plan["rxdose"] = 0.0
45 | if "DoseReferenceSequence" in self.ds:
46 | for item in self.ds.DoseReferenceSequence:
47 | if item.DoseReferenceStructureType == "SITE":
48 | self.plan["name"] = "N/A"
49 | if "DoseReferenceDescription" in item:
50 | self.plan["name"] = item.DoseReferenceDescription
51 | if "TargetPrescriptionDose" in item:
52 | rxdose = item.TargetPrescriptionDose * 100
53 | if rxdose > self.plan["rxdose"]:
54 | self.plan["rxdose"] = rxdose
55 | elif item.DoseReferenceStructureType == "VOLUME":
56 | if "TargetPrescriptionDose" in item:
57 | self.plan["rxdose"] = item.TargetPrescriptionDose * 100
58 | if ("FractionGroupSequence" in self.ds) and (self.plan["rxdose"] == 0):
59 | fg = self.ds.FractionGroupSequence[0]
60 | if ("ReferencedBeamSequence" in fg) and ("NumberofFractionsPlanned" in fg):
61 | beams = fg.ReferencedBeamSequence
62 | fx = fg.NumberofFractionsPlanned
63 | for beam in beams:
64 | if "BeamDose" in beam:
65 | self.plan["rxdose"] += beam.BeamDose * fx * 100
66 |
67 | if "FractionGroupSequence" in self.ds:
68 | fg = self.ds.FractionGroupSequence[0]
69 | if "ReferencedBeamSequence" in fg:
70 | self.plan["fractions"] = fg.NumberOfFractionsPlanned
71 | self.plan["rxdose"] = int(self.plan["rxdose"])
72 |
73 | # referenced beams
74 | ref_beams = self.get_beams()
75 | self.plan["beams"] = ref_beams
76 |
77 | # try estimate the number of isocenters
78 | isos = np.array([ref_beams[i]["IsocenterPosition"] for i in ref_beams])
79 |
80 | # round to 2 decimals
81 | isos = np.round(isos, 2)
82 | dist = np.sqrt(np.sum((isos - isos[0]) ** 2, axis=1))
83 | self.plan["n_isocenters"] = len(np.unique(dist))
84 |
85 | # Total number of MU
86 | total_mu = np.sum(
87 | [ref_beams[b]["MU"] for b in ref_beams if "MU" in ref_beams[b]]
88 | )
89 | self.plan["Plan_MU"] = total_mu
90 |
91 | tmp = self.get_study_info()
92 | self.plan["description"] = tmp["description"]
93 | if "RTPlanName" in self.ds:
94 | self.plan["plan_name"] = self.ds.RTPlanName
95 | else:
96 | self.plan["plan_name"] = ""
97 | if "PatientsName" in self.ds:
98 | name = (
99 | self.ds.PatientsName.family_comma_given()
100 | .replace(",", "")
101 | .replace("^", " ")
102 | .strip()
103 | )
104 | self.plan["patient_name"] = name
105 | else:
106 | self.plan["patient_name"] = ""
107 | return self.plan
108 |
109 | def get_beams(self, fx: int = 0) -> Dict[IS, Dict[str, str]]:
110 | """Return the referenced beams from the specified fraction."""
111 |
112 | beams = {}
113 | if "BeamSequence" in self.ds:
114 | bdict = self.ds.BeamSequence
115 | elif "IonBeamSequence" in self.ds:
116 | bdict = self.ds.IonBeamSequence
117 | else:
118 | return beams
119 | # Obtain the beam information
120 | for bi in bdict:
121 | beam = dict()
122 | beam["Manufacturer"] = bi.Manufacturer if "Manufacturer" in bi else ""
123 | beam["InstitutionName"] = (
124 | bi.InstitutionName if "InstitutionName" in bi else ""
125 | )
126 | beam["TreatmentMachineName"] = (
127 | bi.TreatmentMachineName if "TreatmentMachineName" in bi else ""
128 | )
129 | beam["BeamName"] = bi.BeamName if "BeamName" in bi else ""
130 | beam["SourcetoSurfaceDistance"] = (
131 | bi.SourcetoSurfaceDistance if "SourcetoSurfaceDistance" in bi else ""
132 | )
133 | beam["BeamDescription "] = (
134 | bi.BeamDescription if "BeamDescription" in bi else ""
135 | )
136 | beam["BeamType"] = bi.BeamType if "BeamType" in bi else ""
137 | beam["RadiationType"] = bi.RadiationType if "RadiationType" in bi else ""
138 | beam["ManufacturerModelName"] = (
139 | bi.ManufacturerModelName if "ManufacturerModelName" in bi else ""
140 | )
141 | beam["PrimaryDosimeterUnit"] = (
142 | bi.PrimaryDosimeterUnit if "PrimaryDosimeterUnit" in bi else ""
143 | )
144 | beam["NumberofWedges"] = bi.NumberofWedges if "NumberofWedges" in bi else ""
145 | beam["NumberofCompensators"] = (
146 | bi.NumberofCompensators if "NumberofCompensators" in bi else ""
147 | )
148 | beam["NumberofBoli"] = bi.NumberofBoli if "NumberofBoli" in bi else ""
149 | beam["NumberofBlocks"] = bi.NumberofBlocks if "NumberofBlocks" in bi else ""
150 | ftemp = (
151 | bi.FinalCumulativeMetersetWeight
152 | if "FinalCumulativeMetersetWeight" in bi
153 | else ""
154 | )
155 | beam["FinalCumulativeMetersetWeight"] = ftemp
156 | beam["NumberofControlPoints"] = (
157 | bi.NumberofControlPoints if "NumberofControlPoints" in bi else ""
158 | )
159 | beam["TreatmentDeliveryType"] = (
160 | bi.TreatmentDeliveryType if "TreatmentDeliveryType" in bi else ""
161 | )
162 |
163 | # adding mlc info from BeamLimitingDeviceSequence
164 | beam_limits = (
165 | bi.BeamLimitingDeviceSequence
166 | if "BeamLimitingDeviceSequence" in bi
167 | else ""
168 | )
169 | beam["BeamLimitingDeviceSequence"] = beam_limits
170 |
171 | # Check control points if exists
172 | if "ControlPointSequence" in bi:
173 | beam["ControlPointSequence"] = bi.ControlPointSequence
174 | # control point 0
175 | cp0 = bi.ControlPointSequence[0]
176 | # final control point
177 | final_cp = bi.ControlPointSequence[-1]
178 |
179 | beam["NominalBeamEnergy"] = (
180 | cp0.NominalBeamEnergy if "NominalBeamEnergy" in cp0 else ""
181 | )
182 | beam["DoseRateSet"] = cp0.DoseRateSet if "DoseRateSet" in cp0 else ""
183 | beam["IsocenterPosition"] = (
184 | cp0.IsocenterPosition if "IsocenterPosition" in cp0 else ""
185 | )
186 | beam["GantryAngle"] = cp0.GantryAngle if "GantryAngle" in cp0 else ""
187 |
188 | # check VMAT delivery
189 | if "GantryRotationDirection" in cp0:
190 | if cp0.GantryRotationDirection != "NONE":
191 |
192 | # VMAT Delivery
193 | beam["GantryRotationDirection"] = (
194 | cp0.GantryRotationDirection
195 | if "GantryRotationDirection" in cp0
196 | else ""
197 | )
198 |
199 | # last control point angle
200 | if final_cp.GantryRotationDirection == "NONE":
201 | final_angle = (
202 | bi.ControlPointSequence[-1].GantryAngle
203 | if "GantryAngle" in cp0
204 | else ""
205 | )
206 | beam["GantryFinalAngle"] = final_angle
207 |
208 | btmp = (
209 | cp0.BeamLimitingDeviceAngle
210 | if "BeamLimitingDeviceAngle" in cp0
211 | else ""
212 | )
213 | beam["BeamLimitingDeviceAngle"] = btmp
214 | beam["TableTopEccentricAngle"] = (
215 | cp0.TableTopEccentricAngle
216 | if "TableTopEccentricAngle" in cp0
217 | else ""
218 | )
219 |
220 | # check beam limits
221 | if "BeamLimitingDevicePositionSequence" in cp0:
222 | for bl in cp0.BeamLimitingDevicePositionSequence:
223 | beam[bl.RTBeamLimitingDeviceType] = bl.LeafJawPositions
224 |
225 | # Ion control point sequence
226 | if "IonControlPointSequence" in bi:
227 | beam["IonControlPointSequence"] = bi.IonControlPointSequence
228 | cp0 = bi.IonControlPointSequence[0]
229 | beam["NominalBeamEnergyUnit"] = (
230 | cp0.NominalBeamEnergyUnit if "NominalBeamEnergyUnit" in cp0 else ""
231 | )
232 | beam["NominalBeamEnergy"] = (
233 | cp0.NominalBeamEnergy if "NominalBeamEnergy" in cp0 else ""
234 | )
235 | beam["DoseRateSet"] = cp0.DoseRateSet if "DoseRateSet" in cp0 else ""
236 | beam["IsocenterPosition"] = (
237 | cp0.IsocenterPosition if "IsocenterPosition" in cp0 else ""
238 | )
239 | beam["GantryAngle"] = cp0.GantryAngle if "GantryAngle" in cp0 else ""
240 | btmp1 = (
241 | cp0.BeamLimitingDeviceAngle
242 | if "BeamLimitingDeviceAngle" in cp0
243 | else ""
244 | )
245 | beam["BeamLimitingDeviceAngle"] = btmp1
246 |
247 | # add each beam to beams dict
248 | beams[bi.BeamNumber] = beam
249 |
250 | # Obtain the referenced beam info from the fraction info
251 | if "FractionGroupSequence" in self.ds:
252 | fg = self.ds.FractionGroupSequence[fx]
253 | if "ReferencedBeamSequence" in fg:
254 | rb = fg.ReferencedBeamSequence
255 | nfx = fg.NumberOfFractionsPlanned
256 | for bi in rb:
257 | if "BeamDose" in bi:
258 | # dose in cGy
259 | beams[bi.ReferencedBeamNumber]["dose"] = bi.BeamDose * nfx * 100
260 | if "BeamMeterset" in bi:
261 | beams[bi.ReferencedBeamNumber]["MU"] = float(bi.BeamMeterset)
262 | return beams
263 |
264 | def get_study_info(self) -> Dict[str, str]:
265 | """Return the study information of the current file."""
266 |
267 | study = {}
268 | if "StudyDescription" in self.ds:
269 | desc = self.ds.StudyDescription
270 | else:
271 | desc = "No description"
272 | study["description"] = desc
273 | # Don't assume that every dataset includes a study UID
274 | study["id"] = self.ds.SeriesInstanceUID
275 | if "StudyInstanceUID" in self.ds:
276 | study["id"] = self.ds.StudyInstanceUID
277 |
278 | return study
279 |
--------------------------------------------------------------------------------
/complexity/misc.py:
--------------------------------------------------------------------------------
1 | """Classes to estimate many complexity metrics"""
2 | # Copyright (c) 2017-2018 Victor G. L. Alves
3 |
4 | import numpy as np
5 | import pandas as pd
6 | from scipy import integrate
7 |
8 | from complexity.PyApertureMetric import (
9 | PyMetersetsFromMetersetWeightsCreator,
10 | PyAperturesFromBeamCreator,
11 | )
12 | from complexity.PyComplexityMetric import PyComplexityMetric
13 |
14 |
15 | class LeafSequenceVariability:
16 | def Calculate(self, aperture, aav_norm):
17 | """
18 | variability in segment shape for a
19 | specific plan. The shape of each segment is considered,
20 | based on the change in leaf position between adjacent MLC
21 | leaves. This is calculated for leaves on each bank that define
22 | a specific segment. The LSV is defined using N, the number
23 | of open leaves constituting the beam and the coordinates of
24 | the leaf positions. Leaves are not considered if they are
25 | positioned under the jaws. The position of each leaf is incor-
26 | porated by defining pos max .
27 | The second IMRT segment characteristic that is considered
28 | for the overall determination of complexity is the area
29 | of the beam aperture. The aperture area variability AAV is
30 | used to characterize the variation in segment area relative to
31 | the maximum aperture defined by all of the segments. Segments
32 | that are more similar in area to the maximum beam
33 | aperture contribute to a larger score.
34 |
35 | Reference:
36 | McNiven AL, Sharpe MB, Purdie TG. A new metric for assessing IMRT
37 | modulation complexity and plan deliverability. Med Phys 2010;37:505–15.
38 | http://dx.doi.org/10.1118/1.3276775.
39 |
40 | :param aav_norm: Maximum aperture area
41 | :param aperture: Control point PyAperture class
42 | :return: product LSV * AAV
43 | """
44 |
45 | pos = [
46 | (lp.Left, lp.Right) for lp in aperture.LeafPairs if not lp.IsOutsideJaw()
47 | ]
48 | N = len(pos)
49 | pos_max = np.max(pos, axis=0) - np.min(pos, axis=0)
50 | tmp = np.sum(pos_max + np.diff(pos, axis=0), axis=0) / (N * pos_max)
51 | LSV = np.prod(tmp)
52 |
53 | num = sum(
54 | ([lp.FieldSize() for lp in aperture.LeafPairs if not lp.IsOutsideJaw()])
55 | )
56 | AAV = self.DivisionOrDefault(num, aav_norm)
57 |
58 | return LSV * AAV
59 |
60 | @staticmethod
61 | def DivisionOrDefault(a, b):
62 | return a / b if b != 0 else 0
63 |
64 |
65 | class ModulationComplexityScore(PyComplexityMetric):
66 | """ Reference:
67 | McNiven AL, Sharpe MB, Purdie TG. A new metric for assessing IMRT
68 | modulation complexity and plan deliverability. Med Phys 2010;37:505–15.
69 | http://dx.doi.org/10.1118/1.3276775."""
70 |
71 | def CalculatePerAperture(self, apertures):
72 | aav_norm = 0
73 | for aperture in apertures:
74 | posi = [
75 | (lp.Left, lp.Right)
76 | for lp in aperture.LeafPairs
77 | if not lp.IsOutsideJaw()
78 | ]
79 | posi_max = np.max(posi, axis=0)
80 | aav_norm += abs(posi_max[1] - posi_max[0])
81 | metric = LeafSequenceVariability()
82 |
83 | return [metric.Calculate(aperture, aav_norm) for aperture in apertures]
84 |
85 |
86 | class ModulationIndexScore(PyComplexityMetric):
87 |
88 | def CalculateForPlan(self, patient=None, plan=None, k=0.02):
89 | """
90 | Jong Min Park et al - "Modulation indices for volumetric modulated arc therapy"
91 | https://iopscience.iop.org/article/10.1088/0031-9155/59/23/7315
92 | See table 1
93 | """
94 | apertures = []
95 | cumulative_metersets = []
96 | meterset_creator = PyMetersetsFromMetersetWeightsCreator()
97 | for k, beam in plan["beams"].items():
98 | if "MU" in beam:
99 | apertures += PyAperturesFromBeamCreator().Create(beam)
100 | cum = meterset_creator.GetCumulativeMetersets(beam)
101 | cumulative_metersets.append(cum)
102 |
103 | cumulative_mu = np.concatenate(cumulative_metersets)
104 | mid = ModulationIndexTotal(apertures, cumulative_mu)
105 | return mid.calculate_integrate(k=k)
106 |
107 | def CalculateForBeam(self, patient, plan, beam, k=0.02):
108 | apertures = PyAperturesFromBeamCreator().Create(beam)
109 | cumulative_metersets = PyMetersetsFromMetersetWeightsCreator().GetCumulativeMetersets(
110 | beam
111 | )
112 | mid = ModulationIndexTotal(apertures, cumulative_metersets)
113 | return mid.calculate_integrate(k=k)
114 |
115 |
116 | class ModulationIndexTotal:
117 | def __init__(self, apertures, cumulative_mu):
118 | # beam data
119 | self.apertures = apertures
120 | self.Ncp = len(self.apertures)
121 |
122 | # meterset data
123 | self.cumulative_mu = self.get_mu_data(cumulative_mu)
124 |
125 | # MLC position data
126 | self.mlc_positions = self.get_positions(self.apertures)
127 | self.mlc_speed = (
128 | self.mlc_positions.diff().abs().T / self.cumulative_mu["time"]
129 | ).T
130 | self.mlc_speed_std = self.mlc_speed.std()
131 | self.mlc_acceleration = (
132 | self.mlc_speed.diff().abs().T / self.cumulative_mu["time"]
133 | ).T
134 | self.mlc_acceleration_std = self.mlc_acceleration.std()
135 |
136 | # gantry data
137 | gantry_angles = np.array([ap.GantryAngle for ap in self.apertures])
138 | self.gantry = pd.DataFrame(gantry_angles, columns=["gantry"])
139 | self.gantry["delta_gantry"] = self.rolling_apply(
140 | self.delta_gantry, gantry_angles
141 | )
142 | self.gantry["gantry_speed"] = (
143 | self.gantry["delta_gantry"] / self.cumulative_mu["time"]
144 | )
145 | self.gantry["delta_gantry_speed"] = self.gantry["gantry_speed"].diff().abs()
146 | self.gantry["gantry_acc"] = (
147 | self.gantry["delta_gantry_speed"] / self.cumulative_mu["time"]
148 | )
149 |
150 | # dose rate data
151 | self.dose_rate = pd.DataFrame(
152 | self.cumulative_mu["delta_mu"] / self.cumulative_mu["time"], columns=["DR"]
153 | )
154 | self.dose_rate["delta_dose_rate"] = self.dose_rate.diff().abs()
155 |
156 | def get_mu_data(self, cumulative_mu):
157 | # meterset data
158 | tmp = pd.DataFrame(cumulative_mu, columns=["MU"])
159 | tmp["delta_mu"] = tmp.diff().abs()
160 | tmp["time"] = tmp["delta_mu"].apply(self.calculate_time)
161 | return tmp
162 |
163 | @staticmethod
164 | def calculate_time(delta_mu):
165 | """
166 | Calculate time between control points in seconds
167 | :param delta_mu:
168 | :return: time in seconds
169 | """
170 | if delta_mu <= 4.238:
171 | return 2.0341 / 4.8
172 | elif delta_mu > 4.238:
173 | return delta_mu / 10
174 |
175 | @staticmethod
176 | def delta_gantry(param):
177 | alpha, beta = param
178 | phi = abs(beta - alpha) % 360
179 | return 360 - phi if phi > 180 else phi
180 |
181 | @staticmethod
182 | def rolling_apply(fun, a, w=2):
183 | r = np.empty(a.shape)
184 | r.fill(np.nan)
185 | for i in range(w - 1, a.shape[0]):
186 | r[i] = fun(a[(i - w + 1) : i + 1])
187 | return r
188 |
189 | @staticmethod
190 | def get_positions(apertures):
191 | pos = []
192 | for aperture in apertures:
193 | cp_pos = [(lp.Left, lp.Right) for lp in aperture.LeafPairs]
194 | arr = np.ravel(cp_pos)
195 | pos.append(arr)
196 |
197 | return pd.DataFrame(pos)
198 |
199 | def calc_mi_speed(self, mlc_speed, speed_std, k=1.0):
200 |
201 | calc_z = (
202 | lambda f: 1 / (self.Ncp - 1) * np.sum(np.sum(mlc_speed > f * speed_std))
203 | )
204 | res = integrate.quad(calc_z, 0, k)
205 | return res[0]
206 |
207 | def calc_mi_acceleration(
208 | self, mlc_speed, speed_std, mlc_acc, mlc_acc_std, k=1.0, alpha=1.0
209 | ):
210 |
211 | z_acc = lambda f: (1 / (self.Ncp - 2)) * np.nansum(
212 | np.nansum(
213 | np.logical_or(
214 | mlc_speed > f * speed_std, mlc_acc > alpha * f * mlc_acc_std
215 | )
216 | )
217 | )
218 | res = integrate.quad(z_acc, 0, k)
219 | return res[0]
220 |
221 | def calc_mi_total(
222 | self,
223 | mlc_speed,
224 | speed_std,
225 | mlc_acc,
226 | mlc_acc_std,
227 | k=1.0,
228 | alpha=1.0,
229 | WGA=None,
230 | WMU=None,
231 | ):
232 |
233 | z_total = lambda f: (1 / (self.Ncp - 2)) * np.nansum(
234 | np.nansum(
235 | np.logical_or(
236 | mlc_speed > f * speed_std, mlc_acc > alpha * f * mlc_acc_std
237 | ),
238 | axis=1,
239 | )
240 | * WGA
241 | * WMU
242 | )
243 |
244 | res = integrate.quad(z_total, 0, k)
245 |
246 | return res[0]
247 |
248 | def calculate_integrate(self, k=1.0, beta=2.0, alpha=2.0):
249 |
250 | # fill NAN
251 | mlc_speed = np.nan_to_num(self.mlc_speed)
252 | mlc_acc = np.nan_to_num(self.mlc_acceleration)
253 |
254 | mis = self.calc_mi_speed(mlc_speed, self.mlc_speed_std.values, k)
255 |
256 | alpha_acc = 1.0 / self.cumulative_mu["time"].mean()
257 | mia = self.calc_mi_acceleration(
258 | mlc_speed,
259 | self.mlc_speed_std.values,
260 | mlc_acc,
261 | self.mlc_acceleration_std.values,
262 | k=k,
263 | alpha=alpha_acc,
264 | )
265 |
266 | gantry_acc = self.gantry["gantry_acc"].values
267 | WGA = beta / (1 + (beta - 1) * np.exp(-gantry_acc / alpha))
268 |
269 | # Wmu
270 | delta_dose_rate = self.dose_rate["delta_dose_rate"].values
271 | WMU = beta / (1 + (beta - 1) * np.exp(-delta_dose_rate / alpha))
272 |
273 | mit = self.calc_mi_total(
274 | mlc_speed,
275 | self.mlc_speed_std.values,
276 | mlc_acc,
277 | self.mlc_acceleration_std.values,
278 | k=k,
279 | alpha=alpha_acc,
280 | WGA=WGA,
281 | WMU=WMU,
282 | )
283 |
284 | return mis, mia, mit
285 |
286 | def calculate(self, f=1.0, beta=2.0, alpha=2.0):
287 |
288 | # speed MI
289 | mask_speed_std = self.mlc_speed > f * self.mlc_speed_std
290 | Ns = mask_speed_std.sum().sum()
291 | z_speed = 1 / (self.Ncp - 1) * Ns
292 |
293 | # acc MI
294 | alpha_acc = 1.0 / self.cumulative_mu["time"].mean()
295 | mask_acc_std = self.mlc_acceleration > alpha_acc * f * self.mlc_acceleration_std
296 |
297 | mask_acc_mi = np.logical_or(mask_speed_std, mask_acc_std)
298 | Nacc = mask_acc_mi.sum().sum()
299 | z_acc = 1 / (self.Ncp - 2) * Nacc
300 |
301 | # Total MI
302 | gantry_acc = self.gantry["gantry_acc"]
303 | WGA = beta / (1 + (beta - 1) * np.exp(-gantry_acc / alpha))
304 |
305 | # Wmu
306 | delta_dose_rate = self.dose_rate["delta_dose_rate"]
307 | WMU = beta / (1 + (beta - 1) * np.exp(-delta_dose_rate / alpha))
308 |
309 | tmp = mask_acc_mi.multiply(WGA, axis="index").multiply(WMU, axis="index")
310 | Mti = tmp.sum().sum() / (self.Ncp - 2)
311 |
312 | return z_speed, z_acc, Mti
313 |
--------------------------------------------------------------------------------
/metrics_examples.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import os
3 |
4 | from complexity.PyComplexityMetric import (
5 | PyComplexityMetric,
6 | MeanAreaMetricEstimator,
7 | AreaMetricEstimator,
8 | ApertureIrregularityMetric,
9 | )
10 | from complexity.misc import ModulationIndexScore
11 | from complexity.dicomrt import RTPlan
12 |
13 | if __name__ == "__main__":
14 | # Path to DICOM RTPLAN file - IMRT/VMAT
15 | # pfile = "RP.dcm"
16 | path_to_rtplan_file = "RP.dcm"
17 |
18 | # Getting planning data from DICOM file.
19 | plan_info = RTPlan(filename=path_to_rtplan_file)
20 | plan_dict = plan_info.get_plan()
21 |
22 | metrics_list = [
23 | #ModulationIndexScore,
24 | PyComplexityMetric,
25 | MeanAreaMetricEstimator,
26 | AreaMetricEstimator,
27 | ApertureIrregularityMetric,
28 | ]
29 | units = ["CI [mm^-1]", "mm^2", "mm^2", "dimensionless"]
30 |
31 | # plotting results
32 | for unit, cc in zip(units, metrics_list):
33 | cc_obj = cc()
34 | # compute per plan
35 | plan_metric = cc_obj.CalculateForPlan(None, plan_dict)
36 | print(f"{cc.__name__} Plan Metric - {plan_metric} {unit}")
37 | for k, beam in plan_dict["beams"].items():
38 | # skip setup fields
39 | if beam["TreatmentDeliveryType"] == "TREATMENT" and beam["MU"] > 0:
40 | fig = plt.figure(figsize=(6, 6))
41 | # create a subplot
42 | ax = fig.add_subplot(111)
43 | cpx_beam_cp = cc_obj.CalculateForBeamPerAperture(
44 | None, plan_dict, beam
45 | )
46 | ax.plot(cpx_beam_cp)
47 | ax.set_xlabel("Control Point")
48 | ax.set_ylabel(f"${unit}$")
49 | txt = f"Output - Beam name: {beam['BeamName']} - {cc.__name__}"
50 | ax.set_title(txt)
51 | plt.show()
52 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pydicom
2 | numpy
3 | pandas
4 | scipy
5 | matplotlib
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup, find_packages
2 |
3 | with open("README.md") as f:
4 | readme = f.read()
5 |
6 | with open("LICENSE") as f:
7 | license = f.read()
8 |
9 | setup(
10 | name="Complexity",
11 | version="0.1.0",
12 | description="Python 3.x port of the Eclipse ESAPI plug-in script",
13 | long_description=readme,
14 | author="Victor G. L Alves",
15 | author_email="victorgabr@gmail.com",
16 | url="https://github.com/victorgabr/ApertureComplexity",
17 | license=license,
18 | # packages=find_packages(exclude=('tests', 'docs'))
19 | packages=["complexity"],
20 | )
21 |
--------------------------------------------------------------------------------
/test-requirements.txt:
--------------------------------------------------------------------------------
1 | pytest
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/victorgabr/ApertureComplexity/fbb25e756dd2a7b265a77cb6903fe69e868cce6e/tests/__init__.py
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from complexity.dicomrt import RTPlan
4 | import pytest
5 |
6 |
7 | @pytest.fixture()
8 | def plan_dcm():
9 | plan_file = os.path.join(DATA_DIR, "RP_FiF.dcm")
10 | plan_info = RTPlan(filename=plan_file)
11 | return plan_info
12 |
--------------------------------------------------------------------------------
/tests/test_aperture.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 |
4 | class TestAperture(TestCase):
5 | def test_CreateLeafPairs(self):
6 | self.fail()
7 |
8 | def test_GetLeafTops(self):
9 | self.fail()
10 |
11 | def test_CreateJaw(self):
12 | self.fail()
13 |
14 | def test_Jaw(self):
15 | self.fail()
16 |
17 | def test_LeafPairs(self):
18 | self.fail()
19 |
20 | def test_HasOpenLeafBehindJaws(self):
21 | self.fail()
22 |
23 | def test_Area(self):
24 | self.fail()
25 |
26 | def test_side_perimeter(self):
27 | self.fail()
28 |
29 | def test_SidePerimeter(self):
30 | self.fail()
31 |
32 | def test_LeafPairsAreOutsideJaw(self):
33 | self.fail()
34 |
35 | def test_JawTopIsBelowTopLeafPair(self):
36 | self.fail()
37 |
38 | def test_JawBottomIsAboveBottomLeafPair(self):
39 | self.fail()
40 |
41 | def test_LeafPairsAreDisjoint(self):
42 | self.fail()
43 |
--------------------------------------------------------------------------------
/tests/test_apertureIrregularityMetric.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 |
4 | class TestApertureIrregularityMetric(TestCase):
5 | def test_CalculatePerAperture(self):
6 | self.fail()
7 |
--------------------------------------------------------------------------------
/tests/test_jaw.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | from complexity.ApertureMetric import Jaw, Rect
4 |
5 | left, top, right, botton = -50, -50, 50, 50
6 | jaw = Jaw(left, top, right, botton)
7 |
8 |
9 | class TestJaw(TestCase):
10 | def test_Position(self):
11 | assert isinstance(jaw.Position, Rect)
12 |
13 | def test_Left(self):
14 | assert jaw.Left == -50
15 |
16 | def test_Top(self):
17 | assert jaw.Top == -50
18 |
19 | def test_Right(self):
20 | assert jaw.Right == 50
21 |
22 | def test_Bottom(self):
23 | assert jaw.Bottom == 50
24 |
--------------------------------------------------------------------------------
/tests/test_leafPair.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | from complexity.ApertureMetric import LeafPair, Jaw, Rect
4 |
5 | left, top, right, botton = -50, -50, 50, 50
6 | jaw = Jaw(left, top, right, botton)
7 | lp = LeafPair(-25, 25, 5, -5, jaw)
8 |
9 |
10 | class TestLeafPair(TestCase):
11 | def test_Position(self):
12 | assert isinstance(lp.Position, Rect)
13 |
14 | def test_Left(self):
15 | self.assertAlmostEqual(lp.Left, -25)
16 |
17 | def test_Top(self):
18 | self.assertAlmostEqual(lp.Top, 5)
19 |
20 | def test_Right(self):
21 | self.assertAlmostEqual(lp.Right, 25)
22 |
23 | def test_Bottom(self):
24 | self.assertAlmostEqual(lp.Bottom, 0)
25 |
26 | def test_Width(self):
27 | self.assertAlmostEqual(lp.Width, 0)
28 |
29 | def test_Jaw(self):
30 | assert lp.jaw.Left == -50
31 |
32 | assert lp.jaw.Top == -50
33 |
34 | assert lp.jaw.Right == 50
35 |
36 | assert lp.jaw.Bottom == 50
37 |
38 | def test_FieldSize(self):
39 | target = 50 * 5
40 | self.assertAlmostEqual(lp.FieldSize(), target)
41 |
42 | def test_FieldArea(self):
43 | self.fail()
44 |
45 | def test_IsOutsideJaw(self):
46 | self.fail()
47 |
48 | def test_IsOpen(self):
49 | self.fail()
50 |
51 | def test_IsOpenButBehindJaw(self):
52 | self.fail()
53 |
54 | def test_OpenLeafWidth(self):
55 | self.fail()
56 |
--------------------------------------------------------------------------------
/tests/test_leafSequenceVariability.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 |
4 | class TestLeafSequenceVariability(TestCase):
5 | def test_Calculate(self):
6 | self.fail()
7 |
--------------------------------------------------------------------------------
/tests/test_modulationComplexityScore.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 |
4 | class TestModulationComplexityScore(TestCase):
5 | def test_CalculatePerAperture(self):
6 | self.fail()
7 |
--------------------------------------------------------------------------------
/tests/test_modulationIndexScore.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 |
4 | class TestModulationIndexScore(TestCase):
5 | def test_CalculateForPlan(self):
6 | self.fail()
7 |
8 | def test_CalculateForBeam(self):
9 | self.fail()
10 |
--------------------------------------------------------------------------------
/tests/test_modulationIndexTotal.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 |
4 | class TestModulationIndexTotal(TestCase):
5 | def test_get_mu_data(self):
6 | self.fail()
7 |
8 | def test_calculate_time(self):
9 | self.fail()
10 |
11 | def test_delta_gantry(self):
12 | self.fail()
13 |
14 | def test_rolling_apply(self):
15 | self.fail()
16 |
17 | def test_get_positions(self):
18 | self.fail()
19 |
20 | def test_calc_mi_speed(self):
21 | self.fail()
22 |
23 | def test_calc_mi_acceleration(self):
24 | self.fail()
25 |
26 | def test_calc_mi_total(self):
27 | self.fail()
28 |
29 | def test_calculate_integrate(self):
30 | self.fail()
31 |
32 | def test_calculate(self):
33 | self.fail()
34 |
--------------------------------------------------------------------------------
/tests/test_pyAperture.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 |
4 | class TestPyAperture(TestCase):
5 | def test_CreateLeafPairs(self):
6 | self.fail()
7 |
8 | def test_LeafPairArea(self):
9 | self.fail()
10 |
11 | def test_GantryAngle(self):
12 | self.fail()
13 |
--------------------------------------------------------------------------------
/tests/test_pyAperturesFromBeamCreator.py:
--------------------------------------------------------------------------------
1 | from complexity.PyApertureMetric import PyAperturesFromBeamCreator
2 |
3 |
4 | def test_Create(plan_dcm):
5 | # given 10 x 10 cm field size
6 | plan_dict = plan_dcm.get_plan()
7 | beam = plan_dict["beams"][1]
8 | apertures = PyAperturesFromBeamCreator().Create(beam)
9 |
10 | assert apertures[1].side_perimeter() == 200.0
11 | assert apertures[3].side_perimeter() == 100.0
12 | assert len(apertures) == 4
13 | assert apertures[0].Area() == 100 * 100
14 | assert apertures[2].Area() == 50 * 50
15 |
--------------------------------------------------------------------------------
/tests/test_pyComplexityMetric.py:
--------------------------------------------------------------------------------
1 | from complexity.PyComplexityMetric import PyComplexityMetric
2 |
3 |
4 | def test_CalculateForPlan(plan_dcm):
5 | plan_dict = plan_dcm.get_plan()
6 | complexity_metric = PyComplexityMetric().CalculateForPlan(None, plan_dict)
7 |
8 | cp0 = 100 * 2 / (100 ** 2)
9 | cp1 = 50 * 2 / (50 ** 2)
10 | expected = (100 * cp0 + 100 * cp1) / 200.0
11 | assert complexity_metric == expected
12 |
--------------------------------------------------------------------------------
/tests/test_pyMetersetsFromMetersetWeightsCreator.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 |
4 | class TestPyMetersetsFromMetersetWeightsCreator(TestCase):
5 | def test_Create(self):
6 | self.fail()
7 |
8 | def test_GetCumulativeMetersets(self):
9 | self.fail()
10 |
11 | def test_GetMetersetWeights(self):
12 | self.fail()
13 |
14 | def test_ConvertMetersetWeightsToMetersets(self):
15 | self.fail()
16 |
17 | def test_UndoCummulativeSum(self):
18 | self.fail()
19 |
--------------------------------------------------------------------------------
/tests/tests_data/RP_FiF.dcm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/victorgabr/ApertureComplexity/fbb25e756dd2a7b265a77cb6903fe69e868cce6e/tests/tests_data/RP_FiF.dcm
--------------------------------------------------------------------------------