├── .gitignore
├── LICENSE
├── README.md
├── config.py
├── experiments
├── spatial_transfer.ipynb
└── training.ipynb
├── models
└── dcm.py
├── preprocessing
├── preprocess_ARD.ipynb
└── preprocess_CDL.ipynb
├── requirements.txt
└── utils
├── date.py
├── helper.py
├── io_func.py
├── logger.py
└── timer.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
98 | __pypackages__/
99 |
100 | # Celery stuff
101 | celerybeat-schedule
102 | celerybeat.pid
103 |
104 | # SageMath parsed files
105 | *.sage.py
106 |
107 | # Environments
108 | .env
109 | .venv
110 | env/
111 | venv/
112 | ENV/
113 | env.bak/
114 | venv.bak/
115 |
116 | # Spyder project settings
117 | .spyderproject
118 | .spyproject
119 |
120 | # Rope project settings
121 | .ropeproject
122 |
123 | # mkdocs documentation
124 | /site
125 |
126 | # mypy
127 | .mypy_cache/
128 | .dmypy.json
129 | dmypy.json
130 |
131 | # Pyre type checker
132 | .pyre/
133 |
134 | # pytype static type analyzer
135 | .pytype/
136 |
137 | # Cython debug symbols
138 | cython_debug/
--------------------------------------------------------------------------------
/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 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DeepCropMapping: A multi-temporal deep learning approach with improved spatial generalizability for dynamic corn and soybean mapping
2 |
3 | This repository is the official implementation of DeepCropMapping: A multi-temporal deep learning approach with improved spatial generalizability for dynamic corn and soybean mapping.
4 |
5 | ## Requirements
6 |
7 | - torch
8 | - numpy
9 | - pandas
10 | - scikit-learn
11 | - jupyter
12 |
13 | The code has been tested in the following environment:
14 | Ubuntu 16.04.4 LTS, Python 3.5.2, PyTorch 1.2.0
15 |
16 | ## Data
17 |
18 | The preprocessed data (`.npy` files) for model training and evaluation is not directly provided here due to the large data volume. You can download raw Landsat Analysis Ready Data (ARD) from [EarthExplore](https://earthexplorer.usgs.gov/) and raw Cropland Data Layer (CDL) from [CropScape](https://nassgeodata.gmu.edu/CropScape/), then follow the code in the `preprocessing` folder to generate the `.npy` files. The raw Landsat ARD and CDL data should be stored in a new `data` folder that has the following structure (specific downloaded file names may change):
19 |
20 | ```
21 | data
22 | ├── Site_A
23 | │ ├── ARD
24 | │ │ ├── 2015
25 | │ │ │ ├── LC08_CU_018007_20150424_20181206_C01_V01_PIXELQA.tif
26 | │ │ │ ├── LC08_CU_018007_20150424_20181206_C01_V01_SRB2.tif
27 | │ │ │ └── . . .
28 | │ │ ├── . . .
29 | │ │ └── 2018
30 | │ └── CDL
31 | │ ├── CDL_2015_clip_20190409130240_375669680.tif
32 | │ ├── . . .
33 | │ └── CDL_2018_clip_20190409125506_12566268.tif
34 | ├── Site_B
35 | ├── . . .
36 | └── Site_F
37 | ```
38 |
39 | The preprocessed data should be stored in the `preprocessing/out` folder that has the following structure:
40 |
41 | ```
42 | preprocessing/out
43 | ├── Site_A
44 | │ ├── x-2015.npy
45 | │ ├── y-2015.npy
46 | │ ├── . . .
47 | │ ├── x-2018.npy
48 | │ └── y-2018.npy
49 | ├── Site_B
50 | ├── . . .
51 | └── Site_F
52 | ```
53 |
54 | ## Training and evaluation
55 |
56 | - The PyTorch implementation of DeepCropMapping (DCM) model is located in the `models` folder.
57 | - The `utils` folder contains some utilities that are used for data loading, normalization, training and evluation.
58 |
59 | The specific training and evaluation process can be executed by running the `.ipynb` files in the `experiments` folder.
60 |
61 | The hyperparameters for different sites in the paper are set as follows:
62 |
63 | | Hyperparameter | Site A | Site B | Site C | Site D | Site E | Site F |
64 | | --- | --- | --- | --- | --- | --- | --- |
65 | |Dimension of LSTM hidden features | 256 | 512 | 256 | 512 | 256 | 256 |
66 | | Number of LSTM layers | 2 | 2 | 2 | 2 | 2 | 3 |
67 |
--------------------------------------------------------------------------------
/config.py:
--------------------------------------------------------------------------------
1 | START_V_I = 1650 # start_vertical_index
2 | START_H_I = 1650 # start_horizontal_index
3 | SIDE_LEN = 1700 # side length
4 |
5 | INTRPL_START_DATE_STR = "0422" # interpolated_start_date
6 | INTRPL_END_DATE_STR = "0923" # interpolated_end_date
7 |
8 | SEED = 313 # random seed
9 |
--------------------------------------------------------------------------------
/experiments/spatial_transfer.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {
7 | "ExecuteTime": {
8 | "end_time": "2020-04-19T08:23:25.757521Z",
9 | "start_time": "2020-04-19T08:23:25.753117Z"
10 | }
11 | },
12 | "outputs": [],
13 | "source": [
14 | "import os\n",
15 | "import sys\n",
16 | "module_path = os.path.abspath(os.path.join(\"..\"))\n",
17 | "if module_path not in sys.path:\n",
18 | " sys.path.append(module_path)"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": null,
24 | "metadata": {
25 | "ExecuteTime": {
26 | "end_time": "2020-04-19T08:23:28.755303Z",
27 | "start_time": "2020-04-19T08:23:25.760710Z"
28 | }
29 | },
30 | "outputs": [],
31 | "source": [
32 | "import numpy as np\n",
33 | "import pandas as pd\n",
34 | "from sklearn.metrics import accuracy_score\n",
35 | "import torch\n",
36 | "import torch.nn as nn\n",
37 | "from utils.logger import PrettyLogger\n",
38 | "from utils.io_func import save_to_csv, load_from_pkl, load_from_pth\n",
39 | "from utils.helper import DCMHelper"
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": null,
45 | "metadata": {
46 | "ExecuteTime": {
47 | "end_time": "2020-04-19T08:23:28.763085Z",
48 | "start_time": "2020-04-19T08:23:28.758935Z"
49 | }
50 | },
51 | "outputs": [],
52 | "source": [
53 | "logger = PrettyLogger()\n",
54 | "helper = DCMHelper()"
55 | ]
56 | },
57 | {
58 | "cell_type": "code",
59 | "execution_count": null,
60 | "metadata": {
61 | "ExecuteTime": {
62 | "end_time": "2020-04-19T08:23:28.775382Z",
63 | "start_time": "2020-04-19T08:23:28.766284Z"
64 | }
65 | },
66 | "outputs": [],
67 | "source": [
68 | "BASE_SITES = [\"Site_A\"]\n",
69 | "TEST_SITE = \"Site_B\"\n",
70 | "TEST_YEARS = [str(year) for year in [2018]]\n",
71 | "DATA_DIR = \"../preprocessing/out/{}\".format(TEST_SITE)\n",
72 | "X_PATH_TEMPLATE = os.path.join(DATA_DIR, \"x-{year}.npy\")\n",
73 | "Y_PATH_TEMPLATE = os.path.join(DATA_DIR, \"y-{year}.npy\")\n",
74 | "SCALER_PATH = \"./out/training/{}/scaler.pkl\".format(\"_\".join(BASE_SITES))\n",
75 | "MODEL_PATH = \"./out/training/{}/atbilstm.pth\".format(\"_\".join(BASE_SITES))\n",
76 | "RESULT_DIR = \"./out/spatial_tran/{}/{}\".format(\"_\".join(BASE_SITES), TEST_SITE)\n",
77 | "DEVICE = torch.device(\"cuda:0\")"
78 | ]
79 | },
80 | {
81 | "cell_type": "markdown",
82 | "metadata": {},
83 | "source": [
84 | "# Input"
85 | ]
86 | },
87 | {
88 | "cell_type": "code",
89 | "execution_count": null,
90 | "metadata": {
91 | "ExecuteTime": {
92 | "end_time": "2020-04-19T08:23:30.864974Z",
93 | "start_time": "2020-04-19T08:23:28.778968Z"
94 | }
95 | },
96 | "outputs": [],
97 | "source": [
98 | "def get_paths(path_template, years):\n",
99 | " return [path_template.format(year=year) for year in years]\n",
100 | "\n",
101 | "\n",
102 | "x_test = helper.input_x(get_paths(X_PATH_TEMPLATE, TEST_YEARS))\n",
103 | "y_test = helper.input_y(get_paths(Y_PATH_TEMPLATE, TEST_YEARS))"
104 | ]
105 | },
106 | {
107 | "cell_type": "markdown",
108 | "metadata": {},
109 | "source": [
110 | "# Normalization"
111 | ]
112 | },
113 | {
114 | "cell_type": "code",
115 | "execution_count": null,
116 | "metadata": {
117 | "ExecuteTime": {
118 | "end_time": "2020-04-19T08:23:31.323735Z",
119 | "start_time": "2020-04-19T08:23:30.867103Z"
120 | }
121 | },
122 | "outputs": [],
123 | "source": [
124 | "scaler = load_from_pkl(SCALER_PATH)\n",
125 | "x_test = helper.normalize_with_scaler(scaler, x_test)"
126 | ]
127 | },
128 | {
129 | "cell_type": "markdown",
130 | "metadata": {},
131 | "source": [
132 | "# Prediction"
133 | ]
134 | },
135 | {
136 | "cell_type": "code",
137 | "execution_count": null,
138 | "metadata": {
139 | "ExecuteTime": {
140 | "end_time": "2020-04-19T08:23:55.970104Z",
141 | "start_time": "2020-04-19T08:23:31.326136Z"
142 | }
143 | },
144 | "outputs": [],
145 | "source": [
146 | "test_dataloader = helper.make_data_loader(x_test, y_test, shuffle=False)\n",
147 | "\n",
148 | "net = helper.build_model()\n",
149 | "net.load_state_dict(load_from_pth(MODEL_PATH))\n",
150 | "net = nn.DataParallel(net, device_ids=[0, 1, 2, 3])\n",
151 | "net.to(DEVICE)\n",
152 | "\n",
153 | "y_test_soft_pred, y_test_hard_pred, attn_test = helper.predict(\n",
154 | " net, test_dataloader, DEVICE\n",
155 | ")\n",
156 | "acc_test = accuracy_score(y_test, y_test_hard_pred)\n",
157 | "logger.info(TEST_SITE, \"test acc:\", acc_test)"
158 | ]
159 | },
160 | {
161 | "cell_type": "markdown",
162 | "metadata": {},
163 | "source": [
164 | "# Saving all"
165 | ]
166 | },
167 | {
168 | "cell_type": "code",
169 | "execution_count": null,
170 | "metadata": {
171 | "ExecuteTime": {
172 | "end_time": "2020-04-19T08:24:03.541550Z",
173 | "start_time": "2020-04-19T08:23:55.972732Z"
174 | }
175 | },
176 | "outputs": [],
177 | "source": [
178 | "save_to_csv(\n",
179 | " y_test_soft_pred, os.path.join(RESULT_DIR, \"y_test_soft_pred.csv\")\n",
180 | ")\n",
181 | "save_to_csv(\n",
182 | " y_test_hard_pred, os.path.join(RESULT_DIR, \"y_test_hard_pred.csv\")\n",
183 | ")\n",
184 | "save_to_csv(\n",
185 | " np.array([[acc_test]]),\n",
186 | " os.path.join(RESULT_DIR, \"perf_abstract.csv\"),\n",
187 | " header=[\"acc_test\"]\n",
188 | ")\n",
189 | "save_to_csv(\n",
190 | " helper.test_time_list,\n",
191 | " os.path.join(RESULT_DIR, \"test_time.csv\"),\n",
192 | " header=[\"test_start_time\", \"test_end_time\", \"duration\"]\n",
193 | ")"
194 | ]
195 | }
196 | ],
197 | "metadata": {
198 | "kernelspec": {
199 | "display_name": "Python 3",
200 | "language": "python",
201 | "name": "python3"
202 | },
203 | "language_info": {
204 | "codemirror_mode": {
205 | "name": "ipython",
206 | "version": 3
207 | },
208 | "file_extension": ".py",
209 | "mimetype": "text/x-python",
210 | "name": "python",
211 | "nbconvert_exporter": "python",
212 | "pygments_lexer": "ipython3",
213 | "version": "3.5.2"
214 | },
215 | "toc": {
216 | "base_numbering": 1,
217 | "nav_menu": {
218 | "height": "225px",
219 | "width": "262px"
220 | },
221 | "number_sections": true,
222 | "sideBar": true,
223 | "skip_h1_title": false,
224 | "title_cell": "Table of Contents",
225 | "title_sidebar": "Contents",
226 | "toc_cell": false,
227 | "toc_position": {
228 | "height": "calc(100% - 180px)",
229 | "left": "10px",
230 | "top": "150px",
231 | "width": "223px"
232 | },
233 | "toc_section_display": true,
234 | "toc_window_display": true
235 | }
236 | },
237 | "nbformat": 4,
238 | "nbformat_minor": 2
239 | }
240 |
--------------------------------------------------------------------------------
/experiments/training.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {
7 | "ExecuteTime": {
8 | "end_time": "2020-04-19T08:36:08.479621Z",
9 | "start_time": "2020-04-19T08:36:08.475766Z"
10 | }
11 | },
12 | "outputs": [],
13 | "source": [
14 | "import os\n",
15 | "import sys\n",
16 | "module_path = os.path.abspath(os.path.join(\"..\"))\n",
17 | "if module_path not in sys.path:\n",
18 | " sys.path.append(module_path)"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": null,
24 | "metadata": {
25 | "ExecuteTime": {
26 | "end_time": "2020-04-19T08:36:11.762000Z",
27 | "start_time": "2020-04-19T08:36:08.482310Z"
28 | }
29 | },
30 | "outputs": [],
31 | "source": [
32 | "import numpy as np\n",
33 | "import pandas as pd\n",
34 | "from sklearn.metrics import accuracy_score\n",
35 | "import torch\n",
36 | "import torch.nn as nn\n",
37 | "from utils.logger import PrettyLogger\n",
38 | "from utils.io_func import save_to_csv, save_to_pkl, save_to_pth\n",
39 | "from utils.helper import DCMHelper\n",
40 | "from config import SEED"
41 | ]
42 | },
43 | {
44 | "cell_type": "code",
45 | "execution_count": null,
46 | "metadata": {
47 | "ExecuteTime": {
48 | "end_time": "2020-04-19T08:36:11.768990Z",
49 | "start_time": "2020-04-19T08:36:11.765512Z"
50 | }
51 | },
52 | "outputs": [],
53 | "source": [
54 | "logger = PrettyLogger()\n",
55 | "helper = DCMHelper()"
56 | ]
57 | },
58 | {
59 | "cell_type": "code",
60 | "execution_count": null,
61 | "metadata": {
62 | "ExecuteTime": {
63 | "end_time": "2020-04-19T08:36:11.777101Z",
64 | "start_time": "2020-04-19T08:36:11.771775Z"
65 | }
66 | },
67 | "outputs": [],
68 | "source": [
69 | "BASE_SITES = [\"Site_A\"]\n",
70 | "TRAIN_YEARS = [str(year) for year in [2015, 2016, 2017]]\n",
71 | "TEST_YEARS = [str(year) for year in [2018]]\n",
72 | "DATA_DIR_TEMPLATE = \"../preprocessing/out/{site}/\"\n",
73 | "X_PATH_TEMPLATE = os.path.join(DATA_DIR_TEMPLATE, \"x-{year}.npy\")\n",
74 | "Y_PATH_TEMPLATE = os.path.join(DATA_DIR_TEMPLATE, \"y-{year}.npy\")\n",
75 | "RESULT_DIR = \"./out/DCM-20200101/{}/\".format(\"_\".join(BASE_SITES))\n",
76 | "DEVICE = torch.device(\"cuda:0\")"
77 | ]
78 | },
79 | {
80 | "cell_type": "markdown",
81 | "metadata": {},
82 | "source": [
83 | "# Input"
84 | ]
85 | },
86 | {
87 | "cell_type": "code",
88 | "execution_count": null,
89 | "metadata": {
90 | "ExecuteTime": {
91 | "end_time": "2020-04-19T08:36:32.601886Z",
92 | "start_time": "2020-04-19T08:36:11.780395Z"
93 | }
94 | },
95 | "outputs": [],
96 | "source": [
97 | "def get_paths(path_template, sites, years):\n",
98 | " paths = []\n",
99 | " for site in sites:\n",
100 | " for year in years:\n",
101 | " paths.append(path_template.format(site=site, year=year))\n",
102 | " return paths\n",
103 | "\n",
104 | "\n",
105 | "x_train = helper.input_x(get_paths(X_PATH_TEMPLATE, BASE_SITES, TRAIN_YEARS))\n",
106 | "y_train = helper.input_y(get_paths(Y_PATH_TEMPLATE, BASE_SITES, TRAIN_YEARS))\n",
107 | "x_test = helper.input_x(get_paths(X_PATH_TEMPLATE, BASE_SITES, TEST_YEARS))\n",
108 | "y_test = helper.input_y(get_paths(Y_PATH_TEMPLATE, BASE_SITES, TEST_YEARS))"
109 | ]
110 | },
111 | {
112 | "cell_type": "markdown",
113 | "metadata": {},
114 | "source": [
115 | "# Normalization"
116 | ]
117 | },
118 | {
119 | "cell_type": "code",
120 | "execution_count": null,
121 | "metadata": {
122 | "ExecuteTime": {
123 | "end_time": "2020-04-19T08:36:40.013263Z",
124 | "start_time": "2020-04-19T08:36:32.604725Z"
125 | }
126 | },
127 | "outputs": [],
128 | "source": [
129 | "scaler, x_train, x_test = helper.normalize_without_scaler(x_train, x_test)"
130 | ]
131 | },
132 | {
133 | "cell_type": "markdown",
134 | "metadata": {},
135 | "source": [
136 | "# Training models"
137 | ]
138 | },
139 | {
140 | "cell_type": "code",
141 | "execution_count": null,
142 | "metadata": {
143 | "ExecuteTime": {
144 | "end_time": "2020-04-19T08:36:40.014295Z",
145 | "start_time": "2020-04-19T08:36:44.267Z"
146 | },
147 | "scrolled": true
148 | },
149 | "outputs": [],
150 | "source": [
151 | "train_dataloader = helper.make_data_loader(x_train, y_train, shuffle=True)\n",
152 | "test_dataloader = helper.make_data_loader(x_test, y_test, shuffle=False)\n",
153 | "\n",
154 | "net = helper.build_model()\n",
155 | "helper.init_parameters(net)\n",
156 | "net = nn.DataParallel(net, device_ids=[0, 1, 2, 3])\n",
157 | "net.to(DEVICE)\n",
158 | "\n",
159 | "loss_train_list, acc_train_list, attn_train_list = [], [], []\n",
160 | "loss_test_list, acc_test_list, attn_test_list = [], [], []\n",
161 | "helper.train_model(\n",
162 | " net, train_dataloader, test_dataloader, DEVICE, logger,\n",
163 | " loss_train_list, acc_train_list, attn_train_list,\n",
164 | " loss_test_list, acc_test_list, attn_test_list,\n",
165 | ")"
166 | ]
167 | },
168 | {
169 | "cell_type": "markdown",
170 | "metadata": {},
171 | "source": [
172 | "# Prediction"
173 | ]
174 | },
175 | {
176 | "cell_type": "code",
177 | "execution_count": null,
178 | "metadata": {
179 | "ExecuteTime": {
180 | "end_time": "2020-04-19T08:36:40.015386Z",
181 | "start_time": "2020-04-19T08:36:44.269Z"
182 | }
183 | },
184 | "outputs": [],
185 | "source": [
186 | "y_train_soft_pred, y_train_hard_pred, attn_train = helper.predict(\n",
187 | " net, helper.make_data_loader(x_train, y_train, shuffle=False), DEVICE\n",
188 | ")\n",
189 | "y_test_soft_pred, y_test_hard_pred, attn_test = helper.predict(\n",
190 | " net, test_dataloader, DEVICE\n",
191 | ")\n",
192 | "acc_train = accuracy_score(y_train, y_train_hard_pred)\n",
193 | "acc_test = accuracy_score(y_test, y_test_hard_pred)\n",
194 | "logger.info(\"train acc:\", acc_train, \"test acc:\", acc_test)"
195 | ]
196 | },
197 | {
198 | "cell_type": "markdown",
199 | "metadata": {},
200 | "source": [
201 | "# Saving all"
202 | ]
203 | },
204 | {
205 | "cell_type": "code",
206 | "execution_count": null,
207 | "metadata": {
208 | "ExecuteTime": {
209 | "end_time": "2020-04-19T08:36:40.016294Z",
210 | "start_time": "2020-04-19T08:36:44.273Z"
211 | }
212 | },
213 | "outputs": [],
214 | "source": [
215 | "save_to_csv(\n",
216 | " y_train_soft_pred, os.path.join(RESULT_DIR, \"y_train_soft_pred.csv\")\n",
217 | ")\n",
218 | "save_to_csv(\n",
219 | " y_test_soft_pred, os.path.join(RESULT_DIR, \"y_test_soft_pred.csv\")\n",
220 | ")\n",
221 | "save_to_csv(\n",
222 | " y_train_hard_pred, os.path.join(RESULT_DIR, \"y_train_hard_pred.csv\")\n",
223 | ")\n",
224 | "save_to_csv(\n",
225 | " y_test_hard_pred, os.path.join(RESULT_DIR, \"y_test_hard_pred.csv\")\n",
226 | ")\n",
227 | "save_to_csv(\n",
228 | " np.array([\n",
229 | " loss_train_list, loss_test_list, acc_train_list, acc_test_list\n",
230 | " ]).T,\n",
231 | " os.path.join(RESULT_DIR, \"training_record.csv\"),\n",
232 | " header=[\"training loss\", \"test loss\", \"training acc\", \"test acc\"]\n",
233 | ")\n",
234 | "save_to_csv(\n",
235 | " np.array([[acc_train, acc_test]]),\n",
236 | " os.path.join(RESULT_DIR, \"perf_abstract.csv\"),\n",
237 | " header=[\"acc_train\", \"acc_test\"]\n",
238 | ")\n",
239 | "save_to_pkl(scaler, os.path.join(RESULT_DIR, \"scaler.pkl\"))\n",
240 | "save_to_pth(net, os.path.join(RESULT_DIR, \"atbilstm.pth\"))\n",
241 | "save_to_csv(\n",
242 | " helper.train_time_list,\n",
243 | " os.path.join(RESULT_DIR, \"train_time.csv\"),\n",
244 | " header=[\"train_start_time\", \"train_end_time\", \"duration\"]\n",
245 | ")\n",
246 | "save_to_csv(\n",
247 | " helper.test_time_list,\n",
248 | " os.path.join(RESULT_DIR, \"test_time.csv\"),\n",
249 | " header=[\"test_start_time\", \"test_end_time\", \"duration\"]\n",
250 | ")"
251 | ]
252 | }
253 | ],
254 | "metadata": {
255 | "kernelspec": {
256 | "display_name": "Python 3",
257 | "language": "python",
258 | "name": "python3"
259 | },
260 | "language_info": {
261 | "codemirror_mode": {
262 | "name": "ipython",
263 | "version": 3
264 | },
265 | "file_extension": ".py",
266 | "mimetype": "text/x-python",
267 | "name": "python",
268 | "nbconvert_exporter": "python",
269 | "pygments_lexer": "ipython3",
270 | "version": "3.5.2"
271 | },
272 | "toc": {
273 | "base_numbering": "1",
274 | "nav_menu": {
275 | "height": "225px",
276 | "width": "262px"
277 | },
278 | "number_sections": true,
279 | "sideBar": true,
280 | "skip_h1_title": false,
281 | "title_cell": "Table of Contents",
282 | "title_sidebar": "Contents",
283 | "toc_cell": false,
284 | "toc_position": {
285 | "height": "calc(100% - 180px)",
286 | "left": "10px",
287 | "top": "150px",
288 | "width": "189px"
289 | },
290 | "toc_section_display": true,
291 | "toc_window_display": true
292 | }
293 | },
294 | "nbformat": 4,
295 | "nbformat_minor": 2
296 | }
297 |
--------------------------------------------------------------------------------
/models/dcm.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | import torch.nn as nn
4 | import torch.nn.functional as F
5 |
6 |
7 | class DCM(nn.Module):
8 | def __init__(
9 | self, seed, input_feature_size, hidden_size, num_layers,
10 | bidirectional, dropout, num_classes
11 | ):
12 | super().__init__()
13 | self._set_reproducible(seed)
14 |
15 | self.lstm = nn.LSTM(
16 | input_size=input_feature_size,
17 | hidden_size=hidden_size,
18 | num_layers=num_layers,
19 | bidirectional=bidirectional,
20 | batch_first=True,
21 | dropout=dropout,
22 | ) # i/o: (batch, seq_len, num_directions*input_/hidden_size)
23 | num_directions = 2 if bidirectional else 1
24 | self.attention = nn.Linear(
25 | in_features=num_directions * hidden_size,
26 | out_features=1,
27 | )
28 | self.fc = nn.Linear(
29 | in_features=num_directions * hidden_size,
30 | out_features=num_classes,
31 | )
32 |
33 | def _set_reproducible(self, seed, cudnn=False):
34 | np.random.seed(seed)
35 | torch.manual_seed(seed)
36 | if cudnn:
37 | torch.backends.cudnn.deterministic = True
38 | torch.backends.cudnn.benchmark = False
39 |
40 | def forward(self, x):
41 | self.lstm.flatten_parameters()
42 | # lstm_out: (batch, seq_len, num_directions*hidden_size)
43 | lstm_out, _ = self.lstm(x)
44 | # softmax along seq_len axis
45 | attn_weights = F.softmax(F.relu(self.attention(lstm_out)), dim=1)
46 | # attn (after permutation): (batch, 1, seq_len)
47 | fc_in = attn_weights.permute(0, 2, 1).bmm(lstm_out)
48 | fc_out = self.fc(fc_in)
49 | return fc_out.squeeze(), attn_weights.squeeze()
--------------------------------------------------------------------------------
/preprocessing/preprocess_ARD.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {
7 | "ExecuteTime": {
8 | "end_time": "2020-01-09T01:19:39.422963Z",
9 | "start_time": "2020-01-09T01:19:39.417422Z"
10 | }
11 | },
12 | "outputs": [],
13 | "source": [
14 | "import os\n",
15 | "import sys\n",
16 | "module_path = os.path.abspath(os.path.join(\"..\"))\n",
17 | "if module_path not in sys.path:\n",
18 | " sys.path.append(module_path)"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": null,
24 | "metadata": {
25 | "ExecuteTime": {
26 | "end_time": "2020-01-09T01:19:59.036142Z",
27 | "start_time": "2020-01-09T01:19:39.435378Z"
28 | }
29 | },
30 | "outputs": [],
31 | "source": [
32 | "import numpy as np\n",
33 | "from utils.logger import PrettyLogger\n",
34 | "from utils.date import str2date, int2date_delta, date2str\n",
35 | "from utils.io_func import save_to_npy, load_from_tiff\n",
36 | "from config import (\n",
37 | " START_V_I, START_H_I, SIDE_LEN, INTRPL_START_DATE_STR, INTRPL_END_DATE_STR\n",
38 | ")"
39 | ]
40 | },
41 | {
42 | "cell_type": "code",
43 | "execution_count": null,
44 | "metadata": {
45 | "ExecuteTime": {
46 | "end_time": "2020-01-09T01:19:59.043143Z",
47 | "start_time": "2020-01-09T01:19:59.039422Z"
48 | }
49 | },
50 | "outputs": [],
51 | "source": [
52 | "logger = PrettyLogger()"
53 | ]
54 | },
55 | {
56 | "cell_type": "code",
57 | "execution_count": null,
58 | "metadata": {
59 | "ExecuteTime": {
60 | "end_time": "2020-01-09T01:19:59.055840Z",
61 | "start_time": "2020-01-09T01:19:59.045850Z"
62 | }
63 | },
64 | "outputs": [],
65 | "source": [
66 | "SITE = \"Site_A\"\n",
67 | "YEAR = \"2015\"\n",
68 | "DATA_DIR = \"../data/{}/ARD/{}/\".format(SITE, YEAR)\n",
69 | "OUTPUT_DIR = \"./out/{}/ARD/cropped_interpolated/{}/\".format(SITE, YEAR)\n",
70 | "AVAI_PATH = os.path.join(OUTPUT_DIR, \"availability.npy\")\n",
71 | "FILTER_BAND_PATH = os.path.join(OUTPUT_DIR, \"filter_band.npy\")\n",
72 | "INTERPOLATED_PATH = os.path.join(OUTPUT_DIR, \"interpolated.npy\")\n",
73 | "FINAL_OUTOUT_FILEPATH = \"./out/{}/x-{}.npy\".format(SITE, YEAR)"
74 | ]
75 | },
76 | {
77 | "cell_type": "markdown",
78 | "metadata": {},
79 | "source": [
80 | "# ARD observation input, cropping and filtering"
81 | ]
82 | },
83 | {
84 | "cell_type": "code",
85 | "execution_count": null,
86 | "metadata": {
87 | "ExecuteTime": {
88 | "end_time": "2020-01-09T01:19:59.109273Z",
89 | "start_time": "2020-01-09T01:19:59.059000Z"
90 | }
91 | },
92 | "outputs": [],
93 | "source": [
94 | "# link the filenames to date\n",
95 | "date_filename_dict = {}\n",
96 | "for filename in sorted(os.listdir(DATA_DIR)):\n",
97 | " date = str2date(filename[15:23])\n",
98 | " if (\n",
99 | " date >= str2date(\"{}{}\".format(YEAR, INTRPL_START_DATE_STR))\n",
100 | " and date <= str2date(\"{}{}\".format(YEAR, INTRPL_END_DATE_STR))\n",
101 | " ):\n",
102 | " if date not in date_filename_dict.keys():\n",
103 | " date_filename_dict[date] = []\n",
104 | " date_filename_dict[date].append(filename)"
105 | ]
106 | },
107 | {
108 | "cell_type": "code",
109 | "execution_count": null,
110 | "metadata": {
111 | "ExecuteTime": {
112 | "end_time": "2020-01-09T01:36:33.301768Z",
113 | "start_time": "2020-01-09T01:19:59.112110Z"
114 | },
115 | "scrolled": true
116 | },
117 | "outputs": [],
118 | "source": [
119 | "# read ARD images, crop ARD images and detect invalid values\n",
120 | "raw_dates = sorted(date_filename_dict.keys())\n",
121 | "availability = np.zeros((SIDE_LEN, SIDE_LEN, len(raw_dates)))\n",
122 | "valid = np.zeros((SIDE_LEN, SIDE_LEN, len(raw_dates), 6))\n",
123 | "\n",
124 | "to_fill = np.vectorize(lambda x: int(\"{:011b}\".format(x)[-1], 2))\n",
125 | "to_clear = np.vectorize(lambda x: int(\"{:011b}\".format(x)[-2], 2))\n",
126 | "to_cloud_shadow = np.vectorize(lambda x: int(\"{:011b}\".format(x)[-4], 2))\n",
127 | "to_cloud = np.vectorize(lambda x: int(\"{:011b}\".format(x)[-6], 2))\n",
128 | "for i, date in enumerate(raw_dates):\n",
129 | " logger.info(\"Loading: {}/{}\".format(i+1, len(raw_dates)), date2str(date))\n",
130 | " sr_bands = []\n",
131 | " for filename in date_filename_dict[date]:\n",
132 | " band = load_from_tiff(os.path.join(DATA_DIR, filename))[\n",
133 | " START_V_I:START_V_I+SIDE_LEN, START_H_I:START_H_I+SIDE_LEN\n",
134 | " ]\n",
135 | " if filename[-11:-4] != \"PIXELQA\":\n",
136 | " sr_bands.append(band)\n",
137 | " else:\n",
138 | " qa_band = band\n",
139 | " sr_bands = np.array(sr_bands).transpose((1, 2, 0))\n",
140 | "\n",
141 | " flag_sr_range = ((sr_bands >= 0) & (sr_bands <= 10000)).all(axis=2)\n",
142 | " fill_band = to_fill(qa_band)\n",
143 | " flag_fill = (fill_band == 0)\n",
144 | " clear_band = to_clear(qa_band)\n",
145 | " flag_clear = (clear_band == 1)\n",
146 | " cloud_shadow_band = to_cloud_shadow(qa_band)\n",
147 | " flag_cloud_shadow = (cloud_shadow_band == 0)\n",
148 | " cloud_band = to_cloud(qa_band)\n",
149 | " flag_cloud = (cloud_band == 0)\n",
150 | " flag = flag_sr_range*flag_fill*flag_clear*flag_cloud_shadow*flag_cloud\n",
151 | "\n",
152 | " availability[:, :, i] = flag\n",
153 | "\n",
154 | " # make invalid observations zero, only for the convenience of debugging\n",
155 | " valid[:, :, i, :] = sr_bands\n",
156 | " valid[:, :, i, :] = valid[:, :, i, :]*(flag.reshape(*flag.shape, 1))\n",
157 | "\n",
158 | "save_to_npy(availability, AVAI_PATH)"
159 | ]
160 | },
161 | {
162 | "cell_type": "code",
163 | "execution_count": null,
164 | "metadata": {
165 | "ExecuteTime": {
166 | "end_time": "2020-01-09T01:36:34.384851Z",
167 | "start_time": "2020-01-09T01:36:33.306697Z"
168 | }
169 | },
170 | "outputs": [],
171 | "source": [
172 | "\"\"\"\n",
173 | "========== PIXEL FILTER METHOD BY AVAILABILITY ==========\n",
174 | "If the number of valid observations after May 15 >= 7,\n",
175 | "the pixel will be included in the dataset, otherwise it will be excluded.\n",
176 | "\"\"\"\n",
177 | "\n",
178 | "index4filter = raw_dates.index(list(filter(\n",
179 | " lambda x: x > str2date(\"{}0515\".format(YEAR)), raw_dates\n",
180 | "))[0])\n",
181 | "filter_band = availability[:, :, index4filter:].sum(axis=2) >= 7\n",
182 | "logger.info(\"Validity percentage ({} {}): {:.4f}\".format(\n",
183 | " SITE, YEAR,\n",
184 | " filter_band.sum()/(filter_band.shape[0]*filter_band.shape[1])\n",
185 | "))\n",
186 | "save_to_npy(filter_band, FILTER_BAND_PATH)"
187 | ]
188 | },
189 | {
190 | "cell_type": "markdown",
191 | "metadata": {},
192 | "source": [
193 | "# Temporal interpolation"
194 | ]
195 | },
196 | {
197 | "cell_type": "code",
198 | "execution_count": null,
199 | "metadata": {
200 | "ExecuteTime": {
201 | "end_time": "2020-01-09T01:36:38.032317Z",
202 | "start_time": "2020-01-09T01:36:36.930790Z"
203 | }
204 | },
205 | "outputs": [],
206 | "source": [
207 | "# prepare target dates for interpolation\n",
208 | "intrpl_start_date = str2date(\"{}{}\".format(YEAR, INTRPL_START_DATE_STR))\n",
209 | "intrpl_end_date = str2date(\"{}{}\".format(YEAR, INTRPL_END_DATE_STR))\n",
210 | "intrpl_delta_days = list(range(\n",
211 | " 0, (intrpl_end_date - intrpl_start_date).days + 1, 7\n",
212 | "))\n",
213 | "intrpl_dates = [\n",
214 | " int2date_delta(intrpl_delta_day) + intrpl_start_date\n",
215 | " for intrpl_delta_day in intrpl_delta_days\n",
216 | "]"
217 | ]
218 | },
219 | {
220 | "cell_type": "code",
221 | "execution_count": null,
222 | "metadata": {
223 | "ExecuteTime": {
224 | "end_time": "2020-01-09T03:00:21.154986Z",
225 | "start_time": "2020-01-09T01:36:38.035281Z"
226 | },
227 | "scrolled": true
228 | },
229 | "outputs": [],
230 | "source": [
231 | "'''\n",
232 | "========== INTERPOLATION METHOD ==========\n",
233 | "situation I (normal): d_1, d_2*, target, d_3*, d_4, ...\n",
234 | "situation II (close to the start date): target, d_1*, d_2*, d_3, ...\n",
235 | "situation III (close to the end date): d_1, d_2, ..., d_(-2), d_(-1), target\n",
236 | "'''\n",
237 | "\n",
238 | "interpolated = np.zeros((SIDE_LEN, SIDE_LEN, len(intrpl_dates), 6))\n",
239 | "for intrpl_date_index, intrpl_date in enumerate(intrpl_dates):\n",
240 | " logger.info(\"Interpolating: {}/{} {} \".format(\n",
241 | " intrpl_date_index + 1, len(intrpl_dates), date2str(intrpl_date))\n",
242 | " )\n",
243 | " # descending/ascending order for searching the nearest day before/after\n",
244 | " before_dates = list(filter(lambda x: x <= intrpl_date, raw_dates))[::-1]\n",
245 | " after_dates = list(filter(lambda x: x >= intrpl_date, raw_dates))\n",
246 | "\n",
247 | " for i in range(SIDE_LEN):\n",
248 | " for j in range(SIDE_LEN):\n",
249 | "\n",
250 | " # filter invalid pixel\n",
251 | " if not filter_band[i, j]:\n",
252 | " continue\n",
253 | "\n",
254 | " # situation I\n",
255 | " d_1 = None\n",
256 | " for nearest_before_index, before_date in enumerate(before_dates):\n",
257 | " before_date_raw_index = raw_dates.index(before_date)\n",
258 | " if availability[i, j][before_date_raw_index]:\n",
259 | " d_1 = before_date\n",
260 | " date_raw_index_1 = before_date_raw_index\n",
261 | " break\n",
262 | " d_2 = None\n",
263 | " for nearest_after_index, after_date in enumerate(after_dates):\n",
264 | " after_date_raw_index = raw_dates.index(after_date)\n",
265 | " if availability[i, j][after_date_raw_index]:\n",
266 | " d_2 = after_date\n",
267 | " date_raw_index_2 = after_date_raw_index\n",
268 | " break\n",
269 | "\n",
270 | " # situation II: search the second nearest after date\n",
271 | " if not d_1:\n",
272 | " for after_date in after_dates[nearest_after_index+1:]:\n",
273 | " after_date_raw_index = raw_dates.index(after_date)\n",
274 | " if availability[i, j][after_date_raw_index]:\n",
275 | " d_1 = after_date\n",
276 | " date_raw_index_1 = after_date_raw_index\n",
277 | " break\n",
278 | "\n",
279 | " # situation III: search the second nearest before date\n",
280 | " if not d_2:\n",
281 | " for before_date in before_dates[nearest_before_index+1:]:\n",
282 | " before_date_raw_index = raw_dates.index(before_date)\n",
283 | " if availability[i, j][before_date_raw_index]:\n",
284 | " d_2 = before_date\n",
285 | " date_raw_index_2 = before_date_raw_index\n",
286 | " break\n",
287 | "\n",
288 | " interpolated[i][j][intrpl_date_index] = [np.interp(\n",
289 | " (intrpl_date-d_1).days,\n",
290 | " [0, (d_2-d_1).days],\n",
291 | " [valid[i, j, date_raw_index_1, band_index],\n",
292 | " valid[i, j, date_raw_index_2, band_index]]\n",
293 | " ) for band_index in range(6)]\n",
294 | "\n",
295 | "save_to_npy(interpolated, INTERPOLATED_PATH)\n",
296 | "x = interpolated[filter_band]\n",
297 | "save_to_npy(x, FINAL_OUTOUT_FILEPATH)"
298 | ]
299 | }
300 | ],
301 | "metadata": {
302 | "kernelspec": {
303 | "display_name": "Python 3",
304 | "language": "python",
305 | "name": "python3"
306 | },
307 | "language_info": {
308 | "codemirror_mode": {
309 | "name": "ipython",
310 | "version": 3
311 | },
312 | "file_extension": ".py",
313 | "mimetype": "text/x-python",
314 | "name": "python",
315 | "nbconvert_exporter": "python",
316 | "pygments_lexer": "ipython3",
317 | "version": "3.5.2"
318 | },
319 | "toc": {
320 | "base_numbering": 1,
321 | "nav_menu": {},
322 | "number_sections": true,
323 | "sideBar": true,
324 | "skip_h1_title": false,
325 | "title_cell": "Table of Contents",
326 | "title_sidebar": "Contents",
327 | "toc_cell": false,
328 | "toc_position": {
329 | "height": "calc(100% - 180px)",
330 | "left": "10px",
331 | "top": "150px",
332 | "width": "235px"
333 | },
334 | "toc_section_display": true,
335 | "toc_window_display": true
336 | }
337 | },
338 | "nbformat": 4,
339 | "nbformat_minor": 2
340 | }
341 |
--------------------------------------------------------------------------------
/preprocessing/preprocess_CDL.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {
7 | "ExecuteTime": {
8 | "end_time": "2020-01-09T06:35:28.038350Z",
9 | "start_time": "2020-01-09T06:35:28.031637Z"
10 | }
11 | },
12 | "outputs": [],
13 | "source": [
14 | "import os\n",
15 | "import sys\n",
16 | "module_path = os.path.abspath(os.path.join(\"..\"))\n",
17 | "if module_path not in sys.path:\n",
18 | " sys.path.append(module_path)"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": null,
24 | "metadata": {
25 | "ExecuteTime": {
26 | "end_time": "2020-01-09T06:35:35.435742Z",
27 | "start_time": "2020-01-09T06:35:28.052269Z"
28 | }
29 | },
30 | "outputs": [],
31 | "source": [
32 | "import numpy as np\n",
33 | "from utils.logger import PrettyLogger\n",
34 | "from utils.io_func import (\n",
35 | " load_from_tiff, save_to_tiff, load_from_npy, save_to_npy\n",
36 | ")\n",
37 | "from config import START_V_I, START_H_I, SIDE_LEN"
38 | ]
39 | },
40 | {
41 | "cell_type": "code",
42 | "execution_count": null,
43 | "metadata": {
44 | "ExecuteTime": {
45 | "end_time": "2020-01-09T06:35:35.443189Z",
46 | "start_time": "2020-01-09T06:35:35.439382Z"
47 | }
48 | },
49 | "outputs": [],
50 | "source": [
51 | "logger = PrettyLogger()"
52 | ]
53 | },
54 | {
55 | "cell_type": "code",
56 | "execution_count": null,
57 | "metadata": {
58 | "ExecuteTime": {
59 | "end_time": "2020-01-09T06:35:35.464212Z",
60 | "start_time": "2020-01-09T06:35:35.445754Z"
61 | }
62 | },
63 | "outputs": [],
64 | "source": [
65 | "SITE_YEAR_TUPLE = ((\"Site_A\", \"2015\"),)\n",
66 | "DATA_DIR_TEMPLATE = \"../data/{site}/CDL/\"\n",
67 | "CROPPED_FILEPATH_TEMPLATE = \"./out/{site}/CDL/cropped/CDL-{year}.tif\"\n",
68 | "TRANSCODED_FILEPATH_TEMPLATE = \"./out/{site}/CDL/transcoded/CDL-{year}.tif\"\n",
69 | "INTERPOLATED_FILEPATH_TEMPLATE = (\n",
70 | " \"./out/{site}/ARD/cropped_interpolated/{year}/filter_band.npy\"\n",
71 | ")\n",
72 | "FINAL_OUT_FILEPATH_TEMPLATE = \"./out/{site}/y-{year}.npy\""
73 | ]
74 | },
75 | {
76 | "cell_type": "markdown",
77 | "metadata": {},
78 | "source": [
79 | "# Cropping and transcoding"
80 | ]
81 | },
82 | {
83 | "cell_type": "code",
84 | "execution_count": null,
85 | "metadata": {
86 | "ExecuteTime": {
87 | "end_time": "2020-01-09T06:35:35.493707Z",
88 | "start_time": "2020-01-09T06:35:35.467584Z"
89 | }
90 | },
91 | "outputs": [],
92 | "source": [
93 | "def transcode(p):\n",
94 | " # corn:1 -> 1, soybean:5 -> 2, other:other -> 0\n",
95 | " return 1 if p == 1 else 2 if p == 5 else 0\n",
96 | "\n",
97 | "\n",
98 | "def preprocess_cdl(\n",
99 | " data_path, cropped_filepath, transcoded_filepath,\n",
100 | " interpolated_filepath, final_out_filepath\n",
101 | "):\n",
102 | " # input\n",
103 | " raw_img = load_from_tiff(data_path)\n",
104 | "\n",
105 | " # crop cdl\n",
106 | " cropped_img = raw_img[\n",
107 | " START_V_I:START_V_I + SIDE_LEN, START_H_I:START_H_I+SIDE_LEN\n",
108 | " ]\n",
109 | " save_to_tiff(cropped_img, cropped_filepath)\n",
110 | "\n",
111 | " # transcoding\n",
112 | " transcoded_img = np.vectorize(transcode)(cropped_img)\n",
113 | " save_to_tiff(transcoded_img, transcoded_filepath)\n",
114 | "\n",
115 | " # remove invalid pixels\n",
116 | " filter_band = load_from_npy(interpolated_filepath)\n",
117 | " y = transcoded_img[filter_band]\n",
118 | "\n",
119 | " # output preprocessed data\n",
120 | " save_to_npy(y, final_out_filepath)"
121 | ]
122 | },
123 | {
124 | "cell_type": "code",
125 | "execution_count": null,
126 | "metadata": {
127 | "ExecuteTime": {
128 | "end_time": "2020-01-09T06:36:15.105776Z",
129 | "start_time": "2020-01-09T06:35:35.496690Z"
130 | }
131 | },
132 | "outputs": [],
133 | "source": [
134 | "for site, year in SITE_YEAR_TUPLE:\n",
135 | " data_dir = DATA_DIR_TEMPLATE.format(site=site)\n",
136 | " filename = list(filter(lambda x: x[4:8] == year, os.listdir(data_dir)))[0]\n",
137 | " data_path = os.path.join(data_dir, filename)\n",
138 | " logger.info(\"Processing:\" site, filename)\n",
139 | " preprocess_cdl(\n",
140 | " data_path=data_path,\n",
141 | " cropped_filepath=CROPPED_FILEPATH_TEMPLATE.format(\n",
142 | " site=site, year=year\n",
143 | " ),\n",
144 | " transcoded_filepath=TRANSCODED_FILEPATH_TEMPLATE.format(\n",
145 | " site=site, year=year\n",
146 | " ),\n",
147 | " interpolated_filepath=INTERPOLATED_FILEPATH_TEMPLATE.format(\n",
148 | " site=site, year=year\n",
149 | " ),\n",
150 | " final_out_filepath=FINAL_OUT_FILEPATH_TEMPLATE.format(\n",
151 | " site=site, year=year\n",
152 | " )\n",
153 | " )"
154 | ]
155 | }
156 | ],
157 | "metadata": {
158 | "kernelspec": {
159 | "display_name": "Python 3",
160 | "language": "python",
161 | "name": "python3"
162 | },
163 | "language_info": {
164 | "codemirror_mode": {
165 | "name": "ipython",
166 | "version": 3
167 | },
168 | "file_extension": ".py",
169 | "mimetype": "text/x-python",
170 | "name": "python",
171 | "nbconvert_exporter": "python",
172 | "pygments_lexer": "ipython3",
173 | "version": "3.5.2"
174 | },
175 | "toc": {
176 | "base_numbering": 1,
177 | "nav_menu": {},
178 | "number_sections": true,
179 | "sideBar": true,
180 | "skip_h1_title": false,
181 | "title_cell": "Table of Contents",
182 | "title_sidebar": "Contents",
183 | "toc_cell": false,
184 | "toc_position": {
185 | "height": "calc(100% - 180px)",
186 | "left": "10px",
187 | "top": "150px",
188 | "width": "231px"
189 | },
190 | "toc_section_display": true,
191 | "toc_window_display": true
192 | }
193 | },
194 | "nbformat": 4,
195 | "nbformat_minor": 2
196 | }
197 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | torch
2 | numpy
3 | pandas
4 | scikit-learn
5 | jupyter
6 |
--------------------------------------------------------------------------------
/utils/date.py:
--------------------------------------------------------------------------------
1 | import datetime
2 |
3 |
4 | def str2date(date_str, format="%Y%m%d"):
5 | return datetime.datetime.strptime(date_str, format)
6 |
7 |
8 | def date2str(date, format="%Y%m%d"):
9 | return date.strftime(format)
10 |
11 |
12 | def int2date_delta(date_delta_int):
13 | return datetime.timedelta(date_delta_int)
--------------------------------------------------------------------------------
/utils/helper.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | module_path = os.path.abspath(os.path.join(".."))
4 | if module_path not in sys.path:
5 | sys.path.append(module_path)
6 |
7 | import re
8 | import numpy as np
9 | import torch
10 | from torch.utils.data import Dataset, DataLoader
11 | import torch.nn as nn
12 | import torch.nn.functional as F
13 | import torch.optim as optim
14 | from models.dcm import DCM
15 | from config import SEED
16 | from utils.timer import record_time
17 |
18 |
19 | class DCMHelper(object):
20 | def __init__(
21 | self, seed=SEED, hidden_size=256, num_layers=2,
22 | bidirectional=True, dropout=0.5, batch_size=int(pow(2, 15)),
23 | num_workers=2, drop_last=False, criterion=nn.CrossEntropyLoss(),
24 | max_epoch=300, min_stop_epoch=5, stop_threshold=0.0002,
25 | record_attn=False, lr=0.0005, weight_decay=0.001, use_scheduler=True,
26 | mode="min", factor=0.5, patience=3, threshold=0.002,
27 | threshold_mode="abs", verbose=True
28 | ):
29 | # data description
30 | self.input_feature_size = None
31 | self.num_classes = None
32 |
33 | # model initialization (structure and hyperparameters)
34 | self.seed = seed
35 | self.hidden_size = hidden_size
36 | self.num_layers = num_layers
37 | self.bidirectional = bidirectional
38 | self.num_directions = 2 if self.bidirectional else 1
39 | self.dropout = dropout
40 |
41 | # data loader
42 | self.batch_size = batch_size
43 | self.num_workers = num_workers
44 | self.drop_last = drop_last
45 |
46 | # training process
47 | self.criterion = criterion
48 | self.max_epoch = max_epoch
49 | self.min_stop_epoch = min_stop_epoch
50 | self.stop_threshold = stop_threshold
51 | self.record_attn = record_attn
52 |
53 | # optimizer
54 | self.lr = lr
55 | self.weight_decay = weight_decay
56 |
57 | # scheduler
58 | self.use_scheduler = use_scheduler
59 | self.mode = mode
60 | self.factor = factor
61 | self.patience = patience
62 | self.threshold = threshold
63 | self.threshold_mode = threshold_mode
64 | self.verbose = verbose
65 |
66 | self.train_time_list = []
67 | self.test_time_list = []
68 |
69 | def _input_data(self, paths):
70 | data = np.concatenate(
71 | [np.load(path) for path in paths], axis=0
72 | )
73 | return data
74 |
75 | def input_x(self, paths):
76 | # x: (num_samples, seq_len, input_feature_size)
77 | x = self._input_data(paths).astype("float32")
78 | self.input_feature_size = x.shape[2]
79 | return x
80 |
81 | def input_y(self, paths):
82 | y = self._input_data(paths).astype("int64")
83 | self.num_classes = np.unique(y).shape[0]
84 | return y
85 |
86 | def normalize_with_scaler(self, scaler, x_test):
87 | x_test = scaler(
88 | torch.FloatTensor(x_test.transpose((0, 2, 1)))
89 | ).numpy().transpose((0, 2, 1))
90 | return x_test
91 |
92 | def normalize_without_scaler(self, x_train, x_test):
93 | scaler = torch.nn.BatchNorm1d(
94 | self.input_feature_size, eps=0, momentum=1, affine=False
95 | )
96 | scaler.train()
97 | x_train = scaler(
98 | torch.FloatTensor(x_train.transpose((0, 2, 1)))
99 | ).numpy().transpose((0, 2, 1))
100 | scaler.eval()
101 | x_test = scaler(
102 | torch.FloatTensor(x_test.transpose((0, 2, 1)))
103 | ).numpy().transpose((0, 2, 1))
104 | return scaler, x_train, x_test
105 |
106 | def _collate_fn(self, batch):
107 | """
108 | define how to aggregate samples to batch
109 | """
110 | return {
111 | "x": torch.FloatTensor(
112 | np.array([sample["sample_x"] for sample in batch])
113 | ),
114 | "y": torch.LongTensor(
115 | np.array([sample["sample_y"] for sample in batch])
116 | )
117 | }
118 |
119 | def make_data_loader(self, x, y, shuffle):
120 | return DataLoader(
121 | CropMappingDataset(x, y),
122 | batch_size=self.batch_size, shuffle=shuffle,
123 | num_workers=self.num_workers, collate_fn=self._collate_fn,
124 | drop_last=self.drop_last
125 | )
126 |
127 | def build_model(self):
128 | return DCM(
129 | seed=self.seed,
130 | input_feature_size=self.input_feature_size,
131 | hidden_size=self.hidden_size,
132 | num_layers=self.num_layers,
133 | bidirectional=self.bidirectional,
134 | dropout=self.dropout,
135 | num_classes=self.num_classes
136 | )
137 |
138 | def _init_parameters(self, submodule):
139 | if type(submodule) == nn.LSTM:
140 | for name, param in submodule.named_parameters():
141 | if re.search("bias_ih", name):
142 | # set forget gate bias to 3.0
143 | param.detach().chunk(4)[1].fill_(3.0)
144 |
145 | def init_parameters(self, net):
146 | net.apply(self._init_parameters)
147 |
148 | def _eval_perf(self, net, dataloader, device):
149 | net.eval()
150 | with torch.no_grad():
151 | attn_batch_list = []
152 | losses = 0
153 | correct = 0
154 | for i, batch in enumerate(dataloader):
155 | xt, yt = batch["x"].to(device), batch["y"].to(device)
156 | outputs, attn_batch = net(xt)
157 | loss = self.criterion(outputs, yt)
158 | losses += loss.item() * yt.shape[0]
159 | yt_pred = torch.max(outputs, dim=1)[1]
160 | correct += (yt_pred == yt).sum().item()
161 | attn_batch_list.append(attn_batch)
162 | running_loss = losses / len(dataloader.dataset)
163 | acc = correct / len(dataloader.dataset)
164 | attn = torch.cat(attn_batch_list, dim=0).cpu().numpy()
165 | net.train()
166 | return running_loss, acc, attn
167 |
168 | def _train_model(
169 | self, net, train_dataloader, test_dataloader, device, logger,
170 | loss_train_list, acc_train_list, attn_train_list, loss_test_list,
171 | acc_test_list, attn_test_list
172 | ):
173 | optimizer = optim.Adam(
174 | net.parameters(), lr=self.lr, weight_decay=self.weight_decay,
175 | )
176 | scheduler = optim.lr_scheduler.ReduceLROnPlateau(
177 | optimizer, mode=self.mode, factor=self.factor,
178 | patience=self.patience, threshold=self.threshold,
179 | threshold_mode=self.threshold_mode, verbose=self.verbose
180 | )
181 |
182 | for epoch in range(1, self.max_epoch + 1):
183 | net.train()
184 | for i, batch in enumerate(train_dataloader):
185 | xt_train_batch = batch["x"].to(device)
186 | yt_train_batch = batch["y"].to(device)
187 | optimizer.zero_grad()
188 | outputs, _ = net(xt_train_batch)
189 | loss = self.criterion(outputs, yt_train_batch)
190 | loss.backward()
191 | optimizer.step()
192 | loss_train, acc_train, attn_train = self._eval_perf(
193 | net, train_dataloader, device
194 | )
195 | if self.use_scheduler:
196 | scheduler.step(loss_train) # adjust learning rate
197 | loss_test, acc_test, attn_test = self._eval_perf(
198 | net, test_dataloader, device
199 | )
200 | loss_train_list.append(loss_train)
201 | acc_train_list.append(acc_train)
202 | loss_test_list.append(loss_test)
203 | acc_test_list.append(acc_test)
204 | if self.record_attn:
205 | attn_train_list.append(attn_train)
206 | attn_test_list.append(attn_test)
207 |
208 | logger.info((
209 | "[epoch {:d}] "
210 | "training loss: {:.4f}, test loss: {:.4f}, "
211 | "training acc: {:.4f}, test acc: {:.4f} "
212 | " (lr => {:f})"
213 | ).format(
214 | epoch,
215 | loss_train, loss_test,
216 | acc_train, acc_test,
217 | optimizer.param_groups[0]["lr"])
218 | )
219 |
220 | if (
221 | epoch >= self.min_stop_epoch
222 | and (
223 | np.array(acc_train_list[epoch - 5:epoch]).ptp()
224 | <= self.stop_threshold
225 | )
226 | ):
227 | break
228 |
229 | logger.info("Training completed")
230 |
231 | def train_model(
232 | self, net, train_dataloader, test_dataloader, device, logger,
233 | loss_train_list, acc_train_list, attn_train_list, loss_test_list,
234 | acc_test_list, attn_test_list
235 | ):
236 | record_time(self.train_time_list, self._train_model, [
237 | net, train_dataloader, test_dataloader, device, logger,
238 | loss_train_list, acc_train_list, attn_train_list, loss_test_list,
239 | acc_test_list, attn_test_list
240 | ])
241 |
242 | def _predict(self, net, dataloader, device):
243 | yt_soft_pred_batch_list = []
244 | attn_batch_list = []
245 | net.eval()
246 | with torch.no_grad():
247 | for i, batch in enumerate(dataloader):
248 | xt, yt = batch["x"].to(device), batch["y"].to(device)
249 | outputs, attn_batch = net(xt)
250 | yt_soft_pred_batch_list.append(F.softmax(outputs, dim=1))
251 | attn_batch_list.append(attn_batch)
252 | y_soft_pred = torch.cat(
253 | yt_soft_pred_batch_list, dim=0
254 | ).cpu().numpy()
255 | y_hard_pred = np.argmax(y_soft_pred, axis=1)
256 | attn = torch.cat(attn_batch_list, dim=0).cpu().numpy()
257 | return y_soft_pred, y_hard_pred, attn
258 |
259 | def predict(self, net, dataloader, device):
260 | return record_time(self.test_time_list, self._predict, [
261 | net, dataloader, device
262 | ])
263 |
264 |
265 | class CropMappingDataset(Dataset):
266 | """
267 | crop classification dataset
268 | """
269 |
270 | def __init__(self, x, y):
271 | self.x = x
272 | self.y = y
273 |
274 | def __len__(self):
275 | return self.x.shape[0]
276 |
277 | def __getitem__(self, idx):
278 | return {"sample_x": self.x[idx], "sample_y": self.y[idx]}
279 |
--------------------------------------------------------------------------------
/utils/io_func.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 | import pickle
4 | import numpy as np
5 | import pandas as pd
6 | import matplotlib.pyplot as plt
7 | import tifffile as tiff
8 | import torch
9 |
10 |
11 | def _assert_suffix_match(suffix, path):
12 | assert re.search(r"\.{}$".format(suffix), path), "suffix mismatch"
13 |
14 |
15 | def make_parent_dir(filepath):
16 | parent_path = os.path.dirname(filepath)
17 | if not os.path.isdir(parent_path):
18 | try:
19 | os.mkdir(parent_path)
20 | except FileNotFoundError:
21 | make_parent_dir(parent_path)
22 | os.mkdir(parent_path)
23 | print("[INFO] Make new directory: '{}'".format(parent_path))
24 |
25 |
26 | def save_to_csv(data, path, header=None, index=None):
27 | _assert_suffix_match("csv", path)
28 | make_parent_dir(path)
29 | pd.DataFrame(data).to_csv(path, header=header, index=index)
30 | print("[INFO] Save as csv: '{}'".format(path))
31 |
32 |
33 | def load_from_csv(path, header=None, index_col=None):
34 | return pd.read_csv(path, header=header, index_col=index_col)
35 |
36 |
37 | def save_to_excel(data, writer, other_kws={}):
38 | if type(writer) == str: # if path is ExcelWriter, skip this validation
39 | _assert_suffix_match("xlsx", writer)
40 | make_parent_dir(writer)
41 | else:
42 | _assert_suffix_match("xlsx", writer.path)
43 | make_parent_dir(writer.path)
44 | if not hasattr(data, "to_excel"):
45 | data = pd.DataFrame(data)
46 | data.to_excel(writer, **other_kws)
47 | print("[INFO] Save as excel: '{}'".format(
48 | writer if type(writer) == str else writer.path
49 | ))
50 |
51 |
52 | def load_from_excel(path, header=[0], index_col=[0]):
53 | return pd.read_excel(path, header=header, index_col=index_col)
54 |
55 |
56 | def save_to_pkl(data, path):
57 | _assert_suffix_match("pkl", path)
58 | make_parent_dir(path)
59 | with open(path, "wb") as f:
60 | pickle.dump(data, f, protocol=-1)
61 | print("[INFO] Save as pkl: '{}'".format(path))
62 |
63 |
64 | def load_from_pkl(path):
65 | with open(path, "rb") as f:
66 | return pickle.load(f)
67 |
68 |
69 | def save_to_npy(data, path):
70 | _assert_suffix_match("npy", path)
71 | make_parent_dir(path)
72 | np.save(path, data)
73 | print("[INFO] Save as npy: '{}'".format(path))
74 |
75 |
76 | def load_from_npy(path):
77 | return np.load(path)
78 |
79 |
80 | def save_to_pth(data, path, model=True):
81 | _assert_suffix_match("pth", path)
82 | make_parent_dir(path)
83 | if model:
84 | if hasattr(data, "module"):
85 | data = data.module.state_dict()
86 | else:
87 | data = data.state_dict()
88 | torch.save(data, path)
89 | print("[INFO] Save as pth: '{}'".format(path))
90 |
91 |
92 | def load_from_pth(path):
93 | return torch.load(path)
94 |
95 |
96 | def save_to_tiff(data, path):
97 | _assert_suffix_match("tiff?", path)
98 | make_parent_dir(path)
99 | tiff.imsave(path, data)
100 | print("[INFO] Save as tiff: '{}'".format(path))
101 |
102 |
103 | def load_from_tiff(path):
104 | return tiff.imread(path)
105 |
106 |
107 | def savefig_png(path, dpi=150):
108 | _assert_suffix_match("png", path)
109 | make_parent_dir(path)
110 | plt.savefig(path, bbox_inches="tight", dpi=dpi)
111 | print("[INFO] Save figure as png: '{}'".format(path))
112 |
113 |
114 | def savefig_eps(path):
115 | _assert_suffix_match("eps", path)
116 | make_parent_dir(path)
117 | plt.savefig(path, bbox_inches="tight")
118 | print("[INFO] Save figure as eps: '{}'".format(path))
119 |
120 |
121 | def saveimg_png(data, path, dpi=150):
122 | _assert_suffix_match("png", path)
123 | make_parent_dir(path)
124 | plt.imsave(fname=path, arr=data, dpi=dpi)
125 | print("[INFO] Save image as png: '{}'".format(path))
126 |
--------------------------------------------------------------------------------
/utils/logger.py:
--------------------------------------------------------------------------------
1 | import time
2 | import logging
3 | from colorama import Fore, Back, Style
4 |
5 |
6 | class ColoredFormatter(logging.Formatter):
7 | def __init__(self):
8 | self._fmt = "{prefix_style}[{levelname:.1} {asctime}]{reset} {message_style}{message}{reset}"
9 | self._style = "{"
10 | super().__init__(fmt=self._fmt, datefmt="%Y-%m-%d %H:%M:%S", style=self._style)
11 | self._pallet = {
12 | "CRITICAL": Fore.BLUE,
13 | "ERROR": Fore.RED,
14 | "WARNING": Fore.YELLOW,
15 | "INFO": Fore.GREEN,
16 | "DEBUG": Fore.MAGENTA,
17 | }
18 |
19 | def format(self, record):
20 | record.prefix_style = self._pallet[record.levelname]
21 | record.message_style = self._pallet[record.levelname]+Style.BRIGHT
22 | record.reset = Style.RESET_ALL
23 | return logging.Formatter.format(self, record)
24 |
25 |
26 | class PrettyLogger(object):
27 | """Customized logger for pretty logging messages"""
28 |
29 | def __init__(self, level=logging.DEBUG):
30 | self._level = level
31 | self.logger = self._init_logger()
32 |
33 | def get_logger(self):
34 | return self.logger
35 |
36 | def _init_logger(self, clear_prev_handlers=True):
37 | logger = logging.getLogger()
38 | logger.setLevel(self._level)
39 | console_handler = logging.StreamHandler()
40 | console_handler.setLevel(self._level)
41 | colored_formatter = ColoredFormatter()
42 | console_handler.setFormatter(colored_formatter)
43 | if clear_prev_handlers:
44 | logger.handlers.clear()
45 | logger.addHandler(console_handler)
46 | return logger
47 |
48 | def _join_words(self, words):
49 | return " ".join(map(str, words))
50 |
51 | def critical(self, *words):
52 | self.logger.critical(self._join_words(words))
53 |
54 | def error(self, *words):
55 | self.logger.error(self._join_words(words))
56 |
57 | def warning(self, *words):
58 | self.logger.warning(self._join_words(words))
59 |
60 | def info(self, *words):
61 | self.logger.info(self._join_words(words))
62 |
63 | def debug(self, *words):
64 | self.logger.debug(self._join_words(words))
--------------------------------------------------------------------------------
/utils/timer.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 |
3 |
4 | def record_time(record_list, func, args, time_format="%Y%m%d-%H:%M:%S"):
5 | start_time = datetime.now()
6 | result = func(*args)
7 | end_time = datetime.now()
8 | duration = end_time - start_time
9 | record_list.append([
10 | start_time.strftime(time_format),
11 | end_time.strftime(time_format),
12 | format_timedelta(duration),
13 | ])
14 | return result
15 |
16 | def format_timedelta(timedelta):
17 | total_seconds = int(timedelta.total_seconds())
18 | hours, remainder = divmod(total_seconds, 60*60)
19 | minutes, seconds = divmod(remainder, 60)
20 | return "{}:{}:{}".format(hours, minutes, seconds)
21 |
22 |
23 |
--------------------------------------------------------------------------------