├── .gitignore
├── LICENSE
├── README.md
├── dataloader
└── graph_loader.py
├── dataset.py
├── doc
└── iguana.png
├── environment.yml
├── features.yml
├── features_all.yml
├── metrics
└── stats_utils.py
├── misc
├── bam_utils.py
├── feat_utils.py
└── utils.py
├── models
├── net_desc.py
└── run_desc.py
├── run_infer.py
├── run_infer.sh
└── run_utils
├── callbacks
├── base.py
├── logging.py
└── serialize.py
├── engine.py
└── utils.py
/.gitignore:
--------------------------------------------------------------------------------
1 | .vscode
2 | *__pycache__
3 |
4 | # directories
5 | cache/
6 | dataset/
7 | exp_output/
8 |
9 | # files
10 | *.npz
11 | *.png
12 | *.log
13 | *.dat
14 | *.csv
15 |
--------------------------------------------------------------------------------
/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 |
635 | Copyright (C)
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 | Copyright (C)
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 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | [](https://www.gnu.org/licenses/gpl-3.0)
6 |
7 |
8 |
9 | # Interpretable Gland-Graph Networks using a Neural Aggregator
10 |
11 | IGUANA is a graph neural network built for colon biopsy screening. IGUANA represents a whole-slide image (WSI) as a graph built with nodes on top of glands in the tissue, each node associated with a set of interpretable features.
12 |
13 | For a full description, take a look at our [preprint](https://doi.org/10.1101/2022.10.17.22279804).
14 |
15 | ## Set Up Environment
16 |
17 | ```
18 | # create base conda environment
19 | conda env create -f environment.yml
20 |
21 | # activate environment
22 | conda activate iguana
23 |
24 | # install PyTorch with pip
25 | pip install torch==1.10.1+cu102 torchvision==0.11.2+cu102 -f https://download.pytorch.org/whl/cu102/torch_stable.html
26 |
27 | # install PyTorch Geometric and dependencies
28 | pip install torch-scatter -f https://data.pyg.org/whl/torch-1.10.1+cu102.html
29 | pip install torch-sparse -f https://data.pyg.org/whl/torch-1.10.1+cu102.html
30 | pip install torch-geometric
31 | ```
32 |
33 | ## Repository Structure
34 |
35 | - `doc`: image files used for rendering the README - not necessary for running the code.
36 | - `dataloader`: contains code for loading the data to the model.
37 | - `metrics`: utility scripts and functions for computing metrics/statistics.
38 | - `misc`: miscellaneous scripts and functions.
39 | - `models`: scripts relating to defining the model, the hyperparameters and I/O configuration.
40 | - `run_utils`: main engine and callbacks.
41 |
42 |
43 | ## Inference
44 |
45 | To see the full list of command line arguments for inference and explanation, run `python run_infer.py -h` and `python run_explainer.py -h`, respectively. We have also created two bash scripts to make it easier to run the code with the appropriate arguments. As an example, to run model inference enter:
46 |
47 | ```
48 | python run_infer.py --gpu= --model_path= --data_dir= --data_info= --stats_dir=
49 | ```
50 |
51 | You will see above that the `data_info` csv file will need to be incorporated as an argument. This will determine the label and which images to process. By default, the code will process images with values in the fold column equal to 3. If considering a test set, there will be a single 'fold' column named `test_info`. The `fold_nr` and `split_nr` can be added as additional arguments if considering cross validation, which determines the subset of the data from the csv file.
52 |
53 |
54 | ## Interactive Demo
55 | We have made an interactive demo to help visualise the output of our model. Note, this is not optimised for mobile phones and tablets. The demo was built using the TIAToolbox [tile server](https://tia-toolbox.readthedocs.io/en/latest/_autosummary/tiatoolbox.visualization.tileserver.TileServer.html).
56 |
57 | Check out the demo [here](https://iguana.dcs.warwick.ac.uk).
58 |
59 | In the demo, we provide multiple examples of WSI-level results. By default, glands are coloured by their node explanation score, indicating how much they contribute to the slide being predicted as abnormal. Glands can also be coloured by a specific feature using the drop-down menu on the right hand side.
60 |
61 | As you zoom in, smaller objects such as lumen and nuclei will become visible. These are accordingly coloured by their predicted class. For example, epithelial cells are coloured green and lymphocytes red.
62 |
63 | Each histological object can be toggled on/off by clicking the appropriate buton on the right hand side. Also, the colours and the opacity can be altered.
64 |
65 | To see which histological features are contributing to glands being flagged as abnormal, hover over the corresponding node. To view these nodes, toggle the graph on at the bottom-right of the screen.
66 |
67 | 
68 |
69 | ## Sample Data and Weights
70 | We have released a small portion of data to allow researchers to get the code running and see how our graph data is structured. We also include two 'data info' csv files - one as if the data is to be used for cross validation and the other as an external test set. Click [here](https://drive.google.com/drive/folders/14MYdB-Acb93L6IdJfHnlWG7M2pkBn53I?usp=sharing) to download the sample dataset.
71 |
72 | To download the **IGUANA weights** trained on each fold of the UHCW dataset, click [here](https://drive.google.com/drive/folders/1J78dItPqMZcj2BsM4mf69x61wNAuJwKP?usp=share_link). To get the code running, you will also need the stats info used to standardise the input data. This includes the statistics (mean, mean, etc) of the features and the input node degree. Click [here](https://drive.google.com/drive/folders/1vcbf-9YrtoQUpFvf_l73iy5TupVWEdBF?usp=sharing) to download the stats info.
73 | ## License
74 |
75 | Code is under a GPL-3.0 license. See the [LICENSE](https://github.com/TissueImageAnalytics/cerberus/blob/master/LICENSE) file for further details.
76 |
77 | Model weights are licensed under [Attribution-NonCommercial-ShareAlike 4.0 International](http://creativecommons.org/licenses/by-nc-sa/4.0/). Please consider the implications of using the weights under this license.
78 |
79 | ## Cite this repository
80 |
81 | ```
82 | @article{graham2022screening,
83 | title={Screening of normal endoscopic large bowel biopsies with artificial intelligence: a retrospective study},
84 | author={Graham, Simon and Minhas, Fayyaz and Bilal, Mohsin and Ali, Mahmoud and Tsang, Yee Wah and Eastwood, Mark and Wahab, Noorul and Jahanifar, Mostafa and Hero, Emily and Dodd, Katherine and others},
85 | journal={medRxiv},
86 | year={2022},
87 | publisher={Cold Spring Harbor Laboratory Press}
88 | }
89 | ```
90 |
--------------------------------------------------------------------------------
/dataloader/graph_loader.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import joblib
3 | import torch
4 |
5 | from torch_geometric.data import Data
6 |
7 |
8 | class FileLoader(torch.utils.data.Dataset):
9 | """Data loader for graph data. The loader will use features defined in features.yml."""
10 |
11 | def __init__(self, file_list, feat_names, feat_stats, norm, data_clean):
12 | self.file_list = file_list
13 | self.feat_stats = feat_stats
14 | self.feat_names = feat_names
15 |
16 | if feat_stats is not None:
17 | self.mean_stats = np.array([feat_stats["mean"][k] for k in self.feat_names])
18 | self.median_stats = np.array([feat_stats["median"][k] for k in self.feat_names])
19 | self.std_stats = np.array([feat_stats["std"][k] for k in self.feat_names])
20 | self.perc_25_stats = np.array([feat_stats["perc_25"][k] for k in self.feat_names])
21 | self.perc_75_stats = np.array([feat_stats["perc_75"][k] for k in self.feat_names])
22 |
23 | # get lower and upper bounds for clipping data (outlier removal)
24 | if data_clean == 'std':
25 | self.local_lower_bounds = self.mean_stats - 3 * self.std_stats
26 | self.local_upper_bounds = self.mean_stats + 3 * self.std_stats
27 | elif data_clean == 'iqr':
28 | iqr = self.perc_75_stats - self.perc_25_stats
29 | self.local_lower_bounds = self.perc_25_stats - 2 * iqr
30 | self.local_upper_bounds = self.perc_75_stats + 2 * iqr
31 |
32 | self.norm = norm
33 |
34 | assert (
35 | self.norm == "standard" or self.norm == "robust" or self.norm == None
36 | ), "`norm` must be `standard` or `robust`."
37 | self.data_clean = data_clean
38 | assert (
39 | self.data_clean == "std" or self.data_clean == "iqr" or self.data_clean == None
40 | ), "`data_clean` must be `std` or `iqr`."
41 | return
42 |
43 | def __len__(self):
44 | return len(self.file_list)
45 |
46 | def __getitem__(self, idx):
47 | path = self.file_list[idx]
48 | data = joblib.load(path)
49 |
50 | edge_index = np.array(data["edge_index"])
51 | feats = data["local_feats"]
52 |
53 | nr_local_feats = len(self.feat_names)
54 |
55 | feats_sub = dict((k, feats[k]) for k in self.feat_names) # get subset of features
56 | feats_sub = np.array(list(feats_sub.values())).astype("float32") # convert to array
57 | feats_sub = np.transpose(feats_sub) # ensure NxF
58 | wsi_name = data["wsi_name"]
59 | obj_id = feats["obj_id"]
60 |
61 | # clean up data - deal with outliers!
62 | if self.data_clean is not None:
63 | # local feats
64 | clipped_feats = []
65 | for idx in range(nr_local_feats):
66 | feat_single = feats_sub[:, idx]
67 | feat_single[feat_single > self.local_upper_bounds[idx]] = self.local_upper_bounds[idx]
68 | feat_single[feat_single < self.local_lower_bounds[idx]] = self.local_lower_bounds[idx]
69 | clipped_feats.append(feat_single)
70 | feats_sub = np.squeeze(np.dstack(clipped_feats), axis=0)
71 |
72 | # normalise the feature subset
73 | if self.norm == "standard":
74 | feats_sub = ((feats_sub - self.mean_stats) + 1e-8) / (self.std_stats + 1e-8)
75 | elif self.norm == "robust":
76 | feats_sub = ((feats_sub - self.median_stats) + 1e-8) / ((self.perc_75_stats - self.perc_25_stats) + 1e-8)
77 |
78 | label = np.array([data["label"]])
79 |
80 | x = torch.Tensor(feats_sub).type(torch.float)
81 | edge_index = torch.Tensor(edge_index).type(torch.long)
82 | label = torch.Tensor(label).type(torch.float)
83 |
84 | return Data(x=x, edge_index=edge_index, y=label, obj_id=obj_id, wsi_name=wsi_name)
85 |
--------------------------------------------------------------------------------
/dataset.py:
--------------------------------------------------------------------------------
1 | """Dataset info. Modify this with your own data directories for training IGUANA."""
2 |
3 | import glob
4 | import pandas as pd
5 | import numpy as np
6 |
7 |
8 | class __CoBi(object):
9 | """Defines the Colon Biopsy (CoBi) graph dataset"""
10 |
11 | def __init__(self, fold_nr):
12 |
13 | file_ext = ".dat"
14 | root_dir = '/root/lsf_workspace/proc_slides/cobi/uhcw/graphs'
15 |
16 | self.stats_path = f"{root_dir}/stats"
17 |
18 | self.all_data = glob.glob(f"{root_dir}/data/*{file_ext}")
19 |
20 | # csv file - 1st column indicates the WSI name and each subsequent column gives the fold info
21 | # eg column 2 gives the info for fold1, column 3, gives the info for fold2, etc
22 | # for fold info: 1 denotes training, 2 denotes validation and 3 denotes testing
23 | # if the dataset is an independent test set, use 1 fold info column, with all cells set to 3
24 | fold_info = pd.read_csv(f"{root_dir}/uhcw_info.csv")
25 |
26 | wsi_names = np.array(fold_info.iloc[:, 0])
27 | fold_info = np.array(fold_info.iloc[:, fold_nr])
28 |
29 | wsi_train = wsi_names[fold_info==1]
30 | wsi_valid = wsi_names[fold_info==2]
31 |
32 | self.train_list = []
33 | for wsi_name in wsi_train:
34 | self.train_list.append(f"{root_dir}/data/{wsi_name}{file_ext}")
35 |
36 | self.valid_list = []
37 | for wsi_name in wsi_valid:
38 | self.valid_list.append(f"{root_dir}/data/{wsi_name}{file_ext}")
39 |
40 |
41 | def get_dataset(name):
42 | """Return a pre-defined dataset object associated with `name`"""
43 | if name.lower() == "cobi_fold1":
44 | return __CoBi(fold_nr=1)
45 | elif name.lower() == "cobi_fold2":
46 | return __CoBi(fold_nr=2)
47 | elif name.lower() == "cobi_fold3":
48 | return __CoBi(fold_nr=3)
49 | else:
50 | assert False, "Unknown dataset `%s`" % name
51 |
--------------------------------------------------------------------------------
/doc/iguana.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TissueImageAnalytics/iguana/c4cd93d0ed67c8d0bfc358f5837d1309963df841/doc/iguana.png
--------------------------------------------------------------------------------
/environment.yml:
--------------------------------------------------------------------------------
1 | name: iguana
2 | channels:
3 | - conda-forge
4 | - defaults
5 | dependencies:
6 | - docopt=0.6.2=py37h06a4308_0
7 | - hdf5=1.12.1=nompi_h2386368_104
8 | - joblib=1.1.0=pyhd3eb1b0_0
9 | - matplotlib=3.5.1=py37h06a4308_1
10 | - matplotlib-base=3.5.1=py37ha18d171_1
11 | - numpy=1.21.5=py37h6c91a56_3
12 | - numpy-base=1.21.5=py37ha15fc14_3
13 | - pandas=1.3.5=py37h8c16a72_0
14 | - pillow=9.0.1=py37h22f2fdc_0
15 | - pip=21.2.2=py37h06a4308_0
16 | - progress=1.5=py37h06a4308_0
17 | - python=3.7.12=hb7a2778_100_cpython
18 | - pyyaml=6.0=py37h7f8727e_1
19 | - scikit-image=0.19.2=py37h51133e4_0
20 | - scikit-learn=1.0.2=py37h51133e4_1
21 | - scipy=1.7.3=py37hf2a6cf1_0
22 | - shapely=1.7.1=py37h1728cc4_0
23 | - termcolor=1.1.0=py37h06a4308_1
24 | - tqdm=4.64.0=py37h06a4308_0
25 | - yaml=0.2.5=h7b6447c_0
26 | - pip:
27 | - captum==0.5.0
28 | - imgaug==0.4.0
29 | - opencv-python==4.5.5.64
30 | - opencv-python-headless==4.5.5.64
31 | - seaborn==0.11.2
32 | - tensorboardx==2.5.1
33 | - tiatoolbox==1.3.0
34 |
--------------------------------------------------------------------------------
/features.yml:
--------------------------------------------------------------------------------
1 | # below are the selected features used within the framework
2 | # look at the complete list of features obtained after running extract_feats.py in features_all.yml
3 | # you must not swap the ordering of the list!
4 |
5 | features:
6 | - gland-bam
7 | - gland-area
8 | - gland-dist1
9 | - lumen-number
10 | - lumen-gland-ratio
11 | - lumen-bam-mean
12 | - lumen-area-max
13 | - nuclei-gland-epi-count
14 | - nuclei-gland-lym-count
15 | - nuclei-gland-neut-count
16 | - nuclei-gland-eos-count
17 | - nuclei-inter-epi-mean
18 | - nuclei-inter-epi-std
19 | - nuclei-dist-boundary-mean
20 | - nuclei-dist-boundary-std
21 | - nuclei-dist-lumen-mean
22 | - nuclei-dist-lumen-std
23 | - nuclei-area-mean
24 | - nuclei-area-std
25 | - nuclei-focus-lym-prop
26 | - nuclei-focus-plas-prop
27 | - nuclei-focus-neut-prop
28 | - nuclei-focus-eos-prop
29 | - nuclei-focus-conn-prop
30 | - nuclei-inf-density
--------------------------------------------------------------------------------
/features_all.yml:
--------------------------------------------------------------------------------
1 | features:
2 | - obj_id
3 | - gland-inflam-prop
4 | - gland-mucous-prop
5 | - gland-debris-prop
6 | - gland-normal-prop
7 | - gland-tumour-prop
8 | - gland-adipose-prop
9 | - gland-stroma-prop
10 | - gland-muscle-prop
11 | - gland-bam
12 | - gland-area
13 | - gland-perimeter
14 | - gland-equiv-diameter
15 | - gland-extent
16 | - gland-convex-area
17 | - gland-solidity
18 | - gland-major-axis-length
19 | - gland-minor-axis-length
20 | - gland-eccentricity
21 | - gland-orientation
22 | - gland-ellipse-centre-x
23 | - gland-ellipse-centre-y
24 | - gland-dist1
25 | - gland-dist2
26 | - gland-dist3
27 | - gland-dist4
28 | - gland-dist5
29 | - gland-dist6
30 | - lumen-number
31 | - lumen-gland-ratio
32 | - lumen-bam-min
33 | - lumen-bam-max
34 | - lumen-bam-mean
35 | - lumen-bam-std
36 | - lumen-area-min
37 | - lumen-area-max
38 | - lumen-area-mean
39 | - lumen-area-mtd
40 | - lumen-perimeter-min
41 | - lumen-perimeter-max
42 | - lumen-perimeter-mean
43 | - lumen-perimeter-mtd
44 | - lumen-equiv-diameter-min
45 | - lumen-equiv-diameter-max
46 | - lumen-equiv-diameter-mean
47 | - lumen-equiv-diameter-mtd
48 | - lumen-extent-min
49 | - lumen-extent-max
50 | - lumen-extent-mean
51 | - lumen-extent-mtd
52 | - lumen-convex-area-min
53 | - lumen-convex-area-max
54 | - lumen-convex-area-mean
55 | - lumen-convex-area-mtd
56 | - lumen-solidity-min
57 | - lumen-solidity-max
58 | - lumen-solidity-mean
59 | - lumen-solidity-mtd
60 | - lumen-major-axis-length-min
61 | - lumen-major-axis-length-max
62 | - lumen-major-axis-length-mean
63 | - lumen-major-axis-length-mtd
64 | - lumen-minor-axis-length-min
65 | - lumen-minor-axis-length-max
66 | - lumen-minor-axis-length-mean
67 | - lumen-minor-axis-length-mtd
68 | - lumen-eccentricity-min
69 | - lumen-eccentricity-max
70 | - lumen-eccentricity-mean
71 | - lumen-eccentricity-mtd
72 | - lumen-orientation-min
73 | - lumen-orientation-max
74 | - lumen-orientation-mean
75 | - lumen-orientation-mtd
76 | - lumen-ellipse-centre-x-min
77 | - lumen-ellipse-centre-x-max
78 | - lumen-ellipse-centre-x-mean
79 | - lumen-ellipse-centre-x-mtd
80 | - lumen-ellipse-centre-y-min
81 | - lumen-ellipse-centre-y-max
82 | - lumen-ellipse-centre-y-mean
83 | - lumen-ellipse-centre-y-mtd
84 | - nuclei-gland-epi-count
85 | - nuclei-gland-lym-count
86 | - nuclei-gland-plas-count
87 | - nuclei-gland-neut-count
88 | - nuclei-gland-eos-count
89 | - nuclei-gland-nuc-count
90 | - nuclei-inter-epi-min
91 | - nuclei-inter-epi-max
92 | - nuclei-inter-epi-mean
93 | - nuclei-inter-epi-std
94 | - nuclei-dist-boundary-min
95 | - nuclei-dist-boundary-max
96 | - nuclei-dist-boundary-mean
97 | - nuclei-dist-boundary-std
98 | - nuclei-dist-lumen-min
99 | - nuclei-dist-lumen-max
100 | - nuclei-dist-lumen-mean
101 | - nuclei-dist-lumen-std
102 | - nuclei-area-min
103 | - nuclei-area-max
104 | - nuclei-area-mean
105 | - nuclei-area-std
106 | - nuclei-perimeter-min
107 | - nuclei-perimeter-max
108 | - nuclei-perimeter-mean
109 | - nuclei-perimeter-std
110 | - nuclei-equiv-diameter-min
111 | - nuclei-equiv-diameter-max
112 | - nuclei-equiv-diameter-mean
113 | - nuclei-equiv-diameter-std
114 | - nuclei-extent-min
115 | - nuclei-extent-max
116 | - nuclei-extent-mean
117 | - nuclei-extent-std
118 | - nuclei-convex-area-min
119 | - nuclei-convex-area-max
120 | - nuclei-convex-area-mean
121 | - nuclei-convex-area-std
122 | - nuclei-solidity-min
123 | - nuclei-solidity-max
124 | - nuclei-solidity-mean
125 | - nuclei-solidity-std
126 | - nuclei-major-axis-length-min
127 | - nuclei-major-axis-length-max
128 | - nuclei-major-axis-length-mean
129 | - nuclei-major-axis-length-std
130 | - nuclei-minor-axis-length-min
131 | - nuclei-minor-axis-length-max
132 | - nuclei-minor-axis-length-mean
133 | - nuclei-minor-axis-length-std
134 | - nuclei-eccentricity-min
135 | - nuclei-eccentricity-max
136 | - nuclei-eccentricity-mean
137 | - nuclei-eccentricity-std
138 | - nuclei-orientation-min
139 | - nuclei-orientation-max
140 | - nuclei-orientation-mean
141 | - nuclei-orientation-std
142 | - nuclei-ellipse-centre-x-min
143 | - nuclei-ellipse-centre-x-max
144 | - nuclei-ellipse-centre-x-mean
145 | - nuclei-ellipse-centre-x-std
146 | - nuclei-ellipse-centre-y-min
147 | - nuclei-ellipse-centre-y-max
148 | - nuclei-ellipse-centre-y-mean
149 | - nuclei-ellipse-centre-y-std
150 | - colocalisation-neut-neut
151 | - colocalisation-neut-epi
152 | - colocalisation-neut-lym
153 | - colocalisation-neut-plas
154 | - colocalisation-neut-eos
155 | - colocalisation-neut-conn
156 | - colocalisation-epi-neut
157 | - colocalisation-epi-epi
158 | - colocalisation-epi-lym
159 | - colocalisation-epi-plas
160 | - colocalisation-epi-eos
161 | - colocalisation-epi-conn
162 | - colocalisation-lym-neut
163 | - colocalisation-lym-epi
164 | - colocalisation-lym-lym
165 | - colocalisation-lym-plas
166 | - colocalisation-lym-eos
167 | - colocalisation-lym-conn
168 | - colocalisation-plas-neut
169 | - colocalisation-plas-epi
170 | - colocalisation-plas-lym
171 | - colocalisation-plas-plas
172 | - colocalisation-plas-eos
173 | - colocalisation-plas-conn
174 | - colocalisation-eos-neut
175 | - colocalisation-eos-epi
176 | - colocalisation-eos-lym
177 | - colocalisation-eos-plas
178 | - colocalisation-eos-eos
179 | - colocalisation-eos-conn
180 | - colocalisation-conn-neut
181 | - colocalisation-conn-epi
182 | - colocalisation-conn-lym
183 | - colocalisation-conn-plas
184 | - colocalisation-conn-eos
185 | - colocalisation-conn-conn
186 | - nuclei-focus-lym-prop
187 | - nuclei-focus-plas-prop
188 | - nuclei-focus-neut-prop
189 | - nuclei-focus-eos-prop
190 | - nuclei-focus-conn-prop
191 | - nuclei-focus-lym-density
192 | - nuclei-focus-plas-density
193 | - nuclei-focus-neut-density
194 | - nuclei-focus-eos-density
195 | - nuclei-focus-conn-density
196 | - nuclei-inf-density
197 |
--------------------------------------------------------------------------------
/metrics/stats_utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from sklearn.metrics import roc_curve
3 |
4 |
5 | def get_sens_spec_metrics(targets, probs):
6 | """Get the specificity at different sensitivity cut-offs.
7 |
8 | Args:
9 | targets (list): list of true labels
10 | probs (list): list of predicted scores
11 |
12 | Returns:
13 |
14 | """
15 | binary_labels = np.array(targets.copy())
16 | specificity_at_95 = []
17 | specificity_at_97 = []
18 | specificity_at_98 = []
19 | specificity_at_99 = []
20 | specificity_at_100 = []
21 |
22 | fpr, tpr, _ = roc_curve(binary_labels, probs)
23 | tnr = 1 - fpr
24 | specificity_at_95 = tnr[tpr >= 0.95][0]
25 | specificity_at_97 = tnr[tpr >= 0.97][0]
26 | specificity_at_98 = tnr[tpr >= 0.98][0]
27 | specificity_at_99 = tnr[tpr >= 0.99][0]
28 | specificity_at_100 = tnr[tpr >= 1.0][0]
29 |
30 | return specificity_at_95, specificity_at_97, specificity_at_98, specificity_at_99, specificity_at_100
--------------------------------------------------------------------------------
/misc/bam_utils.py:
--------------------------------------------------------------------------------
1 | """
2 | Utility functions for computing the BAM metric for a given object
3 | """
4 |
5 | import numpy as np
6 | import cv2
7 | from skimage import draw
8 | from skimage.measure import regionprops
9 | import matplotlib.pyplot as plt
10 | import scipy
11 | from scipy.interpolate import InterpolatedUnivariateSpline
12 |
13 |
14 |
15 | def get_enclosing_ellipse(cnt):
16 | """Generates a discretised contour for the smallest enclosing ellipse
17 |
18 | Args:
19 | cnt: a 2-column matrix for discritised contour
20 |
21 | Returns:
22 | x: a 2-column matrix for discritised smallest enclosing ellipse
23 |
24 | """
25 | hull = cv2.convexHull(cnt, clockwise=True).squeeze() # get the convex hull
26 | A, centre, radii, rotation = min_2d_ellipse(hull, 0.01)
27 |
28 | return ellipse_coordinates(A,centre,radii,rotation)
29 |
30 |
31 | def min_2d_ellipse(P, tol):
32 | """Find the minimum covering 2D ellipse which holds all the points
33 |
34 | Based on work by Nima Moshtagh
35 | http://www.mathworks.com/matlabcentral/fileexchange/9542
36 | and also by looking at:
37 | http://cctbx.sourceforge.net/current/python/scitbx.math.minimum_covering_ellipsoid.html
38 |
39 | Args:
40 | P: (d x N) dimnesional matrix containing N points in R^d.
41 | tol: error in the solution with respect to the optimal value.
42 |
43 | Returns:
44 | A: coordinates of the ellipse
45 | centre: centre of ellipse
46 | radii: radii of ellipse
47 | rotation: rotation of ellipse
48 |
49 | """
50 | (N, d) = np.shape(P)
51 | d = float(d)
52 |
53 | # Q will be our working array
54 | Q = np.vstack([np.copy(P.T), np.ones(N)])
55 | QT = Q.T
56 |
57 | # initialisations
58 | err = 1.0 + tol
59 | u = (1.0 / N) * np.ones(N)
60 |
61 | # Khachiyan Algorithm
62 | while err > tol:
63 | V = np.dot(Q, np.dot(np.diag(u), QT))
64 | M = np.diag(np.dot(QT , np.dot(np.linalg.inv(V), Q))) # M the diagonal vector of an NxN matrix
65 | j = np.argmax(M)
66 | maximum = M[j]
67 | step_size = (maximum - d - 1.0) / ((d + 1.0) * (maximum - 1.0))
68 | new_u = (1.0 - step_size) * u
69 | new_u[j] += step_size
70 | err = np.linalg.norm(new_u - u)
71 | u = new_u
72 |
73 | # centre of the ellipse
74 | centre = np.dot(P.T, u)
75 |
76 | # the A matrix for the ellipse
77 | A = np.linalg.inv(
78 | np.dot(P.T, np.dot(np.diag(u), P)) -
79 | np.array([[a * b for b in centre] for a in centre])
80 | ) / d
81 |
82 | # Get the values we'd like to return
83 | U, s, rotation = np.linalg.svd(A)
84 | radii = 1.0/np.sqrt(s)
85 |
86 | return A, centre, radii, rotation
87 |
88 |
89 | def ellipse_coordinates(A, centre, radii, rotation, N=20.0):
90 | """Generates the coordinates of the minimum enclosing ellipse
91 |
92 | Args:
93 | A: a 2x2 matrix.
94 | centre: a 2D vector which represents the centre of the ellipsoid.
95 | radii: radii of ellipsoid generated from SVD
96 | rotation: rotation output by SVD
97 | N: the number of grid points for plotting the ellipse; Default: N = 20
98 |
99 | Returns:
100 | coordinates of ellipse
101 |
102 | """
103 | steps = int(round((2.0 * np.pi + 1/N)*N))
104 | theta = np.linspace(0.0, 2.0 * np.pi + 1/N, steps)
105 |
106 | # parametric equation of the ellipse
107 | x = radii[0] * np.cos(theta)
108 | y = radii[1] * np.sin(theta)
109 |
110 | # coordinate transform
111 | X = np.matmul(rotation,np.array([x,y]))
112 | X += np.expand_dims(centre.T, -1)
113 | return X.T
114 |
115 |
116 | def ellipse_to_circle(coords):
117 | """Transform ellipse to circle
118 |
119 | Args:
120 | coords: input coordinates of ellipse
121 |
122 | Returns:
123 | circle_coords: coordinates of circle (transformed ellipse)
124 | alpha: orientation in radians
125 | a: major axis length of input ellipse
126 | b: minor axis length of input ellipse
127 |
128 | """
129 | # get the minimum x and y coordinates
130 | min_x = min(coords[:,1])
131 | min_y = min(coords[:,0])
132 |
133 | coords2 = np.round(coords - np.array([min_y, min_x]))
134 |
135 | # generate binary mask from coordinates
136 | shape = (int(max(coords2[:,1]) - min(coords2[:,1])), int(max(coords2[:,0]) - min(coords2[:,0])))
137 | mask = coords2mask(coords2[:,1], coords2[:,0], shape)
138 | mask = mask.T
139 | # get properties from binary mask
140 | props = regionprops(mask.astype('int'))
141 | orientation = props[0].orientation
142 | a = props[0].major_axis_length
143 | b = props[0].minor_axis_length
144 | centroid = props[0].centroid
145 |
146 | centre = (centroid + np.array([min_y, min_x]))
147 | centre = np.array([centre[1], centre[0]])
148 | alpha = -orientation
149 |
150 | circle_coords = apply_transform(coords, centre, alpha, a, b)
151 |
152 | return circle_coords, alpha, a, b
153 |
154 |
155 | def apply_transform(coords, centre, alpha, a, b):
156 | """Apply transformation to set of input coordinates
157 |
158 | Args:
159 | coords: input coordinates
160 | centre: centre of input coordinates
161 | alpha: orientation in radians
162 | a: major axis length of input
163 | b: major axis length of input
164 |
165 | Returns:
166 | transformed coordinates
167 |
168 | """
169 | T1 = [[1, 0, -centre[1]],
170 | [0, 1, -centre[0]],
171 | [0, 0, 1 ]]
172 |
173 | T2 = [[1, 0, centre[1]],
174 | [0, 1, centre[0]],
175 | [0, 0, 1 ]]
176 |
177 | R = [[np.cos(alpha), -np.sin(alpha), 0],
178 | [np.sin(alpha), np.cos(alpha) , 0],
179 | [0 , 0 , 1]]
180 |
181 | S = [[1, 0, 0],
182 | [0, a/b, 0],
183 | [0, 0 , 1]]
184 |
185 | trans_matrix = np.matmul(T2,np.matmul(S,np.matmul(R,T1)))
186 |
187 | coords_ones = np.hstack([coords[:,1:2], coords[:,:1], np.ones([coords.shape[0],1])])
188 | transformed_coords = np.matmul(trans_matrix, coords_ones[:, [1,0,2]].T).T
189 | return transformed_coords[:, [0,1]]
190 |
191 |
192 | def coords2mask(row_coords, col_coords, shape):
193 | """Convert coordinates to a binary mask
194 |
195 | Args:
196 | row_coords: coordinates in y direction
197 | col_coords: coordinates in x direction
198 | shape: shape of binary mask to output
199 |
200 | Returns:
201 | mask: binary mask
202 |
203 | """
204 | fill_row_coords, fill_col_coords = draw.polygon(row_coords, col_coords, shape)
205 | mask = np.zeros(shape, dtype=np.bool)
206 | mask[fill_row_coords, fill_col_coords] = True
207 | return mask
208 |
209 |
210 | def best_alignment_metric(circle_coords, trans_coords, show_plots):
211 | """Compute BAM between two sets of coordinates as described in:
212 |
213 | Awan, Ruqayya, et al. "Glandular morphometrics for objective grading
214 | of colorectal adenocarcinoma histology images." Scientific reports 7.1 (2017): 1-12.
215 |
216 | Args:
217 | circle_coords: circle coordinates
218 | trans_coords: transformed object coordinates
219 | show_plots: show the coordinate plots at each stage of the implementation
220 |
221 | Returns:
222 | d: best alignment distance
223 | R: best index shift
224 | phi: best planar rotation
225 |
226 | """
227 | # normalise the contour
228 | circle_coords_rs = resample_curve(circle_coords, 300)
229 | trans_coords_rs = resample_curve(trans_coords, 300)
230 |
231 | # convert to complex representation
232 | circle_complex = get_complex(circle_coords_rs)
233 | trans_complex = get_complex(trans_coords_rs)
234 |
235 | d, R, phi = bam_distance(circle_complex, trans_complex)
236 |
237 | if show_plots:
238 | plt.figure(figsize=(5, 5))
239 | rotated_trans_coords = np.exp(1j*phi)*trans_complex
240 | rotated_and_cycled_trans_coords = np.roll(rotated_trans_coords, R)
241 |
242 | plt.subplot(2,2,1)
243 | plt.plot(trans_coords[:,0],trans_coords[:,1]) # plot cartesian transformed object coordinates
244 |
245 | plt.plot(trans_coords[:,0],trans_coords[:,1],'x', markersize=5) # plot x at ticks
246 | plt.plot(trans_coords[0,0],trans_coords[0,1],'.', markersize=30) # mark the first point
247 |
248 | plt.subplot(2,2,2)
249 | plt.plot(circle_coords[:,0],circle_coords[:,1],'r') # plot cartesian circle coordinates
250 |
251 | plt.plot(circle_coords[:,0],circle_coords[:,1],'rx', markersize=5) # plot x at ticks
252 | plt.plot(circle_coords[0,0],circle_coords[0,1],'r.', markersize=30) # mark the first point
253 |
254 | plt.subplot(2,2,3)
255 | plt.plot(circle_complex.real, circle_complex.imag,'r') # plot complex circle coordinates
256 |
257 | plt.plot(circle_complex.real, circle_complex.imag,'rx', markersize=5)
258 | plt.plot(circle_complex.real[0],circle_complex.imag[0],'r.', markersize=30)
259 | plt.plot(rotated_trans_coords.real, rotated_trans_coords.imag) # plot optimally rotated complex transformed object
260 | plt.plot(rotated_trans_coords.real, rotated_trans_coords.imag,'x', markersize=5)
261 | plt.plot(rotated_trans_coords.real[0], rotated_trans_coords.imag[0],'.', markersize=30)
262 |
263 | plt.subplot(2,2,4)
264 | plt.plot(circle_complex.real, circle_complex.imag,'r') # plot complex circle coordinates
265 |
266 | plt.plot(circle_complex.real, circle_complex.imag,'rx', markersize=5)
267 | plt.plot(circle_complex.real[0], circle_complex.imag[0],'r.', markersize=30)
268 | plt.plot(rotated_and_cycled_trans_coords.real, rotated_and_cycled_trans_coords.imag) # plot optimally rotated and cyclically reordered complex transformed object
269 | plt.plot(rotated_and_cycled_trans_coords.real, rotated_and_cycled_trans_coords.imag,'x', markersize=5)
270 | plt.plot(rotated_and_cycled_trans_coords.real[0],rotated_and_cycled_trans_coords.imag[1],'.', markersize=30)
271 |
272 | plt.show()
273 |
274 | return d, R, phi
275 |
276 |
277 | def bam_distance(u, v):
278 | """Rapidly computes the distance between curves u & v in the plane
279 |
280 | Args:
281 | u: complex vector with shape 1xN
282 | v: complex vector with shape 1xN
283 |
284 | Returns:
285 | d: best alignment distance
286 | R: best index shift
287 | phi: best planar rotation
288 |
289 | """
290 | sum_u = np.sum(u.real**2 + u.imag**2)
291 | sum_v = np.sum(v.real**2 + v.imag**2)
292 | v_tmp = np.flipud(v) # ! why do this?
293 | Xcorr = np.fft.ifft(np.fft.fft(np.conj(u)) * np.fft.fft(v_tmp))
294 |
295 | Xcorr2 = abs(Xcorr)
296 | A = np.max(Xcorr2)
297 | idx = np.argmax(Xcorr2)
298 | phi = np.arctan2(Xcorr[idx].imag, Xcorr[idx].real)
299 | R = idx
300 |
301 | summand = sum_u + sum_v - 2*A
302 | if summand < 0:
303 | summand = 0
304 | d = np.sqrt(summand)
305 |
306 | return d, R, phi
307 |
308 |
309 | def resample_curve(coords, N):
310 | """Resample the points on the input curve by interpolation.
311 |
312 | Args:
313 | coords: input coordinates
314 | N: number of sample points
315 |
316 | Returns:
317 | Xn: resampled coordinates
318 |
319 | """
320 | coords = coords.T
321 | diff = coords[:,1:] - coords[:,:-1] # check same size (measure diff between points)
322 | dist = np.sqrt(diff[0,:]**2 + diff[1,:]**2) # calculate the magnitude between neighbouring coordinates
323 | dist = np.concatenate((np.array([0]),dist), axis=-1)
324 | cum_dist = np.cumsum(dist)/np.sum(dist) # cumulative sum of distances between neighbouring coordinates
325 |
326 | sample_points = np.linspace(1/N,1,N)
327 | interp = np.zeros([2,N])
328 | for i in range(2):
329 | # generate interpolated points
330 | spline = InterpolatedUnivariateSpline(cum_dist,coords[i,:])
331 | interp[i,:] = spline(sample_points)
332 |
333 | q = curve_to_q(interp) # include description
334 | qn = ProjectC(q) # include description
335 | Xn = q_to_curve(qn)
336 |
337 | return Xn
338 |
339 |
340 | def get_complex(curve):
341 | """Convert input curve to complex form and translate
342 | it such that it is centred at (0,0)
343 |
344 | Args:
345 | curve: input cartesian coordinates
346 |
347 | Returns:
348 | comp_curve_trans: translated complex curve
349 |
350 | """
351 | comp_curve = curve[0,:]+1j*curve[1,:]
352 | cf = np.mean(comp_curve)
353 | comp_curve_trans = comp_curve-cf
354 |
355 | return comp_curve_trans
356 |
357 |
358 | def curve_to_q(p):
359 | """Include docstring
360 |
361 | Args:
362 | p:
363 |
364 | """
365 | #! NEED TO UNDERSTAND WHAT IS GOING ON IN THIS FUNCTION and give appropriate comments
366 | N = p.shape[1]
367 | v = np.zeros([2,N])
368 | for i in range(2):
369 | v[i,:] = np.gradient(p[i,:], 1/N)
370 |
371 | # unit velocity
372 | L = np.sqrt(np.sqrt(v[0,:]**2 + v[1,:]**2)) # check whether this is the right thing to do
373 |
374 | okPos = L > 1e-5
375 | q = v[:,okPos] / L[okPos]
376 | q[:,~okPos] = np.zeros([2, np.sum(~okPos)])
377 |
378 | T = q.shape[1]
379 | s = np.linspace(0,1,T)
380 | val = np.trapz(np.sum(q*q, axis=0), s)
381 | return q / np.sqrt(val)
382 |
383 |
384 | def q_to_curve(q):
385 | """Include docstring
386 |
387 | Args:
388 | q:
389 |
390 | """
391 | #! NEED TO UNDERSTAND WHAT IS GOING ON IN THIS FUNCTION and give appropriate comments
392 | T = q.shape[1]
393 | qnorm = np.sqrt(q[0,:]**2 + q[1,:]**2)
394 |
395 | p = np.zeros([2,T])
396 | for i in range(2):
397 | p[i,:] = scipy.integrate.cumtrapz(q[i,:]*qnorm, initial=0)/T
398 | return p
399 |
400 |
401 | def ProjectC(q):
402 | """Include description
403 |
404 | Args:
405 | q:
406 |
407 | """
408 | #! NEED TO UNDERSTAND WHAT IS GOING ON IN THIS FUNCTION and give appropriate comments
409 | T = q.shape[1]
410 | dt = 0.35 # what is this? - provide description
411 |
412 | epsilon = 1e-6
413 | count = 1
414 | res = np.ones([1,2])
415 |
416 | s = np.linspace(0,1,T)
417 | tmp = np.trapz(np.sum(q*q, axis=0), s)
418 | qnew = q / np.sqrt(tmp)
419 |
420 | while np.linalg.norm(res, ord=2) > epsilon:
421 | if count > 300:
422 | break
423 |
424 | J = np.zeros([2,2])
425 | for i in range(2):
426 | for j in range(1,2):
427 | J[i,j] = 3 * np.trapz(qnew[i,:]*qnew[j,:], s)
428 |
429 | J = J + J.T
430 | for i in range(2):
431 | J[i,i] = 3 * np.trapz(qnew[i,:]*qnew[i,:], s)
432 |
433 | J = J + np.identity(J.shape[0])
434 | qnorm = np.sqrt(qnew[0,:]**2 + qnew[1,:]**2)
435 |
436 | G = np.zeros([2])
437 | for i in range(2):
438 | G[i] = np.trapz(qnew[i,:]*qnorm, s)
439 | res = -G
440 |
441 | if np.linalg.norm(res, ord=2) < epsilon:
442 | break
443 |
444 | x = np.linalg.lstsq(J, res.T, rcond=None)[0] # solve system by least squares
445 |
446 | delG = form_basis_normal_A(qnew)
447 |
448 | tmp = x[0]*delG[0]*dt + x[1]*delG[1]*dt
449 | qnew = qnew + tmp
450 |
451 | count += 1
452 |
453 | tmp = np.trapz(np.sum(qnew*qnew, axis=0), s)
454 | return qnew / np.sqrt(tmp)
455 |
456 |
457 | def form_basis_normal_A(q):
458 | """Include docstring
459 |
460 | Args:
461 | q:
462 |
463 | """
464 | #! NEED TO UNDERSTAND WHAT IS GOING ON IN THIS FUNCTION and give appropriate comments
465 | T = q.shape[1]
466 |
467 | e = np.identity(2)
468 | Ev = np.zeros([2,T,2])
469 | for i in range(2):
470 | Ev[:,:,i] = np.tile(np.expand_dims(e[:,i],-1),(1,T))
471 |
472 | qnorm = np.sqrt(q[0,:]**2 + q[1,:]**2)
473 |
474 | delG = []
475 | for i in range(2):
476 | tmp1 = np.tile(q[i,:]/qnorm,(2,1))
477 | tmp2 = np.tile(qnorm,(2,1))
478 | delG.append(tmp1*q + tmp2*Ev[:,:,i])
479 |
480 | return delG
481 |
--------------------------------------------------------------------------------
/misc/feat_utils.py:
--------------------------------------------------------------------------------
1 | """
2 | Functions for feature extraction
3 | """
4 |
5 | import cv2
6 | import numpy as np
7 | import pandas as pd
8 | import uuid
9 | import math
10 |
11 | from shapely.geometry import Polygon
12 | from scipy.spatial import distance, Voronoi, Delaunay
13 | from sklearn.neighbors import KDTree
14 |
15 | from .bam_utils import get_enclosing_ellipse, ellipse_to_circle, apply_transform, best_alignment_metric
16 |
17 |
18 | def get_contour_feats(cnt):
19 | """Get morphological features from input contours."""
20 |
21 | # calculate some things useful later:
22 | m = cv2.moments(cnt)
23 |
24 | # ** regionprops **
25 | Area = m["m00"]
26 | if Area > 0:
27 | Perimeter = cv2.arcLength(cnt, True)
28 | # bounding box: x,y,width,height
29 | BoundingBox = cv2.boundingRect(cnt)
30 | # centroid = m10/m00, m01/m00 (x,y)
31 | Centroid = (m["m10"] / m["m00"], m["m01"] / m["m00"])
32 |
33 | # EquivDiameter: diameter of circle with same area as region
34 | EquivDiameter = np.sqrt(4 * Area / np.pi)
35 | # Extent: ratio of area of region to area of bounding box
36 | Extent = Area / (BoundingBox[2] * BoundingBox[3])
37 |
38 | # CONVEX HULL stuff
39 | # convex hull vertices
40 | ConvexHull = cv2.convexHull(cnt)
41 | ConvexArea = cv2.contourArea(ConvexHull)
42 | # Solidity := Area/ConvexArea
43 | Solidity = Area / ConvexArea
44 |
45 | # ELLIPSE - determine best-fitting ellipse.
46 | centre, axes, angle = cv2.fitEllipse(cnt)
47 | MAJ = np.argmax(axes) # this is MAJor axis, 1 or 0
48 | MIN = 1 - MAJ # 0 or 1, minor axis
49 | # Note: axes length is 2*radius in that dimension
50 | MajorAxisLength = axes[MAJ]
51 | MinorAxisLength = axes[MIN]
52 | Eccentricity = np.sqrt(1 - (axes[MIN] / axes[MAJ]) ** 2)
53 | Orientation = angle
54 | EllipseCentre = centre # x,y
55 |
56 | else:
57 | Perimeter = 0
58 | EquivDiameter = 0
59 | Extent = 0
60 | ConvexArea = 0
61 | Solidity = 0
62 | MajorAxisLength = 0
63 | MinorAxisLength = 0
64 | Eccentricity = 0
65 | Orientation = 0
66 | EllipseCentre = [0, 0]
67 |
68 | return {
69 | "area": Area,
70 | "perimeter": Perimeter,
71 | "equiv-diameter": EquivDiameter,
72 | "extent": Extent,
73 | "convex-area": ConvexArea,
74 | "solidity": Solidity,
75 | "major-axis-length": MajorAxisLength,
76 | "minor-axis-length": MinorAxisLength,
77 | "eccentricity": Eccentricity,
78 | "orientation": Orientation,
79 | "ellipse-centre-x": EllipseCentre[0],
80 | "ellipse-centre-y": EllipseCentre[1],
81 | }
82 |
83 |
84 | def grab_cnts(input_info, ds_factor):
85 | """Get the contours from the input dictionary and remove excessive coordinates.
86 |
87 | input_info (list): List of input dictionaries
88 | ds_factor (int): Factor for removing coordinates
89 |
90 | """
91 | output_dict = {}
92 | # first get the input dictionary for a single tissue region
93 | for tissue_idx, input_dict in input_info.items():
94 | tissue_dict = {}
95 | for inst_id, info in input_dict.items():
96 | cnt = info["contour"]
97 | cnt = cnt[::ds_factor, :]
98 | tissue_dict[inst_id] = cnt
99 | output_dict[tissue_idx] = tissue_dict
100 |
101 | return output_dict
102 |
103 |
104 | def grab_centroids_type(input_info):
105 | """Get the contours from the input dictionary and remove excessive coordinates.
106 |
107 | input_info (list): List of input dictionaries
108 |
109 | """
110 | output_dict = {}
111 | # first get the input dictionary for a single tissue region
112 | for tissue_idx, input_dict in input_info.items():
113 | tissue_dict = {}
114 | for inst_id, info in input_dict.items():
115 | centroid = info["centroid"]
116 | type = info["type"]
117 | tissue_dict[inst_id] = {"centroid": centroid, "type": type}
118 | output_dict[tissue_idx] = tissue_dict
119 |
120 | return output_dict
121 |
122 |
123 | def convert_to_df(input_dict, return_type=True):
124 | """Convert input dict to dataframe."""
125 |
126 | cx_list = []
127 | cy_list = []
128 | cnt_list = []
129 | type_list = []
130 | for info in input_dict.values():
131 | centroid = info["centroid"]
132 | cx_list.append(centroid[0])
133 | cy_list.append(centroid[1])
134 | cnt_list.append(info["contour"])
135 | if return_type:
136 | type_list.append(info["type"])
137 |
138 | if return_type:
139 | df = pd.DataFrame(data={"cx": cx_list, "cy": cy_list, "contour": cnt_list, "type": type_list})
140 | else:
141 | df = pd.DataFrame(data={"cx": cx_list, "cy": cy_list, "contour": cnt_list})
142 |
143 | return df
144 |
145 |
146 |
147 | def filter_coords_msk(coords, mask, scale=1, mode="contour", label=None):
148 | """Filter input coordinates so that only coordinates within mask remain.
149 |
150 | Args:
151 | coords: input coordinates to filter
152 | mask: labelled tissue mask
153 | scale: processing resolution to mask scale factor
154 | mode: whether to check entire contour or jus the centroid
155 |
156 | """
157 |
158 | unique_tissue = np.unique(mask).tolist()[1:]
159 | # populate empty dictionary - one per connected component in the tissue mask
160 | output_dict = {}
161 | for idx in unique_tissue:
162 | output_dict[idx] = {}
163 |
164 | # iterate over each object and check to see whether it is within the tissue
165 | for key, value in coords.items():
166 | # if a label is provided, then only consider the contour if it is equal to the label
167 | if label is not None and value["type"] != label:
168 | continue
169 | contours = value[mode]
170 | if mode == "centroid":
171 | contours = [contours]
172 | in_mask = False
173 | for coord in contours:
174 | coord = coord.astype("float64")
175 | coord *= scale
176 | coord = np.rint(coord).astype("int32")
177 | # make sure coordinate is within the mask
178 | if coord[0] > 0 and coord[1] > 0 and coord[0] < mask.shape[1] and coord[1] < mask.shape[0]:
179 | if np.sum(mask[coord[1], coord[0]]) > 0:
180 | tissue_idx = int(mask[coord[1], coord[0]])
181 | in_mask = True
182 |
183 | if in_mask:
184 | inst_uuid = uuid.uuid4().hex
185 | # add contour info to corresponding postion in output dictionary
186 | output_dict[tissue_idx][inst_uuid] = value
187 |
188 | return output_dict
189 |
190 |
191 | def filter_coords_msk2(coords, mask1, mask2, scale=1, mode="centroid"):
192 | """Filter input coordinates so that only coordinates within mask remain.
193 | This function returns an additional dictionary to `filter_coords_msk()`,
194 | which only considers objects in a second provided mask.
195 |
196 | Args:
197 | coords: input coordinates to filter
198 | mask1: labelled tissue mask
199 | mask2: binary mask for further sampling
200 | scale: processing resolution to mask scale factor
201 | mode: whether to check entire contour or jus the centroid
202 |
203 | Returns:
204 | output_dict1 (dict): dictionary of objects within mask
205 | output_dict2 (dict): subset of output_dict1 containing only objects that are also in mask2
206 |
207 | """
208 |
209 | unique_tissue = np.unique(mask1).tolist()[1:]
210 | # populate empty dictionary - one per connected component in the tissue mask
211 | output_dict = {}
212 | output_dict2 = {}
213 | for idx in unique_tissue:
214 | output_dict[idx] = {}
215 | output_dict2[idx] = {}
216 |
217 | # iterate over each object and check to see whether it is within the tissue
218 | for key, value in coords.items():
219 |
220 | contours = value[mode]
221 | if mode == "centroid":
222 | contours = [contours]
223 | in_mask = False
224 | in_mask2 = False
225 | for coord in contours:
226 | coord = coord.astype("float64")
227 | coord *= scale
228 | coord = np.rint(coord).astype("int32")
229 | # make sure coordinate is within the mask
230 | if coord[0] > 0 and coord[1] > 0 and coord[0] < mask1.shape[1] and coord[1] < mask1.shape[0]:
231 | if np.sum(mask1[coord[1], coord[0]]) > 0:
232 | tissue_idx = int(mask1[coord[1], coord[0]])
233 | in_mask = True
234 | ######
235 | if np.sum(mask2[coord[1], coord[0]]) > 0:
236 | # only consider non-epithelilal classes!
237 | if value["type"] != 2:
238 | in_mask2 = True
239 | if in_mask:
240 | inst_uuid = uuid.uuid4().hex
241 | # add contour info to corresponding postion in output dictionary
242 | output_dict[tissue_idx][inst_uuid] = value
243 | if in_mask2:
244 | output_dict2[tissue_idx][inst_uuid] = value
245 |
246 |
247 | return output_dict, output_dict2
248 |
249 |
250 | def filter_coords_cnt(df, contour, mode="contour", return_type=True):
251 | """Filter input coordaintes so that only coordinates within contour remain.
252 |
253 | Args:
254 | df: input dataframe containing coordinates
255 | contour: contours for which to check
256 | mode: whether to check entire contour or jus the centroid
257 |
258 | """
259 |
260 | assert mode in [
261 | "contour",
262 | "centroid",
263 | ], "`mode` must either be `contour` or `centroid`."
264 |
265 | output_dict = {}
266 | # iterate over each object and check to see whether it is within the contour (gland in this case)
267 | for idx, row in df.iterrows():
268 | if mode == "centroid":
269 | cnts = [[row["cx"], row["cy"]]]
270 | else:
271 | cnts = row["contour"]
272 | count = 0
273 | total = 0
274 | for cnt in cnts:
275 | total += 1
276 | cnt = np.rint(cnt).astype("int")
277 | contour = contour.astype("int")
278 | result = cv2.pointPolygonTest(contour, (int(cnt[0]), int(cnt[1])), False)
279 | # check if coordinate lies on or inside the gland contour
280 | if result != -1:
281 | count += 1
282 | # make sure at least 95% of contours are within / on the gland
283 | if count / total > 0.95:
284 | inst_uuid = uuid.uuid4().hex
285 | # add contour info to corresponding postion in output dictionary
286 | if return_type:
287 | output_dict[inst_uuid] = {
288 | "centroid": [row["cx"], row["cy"]],
289 | "contour": row["contour"],
290 | "type": row["type"]
291 | }
292 | else:
293 | output_dict[inst_uuid] = {
294 | "centroid": [row["cx"], row["cy"]],
295 | "contour": row["contour"]
296 | }
297 |
298 | return output_dict
299 |
300 |
301 | def points_list_pairwise_edt(list_a, list_b):
302 | """Get the parwise euclidean distance between two lists of contours.
303 |
304 | Args:
305 | list_a: first list of x,y contour coordinates, with shape Nx2.
306 | list_b: second list of x,y contour coordinates, with shape Nx2.
307 |
308 | Returns:
309 | pairwise euclidean distance.
310 |
311 | """
312 | pix_x_wrt_cnt_x = np.subtract.outer(list_a[:, 0], list_b[:, 0]) # INNER x CNT
313 | pix_y_wrt_cnt_y = np.subtract.outer(list_a[:, 1], list_b[:, 1])
314 | pix_x_wrt_cnt_x = pix_x_wrt_cnt_x.flatten()
315 | pix_y_wrt_cnt_y = pix_y_wrt_cnt_y.flatten()
316 | pix_cnt_dst = np.sqrt(pix_x_wrt_cnt_x ** 2 + pix_y_wrt_cnt_y ** 2) # INNER x CNT
317 | pix_cnt_dst = np.reshape(pix_cnt_dst, (list_a.shape[0], list_b.shape[0]))
318 | return pix_cnt_dst
319 |
320 |
321 | def get_centroid(cnt):
322 | """Get the centroid of a set of contour coordinates.
323 |
324 | Args:
325 | cnt: input contour coordinates.
326 |
327 | Returns:
328 | x and y centroid coordinates.
329 |
330 | """
331 | M = cv2.moments(cnt)
332 | cX = int(M["m10"] / M["m00"])
333 | cY = int(M["m01"] / M["m00"])
334 |
335 | return cX, cY
336 |
337 |
338 | def get_boundary_distance(cnts, centroid):
339 | """"Get the euclidean distance of a centroid to the nearest contour boundary.
340 |
341 | Args:
342 | cnts: coordinates of contour
343 | centroid: coordinates of centroid
344 |
345 | """
346 | min_dst = 100000
347 | for cnt in cnts:
348 | dst = math.sqrt((cnt[0] - centroid[0]) ** 2 + (cnt[1] - centroid[1]) ** 2)
349 | if dst < min_dst:
350 | min_dst = dst
351 |
352 | return min_dst
353 |
354 |
355 | def get_lumen_distance(lumen_info, centroid):
356 | """"Get the euclidean distance of a centroid to the nearest lumen boundary.
357 |
358 | Args:
359 | lumen_info: dict of lumen info
360 | centroid: coordinates of centroid
361 |
362 | """
363 |
364 | dst_list = []
365 | for _, info in lumen_info.items():
366 | cnts = info["contour"]
367 | min_dst = 100000
368 | for cnt in cnts:
369 | dst = math.sqrt((cnt[0] - centroid[0]) ** 2 + (cnt[1] - centroid[1]) ** 2)
370 | if dst < min_dst:
371 | min_dst = dst
372 | dst_list.append(min_dst)
373 |
374 | if len(dst_list) > 0:
375 | return min(dst_list)
376 | else:
377 | return np.nan
378 |
379 |
380 | def get_voronoi_feats(coords):
381 | """Get voronoi diagram features."""
382 | vor = Voronoi(coords)
383 | regions = vor.regions
384 | vertices = vor.vertices
385 |
386 | area = []
387 | perim = []
388 | for region in regions:
389 | if len(region) > 0:
390 | if -1 in region:
391 | region.remove(-1)
392 | if len(region) > 2:
393 | # get the polygon area and perimeter info
394 | region_coords = vertices[region, :].astype('int')
395 | xy_coords = list(zip(region_coords[:, 0], region_coords[:, 1]))
396 | pgon = Polygon(xy_coords) # Assuming the OP's x,y coordinates
397 | area.append(pgon.area)
398 | perim.append(pgon.length)
399 | else:
400 | area.append(0)
401 | perim.append(0)
402 |
403 | return area, perim
404 |
405 |
406 | def find_neighbors(pindex, triang):
407 | """Get the neighbouring vertices of a given vertex from Delaunay triangulation."""
408 | return triang.vertex_neighbor_vertices[1][triang.vertex_neighbor_vertices[0][pindex]:triang.vertex_neighbor_vertices[0][pindex+1]]
409 |
410 |
411 | def get_delaunay_feats(coords):
412 | """Get Delaunay triangulation features."""
413 | tess = Delaunay(coords)
414 | simps = tess.simplices
415 |
416 | area = []
417 | perim = []
418 | min_dst = []
419 | max_dst = []
420 | max_min_dst = []
421 | for idx, simp in enumerate(simps):
422 |
423 | tri_coords = coords[simp, :]
424 | # just being sure that 3 coordinates exist!
425 | if tri_coords.shape[0] == 3:
426 | # get the edge distance info
427 | dst_list = []
428 | for idx in range(3):
429 | if idx+1 == 3:
430 | idx2 = 0
431 | else:
432 | idx2 = idx+1
433 | a = tri_coords[idx, :]
434 | b = tri_coords[idx2, :]
435 | dst_list.append(distance.euclidean(a, b))
436 | min_dst.append(min(dst_list))
437 | max_dst.append(max(dst_list))
438 | max_min_dst.append(max(dst_list) / min(dst_list))
439 |
440 | # get the polygon area and perimeter info
441 | xy_coords = list(zip(tri_coords[:, 0], tri_coords[:, 1]))
442 | pgon = Polygon(xy_coords) # Assuming the OP's x,y coordinates
443 | area.append(pgon.area)
444 | perim.append(pgon.length)
445 |
446 | return area, perim, min_dst, max_dst, max_min_dst
447 |
448 |
449 | def get_k_nearest_from_contour(contour, obj_kdtree, labels, centroids, k=175, nr_samples=None):
450 | """ Get the K nearest nuclei from the contour.
451 |
452 | Args:
453 | contour: input contour
454 | obj_kdtree (sklearn.neighbors.KDTree): KDTree of nuclei centroids
455 | labels: object labels (same index as the tree)
456 | centroids: objects coordinates (same index as the tree)
457 | k: return k nearest objects
458 |
459 | Returns:
460 | output_dst: distances of nearest objects
461 | output_labs: labels of nearest objects
462 | output_cents: coordinates of nearest objects
463 | """
464 | #! This needs optimisation. Consider geopandas.sindex.SpatialIndex.nearest
465 | if nr_samples < k:
466 | k = nr_samples
467 |
468 | contour = np.array(contour)
469 | dist, inds = obj_kdtree.query(contour, k=k)
470 |
471 | distances = {}
472 | if contour.shape[0] > 1:
473 | unique_inds = np.unique(inds).tolist()
474 | for ind in unique_inds:
475 | dist_subset = dist[inds == ind]
476 | min_dst = np.min(dist_subset)
477 | distances[ind] = min_dst
478 | else:
479 | for index in range(dist.shape[-1]):
480 | distances[inds[0, index]] = dist[0, index]
481 |
482 | distances = {k: v for k, v in sorted(distances.items(), key=lambda item: item[1])}
483 |
484 | if len(list(distances.keys())) < k:
485 | k = len(list(distances.keys()))
486 |
487 | # output dict is {type: distance}
488 | output_labs = []
489 | output_cents = []
490 | output_dst = []
491 | dist_keys = list(distances.keys())
492 | dist_values = list(distances.values())
493 | for idx in range(k):
494 | grab_idx = dist_keys[idx]
495 | output_labs.append(labels[grab_idx])
496 | output_cents.append(centroids[grab_idx])
497 | output_dst.append(dist_values[idx])
498 |
499 | return output_dst, output_labs, output_cents
500 |
501 |
502 | def get_nearest_within_radius(centroid, obj_kdtree, labels, r=50, nr_types=6):
503 | """ Get the objects within a fixed radius.
504 |
505 | Args:
506 | contour: input contour
507 | obj_kdtree (sklearn.neighbors.KDTree): KDTree of nuclei centroids
508 | labels: object labels (same index as the tree)
509 | r: return objects within fixed radius
510 |
511 | Returns:
512 | output_dict: frequencies of different nuclei types within radius of r
513 | """
514 |
515 | centroid = np.array(centroid)
516 | inds = obj_kdtree.query_radius(centroid, r=r, return_distance=False)
517 | inds = np.squeeze(inds).tolist()
518 |
519 | lab_list = []
520 | for ind in inds:
521 | lab_list.append(labels[ind])
522 |
523 | # output dict format: {type: frequency}
524 | output_dict = {}
525 | for idx in range(nr_types):
526 | output_dict[idx+1] = lab_list.count(idx+1)
527 |
528 | return output_dict
529 |
530 |
531 | def get_kdtree(input_dict):
532 | """Convert input dictionary of results to KDTree.
533 |
534 | Args:
535 | input_dict: results dictionary.
536 |
537 | Returns:
538 | centroid_kdtree (sklearn.neighbors.KDTree): KD-Tree of object centroids.
539 |
540 | """
541 | centroid_list = []
542 | label_list = []
543 | for key, values in input_dict.items():
544 | centroid_list.append(values["centroid"])
545 | label_list.append(values["type"])
546 |
547 | if len(centroid_list) > 0:
548 | centroid_array = np.array(centroid_list)
549 | centroid_kdtree = KDTree(centroid_array)
550 | else:
551 | centroid_kdtree = None
552 | label_list = None
553 |
554 | return centroid_kdtree, label_list, centroid_list
555 |
556 |
557 | def inter_epi_dst(input_dict, obj_kdtree, labels, lab=2):
558 | """get the stats for distances between epithelial cells.
559 |
560 | Args:
561 | input_dict:
562 | obj_kdtree (sklearn.neighbors.KDTree): KDTree of nuclei centroids in gland
563 | labels: labels of each nucleus
564 | lab: label to consider
565 |
566 | Returns:
567 | mean and std of inter-nuclei distances
568 |
569 | """
570 | centroid_list = []
571 | for values in input_dict.values():
572 | # find nearest object
573 | # only for epi
574 | if values["type"] == lab:
575 | centroid_list.append(values["centroid"])
576 |
577 | if len(centroid_list) > 1:
578 | dst_list = []
579 | for centroid in centroid_list:
580 | centroid = np.reshape(centroid, (1, 2))
581 | dst, _ = obj_kdtree.query(centroid, k=2)
582 | dst_list.append(dst[0,1])
583 | else:
584 | dst_list = [0]
585 |
586 | return dst_list
587 |
588 |
589 | def get_dst_matrix(list_cnts, sorted=False):
590 | """Get the distance matrix. Measures the distance between all object contours.
591 |
592 | Args:
593 | list_cnts: input list of object contour coordinates.
594 |
595 |
596 | Returns:
597 | dst_matrix: NxN array of matrix of distances between objects.
598 |
599 | """
600 | nr_objs = len(list_cnts)
601 | dst_matrix = np.zeros([nr_objs, nr_objs])
602 |
603 | for i in range(nr_objs):
604 | cnt1 = list_cnts[i]
605 | for j in range(nr_objs):
606 | if i != j:
607 | cnt2 = list_cnts[j]
608 | dist = points_list_pairwise_edt(cnt1, cnt2)
609 | # distance between objects is the min dist between 2 contours
610 | dst_matrix[i, j] = np.min(dist)
611 |
612 | if sorted:
613 | dst_matrix = np.sort(dst_matrix, axis=-1)
614 |
615 | return dst_matrix
616 |
617 |
618 | def get_bam(cnt, centroid):
619 | """Get the BAM (best alignment metric)."""
620 | # get enclosing ellipse
621 | ellipse_coords = get_enclosing_ellipse(cnt)
622 | # transform ellipse to circle
623 | circle_coords, alpha, a, b = ellipse_to_circle(ellipse_coords)
624 | # transform original object with same transformation
625 | trans_coords = apply_transform(cnt, centroid, alpha, a, b)
626 | # compute best alignment metric (BAM)
627 | bam_distance, _, _ = best_alignment_metric(
628 | circle_coords, trans_coords, show_plots=False
629 | )
630 |
631 | return bam_distance
632 |
633 |
634 | def get_tissue_region_info_patch(cnt, mask, relax_pix=50, ds_factor=0.125):
635 | """Get the patch around a given contour by considering the relaxed bounding box."""
636 |
637 | # contour is at 0.5 mpp
638 | # mask is at 4.0 mpp
639 | # relax_pix operates at mask level
640 |
641 | # first convert contours to correct scale
642 | cnt = cnt * ds_factor
643 | cnt = cnt.astype('int')
644 | x,y,w,h = cv2.boundingRect(cnt)
645 |
646 | x = x - relax_pix
647 | y = y - relax_pix
648 | w = w + 2*relax_pix
649 | h = h + 2*relax_pix
650 |
651 | if x < 0:
652 | x = 0
653 | if y < 0:
654 | y = 0
655 | if x > (mask.shape[1] - relax_pix):
656 | x = mask.shape[1] - relax_pix
657 | if y > (mask.shape[0] - relax_pix):
658 | y = mask.shape[0] - relax_pix
659 |
660 | patch = mask[y: y+h, x: x+w]
661 |
662 | return patch
663 |
664 |
665 | def get_patch_prop(region_info_patch, total_pix, labs):
666 | """Get the proportion of a certain tissue type in a labelled input patch."""
667 | output_list = []
668 | for lab in labs:
669 | lab_tmp = region_info_patch == lab
670 | nr_pix = np.sum(lab_tmp)
671 |
672 | if total_pix == 0:
673 | output_list.append(0)
674 | else:
675 | output_list.append(nr_pix / total_pix)
676 |
677 | return output_list
--------------------------------------------------------------------------------
/misc/utils.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import os
3 | import shutil
4 | import joblib
5 | import numpy as np
6 | import cv2
7 | import torch
8 |
9 | import sys
10 | sys.path.append("../")
11 |
12 |
13 | def normalize(mask, dtype=np.uint8):
14 | return (255 * mask / np.amax(mask)).astype(dtype)
15 |
16 |
17 | def get_bounding_box(img):
18 | rows = np.any(img, axis=1)
19 | cols = np.any(img, axis=0)
20 | rmin, rmax = np.where(rows)[0][[0, -1]]
21 | cmin, cmax = np.where(cols)[0][[0, -1]]
22 | # due to python indexing, need to add 1 to max
23 | # else accessing will be 1px in the box, not out
24 | rmax += 1
25 | cmax += 1
26 | return [rmin, rmax, cmin, cmax]
27 |
28 |
29 | def cropping_center(x, crop_shape, batch=False):
30 | orig_shape = x.shape
31 | if not batch:
32 | h0 = int((orig_shape[0] - crop_shape[0]) * 0.5)
33 | w0 = int((orig_shape[1] - crop_shape[1]) * 0.5)
34 | x = x[h0:h0 + crop_shape[0], w0:w0 + crop_shape[1]]
35 | else:
36 | h0 = int((orig_shape[1] - crop_shape[0]) * 0.5)
37 | w0 = int((orig_shape[2] - crop_shape[1]) * 0.5)
38 | x = x[:, h0:h0 + crop_shape[0], w0:w0 + crop_shape[1]]
39 | return x
40 |
41 |
42 | def rm_n_mkdir(dir_path):
43 | if (os.path.isdir(dir_path)):
44 | shutil.rmtree(dir_path)
45 | os.makedirs(dir_path)
46 |
47 |
48 | def get_files(data_dir_list, data_ext):
49 | """Given a list of directories containing data with extention 'data_ext',
50 | generate a list of paths for all files within these directories
51 |
52 | """
53 | data_files = []
54 | for sub_dir in data_dir_list:
55 | files_list = glob.glob(sub_dir + '/*' + data_ext)
56 | files_list.sort() # ensure same order
57 | data_files.extend(files_list)
58 |
59 | return data_files
60 |
61 |
62 | def remap_label(pred, by_size=False, ds_factor=None):
63 | """Rename all instance id so that the id is contiguous i.e [0, 1, 2, 3]
64 | not [0, 2, 4, 6]. The ordering of instances (which one comes first)
65 | is preserved unless by_size=True, then the instances will be reordered
66 | so that bigger nucler has smaller ID
67 |
68 | Args:
69 | pred : the 2d array contain instances where each instances is marked
70 | by non-zero integer
71 | by_size : renaming with larger nuclei has smaller id (on-top)
72 |
73 | """
74 | pred_id = list(np.unique(pred))
75 | pred_id.remove(0)
76 | if len(pred_id) == 0:
77 | return pred # no label
78 | if by_size:
79 | pred_size = []
80 | for inst_id in pred_id:
81 | size = (pred == inst_id).sum()
82 | pred_size.append(size)
83 | # sort the id by size in descending order
84 | pair_list = zip(pred_id, pred_size)
85 | pair_list = sorted(pair_list, key=lambda x: x[1], reverse=True)
86 | pred_id, pred_size = zip(*pair_list)
87 |
88 | new_pred = np.zeros(pred.shape, np.int32)
89 | for idx, inst_id in enumerate(pred_id):
90 | new_pred[pred == inst_id] = idx + 1
91 |
92 | return new_pred
93 |
94 |
95 | def get_inst_centroid(inst_map):
96 | inst_centroid_list = []
97 | inst_id_list = list(np.unique(inst_map))
98 | for inst_id in inst_id_list[1:]: # avoid 0 i.e background
99 | mask = np.array(inst_map == inst_id, np.uint8)
100 | inst_moment = cv2.moments(mask)
101 | inst_centroid = [(inst_moment["m10"] / inst_moment["m00"]),
102 | (inst_moment["m01"] / inst_moment["m00"])]
103 | inst_centroid_list.append(inst_centroid)
104 | return np.array(inst_centroid_list)
105 |
106 |
107 | def get_local_feat_stats(file_list):
108 | """Calculate mean and standard deviation from features- used for normalisation
109 | of input features before input to GCN.
110 |
111 | Args:
112 | file_list: list of .dat files containing features
113 |
114 | """
115 | feats_tmp = joblib.load(file_list[0])
116 | feat_names = list(feats_tmp["local_feats"].keys())
117 | del feats_tmp
118 |
119 | print("Getting local feature statistics...")
120 | output_dict = {}
121 | mean_dict = {}
122 | median_dict = {}
123 | std_dict = {}
124 | perc_25_dict = {}
125 | perc_75_dict = {}
126 | for feat_name in feat_names:
127 | if feat_name == "obj_id":
128 | mean = 0.0
129 | median = 0.0
130 | std = 0.0
131 | perc_25 = 0.0
132 | perc_75 = 0.0
133 | else:
134 | accumulated_feats_tmp = []
135 | for filepath in file_list:
136 | feats = joblib.load(filepath)["local_feats"] # hard assumption on .dat file
137 | feats = feats[feat_name].tolist()
138 | accumulated_feats_tmp.extend(np.float32(feats))
139 | mean = float(np.nanmean(np.array(accumulated_feats_tmp)))
140 | median = float(np.nanmedian(np.array(accumulated_feats_tmp)))
141 | std = float(np.nanstd(np.array(accumulated_feats_tmp)))
142 | perc_25 = float(np.nanpercentile(np.array(accumulated_feats_tmp), q=25))
143 | perc_75 = float(np.nanpercentile(np.array(accumulated_feats_tmp), q=75))
144 |
145 | mean_dict[feat_name] = mean
146 | median_dict[feat_name] = median
147 | std_dict[feat_name] = std
148 | perc_25_dict[feat_name] = perc_25
149 | perc_75_dict[feat_name] = perc_75
150 |
151 | output_dict["mean"] = mean_dict
152 | output_dict["median"] = median_dict
153 | output_dict["std"] = std_dict
154 | output_dict["perc_25"] = perc_25_dict
155 | output_dict["perc_75"] = perc_75_dict
156 |
157 | return output_dict
158 |
159 | def get_pna_deg(file_list, feat_names, save_path):
160 | """Compute the maximum in-degree in the training data. Only needed for PNA Conv."""
161 |
162 | from dataloader.graph_loader import FileLoader
163 | from torch_geometric.utils import degree
164 |
165 | print("Computing maximum node degree for PNA conv...")
166 |
167 | input_dataset = FileLoader(file_list, feat_names, feat_stats=None, norm=None, data_clean=None)
168 |
169 | max_degree = -1
170 | for data in input_dataset:
171 | d = degree(data.edge_index[1], num_nodes=data.num_nodes, dtype=torch.long)
172 | max_degree = max(max_degree, int(d.max()))
173 |
174 | # Compute the in-degree histogram tensor
175 | deg = torch.zeros(max_degree + 1, dtype=torch.long)
176 | for data in input_dataset:
177 | d = degree(data.edge_index[1], num_nodes=data.num_nodes, dtype=torch.long)
178 | deg += torch.bincount(d, minlength=deg.numel())
179 |
180 | np.save(f"{save_path}/node_deg.npy", deg)
181 |
182 |
183 | def ranking_loss(pred, true):
184 | """Ranking loss.
185 |
186 | Args:
187 | pred: prediction array
188 | true: ground truth array
189 |
190 | """
191 | loss = 0
192 | c = 0
193 | z = torch.Tensor([0]).to("cuda").type(torch.float32)
194 | for i in range(len(true)-1):
195 | for j in range(i+1, len(true)):
196 | if true[i] != true[j]:
197 | c += 1
198 | dz = pred[i,-1]-pred[j,-1]
199 | dy = true[i]-true[j]
200 | loss += torch.max(z, 1.0-dy*dz)
201 | return loss/c
202 |
203 |
204 | def refine_files(file_list, wsi_info):
205 | """Remove unwanted categories."""
206 |
207 | wsi_info["Diagnostic Category"].replace(
208 | {
209 | "Normal ": "Normal",
210 | "Abnormal: Non-Neoplastic ": "Abnormal: Non-Neoplastic",
211 | "Abnormal: Neoplastic ": "Abnormal: Neoplastic",
212 | },
213 | inplace=True,
214 | )
215 |
216 | refined_list = []
217 | for filename in file_list:
218 | wsiname = os.path.basename(filename)
219 | wsiname = wsiname[:-4]
220 |
221 | subset = wsi_info.loc[wsi_info["WSI no"] == wsiname]
222 | diagnosis = np.array(subset["Specific Diagnosis"])[0]
223 | if not isinstance(diagnosis, float):
224 | diagnosis = diagnosis.lower()
225 |
226 | category = np.array(subset["Diagnostic Category"])[0]
227 | if category == "Normal":
228 | category = 0
229 | if category == "Abnormal: Non-Neoplastic":
230 | category = 1
231 | if category == "Abnormal: Neoplastic":
232 | category = 2
233 |
234 | # clean up
235 | diagnosis = diagnosis.replace(",", " ")
236 | diagnosis = diagnosis.replace(":", " ")
237 | diagnosis = diagnosis.replace(".", " ")
238 | diagnosis = diagnosis.replace("?", " ")
239 | diagnosis = diagnosis.replace("-", " ")
240 | diagnosis_split = diagnosis.split(" ")
241 |
242 | if "spirochetosis" not in diagnosis_split and "melanosis" not in diagnosis_split and "malanosis" not in diagnosis_split:
243 | refined_list.append(filename)
244 |
245 | return refined_list
246 |
247 |
248 | def get_focus_tissue(wsi_path, tissuetype, results_gland, nr_classes=9, mode="lp", ds_factor=8):
249 | """Get non-glandular area within the issue which is considered for cell quantification. For
250 | biopsies, this is the lamina propria - otherwise, consider the entire non-glandular tissue area!
251 |
252 | Args:
253 | wsi_path: path to the original WSI
254 | tissetype (array): tissue type prediction
255 | results_gland (dict): gland segmentation results
256 | nr_classes (int): Number of classes considered by tissue type prediction
257 | mode (str): if `lp` then consider lamina propria area - otherwise consider entire tissue
258 | ds_factor (int): factor for converting gland segmentation coordinates to appropriate resolution.
259 |
260 | Returns:
261 | out_focus (array): binary map containing tissue region of interest
262 |
263 | """
264 | from scipy.ndimage import measurements
265 | from skimage.morphology import remove_small_holes
266 | from skimage.morphology.misc import remove_small_objects
267 |
268 | from tiatoolbox.wsicore.wsireader import WSIReader
269 |
270 | wsi_handler = WSIReader.open(wsi_path)
271 | # in XY
272 | wsi_thumb = wsi_handler.slide_thumbnail(resolution=4.0, units="mpp")
273 | wsi_blur = cv2.GaussianBlur(
274 | cv2.cvtColor(wsi_thumb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
275 |
276 | tissuetype = cv2.resize(tissuetype, (wsi_thumb.shape[1], wsi_thumb.shape[0]))
277 | del wsi_thumb
278 |
279 | out_focus = np.zeros([tissuetype.shape[0], tissuetype.shape[1]])
280 |
281 | if mode == "lp":
282 | # only consider tumour and glandular regions if lamina propria
283 | for i in range(nr_classes):
284 | if i == 1 or i == 2:
285 | tmp = tissuetype == i
286 | out_focus[tmp] = 1
287 | else:
288 | tmp = tissuetype == i
289 | out_focus[tmp] = 0
290 | else:
291 | # consider all tissue
292 | out_focus[out_focus > 0] = 1
293 |
294 | out_focus = remove_small_holes(out_focus.astype("bool"), area_threshold=3900)
295 | out_focus = out_focus.astype("uint8")
296 |
297 | out_focus[out_focus > 0] = 1
298 |
299 | for inst_info in results_gland.values():
300 | cnt = inst_info["contour"]
301 | cnt = cnt / ds_factor
302 | cnt = np.rint(cnt).astype("int")
303 | cv2.fillPoly(out_focus, pts=[cnt], color=0)
304 |
305 | del results_gland
306 |
307 | out_focus[wsi_blur > 225] = 0
308 |
309 | out_focus_lab = measurements.label(out_focus)[0]
310 | out_focus = remove_small_objects(out_focus_lab.astype("bool"), min_size=2500)
311 |
312 | out_focus[out_focus > 0] = 255
313 |
314 | return out_focus
--------------------------------------------------------------------------------
/models/net_desc.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 | import torch
4 | import torch.nn as nn
5 | import torch.nn.functional as F
6 | from torch.nn import BatchNorm1d
7 |
8 | from torch_geometric.nn import (
9 | PNAConv,
10 | GATConv,
11 | global_mean_pool,
12 | )
13 | from torch_geometric.utils import softmax
14 | from torch_geometric.nn.inits import reset
15 | from torch_scatter import scatter_add
16 |
17 |
18 | def weights_init(m):
19 | if isinstance(m, nn.Linear):
20 | nn.init.kaiming_uniform_(m.weight, mode="fan_out", nonlinearity="relu")
21 | nn.init.constant_(m.bias, 0)
22 | if isinstance(m, nn.BatchNorm1d):
23 | nn.init.constant_(m.weight, 1)
24 | nn.init.constant_(m.bias, 0)
25 |
26 |
27 | class GlobalAtt(torch.nn.Module):
28 | """GlobalAttenion but returning the attention scores."""
29 | def __init__(self, gate_nn, nn):
30 | super().__init__()
31 | self.gate_nn = gate_nn
32 | self.nn = nn
33 |
34 | self.reset_parameters()
35 |
36 | def reset_parameters(self):
37 | reset(self.gate_nn)
38 | reset(self.nn)
39 |
40 | def forward(self, x: torch.Tensor, batch: Optional[torch.Tensor] = None,
41 | size: Optional[int] = None):
42 | r"""
43 | Args:
44 | x (Tensor): The input node features.
45 | batch (LongTensor, optional): A vector that maps each node to its
46 | respective graph identifier. (default: :obj:`None`)
47 | size (int, optional): The number of graphs in the batch.
48 | (default: :obj:`None`)
49 | """
50 | if batch is None:
51 | batch = x.new_zeros(x.size(0), dtype=torch.int64)
52 |
53 | x = x.unsqueeze(-1) if x.dim() == 1 else x
54 | size = int(batch.max()) + 1 if size is None else size
55 |
56 | gate = self.gate_nn(x).view(-1, 1)
57 | x = self.nn(x) if self.nn is not None else x
58 | assert gate.dim() == x.dim() and gate.size(0) == x.size(0)
59 |
60 | gate = softmax(gate, batch, num_nodes=size)
61 | out = scatter_add(gate * x, batch, dim=0, dim_size=size)
62 |
63 | return out, gate
64 |
65 |
66 | class PNALayer(nn.Module):
67 | """PNA layer.
68 |
69 | Args:
70 | in_ch: number of input channels.
71 | out_ch: number of output channels.
72 |
73 | """
74 |
75 | def __init__(
76 | self,
77 | in_ch,
78 | out_ch,
79 | aggregators=['mean', 'min', 'max', 'std'],
80 | scalers = ['identity', 'amplification', 'attenuation'],
81 | deg=None
82 | ):
83 | super().__init__()
84 |
85 | self.gconv = PNAConv(in_ch, out_ch, aggregators=aggregators, scalers=scalers, deg=deg)
86 |
87 | def forward(self, x, edge_index, freeze=False):
88 | if self.training:
89 | with torch.set_grad_enabled(not freeze):
90 | new_feat = self.gconv(x, edge_index)
91 | else:
92 | new_feat = self.gconv(x, edge_index)
93 |
94 | return new_feat
95 |
96 |
97 | class NetDesc(nn.Module):
98 | """Network description."""
99 |
100 | def __init__(
101 | self,
102 | model_name,
103 | nr_features,
104 | node_degree,
105 | nhid=[12,12,12],
106 | grph_dim=10,
107 | dropout_rate=0.03,
108 | use_edges=0,
109 | label_dim=2,
110 | agg="attention",
111 | return_prob=False,
112 | ):
113 | super().__init__()
114 | self.dropout_rate = dropout_rate
115 | self.use_edges = use_edges
116 | self.agg = agg
117 | self.return_prob = return_prob
118 |
119 | node_degree = torch.Tensor(node_degree)
120 |
121 | if model_name == "graphsage":
122 | self.gconv1 = GraphSageLayer(nhid[0], nhid[1])
123 | self.gconv2 = GraphSageLayer(nhid[1], nhid[2])
124 | elif model_name == "gat":
125 | self.gconv1 = GATLayer(nhid[0], nhid[1])
126 | self.gconv2 = GATLayer(nhid[1], nhid[2])
127 | elif model_name == "gin":
128 | self.gconv1 = GINLayer(nhid[0], nhid[1], act="relu")
129 | self.gconv2 = GINLayer(nhid[1], nhid[2], act="relu")
130 | elif model_name == "pna":
131 | self.gconv1 = PNALayer(nhid[0], nhid[1], deg=node_degree)
132 | self.gconv2 = PNALayer(nhid[1], nhid[2], deg=node_degree)
133 | elif model_name == "edge":
134 | self.gconv1 = EdgeConvLayer(nhid[0], nhid[1], act="relu")
135 | self.gconv2 = EdgeConvLayer(nhid[1], nhid[2], act="relu")
136 | elif model_name == "linear":
137 | self.gconv1 = nn.Linear(nhid[0], nhid[1])
138 | self.gconv2 = nn.Linear(nhid[1], nhid[2])
139 |
140 | self.lin0 = nn.Linear(nr_features, nhid[0])
141 | self.lin_emb0 = nn.Linear(nhid[0], grph_dim)
142 | self.lin_emb1 = nn.Linear(nhid[1], grph_dim)
143 | self.lin_emb2 = nn.Linear(nhid[2], grph_dim)
144 |
145 | self.lin_merge = nn.Linear(grph_dim*3, grph_dim)
146 |
147 | gate_nn = nn.Sequential(nn.Linear(grph_dim, 1))
148 | v_nn = nn.Sequential(nn.Linear(grph_dim, grph_dim))
149 | self.gpool = GlobalAtt(gate_nn, v_nn)
150 | # self.gpool = GlobalAttention(gate_nn, v_nn)
151 |
152 | self.lin_out = nn.Linear(grph_dim, label_dim)
153 |
154 | self.dropout = nn.Dropout(dropout_rate)
155 |
156 | def forward(self, x, edge_index, batch):
157 | edge_attr = None
158 | x0 = self.lin0(x)
159 | x1 = self.gconv1(x0, edge_index)
160 | x2 = self.gconv2(x1, edge_index)
161 | ###
162 | x0 = self.dropout(F.relu(self.lin_emb0(x0)))
163 | x1 = self.dropout(F.relu(self.lin_emb1(x1)))
164 | x2 = self.dropout(F.relu(self.lin_emb2(x2)))
165 | ###
166 | x_combined = F.relu(self.lin_merge(torch.cat((x0, x1, x2), dim=1)))
167 |
168 | # pool over node-level features
169 | if self.agg == 'attention':
170 | att_pool = self.gpool(x_combined, batch)
171 | logits = att_pool[0]
172 | scores = att_pool[1]
173 | scores = None
174 | elif self.agg == 'mean':
175 | scores = self.lin_scores(x_combined)
176 | logits = global_mean_pool(scores, batch)
177 |
178 | output1 = F.softmax(self.lin_out(logits), dim=-1)
179 | output2 = self.lin_out(logits)
180 |
181 | if self.return_prob:
182 | output = output1
183 | else:
184 | output = {"output": output1, "output_log": output2, "node_scores": scores}
185 |
186 | return output
187 |
188 | ####
189 | def create_model(**kwargs):
190 | return NetDesc(**kwargs)
191 |
--------------------------------------------------------------------------------
/models/run_desc.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | import torch.nn.functional as F
4 | from sklearn.metrics import roc_auc_score
5 |
6 | import sys
7 | sys.path.append("..")
8 | from metrics.stats_utils import get_sens_spec_metrics
9 | from misc.utils import ranking_loss
10 |
11 |
12 | def train_step(batch_data, run_info, device="cuda"):
13 | run_info, state_info = run_info
14 |
15 | weight = torch.tensor([1, 1]).to(device).type(torch.float32)
16 |
17 | loss_func_dict = {
18 | "ce": torch.nn.CrossEntropyLoss(weight),
19 | "ranking": ranking_loss
20 | }
21 | # use 'ema' to add for EMA calculation, must be scalar!
22 | result_dict = {"EMA": {}}
23 | track_value = lambda name, value: result_dict["EMA"].update({name: value})
24 |
25 | ####
26 | batch = batch_data.batch
27 | edge_index = batch_data.edge_index
28 | feats = batch_data.x
29 | label = batch_data.y
30 |
31 | #! below is specific to CoBi!
32 | # data is 3-class -> convert to 2 class (normal vs abnormal)
33 | label_orig = label.clone() # make copy of original 3 class label for evaluation
34 | label[label > 1] = 1
35 |
36 | batch = batch.to(device).type(torch.int64)
37 | edge_index = edge_index.to(device).type(torch.long)
38 | feats = feats.to(device).type(torch.float32)
39 | label = torch.squeeze(label.to(device).type(torch.int64))
40 |
41 | ####
42 | model = run_info["net"]["desc"]
43 | optimizer = run_info["net"]["optimizer"]
44 | ####
45 | model.train()
46 | model.zero_grad() # not rnn so don't accumulate
47 | out_dict = model(feats, edge_index, batch)
48 | out = out_dict["output_log"]
49 | prob = out
50 |
51 | ####
52 | loss = 0
53 | loss_opts = run_info["net"]["extra_info"]["loss"]
54 |
55 | for loss_name, loss_weight in loss_opts.items():
56 | loss_func = loss_func_dict[loss_name]
57 | loss_args = [out, label]
58 | term_loss = loss_func(*loss_args)
59 | track_value("loss_%s" % loss_name, term_loss.cpu().item())
60 | loss += loss_weight * term_loss
61 | loss = torch.unsqueeze(loss, 0)
62 |
63 | track_value("overall_loss", loss.cpu().item())
64 |
65 | # * gradient update
66 | loss.backward()
67 | optimizer.step()
68 | ####
69 |
70 | # * Its up to user to define the protocol to process the raw output per step!
71 | result_dict["raw"] = {"true": label, "true_orig": label_orig, "prob": prob}
72 |
73 | return result_dict
74 |
75 |
76 | def valid_step(batch_data, run_info, device="cuda"):
77 | run_info, state_info = run_info
78 | ####
79 | batch = batch_data.batch
80 | edge_index = batch_data.edge_index
81 | feats = batch_data.x
82 | label = batch_data.y
83 |
84 | # data is 3-class -> convert to 2 class (normal vs abnormal)
85 | label_orig = label.clone() # make copy of original 3 class label for evaluation
86 | label[label > 1] = 1
87 |
88 | batch = batch.to(device).type(torch.int64)
89 | edge_index = edge_index.to(device).type(torch.long)
90 | feats = feats.to(device).type(torch.float32)
91 | label = label.to(device).type(torch.int64)
92 |
93 | ####
94 | model = run_info["net"]["desc"]
95 | model.eval() # inference mode
96 |
97 | # --------------------------------------------------------------
98 | with torch.no_grad(): # dont compute gradient
99 | out_dict = model(feats, edge_index, batch)
100 | prob = out_dict["output"]
101 |
102 | # * Its up to user to define the protocol to process the raw output per step!
103 | result_dict = {"raw": {"true": label, "true_orig": label_orig, "prob": prob}}
104 |
105 | return result_dict
106 |
107 |
108 | def infer_step(batch_data, model, device="cuda"):
109 | ####
110 | batch = batch_data.batch
111 | edge_index = batch_data.edge_index
112 | feats = batch_data.x
113 | label = batch_data.y
114 | wsi_name = batch_data.wsi_name
115 |
116 | # data is 3-class -> convert to 2 class (normal vs abnormal)
117 | label_orig = label.clone() # make copy of original 3 class label for evaluation
118 | label[label > 1] = 1
119 |
120 | batch = batch.to(device).type(torch.int64)
121 | edge_index = edge_index.to(device).type(torch.long)
122 | feats = feats.to(device).type(torch.float32)
123 | label = label.to(device).type(torch.int64)
124 |
125 | ####
126 | model.eval() # inference mode
127 |
128 | # --------------------------------------------------------------
129 | with torch.no_grad(): # dont compute gradient
130 | out_dict = model(feats, edge_index, batch)
131 | prob = out_dict["output"]
132 | node_scores = out_dict["node_scores"]
133 |
134 | # * Its up to user to define the protocol to process the raw output per step!
135 | result_dict = {"true": label, "true_orig": label_orig, "prob": prob, "node_scores": node_scores, "wsi_name": wsi_name}
136 |
137 | return result_dict
138 |
139 |
140 | def proc_valid_step_output(raw_data):
141 | track_dict = {"scalar": {}, "image": {}}
142 |
143 | def track_value(name, value, vtype):
144 | return track_dict[vtype].update({name: value})
145 |
146 | prob = raw_data["prob"]
147 | true = raw_data["true"]
148 | true_orig = np.array(raw_data["true_orig"])
149 | num_examples = len(raw_data["true"])
150 |
151 | prob_list = []
152 | true_list = []
153 | for idx in range(num_examples):
154 | graph_prob = prob[idx][1]
155 | graph_true = true[idx]
156 | prob_list.append(graph_prob.cpu())
157 | true_list.append(graph_true.cpu())
158 |
159 | prob = np.array(prob_list)
160 | pred = prob.copy()
161 | pred[pred >= 0.5] = 1
162 | pred[pred < 0.5] = 0
163 | true = np.array(true_list)
164 |
165 | auc = roc_auc_score(true, prob)
166 |
167 | spec_95, spec_97, spec_98, spec_99, spec_100 = get_sens_spec_metrics(true, prob)
168 |
169 | track_value("AUC-ROC", auc, "scalar")
170 | track_value("Specifity_at_95_Sensitivity", spec_95, "scalar")
171 | track_value("Specifity_at_97_Sensitivity", spec_97, "scalar")
172 | track_value("Specifity_at_98_Sensitivity", spec_98, "scalar")
173 | track_value("Specifity_at_99_Sensitivity", spec_99, "scalar")
174 |
175 | return track_dict
176 |
177 |
--------------------------------------------------------------------------------
/run_infer.py:
--------------------------------------------------------------------------------
1 | """run_infer.py
2 |
3 | Process slides with IGUANA.
4 |
5 | Usage:
6 | run_infer.py [--gpu=] [--model_path=] [--model_name=] [--data_dir=] \
7 | [--data_info=] [--stats_dir=] [--output_dir=] [--batch_size=] \
8 | [--fold_nr=] [--split_nr=] [--num_workers=]
9 | run_infer.py (-h | --help)
10 | run_infer.py --version
11 |
12 | Options:
13 | -h --help Show this string.
14 | --version Show version.
15 | --gpu= GPU list. [default: 0]
16 | --model_path= Path to saved checkpoint.
17 | --model_name= Type of graph convolution used. [default: pna]
18 | --data_dir= Path to where graph data is stored.
19 | --data_info= Path to where data information csv file is stored
20 | --stats_dir= Location of feaure stats directory for input standardisation.
21 | --output_dir= Path where output will be saved. [default: output/]
22 | --batch_size= Batch size. [default: 1]
23 | --fold_nr= Fold number considered during cross validation. Don't change if considering independent test set. [default: 1]
24 | --split_nr= Only consider slides in the data info csv according to this selected number. [default: 3]
25 | --num_workers= Number of workers. [default: 8]
26 |
27 | """
28 |
29 | import os
30 | import yaml
31 | from docopt import docopt
32 | import tqdm
33 | import numpy as np
34 | import pandas as pd
35 | from importlib import import_module
36 | import glob
37 | from sklearn.metrics import roc_auc_score, precision_recall_curve, auc
38 |
39 | import torch
40 | from torch_geometric.data import DataLoader
41 |
42 | from dataloader.graph_loader import FileLoader
43 | from metrics.stats_utils import get_sens_spec_metrics
44 | from misc.utils import rm_n_mkdir
45 |
46 | import warnings
47 | warnings.filterwarnings('ignore')
48 |
49 |
50 | def get_labels_scores(wsi_names, scores, gt, binarize=True):
51 | """Align the scores and labels."""
52 | labels_output = []
53 | scores_output = []
54 | for idx, wsi_name in enumerate(wsi_names):
55 | score = scores[idx]
56 | gt_subset = gt[gt["wsi_name"] == wsi_name]
57 | lab = list(gt_subset["label"])
58 | if len(lab) > 0:
59 | lab = int(lab[0])
60 | if binarize:
61 | if lab > 0:
62 | lab = 1
63 | labels_output.append(lab)
64 | scores_output.append(score)
65 | return labels_output, scores_output
66 |
67 |
68 | class InferBase(object):
69 | def __init__(self, **kwargs):
70 | self.run_step = None
71 | for variable, value in kwargs.items():
72 | self.__setattr__(variable, value)
73 | self.__load_model()
74 | return
75 |
76 | def __load_model(self):
77 | """Create the model, load the checkpoint and define
78 | associated run steps to process each data batch
79 |
80 | """
81 | model_desc = import_module('models.net_desc')
82 | model_creator = getattr(model_desc, 'create_model')
83 |
84 | # TODO: deal with parsing multi level model desc
85 | net = model_creator(
86 | model_name=self.model_name,
87 | nr_features=len(self.feat_names),
88 | node_degree=self.node_degree).to('cuda')
89 | saved_state_dict = torch.load(self.model_path)
90 | net.load_state_dict(saved_state_dict['desc'], strict=True)
91 |
92 | run_desc = import_module('models.run_desc')
93 | self.run_step = lambda input_batch: getattr(
94 | run_desc, 'infer_step')(input_batch, net)
95 | return
96 |
97 |
98 | class Infer(InferBase):
99 | def __run_model(self, file_list):
100 |
101 | print('Loading feature statistics...')
102 | with open(f"{self.stats_path}/stats_dict.yml") as fptr:
103 | stats_dict = yaml.full_load(fptr)
104 |
105 | input_dataset = FileLoader(
106 | file_list, self.feat_names, feat_stats=stats_dict, norm="standard", data_clean="std"
107 | )
108 |
109 | dataloader = DataLoader(input_dataset,
110 | num_workers=self.nr_procs,
111 | batch_size=self.batch_size,
112 | shuffle=False,
113 | drop_last=False
114 | )
115 |
116 | pbar = tqdm.tqdm(desc='Processsing', leave=True,
117 | total=int(len(dataloader)),
118 | ncols=80, ascii=True, position=0)
119 |
120 | pred_all = []
121 | prob_all = []
122 | true_all = []
123 | wsi_name_all = []
124 | for _, batch_data in enumerate(dataloader):
125 |
126 | batch_output = self.run_step(batch_data)
127 | pred_list = []
128 | prob_list = []
129 | true_list = []
130 | wsi_name_list = []
131 |
132 | prob = batch_output['prob']
133 | true = batch_output['true']
134 | wsi_name = batch_output['wsi_name'][0]
135 | num_examples = len(batch_output['true'])
136 |
137 | for idx in range(num_examples):
138 | pred_tmp = torch.argmax(prob[idx])
139 | prob_tmp = prob[idx][1]
140 | true_tmp = true[idx]
141 | pred_list.append(pred_tmp.cpu())
142 | prob_list.append(prob_tmp.cpu())
143 | true_list.append(true_tmp.cpu())
144 | wsi_name_list.append(wsi_name)
145 |
146 | pred_all.extend(pred_list)
147 | prob_all.extend(prob_list)
148 | true_all.extend(true_list)
149 | wsi_name_all.extend(wsi_name_list)
150 |
151 | pbar.update()
152 | pbar.close()
153 | return np.array(pred_all), np.array(prob_all), np.array(true_all), np.array(wsi_name_all)
154 |
155 |
156 | def __get_stats(self, prob, true):
157 | # AUC-ROC
158 | auc_roc = roc_auc_score(true, prob)
159 | # AUC-PR
160 | pr, re, _ = precision_recall_curve(true, prob)
161 | auc_pr = auc(re, pr)
162 | # specificity @ given sensitivity
163 | spec_95, spec_97, spec_98, spec_99, spec_100 = get_sens_spec_metrics(true, prob)
164 |
165 | print('='*50)
166 | print("AUC-ROC:", auc_roc)
167 | print("AUC-PR:", auc_pr)
168 | print("Specifity_at_97_Sensitivity:", spec_97)
169 | print("Specifity_at_98_Sensitivity:", spec_98)
170 | print("Specifity_at_99_Sensitivity:", spec_99)
171 |
172 | def process_files(self):
173 |
174 | # select the slides according to selected fold_nr and split_nr
175 | # independent test set should have split_nr all equal to 3
176 | data_info = pd.read_csv(self.data_info)
177 | file_list = []
178 | for row in data_info.iterrows():
179 | wsi_name = row[1].iloc[0]
180 | if row[1].iloc[self.fold_nr] == self.split_nr:
181 | file_list.append(f"{self.data_path}/{wsi_name}.dat")
182 | file_list.sort() # to always ensure same input ordering
183 |
184 | print('Number of WSI graphs:', len(file_list))
185 | print('-'*50)
186 |
187 | pred, prob, true, wsi_names = self.__run_model(file_list)
188 |
189 | # save results to a single csv file
190 | df = pd.DataFrame(data = {'wsi_name': wsi_names, 'score': prob, "pred": pred, 'label': true})
191 | df.to_csv(f"{self.output_path}/results.csv")
192 |
193 | # get stats
194 | true, prob = get_labels_scores(wsi_names, prob, data_info)
195 | self.__get_stats(prob, true)
196 |
197 |
198 | #-------------------------------------------------------------------------------------------------------
199 |
200 | if __name__ == '__main__':
201 | args = docopt(__doc__, version='IGUANA Inference v1.0')
202 | print(args)
203 |
204 | os.environ['CUDA_VISIBLE_DEVICES'] = args['--gpu']
205 |
206 | # get the subset of features to be input to the GNN
207 | with open("features.yml") as fptr:
208 | feat_names = list(yaml.full_load(fptr).values())[0]
209 |
210 | # load node degree
211 | stats_path = args["--stats_dir"]
212 | if args["--model_name"] == "pna":
213 | node_degree = np.load(f"{stats_path}/node_deg.npy")
214 | else:
215 | node_degree = None
216 |
217 | if not os.path.exists(args["--output_dir"]):
218 | rm_n_mkdir(args["--output_dir"])
219 |
220 | #TODO Batch size must be set at 1 at the moment - fix this!
221 | args = {
222 | "model_name": args["--model_name"],
223 | "model_path": args["--model_path"],
224 | "stats_path": stats_path,
225 | "node_degree": node_degree,
226 | "data_path": args["--data_dir"],
227 | "data_info": args["--data_info"],
228 | "feat_names": feat_names,
229 | "batch_size": int(args["--batch_size"]),
230 | "nr_procs": int(args["--num_workers"]),
231 | "output_path": args["--output_dir"],
232 | "fold_nr": int(args["--fold_nr"]),
233 | "split_nr": int(args["--split_nr"]),
234 | }
235 |
236 | infer = Infer(**args)
237 | infer.process_files()
238 |
239 |
--------------------------------------------------------------------------------
/run_infer.sh:
--------------------------------------------------------------------------------
1 | python run_infer.py \
2 | --gpu=0 \
3 | --model_path="/root/lsf_workspace/iguana_data/weights/iguana_fold1.tar" \
4 | --model_name="pna" \
5 | --data_dir="/root/lsf_workspace/proc_slides/cobi/colchester/graphs/data" \
6 | --data_info="/root/lsf_workspace/proc_slides/cobi/colchester/graphs/colchester_info.csv" \
7 | --stats_dir="/root/lsf_workspace/proc_slides/cobi/uhcw/graphs/stats" \
8 | --output_dir="output_test/" \
--------------------------------------------------------------------------------
/run_utils/callbacks/base.py:
--------------------------------------------------------------------------------
1 |
2 | import cv2
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 | import torch
6 | from scipy.stats import mode as major_value
7 | from sklearn.metrics import confusion_matrix
8 |
9 |
10 | ####
11 | class BaseCallbacks(object):
12 | def __init__(self):
13 | self.engine_trigger = False
14 |
15 | def reset(self):
16 | pass
17 |
18 | def run(self, state, event):
19 | pass
20 |
21 | ####
22 | class TrackLr(BaseCallbacks):
23 | """
24 | Add learning rate to tracking
25 | """
26 | def __init__(self, per_n_epoch=1, per_n_step=None):
27 | super().__init__()
28 | self.per_n_epoch = per_n_epoch
29 | self.per_n_step = per_n_step
30 |
31 | def run(self, state, event):
32 | # logging learning rate, decouple into another callback?
33 | run_info = state.run_info
34 | for net_name, net_info in run_info.items():
35 | lr = net_info['optimizer'].param_groups[0]['lr']
36 | state.tracked_step_output['scalar']['lr-%s' % net_name] = lr
37 | return
38 |
39 | ####
40 | class ScheduleLr(BaseCallbacks):
41 | """
42 | Trigger all scheduler
43 | """
44 | def __init__(self):
45 | super().__init__()
46 |
47 | def run(self, state, event):
48 | # logging learning rate, decouple into another callback?
49 | run_info = state.run_info
50 | for net_name, net_info in run_info.items():
51 | net_info['lr_scheduler'].step()
52 | return
53 |
54 | ####
55 | class TriggerEngine(BaseCallbacks):
56 | def __init__(self, triggered_engine_name, nr_epoch=1):
57 | self.engine_trigger = True
58 | self.triggered_engine_name = triggered_engine_name
59 | self.triggered_engine = None
60 | self.nr_epoch = nr_epoch
61 |
62 | def run(self, state, event):
63 | self.triggered_engine.run(chained=True,
64 | nr_epoch=self.nr_epoch,
65 | shared_state=state)
66 | return
67 | ####
68 | class CheckpointSaver(BaseCallbacks):
69 | """
70 | Must declare save dir first in the shared global state of the
71 | attached engine
72 | """
73 | def run(self, state, event):
74 | if not state.logging:
75 | return
76 | for net_name, net_info in state.run_info.items():
77 | net_checkpoint = {}
78 | for key, value in net_info.items():
79 | if key != 'extra_info':
80 | net_checkpoint[key] = value.state_dict()
81 | torch.save(net_checkpoint, '%s/%s_epoch=%d.tar' %
82 | (state.log_dir, net_name, state.curr_epoch))
83 | return
84 |
85 | ####
86 | class AccumulateRawOutput(BaseCallbacks):
87 | def run(self, state, event):
88 | step_output = state.step_output['raw']
89 | accumulated_output = state.epoch_accumulated_output
90 |
91 | for key, step_value in step_output.items():
92 | if key in accumulated_output:
93 | accumulated_output[key].extend(list(step_value))
94 | else:
95 | accumulated_output[key] = list(step_value)
96 | return
97 | ####
98 | class ScalarMovingAverage(BaseCallbacks):
99 | """
100 | Calculate the running average for all scalar output of
101 | each runstep of the attached RunEngine
102 | """
103 |
104 | def __init__(self, alpha=0.95):
105 | super().__init__()
106 | self.alpha = alpha
107 | self.tracking_dict = {}
108 |
109 | def run(self, state, event):
110 | # TODO: protocol for dynamic key retrieval for EMA
111 | step_output = state.step_output['EMA']
112 |
113 | for key, current_value in step_output.items():
114 | if key in self.tracking_dict:
115 | old_ema_value = self.tracking_dict[key]
116 | # calculate the exponential moving average
117 | new_ema_value = old_ema_value * self.alpha + (1.0 - self.alpha) * current_value
118 | self.tracking_dict[key] = new_ema_value
119 | else: # init for variable which appear for the first time
120 | new_ema_value = current_value
121 | self.tracking_dict[key] = new_ema_value
122 |
123 | state.tracked_step_output['scalar'] = self.tracking_dict
124 | return
125 |
126 | ####
127 | class ProcessAccumulatedRawOutput(BaseCallbacks):
128 | def __init__(self, proc_func, per_n_epoch=1):
129 | # TODO: allow dynamically attach specific procesing for `type`
130 | super().__init__()
131 | self.per_n_epoch = per_n_epoch
132 | self.proc_func = proc_func
133 |
134 | def run(self, state, event):
135 | current_epoch = state.curr_epoch
136 | # if current_epoch % self.per_n_epoch != 0: return
137 | raw_data = state.epoch_accumulated_output
138 | track_dict = self.proc_func(raw_data)
139 | # update global shared states
140 | state.tracked_step_output = track_dict
141 | return
142 |
143 | ####
144 | class VisualizeOutput(BaseCallbacks):
145 | def __init__(self, proc_func, per_n_epoch=1):
146 | super().__init__()
147 | # TODO: option to dump viz per epoch or per n step
148 | self.per_n_epoch = per_n_epoch
149 | self.proc_func = proc_func
150 |
151 | def run(self, state, event):
152 | current_epoch = state.curr_epoch
153 | raw_output = state.step_output['raw']
154 | viz_image = self.proc_func(raw_output)
155 | state.tracked_step_output['image']['output'] = viz_image
156 | return
157 |
--------------------------------------------------------------------------------
/run_utils/callbacks/logging.py:
--------------------------------------------------------------------------------
1 |
2 | import json
3 | import random
4 |
5 | import matplotlib.pyplot as plt
6 | import numpy as np
7 | from matplotlib.lines import Line2D
8 | from termcolor import colored
9 |
10 | from .base import BaseCallbacks
11 | from .serialize import fig2data, serialize
12 |
13 | # TODO: logging for all printed info on the terminal
14 |
15 |
16 | ####
17 | class LoggingGradient(BaseCallbacks):
18 | """
19 | Will log per each training step
20 | """
21 | def _pyplot_grad_flow(self, named_parameters):
22 | """
23 | Plots the gradients flowing through different layers in the net during training.
24 | "_pyplot_grad_flow(self.model.named_parameters())" to visualize the gradient flow
25 |
26 | ! Very slow if triggered per steps because of CPU <=> GPU
27 | """
28 | ave_grads = []
29 | max_grads = []
30 | layers = []
31 | for n, p in named_parameters:
32 | if(p.requires_grad) and ("bias" not in n):
33 | layers.append(n)
34 | ave_grads.append(p.grad.abs().mean().cpu().item())
35 | max_grads.append(p.grad.abs().max().cpu().item())
36 | fig = plt.figure(figsize=(10, 10))
37 | plt.bar(np.arange(len(max_grads)), max_grads,
38 | alpha=0.1, lw=1, color="c")
39 | plt.bar(np.arange(len(max_grads)), ave_grads,
40 | alpha=0.1, lw=1, color="b")
41 | plt.hlines(0, 0, len(ave_grads)+1, lw=2, color="k")
42 | plt.xticks(range(0, len(ave_grads), 1), layers, rotation="vertical")
43 | plt.xlim(left=0, right=len(ave_grads))
44 | # zoom in on the lower gradient regions
45 | plt.xlabel("Layers")
46 | plt.ylabel("average gradient")
47 | plt.title("Gradient flow")
48 | plt.grid(True)
49 | plt.legend([Line2D([0], [0], color="c", lw=4),
50 | Line2D([0], [0], color="b", lw=4),
51 | Line2D([0], [0], color="k", lw=4)],
52 | ['max-gradient', 'mean-gradient', 'zero-gradient'])
53 | fig = np.transpose(fig2data(fig), axes=[2, 0, 1]) # HWC => CHW
54 | plt.close()
55 | return fig
56 |
57 | def run(self, state, event):
58 |
59 | if random.random() > 0.05: return
60 | curr_step = state.curr_global_step
61 |
62 | # logging the grad of all trainable parameters
63 | tfwriter = state.log_info['tfwriter']
64 | run_info = state.run_info
65 | for net_name, net_info in run_info.items():
66 | netdesc = net_info['desc'].module
67 | for param_name, param in netdesc.named_parameters():
68 | param_grad = param.grad
69 | # TODO: sync test None or epislon for pytorch 1.4 vs 1.5
70 | if param_grad is None: continue
71 | tfwriter.add_histogram(
72 | "%s_grad/%s" % (net_name, param_name),
73 | param_grad.detach().cpu().numpy().flatten(),
74 | global_step=curr_step) # ditribute into 10 bins (np default)
75 | tfwriter.add_histogram(
76 | "%s_para/%s" % (net_name, param_name),
77 | param.detach().cpu().numpy().flatten(),
78 | global_step=curr_step) # ditribute into 10 bins (np default)
79 | return
80 |
81 |
82 | ####
83 | class LoggingEpochOutput(BaseCallbacks):
84 | """
85 | Must declare save dir first in the shared global state of the
86 | attached engine
87 | """
88 | def __init__(self, per_n_epoch=1):
89 | super().__init__()
90 | self.per_n_epoch = per_n_epoch
91 |
92 | def run(self, state, event):
93 |
94 | # only logging every n epochs also
95 | if state.curr_epoch % self.per_n_epoch != 0:
96 | return
97 |
98 | # TODO: rename to differentiate global vs local epoch
99 | if state.global_state is not None:
100 | current_epoch = str(state.global_state.curr_epoch)
101 | else:
102 | current_epoch = str(state.curr_epoch)
103 |
104 | output = state.tracked_step_output
105 |
106 | def get_serializable_values(output_format):
107 | log_dict = {}
108 | # get type and variable that is serializable
109 | # to console or other logging format (json, tensorboard)
110 | for variable_type, variable_dict in output.items():
111 | for value_name, value in variable_dict.items():
112 | value_name = '%s-%s' % (state.attached_engine_name,
113 | value_name)
114 | new_format = serialize(value, variable_type, output_format)
115 | if new_format is not None:
116 | log_dict[value_name] = new_format
117 | return log_dict
118 |
119 | # * Serialize to Console
120 | # align the console print output
121 | formatted_values = get_serializable_values('console')
122 | max_length = len(max(formatted_values.keys(), key=len))
123 | for value_name, value_text in formatted_values.items():
124 | value_name = colored(value_name.ljust(max_length), 'green')
125 | print('------%s : %s' % (value_name, value_text))
126 |
127 | # TODO: [CRITICAL] fix passing this between engine
128 | # if not state.logging: return
129 |
130 | # * Serialize to JSON file
131 | stat_dict = get_serializable_values('json')
132 | # json stat log file, update and overwrite
133 | with open(state.log_info['json_file']) as json_file:
134 | json_data = json.load(json_file)
135 |
136 | if current_epoch in json_data:
137 | old_stat_dict = json_data[current_epoch]
138 | stat_dict.update(old_stat_dict)
139 | current_epoch_dict = {current_epoch: stat_dict}
140 | json_data.update(current_epoch_dict)
141 |
142 | # TODO: may corrupt
143 | with open(state.log_info['json_file'], 'w') as json_file:
144 | json.dump(json_data, json_file)
145 |
146 | # * Serialize to Tensorboard
147 | tfwriter = state.log_info['tfwriter']
148 | formatted_values = get_serializable_values('tensorboard')
149 | # ! may need to flush to force update
150 | for value_name, value in formatted_values.items():
151 | # TODO: dynamically call this
152 | if value[0] == 'scalar':
153 | tfwriter.add_scalar(value_name, value[1], current_epoch)
154 | elif value[0] == 'image':
155 | tfwriter.add_image(value_name, value[1], current_epoch,
156 | dataformats='HWC')
157 | # tfwriter.flush()
158 |
159 | return
160 |
--------------------------------------------------------------------------------
/run_utils/callbacks/serialize.py:
--------------------------------------------------------------------------------
1 |
2 | import cv2
3 | import matplotlib
4 | import numpy as np
5 | from matplotlib import pyplot as plt
6 |
7 | # * syn where to set this
8 | # must use 'Agg' to plot out onto image
9 | matplotlib.use('Agg')
10 |
11 | ####
12 | def fig2data(fig, dpi=180):
13 | """
14 | Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
15 | Args:
16 | fig: a matplotlib figure
17 |
18 | Return: a numpy 3D array of RGBA values
19 | """
20 | buf = io.BytesIO()
21 | fig.savefig(buf, format="png", dpi=dpi)
22 | buf.seek(0)
23 | img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
24 | buf.close()
25 | img = cv2.imdecode(img_arr, 1)
26 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
27 | return img
28 | ####
29 |
30 |
31 | ####
32 | class _Scalar(object):
33 | @staticmethod
34 | def to_console(value):
35 | return '%0.5f' % value
36 |
37 | @staticmethod
38 | def to_json(value):
39 | return value
40 |
41 | @staticmethod
42 | def to_tensorboard(value):
43 | return 'scalar', value
44 |
45 | ####
46 | class _ConfusionMatrix(object):
47 | @staticmethod
48 | def to_console(value):
49 | value = pd.DataFrame(value)
50 | value.index.name = 'True'
51 | value.columns.name = 'Pred'
52 | formatted_value = value.to_string()
53 | return '\n' + formatted_value
54 |
55 | @staticmethod
56 | def to_json(value):
57 | value = pd.DataFrame(value)
58 | value.index.name = 'True'
59 | value.columns.name = 'Pred'
60 | value = value.unstack().rename('value').reset_index()
61 | value = pd.Series({'conf_mat': value})
62 | formatted_value = value.to_json(orient='records')
63 | return formatted_value
64 |
65 | @staticmethod
66 | def to_tensorboard(value):
67 | def plot_confusion_matrix(cm,
68 | target_names,
69 | title='Confusion matrix',
70 | cmap=None,
71 | normalize=False):
72 | """
73 | given a sklearn confusion matrix (cm), make a nice plot
74 |
75 | Arguments
76 | ---------
77 | cm: confusion matrix from sklearn.metrics.confusion_matrix
78 |
79 | target_names: given classification classes such as [0, 1, 2]
80 | the class names, for example: ['high', 'medium', 'low']
81 |
82 | title: the text to display at the top of the matrix
83 |
84 | cmap: the gradient of the values displayed from matplotlib.pyplot.cm
85 | see http://matplotlib.org/examples/color/colormaps_reference.html
86 | plt.get_cmap('jet') or plt.cm.Blues
87 |
88 | normalize: If False, plot the raw numbers
89 | If True, plot the proportions
90 |
91 | Usage
92 | -----
93 | plot_confusion_matrix(cm = cm, # confusion matrix created by
94 | # sklearn.metrics.confusion_matrix
95 | normalize = True, # show proportions
96 | target_names = y_labels_vals, # list of names of the classes
97 | title = best_estimator_name) # title of graph
98 |
99 | Citiation
100 | ---------
101 | http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
102 |
103 | """
104 | import matplotlib.pyplot as plt
105 | import numpy as np
106 | import itertools
107 |
108 | accuracy = np.trace(cm) / np.sum(cm).astype('float')
109 | misclass = 1 - accuracy
110 |
111 | if cmap is None:
112 | cmap = plt.get_cmap('Blues')
113 |
114 | plt.figure(figsize=(8, 6))
115 | plt.imshow(cm, interpolation='nearest', cmap=cmap)
116 | plt.title(title)
117 | plt.colorbar()
118 |
119 | if target_names is not None:
120 | tick_marks = np.arange(len(target_names))
121 | plt.xticks(tick_marks, target_names, rotation=45)
122 | plt.yticks(tick_marks, target_names)
123 |
124 | if normalize:
125 | cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
126 |
127 |
128 | thresh = cm.max() / 1.5 if normalize else cm.max() / 2
129 | for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
130 | if normalize:
131 | plt.text(j, i, "{:0.4f}".format(cm[i, j]),
132 | horizontalalignment="center",
133 | color="white" if cm[i, j] > thresh else "black")
134 | else:
135 | plt.text(j, i, "{:,}".format(cm[i, j]),
136 | horizontalalignment="center",
137 | color="white" if cm[i, j] > thresh else "black")
138 |
139 |
140 | plt.tight_layout()
141 | plt.ylabel('True label')
142 | plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
143 |
144 | plot_confusion_matrix(value, ['0', '1'])
145 | img = fig2data(plt.gcf())
146 | plt.close()
147 | return 'image', img
148 |
149 | ####
150 | class _Image(object):
151 | @staticmethod
152 | def to_console(value):
153 | # TODO: add warn for not possible or sthg here
154 | return None
155 |
156 | @staticmethod
157 | def to_json(value):
158 | # TODO: add warn for not possible or sthg here
159 | return None
160 |
161 | @staticmethod
162 | def to_tensorboard(value):
163 | # TODO: add method
164 | return 'image', value
165 |
166 |
167 | __converter_dict = {
168 | 'scalar': _Scalar,
169 | 'conf_mat': _ConfusionMatrix,
170 | 'image': _Image
171 | }
172 |
173 |
174 | ####
175 | def serialize(value, input_format, output_format):
176 | converter = __converter_dict[input_format]
177 | if output_format == 'console':
178 | return converter.to_console(value)
179 | elif output_format == 'json':
180 | return converter.to_json(value)
181 | elif output_format == 'tensorboard':
182 | return converter.to_tensorboard(value)
183 | else:
184 | assert False, 'Unknown format'
185 |
--------------------------------------------------------------------------------
/run_utils/engine.py:
--------------------------------------------------------------------------------
1 | import tqdm
2 | from enum import Enum
3 |
4 |
5 | ####
6 | class Events(Enum):
7 | EPOCH_STARTED = "epoch_started"
8 | EPOCH_COMPLETED = "epoch_completed"
9 | STEP_STARTED = "step_started"
10 | STEP_COMPLETED = "step_completed"
11 | STARTED = "started"
12 | COMPLETED = "completed"
13 | EXCEPTION_RAISED = "exception_raised"
14 |
15 |
16 | ####
17 | class State(object):
18 | """
19 | An object that is used to pass internal and
20 | user-defined state between event handlers
21 | """
22 |
23 | def __init__(self):
24 | # settings propagated from config
25 | self.logging = None
26 | self.log_dir = None
27 | self.log_info = None
28 |
29 | # internal variable
30 | self.curr_epoch_step = 0 # current step in epoch
31 | self.curr_global_step = 0 # current global step
32 | self.curr_epoch = 0 # current global epoch
33 |
34 | # TODO: [LOW] better document this
35 | # for outputing value that will be tracked per step
36 | # "scalar" will always be printed out and added to the tensorboard
37 | # "images" will need dedicated function to process and added to the tensorboard
38 |
39 | # ! naming should match with types supported for serialize
40 | # TODO: Need way to dynamically adding new types
41 | self.tracked_step_output = {
42 | "scalar": {}, # type : {variable_name : variablee_value}
43 | "image": {},
44 | }
45 | # TODO: find way to known which method bind/interact with which value
46 |
47 | self.epoch_accumulated_output = {} # all output of the current epoch
48 |
49 | # TODO: soft reset for pertain variable for N epochs
50 | self.run_accumulated_output = [] # of run until reseted
51 |
52 | # holder for output returned after current runstep
53 | # * depend on the type of training i.e GAN, the updated accumulated may be different
54 | self.step_output = None
55 |
56 | self.global_state = None
57 | return
58 |
59 | def reset_variable(self):
60 | # type : {variable_name : variable_value}
61 | self.tracked_step_output = {k: {} for k in self.tracked_step_output.keys()}
62 |
63 | # TODO: [CRITICAL] refactor this
64 | if self.curr_epoch % self.pertain_n_epoch_output == 0:
65 | self.run_accumulated_output = []
66 |
67 | self.epoch_accumulated_output = {}
68 |
69 | # * depend on the type of training i.e GAN, the updated accumulated may be different
70 | self.step_output = None # holder for output returned after current runstep
71 | return
72 |
73 |
74 | ####
75 | class RunEngine(object):
76 | """
77 | TODO: Include docstring
78 | """
79 |
80 | def __init__(
81 | self,
82 | engine_name=None,
83 | dataloader=None,
84 | run_step=None,
85 | run_info=None,
86 | log_info=None, # TODO: refactor this with trainer.py
87 | ):
88 |
89 | # * auto set all input as object variables
90 | self.engine_name = engine_name
91 | self.run_step = run_step
92 | self.dataloader = dataloader
93 |
94 | # * global variable/object holder shared between all event handler
95 | self.state = State()
96 | # * check if correctly referenced, not new copies
97 | self.state.attached_engine_name = engine_name # TODO: redundant?
98 | self.state.run_info = run_info
99 | self.state.log_info = log_info
100 | self.state.batch_size = dataloader.batch_size
101 |
102 | # TODO: [CRITICAL] match all the mechanism outline with opt
103 | self.state.pertain_n_epoch_output = 1 if engine_name == "valid" else 1
104 |
105 | self.event_handler_dict = {event: [] for event in Events}
106 |
107 | # TODO: think about this more
108 | # to share global state across a chain of RunEngine such as
109 | # from the engine for training to engine for validation
110 |
111 | #
112 | self.terminate = False
113 | return
114 |
115 | def __reset_state(self):
116 | # TODO: think about this more, looks too redundant
117 | new_state = State()
118 | new_state.attached_engine_name = self.state.attached_engine_name
119 | new_state.run_info = self.state.run_info
120 | new_state.log_info = self.state.log_info
121 | self.state = new_state
122 | return
123 |
124 | def __trigger_events(self, event):
125 | for callback in self.event_handler_dict[event]:
126 | callback.run(self.state, event)
127 | # TODO: exception and throwing error with name or sthg to allow trace back
128 | return
129 |
130 | # TODO: variable to indicate output dependency between handler !
131 | def add_event_handler(self, event_name, handler):
132 | self.event_handler_dict[event_name].append(handler)
133 |
134 | # ! Put into trainer.py ?
135 | def run(self, nr_epoch=1, shared_state=None, chained=False):
136 |
137 | # TODO: refactor this
138 | if chained:
139 | self.state.curr_epoch = 0
140 | self.state.global_state = shared_state
141 |
142 | while self.state.curr_epoch < nr_epoch:
143 | self.state.reset_variable() # * reset all EMA holder per epoch
144 |
145 | if not chained:
146 | print("----------------EPOCH %d" % (self.state.curr_epoch + 1))
147 |
148 | self.__trigger_events(Events.EPOCH_STARTED)
149 |
150 | pbar_format = (
151 | "Processing: |{bar}| "
152 | "{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_fmt}]"
153 | )
154 | if self.engine_name == "train":
155 | pbar_format += (
156 | "Batch = {postfix[1][Batch]:0.5f}|" "EMA = {postfix[1][EMA]:0.5f}"
157 | )
158 | # * changing print char may break the bar so avoid it
159 | pbar = tqdm.tqdm(
160 | total=len(self.dataloader),
161 | leave=True,
162 | initial=0,
163 | bar_format=pbar_format,
164 | ascii=True,
165 | postfix=["", dict(Batch=float("NaN"), EMA=float("NaN"))],
166 | )
167 | else:
168 | pbar = tqdm.tqdm(
169 | total=len(self.dataloader),
170 | leave=True,
171 | bar_format=pbar_format,
172 | ascii=True,
173 | )
174 |
175 | for data_batch in self.dataloader:
176 | data = data_batch
177 |
178 | self.__trigger_events(Events.STEP_STARTED)
179 |
180 | step_run_info = [
181 | self.state.run_info,
182 | {
183 | "epoch": self.state.curr_epoch,
184 | "step": self.state.curr_global_step,
185 | },
186 | ]
187 | step_output = self.run_step(data_batch, step_run_info)
188 | self.state.step_output = step_output
189 |
190 | self.__trigger_events(Events.STEP_COMPLETED)
191 | self.state.curr_global_step += 1
192 | self.state.curr_epoch_step += 1
193 |
194 | if self.engine_name == "train":
195 | pbar.postfix[1]["Batch"] = step_output["EMA"]["overall_loss"]
196 | pbar.postfix[1]["EMA"] = self.state.tracked_step_output["scalar"][
197 | "overall_loss"
198 | ]
199 | pbar.update()
200 | pbar.close() # to flush out the bar before doing end of epoch reporting
201 | self.state.curr_epoch += 1
202 | self.__trigger_events(Events.EPOCH_COMPLETED)
203 |
204 | # TODO: [CRITICAL] align the protocol
205 | self.state.run_accumulated_output.append(
206 | self.state.epoch_accumulated_output
207 | )
208 |
209 | return
210 |
211 |
--------------------------------------------------------------------------------
/run_utils/utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import random
3 | import shutil
4 | from collections import OrderedDict
5 |
6 | import numpy as np
7 | import torch
8 | import torch.nn as nn
9 | from imgaug import imgaug as ia
10 | from termcolor import colored
11 | from torch.autograd import Variable
12 |
13 |
14 | ####
15 | def check_manual_seed(seed):
16 | """
17 | If manual seed is not specified, choose a
18 | random one and communicate it to the user.
19 |
20 | Args:
21 | seed: seed to check
22 | """
23 |
24 | seed = seed or random.randint(1, 10000)
25 | random.seed(seed)
26 | np.random.seed(seed)
27 | torch.manual_seed(seed)
28 | torch.cuda.manual_seed(seed)
29 | # ia.random.seed(seed)
30 |
31 | print('Using manual seed: {seed}'.format(seed=seed))
32 | return
33 |
34 |
35 | ####
36 | def check_log_dir(log_dir):
37 | """
38 | Check if log directory exists
39 |
40 | Args:
41 | log_dir: path to logs
42 | """
43 |
44 | if os.path.isdir(log_dir):
45 | colored_word = colored('WARNING', color='red', attrs=['bold', 'blink'])
46 | print('%s: %s exist!' %
47 | (colored_word, colored(log_dir, attrs=['underline'])))
48 | while (True):
49 | print('Select Action: d (delete) / q (quit)', end='')
50 | key = input()
51 | if key == 'd':
52 | shutil.rmtree(log_dir)
53 | break
54 | elif key == 'q':
55 | exit()
56 | else:
57 | color_word = colored('ERR', color='red')
58 | print('---[%s] Unrecognize Characters!' % colored_word)
59 | return
60 |
61 | def get_model_summary(model, input_size, batch_size=-1, device=torch.device('cpu'), dtypes=None):
62 | """
63 | Reusable utility layers such as pool or upsample will also get printed, but their printed values will
64 | be corresponding to the last call
65 | """
66 |
67 | if dtypes == None:
68 | dtypes = [torch.FloatTensor]*len(input_size)
69 |
70 | summary_str = ''
71 |
72 | def register_hook(module):
73 | def hook(module, input, output):
74 | class_name = str(module.__class__).split(".")[-1].split("'")[0]
75 | module_idx = len(summary)
76 |
77 | m_key = module.name if module.name != '' else "%s" % class_name
78 |
79 | summary[m_key] = OrderedDict()
80 | summary[m_key]["input_shape"] = list(input[0].size())
81 | summary[m_key]["input_shape"][0] = batch_size
82 | if isinstance(output, (list, tuple)):
83 | summary[m_key]["output_shape"] = [
84 | [-1] + list(o.size())[1:] for o in output
85 | ]
86 | elif isinstance(output, dict):
87 | summary[m_key]["output_shape"] = [
88 | [-1] + list(o.size())[1:] for o in output.values()
89 | ]
90 | elif isinstance(output, torch.Tensor):
91 | summary[m_key]["output_shape"] = list(output.size())
92 | summary[m_key]["output_shape"][0] = batch_size
93 |
94 | params = 0
95 | if hasattr(module, "weight") and hasattr(module.weight, "size"):
96 | params += torch.prod(torch.LongTensor(list(module.weight.size())))
97 | summary[m_key]["trainable"] = module.weight.requires_grad
98 | if hasattr(module, "bias") and hasattr(module.bias, "size"):
99 | params += torch.prod(torch.LongTensor(list(module.bias.size())))
100 | summary[m_key]["nb_params"] = params
101 |
102 | if len(list(module.children())) == 0:
103 | hooks.append(module.register_forward_hook(hook))
104 |
105 | # multiple inputs to the network
106 | if isinstance(input_size, tuple):
107 | input_size = [input_size]
108 |
109 | # batch_size of 2 for batchnorm
110 | x = [torch.rand(2, *in_size).type(dtype).to(device=device)
111 | for in_size, dtype in zip(input_size, dtypes)]
112 |
113 | # create properties
114 | summary = OrderedDict()
115 | hooks = []
116 |
117 | # create layer name according to hierachy names
118 | for name, module in model.named_modules():
119 | module.name = name
120 |
121 | # register hook
122 | model.apply(register_hook)
123 |
124 | # make a forward pass
125 | model(*x)
126 |
127 | # aligning name to the left
128 | max_name_length = len(max(summary.keys(), key=len))
129 | summary = [(k.ljust(max_name_length), v) for k, v in summary.items()]
130 | summary = OrderedDict(summary)
131 |
132 | # remove these hooks
133 | for h in hooks:
134 | h.remove()
135 |
136 | header_line = "{} {:>25} {:>15}".format("Layer Name".center(max_name_length), "Output Shape", "Param #")
137 | summary_str += "".join('-' for _ in range(len(header_line))) + "\n"
138 | summary_str += header_line + "\n"
139 | summary_str += "".join('=' for _ in range(len(header_line))) + "\n"
140 | total_params = 0
141 | total_output = 0
142 | trainable_params = 0
143 | for layer in summary:
144 | # input_shape, output_shape, trainable, nb_params
145 | line_new = "{:>20} {:>25} {:>15}".format(
146 | layer,
147 | str(summary[layer]["output_shape"]),
148 | "{0:,}".format(summary[layer]["nb_params"]),
149 | )
150 | total_params += summary[layer]["nb_params"]
151 |
152 | total_output += np.prod(summary[layer]["output_shape"])
153 | if "trainable" in summary[layer]:
154 | if summary[layer]["trainable"] == True:
155 | trainable_params += summary[layer]["nb_params"]
156 | summary_str += line_new + "\n"
157 |
158 | # assume 4 bytes/number (float on cuda).
159 | total_input_size = abs(np.prod(sum(input_size, ())) * batch_size * 4. / (1024 ** 2.))
160 | total_output_size = abs(2. * total_output * 4. / (1024 ** 2.)) # x2 for gradients
161 | total_params_size = abs(total_params * 4. / (1024 ** 2.))
162 | total_size = total_params_size + total_output_size + total_input_size
163 |
164 | summary_str += "".join('=' for _ in range(len(header_line))) + "\n"
165 | summary_str += "Total params: {0:,}".format(total_params) + "\n"
166 | summary_str += "Trainable params: {0:,}".format(trainable_params) + "\n"
167 | summary_str += "Non-trainable params: {0:,}".format(total_params -
168 | trainable_params) + "\n"
169 | summary_str += "".join('-' for _ in range(len(header_line))) + "\n"
170 | summary_str += "Input size (MB): %0.2f" % total_input_size + "\n"
171 | summary_str += "Forward/backward pass size (MB): %0.2f" % total_output_size + "\n"
172 | summary_str += "Params size (MB): %0.2f" % total_params_size + "\n"
173 | summary_str += "Estimated Total Size (MB): %0.2f" % total_size + "\n"
174 | summary_str += "".join('-' for _ in range(len(header_line))) + "\n"
175 | return summary_str
176 |
--------------------------------------------------------------------------------