diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..816a2c5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,138 @@
+
+# File where is saved the JAVA environment
+JavaPath.csv
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+temp/
+wheels/
+pip-wheel-metadata/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+zip_build/
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+.python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject/
+.spyproject/
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+
+
diff --git a/Icons/CoolParksTool.png b/Icons/CoolParksTool.png
new file mode 100644
index 0000000..3b8bcb1
Binary files /dev/null and b/Icons/CoolParksTool.png differ
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..4dfc1f0
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,244 @@
+#/***************************************************************************
+# ProcessingUMEP
+#
+# UMEP for processing toolbox
+# -------------------
+# begin : 2020-04-02
+# git sha : $Format:%H$
+# copyright : (C) 2020 by Fredrik Lindberg
+# email : fredrikl@gvc.gu.se
+# ***************************************************************************/
+#
+#/***************************************************************************
+# * *
+# * This program is free software; you can redistribute it and/or modify *
+# * it under the terms of the GNU General Public License as published by *
+# * the Free Software Foundation; either version 2 of the License, or *
+# * (at your option) any later version. *
+# * *
+# ***************************************************************************/
+
+#################################################
+# Edit the following to match your sources lists
+#################################################
+
+
+#Add iso code for any locales you want to support here (space separated)
+# default is no locales
+# LOCALES = af
+LOCALES =
+
+# If locales are enabled, set the name of the lrelease binary on your system. If
+# you have trouble compiling the translations, you may have to specify the full path to
+# lrelease
+#LRELEASE = lrelease
+#LRELEASE = lrelease-qt4
+
+
+# translation
+SOURCES = \
+ __init__.py \
+ processing_umep.py
+
+PLUGINNAME = processing_umep
+
+PY_FILES = \
+ __init__.py \
+ processing_umep.py
+
+UI_FILES =
+
+EXTRAS = metadata.txt
+
+EXTRA_DIRS =
+
+COMPILED_RESOURCE_FILES =
+
+PEP8EXCLUDE=pydev,resources.py,conf.py,third_party,ui
+
+# QGISDIR points to the location where your plugin should be installed.
+# This varies by platform, relative to your HOME directory:
+# * Linux:
+# .local/share/QGIS/QGIS3/profiles/default/python/plugins/
+# * Mac OS X:
+# Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins
+# * Windows:
+# AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins'
+
+QGISDIR=C:\Users\xlinfr\AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins
+
+#################################################
+# Normally you would not need to edit below here
+#################################################
+
+HELP = help/build/html
+
+PLUGIN_UPLOAD = $(c)/plugin_upload.py
+
+RESOURCE_SRC=$(shell grep '^ *@@g;s/.*>//g' | tr '\n' ' ')
+
+.PHONY: default
+default:
+ @echo While you can use make to build and deploy your plugin, pb_tool
+ @echo is a much better solution.
+ @echo A Python script, pb_tool provides platform independent management of
+ @echo your plugins and runs anywhere.
+ @echo You can install pb_tool using: pip install pb_tool
+ @echo See https://g-sherman.github.io/plugin_build_tool/ for info.
+
+compile: $(COMPILED_RESOURCE_FILES)
+
+%.py : %.qrc $(RESOURCES_SRC)
+ pyrcc5 -o $*.py $<
+
+%.qm : %.ts
+ $(LRELEASE) $<
+
+test: compile transcompile
+ @echo
+ @echo "----------------------"
+ @echo "Regression Test Suite"
+ @echo "----------------------"
+
+ @# Preceding dash means that make will continue in case of errors
+ @-export PYTHONPATH=`pwd`:$(PYTHONPATH); \
+ export QGIS_DEBUG=0; \
+ export QGIS_LOG_FILE=/dev/null; \
+ nosetests -v --with-id --with-coverage --cover-package=. \
+ 3>&1 1>&2 2>&3 3>&- || true
+ @echo "----------------------"
+ @echo "If you get a 'no module named qgis.core error, try sourcing"
+ @echo "the helper script we have provided first then run make test."
+ @echo "e.g. source run-env-linux.sh ; make test"
+ @echo "----------------------"
+
+deploy: compile doc transcompile
+ @echo
+ @echo "------------------------------------------"
+ @echo "Deploying plugin to your .qgis2 directory."
+ @echo "------------------------------------------"
+ # The deploy target only works on unix like operating system where
+ # the Python plugin directory is located at:
+ # $HOME/$(QGISDIR)/python/plugins
+ mkdir -p $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+ cp -vf $(PY_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+ cp -vf $(UI_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+ cp -vf $(COMPILED_RESOURCE_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+ cp -vf $(EXTRAS) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+ cp -vfr i18n $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+ cp -vfr $(HELP) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)/help
+ # Copy extra directories if any
+ (foreach EXTRA_DIR,(EXTRA_DIRS), cp -R (EXTRA_DIR) (HOME)/(QGISDIR)/python/plugins/(PLUGINNAME)/;)
+
+
+# The dclean target removes compiled python files from plugin directory
+# also deletes any .git entry
+dclean:
+ @echo
+ @echo "-----------------------------------"
+ @echo "Removing any compiled python files."
+ @echo "-----------------------------------"
+ find $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) -iname "*.pyc" -delete
+ find $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) -iname ".git" -prune -exec rm -Rf {} \;
+
+
+derase:
+ @echo
+ @echo "-------------------------"
+ @echo "Removing deployed plugin."
+ @echo "-------------------------"
+ rm -Rf $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
+
+zip: deploy dclean
+ @echo
+ @echo "---------------------------"
+ @echo "Creating plugin zip bundle."
+ @echo "---------------------------"
+ # The zip target deploys the plugin and creates a zip file with the deployed
+ # content. You can then upload the zip file on http://plugins.qgis.org
+ rm -f $(PLUGINNAME).zip
+ cd $(HOME)/$(QGISDIR)/python/plugins; zip -9r $(CURDIR)/$(PLUGINNAME).zip $(PLUGINNAME)
+
+package: compile
+ # Create a zip package of the plugin named $(PLUGINNAME).zip.
+ # This requires use of git (your plugin development directory must be a
+ # git repository).
+ # To use, pass a valid commit or tag as follows:
+ # make package VERSION=Version_0.3.2
+ @echo
+ @echo "------------------------------------"
+ @echo "Exporting plugin to zip package. "
+ @echo "------------------------------------"
+ rm -f $(PLUGINNAME).zip
+ git archive --prefix=$(PLUGINNAME)/ -o $(PLUGINNAME).zip $(VERSION)
+ echo "Created package: $(PLUGINNAME).zip"
+
+upload: zip
+ @echo
+ @echo "-------------------------------------"
+ @echo "Uploading plugin to QGIS Plugin repo."
+ @echo "-------------------------------------"
+ $(PLUGIN_UPLOAD) $(PLUGINNAME).zip
+
+transup:
+ @echo
+ @echo "------------------------------------------------"
+ @echo "Updating translation files with any new strings."
+ @echo "------------------------------------------------"
+ @chmod +x scripts/update-strings.sh
+ @scripts/update-strings.sh $(LOCALES)
+
+transcompile:
+ @echo
+ @echo "----------------------------------------"
+ @echo "Compiled translation files to .qm files."
+ @echo "----------------------------------------"
+ @chmod +x scripts/compile-strings.sh
+ @scripts/compile-strings.sh $(LRELEASE) $(LOCALES)
+
+transclean:
+ @echo
+ @echo "------------------------------------"
+ @echo "Removing compiled translation files."
+ @echo "------------------------------------"
+ rm -f i18n/*.qm
+
+clean:
+ @echo
+ @echo "------------------------------------"
+ @echo "Removing uic and rcc generated files"
+ @echo "------------------------------------"
+ rm $(COMPILED_UI_FILES) $(COMPILED_RESOURCE_FILES)
+
+doc:
+ @echo
+ @echo "------------------------------------"
+ @echo "Building documentation using sphinx."
+ @echo "------------------------------------"
+ cd help; make html
+
+pylint:
+ @echo
+ @echo "-----------------"
+ @echo "Pylint violations"
+ @echo "-----------------"
+ @pylint --reports=n --rcfile=pylintrc . || true
+ @echo
+ @echo "----------------------"
+ @echo "If you get a 'no module named qgis.core' error, try sourcing"
+ @echo "the helper script we have provided first then run make pylint."
+ @echo "e.g. source run-env-linux.sh ; make pylint"
+ @echo "----------------------"
+
+
+# Run pep8 style checking
+#http://pypi.python.org/pypi/pep8
+pep8:
+ @echo
+ @echo "-----------"
+ @echo "PEP8 issues"
+ @echo "-----------"
+ @pep8 --repeat --ignore=E203,E121,E122,E123,E124,E125,E126,E127,E128 --exclude $(PEP8EXCLUDE) . || true
+ @echo "-----------"
+ @echo "Ignored in PEP8 check:"
+ @echo $(PEP8EXCLUDE)
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b9bb021
--- /dev/null
+++ b/README.md
@@ -0,0 +1,70 @@
+# CoolParksTool
+
+**A version for the Processing Toolbox in QGIS**
+
+This is the official repository for the CoolParksTool.
+It summarizes the results of the research project called CoolParks.
+The user provides park boundaries, type of ground within the park,
+type of canopy within the park and meteorological conditions.
+As output the cooling effect of the park on its surrounding built-up area
+is calculated as well as its impact on building energy consumption and building
+ indoor thermal comfort
+
+## Description
+
+Vous trouverez une [vidéo](https://github.com/j3r3m1/coolparkstool/blob/main/Presentations/video_presentation.mp4) et un [support de présentation](https://github.com/j3r3m1/coolparkstool/blob/main/Presentations/10h15-10h30_Presentation_CoolParksTool.pdf) de l'outil CoolParksTool.
+
+## Installation
+
+### Pré-requis
+Comme [GeoClimate](https://github.com/orbisgis/geoclimate) ou le module [URock de UMEP](https://umep-docs.readthedocs.io/en/latest/processor/Wind%20model%20URock.html), CoolParksTool utilise pour une grande partie de ses calculs le système de gestion de bases de données spatiales [H2GIS](https://github.com/orbisgis/h2gis).
+
+Ce système reposant sur Java, il est nécessaire que votre ordinateur dispose d'une installation du logiciel Java relativement récente (>=8):
+- pour windows: https://java.com/en/download/windows_manual.jsp
+- pour linux: https://java.com/en/download/
+- pour macOS: https://www.java.com/en/download/apple.jsp
+
+### Créer un environnement propice à l’installation de CoolParksTool
+
+Il est tout d'abord nécessaire de créer un environnement propice à l'installation de CoolParksTool. Pour cela, 2 solutions sont possibles :
+- **Vous avez un environnement Windows**, il est préférable de préalablement installer le programme qui s’appelle osgeo4W (https://trac.osgeo.org/osgeo4w/).
+- **Vous avez un environnement Linux ou MacOS** ou vous avez Windows mais ne souhaitez pas utiliser osgeo4w, il est recommandé de préalablement utiliser le programme qui s’appelle Anaconda (https://anaconda.org/).
+
+#### Vous avez un environnement Windows
+Il est recommandé d'installer osgeo4W. Ce programme permet de gérer l’installation de librairies python dans un environnement dédié dans lequel un certain nombre de librairies utilisées par QGIS sont préinstallées.
+
+Pour l’utiliser :
+- télécharger l’installateur: https://download.osgeo.org/osgeo4w/v2/osgeo4w-setup.exe
+- lancer le une première fois en sélectionnant “install express”. Cocher QGIS, QGIS LTR, GDAL et GRASS
+- à la fin de l’installation, il est nécessaire d’installer d’autres librairies. Pour cela, relancer l’installateur (osgeo4W-setup) mais cette fois ci sélectionner “advanced installation”. Cliquer XX fois sur suivant. Trois librairies doivent ensuite être installées : shapely, geopandas et statsmodels. Pour cela :
+ - rechercher les dans la barre de recherche : entrer le nom mais inutile de taper entrer ensuite, il s’agit simplement de cliquer sur le + qui permet d’afficher les résultats de la recherche
+ - l’installer si nécessaire : si aucune version de la librairie recherchée n’est installée, il faut cliquer une seule fois sur la ligne correspondant à la librairie à installer. Si une version est affichée, cela signifie que la librairie est déjà installer, aucune action n’est nécessaire. Réitérer ces deux derniers points pour chaque librairie à installer.
+- Enfin, X autres librairies sont à installer en-dehors de l’installateur d’osgeo4W. Elles doivent cependant être installées dans le même environnement. Pour cela, il faut cette fois ci lancer le “shell osgeo4W”. Une fois lancé, il faut installer les librairies via pip :
+ - pip install unidecode
+ - pip install jaydebeapi
+
+#### Vous avez un environnement Linux ou MacO
+Si vous ne souhaitez pas installer osgeo4W ou que vous utilisez un système d'exploitation linux ou MacOS, il est recommandé d'installer Anaconda. Il permet de gérer l’installation de librairies Python via la création d’environnements dédiés à un besoin donné. Il permet également de s’assurer de l’intercompatibilité des librairies entre elles dans un environnement donné.
+
+Pour l’utiliser :
+- suiver les recommandations d'installation relatives à votre système d'exploitation : https://docs.anaconda.com/free/anaconda/install
+- il s’agit maintenant de créer un nouvel environnement dédié à l’utilisation de CoolParksTool et d’installer les librairies nécessaires à son fonctionnement dans cet environnement. Pour cela, deux solutions existent :
+ - si vous avez installé anaconda en mode “ligne de commande” :
+ - ouvrer un terminal
+ - créer un nouvel environnement : conda create --name coolparks
+ - activer cet environnement : conda activate coolparks
+ - ajouter une nouvelle source de librairies d’où anaconda pourra télécharger des librairies : conda config --add channels conda-forge
+ - installer les librairies (cela peut prendre un temps considérable de gérer les dépendances) : conda install gdal qgis=3.28.3 shapely geopandas unidecode statsmodels jaydebeapi
+ - lancer QGIS via le terminal en tapant : qgis
+ - si vous avez installé anaconda en mode “graphique” :
+
+### Installer CoolParksTool
+Quelle que soit la solution choisie, vous devez maintenant avoir QGIS ouvert dans un environnement propice au bon fonctionnement de CoolParksTool. Pour installer ce dernier, il suffit maintenant :
+- de lancer QGIS et d'installer le plug-in via le menu "Extensions" puis "Installer/Gérer les extensions". Vous pouvez maintenant rechercher puis sélectionner "coolparkstool" puis cliquer sur "Installer le plugin".
+- un message sur fond vers vous informant du succès de l'installation doit normalement apparaître temporairement. Lorsque vous ouvrez la boîte à outil de QGIS, le plug-in CoolParks tool doit maintenant apparaître (cf. Figure ci-dessous)
+
+![image](https://github.com/j3r3m1/coolparkstool/assets/13120405/20b24f01-5c53-48ae-91ba-0c8884f7d78f)
+
+
+## Acknowledgements
+This work has been performed within the research project CoolParks co-funded by the French Agency ADEME (grant number 1917C0002).
diff --git a/__init__.py b/__init__.py
new file mode 100644
index 0000000..606c287
--- /dev/null
+++ b/__init__.py
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+"""
+/***************************************************************************
+ CoolParks tool
+ A QGIS plugin
+ Coolparks toolbox
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+ -------------------
+ begin : 2024-02-06
+ copyright : (C) 2023 by Jérémy Bernard
+ email : jeremy.bernard@zaclys.net
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+"""
+
+__author__ = 'Jérémy Bernard'
+__date__ = '2024-02-06'
+__copyright__ = '(C) 2024 by Jérémy Bernard'
+
+
+# noinspection PyPep8Naming
+def classFactory(iface): # pylint: disable=invalid-name
+ """Load ProcessingCoolParksTool class from file ProcessingGeoClimateTool.
+
+ :param iface: A QGIS interface instance.
+ :type iface: QgsInterface
+ """
+ #
+ from .processing_geoclimate import ProcessingGeoClimatePlugin
+ return ProcessingGeoClimatePlugin()
diff --git a/dep.txt b/dep.txt
new file mode 100644
index 0000000..bc5e24c
--- /dev/null
+++ b/dep.txt
@@ -0,0 +1,2 @@
+subprocess
+json
diff --git a/functions/globalVariables.py b/functions/globalVariables.py
new file mode 100644
index 0000000..ebfd1ef
--- /dev/null
+++ b/functions/globalVariables.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Created on Feb 2024
+
+@author: Jérémy Bernard, CNRM, chercheur associé au Lab-STICC et accueilli au LOCIE
+"""
+import tempfile
+import os
+from pathlib import Path
+
+GEOCLIMATE_VERSION = "1.0.0"
+
+GEOCLIMATE_JAR_URL = f"https://github.com/orbisgis/geoclimate/releases/download/v{GEOCLIMATE_VERSION}/geoclimate-{GEOCLIMATE_VERSION}.jar"
+
+GEOCLIMATE_JAR_NAME = f"geoclimate-{GEOCLIMATE_VERSION}.jar"
+
+CONFIG_FILENAME = "configuration_file_{0}.json"
+
+TEMPO_DIRECTORY = tempfile.tempdir
+OUTPUT_TABLES = ["building_indicators",
+ "block_indicators",
+ "rsu_indicators",
+ "rsu_lcz",
+ "zone",
+ "building",
+ "road",
+ "rail",
+ "water",
+ "vegetation",
+ "impervious",
+ "urban_areas",
+ "rsu_utrf_area",
+ "rsu_utrf_floor_area",
+ "building_utrf",
+ "grid_indicators",
+ "sea_land_mask",
+ "building_height_missing",
+ "road_traffic",
+ "population",
+ "ground_acoustic"]
+
+# Define names used by GeoClimate for each type of dataset
+OSM = "OSM"
+BDT_V2 = "BDTOPO_V2"
+BDT_V3 = "BDTOPO_V3"
+
+# Define default SRID
+SRID = {OSM: 4326, BDT_V2: 2154, BDT_V3: 2154}
\ No newline at end of file
diff --git a/functions/otherFunctions.py b/functions/otherFunctions.py
new file mode 100644
index 0000000..f742afb
--- /dev/null
+++ b/functions/otherFunctions.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Created on Fri Feb 16 16:36:54 2024
+
+@author: Jérémy Bernard, CNRM, chercheur associé au Lab-STICC et accueilli au LOCIE
+"""
+import subprocess
+
+def runProcess(exe):
+ """Function to run subprocesses using shell and getting live log.
+
+ Parameters
+ _ _ _ _ _ _ _ _ _ _
+
+ exe: list
+ List of key words composing the execution command (e.g. ['echo', 'Hello world'])
+
+ Source of the code: https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output
+ """
+
+ p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ while(True):
+ # returns None while subprocess is running
+ retcode = p.poll()
+ line = p.stdout.readline()
+ yield line
+ if retcode is not None:
+ break
\ No newline at end of file
diff --git a/metadata.txt b/metadata.txt
new file mode 100644
index 0000000..632b025
--- /dev/null
+++ b/metadata.txt
@@ -0,0 +1,50 @@
+# This file contains metadata for your plugin.
+
+# This file should be included when you package your plugin.# Mandatory items:
+
+[general]
+name=CoolParksTool
+qgisMinimumVersion=3.0
+description=This plugin evaluates the cooling effect of a park and its impact on buildings energy and thermal comfort
+version=0.0.2
+author=Jeremy Bernard
+email=jeremy.bernard@zaclys.net
+
+about=This plugin summarizes the results of the research project called CoolParks. The user provides park boundaries, type of ground within the park, type of canopy within the park and meteorological conditions. As output the cooling effect of the park on its surrounding built-up area is calculated as well as its impact on building energy consumption and building indoor thermal comfort
+
+
+tracker=https://github.com/j3r3m1/coolparkstool/issues
+repository=https://github.com/j3r3m1/coolparkstool
+# End of mandatory metadata
+
+# Recommended items:
+
+hasProcessingProvider=yes
+# Uncomment the following line and add your changelog:
+changelog=
+ 0.0.2 : Add the unload function in the processing_coolparks.py file
+ 0.0.1 : First release. Experimental.
+
+# Tags are comma separated with spaces allowed
+tags=urban climate, urban planning, parks, cooling, modelling, urban morphology, urban geometry
+
+homepage=https://github.com/j3r3m1/coolparkstool#readme
+# category=Plugins
+icon=Icons/CoolParksTool.png
+# experimental flag
+experimental=True
+
+# deprecated flag (applies to the whole plugin, not just a single version)
+deprecated=False
+
+# Since QGIS 3.8, a comma separated list of plugins to be installed
+# (or upgraded) can be specified.
+# Check the documentation for more information.
+# plugin_dependencies=
+
+Category of the plugin: Raster, Vector, Database or Web
+# category=
+
+# If the plugin can run on QGIS Server.
+server=False
+
diff --git a/pb_tool.cfg b/pb_tool.cfg
new file mode 100644
index 0000000..43d84c6
--- /dev/null
+++ b/pb_tool.cfg
@@ -0,0 +1,80 @@
+#/***************************************************************************
+# GeoClimateTool
+#
+# Configuration file for plugin builder tool (pb_tool)
+# Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+# -------------------
+# begin : 2024-02-06
+# copyright : (C) 2024 by Jérémy Bernard
+# email : jeremy.bernard@zaclys.net
+# ***************************************************************************/
+#
+#/***************************************************************************
+# * *
+# * This program is free software; you can redistribute it and/or modify *
+# * it under the terms of the GNU General Public License as published by *
+# * the Free Software Foundation; either version 2 of the License, or *
+# * (at your option) any later version. *
+# * *
+# ***************************************************************************/
+#
+#
+# You can install pb_tool using:
+# pip install http://geoapt.net/files/pb_tool.zip
+#
+# Consider doing your development (and install of pb_tool) in a virtualenv.
+#
+# For details on setting up and using pb_tool, see:
+# http://g-sherman.github.io/plugin_build_tool/
+#
+# Issues and pull requests here:
+# https://github.com/g-sherman/plugin_build_tool:
+#
+# Sane defaults for your plugin generated by the Plugin Builder are
+# already set below.
+#
+# As you add Python source files and UI files to your plugin, add
+# them to the appropriate [files] section below.
+
+[plugin]
+# Name of the plugin. This is the name of the directory that will
+# be created in .qgis2/python/plugins
+name: geoclimatetool
+
+# Full path to where you want your plugin directory copied. If empty,
+# the QGIS default path will be used. Don't include the plugin name in
+# the path.
+plugin_path:
+
+[files]
+# Python files that should be deployed with the plugin
+python_files: __init__.py processing_geoclimate.py processing_geoclimate_provider.py processing_algorithm.py
+
+# The main dialog file that is loaded (not compiled)
+main_dialog:
+
+# Other ui files for dialogs you create (these will be compiled)
+compiled_ui_files:
+
+# Resource file(s) that will be compiled
+resource_files:
+
+# Other files required for the plugin
+extras: metadata.txt
+
+# Other directories to be deployed with the plugin.
+# These must be subdirectories under the plugin directory
+extra_dirs: Icons util functions Resources
+
+# ISO code(s) for any locales (translations), separated by spaces.
+# Corresponding .ts files must exist in the i18n directory
+locales:
+
+[help]
+# the built help directory that should be deployed with the plugin
+dir: help/build/html
+# the name of the directory to target in the deployed plugin
+target: help
+
+
+
diff --git a/plugin_upload.py b/plugin_upload.py
new file mode 100644
index 0000000..a88ea2b
--- /dev/null
+++ b/plugin_upload.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+# coding=utf-8
+"""This script uploads a plugin package to the plugin repository.
+ Authors: A. Pasotti, V. Picavet
+ git sha : $TemplateVCSFormat
+"""
+
+import sys
+import getpass
+import xmlrpc.client
+from optparse import OptionParser
+
+standard_library.install_aliases()
+
+# Configuration
+PROTOCOL = 'https'
+SERVER = 'plugins.qgis.org'
+PORT = '443'
+ENDPOINT = '/plugins/RPC2/'
+VERBOSE = False
+
+
+def main(parameters, arguments):
+ """Main entry point.
+
+ :param parameters: Command line parameters.
+ :param arguments: Command line arguments.
+ """
+ address = "{protocol}://{username}:{password}@{server}:{port}{endpoint}".format(
+ protocol=PROTOCOL,
+ username=parameters.username,
+ password=parameters.password,
+ server=parameters.server,
+ port=parameters.port,
+ endpoint=ENDPOINT)
+ print("Connecting to: %s" % hide_password(address))
+
+ server = xmlrpc.client.ServerProxy(address, verbose=VERBOSE)
+
+ try:
+ with open(arguments[0], 'rb') as handle:
+ plugin_id, version_id = server.plugin.upload(
+ xmlrpc.client.Binary(handle.read()))
+ print("Plugin ID: %s" % plugin_id)
+ print("Version ID: %s" % version_id)
+ except xmlrpc.client.ProtocolError as err:
+ print("A protocol error occurred")
+ print("URL: %s" % hide_password(err.url, 0))
+ print("HTTP/HTTPS headers: %s" % err.headers)
+ print("Error code: %d" % err.errcode)
+ print("Error message: %s" % err.errmsg)
+ except xmlrpc.client.Fault as err:
+ print("A fault occurred")
+ print("Fault code: %d" % err.faultCode)
+ print("Fault string: %s" % err.faultString)
+
+
+def hide_password(url, start=6):
+ """Returns the http url with password part replaced with '*'.
+
+ :param url: URL to upload the plugin to.
+ :type url: str
+
+ :param start: Position of start of password.
+ :type start: int
+ """
+ start_position = url.find(':', start) + 1
+ end_position = url.find('@')
+ return "%s%s%s" % (
+ url[:start_position],
+ '*' * (end_position - start_position),
+ url[end_position:])
+
+
+if __name__ == "__main__":
+ parser = OptionParser(usage="%prog [options] plugin.zip")
+ parser.add_option(
+ "-w", "--password", dest="password",
+ help="Password for plugin site", metavar="******")
+ parser.add_option(
+ "-u", "--username", dest="username",
+ help="Username of plugin site", metavar="user")
+ parser.add_option(
+ "-p", "--port", dest="port",
+ help="Server port to connect to", metavar="80")
+ parser.add_option(
+ "-s", "--server", dest="server",
+ help="Specify server name", metavar="plugins.qgis.org")
+ options, args = parser.parse_args()
+ if len(args) != 1:
+ print("Please specify zip file.\n")
+ parser.print_help()
+ sys.exit(1)
+ if not options.server:
+ options.server = SERVER
+ if not options.port:
+ options.port = PORT
+ if not options.username:
+ # interactive mode
+ username = getpass.getuser()
+ print("Please enter user name [%s] :" % username, end=' ')
+
+ res = input()
+ if res != "":
+ options.username = res
+ else:
+ options.username = username
+ if not options.password:
+ # interactive mode
+ options.password = getpass.getpass()
+ main(options, args)
diff --git a/processing_algorithm.py b/processing_algorithm.py
new file mode 100644
index 0000000..a634289
--- /dev/null
+++ b/processing_algorithm.py
@@ -0,0 +1,419 @@
+# -*- coding: utf-8 -*-
+
+"""
+/***************************************************************************
+ GeoClimate Workflow
+ A QGIS plugin
+ This plugin execute the GeoClimate workflows
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+ -------------------
+ begin : 2024-02-06
+ copyright : (C) 2023 by Jérémy Bernard
+ email : jeremy.bernard@zaclys.net
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+"""
+
+__author__ = 'Jérémy Bernard'
+__date__ = '2024-02-06'
+__copyright__ = '(C) 2024 by Jérémy Bernard'
+
+# This will get replaced with a git SHA1 when you do a git archive
+
+__revision__ = '$Format:%H$'
+
+import os
+from qgis.PyQt.QtCore import QCoreApplication, QVariant
+from qgis.core import (QgsProcessing,
+ QgsProcessingAlgorithm,
+ QgsProcessingParameterField,
+ QgsProcessingParameterFeatureSource,
+ QgsProcessingParameterNumber,
+ QgsProcessingParameterMatrix,
+ QgsProcessingParameterFolderDestination,
+ QgsProcessingParameterString,
+ QgsProcessingParameterRasterLayer,
+ QgsProcessingParameterBoolean,
+ QgsRasterLayer,
+ QgsVectorLayer,
+ QgsProject,
+ QgsProcessingContext,
+ QgsProcessingParameterEnum,
+ QgsProcessingParameterFile,
+ QgsProcessingException,
+ QgsLayerTreeGroup,
+ QgsProcessingParameterExtent,
+ QgsCoordinateTransform,
+ QgsCoordinateReferenceSystem,
+ QgsGeometry)
+from qgis.utils import iface
+from pathlib import Path
+from qgis.PyQt.QtGui import QIcon
+import inspect
+#import unidecode
+from .functions.globalVariables import *
+from .functions.otherFunctions import runProcess
+import json
+from urllib.request import urlretrieve
+import glob
+
+class GeoClimateProcessorAlgorithm(QgsProcessingAlgorithm):
+ """ Create a GeoClimate config file and run the corresponding workflow
+ """
+
+ # Constants used to refer to parameters and outputs. They will be
+ # used when calling the algorithm from another algorithm, or when
+ # calling from the QGIS console.
+
+ # Input variables
+ # Input dataset used for the workflow
+ INPUT_DATASET = "INPUT_DATASET"
+ # Tick if you want to estimate missing OSM building height
+ ESTIMATED_HEIGHT = "ESTIMATED_HEIGHT"
+ # Tick if you want to produce a LCZ map"
+ LCZ_CALC = "LCZ_CALC"
+ # Tick if you want to produce the UTRF classification
+ UTRF_CALC = "UTRF_CALC"
+ # Tick if you want to calculate WRF inputs
+ WRF_INPUTS = "WRF_INPUTS"
+ # Tick if you want to calculate TEB inputs
+ TEB_INPUTS = "TEB_INPUTS"
+ # Quick calculation of the SVF
+ SVF_SIMPLIFIED = "SVF_SIMPLIFIED"
+ # Location to process
+ LOCATION = "LOCATION"
+ # Extent if extent is used instead of location
+ EXTENT = "EXTENT"
+ # Warning: seems to not work in any folder of the temp...
+ OUTPUT_DIRECTORY = "OUTPUT_DIRECTORY"
+
+ def initAlgorithm(self, config):
+ """
+ Here we define the inputs and output of the algorithm, along
+ with some other properties.
+ """
+
+ # We add the input parameters
+ self.addParameter(
+ QgsProcessingParameterEnum(
+ self.INPUT_DATASET,
+ self.tr('What data do you want to use as input'),
+ list(SRID.keys()),
+ defaultValue=0,
+ optional = False))
+ self.addParameter(
+ QgsProcessingParameterBoolean(
+ self.ESTIMATED_HEIGHT,
+ self.tr('Tick if you want to estimate missing OSM building height'),
+ defaultValue = True))
+ self.addParameter(
+ QgsProcessingParameterBoolean(
+ self.LCZ_CALC,
+ self.tr('Tick if you want to produce a LCZ map"'),
+ defaultValue = False))
+ self.addParameter(
+ QgsProcessingParameterBoolean(
+ self.UTRF_CALC,
+ self.tr('Tick if you want to produce the UTRF classification'),
+ defaultValue = False))
+ self.addParameter(
+ QgsProcessingParameterBoolean(
+ self.WRF_INPUTS,
+ self.tr('Tick if you want to calculate the WRF spatial inputs'),
+ defaultValue = False))
+ self.addParameter(
+ QgsProcessingParameterBoolean(
+ self.TEB_INPUTS,
+ self.tr('Tick if you want to calculate the TEB spatial inputs'),
+ defaultValue = False))
+ self.addParameter(
+ QgsProcessingParameterBoolean(
+ self.SVF_SIMPLIFIED,
+ self.tr('Tick if you want a quick (but less accurate) calculation of the SVF'),
+ defaultValue = True))
+ self.addParameter(
+ QgsProcessingParameterString(
+ self.LOCATION,
+ self.tr('A place name to run (recommended: commune name)'),
+ defaultValue = "",
+ optional = True))
+ self.addParameter(
+ QgsProcessingParameterExtent(
+ self.EXTENT,
+ self.tr('Clipping extent'),
+ optional = True))
+ self.addParameter(
+ QgsProcessingParameterFolderDestination(
+ self.OUTPUT_DIRECTORY,
+ self.tr('Directory to save the outputs'),
+ defaultValue = ""))
+
+ def processAlgorithm(self, parameters, context, feedback):
+ """
+ Here is where the processing itself takes place.
+ """
+
+ inputDataset = self.parameterAsInt(parameters, self.INPUT_DATASET, context)
+ estimatedHeight = self.parameterAsBoolean(parameters, self.ESTIMATED_HEIGHT, context)
+ lczCalc = self.parameterAsBoolean(parameters, self.LCZ_CALC, context)
+ utrfCalc = self.parameterAsBoolean(parameters, self.UTRF_CALC, context)
+ wrfInputs = self.parameterAsBoolean(parameters, self.WRF_INPUTS, context)
+ tebInputs = self.parameterAsBoolean(parameters, self.TEB_INPUTS, context)
+ svfSimplified = self.parameterAsBoolean(parameters, self.SVF_SIMPLIFIED, context)
+ location = self.parameterAsString(parameters, self.LOCATION, context)
+ bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
+ bbox_crs_ini = self.parameterAsExtentCrs(parameters, self.EXTENT, context)
+ outputDirectory = self.parameterAsString(parameters, self.OUTPUT_DIRECTORY, context)
+
+ #prefix = unidecode.unidecode(weatherScenario).replace(" ", "_")
+
+ if location and not bbox.isNull():
+ raise QgsProcessingException("You should fill a location OR select an extent, not both !!")
+ elif not location and bbox.isNull():
+ raise QgsProcessingException("You should specify a location or select an extent !!")
+
+
+ # Get the plugin directory to put the last stable GeoClimate version
+ plugin_directory = self.plugin_dir = os.path.dirname(__file__)
+
+ # GeoClimate path of the last version
+ geoclim_jar_path = os.path.join(plugin_directory, 'Resources', GEOCLIMATE_JAR_NAME)
+
+ list_loc_geoc_vers = glob.glob(os.path.join(plugin_directory, 'Resources', "geoclimate*.jar"))
+ if list_loc_geoc_vers:
+ # Remove all potential old GeoClimate versions
+ list_old_geoc_vers = list_loc_geoc_vers.copy()
+ if list_loc_geoc_vers.count(geoclim_jar_path)>0:
+ list_old_geoc_vers.remove(geoclim_jar_path)
+ for path_old_v in list_old_geoc_vers:
+ os.remove(path_old_v)
+
+ # Download the last GeoClimate version if not already downloaded
+ if not os.path.exists(geoclim_jar_path):
+ if feedback:
+ feedback.setProgressText("You do not have the last GeoClimate version. Downloading...")
+ if feedback.isCanceled():
+ feedback.setProgressText("Calculation cancelled by user")
+ return {}
+ urlretrieve(GEOCLIMATE_JAR_URL, geoclim_jar_path)
+ else:
+ if feedback:
+ feedback.setProgressText("You do not have the last GeoClimate version. Downloading...")
+ if feedback.isCanceled():
+ feedback.setProgressText("Calculation cancelled by user")
+ return {}
+ urlretrieve(GEOCLIMATE_JAR_URL, geoclim_jar_path)
+
+ # Get the input dataset used by the workflow
+ inputDataset = list(SRID.keys())[inputDataset]
+
+ # Recover the bbox coordinates if exists
+ if not bbox.isNull():
+ # Get the bbox srid
+ if not bbox_crs_ini:
+ mapRenderer = iface.mapCanvas().mapRenderer()
+ bbox_crs_ini=mapRenderer.destinationCrs()
+ # Get the srid as an integer
+ bbox_srid_ini = bbox_crs_ini.postgisSrid()
+
+
+ # The bbox coordinates should be in the correct srid, otherwise should be reprojected
+ if bbox_srid_ini != SRID[inputDataset]:
+ bbox_transform = QgsCoordinateTransform(QgsCoordinateReferenceSystem("EPSG:3111"),
+ QgsCoordinateReferenceSystem("EPSG:4326"),
+ QgsProject.instance())
+ # The rectangle has to be converted to geometry before transform...
+ bbox_geom = QgsGeometry.fromRect(bbox)
+ bbox_geom.transform(bbox_transform)
+ # The geometry has to be converted back to rectangle to get x and y min and max...
+ bbox = bbox_geom.boundingBox()
+
+ # Create the bbox as required by GeoClimate
+ bbox_coord = [bbox.xMinimum(),
+ bbox.yMinimum(),
+ bbox.xMaximum(),
+ bbox.yMaximum()]
+
+ # The location argument in the GeoClimate config file is replaced by
+ # the bbox coordinates
+ location = bbox_coord
+
+ if feedback:
+ feedback.setProgressText("Start GeoClimate calculations")
+ if feedback.isCanceled():
+ feedback.setProgressText("Calculation cancelled by user")
+ return {}
+
+ # Create the outputDirectory if not exists
+ if not os.path.exists(outputDirectory):
+ if os.path.exists(Path(outputDirectory).parent.absolute()):
+ os.mkdir(outputDirectory)
+ else:
+ raise QgsProcessingException('The output directory does not exist, neither its parent directory')
+ config_file_path = os.path.join(outputDirectory,
+ CONFIG_FILENAME.format(str(location).replace(',','_')))
+
+ # Fill in the indicator use list
+ estimateHeight = False
+ indicatorUse = []
+ if lczCalc:
+ indicatorUse.append("LCZ")
+ if tebInputs:
+ indicatorUse.append("TEB")
+ if utrfCalc:
+ indicatorUse.append("UTRF")
+ if wrfInputs:
+ indicatorUse.append("WRF")
+
+
+ # Create the json configuration file used by GeoClimate
+ config_file_content = {
+ "description": "GeoClimate configuration file created using the QGIS plug-in GeoClimateTool",
+ "input": {
+ "locations": [
+ location
+ ],
+ "area": 10000
+ },
+ "output": {
+ "folder": outputDirectory,
+ "tables": OUTPUT_TABLES
+ },
+ "parameters": {
+ "rsu_indicators": {
+ "indicatorUse": indicatorUse,
+ "svfSimplified": svfSimplified,
+ "estimateHeight": estimateHeight
+ }
+ }
+ }
+
+ # Serializing json
+ json_object = json.dumps(config_file_content, indent=4)
+
+ # Writing to sample.json
+ with open(config_file_path, "w") as outfile:
+ outfile.write(json_object)
+
+ # Define the java command line to be executed
+ java_cmd = f'java -jar {geoclim_jar_path} -w OSM -f {config_file_path}'
+
+ # Execute the GeoClimate workflow and log informations
+ for line in runProcess(java_cmd.split()):
+ feedback.setProgressText(line.decode("utf8"))
+
+
+ # ######################################################################
+ # ######################## LOAD DATA INTO QGIS #########################
+ # ######################################################################
+ # # Calculates the number of significant digits
+ # if NB_ISOVALUES < 10:
+ # sign_digits = 1
+ # else:
+ # sign_digits = 2
+
+ # # Load data into QGIS
+ # global layernames
+ # layernames = {}
+ # i = 0
+ # for tp in [DAY_TIME, NIGHT_TIME]:
+ # layernames[i] = Renamer(f"{scenarioDirectory.split(os.sep)[-1]} and {weatherScenario}: Park impact on air temperature at {tp}:00 (°C)")
+ # # Load the vector layer with a given style
+ # loadCoolParksVector(filepath = output_dt_path[tp] + ".geojson",
+ # layername = layernames[i],
+ # variable = None,
+ # subgroup = QgsLayerTreeGroup("parameter not used..."),
+ # vector_min = deltaT_min_value,
+ # vector_max = deltaT_max_value,
+ # feedback = feedback,
+ # context = context,
+ # valueZero = 0,
+ # opacity = DEFAULT_OPACITY)
+ # i += 1
+
+ # # Load building results into QGIS
+ # for var in BUILDING_LEGEND_PROCESS.index:
+ # layernames[i] = Renamer(f"{scenarioDirectory.split(os.sep)[-1]} and {weatherScenario}: {BUILDING_LEGEND_PROCESS[var]}")
+ # loadCoolParksVector(filepath = output_build_path,
+ # layername = layernames[i],
+ # variable = var,
+ # subgroup = QgsLayerTreeGroup("parameter not used..."),
+ # vector_min = gdf_build[var].min(),
+ # vector_max = gdf_build[var].max(),
+ # feedback = feedback,
+ # context = context,
+ # valueZero = 0,
+ # opacity = 1)
+ # i += 1
+
+ # # Return the output file names
+ # return {self.OUTPUT_DIRECTORY: scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER + os.sep + prefix}
+ # Return the output file names
+ return {self.OUTPUT_DIRECTORY: outputDirectory}
+
+ def name(self):
+ """
+ Returns the algorithm name, used for identifying the algorithm. This
+ string should be fixed for the algorithm, and must not be localised.
+ The name should be unique within each provider. Names should contain
+ lowercase alphanumeric characters only and no spaces or other
+ formatting characters.
+ """
+ return 'coolparkstool_process'
+
+ def displayName(self):
+ """
+ Returns the translated algorithm name, which should be used for any
+ user-visible display of the algorithm name.
+ """
+ return self.tr('GeoClimate workflow')
+
+ def group(self):
+ """
+ Returns the name of the group this algorithm belongs to. This string
+ should be localised.
+ """
+ return self.tr(self.groupId())
+
+ def groupId(self):
+ """
+ Returns the unique ID of the group this algorithm belongs to. This
+ string should be fixed for the algorithm, and must not be localised.
+ The group id should be unique within each provider. Group id should
+ contain lowercase alphanumeric characters only and no spaces or other
+ formatting characters.
+ """
+ return ''
+
+ def tr(self, string):
+ return QCoreApplication.translate('Processing', string)
+
+ def shortHelpString(self):
+ return self.tr('The GeoClimateTool "GeoClimate workflows" module is used '+
+ 'to:\n'+
+ ' - download data from OSM and convert to GIS files,\n'+
+ ' - calculates spatial indicators and typology from these files,\n'
+ '\n'
+ '\n'
+ '---------------\n'
+ 'Full manual available via the Help-button.')
+
+ def helpUrl(self):
+ url = "https://github.com/j3r3m1/geoclimatetool"
+ return url
+
+ def icon(self):
+ cmd_folder = Path(os.path.split(inspect.getfile(inspect.currentframe()))[0]).parent
+ icon = QIcon(str(cmd_folder) + "/icons/CoolParksTool.png")
+ return icon
+
+ def createInstance(self):
+ return GeoClimateProcessorAlgorithm()
diff --git a/processing_geoclimate.py b/processing_geoclimate.py
new file mode 100644
index 0000000..a921afd
--- /dev/null
+++ b/processing_geoclimate.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+
+"""
+/***************************************************************************
+ CoolParks tool
+ A QGIS plugin
+ Coolparks toolbox
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+ -------------------
+ begin : 2024-02-06
+ copyright : (C) 2024 by Jérémy Bernard
+ email : jeremy.bernard@zaclys.net
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+"""
+
+__author__ = 'Jérémy Bernard'
+__date__ = '2024-02-06'
+__copyright__ = '(C) 2024 by Jérémy Bernard'
+
+# This will get replaced with a git SHA1 when you do a git archive
+
+__revision__ = '$Format:%H$'
+
+import os
+import sys
+import inspect
+
+from qgis.core import QgsProcessingAlgorithm, QgsApplication
+from .processing_geoclimate_provider import ProcessingGeoClimateProvider
+
+cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]
+
+if cmd_folder not in sys.path:
+ sys.path.insert(0, cmd_folder)
+
+
+class ProcessingGeoClimatePlugin(object):
+
+ def __init__(self):
+ self.provider = None
+
+ def initProcessing(self):
+ """Init Processing provider for QGIS >= 3.8."""
+ self.provider = ProcessingGeoClimateProvider()
+ QgsApplication.processingRegistry().addProvider(self.provider)
+
+ def initGui(self):
+ self.initProcessing()
+
+ def unload(self):
+ QgsApplication.processingRegistry().removeProvider(self.provider)
+
+ def unload(self):
+ QgsApplication.processingRegistry().removeProvider(self.provider)
diff --git a/processing_geoclimate_provider.py b/processing_geoclimate_provider.py
new file mode 100644
index 0000000..94659f2
--- /dev/null
+++ b/processing_geoclimate_provider.py
@@ -0,0 +1,101 @@
+# -*- coding: utf-8 -*-
+
+"""
+/***************************************************************************
+ CoolParks tool
+ A QGIS plugin
+ Coolparks toolbox
+ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+ -------------------
+ begin : 2024-02-06
+ copyright : (C) 2024 by Jérémy Bernard
+ email : jeremy.bernard@zaclys.net
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+"""
+
+__author__ = 'Jérémy Bernard'
+__date__ = '2024-02-06'
+__copyright__ = '(C) 2024 by Jérémy Bernard'
+
+# This will get replaced with a git SHA1 when you do a git archive
+
+__revision__ = '$Format:%H$'
+
+from qgis.core import QgsProcessingProvider
+from processing.core.ProcessingConfig import ProcessingConfig
+
+from .processing_algorithm import GeoClimateProcessorAlgorithm
+
+import os.path
+from qgis.PyQt.QtGui import QIcon
+import inspect
+# from PyQt5.QtGui import QIcon
+
+class ProcessingGeoClimateProvider(QgsProcessingProvider):
+
+ def __init__(self):
+ """
+ Default constructor.
+ """
+ self.plugin_dir = os.path.dirname(__file__)
+ QgsProcessingProvider.__init__(self)
+
+ if not (os.path.isdir(self.plugin_dir + '/temp')):
+ os.mkdir(self.plugin_dir + '/temp')
+
+ def unload(self):
+ """
+ Unloads the provider. Any tear-down steps required by the provider
+ should be implemented here.
+ """
+ pass
+
+ def loadAlgorithms(self):
+ """
+ Loads all algorithms belonging to this provider.
+ """
+ # #Processor
+ self.addAlgorithm(GeoClimateProcessorAlgorithm())
+
+ def id(self):
+ """
+ Returns the unique provider id, used for identifying the provider. This
+ string should be a unique, short, character only string, eg "qgis" or
+ "gdal". This string should not be localised.
+ """
+ return 'GeoClimateTool'
+
+ def name(self):
+ """
+ Returns the provider name, which is used to describe the provider
+ within the GUI.
+
+ This string should be short (e.g. "Lastools") and localised.
+ """
+ return 'GeoClimateTool'
+
+ def icon(self):
+ """
+ Should return a QIcon which is used for your provider inside
+ the Processing toolbox.
+ """
+ icon = QIcon(os.path.dirname(__file__) + "/Icons/CoolParksTool.png")
+ return icon
+
+ def longName(self):
+ """
+ Returns the a longer version of the provider name, which can include
+ extra details such as version numbers. E.g. "Lastools LIDAR tools
+ (version 2.2.1)". This string should be localised. The default
+ implementation returns the same string as name().
+ """
+ return 'GeoClimateTool, Version 1.0.0'
diff --git a/pylintrc b/pylintrc
new file mode 100644
index 0000000..7e168f6
--- /dev/null
+++ b/pylintrc
@@ -0,0 +1,281 @@
+[MASTER]
+
+# Specify a configuration file.
+#rcfile=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Profiled execution.
+profile=no
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=CVS
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+
+[MESSAGES CONTROL]
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time. See also the "--disable" option for examples.
+#enable=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once).You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use"--disable=all --enable=classes
+# --disable=W"
+# see http://stackoverflow.com/questions/21487025/pylint-locally-defined-disables-still-give-warnings-how-to-suppress-them
+disable=locally-disabled,C0103
+
+
+[REPORTS]
+
+# Set the output format. Available formats are text, parseable, colorized, msvs
+# (visual studio) and html. You can also give a reporter class, eg
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Put messages in a separate file for each module / package specified on the
+# command line instead of printing them on stdout. Reports (if any) will be
+# written in a file name "pylint_global.[txt|html]".
+files-output=no
+
+# Tells whether to display a full report or only the messages
+reports=yes
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Add a comment according to your evaluation note. This is used by the global
+# evaluation report (RP0004).
+comment=no
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details
+#msg-template=
+
+
+[BASIC]
+
+# Required attributes for module, separated by a comma
+required-attributes=
+
+# List of builtins function names that should not be used, separated by a comma
+bad-functions=map,filter,apply,input
+
+# Regular expression which should only match correct module names
+module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
+
+# Regular expression which should only match correct module level names
+const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
+
+# Regular expression which should only match correct class names
+class-rgx=[A-Z_][a-zA-Z0-9]+$
+
+# Regular expression which should only match correct function names
+function-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct method names
+method-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct instance attribute names
+attr-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct argument names
+argument-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct variable names
+variable-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct attribute names in class
+# bodies
+class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
+
+# Regular expression which should only match correct list comprehension /
+# generator expression variable names
+inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
+
+# Good variable names which should always be accepted, separated by a comma
+good-names=i,j,k,ex,Run,_
+
+# Bad variable names which should always be refused, separated by a comma
+bad-names=foo,bar,baz,toto,tutu,tata
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=__.*__
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,XXX,TODO
+
+
+[TYPECHECK]
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# List of classes names for which member attributes should not be checked
+# (useful for classes with attributes dynamically set).
+ignored-classes=SQLObject
+
+# When zope mode is activated, add a predefined set of Zope acquired attributes
+# to generated-members.
+zope=no
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E0201 when accessed. Python regular
+# expressions are accepted.
+generated-members=REQUEST,acl_users,aq_parent
+
+
+[VARIABLES]
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# A regular expression matching the beginning of the name of dummy variables
+# (i.e. not used).
+dummy-variables-rgx=_$|dummy
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid to define new builtins when possible.
+additional-builtins=
+
+
+[FORMAT]
+
+# Maximum number of characters on a single line.
+max-line-length=80
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )??$
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+# List of optional constructs for which whitespace checking is disabled
+no-space-check=trailing-comma,dict-separator
+
+# Maximum number of lines in a module
+max-module-lines=1000
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string=' '
+
+
+[SIMILARITIES]
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+
+[IMPORTS]
+
+# Deprecated modules which should not be used, separated by a comma
+deprecated-modules=regsub,TERMIOS,Bastion,rexec
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled)
+import-graph=
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled)
+ext-import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled)
+int-import-graph=
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method
+max-args=5
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore
+ignored-argument-names=_.*
+
+# Maximum number of locals for function / method body
+max-locals=15
+
+# Maximum number of return / yield for function / method body
+max-returns=6
+
+# Maximum number of branch for function / method body
+max-branches=12
+
+# Maximum number of statements in function / method body
+max-statements=50
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+
+[CLASSES]
+
+# List of interface methods to ignore, separated by a comma. This is used for
+# instance to not check methods defines in Zope's Interface base class.
+ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,__new__,setUp
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=mcs
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "Exception"
+overgeneral-exceptions=Exception
diff --git a/util/__init__.py b/util/__init__.py
new file mode 100644
index 0000000..139a24d
--- /dev/null
+++ b/util/__init__.py
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+# __author__ = 'xlinfr'
+
+from qgis.PyQt.QtWidgets import QMessageBox
+from .coolparkstool_installer import setup_coolparkstool_python
+from qgis.core import Qgis, QgsMessageLog
+# we can specify a version if needed
+try:
+ import jaydebeapi
+except:
+ if QMessageBox.question(None, "CoolParksTool Python dependencies not installed",
+ "Do you automatically want install missing python modules? \r\n"
+ "QGIS will be non-responsive for a couple of minutes.",
+ QMessageBox.Ok | QMessageBox.Cancel) == QMessageBox.Ok:
+ try:
+ setup_coolparkstool_python(ver=None)
+ QMessageBox.information(None, "Packages successfully installed",
+ "To make all parts of the plugin work it is recommended to restart your QGIS-session.")
+ except Exception as e:
+ QMessageBox.information(None, "An error occurred",
+ "Packages not installed. report any errors to https://github.com/J3r3m1/CoolParksTool/issues")
+ else:
+ QMessageBox.information(None,
+ "Information", "Packages not installed. CoolParksTool will not be fully operational.")
diff --git a/util/coolparkstool_installer.py b/util/coolparkstool_installer.py
new file mode 100644
index 0000000..c1877bc
--- /dev/null
+++ b/util/coolparkstool_installer.py
@@ -0,0 +1,112 @@
+import sys, subprocess, os
+from pathlib import Path
+import platform
+from packaging import version
+
+
+# locate QGIS-python interpreter
+def locate_py():
+
+ # get Python version
+ str_ver_qgis = sys.version.split(" ")[0]
+
+ try:
+ # non-Linux
+ path_py = os.environ["PYTHONHOME"]
+ except Exception:
+ # Linux
+ path_py = sys.executable
+
+ # convert to Path for eaiser processing
+ path_py = Path(path_py)
+
+ # pre-defined paths for python executable
+ dict_pybin = {
+ "Darwin": path_py / "bin" / "python3",
+ "Windows": path_py
+ / (
+ "../../bin/pythonw.exe"
+ if version.parse(str_ver_qgis) >= version.parse("3.9.1")
+ else "pythonw.exe"
+ ),
+ "Linux": path_py,
+ }
+
+ # python executable
+ path_pybin = dict_pybin[platform.system()]
+
+ if path_pybin.exists():
+ return path_pybin
+ else:
+ raise RuntimeError("CoolParksTool cannot locate the Python interpreter used by QGIS!")
+
+
+# install CoolParksTool
+def install_coolparkstool_python(ver=None):
+ str_ver = f"=={ver}" if ver else ""
+ # get Python version
+ str_ver_qgis = sys.version.split(" ")[0]
+ try:
+ path_pybin = locate_py()
+ # update pip to use new features
+ list_cmd0 = f"{str(path_pybin)} -m pip install pip -U --user".split()
+ str_info0 = subprocess.check_output(
+ list_cmd0, stderr=subprocess.STDOUT, encoding="UTF8"
+ )
+
+ # add netCDF4 TODO: Should later be replaced with xarrays
+ # list_cmd0 = f"{str(path_pybin)} -m pip install netCDF4 -U --user".split()
+ # str_info0 = subprocess.check_output(
+ # list_cmd0, stderr=subprocess.STDOUT, encoding="UTF8"
+ # )
+
+ # install dependencies
+ str_use_feature = (
+ "--use-feature=2020-resolver"
+ if version.parse(str_ver_qgis) <= version.parse("3.9.1")
+ else ""
+ )
+ list_cmd = f"{str(path_pybin)} -m pip install coolparkstool-reqs{str_ver} -U --user {str_use_feature}".split()
+ str_info = subprocess.check_output(
+ list_cmd, stderr=subprocess.STDOUT, encoding="UTF8"
+ )
+
+ str_info = str_info.split("\n")[-2].strip()
+
+ str_info = (
+ str_info
+ if "Successfully installed CoolParksTool dependent Python packages" in str_info
+ else f"CoolParksTool dependent Python packages has already been installed!"
+ )
+ return str_info
+ except Exception:
+ raise RuntimeError(f"CoolParksTool couldn't install Python packages!") from Exception
+
+
+# uninstall supy
+def uninstall_coolparkstool_python():
+
+ try:
+ path_pybin = locate_py()
+ list_cmd = f"{str(path_pybin)} -m pip uninstall coolparkstool-reqs -y".split()
+ list_info = subprocess.check_output(list_cmd, encoding="UTF8").split("\n")
+
+ str_info = list_info[-2].strip()
+ return str_info
+ except Exception:
+ raise RuntimeError(f"CoolParksTool couldn't uninstall coolparkstool-reqs!") from Exception
+
+
+# set up umep
+def setup_coolparkstool_python(ver=None, debug=False):
+ if debug:
+ uninstall_coolparkstool_python()
+ install_coolparkstool_python(ver)
+
+ try:
+ # check if supy and others have been installed
+ import jaydebeapi
+
+ except Exception:
+ # install coolparkstool dependencies
+ install_coolparkstool_python(ver)
diff --git a/util/f90nml/__init__.py b/util/f90nml/__init__.py
new file mode 100644
index 0000000..6410f3d
--- /dev/null
+++ b/util/f90nml/__init__.py
@@ -0,0 +1,34 @@
+"""f90nml
+ ======
+
+ A Fortran 90 namelist parser and generator.
+
+ :copyright: Copyright 2014 Marshall Ward, see AUTHORS for details.
+ :license: Apache License, Version 2.0, see LICENSE for details.
+"""
+from __future__ import absolute_import
+# from f90nml.parser import Parser
+from .parser import Parser
+
+__version__ = '0.12'
+
+
+def read(nml_fname):
+ """Parse a Fortran 90 namelist file (data.nml) and store its contents.
+
+ >>> nml = f90nml.read('data.nml')"""
+ return Parser().read(nml_fname)
+
+
+def write(nml, nml_fname, force=False):
+ """Output namelist (nml) to a Fortran 90 namelist file (data.nml).
+
+ >>> f90nml.write(nml, 'data.nml')"""
+ nml.write(nml_fname, force=force)
+
+
+def patch(nml_fname, nml_patch, out_fname=None):
+ """Create a new namelist based on an input namelist and reference dict.
+
+ >>> f90nml.patch('data.nml', nml_patch, 'patched_data.nml')"""
+ return Parser().read(nml_fname, nml_patch, out_fname)
diff --git a/util/f90nml/fpy.py b/util/f90nml/fpy.py
new file mode 100644
index 0000000..74ebadf
--- /dev/null
+++ b/util/f90nml/fpy.py
@@ -0,0 +1,60 @@
+"""f90nml.fpy
+ =============
+
+ Module for conversion between basic data types and Fortran string
+ representations.
+
+ :copyright: Copyright 2014 Marshall Ward, see AUTHORS for details.
+ :license: Apache License, Version 2.0, see LICENSE for details.
+"""
+
+
+def pyfloat(v_str):
+ """Convert string repr of Fortran floating point to Python double."""
+ # NOTE: There is no loss of information from SP to DP floats
+
+ return float(v_str.lower().replace('d', 'e'))
+
+
+def pycomplex(v_str):
+ """Convert string repr of Fortran complex to Python complex."""
+ assert isinstance(v_str, str)
+
+ if v_str[0] == '(' and v_str[-1] == ')' and len(v_str.split(',')) == 2:
+ v_re, v_im = v_str[1:-1].split(',', 1)
+
+ # NOTE: Failed float(str) will raise ValueError
+ return complex(pyfloat(v_re), pyfloat(v_im))
+ else:
+ raise ValueError('{0} must be in complex number form (x, y).'
+ ''.format(v_str))
+
+
+def pybool(v_str):
+ """Convert string repr of Fortran logical to Python logical."""
+ assert isinstance(v_str, str)
+
+ try:
+ if v_str.startswith('.'):
+ v_bool = v_str[1].lower()
+ else:
+ v_bool = v_str[0].lower()
+ except IndexError:
+ raise ValueError('{0} is not a valid logical constant.'.format(v_str))
+
+ if v_bool == 't':
+ return True
+ elif v_bool == 'f':
+ return False
+ else:
+ raise ValueError('{0} is not a valid logical constant.'.format(v_str))
+
+
+def pystr(v_str):
+ """Convert string repr of Fortran string to Python string."""
+ assert isinstance(v_str, str)
+
+ if v_str[0] in ("'", '"') and v_str[0] == v_str[-1]:
+ return v_str[1:-1]
+ else:
+ return v_str
diff --git a/util/f90nml/namelist.py b/util/f90nml/namelist.py
new file mode 100644
index 0000000..b8221da
--- /dev/null
+++ b/util/f90nml/namelist.py
@@ -0,0 +1,326 @@
+"""f90nml.namelist
+ ===============
+
+ Tools for creating Fortran namelist files from Python ``dict``s.
+
+ :copyright: Copyright 2014 Marshall Ward, see AUTHORS for details.
+ :license: Apache License, Version 2.0, see LICENSE for details.
+"""
+from __future__ import print_function
+from builtins import str
+
+import os
+try:
+ from collections import OrderedDict
+except ImportError:
+ from ordereddict import OrderedDict
+
+
+class NmlDict(OrderedDict):
+ """Case-insensitive Python dict"""
+
+ def __init__(self, *args, **kwds):
+ super(NmlDict, self).__init__(*args, **kwds)
+
+ # Convert any internal dicts to NmlDicts
+ for key, val in list(self.items()):
+ if isinstance(val, dict):
+ self[key] = NmlDict(val)
+
+ # Formatting properties
+ self._colwidth = 72
+ self._indent = 4 * ' '
+ self._end_comma = False
+ self._uppercase = False
+ self._floatformat = ''
+ self._logical_repr = {False: '.false.', True: '.true.'}
+
+ # Representatation functions
+ self.f90str = {
+ bool:
+ lambda x: self.logical_repr[x],
+ int:
+ lambda x: str(x),
+ float:
+ lambda x: '{0:{fmt}}'.format(x, fmt=self.floatformat),
+ complex:
+ lambda x: '({0}, {1})'.format(x.real, x.imag),
+ str:
+ lambda x: repr(x).replace("\\'", "''").replace('\\"', '""'),
+ type(None):
+ lambda x: ''
+ }
+
+ def __contains__(self, key):
+ return super(NmlDict, self).__contains__(key.lower())
+
+ def __delitem__(self, key):
+ return super(NmlDict, self).__delitem__(key.lower())
+
+ def __getitem__(self, key):
+ return super(NmlDict, self).__getitem__(key.lower())
+
+ def __setitem__(self, key, value):
+ super(NmlDict, self).__setitem__(key.lower(), value)
+
+ # Format configuration
+
+ # Column width
+ @property
+ def colwidth(self):
+ """Return the target column width of the namelist file."""
+ return self._colwidth
+
+ @colwidth.setter
+ def colwidth(self, width):
+ """Validate and set the column width."""
+ if isinstance(width, int):
+ if width >= 0:
+ self._colwidth = width
+ else:
+ raise ValueError('Column width must be nonnegative.')
+ else:
+ raise TypeError('Column width must be a nonnegative integer.')
+
+ # Variable indent
+ @property
+ def indent(self):
+ """Return the indentation string within namelist group entries."""
+ return self._indent
+
+ @indent.setter
+ def indent(self, value):
+ """Validate and set the indent width, either as an explicit whitespace
+ string or by the number of whitespace characters.
+ """
+
+ # Explicit indent setting
+ if isinstance(value, str):
+ if value.isspace():
+ self._indent = value
+ else:
+ raise ValueError('String indentation can only contain '
+ 'whitespace.')
+
+ # Set indent width
+ elif isinstance(value, int):
+ if value >= 0:
+ self._indent = value * ' '
+ else:
+ raise ValueError('Indentation spacing must be nonnegative.')
+
+ else:
+ raise TypeError('Indentation must be specified by string or space '
+ 'width.')
+
+ # Terminal comma
+ @property
+ def end_comma(self):
+ """Return True if entries are terminated with commas."""
+ return self._end_comma
+
+ @end_comma.setter
+ def end_comma(self, value):
+ """Validate and set the comma termination flag."""
+ if not isinstance(value, bool):
+ raise TypeError('end_comma attribute must be a logical type.')
+ self._end_comma = value
+
+ # Uppercase
+ @property
+ def uppercase(self):
+ """Return True if names are displayed in upper case."""
+ return self._uppercase
+
+ @uppercase.setter
+ def uppercase(self, value):
+ """Validate and set the upper case flag."""
+ if not isinstance(value, bool):
+ raise TypeError('uppercase attribute must be a logical type.')
+ self._uppercase = value
+
+ # Float format
+ @property
+ def floatformat(self):
+ """Return the current floating point format code."""
+ return self._floatformat
+
+ @floatformat.setter
+ def floatformat(self, value):
+ """Validate and set the upper case flag."""
+ if isinstance(value, str):
+ # Duck-test the format string; raise ValueError on fail
+ '{0:{1}}'.format(1.23, value)
+
+ self._floatformat = value
+ else:
+ raise TypeError('Floating point format code must be a string.')
+
+ # Logical representation
+ # NOTE: This presumes that bools and ints are identical as dict keys
+ @property
+ def logical_repr(self):
+ """Return the namelist representations of logical values."""
+ return self._logical_repr
+
+ @logical_repr.setter
+ def logical_repr(self, value):
+ """Set the namelist representations of logical values."""
+
+ if not any(isinstance(value, t) for t in (list, tuple)):
+ raise TypeError("Logical representation must be a tuple with "
+ "a valid true and false value.")
+ if not len(value) == 2:
+ raise ValueError("List must contain two values.")
+
+ self.false_repr = value[0]
+ self.true_repr = value[1]
+
+ @property
+ def true_repr(self):
+ """Return the namelist representation of logical true."""
+ return self._logical_repr[1]
+
+ @true_repr.setter
+ def true_repr(self, value):
+ """Validate and set the logical true representation."""
+ if isinstance(value, str):
+ if not (value.lower().startswith('t') or
+ value.lower().startswith('.t')):
+ raise ValueError("Logical true representation must start with "
+ "'T' or '.T'.")
+ else:
+ self._logical_repr[1] = value
+ else:
+ raise TypeError('Logical true representation must be a string.')
+
+ @property
+ def false_repr(self):
+ """Return the namelist representation of logical false."""
+ return self._logical_repr[0]
+
+ @false_repr.setter
+ def false_repr(self, value):
+ """Validate and set the logical false representation."""
+ if isinstance(value, str):
+ if not (value.lower().startswith('f') or
+ value.lower().startswith('.f')):
+ raise ValueError("Logical false representation must start "
+ "with 'F' or '.F'.")
+ else:
+ self._logical_repr[0] = value
+ else:
+ raise TypeError('Logical false representation must be a string.')
+
+ # File output
+
+ def write(self, nml_path, force=False):
+ """Output dict to a Fortran 90 namelist file."""
+
+ if not force and os.path.isfile(nml_path):
+ raise IOError('File {0} already exists.'.format(nml_path))
+
+ with open(nml_path, 'w') as nml_file:
+ for grp_name, grp_vars in list(self.items()):
+ # Check for repeated namelist records (saved as lists)
+ if isinstance(grp_vars, list):
+ for g_vars in grp_vars:
+ self.write_nmlgrp(grp_name, g_vars, nml_file)
+ else:
+ self.write_nmlgrp(grp_name, grp_vars, nml_file)
+
+ if list(self.items()):
+ with open(nml_path, 'rb+') as nml_file:
+ nml_file.seek(-1, os.SEEK_END)
+ nml_file.truncate()
+
+ def write_nmlgrp(self, grp_name, grp_vars, nml_file):
+ """Write namelist group to target file."""
+
+ if self.uppercase:
+ grp_name = grp_name.upper()
+
+ print('&{0}'.format(grp_name), file=nml_file)
+
+ for v_name, v_val in list(grp_vars.items()):
+
+ for v_str in self.var_strings(v_name, v_val):
+ nml_line = self.indent + '{0}'.format(v_str)
+ print(nml_line, file=nml_file)
+
+ print('/', file=nml_file)
+ print(file=nml_file)
+
+ def var_strings(self, v_name, v_values):
+ """Convert namelist variable to list of fixed-width strings."""
+
+ if self.uppercase:
+ v_name = v_name.upper()
+
+ var_strs = []
+
+ # Parse derived type contents
+ if isinstance(v_values, dict):
+ for f_name, f_vals in list(v_values.items()):
+ v_title = '%'.join([v_name, f_name])
+
+ v_strs = self.var_strings(v_title, f_vals)
+ var_strs.extend(v_strs)
+
+ # Parse an array of derived types
+ elif (isinstance(v_values, list) and
+ any(isinstance(v, dict) for v in v_values) and
+ all((isinstance(v, dict) or v is None) for v in v_values)):
+ for idx, val in enumerate(v_values, start=1):
+
+ if val is None:
+ continue
+
+ v_title = v_name + '({0})'.format(idx)
+
+ v_strs = self.var_strings(v_title, val)
+ var_strs.extend(v_strs)
+
+ else:
+ if not isinstance(v_values, list):
+ v_values = [v_values]
+
+ # Split output across multiple lines (if necessary)
+ val_strs = []
+
+ val_line = ''
+ for v_val in v_values:
+
+ v_width = self.colwidth - len(self.indent + v_name + ' = ')
+
+ if len(val_line) < v_width:
+ val_line += self.f90repr(v_val) + ', '
+
+ if len(val_line) >= v_width:
+ val_strs.append(val_line.rstrip())
+ val_line = ''
+
+ # Append any remaining values
+ if val_line:
+ if (self.end_comma or
+ (len(v_values) > 1 and v_values[-1] is None)):
+ val_strs.append(val_line)
+ else:
+ val_strs.append(val_line[:-2])
+
+ # Complete the set of values
+ var_strs.append('{0} = {1}'.format(v_name, val_strs[0]).strip())
+
+ for v_str in val_strs[1:]:
+ var_strs.append(' ' * (len(v_name + ' = ')) + v_str)
+
+ return var_strs
+
+ def f90repr(self, value):
+ """Convert primitive Python types to equivalent Fortran strings."""
+
+ try:
+ return self.f90str[type(value)](value)
+ except KeyError:
+ raise ValueError('Type {0} of {1} cannot be converted to a '
+ 'Fortran type.'.format(type(value), value))
diff --git a/util/f90nml/parser.py b/util/f90nml/parser.py
new file mode 100644
index 0000000..466243e
--- /dev/null
+++ b/util/f90nml/parser.py
@@ -0,0 +1,495 @@
+"""f90nml.parser
+ =============
+
+ Fortran namelist parser and tokenizer to convert contents into a hierarchy
+ of dicts containing intrinsic Python data types.
+
+ :copyright: Copyright 2014 Marshall Ward, see AUTHORS for details.
+ :license: Apache License, Version 2.0, see LICENSE for details.
+"""
+from __future__ import absolute_import
+from builtins import next
+from builtins import range
+from builtins import object
+import copy
+import itertools
+import shlex
+from string import whitespace
+
+from .fpy import pyfloat, pycomplex, pybool, pystr
+from .namelist import NmlDict
+
+
+class Parser(object):
+ """shlex-based Fortran namelist parser."""
+
+ def __init__(self):
+
+ # Token management
+ self.tokens = None
+ self.token = None
+ self.prior_token = None
+
+ # Patching
+ self.pfile = None
+
+ def read(self, nml_fname, nml_patch_in=None, patch_fname=None):
+ """Parse a Fortran 90 namelist file and store the contents.
+
+ >>> from parser import Parser
+ >>> parser = Parser()
+ >>> data_nml = parser.read('data.nml')"""
+
+ nml_file = open(nml_fname, 'r')
+
+ if nml_patch_in:
+
+ if not isinstance(nml_patch_in, dict):
+ nml_file.close()
+ raise ValueError('Input patch must be a dict or an NmlDict.')
+
+ nml_patch = copy.deepcopy(NmlDict(nml_patch_in))
+
+ if not patch_fname:
+ patch_fname = nml_fname + '~'
+ elif nml_fname == patch_fname:
+ nml_file.close()
+ raise ValueError('f90nml: error: Patch filepath cannot be the '
+ 'same as the original filepath.')
+ self.pfile = open(patch_fname, 'w')
+ else:
+ nml_patch = NmlDict()
+
+ f90lex = shlex.shlex(nml_file)
+ f90lex.whitespace = ''
+ f90lex.wordchars += '.-+' # Include floating point tokens
+ if nml_patch:
+ f90lex.commenters = ''
+ else:
+ f90lex.commenters = '!'
+
+ self.tokens = iter(f90lex)
+
+ nmls = NmlDict()
+
+ # TODO: Replace "while True" with an update_token() iterator
+ self.update_tokens(write_token=False)
+ while True:
+ try:
+ # Check for classic group terminator
+ if self.token == 'end':
+ self.update_tokens()
+
+ # Ignore tokens outside of namelist groups
+ while self.token not in ('&', '$'):
+ self.update_tokens()
+
+ except StopIteration:
+ break
+
+ # Create the next namelist
+ self.update_tokens()
+ g_name = self.token
+
+ g_vars = NmlDict()
+ v_name = None
+
+ grp_patch = nml_patch.get(g_name, {})
+
+ # Populate the namelist group
+ while g_name:
+
+ if self.token not in ('=', '%', '('):
+ self.update_tokens()
+
+ # Set the next active variable
+ if self.token in ('=', '(', '%'):
+
+ try:
+ v_name, v_values = self.parse_variable(
+ g_vars, patch_nml=grp_patch)
+ except ValueError:
+ nml_file.close()
+ if self.pfile:
+ self.pfile.close()
+ raise
+
+ if v_name in g_vars:
+ v_prior_values = g_vars[v_name]
+ v_values = merge_values(v_prior_values, v_values)
+
+ if v_name in g_vars and isinstance(g_vars[v_name], dict):
+ g_vars[v_name].update(v_values)
+ else:
+ g_vars[v_name] = v_values
+
+ # Deselect variable
+ v_name = None
+ v_values = []
+
+ # Finalise namelist group
+ if self.token in ('/', '&', '$'):
+
+ # Append any remaining patched variables
+ for v_name, v_val in list(grp_patch.items()):
+ g_vars[v_name] = v_val
+ v_strs = nmls.var_strings(v_name, v_val)
+ for v_str in v_strs:
+ self.pfile.write(' {0}\n'.format(v_str))
+
+ # Append the grouplist to the namelist
+ if g_name in nmls:
+ g_update = nmls[g_name]
+
+ # Update to list of groups
+ if not isinstance(g_update, list):
+ g_update = [g_update]
+
+ g_update.append(g_vars)
+
+ else:
+ g_update = g_vars
+
+ nmls[g_name] = g_update
+
+ # Reset state
+ g_name, g_vars = None, None
+
+ try:
+ self.update_tokens()
+ except StopIteration:
+ break
+
+ nml_file.close()
+ if self.pfile:
+ self.pfile.close()
+
+ return nmls
+
+ def parse_variable(self, parent, patch_nml=None):
+ """Parse a variable and return its name and values."""
+
+ if not patch_nml:
+ patch_nml = NmlDict()
+
+ v_name = self.prior_token
+ v_values = []
+
+ # Patch state
+ patch_values = None
+ write_token = v_name not in patch_nml
+
+ if self.token == '(':
+
+ v_indices = self.parse_index()
+
+ # TODO: Multidimensional support
+ i_s = 1 if not v_indices[0][0] else v_indices[0][0]
+ i_e = v_indices[0][1]
+ i_r = 1 if not v_indices[0][2] else v_indices[0][2]
+
+ if i_e:
+ v_idx = iter(list(range(i_s, i_e, i_r)))
+ else:
+ v_idx = (i_s + i_r * k for k in itertools.count())
+ else:
+ v_idx = None
+
+ if self.token == '%':
+
+ # Resolve the derived type
+
+ if parent and v_name in parent:
+ v_parent = parent[v_name]
+ else:
+ v_parent = []
+
+ self.update_tokens()
+ self.update_tokens()
+
+ v_att, v_att_vals = self.parse_variable(v_parent)
+
+ next_value = NmlDict()
+ next_value[v_att] = v_att_vals
+ append_value(v_values, next_value, v_idx)
+
+ else:
+ # Construct the variable array
+
+ assert self.token == '='
+ n_vals = None
+ prior_ws_sep = ws_sep = False
+
+ self.update_tokens()
+
+ if v_name in patch_nml:
+ patch_values = patch_nml.f90repr(patch_nml.pop(v_name))
+ if not isinstance(patch_values, list):
+ patch_values = [patch_values]
+
+ for p_val in patch_values:
+ self.pfile.write(p_val)
+
+ # Add variables until next variable trigger
+ while (self.token not in ('=', '(', '%') or
+ (self.prior_token, self.token) == ('=', '(')):
+
+ # Check for repeated values
+ if self.token == '*':
+ n_vals = self.parse_value(write_token)
+ assert isinstance(n_vals, int)
+ self.update_tokens(write_token)
+ elif not n_vals:
+ n_vals = 1
+
+ # First check for implicit null values
+ if self.prior_token in ('=', '%', ','):
+ if (self.token in (',', '/', '&', '$') and
+ not (self.prior_token == ',' and
+ self.token in ('/', '&', '$'))):
+ append_value(v_values, None, v_idx, n_vals)
+
+ elif self.prior_token == '*':
+
+ if self.token not in ('/', '&', '$'):
+ self.update_tokens(write_token)
+
+ if (self.token == '=' or (self.token in ('/', '&', '$') and
+ self.prior_token == '*')):
+ next_value = None
+ else:
+ next_value = self.parse_value(write_token)
+
+ append_value(v_values, next_value, v_idx, n_vals)
+
+ else:
+ next_value = self.parse_value(write_token)
+
+ # Finished reading old value, we can again write tokens
+ write_token = True
+
+ # Check for escaped strings
+ if (v_values and isinstance(v_values[-1], str) and
+ isinstance(next_value, str) and not prior_ws_sep):
+
+ quote_char = self.prior_token[0]
+ v_values[-1] = quote_char.join([v_values[-1],
+ next_value])
+ else:
+ append_value(v_values, next_value, v_idx, n_vals)
+
+ # Exit for end of nml group (/, &, $) or null broadcast (=)
+ if self.token in ('/', '&', '$', '='):
+ break
+ else:
+ prior_ws_sep = ws_sep
+ ws_sep = self.update_tokens(write_token)
+
+ if patch_values:
+ v_values = patch_values
+
+ if not v_idx:
+ v_values = delist(v_values)
+
+ return v_name, v_values
+
+ def parse_index(self):
+ """Parse Fortran vector indices into a tuple of Python indices."""
+
+ v_name = self.prior_token
+ v_indices = []
+ i_start = i_end = i_stride = None
+
+ # Start index
+ self.update_tokens()
+ try:
+ i_start = int(self.token)
+ self.update_tokens()
+ except ValueError:
+ if self.token in (',', ')'):
+ raise ValueError('{0} index cannot be empty.'.format(v_name))
+ elif not self.token == ':':
+ raise
+
+ # End index
+ if self.token == ':':
+ self.update_tokens()
+ try:
+ i_end = 1 + int(self.token)
+ self.update_tokens()
+ except ValueError:
+ if self.token == ':':
+ raise ValueError('{0} end index cannot be implicit '
+ 'when using stride.'.format(v_name))
+ elif self.token not in (',', ')'):
+ raise
+ elif self.token in (',', ')'):
+ # Replace index with single-index range
+ if i_start:
+ i_end = 1 + i_start
+
+ # Stride index
+ if self.token == ':':
+ self.update_tokens()
+ try:
+ i_stride = int(self.token)
+ except ValueError:
+ if self.token == ')':
+ raise ValueError('{0} stride index cannot be '
+ 'implicit.'.format(v_name))
+ else:
+ raise
+
+ if i_stride == 0:
+ raise ValueError('{0} stride index cannot be zero.'
+ ''.format(v_name))
+
+ self.update_tokens()
+
+ if self.token not in (',', ')'):
+ raise ValueError('{0} index did not terminate '
+ 'correctly.'.format(v_name))
+
+ idx_triplet = (i_start, i_end, i_stride)
+ v_indices.append((idx_triplet))
+ self.update_tokens()
+
+ return v_indices
+
+ def parse_value(self, write_token=True):
+ """Convert string repr of Fortran type to equivalent Python type."""
+ v_str = self.prior_token
+
+ # Construct the complex string
+ if v_str == '(':
+ v_re = self.token
+
+ self.update_tokens(write_token)
+ assert self.token == ','
+
+ self.update_tokens(write_token)
+ v_im = self.token
+
+ self.update_tokens(write_token)
+ assert self.token == ')'
+
+ self.update_tokens(write_token)
+ v_str = '({0}, {1})'.format(v_re, v_im)
+
+ recast_funcs = [int, pyfloat, pycomplex, pybool, pystr]
+
+ for f90type in recast_funcs:
+ try:
+ value = f90type(v_str)
+ return value
+ except ValueError:
+ continue
+
+ def update_tokens(self, write_token=True):
+ """Update tokens to the next available values."""
+
+ ws_sep = False
+ next_token = next(self.tokens)
+
+ if self.pfile and write_token:
+ self.pfile.write(self.token)
+
+ # Commas between values are interpreted as whitespace
+ if self.token == ',':
+ ws_sep = True
+
+ while next_token in tuple(whitespace + '!'):
+
+ if self.pfile:
+ if next_token == '!':
+ while not next_token == '\n':
+ self.pfile.write(next_token)
+ next_token = next(self.tokens)
+ self.pfile.write(next_token)
+
+ ws_sep = True
+ next_token = next(self.tokens)
+
+ self.token, self.prior_token = next_token, self.token
+
+ return ws_sep
+
+
+# Support functions
+
+def append_value(v_values, next_value, v_idx=None, n_vals=1):
+ """Update a list of parsed values with a new value."""
+
+ for _ in range(n_vals):
+ if v_idx:
+ v_i = next(v_idx)
+
+ try:
+ # Default Fortran indexing starts at 1
+ v_values[v_i - 1] = next_value
+ except IndexError:
+ # Expand list to accommodate out-of-range indices
+ size = len(v_values)
+ v_values.extend(None for i in range(size, v_i))
+ v_values[v_i - 1] = next_value
+ else:
+ v_values.append(next_value)
+
+
+def merge_values(src, new):
+ """Merge two lists or dicts into a single element."""
+
+ if isinstance(src, dict) and isinstance(new, dict):
+ return merge_dicts(src, new)
+ else:
+ if not isinstance(src, list):
+ src = [src]
+ if not isinstance(new, list):
+ new = [new]
+
+ return merge_lists(src, new)
+
+
+def merge_lists(src, new):
+ """Update a value list with a list of new or updated values."""
+
+ l_min, l_max = (src, new) if len(src) < len(new) else (new, src)
+
+ l_min.extend(None for i in range(len(l_min), len(l_max)))
+
+ for i, val in enumerate(new):
+ if isinstance(val, dict) and isinstance(src[i], dict):
+ new[i] = merge_dicts(src[i], val)
+ elif val is not None:
+ new[i] = val
+ else:
+ new[i] = src[i]
+
+ return new
+
+
+def merge_dicts(src, patch):
+ """Merge contents of dict `patch` into `src`."""
+
+ for key in patch:
+ if key in src:
+ if isinstance(src[key], dict) and isinstance(patch[key], dict):
+ merge_dicts(src[key], patch[key])
+ else:
+ src[key] = merge_values(src[key], patch[key])
+ else:
+ src[key] = patch[key]
+
+ return src
+
+
+def delist(values):
+ """Reduce lists of zero or one elements to individual values."""
+ assert isinstance(values, list)
+
+ if not values:
+ return None
+ elif len(values) == 1:
+ return values[0]
+ else:
+ return values