├── .gitattributes
├── .github
└── workflows
│ └── dispatch.yml
├── .gitignore
├── LICENSE
├── README.md
├── images
└── force-udf.png
├── python
├── __init__.py
├── ard
│ ├── __init__.py
│ ├── exposed_soil
│ │ ├── exp_soil.py
│ │ └── readme.md
│ ├── max_ndvi
│ │ ├── max_ndvi.py
│ │ └── readme.md
│ └── medoid
│ │ ├── __init__.py
│ │ ├── medoid.py
│ │ ├── readme.md
│ │ └── requirements.txt
├── test_udf
│ ├── __init__.py
│ ├── test.py
│ ├── test_ard_medoid_block_numba.py
│ ├── test_ard_medoid_pixel_simple.py
│ ├── test_ts_clear_observation_sequence.py
│ ├── test_utils.py
│ └── utils.py
└── ts
│ ├── __init__.py
│ ├── dynamic-habitat-indices
│ ├── dhi.py
│ └── readme.md
│ ├── harmonic-fit
│ ├── __init__.py
│ ├── harmonic.py
│ ├── readme.md
│ └── test_ts_harmonic.py
│ └── mowingDetection
│ ├── mowingDetection_UDF.py
│ ├── profileAnalytics.JPG
│ ├── profileAnalytics_broken.JPG
│ ├── readme.md
│ ├── scheme.jpg
│ └── visualize_mowingDetection_UDF.py
└── rstats
├── ard
└── .gitkeep
└── ts
├── .gitkeep
├── dynamic-habitat-indices
├── dhi.r
└── readme.md
└── spline-reconstruction
├── Bolten_Spline_FORCE_UDF.R
└── readme.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Set the default behavior, in case people don't have core.autocrlf set.
2 | * text eol=lf
3 |
4 | # Explicitly declare text files you want to always be normalized and converted
5 | # to native line endings on checkout.
6 | *.py text
7 | *.md text
8 | *.r text
9 | *.R text
10 |
11 | # Denote all files that are truly binary and should not be modified.
12 | *.png binary
13 | *.jpg binary
14 | *.tif binary
15 | *.gif binary
16 |
17 |
--------------------------------------------------------------------------------
/.github/workflows/dispatch.yml:
--------------------------------------------------------------------------------
1 | name: dispatch to FORCE
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 |
7 | jobs:
8 | dispatch:
9 | runs-on: ubuntu-latest
10 | steps:
11 | - name: Repository Dispatch
12 | uses: peter-evans/repository-dispatch@v3
13 | with:
14 | token: ${{ secrets.DISPATCH }}
15 | repository: davidfrantz/force
16 | event-type: udf-dispatch
17 |
--------------------------------------------------------------------------------
/.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 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
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 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 | python/test_udf/BLU_TSS.tif
131 | python/test_udf/BLU_TSS.tif.aux.xml
132 | python/test_udf/GRN_TSS.tif
133 | python/test_udf/GRN_TSS.tif.aux.xml
134 | python/test_udf/NIR_TSS.tif
135 | python/test_udf/NIR_TSS.tif.aux.xml
136 | python/test_udf/RED_TSS.tif
137 | python/test_udf/RED_TSS.tif.aux.xml
138 | python/test_udf/SW1_TSS.tif
139 | python/test_udf/SW1_TSS.tif.aux.xml
140 | python/test_udf/SW2_TSS.tif
141 | python/test_udf/SW2_TSS.tif.aux.xml
142 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # FORCE UDF
2 |
3 | **User-Defined Functions for FORCE**
4 |
5 | 
6 |
7 | This repository collects *user-defined functions* (**UDF**) that can be plugged into [FORCE](https://github.com/davidfrantz/force).
8 |
9 | **Everybody** is encouraged to push their UDFs to this repository, such that the community as a whole benefits and has access to a broad variety of workflows.
10 |
11 | This extra step of publishing your workflow is a small step to overcome the ["*Valley of Death*"](https://twitter.com/gcamara/status/1127887595168514049) in Earth observation applications! Only a minimal documentation is needed, see [this example](https://github.com/davidfrantz/force-udf/blob/main/python/ard/medoid/readme.md).
12 |
13 | Supported are UDFs written in **Python** (needs FORCE v. >= 3.7.0) and **R** (needs FORCE v. >= 3.11.0).
14 |
15 | Tutorials [here (Python)](https://force-eo.readthedocs.io/en/latest/howto/udf_py.html) and [here (R).](https://force-eo.readthedocs.io/en/latest/howto/udf_r.html).
--------------------------------------------------------------------------------
/images/force-udf.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/images/force-udf.png
--------------------------------------------------------------------------------
/python/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/python/__init__.py
--------------------------------------------------------------------------------
/python/ard/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/python/ard/__init__.py
--------------------------------------------------------------------------------
/python/ard/exposed_soil/exp_soil.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | """
4 | >>> Copyright (C) 2022, Max Gerhards, Henning Buddenbaum, David Frantz
5 | """
6 |
7 | def forcepy_init(dates, sensors, bandnames):
8 | """
9 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
10 | sensors: numpy.ndarray[nDates](str)
11 | bandnames: numpy.ndarray[nBands](str)
12 | """
13 |
14 | return bandnames
15 |
16 |
17 | def forcepy_pixel(inarray, outarray, dates, sensors, bandnames, nodata, nproc):
18 | """
19 | inarray: numpy.ndarray[nDates, nBands, nrows, ncols](Int16), nrows & ncols always 1
20 | outarray: numpy.ndarray[nOutBands](Int16) initialized with no data values
21 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
22 | sensors: numpy.ndarray[nDates](str)
23 | bandnames: numpy.ndarray[nBands](str)
24 | nodata: int
25 | nproc: number of allowed processes/threads (always 1)
26 | Write results into outarray.
27 | """
28 |
29 | # remove nodata
30 | inarray = inarray[:, :, 0, 0]
31 | valid = np.where(inarray[:, 0] != nodata)[0] # skip no data; just check first band
32 | if len(valid) == 0:
33 | return
34 |
35 | # subset
36 | vals = inarray[valid,:]
37 |
38 | # band indices
39 | green = np.argwhere(bandnames == b'GREEN')[0][0]
40 | red = np.argwhere(bandnames == b'RED')[0][0]
41 | nir = np.argwhere(bandnames == b'NIR')[0][0]
42 | swir1 = np.argwhere(bandnames == b'SWIR1')[0][0]
43 |
44 | # remove "high" NDVI
45 | ndvi = (vals[:,nir]-vals[:,red]) / (vals[:,nir]+vals[:,red])
46 | valid = np.where(ndvi < 0.3)[0]
47 | if len(valid) == 0:
48 | return
49 |
50 | # subset again
51 | vals = vals[valid,:]
52 |
53 | # Dry Bare Soil Index, Rasul et al. 2018
54 | inds = ((vals[:,swir1]-vals[:,green]) / (vals[:,swir1]+vals[:,green])) - ((vals[:,nir]-vals[:,red]) / (vals[:,nir]+vals[:,red]))
55 |
56 | if np.all(inds == 0):
57 | return
58 |
59 | # weighted average
60 | # there still is an error when weights are 0. Need to fix
61 | outarray[:] = np.average(vals, weights = inds, axis = 0)
62 |
--------------------------------------------------------------------------------
/python/ard/exposed_soil/readme.md:
--------------------------------------------------------------------------------
1 | # Exposed soil synthesis image
2 |
3 | ©
4 | Copyright 2022, Max Gerhards, Henning Buddenbaum, David Frantz
5 |
6 | ## Run with
7 |
8 | - program: ``force-higher-level``
9 | - submodule: ``UDF``
10 | - UDF type: ``PYTHON_TYPE = PIXEL``
11 | - required parameters: ``none``
12 | - required Python libraries: ``numpy``
13 |
14 |
--------------------------------------------------------------------------------
/python/ard/max_ndvi/max_ndvi.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | """
4 | >>> Copyright (C) 2021-2022, Franz Schug, David Frantz
5 | """
6 |
7 | def forcepy_init(dates, sensors, bandnames):
8 | """
9 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
10 | sensors: numpy.ndarray[nDates](str)
11 | bandnames: numpy.ndarray[nBands](str)
12 | """
13 |
14 | return bandnames
15 |
16 |
17 | def forcepy_pixel(inarray, outarray, dates, sensors, bandnames, nodata, nproc):
18 | """
19 | inarray: numpy.ndarray[nDates, nBands, nrows, ncols](Int16), nrows & ncols always 1
20 | outarray: numpy.ndarray[nOutBands](Int16) initialized with no data values
21 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
22 | sensors: numpy.ndarray[nDates](str)
23 | bandnames: numpy.ndarray[nBands](str)
24 | nodata: int
25 | nproc: number of allowed processes/threads (always 1)
26 | Write results into outarray.
27 | """
28 |
29 |
30 | # remove nodata
31 | inarray = inarray[:, :, 0, 0]
32 | valid = np.where(inarray[:, 0] != nodata)[0] # skip no data; just check first band
33 | if len(valid) == 0:
34 | return
35 |
36 | # subset
37 | vals = inarray[valid,:]
38 |
39 | # NDVI
40 | red = np.argwhere(bandnames == b'RED')[0][0]
41 | nir = np.argwhere(bandnames == b'NIR')[0][0]
42 | ndvi = (vals[:,nir]-vals[:,red]) / (vals[:,nir]+vals[:,red])
43 |
44 | outarray[:] = vals[np.argmax(ndvi),:]
45 |
--------------------------------------------------------------------------------
/python/ard/max_ndvi/readme.md:
--------------------------------------------------------------------------------
1 | # Maximum NDVI composite
2 |
3 | ©
4 | Copyright 2021-2022, Franz Schug, David Frantz
5 |
6 | ## Run with
7 |
8 | - program: ``force-higher-level``
9 | - submodule: ``UDF``
10 | - UDF type: ``PYTHON_TYPE = PIXEL``
11 | - required parameters: ``none``
12 | - required Python libraries: ``numpy``
13 |
14 |
--------------------------------------------------------------------------------
/python/ard/medoid/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/python/ard/medoid/__init__.py
--------------------------------------------------------------------------------
/python/ard/medoid/medoid.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from scipy.spatial.distance import squareform, pdist
3 |
4 | """
5 | >>> Medoid
6 | >>> Copyright (C) 2021 Andreas Rabe
7 | """
8 |
9 | def forcepy_init(dates, sensors, bandnames):
10 | """
11 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
12 | sensors: numpy.ndarray[nDates](str)
13 | bandnames: numpy.ndarray[nBands](str)
14 | """
15 |
16 | return bandnames
17 |
18 |
19 | def forcepy_pixel(inarray, outarray, dates, sensors, bandnames, nodata, nproc):
20 | """
21 | inarray: numpy.ndarray[nDates, nBands, nrows, ncols](Int16), nrows & ncols always 1
22 | outarray: numpy.ndarray[nOutBands](Int16) initialized with no data values
23 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
24 | sensors: numpy.ndarray[nDates](str)
25 | bandnames: numpy.ndarray[nBands](str)
26 | nodata: int
27 | nproc: number of allowed processes/threads (always 1)
28 | Write results into outarray.
29 | """
30 |
31 | inarray = inarray[:, :, 0, 0]
32 | valid = np.where(inarray[:, 0] != nodata)[0] # skip no data; just check first band
33 | if len(valid) == 0:
34 | return
35 | pairwiseDistancesSparse = pdist(inarray[valid], 'euclidean')
36 | pairwiseDistances = squareform(pairwiseDistancesSparse)
37 | cumulativDistance = np.sum(pairwiseDistances, axis=0)
38 | argMedoid = valid[np.argmin(cumulativDistance)]
39 | medoid = inarray[argMedoid, :]
40 | outarray[:] = medoid
41 |
--------------------------------------------------------------------------------
/python/ard/medoid/readme.md:
--------------------------------------------------------------------------------
1 | # Medoid
2 |
3 | ©
4 | Copyright 2021, Andreas Rabe
5 |
6 | ## Run with
7 |
8 | - program: ``force-higher-level``
9 | - submodule: ``PLG``
10 | - UDF type: ``PYTHON_TYPE = PIXEL``
11 | - required parameters: ``none``
12 | - required Python libraries: ``numpy, scipy``
13 |
14 | ## References
15 |
16 | - Flood, N. (2013): **Seasonal Composite Landsat TM/ETM+ Images Using the Medoid (a Multi-Dimensional Median)**. *Remote Sensing 5(12)*, 6481-6500; [10.3390/rs5126481](https://doi.org/10.3390/rs5126481)
17 | - [wikipedia](https://en.wikipedia.org/wiki/Medoid)
18 |
--------------------------------------------------------------------------------
/python/ard/medoid/requirements.txt:
--------------------------------------------------------------------------------
1 | scipy
--------------------------------------------------------------------------------
/python/test_udf/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/python/test_udf/__init__.py
--------------------------------------------------------------------------------
/python/test_udf/test.py:
--------------------------------------------------------------------------------
1 | from os import listdir
2 | from os.path import join, dirname, exists
3 | from unittest import TestCase
4 | import numpy as np
5 | from osgeo import gdal
6 | from numba import jit, prange, set_num_threads
7 |
8 | from ard.medoid.pixel_simple.medoid import forcepy_pixel as ardPixelSimple_Medoid
9 | from ard.medoid.block_numba.medoid import forcepy_block as ardBlockNumba_Medoid
10 | from ts.clear_observation_sequence.clear_observation_sequence \
11 | import forcepy_pixel as tsPixelNumba_ClearObservationSequence
12 |
13 | from enmapboxprocessing.driver import Driver
14 | from enmapboxprocessing.rasterreader import RasterReader
15 | from enmapboxprocessing.utils import Utils as EnmapboxProcessingUtils
16 |
17 |
18 | class TestPixelSimpleMedoid(TestCase):
19 |
20 | def test_handmadePixel(self):
21 | nodata = -9999
22 | inarray = np.array([[0, 0], [0, 10], [10, 0], [10, 10], [5, 5]], dtype=np.int16)
23 | inarray = np.concatenate([inarray, inarray * 0 + nodata, inarray * 0 + nodata]) # add a lot of no data pixel
24 | outarray = np.array([nodata, nodata], dtype=np.int16)
25 | ardPixelSimple_Medoid(inarray, outarray, None, None, None, nodata, 1)
26 | assert np.all(outarray == (5, 5))
27 |
28 | def test_realPixel(self):
29 | nodata = -9999
30 | inarray = np.array([[0, 0], [0, 10], [10, 0], [10, 10], [5, 5]], dtype=np.int16)
31 | inarray = np.concatenate([inarray, inarray * 0 + nodata, inarray * 0 + nodata]) # add a lot of no data pixel
32 | outarray = np.array([nodata, nodata], dtype=np.int16)
33 | ardPixelSimple_Medoid(inarray, outarray, None, None, None, nodata, 1)
34 | assert np.all(outarray == (5, 5))
35 | print(Utils.ardBlock())
36 |
37 |
38 | class TestBlockNumbaMedoid(TestCase):
39 |
40 | def test_handmadeBlock(self):
41 | nodata = -9999
42 | inarray = np.array([[0, 0], [0, 10], [10, 0], [10, 10], [5, 5]], dtype=np.int16)
43 | inarray = np.concatenate([inarray * 0 + nodata, inarray, inarray * 0 + nodata]) # add no data pixel
44 | nDates, nBands = inarray.shape
45 | nY, nX = 300, 300
46 | inarray = inarray.reshape((nDates, nBands, 1, 1)) * np.ones((nDates, nBands, nY, nX), dtype=np.int16)
47 | outarray = np.full((nBands, nY, nX), nodata, dtype=np.int16)
48 | nproc = 4
49 | ardBlockNumba_Medoid(inarray, outarray, None, None, None, nodata, nproc)
50 | print('Done', outarray)
51 | assert np.all(outarray == np.full_like(outarray, 5))
52 |
53 |
54 | class TestCompleteTile(TestCase):
55 |
56 | def setUp(self):
57 | self.nproc = 8
58 | self.nodata = -9999
59 | self.inarrayBoa, self.dates, self.sensors, self.extent, self.crs = Utils.boaBlock()
60 | self.inarrayNdvi = Utils.ndviBlock(self.inarrayBoa)
61 | self.nDates, self.nBands, self.nY, self.nX = self.inarrayBoa.shape
62 |
63 | def test_blockNumba_Medoid(self):
64 |
65 | self.outarray = np.full((self.nBands, self.nY, self.nX), self.nodata, dtype=np.int16)
66 |
67 | ardBlockNumba_Medoid(self.inarrayBoa, self.outarray, self.dates, None, None, self.nodata, self.nproc)
68 | self.assertEqual(65343043, self.outarray.flatten()[::100].sum())
69 | self.filename = 'c:/vsimem/blockNumba_Medoid.tif'
70 |
71 | def test_pixelNumba_ClearObservationSequence(self):
72 | self.outarray = np.full((self.nDates * 5, self.nY, self.nX), self.nodata, dtype=np.int16)
73 | self.bandNames = list()
74 | for date, sensor in zip(self.dates, self.sensors):
75 | datestamp = str(np.datetime64('1970-01-01') + np.timedelta64(date, 'D')).replace('-', '')
76 | for name in ['COS-1', 'COS0', 'COS+1', 'COS-1_DTIME', 'COS1_DTIME']:
77 | self.bandNames.append(f'{name}_NDV_{datestamp}_{sensor}')
78 | [print(n) for n in self.bandNames]
79 | utilsMapPixelNumba(
80 | tsPixelNumba_ClearObservationSequence, self.inarrayNdvi, self.outarray, self.dates, None, None, self.nodata,
81 | self.nproc
82 | )
83 | #self.assertEqual(1, self.outarray.flatten()[::100].sum())
84 | self.filename = 'c:/vsimem/pixelNumba_ClearObservationSequence.tif'
85 |
86 | def tearDown(self):
87 | print('write data')
88 | print(self.outarray.shape)
89 | writer = Driver(self.filename).createFromArray(self.outarray, extent=self.extent, crs=self.crs)
90 | for bandNo, bandName in enumerate(self.bandNames, 1):
91 | writer.setBandName(bandName, bandNo)
92 | writer.setNoDataValue(-9999)
93 | print('created', self.filename)
94 |
95 |
96 | class Utils(object):
97 |
98 | @classmethod
99 | def ndviBlock(cls, arrayBoa):
100 | red = arrayBoa[:, 2:3]
101 | nir = arrayBoa[:, 3:4]
102 | ndvi = np.clip((nir - red) / (nir + red) * 10000, -10000, 10000)
103 | ndvi[red == -9999] = -9999
104 | ndvi = ndvi.astype(np.int16)
105 | return ndvi
106 |
107 | @classmethod
108 | def boaBlock(cls):
109 |
110 | pickleFilename = join(dirname(__file__), 'ard_block.dat')
111 | print('read data')
112 | if not exists(pickleFilename):
113 | noData = -9999
114 | xsize, ysize = 1000, 100
115 | # test qai masking
116 | # reader = RasterReader('C:/Work/data/FORCE/deu/ard/X0069_Y0043/20190102_LEVEL2_SEN2B_QAI.tif')
117 | # qai = reader.gdalDataset.ReadAsArray(buf_xsize=100, buf_ysize=100)
118 | # Driver('c:/vsimem/mask.tif').createFromArray(mask[None], extent=reader.extent(), crs=reader.crs())
119 |
120 | rootArd = r'C:\Work\data\FORCE\deu\ard\X0069_Y0043'
121 | array = list()
122 | dates = list()
123 | sensors = list()
124 | for name in listdir(rootArd):
125 | if name.endswith('BOA.tif') and name:
126 | date = np.datetime64(f'{name[:4]}-{name[4:6]}-{name[6:8]}')
127 | sensor = name[16:21]
128 | dates.append(date)
129 | sensors.append(sensor)
130 | print('read', name, sensor)
131 | if 'LND' in name:
132 | bandList = [1, 2, 3, 4, 5, 6]
133 | elif 'SEN2' in name:
134 | bandList = [1, 2, 3, 8, 9, 10]
135 | else:
136 | assert 0
137 |
138 | ds: gdal.Dataset = gdal.Open(join(rootArd, name.replace('BOA', 'QAI')))
139 | qaiArray = ds.ReadAsArray(buf_xsize=xsize, buf_ysize=ysize)
140 | bit, code, mask = 1, 0, 3 # gives CloudState = clear
141 | cloudfree = np.right_shift(qaiArray, bit) & mask == code
142 | bit, code, mask = 3, 0, 1 # gives CloudShadow = no
143 | noshadow = np.right_shift(qaiArray, bit) & mask == code
144 | invalid = np.logical_not(np.logical_and(cloudfree, noshadow))
145 |
146 | ds: gdal.Dataset = gdal.Open(join(rootArd, name))
147 | boaArray = list()
148 | for bandNo in bandList:
149 | boaBandArray = ds.GetRasterBand(bandNo).ReadAsArray(buf_xsize=xsize, buf_ysize=ysize)
150 | boaBandArray[invalid] = noData
151 | boaArray.append(boaBandArray)
152 | array.append(boaArray)
153 | #if len(dates) == 5: break
154 | array = np.array(array, dtype=np.int16)
155 | assert dates == sorted(dates)
156 | dates = np.array([(date - np.datetime64('1970-01-01')).item().days for date in dates])
157 | sensors = np.array(sensors)
158 | anyInputFilename = join(rootArd, name)
159 | EnmapboxProcessingUtils.pickleDump((array, dates, sensors, anyInputFilename), filename=pickleFilename)
160 | else:
161 | array, dates, sensors, anyInputFilename = EnmapboxProcessingUtils.pickleLoad(filename=pickleFilename)
162 |
163 | print(array.shape)
164 | reader = RasterReader(anyInputFilename)
165 | return array, dates, sensors, reader.extent(), reader.crs()
166 |
167 |
168 | @jit(nopython=True, nogil=True, parallel=True)
169 | def utilsMapPixelNumba(f, inblock, outblock, dates, sensors, bandnames, nodata, nproc):
170 | set_num_threads(nproc)
171 |
172 | nDates, nBands, nY, nX = inblock.shape
173 | for iYX in prange(nY * nX):
174 | iX = iYX % nX
175 | iY = iYX // nX
176 | inarray = inblock[:, :, iY, iX]
177 | outarray = outblock[:, iY, iX]
178 | f(inarray, outarray, dates, sensors, bandnames, nodata, nproc)
179 |
--------------------------------------------------------------------------------
/python/test_udf/test_ard_medoid_block_numba.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | import numpy as np
3 |
4 | from .utils import Utils
5 |
6 | from ard.medoid.block_numba.medoid import forcepy_block, forcepy_init
7 |
8 | nodata = Utils.NO_DATA
9 |
10 |
11 | class TestArdBlockNumba_Medoid(TestCase):
12 |
13 | def test_handmade(self):
14 | inarray = np.array([[0, 0], [0, 10], [10, 0], [10, 10], [5, 5]], dtype=np.int16)
15 | inarray = np.concatenate([inarray * 0 + nodata, inarray, inarray * 0 + nodata]) # add no data pixel
16 | nDates, nBands = inarray.shape
17 | nY, nX = 300, 300
18 | inarray = inarray.reshape((nDates, nBands, 1, 1)) * np.ones((nDates, nBands, nY, nX), dtype=np.int16)
19 | outarray = np.full((nBands, nY, nX), nodata, dtype=np.int16)
20 | nproc = 4
21 | forcepy_block(inarray, outarray, None, None, None, nodata, nproc)
22 | self.assertTrue(np.all(outarray == np.full_like(outarray, 5)))
23 |
24 | def test_noData(self):
25 | inarray = np.array([[nodata, nodata]], dtype=np.int16).reshape((1, 2, 1, 1))
26 | outarray = np.array([nodata, nodata], dtype=np.int16).reshape((2, 1, 1))
27 | forcepy_block(inarray, outarray, None, None, None, nodata, 1)
28 | self.assertTrue(np.all(outarray == nodata))
29 |
30 | def test_applyToRaster(self):
31 | outarray = Utils.applyBlockUdf(
32 | 'c:/vsimem/blockNumba_Medoid.tif', forcepy_init, forcepy_block, '20190101', '20191231'
33 | )
34 | self.assertEqual(631050686, outarray.flatten().sum())
35 |
--------------------------------------------------------------------------------
/python/test_udf/test_ard_medoid_pixel_simple.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | import numpy as np
3 |
4 | from .utils import Utils
5 |
6 | from ard.medoid.pixel_simple.medoid import forcepy_pixel, forcepy_init
7 |
8 |
9 | class TestArdPixelSimple_Medoid(TestCase):
10 |
11 | def test_handmade(self):
12 | nodata = -9999
13 | inarray = np.array([[0, 0], [0, 10], [10, 0], [10, 10], [5, 5]], dtype=np.int16)
14 | nDates, nBands = inarray.shape
15 | inarray = inarray.reshape((nDates, nBands, 1, 1))
16 | outarray = np.full((nBands), nodata, dtype=np.int16)
17 | forcepy_pixel(inarray, outarray, None, None, None, nodata, None)
18 | self.assertTrue(np.all(outarray == np.full_like(outarray, 5)))
19 |
20 | def test_applyToRaster(self):
21 | outarray = Utils.applyPixelSimpleUdf(
22 | 'c:/vsimem/pixelSimple_Medoid.tif', forcepy_init, forcepy_pixel, '20190101', '20191231'
23 | )
24 | self.assertEqual(648523542, outarray.flatten().sum())
25 |
--------------------------------------------------------------------------------
/python/test_udf/test_ts_clear_observation_sequence.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | import numpy as np
3 |
4 | from .utils import Utils
5 |
6 | from ts.clear_observation_sequence.clear_observation_sequence import forcepy_block, forcepy_init
7 |
8 | nodata = Utils.NO_DATA
9 |
10 |
11 | class TestTsBlockNumba_ClearObservationSequence(TestCase):
12 |
13 | def test_handmade(self):
14 | assert 0
15 |
16 | def test_applyToRaster(self):
17 | outarray = Utils.applyNdviBlockUdf(
18 | 'c:/vsimem/blockNumba_ClearObservationSequence.tif', forcepy_init, forcepy_block, '20190101', '20191231'
19 | )
20 | self.assertEqual(631050686, outarray.flatten().sum())
21 |
--------------------------------------------------------------------------------
/python/test_udf/test_utils.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | from test_udf.utils import Utils
4 |
5 |
6 | class TestUtils(TestCase):
7 |
8 | def test_createTestRaster(self):
9 | Utils.createTestRaster()
10 |
11 | def test_boaBlock(self):
12 | boaArray, dates, sensors, bandNames = Utils.boaBlock(dateMin='19810101', dateMax='19841231')
13 | self.assertEqual(4, boaArray.ndim)
14 | self.assertEqual((14, 6, 100, 1000), boaArray.shape)
15 |
16 | def test_ndviBlock(self):
17 | boaArray, dates, sensors, bandNames = Utils.boaBlock(dateMin='19810101', dateMax='19841231')
18 | ndviArray = Utils.ndviBlock(boaArray)
19 | self.assertEqual((14, 1, 100, 1000), ndviArray.shape)
20 |
--------------------------------------------------------------------------------
/python/test_udf/utils.py:
--------------------------------------------------------------------------------
1 | import builtins
2 | from datetime import date as Date
3 | from multiprocessing.pool import Pool
4 | from os import listdir
5 | from os.path import join, dirname, exists, abspath
6 | from warnings import warn
7 |
8 | import numpy as np
9 | from osgeo import gdal
10 | from numba import jit, prange, set_num_threads
11 | from qgis._core import QgsRectangle, QgsCoordinateReferenceSystem, QgsRasterLayer
12 |
13 | from enmapboxprocessing.driver import Driver
14 | from enmapboxprocessing.rasterreader import RasterReader
15 |
16 |
17 | class Utils(object):
18 | TILE_DIRECTORY = r'\\141.20.140.222\dagobah\dc\deu\ard\X0069_Y0043'
19 | TILE_DIRECTORY = r'C:\Work\data\FORCE\deu\ts\X0069_Y0043'
20 | TSS_DIRNAME = dirname(__file__)
21 | BOA_NAMES1 = ['BLU', 'GRN', 'RED', 'NIR', 'SW1', 'SW2']
22 | BOA_NAMES2 = ['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2']
23 | NO_DATA = -9999
24 |
25 | #CRS = QgsCoordinateReferenceSystem('EPSG:3035')
26 | #EXTENT = QgsRectangle(
27 | # 4526026.36304164957255125, 3266319.60796480439603329, 4556026.36304164957255125, 3269319.60796480439603329
28 | #)
29 | NPROC = 8
30 |
31 | @classmethod
32 | def applyPixelNumbaUdf(cls, filename, udf_init, udf_pixel, dateMin, dateMax, sensorFilter=None):
33 | inarray, dates, sensors = cls.boaBlock(dateMin, dateMax, sensorFilter)
34 | bandNames = np.array(udf_init(dates, sensors, Utils.BOA_NAMES2))
35 | outarray = Utils.outBlock(len(bandNames), *inarray.shape[-2:])
36 | mapPixelNumba(udf_pixel, inarray, outarray, dates, sensors, bandNames, cls.NO_DATA, cls.NPROC)
37 | cls.writeOutput(outarray, bandNames, filename)
38 | return outarray
39 |
40 | @classmethod
41 | def applyPixelSimpleUdf(cls, filename, udf_init, udf_pixel, dateMin, dateMax, sensorFilter=None):
42 | inarray, dates, sensors = cls.boaBlock(dateMin, dateMax, sensorFilter)
43 | bandNames = np.array(udf_init(dates, sensors, Utils.BOA_NAMES2))
44 | outarray = Utils.outBlock(len(bandNames), *inarray.shape[-2:])
45 | mapPixelSimple(udf_pixel, inarray, outarray, dates, sensors, bandNames, cls.NO_DATA, cls.NPROC)
46 | cls.writeOutput(outarray, bandNames, filename)
47 | return outarray
48 |
49 | @classmethod
50 | def applyBlockUdf(cls, filename, udf_init, udf_block, dateMin, dateMax, sensorFilter=None):
51 | inarray, dates, sensors = cls.boaBlock(dateMin, dateMax, sensorFilter)
52 | bandNames = udf_init(dates, sensors, cls.BOA_NAMES2)
53 | outarray = cls.outBlock(len(bandNames), *inarray.shape[-2:])
54 | udf_block(inarray, outarray, dates, None, None, cls.NO_DATA, cls.NPROC)
55 | cls.writeOutput(outarray, bandNames, filename)
56 | return outarray
57 |
58 | @classmethod
59 | def applyNdviBlockUdf(cls, filename, udf_init, udf_block, dateMin, dateMax, sensorFilter=None):
60 | inarray, dates, sensors = cls.boaBlock(dateMin, dateMax, sensorFilter)
61 | inarray = cls.ndviBlock(inarray)
62 | bandNames = udf_init(dates, sensors, ['NDVI'])
63 | outarray = cls.outBlock(len(bandNames), *inarray.shape[-2:])
64 | udf_block(inarray, outarray, dates, None, None, cls.NO_DATA, cls.NPROC)
65 | cls.writeOutput(outarray, bandNames, filename)
66 | return outarray
67 |
68 |
69 | @classmethod
70 | def writeOutput(cls, outBlock, bandNames, filename):
71 | layer = QgsRasterLayer(join(cls.TSS_DIRNAME, 'BLU_TSS.tif'))
72 | driver = Driver(filename, 'GTiff', 'INTERLEAVE=BAND COMPRESS=LZW PREDICTOR=2 TILED=YES BIGTIFF=YES'.split())
73 | writer = driver.createFromArray(outBlock, layer.extent(), layer.crs())
74 | for bandNo, bandName in enumerate(bandNames, 1):
75 | writer.setBandName(bandName, bandNo)
76 | writer.setNoDataValue(cls.NO_DATA)
77 |
78 | @classmethod
79 | def outBlock(cls, nBands, nY, nX):
80 | return np.full((nBands, nY, nX), cls.NO_DATA, dtype=np.int16)
81 |
82 | @classmethod
83 | def ndviBlock(cls, arrayBoa):
84 | red = arrayBoa[:, 2:3]
85 | nir = arrayBoa[:, 3:4]
86 | ndvi = np.clip((nir - red) / (nir + red) * 10000, -10000, 10000)
87 | ndvi[red == cls.NO_DATA] = cls.NO_DATA
88 | ndvi = ndvi.astype(np.int16)
89 | return ndvi
90 |
91 | @classmethod
92 | def boaBlock(cls, dateMin, dateMax, sensorFilter=None):
93 | readers = [RasterReader(join(cls.TSS_DIRNAME, name + '_TSS.tif')) for name in cls.BOA_NAMES1]
94 | array = list()
95 | dates = list()
96 | sensors = list()
97 | for bandNo in range(1, readers[0].bandCount() + 1):
98 | name = readers[0].bandName(bandNo)
99 | datestamp = name[:8]
100 | sensor = name[16:21]
101 | if dateMin is not None:
102 | if datestamp < dateMin:
103 | continue
104 | if dateMax is not None:
105 | if datestamp > dateMax:
106 | continue
107 | if sensorFilter is not None:
108 | if sensor not in sensorFilter:
109 | continue
110 | daysSinceEpoch = (Date(int(name[:4]), int(name[4:6]), int(name[6:8])) - Date(1970, 1, 1)).days
111 | dates.append(daysSinceEpoch)
112 | sensors.append(sensor)
113 | for reader in readers:
114 | array.append(reader.array(bandList=[bandNo])[0])
115 | array = np.array(array).reshape((-1, 6, readers[0].height(), readers[0].width()))
116 | dates = np.array(dates, np.int16)
117 | sensors = np.array(sensors)
118 | return array, dates, sensors
119 |
120 | @classmethod
121 | def createTestRaster_OLD(cls):
122 | if exists(cls.ARD_FILENAME):
123 | warn(f'Creation skipped, ARD file already exists: {cls.ARD_FILENAME}')
124 | return
125 |
126 | names = list()
127 | for name in listdir(cls.TILE_DIRECTORY):
128 | if name.endswith('BOA.tif') and name:
129 | names.append(name)
130 | #if len(names) == 3: break
131 |
132 | array = list()
133 | dates = list()
134 | sensors = list()
135 | namesSelected =list()
136 | for name in sorted(names):
137 | date = np.datetime64(f'{name[:4]}-{name[4:6]}-{name[6:8]}')
138 | sensor = name[16:21]
139 | dates.append(date)
140 | sensors.append(sensor)
141 | print('read', name, sensor)
142 | buf_xsize, buf_ysize = 1000, 100
143 | if 'LND' in name:
144 | xoff, yoff = 0, 520
145 | xsize, ysize = 1000, 100
146 | bandList = [1, 2, 3, 4, 5, 6]
147 | elif 'SEN2' in name:
148 | xoff, yoff = 0 * 3, 520 * 3
149 | xsize, ysize = 1000 * 3, 100 * 3
150 | bandList = [1, 2, 3, 8, 9, 10]
151 | else:
152 | assert 0
153 |
154 | ds: gdal.Dataset = gdal.Open(join(cls.TILE_DIRECTORY, name.replace('BOA', 'QAI')))
155 | qaiArray = ds.ReadAsArray(xoff, yoff, xsize, ysize, None, buf_xsize, buf_ysize)
156 |
157 | bit, code, mask = 1, 0, 3 # gives CloudState = clear
158 | valid = np.right_shift(qaiArray, bit) & mask == code
159 |
160 | bit, code, mask = 3, 0, 1 # gives CloudShadow = no
161 | valid = np.logical_and(np.right_shift(qaiArray, bit) & mask == code, valid)
162 |
163 | bit, code, mask = 4, 0, 1 # gives Snow = no
164 | valid = np.logical_and(np.right_shift(qaiArray, bit) & mask == code, valid)
165 |
166 | bit, code, mask = 8, 0, 1 # gives Subzero = no
167 | valid = np.logical_and(np.right_shift(qaiArray, bit) & mask == code, valid)
168 |
169 | bit, code, mask = 9, 0, 1 # gives Saturation = no
170 | valid = np.logical_and(np.right_shift(qaiArray, bit) & mask == code, valid)
171 |
172 | validFraction = np.sum(valid) / buf_xsize * buf_ysize
173 | if validFraction < 0.1:
174 | print('skip', name)
175 | continue
176 |
177 | namesSelected.append(name)
178 |
179 | invalid = np.logical_not(valid)
180 |
181 | ds: gdal.Dataset = gdal.Open(join(cls.TILE_DIRECTORY, name))
182 | for bandNo in bandList:
183 | rb: gdal.Band = ds.GetRasterBand(bandNo)
184 | boaBandArray = rb.ReadAsArray(xoff, yoff, xsize, ysize, buf_xsize, buf_ysize)
185 | boaBandArray[invalid] = cls.NO_DATA
186 | array.append(boaBandArray)
187 |
188 | driver = Driver(
189 | cls.ARD_FILENAME, 'GTiff', 'INTERLEAVE=BAND COMPRESS=LZW PREDICTOR=2 TILED=YES BIGTIFF=YES'.split()
190 | )
191 | writer = driver.createFromArray(array, cls.EXTENT, cls.CRS)
192 | writer.setNoDataValue(cls.NO_DATA)
193 | bandNo = 0
194 | for name in sorted(namesSelected):
195 | for boaName in cls.BOA_NAMES:
196 | bandNo += 1
197 | writer.setBandName(name.replace('BOA.tif', boaName), bandNo)
198 |
199 | @classmethod
200 | def createTestRaster(cls):
201 | if exists(join(cls.TSS_DIRNAME, 'BLU_TSS.tif')):
202 | warn('Creation skipped, TSS files already exists: '+ join(cls.TSS_DIRNAME, '*_TSS.tif'))
203 | return
204 | bandList = list()
205 |
206 | for name in ['BLU', 'GRN', 'RED', 'NIR', 'SW1', 'SW2']:
207 | ds: gdal.Dataset = gdal.Open(join(cls.TILE_DIRECTORY, f'1984-2020_001-365_HL_TSA_LNDLG_{name}_TSS.tif'))
208 | translateOptions = gdal.TranslateOptions(
209 | format='GTiff', bandList=bandList, srcWin=[0, 520, 1000, 100],
210 | creationOptions='INTERLEAVE=BAND COMPRESS=LZW PREDICTOR=2 BIGTIFF=YES'.split()
211 | )
212 | outds: gdal.Dataset = gdal.Translate(join(cls.TSS_DIRNAME, name + '_TSS.tif'), ds, options=translateOptions)
213 | outds.SetMetadata(ds.GetMetadata('FORCE'), 'FORCE')
214 | for bandNo in range(1, ds.RasterCount + 1):
215 | rb: gdal.Band = ds.GetRasterBand(bandNo)
216 | outrb: gdal.Band = outds.GetRasterBand(bandNo)
217 | outrb.SetDescription(rb.GetDescription())
218 | outrb.SetMetadata(rb.GetMetadata('FORCE'), 'FORCE')
219 |
220 |
221 | def mapPixelSimple(f, inblock, outblock, dates, sensors, bandnames, nodata, nproc):
222 |
223 | argss = list()
224 | nDates, nBands, nY, nX = inblock.shape
225 | for iYX in range(nY * nX):
226 | iX = iYX % nX
227 | iY = iYX // nX
228 | inarray = inblock[:, :, iY: iY + 1, iX:iX + 1]
229 | outarray = outblock[:, iY, iX]
230 | f(inarray, outarray, dates, sensors, bandnames, nodata, nproc)
231 |
232 |
233 | @jit(nopython=True, nogil=True, parallel=True)
234 | def mapPixelNumba(f, inblock, outblock, dates, sensors, bandnames, nodata, nproc):
235 | set_num_threads(nproc)
236 |
237 | nDates, nBands, nY, nX = inblock.shape
238 | for iYX in prange(nY * nX):
239 | iX = iYX % nX
240 | iY = iYX // nX
241 | inarray = inblock[:, :, iY: iY + 1, iX:iX + 1]
242 | outarray = outblock[:, iY, iX]
243 | f(inarray, outarray, dates, sensors, bandnames, nodata, nproc)
244 |
--------------------------------------------------------------------------------
/python/ts/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/python/ts/__init__.py
--------------------------------------------------------------------------------
/python/ts/dynamic-habitat-indices/dhi.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import warnings
3 |
4 | """
5 | >>> Dynamic Habitat Indices
6 | >>> Copyright (C) 2021 Andreas Rabe
7 | """
8 |
9 | def forcepy_init(dates, sensors, bandnames):
10 | """
11 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
12 | sensors: numpy.ndarray[nDates](str)
13 | bandnames: numpy.ndarray[nBands](str)
14 | """
15 |
16 | return ['cumulative', 'minimum', 'variation']
17 |
18 |
19 | def forcepy_block(inarray, outarray, dates, sensors, bandnames, nodata, nproc):
20 | """
21 | inarray: numpy.ndarray[nDates, nBands, nrows, ncols](Int16)
22 | outarray: numpy.ndarray[nOutBands](Int16) initialized with no data values
23 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
24 | sensors: numpy.ndarray[nDates](str)
25 | bandnames: numpy.ndarray[nBands](str)
26 | nodata: int
27 | nproc: number of allowed processes/threads
28 | Write results into outarray.
29 | """
30 |
31 | # prepare data
32 | inarray = inarray[:, 0].astype(np.float32) # cast to float ...
33 | invalid = inarray == nodata
34 | if np.all(invalid):
35 | return
36 | inarray[invalid] = np.nan # ... and inject NaN to enable np.nan*-functions
37 |
38 | # calculate DHI
39 | with warnings.catch_warnings():
40 | warnings.simplefilter("ignore", RuntimeWarning)
41 | cumulative = np.nansum(inarray, axis=0) / 1e2
42 | minimum = np.nanmin(inarray, axis=0)
43 | variation = np.nanstd(inarray, axis=0) / np.nanmean(inarray, axis=0) * 1e4
44 |
45 | # store results
46 | for arr, outarr in zip([cumulative, minimum, variation], outarray):
47 | valid = np.isfinite(arr)
48 | outarr[valid] = arr[valid]
49 |
--------------------------------------------------------------------------------
/python/ts/dynamic-habitat-indices/readme.md:
--------------------------------------------------------------------------------
1 | # Dynamic Habitat Indices
2 |
3 | ©
4 | Copyright 2021, Andreas Rabe
5 |
6 | ## Run with
7 |
8 | - program: ``force-higher-level``
9 | - submodule: ``TSA``
10 | - UDF type: ``PYTHON_TYPE = BLOCK``
11 | - required parameters:
12 | - ``INTERPOLATE = RBF`` with very large kernels
13 | - ``DATE_RANGE``: set to one(!) full year
14 | - required Python libraries: ``numpy``
15 |
16 | ## References
17 |
18 | - Radeloff, V. C., M. Dubinin, N. C. Coops, A. Allen, T. M. Brooks, M. Clayton, G. Costa, C. H. Graham, D. Helmers, A. R. Ives, D. Kolesov, A. M. Pidgeon, G. Rapacciuolo, E. Razenkova, N. Suttidate, B. E. Young, L. Zhu, and M. Hobi. (2019): **The Dynamic Habitat Indices (DHIs) from MODIS and global biodiversity**. *Remote Sensing of Environment, 222*, 204-214. [10.1016/j.rse.2018.12.009](https://doi.org/10.1016/j.rse.2018.12.009)
19 | - Hobi, M.L., Dubinin, M., Graham, C.H., Coops, N.C., Clayton, M.K., Pidgeon, A.M., & Radeloff, V.C. (2017): **A comparison of Dynamic Habitat Indices derived from different MODIS products as predictors of avian species richness.** *Remote Sensing of Environment, 195*, 142-152. [10.1016/j.rse.2017.04018](https://doi.org/10.1016/j.rse.2017.04018)
20 |
--------------------------------------------------------------------------------
/python/ts/harmonic-fit/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/python/ts/harmonic-fit/__init__.py
--------------------------------------------------------------------------------
/python/ts/harmonic-fit/harmonic.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime, timedelta
2 |
3 | import numpy as np
4 | from scipy.optimize import curve_fit
5 |
6 | """
7 | >>> Harmonic time series fit
8 | >>> Copyright (C) 2021 Andreas Rabe
9 | """
10 |
11 | # some global config variables
12 | date_start = 16436 # days since epoch (1970-01-01)
13 | date_end = 18627 # days since epoch (1970-01-01)
14 | step = 16 # days
15 |
16 |
17 | def forcepy_init(dates, sensors, bandnames):
18 | """
19 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
20 | sensors: numpy.ndarray[nDates](str)
21 | bandnames: numpy.ndarray[nBands](str)
22 | """
23 |
24 | bandnames = [(datetime(1970, 1, 1) + timedelta(days=days)).strftime('%Y%m%d') + ' sin-interpolation'
25 | for days in range(date_start, date_end, step)]
26 | return bandnames
27 |
28 |
29 | # regressor
30 | # define all three models from the paper
31 | def objective_simple(x, a0, a1, b1, c1):
32 | return a0 + a1 * np.cos(2 * np.pi / 365 * x) + b1 * np.sin(2 * np.pi / 365 * x) + c1 * x
33 |
34 |
35 | def objective_advanced(x, a0, a1, b1, c1, a2, b2):
36 | return objective_simple(x, a0, a1, b1, c1) + a2 * np.cos(4 * np.pi / 365 * x) + b2 * np.sin(4 * np.pi / 365 * x)
37 |
38 |
39 | def objective_full(x, a0, a1, b1, c1, a2, b2, a3, b3):
40 | return objective_advanced(x, a0, a1, b1, c1, a2, b2) + a3 * np.cos(6 * np.pi / 365 * x) + b3 * np.sin(
41 | 6 * np.pi / 365 * x)
42 |
43 |
44 | # - choose which model to use
45 | objective = objective_full
46 |
47 |
48 | def forcepy_pixel(inarray, outarray, dates, sensors, bandnames, nodata, nproc):
49 | """
50 | inarray: numpy.ndarray[nDates, nBands, nrows, ncols](Int16), nrows & ncols always 1
51 | outarray: numpy.ndarray[nOutBands](Int16) initialized with no data values
52 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
53 | sensors: numpy.ndarray[nDates](str)
54 | bandnames: numpy.ndarray[nBands](str)
55 | nodata: int
56 | nproc: number of allowed processes/threads (always 1)
57 | Write results into outarray.
58 | """
59 |
60 | # prepare dataset
61 | profile = inarray.flatten()
62 | valid = profile != nodata
63 | if not np.any(valid):
64 | return
65 | xtrain = dates[valid]
66 | ytrain = profile[valid]
67 |
68 | # fit
69 | popt, _ = curve_fit(objective, xtrain, ytrain)
70 |
71 | # predict
72 | xtest = np.array(range(date_start, date_end, step))
73 | ytest = objective(xtest, *popt)
74 |
75 | outarray[:] = ytest
76 |
--------------------------------------------------------------------------------
/python/ts/harmonic-fit/readme.md:
--------------------------------------------------------------------------------
1 | # Harmonic Time Series fitting
2 |
3 | ©
4 | Copyright 2021, Andreas Rabe
5 |
6 | ## Run with
7 |
8 | - program: ``force-higher-level``
9 | - submodule: ``TSA``
10 | - UDF type: ``PYTHON_TYPE = PIXEL``
11 | - required parameters:``none``
12 | - required Python libraries: ``numpy, scipy``
13 |
14 | ## References
15 |
16 | - Zhu, Z., Woodcock, C.E., Hoden, C., Yang, Z. (2015): **Generating synthetic Landsat images based on all available Landsat data: Predicting Landsat surface reflectance at any given time**. *Remote Sensing of Environment, 162*, 67-83. [10.1016/j.rse.2015.02.009](https://doi.org/10.1016/j.rse.2015.02.009)
17 |
--------------------------------------------------------------------------------
/python/ts/harmonic-fit/test_ts_harmonic.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | # todo this is just a saved version - clean this up!
3 | from scipy.optimize import curve_fit
4 | from harmonic import objective
5 |
6 | def test(): # pure python test
7 | from matplotlib.pylab import plot, show
8 | from test_udf.utils import Utils
9 | boaArray, dates, sensors = Utils.boaBlock(dateMin='20100101', dateMax='20130101') # 3 years of data
10 | ndviArray = Utils.ndviBlock(boaArray)
11 | profile = ndviArray[:, 0, 10, 10].astype(float)
12 | valid = profile != -9999
13 | xtrain = dates[valid]
14 | ytrain = profile[valid]
15 |
16 | # fit
17 | popt, _ = curve_fit(objective, xtrain, ytrain)
18 | print(min(xtrain), max(xtrain))
19 | # predict
20 | xtest = np.linspace(min(xtrain), max(xtrain), 100)
21 | ytest = objective(xtest, *popt)
22 |
23 | plot(xtrain, ytrain, '*')
24 | plot(xtest, ytest, '-')
25 | show()
26 |
27 |
28 | def test2(): # forcepy test
29 | from matplotlib.pylab import plot, show
30 | from test_udf.utils import Utils
31 | boaArray, dates, sensors = Utils.boaBlock(dateMin='20100101', dateMax='20130101') # 3 years of data
32 | ndviArray = Utils.ndviBlock(boaArray)
33 | inarray = ndviArray[:, :, 10:11, 10:11]
34 |
35 | # doit
36 | bandnames = forcepy_init(dates, sensors, Utils.BOA_NAMES1)
37 | outarray = np.full(shape=(len(bandnames), 1, 1), fill_value=-9999)
38 | forcepy_pixel(inarray, outarray, dates, sensors, bandnames, -9999, 1)
39 |
40 | # plot result
41 | profile = inarray.flatten()
42 | valid = profile != -9999
43 | xtrain = dates[valid]
44 | ytrain = profile[valid]
45 | xtest = list(range(date_start, date_end, step))
46 | ytest = outarray.flatten()
47 | plot(xtrain, ytrain, '*')
48 | plot(xtest, ytest, '-')
49 | show()
50 |
51 | if __name__ == '__main__':
52 | test()
53 |
--------------------------------------------------------------------------------
/python/ts/mowingDetection/mowingDetection_UDF.py:
--------------------------------------------------------------------------------
1 | from scipy import interpolate
2 | from datetime import datetime, timedelta
3 | import time
4 | import numpy as np
5 | import warnings
6 |
7 | """
8 | >>> Mowing detection
9 | >>> Copyright (C) 2021 Marcel Schwieder and Max Wesemeyer
10 | """
11 |
12 |
13 | def get_cso(x, y, nodata=-9999, verbose=False, SoS=2018.2, EOS=2018.85):
14 | # if no gap is found it will return 5 days as gap
15 | # in case the last potential observation misses the function calculates the gap to the EOS
16 | if np.all(y == nodata):
17 | nodata_ratio = 0
18 | return nodata_ratio, (x[-1] - x[0])*365, nodata
19 | nodata_sum = np.sum(np.where(y==nodata, True, False))
20 |
21 | nodata_ratio = 1-(nodata_sum/len(y))
22 | data_gap = 0
23 | data_gap_indeces = []
24 | data_gap_dates_list = []
25 | for index, value in enumerate(y):
26 | if value == nodata:
27 | if index < 1:
28 | continue
29 | data_gap += 1
30 | if data_gap == 0:
31 | data_gap_indeces.append(index-1)
32 | data_gap_indeces.append(index)
33 | else:
34 | if len(x[data_gap_indeces]) >= 1:
35 | data_gap_indeces.append(index)
36 | gap_dates = x[data_gap_indeces]
37 | gap_days = (gap_dates[-1]-gap_dates[0])*365
38 | data_gap_dates_list.append(gap_days)
39 | else:
40 | data_gap_dates_list.append(0)
41 | data_gap = 0
42 | data_gap_indeces = []
43 | #########################
44 | # calculating gap to EOS
45 | index_to_end_save = -1
46 | for indeces_to_end in range(1, len(y)):
47 | if y[-indeces_to_end] == nodata:
48 | index_to_end_save = -(indeces_to_end + 1)
49 | continue
50 | else:
51 | break
52 | gap_to_EOS = (EOS - x[index_to_end_save]) * 365
53 | data_gap_dates_list.append(gap_to_EOS)
54 | #########################
55 | # calculating gap to SOS
56 | index_to_start_save = 0
57 | for indeces_to_start in range(len(y)):
58 | if y[indeces_to_start] == nodata:
59 | index_to_start_save = (indeces_to_start + 1)
60 | continue
61 | else:
62 | break
63 | gap_to_SOS = (x[index_to_start_save]-SoS) * 365
64 | data_gap_dates_list.append(gap_to_SOS)
65 | #########################
66 | if int(max(data_gap_dates_list)) == 0:
67 | data_gap_dates_list.append(5)
68 | if verbose:
69 | print(max(data_gap_dates_list), 'MAX GAP')
70 | print(x, y)
71 | return nodata_ratio, max(data_gap_dates_list), len(y)-nodata_sum
72 |
73 |
74 | def toYearFraction(date):
75 |
76 | def sinceEpoch(date): # returns seconds since epoch
77 | return time.mktime(date.timetuple())
78 |
79 | s = sinceEpoch
80 |
81 | year = date.year
82 | startOfThisYear = datetime(year=year, month=1, day=1)
83 | startOfNextYear = datetime(year=year + 1, month=1, day=1)
84 |
85 | yearElapsed = s(date) - s(startOfThisYear)
86 | yearDuration = s(startOfNextYear) - s(startOfThisYear)
87 | fraction = yearElapsed / yearDuration
88 |
89 | return date.year + fraction
90 |
91 |
92 | def detectMow_S2_new(xs, ys, clearWd, yr, type='ConHull', nOrder=3, model='linear'):
93 | warnings.simplefilter('ignore')
94 | another_thrs = 0.15
95 |
96 | Y = np.asarray(ys)/10000
97 | X = np.asarray(xs)
98 |
99 | Season_min_frac = yr + GLstart
100 | Season_max_frac = yr + GLend
101 | Start_frac = yr + PSstart
102 | End_frac = yr + PSend
103 |
104 | if type == 'ConHull':
105 | validIndex = Y < 1
106 | Y = Y[validIndex]
107 | X = X[validIndex]
108 | validIndex_2 = Y > 0
109 | Y = Y[validIndex_2]
110 | X = X[validIndex_2]
111 |
112 | ##############################################
113 | # averages duplicates in the time series
114 | records_array = X
115 | vals, inverse, count = np.unique(records_array, return_inverse=True, return_counts=True)
116 |
117 | idx_vals_repeated = np.where(count > 1)[0]
118 |
119 | vals_repeated = vals[idx_vals_repeated]
120 |
121 | new_x_ = np.unique(X)
122 | new_y_ = np.zeros(shape=vals.shape)
123 | for repeated_value in vals_repeated:
124 | where = np.where(X == repeated_value)
125 | new_y_[np.where(new_x_ == repeated_value)] = np.mean(Y[where])
126 |
127 | rows, cols = np.where(inverse == idx_vals_repeated[:, np.newaxis])
128 |
129 | mask = np.ones(shape=X.shape, dtype=bool)
130 | mask[cols] = False
131 | result = Y[mask]
132 |
133 | mask = np.ones(new_x_.shape, dtype=bool)
134 | mask[idx_vals_repeated] = False
135 | new_y_[mask] = result
136 | Y = new_y_
137 | X = new_x_
138 |
139 | ##############################################
140 |
141 | # filter time series to season (check if needed or a code legacy)
142 | SoGLSdiff = np.abs(X - Season_min_frac)
143 | SoGLS = np.where(SoGLSdiff == np.nanmin(SoGLSdiff))
144 | EoGLS = np.abs(X - Season_max_frac)
145 | EoGLS = np.where(EoGLS == np.nanmin(EoGLS))
146 | Y = np.asarray(Y[SoGLS[0][0]:EoGLS[0][0]])
147 | X = np.asarray(X[SoGLS[0][0]:EoGLS[0][0]])
148 |
149 | # calculate NDVI difference (t1) - (t-1)
150 | yT1 = np.asarray(Y[1:])
151 | yT2 = np.asarray(Y[:-1])
152 |
153 | YDiffzero = [0]
154 | YDiff = yT1 - yT2
155 | YDiff = np.append(YDiffzero, YDiff)
156 |
157 | EVI_STD = np.nanstd(Y)
158 | EVI_mean = np.nanmean(Y)
159 | EVI_obs = sum(~np.isnan(Y))
160 | EVI_obs_pot = EVI_obs / len(Y)
161 |
162 | LoS = int(X[len(X) - 1] * 365 - X[0] * 365)
163 | EVI_obs_potII = EVI_obs / (LoS / 5)
164 |
165 | # identify first peak somewhere around the "mid" of the season
166 | # DOY 120
167 | MoSStart = np.abs(X - Start_frac)
168 | MoSStart = np.where(MoSStart == np.min(MoSStart))
169 |
170 | # DOY 240
171 | MoSEnd = np.abs(X - End_frac)
172 | MoSEnd = np.where(MoSEnd == np.min(MoSEnd))
173 |
174 | YPeakSub = Y[MoSStart[0][0]:MoSEnd[0][0]]
175 |
176 | if len(YPeakSub) == 0:
177 | return
178 |
179 | MoSPeak = np.nanmax(YPeakSub)
180 | MoSIndex = np.where(YPeakSub == MoSPeak)[0][0]
181 | IndexDiff = len(X[0:MoSStart[0][0]])
182 | MoSIndex = MoSIndex + IndexDiff
183 |
184 | earlyIndex2 = []
185 | lateIndex2 = []
186 |
187 | # todo check if early and late peak equals Y0
188 | Y0 = np.argwhere(np.isfinite(Y))
189 | Y0 = np.min(Y0)
190 |
191 | if MoSIndex <= 2:
192 | if MoSIndex == 0:
193 | earlyPeak1 = Y[0]
194 | else:
195 | earlyPeak1 = np.nanmax(Y[0:MoSIndex])
196 | earlyIndex1 = np.min(np.where(Y == earlyPeak1))
197 | else:
198 | searchInd = np.argwhere(X <= X[MoSIndex] - clearWd * 0.00273973)
199 | if np.any(searchInd):
200 | searchInd = searchInd.max()
201 | earlyPeak1 = np.nanmax(Y[0:searchInd])
202 | earlyIndex1 = np.min(np.where(Y == earlyPeak1))
203 | else:
204 | earlyIndex1 = 0
205 |
206 | if MoSIndex + 2 == len(X):
207 | latePeak1 = np.nanmax(Y[MoSIndex + 1:len(X)])
208 | lateIndex1 = np.max(np.where(Y == latePeak1))
209 | else:
210 | searchInd2 = np.argwhere(X >= X[MoSIndex] + clearWd * 0.00273973)
211 | if np.any(searchInd2):
212 | searchInd2 = searchInd2.min()
213 | if searchInd2 != len(X)-1:
214 | latePeak1 = np.nanmax(Y[searchInd2:len(X)-1])
215 | lateIndex1 = np.max(np.where(Y == latePeak1))
216 | else:
217 | lateIndex1 = 0
218 | else:
219 | lateIndex1 = 0
220 |
221 | if (earlyIndex1 != 0) and (earlyIndex1 - 2) > 0 and np.any(Y[0:earlyIndex1 - 2]):
222 | searchInd3 = np.argwhere(X <= X[earlyIndex1] - clearWd * 0.00273973)
223 | if np.any(searchInd3):
224 | searchInd3 = searchInd3.max()
225 | earlyPeak2 = np.nanmax(Y[0:searchInd3])
226 | earlyIndex2 = np.min(np.where(Y == earlyPeak2))
227 |
228 | if (lateIndex1 != 0) and lateIndex1 + 2 <= len(X) and np.any(Y[lateIndex1 + 2:len(X)]):
229 | searchInd4 = np.argwhere(X >= X[lateIndex1] + clearWd * 0.00273973)
230 | if np.any(searchInd4):
231 | searchInd4 = searchInd4.min()
232 | latePeak2 = np.nanmax(Y[searchInd4:len(X)])
233 | lateIndex2 = np.max(np.where(Y == latePeak2))
234 |
235 | Xarr = [X[Y0], X[earlyIndex1], X[MoSIndex], X[lateIndex1], X[len(X) - 1]]
236 | Yarr = [Y[Y0], Y[earlyIndex1], Y[MoSIndex], Y[lateIndex1], Y[len(Y) - 1]]
237 |
238 | if earlyIndex2:
239 | Xarr = [X[Y0], X[earlyIndex2], X[earlyIndex1], X[MoSIndex], X[lateIndex1], X[len(X) - 1]]
240 | Yarr = [Y[Y0], Y[earlyIndex2], Y[earlyIndex1], Y[MoSIndex], Y[lateIndex1], Y[len(Y) - 1]]
241 | if lateIndex2:
242 | Xarr = [X[Y0], X[earlyIndex2], X[earlyIndex1], X[MoSIndex], X[lateIndex1], X[lateIndex2], X[len(X) - 1]]
243 | Yarr = [Y[Y0], Y[earlyIndex2], Y[earlyIndex1], Y[MoSIndex], Y[lateIndex1], Y[lateIndex2], Y[len(Y) - 1]]
244 |
245 | if lateIndex2:
246 | Xarr = [X[Y0], X[earlyIndex1], X[MoSIndex], X[lateIndex1], X[lateIndex2], X[len(X) - 1]]
247 | Yarr = [Y[Y0], Y[earlyIndex1], Y[MoSIndex], Y[lateIndex1], Y[lateIndex2], Y[len(Y) - 1]]
248 | if earlyIndex2:
249 | Xarr = [X[Y0], X[earlyIndex2], X[earlyIndex1], X[MoSIndex], X[lateIndex1], X[lateIndex2], X[len(X) - 1]]
250 | Yarr = [Y[Y0], Y[earlyIndex2], Y[earlyIndex1], Y[MoSIndex], Y[lateIndex1], Y[lateIndex2], Y[len(Y) - 1]]
251 |
252 | if model == 'linear':
253 | # model and fit spline
254 | polyVal = np.interp(X, xp=Xarr, fp=Yarr)
255 |
256 | if model == 'poly':
257 | # model and fit polynom of n-th order
258 | poly = np.polyfit(Xarr, Yarr, nOrder)
259 | polyVal = np.polyval(poly, X)
260 |
261 | if model == 'spline':
262 | tck = interpolate.splrep(x=Xarr, y=Yarr, s=0)
263 |
264 | # predict values with spline and write to array
265 | polyVal = interpolate.splev(X, tck, der=0)
266 |
267 | # difference between polynom and values
268 | diff = np.abs(polyVal - Y)
269 | diff_sum = np.nansum(diff)
270 | diff_mean = np.nanmean(diff)
271 | testVal = diff_sum * EVI_obs_potII
272 |
273 | thresh = diff_mean
274 | NDVIthresh = -EVI_STD
275 | NDVIthresh_list = list(np.random.normal(NDVIthresh, GFstd, 100))
276 |
277 | # create empty array for neighborhood indices
278 | clearWidth = []
279 |
280 | mow_date_index = []
281 | mowingEvents = []
282 | mowingDoy = []
283 |
284 | if len(diff) > 0:
285 | i = 1
286 | for evIndex, ev in enumerate(diff):
287 | ndvi_diff_check = False
288 | NDV_Check_list = [YDiff[evIndex]] * 100
289 | # print(NDVIthresh_list)
290 | result = [a for a, b in zip(NDV_Check_list, NDVIthresh_list) if a < b]
291 |
292 | if len(result) >= posEval:
293 | ndvi_diff_check = True
294 | else:
295 | continue
296 | #ndvi_diff_check = False
297 |
298 | eventDate = X[evIndex]
299 |
300 | if evIndex == len(X)-1:
301 | eventDate_next = X[evIndex] + 1
302 | else:
303 | eventDate_next = X[evIndex + 1]
304 |
305 | if i == 1:
306 | if ev > thresh:
307 | # check NDVI difference and compare to threshold
308 | if ndvi_diff_check:
309 | # check next observation
310 | if eventDate_next - eventDate <= 6 * 0.00273973:
311 | if YDiff[evIndex + 1] > another_thrs:
312 | continue
313 | # get julian date
314 | doy = ((eventDate - yr) * 365) + 1
315 | if doy > 305:
316 | continue
317 | else:
318 | dt = datetime(yr, 1, 1)
319 | dtdelta = timedelta(days=doy)
320 | dates = str(dt + dtdelta)
321 | date = dates[0:10]
322 | mowingEvents.append(date)
323 | mowingDoy.append(np.int(doy))
324 | mow_date_index.append(evIndex)
325 | i = i + 1
326 | else:
327 | if ev > thresh:
328 | dec_date_preceding = X[np.array(mow_date_index)[-1]]
329 | dec_date_current_iter = X[evIndex]
330 | # delta days in decimal format
331 | delta_days = dec_date_current_iter - dec_date_preceding
332 | # clearwd (days) divided by 365 = minimum distance from preceding mowing event as decimal number
333 | clearWd_days = clearWd / 365
334 | if delta_days > clearWd_days:
335 | # if evIndex not in clearWidth:
336 | # date of event when threshold was crossed
337 | eventDate = X[evIndex]
338 | if ndvi_diff_check:
339 | if eventDate_next - eventDate <= 6 * 0.00273973:
340 | if YDiff[evIndex + 1] > another_thrs:
341 | continue
342 | # get julian date
343 | doy = ((eventDate - yr) * 365) + 1
344 | if doy > 305:
345 | continue
346 | else:
347 | #############################
348 | # check if there is one observation that is higher than the preceding between
349 | # two mowing events
350 | time_mask = np.where((X >= X[mow_date_index[-1]]) & (X <= eventDate), True, False)
351 | any_preced_lower = np.any(np.ediff1d(Y[time_mask]) > 0)
352 | # in case there is no increase in EVI values between two mowing events
353 | # "any_preced_lower" will be False
354 | # print('Any observation higher than preceding between DOY ', mowingDoy[-1], 'and ',
355 | # int(doy), '?', any_preced_lower)
356 | #############################
357 | if any_preced_lower:
358 | dt = datetime(yr, 1, 1)
359 | dtdelta = timedelta(days=doy)
360 | dates = str(dt + dtdelta)
361 | date = dates[0:10]
362 | mowingEvents.append(date)
363 | mowingDoy.append(np.int(doy))
364 | mow_date_index.append(evIndex)
365 | i = i + 1
366 | else:
367 | None
368 |
369 | if profileAnalytics:
370 | return mowingEvents, mowingDoy, diff_sum, EVI_obs, EVI_obs_pot, testVal, Xarr, Yarr, X, polyVal
371 | else:
372 | return mowingEvents, mowingDoy, diff_sum, EVI_obs, EVI_obs_pot, testVal
373 |
374 | # new version
375 | def forcepy_init(dates, sensors, bandnames):
376 | """
377 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
378 | sensors: numpy.ndarray[nDates](str)
379 | bandnames: numpy.ndarray[nBands](str)
380 | """
381 | bandnames = ['mowingEvents', 'max_gap_days', 'CSO_ABS', 'Data_Ratio',
382 | 'Mow_1', 'Mow_2', 'Mow_3', 'Mow_4', 'Mow_5', 'Mow_6', 'Mow_7', 'Mean', 'Median', 'SD', 'diff_sum',
383 | 'diff_sum_dataavail', 'Error']
384 |
385 | return bandnames
386 |
387 |
388 | def serial_date_to_string(srl_no):
389 | new_date = datetime(1970,1,1,0,0) + timedelta(int(srl_no) - 1)
390 | return new_date
391 |
392 |
393 | def forcepy_pixel(inarray, outarray, dates, sensors, bandnames, nodata, nproc):
394 | """
395 | inarray: numpy.ndarray[nDates, nBands, nrows, ncols](Int16), nrows & ncols always 1
396 | outarray: numpy.ndarray[nOutBands](Int16) initialized with no data values
397 | dates: numpy.ndarray[nDates](int) days since epoch (1970-01-01)
398 | sensors: numpy.ndarray[nDates](str)
399 | bandnames: numpy.ndarray[nBands](str)
400 | nodata: int
401 | nproc: number of allowed processes/threads (always 1)
402 | Write results into outarray.
403 | """
404 | global GLstart, GLend, GLendII, PSstart, PSend, GFstd, posEval, clrwd, profileAnalytics
405 |
406 | ################# user defined parameters #################
407 | # define if you want to run the UDF in FORCE or display the result of the algorithm per pixel using QGIS-Plugin Profile Analytics
408 | # see details: https://enmap-box.readthedocs.io/en/latest/usr_section/usr_manual/eo4q.html?highlight=profile#profile-analytics
409 | # make sure to append an environmental variable in QGIS following this example:
410 | # Settings --> Options --> System --> Environment: Apply: Append | Variable: PYTHONPATH | Value: PATH\TO\mowingDetection_UDF.py
411 |
412 | profileAnalytics = False
413 |
414 | # define the approximate length of grassland season in which you expect the main mowing activity; in decimal years = DOY / 365; make sure too include a temporal buffer --> here end of December
415 | GLstart = 0.2 # DOY 73
416 | GLend = 1 # DOY 365
417 |
418 | # define end of grassland season
419 | GLendII = 0.85 # DOY
420 |
421 | # define the approximate length of the main vegetation season; i.e., time of the year in which you expect at least one peak
422 | PSstart = 0.33 # DOY 120
423 | PSend = 0.66 # DOY 240
424 |
425 | # adjust sensitivity of thresholds; i.e., width of gaussian function and number of positive evaluations needed
426 | GFstd = 0.02
427 | posEval = 40
428 |
429 | # define minimum distance between two consecutive mowing eventsin days
430 | clrwd = 15
431 | ###########################################################
432 |
433 | np.seterr(all='ignore')
434 | ts = inarray.squeeze()
435 |
436 | nodata = nodata
437 |
438 | all_no_data = np.all(ts == nodata)
439 | all_zero = np.all(ts == 0)
440 |
441 | if all_no_data:
442 | return
443 | elif all_zero:
444 | return
445 | else:
446 |
447 | dateList = []
448 |
449 | if profileAnalytics:
450 | for imgDate in dates:
451 | dateList.append(imgDate)
452 | else:
453 | for imgDate in dates:
454 | dateList.append(serial_date_to_string(imgDate))
455 |
456 | date = np.array(dateList)
457 |
458 | try:
459 | if profileAnalytics:
460 | x = date
461 | else:
462 | x = np.array(list(map(toYearFraction, date)))
463 |
464 | yr = int(str(x[0])[:4])
465 | #################################
466 | # get sd mean median
467 | Season_min_frac = yr + GLstart
468 | Season_max_frac = yr + GLendII
469 | subsetter = np.where((Season_min_frac < x) & (x < Season_max_frac), True, False)
470 |
471 | Y = np.array(ts[subsetter])
472 | X = x[subsetter]
473 | nodata_ratio, max_gap_days, cso_abs = get_cso(X, Y, nodata=nodata, verbose=False, SoS=Season_min_frac, EOS=Season_max_frac)
474 | Y = np.array(ts[subsetter], dtype=np.float)
475 | Y[Y == nodata] = np.nan
476 | mean = np.nanmean(Y)
477 | median = np.nanmedian(Y)
478 | sd = np.nanstd(Y)
479 |
480 | Season_min_frac = yr + GLstart
481 | Season_max_frac = yr + GLend
482 | subsetter = np.where((Season_min_frac < x) & (x < Season_max_frac), True, False)
483 | X = x[subsetter]
484 | Y = ts[subsetter]
485 |
486 | if profileAnalytics:
487 | mowingEvents, mowingDoy, diff_sum, EVI_obs, EVI_obs_pot, diff_sum_dataavail, xPeak, yPeak, xPol, yPol = detectMow_S2_new(
488 | X, Y, clearWd=clrwd, yr=yr, type='ConHull', nOrder=3, model='linear'
489 | )
490 | else:
491 | mowingEvents, mowingDoy, diff_sum, EVI_obs, EVI_obs_pot, diff_sum_dataavail = detectMow_S2_new(
492 | X, Y, clearWd=clrwd, yr=yr, type='ConHull', nOrder=3, model='linear'
493 | )
494 |
495 | mowing_doy_out = [0] * 7
496 |
497 | for index, doys in enumerate(mowing_doy_out):
498 | try:
499 | mowing_doy_out[index] = mowingDoy[index]
500 | except:
501 | break
502 | outarray[:] = [int(len(mowingEvents)), int(max_gap_days), int(cso_abs), int(nodata_ratio * 100),
503 | mowing_doy_out[0],
504 | mowing_doy_out[1], mowing_doy_out[2], mowing_doy_out[3], mowing_doy_out[4],
505 | mowing_doy_out[5], mowing_doy_out[6], mean, median, sd,
506 | int(diff_sum * 100),
507 | int(diff_sum_dataavail * 100), 0]
508 | if profileAnalytics:
509 | return mowingEvents, mowing_doy_out, xPeak, yPeak, xPol, yPol
510 | except:
511 | #print('ERROR')
512 | outarray[-1] = 1
513 |
514 |
515 |
516 | '''
517 | # test data set
518 | if __name__ == '__main__':
519 | profileAnalytics = True
520 |
521 | bandnames = forcepy_init(None, None, None)
522 | sensors = None
523 |
524 | text = '2021.0 7681.0, 2021.013698630137 7813.0, 2021.027397260274 7842.0, 2021.041095890411 7823.0, 2021.054794520548 7670.0, 2021.0684931506848 7567.0, 2021.0821917808219 7237.0, 2021.0958904109589 7237.0, 2021.109589041096 6993.0, 2021.123287671233 6916.0, 2021.13698630137 6863.0, 2021.150684931507 6853.0, 2021.164383561644 6937.0, 2021.1780821917807 7011.0, 2021.1917808219177 7022.0, 2021.2054794520548 7292.0, 2021.2191780821918 7541.0, 2021.2328767123288 7722.0, 2021.2465753424658 7667.0, 2021.2602739726028 7544.0, 2021.2739726027398 7145.0, 2021.2876712328766 7010.0, 2021.3013698630136 7457.0, 2021.3150684931506 7894.0, 2021.3287671232877 7927.0, 2021.3424657534247 7779.0, 2021.3561643835617 7655.0, 2021.3698630136987 7879.0, 2021.3835616438357 7926.0, 2021.3972602739725 8093.0, 2021.4109589041095 7964.0, 2021.4246575342465 7666.0, 2021.4383561643835 7035.0, 2021.4520547945206 7176.0, 2021.4657534246576 7406.0, 2021.4794520547946 7606.0, 2021.4931506849316 7740.0, 2021.5068493150684 7410.0, 2021.5205479452054 7269.0, 2021.5342465753424 7127.0, 2021.5479452054794 7101.0, 2021.5616438356165 7049.0, 2021.5753424657535 6826.0, 2021.5890410958905 6723.0, 2021.6027397260275 6510.0, 2021.6164383561643 6122.0, 2021.6301369863013 5919.0, 2021.6438356164383 6295.0, 2021.6575342465753 6443.0, 2021.6712328767123 7090.0, 2021.6849315068494 6990.0, 2021.6986301369864 6767.0, 2021.7123287671234 6507.0, 2021.7260273972602 6385.0, 2021.7397260273972 6284.0, 2021.7534246575342 6277.0, 2021.7671232876712 6243.0, 2021.7808219178082 6193.0, 2021.7945205479452 5828.0, 2021.8082191780823 5633.0, 2021.8219178082193 5479.0, 2021.835616438356 5426.0, 2021.849315068493 5425.0, 2021.86301369863 5554.0, 2021.876712328767 6390.0, 2021.890410958904 6638.0, 2021.9041095890411 6879.0, 2021.9178082191781 6934.0, 2021.9315068493152 7222.0, 2021.945205479452 7267.0, 2021.958904109589 7528.0, 2021.972602739726 7370.0, 2021.986301369863 7179.0'
525 | text = '2018.035616438356 2983.0, 2018.0849315068492 3342.0, 2018.0986301369862 3106.0, 2018.1041095890412 3160.0, 2018.1178082191782 3011.0, 2018.1178082191782 -9999, 2018.13698630137 2731.0, 2018.145205479452 2857.0, 2018.1616438356164 2782.0, 2018.1671232876713 2572.0, 2018.2054794520548 -9999, 2018.2082191780821 2436.0, 2018.2246575342465 2881.0, 2018.227397260274 -9999, 2018.2493150684932 2825.0, 2018.2493150684932 2890.0, 2018.2630136986302 -9999, 2018.268493150685 3965.0, 2018.268493150685 3975.0, 2018.2904109589042 5382.0, 2018.2931506849316 5290.0, 2018.295890410959 5898.0, 2018.304109589041 -9999, 2018.317808219178 -9999, 2018.323287671233 7505.0, 2018.33698630137 7889.0, 2018.33698630137 8057.0, 2018.345205479452 8228.0, 2018.3506849315067 8488.0, 2018.3643835616438 9036.0, 2018.3780821917808 -9999, 2018.3808219178081 9042.0, 2018.386301369863 9182.0, 2018.3917808219178 -9999, 2018.4 -9999, 2018.4054794520548 9255.0, 2018.4136986301369 -9999, 2018.427397260274 8679.0, 2018.4328767123288 8533.0, 2018.441095890411 8628.0, 2018.495890410959 5672.0, 2018.5013698630137 -9999, 2018.5123287671233 5107.0, 2018.5287671232877 5261.0, 2018.531506849315 6430.0, 2018.5369863013698 6234.0, 2018.5424657534247 6375.0, 2018.5506849315068 -9999, 2018.5561643835617 -9999, 2018.5561643835617 -9999, 2018.5643835616438 6787.0, 2018.5698630136985 7416.0, 2018.5753424657535 7059.0, 2018.5780821917808 7079.0, 2018.5972602739726 7322.0, 2018.6 7888.0, 2018.6109589041096 -9999, 2018.6383561643836 7313.0, 2018.6657534246576 -9999, 2018.6739726027397 -9999, 2018.6794520547944 7208.0, 2018.6876712328767 5541.0, 2018.6876712328767 4451.0, 2018.7150684931507 6746.0, 2018.731506849315 7893.0, 2018.7616438356165 2303.0, 2018.7753424657535 3070.0, 2018.7753424657535 3107.0, 2018.7835616438356 3265.0, 2018.7890410958903 3461.0, 2018.8027397260273 3743.0, 2018.8301369863013 -9999, 2018.8438356164384 -9999, 2018.8794520547945 2259.0, 2018.9068493150685 2873.0, 2018.9068493150685 2686.0, 2018.9260273972602 2832.0, 2018.9260273972602 2874.0'
526 | text = text.replace(', ', ' ').split(' ')
527 | data = np.array(text, float).reshape(-1, 2)
528 | dates = data[:, 0]
529 | inarray = data[:, 1]
530 |
531 | nodata = -9999
532 | nproc = 1
533 | outarray = np.ones(len(bandnames))
534 | result = forcepy_pixel(inarray, outarray, dates, sensors, bandnames, nodata, nproc)
535 | print('Done:', result)
536 | '''
537 |
--------------------------------------------------------------------------------
/python/ts/mowingDetection/profileAnalytics.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/python/ts/mowingDetection/profileAnalytics.JPG
--------------------------------------------------------------------------------
/python/ts/mowingDetection/profileAnalytics_broken.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/python/ts/mowingDetection/profileAnalytics_broken.JPG
--------------------------------------------------------------------------------
/python/ts/mowingDetection/readme.md:
--------------------------------------------------------------------------------
1 | # Mowing detection
2 |
3 | ©
4 | Copyright 2021 Marcel Schwieder and Max Wesemeyer
5 |
6 | This algorithm was developed to estimate mowing events on grasslands from dense vegetation index time series derived from Sentinel-2 and Landsat data.
7 | It was developed and tested for grasslands in Germany (see maps here: https://ows.geo.hu-berlin.de/webviewer/mowing-detection/).
8 | While the thresholds used to identify mowing events are derived from the time series itself, some parameters might be adjusted for your specific
9 | use case. Details regarding the indivídual processing steps are described in the Schwieder et al., 2022 (open accesss).
10 |
11 | 
12 |
13 | # Output
14 | The algorithm is pixel based. The output is a raster stack with 17 bands that contain:
15 |
16 | - B1: Sum of mowing events
17 | - B2: Maximum data gap in original time series
18 | - B3: absolute clear sky observations (CSO)
19 | - B4: CSO/potential observations (*100)
20 | - B5 - B11: DOY of detected mowing events
21 | - B12: Mean VI value of the defined grassland season
22 | - B13: Median VI value of the defined grassland season
23 | - B14: VI standard deviation of the defined grassland season
24 | - B15: Sum of differences between interpolated and original values (*100)
25 | - B16: Sum of differences between interpolated and original values * data availability (*100)
26 | - B17: Processing error [0,1]
27 |
28 | ## Usage
29 |
30 | Run with the FORCE higher-level module and the TSA parameter file. Choose a vegetation index of your choice (tested with EVI and NDVI).
31 | Make sure not to output TSI unless you do not want to analyze the original time series.
32 | It is recommended to not use the above und below noise filters (FORCE TSA), as they might filter out potential mowing events.
33 |
34 | - program: ``force-higher-level``
35 | - submodule: ``TSA``
36 | - UDF type: ``PYTHON_TYPE = PIXEL``
37 | - required parameters: ``none``
38 | - suggested parameters: ``INTERPOLATE = NONE, BELOW_NOISE = 0, ABOVE_NOISE = 0``
39 | - required Python libraries: ``numpy, scipy``
40 |
41 | The following parameters might be changed in the mowingDetection.py UDF (search for the function: detectMow_S2_new):
42 | - GLstart and GLend (defines the approximate length of grassland season in which you expect the main mowing activity; make sure too include a buffer)
43 | - PSstart and PSend (defines the approximate length of the main vegetation season; i.e., time of the year in which you expect at least one peak)
44 | - GFstd and posEval (sensitivity of thresholds; i.e., width of gaussian function and number of positive evaluations)
45 |
46 | ## Visualization
47 |
48 | You can visualize the pixelwise results of the mowingDetection_UDF using the QGIS-Plugin Profile Analytics which comes with the installation of the EnMAP-Box Plugin
49 | (van der Linden et al., 2015; implemented since v.3.12-alpha.2; tested in QGIS 3.26; further details: https://enmap-box.readthedocs.io/en/latest/usr_section/usr_manual/eo4q.html?highlight=profile#profile-analytics).
50 |
51 | Please save a local copy of the UDF and make sure to set ``profileAnalytics = True`` in the main code. Additionally you need to set an environmental variable in QGIS
52 | following this example:
53 |
54 | Settings --> Options --> System --> Environment: ``Apply = Append`` | ``Variable = PYTHONPATH`` | ``Value = ;PATH\TO\mowingDetection_UDF.py``
55 | (Note: Make sure to set the correct separator for appended variables (before the defined path) according to your system; here ";")
56 |
57 | Finally you need to download /force-udf/pyhton/ts/mowingDetection/visualize_mowingDetection_UDF.py and prompt to this file in the Profile Analytics GUI.
58 | Choose a FORCE TSS output file (vegetation index of your choice) as raster input and set the x-axis to Date Time (decimal years) in the Profile Analytics GUI. Once you
59 | click a pixel with the "Select current location" tool the vegetation index time series will be visualized along with the results of the mowingDetection_UDF. You can now
60 | adjust parameters in the main code and directly investigate the impacts of your changes. Printouts can be checked in the QGIS Python console.
61 |
62 |
63 | 
64 |
65 |
66 | ## References
67 |
68 | - Schwieder, M., Wesemeyer, M., Frantz, D., Pfoch, K., Erasmi, S., Pickert, J., Nendel, C., & Hostert, P. (2022). Mapping grassland mowing events across Germany based on combined Sentinel-2 and Landsat 8 time series. Remote Sensing of Environment, 269, 112795.
69 | - van der Linden, S., Rabe, A., Held, M., Jakimow, B., Leitão, P.J., Okujeni, A., Schwieder, M., Suess, S., & Hostert, P. (2015). The EnMAP-Box—A Toolbox and Application Programming Interface for EnMAP Data Processing. Remote Sensing, 7, 11249-11266.
70 |
71 |
72 |
--------------------------------------------------------------------------------
/python/ts/mowingDetection/scheme.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/python/ts/mowingDetection/scheme.jpg
--------------------------------------------------------------------------------
/python/ts/mowingDetection/visualize_mowingDetection_UDF.py:
--------------------------------------------------------------------------------
1 | import enmapbox.qgispluginsupport.qps.pyqtgraph.pyqtgraph as pg
2 | from enmapbox.qgispluginsupport.qps.plotstyling.plotstyling import PlotStyle, MarkerSymbol
3 | from profileanalyticsapp.profileanalyticsdockwidget import Profile
4 | from qgis.PyQt.QtCore import Qt
5 | from qgis.PyQt.QtGui import QColor
6 | from enmapboxprocessing.utils import Utils
7 | import mowingDetection_UDF
8 | import importlib
9 | importlib.reload(mowingDetection_UDF)
10 | from mowingDetection_UDF import *
11 | import numpy as np
12 | from typing import List
13 |
14 |
15 | def updatePlot(profile: Profile, profiles: List[Profile], plotWidget: pg.PlotItem):
16 |
17 | # get x (decimal dates) and y (vegetation index values from QGIS)
18 | xValues = np.array(profile.xValues)
19 | yValues = np.array(profile.yValues)
20 |
21 | # default values for running mowingDetection_UDF.py
22 | bandnames = forcepy_init(None, None, None)
23 | sensors = None
24 | dates = xValues
25 | inarray = yValues
26 | nodata = -9999
27 | nproc = 1
28 | outarray = np.ones(len(bandnames))
29 | mowingEvents, mowing_doy_out, xPeak, yPeak, xPol, yPol = forcepy_pixel(inarray, outarray, dates, sensors, bandnames, nodata, nproc)
30 |
31 | # plot indentified verticies (Start, end and peak values)
32 | style = PlotStyle()
33 | style.setMarkerSymbol(MarkerSymbol.Cross)
34 | style.markerBrush.setColor(QColor('#ff0000'))
35 | style.markerSize = 15
36 | plotDataItem = plotWidget.plot(xPeak, [i * 10000 for i in yPeak], name='Vertices')
37 | style.apply(plotDataItem)
38 |
39 | # plot the interpolated "convex hull"
40 | style = PlotStyle()
41 | style.setMarkerSymbol(MarkerSymbol.No_Symbol) # options: Circle, Triangle_Down, Triangle_Up, Triangle_Right, Triangle_Left, Pentagon, Hexagon, Square, Star, Plus, Diamond, Cross, ArrowUp, ArrowRight, ArrowDown, ArrowLeft, No_Symbol
42 | style.linePen.setColor(QColor('#0000ff'))
43 | style.linePen.setWidth(2)
44 | style.linePen.setStyle(Qt.SolidLine)
45 | plotDataItem = plotWidget.plot(xPol, [i * 10000 for i in yPol], name='Interpolation')
46 | style.apply(plotDataItem)
47 |
48 | # plot identified mowing events
49 | style = PlotStyle()
50 | style.setMarkerSymbol(MarkerSymbol.No_Symbol)
51 | style.linePen.setColor(QColor('#00ff00'))
52 | style.linePen.setWidth(2)
53 | style.linePen.setStyle(Qt.DashLine)
54 |
55 | dateTimes = [Utils.parseDateTime(mowingEvent) for mowingEvent in mowingEvents]
56 | dyears = [Utils.dateTimeToDecimalYear(dateTime) for dateTime in dateTimes]
57 |
58 | for i, dyear in enumerate(dyears,1):
59 | plotDataItem = plotWidget.plot(x=[dyear, dyear], y=[0,10000], name=f'Mowing event {i}')
60 | style.apply(plotDataItem)
61 |
62 | # print dates in pyhton console
63 | print(dyears)
64 |
--------------------------------------------------------------------------------
/rstats/ard/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/rstats/ard/.gitkeep
--------------------------------------------------------------------------------
/rstats/ts/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidfrantz/force-udf/666981ba5c761aae9cc66d4ccc1d19e2343e2f9b/rstats/ts/.gitkeep
--------------------------------------------------------------------------------
/rstats/ts/dynamic-habitat-indices/dhi.r:
--------------------------------------------------------------------------------
1 | # global header, e.g., for loading libraries
2 | # library(...)
3 |
4 | # dates: vector with dates of input data (class: Date)
5 | # sensors: vector with sensors of input data (class: character)
6 | # bandnames: vector with bandnames of input data (class: character)
7 | force_rstats_init <- function(dates, sensors, bandnames){
8 |
9 | return(c("cumulative", "minimum", "variation"))
10 | }
11 |
12 |
13 | # inarray: 2D-array with dim = c(length(dates), length(bandnames))
14 | # No-Data values are encoded as NA. (class: Integer)
15 | # dates: vector with dates of input data (class: Date)
16 | # sensors: vector with sensors of input data (class: character)
17 | # bandnames: vector with bandnames of input data (class: character)
18 | # nproc: number of CPUs the UDF may use. Always 1 for pixel functions (class: Integer)
19 | force_rstats_pixel <- function(inarray, dates, sensors, bandnames, nproc){
20 |
21 | s <- sum(inarray[,1], na.rm = TRUE) / 1e2
22 | m <- min(inarray[,1], na.rm = TRUE)
23 | v <- sd(inarray[,1], na.rm = TRUE) / mean(inarray[,1], na.rm = TRUE) * 1e4
24 |
25 | return(c(s, m, v))
26 | }
27 |
--------------------------------------------------------------------------------
/rstats/ts/dynamic-habitat-indices/readme.md:
--------------------------------------------------------------------------------
1 | # Dynamic Habitat Indices
2 |
3 | ©
4 | Copyright 2023, David Frantz
5 |
6 | ## Run with
7 |
8 | - program: ``force-higher-level``
9 | - submodule: ``TSA``
10 | - UDF type: ``RSTATS_TYPE = PIXEL``
11 | - required parameters:
12 | - ``INTERPOLATE = RBF`` with very large kernels
13 | - ``DATE_RANGE``: set to one(!) full year
14 | - required R libraries: none
15 |
16 | ## References
17 |
18 | - Radeloff, V. C., M. Dubinin, N. C. Coops, A. Allen, T. M. Brooks, M. Clayton, G. Costa, C. H. Graham, D. Helmers, A. R. Ives, D. Kolesov, A. M. Pidgeon, G. Rapacciuolo, E. Razenkova, N. Suttidate, B. E. Young, L. Zhu, and M. Hobi. (2019): **The Dynamic Habitat Indices (DHIs) from MODIS and global biodiversity**. *Remote Sensing of Environment, 222*, 204-214. [10.1016/j.rse.2018.12.009](https://doi.org/10.1016/j.rse.2018.12.009)
19 | - Hobi, M.L., Dubinin, M., Graham, C.H., Coops, N.C., Clayton, M.K., Pidgeon, A.M., & Radeloff, V.C. (2017): **A comparison of Dynamic Habitat Indices derived from different MODIS products as predictors of avian species richness.** *Remote Sensing of Environment, 195*, 142-152. [10.1016/j.rse.2017.04018](https://doi.org/10.1016/j.rse.2017.04018)
20 |
--------------------------------------------------------------------------------
/rstats/ts/spline-reconstruction/Bolten_Spline_FORCE_UDF.R:
--------------------------------------------------------------------------------
1 | force_rstats_init <- function(dates, sensors, bandnames){
2 |
3 | # Year which should be reconstructed
4 | year_to_interpolate <- 2023
5 | # Days to predict in this year and the intervall: 60 to 330 (1st March to 26th November)
6 | DOYs_to_predict <- seq(60,330,by =10)
7 | dates_to_predict <- as.Date(paste(year_to_interpolate, DOYs_to_predict), format = "%Y %j")
8 |
9 | band_names <- paste(substr(as.character(dates_to_predict),1,4),substr(as.character(dates_to_predict),6,7),substr(as.character(dates_to_predict),9,10), sep ="")
10 | return(band_names)
11 | }
12 |
13 | force_rstats_pixel <- function(inarray, dates, sensors, bandnames, nproc){
14 |
15 | # Year which should be interpolated (same like above)
16 | year_to_interpolate <- 2023
17 | # Days to predict in this yearand the intervall: 60 to 330 (1st March to 26th November)
18 | DOYs_to_predict <- seq(60,330,by =10)
19 | dates_to_predict <- as.Date(paste(year_to_interpolate, DOYs_to_predict), format = "%Y %j")
20 |
21 | # spline variables
22 | # smoothing factor for the spline reconstruction
23 | smooth_fac <- 0.5
24 | # Bolton's variable of maximum weight to assing for the predessesor years
25 | # the year of reconstruction has a wheight of 1
26 | max_weight <- 0.2
27 |
28 | # cumulate the DOY to the year of interpolation
29 | # start year 2015 (example), because of Sentinel 2 launch date, for e.g. Landsat adjust to your time span
30 | start_year <- 2015
31 | DOYs_to_predict <- (year_to_interpolate - start_year) * 365 + DOYs_to_predict
32 |
33 | tryCatch({
34 | # grap FORCE no-data case
35 | if (all(is.na(inarray[,1]))){
36 | return(rep(-9999,length(DOYs_to_predict)))
37 | }
38 |
39 | # calculate cumulative DOYs for the input data
40 | DOYs <- as.numeric(format(dates, "%j"))
41 | years <- as.numeric(substr(as.character(dates),1,4))
42 | cumulative_DOYs <- (years - start_year) * 365 + DOYs
43 |
44 | # join the data to a dataframe
45 | df <- data.frame(x=cumulative_DOYs,y=inarray[,1])
46 |
47 | # ------- 1.1 calcualte Mean Function --------------
48 | euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))
49 |
50 | # define Start and endpoints for the three spline reconstuctions
51 | DOY_borders_year <- c((year_to_interpolate-start_year)*365 - 180, (year_to_interpolate-start_year+1)*365+180)
52 | DOY_borders_b <- c((year_to_interpolate-start_year-1)*365 - 180, (year_to_interpolate-start_year)*365+180)
53 | DOY_borders_bb <- c((year_to_interpolate-start_year-2)*365 - 180, (year_to_interpolate-start_year-1)*365+180)
54 |
55 | # create dataframes for reconstuction
56 | data_year <- na.exclude(df[df$x %in% seq(DOY_borders_year[1],DOY_borders_year[2]),c(1,2)])
57 | data_b <- na.exclude(df[df$x %in% seq(DOY_borders_b[1] ,DOY_borders_b[2]),c(1,2)])
58 | data_bb <- na.exclude(df[df$x %in% seq(DOY_borders_bb[1],DOY_borders_bb[2]),c(1,2)])
59 |
60 | # calculate spline model for year of reconstruction and predict
61 | DOYs_target_year <- seq(DOY_borders_year[1],DOY_borders_year[2])
62 | tryCatch({
63 | eval( spline_model_year <<- smooth.spline(data_year$x,data_year$y, spar =smooth_fac) )
64 | eval( predict_year <<- predict(spline_model_year, x = DOYs_target_year)$y )
65 | }, error = function(err) {
66 | return(rep(-9999,length(DOYs_to_predict)))
67 | })
68 |
69 | #calculate d_max
70 | mean_year <- mean(na.exclude(data_year$y))
71 | mean_prediction <- rep(mean_year,length(DOYs_target_year))
72 | d_max = euc.dist(mean_prediction, predict_year) / 10000
73 |
74 |
75 | # --------- 1.2 spline for precessor years ------------
76 | # one year before
77 | # predict with DOYs of year of reconstruction, for difference calculation
78 | # between the two spline reconstructions
79 | tryCatch({
80 | eval( spline_model_b <<- smooth.spline(data_b$x+365,data_b$y, spar =smooth_fac) )
81 | eval( predict_b <<- predict(spline_model_b, x = DOYs_target_year)$y )
82 | }, error = function(err) {
83 | return(rep(-9999,length(DOYs_to_predict)))
84 | })
85 | d_b = euc.dist(predict_year, predict_b) / 10000
86 |
87 | # two years before
88 | # predict with DOYs of year of reconstruction, for difference calculation
89 | # between the two spline reconstructions
90 | tryCatch({
91 | eval( spline_model_bb <<- smooth.spline(data_bb$x+(365*2),data_bb$y, spar =smooth_fac) )
92 | eval( predict_bb <<- predict(spline_model_bb, x = DOYs_target_year)$y )
93 | }, error = function(err) {
94 | return(rep(-9999,length(DOYs_to_predict)))
95 | })
96 | d_bb = euc.dist(predict_year, predict_bb) / 10000
97 |
98 | # ---------- 1.3 Calculate weights -------------------
99 | # one year before
100 | if (d_max != 0) {
101 | weight_b = max_weight*(1-(d_b/d_max))
102 | if (weight_b < 0){
103 | weight_b = 0
104 | }
105 | } else {weight_b = 0}
106 |
107 | # two years before
108 | if (d_max != 0) {
109 | weight_bb = max_weight*(1-(d_bb/d_max))
110 | if (weight_bb < 0){
111 | weight_bb = 0
112 | }
113 | } else {weight_bb = 0}
114 |
115 | #----------- 1.4 apply weights and calculate weighted spline --------------
116 | # combine the time series to one year and assign weights to the new data points
117 | combined_x <- c(data_year$x , (data_b$x+365)[weight_b>0] , (data_bb$x + (365*2))[weight_bb>0])
118 | combined_y <- c(data_year$y , data_b$y[weight_b>0] , data_bb$y[weight_bb>0])
119 | vec_weights <- c(rep(1,length(data_year$x)),
120 | rep(weight_b,length(data_b$x))[weight_b>0],
121 | rep(weight_bb,length(data_bb$x))[weight_bb>0])
122 |
123 | # calculate weighted spline
124 | tryCatch({
125 | eval( spline_model_combined <<- smooth.spline(x=combined_x, y=combined_y, w = vec_weights , spar =smooth_fac) )
126 | eval( predict_combined <<- predict(spline_model_combined, x = DOYs_to_predict)$y )
127 | }, error = function(err) {
128 | return(rep(-9999,length(DOYs_to_predict)))
129 | })
130 | return(predict_combined)
131 |
132 | }, error = function(err) {
133 | return(rep(-9999,length(DOYs_to_predict)))
134 | })
135 | }
--------------------------------------------------------------------------------
/rstats/ts/spline-reconstruction/readme.md:
--------------------------------------------------------------------------------
1 | # Time series reconstruction for forest using splines
2 |
3 | ©
4 | Copyright 2024, David Klehr
5 |
6 | ## Run with
7 |
8 | - program: ``force-higher-level``
9 | - submodule: ``TSA``
10 | - DATE_RANGE: ``xxxx-07-01 yyyy-06-31``
11 | * xxxx = three years before your target year
12 | * yyyy = one year after your target year
13 | * e.g. for target year 2022: ``2019-07-01 2023-06-31``
14 | - UDF type: ``RSTATS_TYPE = PIXEL``
15 | - required parameters:``none``
16 | - required R libraries: ``none``
17 |
18 | ## References
19 |
20 | - Bolton, D.K., Gray, J.M., Melaas, E.K., Moon, M., Eklundh, L., Friedl, M.A., 2020. **Continental-scale land surface phenology from harmonized Landsat 8 and Sentinel-2 imagery**. *Remote Sensing of Environment 240*, 111685. https://doi.org/10.1016/j.rse.2020.111685.
--------------------------------------------------------------------------------