├── .circleci └── config.yml ├── .gitignore ├── .gitmodules ├── .travis.yml ├── .woodpecker.yaml ├── AUTHORS ├── CHANGES.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── appveyor.yml ├── conda-recipe ├── bld.bat ├── build.sh └── meta.yaml ├── examples ├── tests │ └── test_examples.py ├── van_der_pol.ipynb ├── van_der_pol.png └── van_der_pol.py ├── pygslodeiv2 ├── __init__.py ├── _config.py ├── _gsl_odeiv2.pyx ├── _release.py ├── _util.py ├── include │ ├── gsl_odeiv2_anyode.hpp │ ├── gsl_odeiv2_anyode.pxd │ ├── gsl_odeiv2_anyode_nogil.pxd │ ├── gsl_odeiv2_anyode_parallel.hpp │ ├── gsl_odeiv2_anyode_parallel.pxd │ ├── gsl_odeiv2_cxx.hpp │ └── gsl_odeiv2_cxx.pxd └── tests │ ├── __init__.py │ └── test_gsl_odeiv2.py ├── scripts ├── build_conda_recipe.sh ├── check_clean_repo_on_master.sh ├── ci.sh ├── coverage_badge.py ├── generate_docs.sh ├── post_release.sh ├── prepare_deploy.sh ├── rasterize.js ├── release.sh ├── render_index.sh ├── render_notebooks.sh ├── run_tests.sh └── update-gh-pages.sh ├── setup.cfg ├── setup.py └── tests ├── Makefile ├── _gsl_odeiv2_anyode.pyx ├── _gsl_odeiv2_anyode.pyxbld ├── _test_gsl_odeiv2_anyode.py ├── cetsa_case.hpp ├── doctest.h.bz2 ├── doctest.h.url ├── test_gsl_odeiv2_anyode.cpp ├── test_gsl_odeiv2_anyode_autorestart.cpp ├── test_gsl_odeiv2_anyode_parallel.cpp ├── test_gsl_odeiv2_cxx.cpp └── testing_utils.hpp /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | jobs: 4 | build: 5 | docker: 6 | - image: continuumio/miniconda3 7 | steps: 8 | - checkout 9 | - run: apt-get update && apt-get --quiet --assume-yes install gcc g++ 10 | - run: conda config --set always_yes yes 11 | - run: conda update python 12 | - run: conda install conda-build 13 | - run: conda config --add channels conda-forge 14 | - run: conda config --set show_channel_urls true 15 | - run: conda build --python 3.6 conda-recipe 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/*.so 2 | **/__pycache__ 3 | **/*.pyc 4 | **/*.pyxbldc 5 | build/ 6 | dist/ 7 | cython_debug/ 8 | pygslodeiv2/_gsl_odeiv2.c* 9 | MANIFEST 10 | .*cache/ 11 | doc/ 12 | **/.ipynb_checkpoints/ 13 | **.egg-info 14 | tests/test_gsl_odeiv2_anyode 15 | tests/test_gsl_odeiv2_cxx 16 | tests/doctest.h 17 | tests/test_gsl_odeiv2_anyode_parallel 18 | tests/_gsl_odeiv2_anyode.cpp 19 | tests/test_gsl_odeiv2_anyode_autorestart 20 | tmp/ 21 | .coverage 22 | examples/index.html 23 | examples/thumbs/ 24 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "external/anyode"] 2 | path = external/anyode 3 | url = https://github.com/bjodah/anyode 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: generic 2 | os: osx 3 | osx_image: xcode6.4 4 | 5 | before_install: 6 | - | 7 | echo "" 8 | echo "Removing homebrew from Travis CI to avoid conflicts." 9 | curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall > ~/uninstall_homebrew 10 | chmod +x ~/uninstall_homebrew 11 | ~/uninstall_homebrew -fq 12 | rm ~/uninstall_homebrew 13 | 14 | install: 15 | - | 16 | echo "" 17 | echo "Installing a fresh version of Miniconda." 18 | MINICONDA_URL="https://repo.continuum.io/miniconda" 19 | MINICONDA_FILE="Miniconda3-latest-MacOSX-x86_64.sh" 20 | curl -L -O "${MINICONDA_URL}/${MINICONDA_FILE}" 21 | bash $MINICONDA_FILE -b 22 | 23 | # Configure conda. 24 | - | 25 | echo "" 26 | echo "Configuring conda." 27 | source /Users/travis/miniconda3/bin/activate root 28 | conda config --set always_yes yes 29 | conda update python 30 | conda install conda-build 31 | conda config --remove channels defaults 32 | conda config --add channels defaults 33 | conda config --add channels conda-forge 34 | conda config --set show_channel_urls true 35 | 36 | script: 37 | - conda build --python 3.6 conda-recipe 38 | 39 | notifications: 40 | email: false 41 | -------------------------------------------------------------------------------- /.woodpecker.yaml: -------------------------------------------------------------------------------- 1 | when: 2 | - event: [push] 3 | 4 | steps: 5 | - name: build-and-test 6 | image: cont-reg.bjodah.se:443/bjodah/triceratops-3:24 7 | environment: 8 | - PYTHONMALLOC=malloc 9 | commands: 10 | - ./scripts/ci.sh ${CI_REPO_NAME} 11 | - ./scripts/prepare_deploy.sh 12 | - if grep "DO-NOT-MERGE!" -R . --exclude ".woodpecker.yaml"; then exit 1; fi 13 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Bjoern I. Dahlgren 2 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | v0.9.6 2 | ====== 3 | - Another bump on AnyODE 4 | 5 | v0.9.5 6 | ====== 7 | - update AnyODE (fix refcounting bug) 8 | 9 | v0.9.4 10 | ====== 11 | - update AnyODE 12 | 13 | v0.9.3 14 | ====== 15 | - update setup.py to re-run Cython when .pyx available 16 | - update setup.py to new requirements in more recent versions of setuptools 17 | 18 | v0.9.2 19 | ====== 20 | - fix illegal escape sequence in setup.py 21 | 22 | v0.9.1 23 | ====== 24 | - New python signature: t is now a NumPy scalar 25 | 26 | v0.9.0 27 | ====== 28 | - Updated AnyODE version (19) 29 | 30 | v0.8.4 31 | ====== 32 | - Only require C++11 33 | 34 | v0.8.3 35 | ====== 36 | - Relax tests for 'time_cpu' & 'time_jac' 37 | 38 | v0.8.2 39 | ====== 40 | - New upstream AnyODE version (12) 41 | 42 | v0.8.1 43 | ====== 44 | - New upstream AnyODE version (11) 45 | 46 | v0.8.0 47 | ====== 48 | - New upstream AnyODE version (8) 49 | 50 | v0.7.4 51 | ====== 52 | - Fix signature in cython pxd 53 | 54 | v0.7.3 55 | ====== 56 | - return atol & rtol in info dict. 57 | 58 | v0.7.2 59 | ====== 60 | - support for record_rhs_xvals/record_jac_xvals/record_order/record_fpe 61 | 62 | v0.7.1 63 | ====== 64 | - get_dx_max_cb (callback to calculate dx_max) 65 | 66 | v0.7.0 67 | ====== 68 | - dx0cb 69 | - pygslodeiv2._config 70 | 71 | v0.6.1 72 | ====== 73 | - adaptive learned two new arguments: ``autorestart`` & ``return_on_error``. 74 | 75 | v0.6.0 76 | ====== 77 | - Changed development status from alpha to beta. 78 | - Refactored to use AnyODE base class (share code with pycvodes & pygslodeiv2) 79 | 80 | v0.5.2 81 | ====== 82 | - Fixes to setu.py 83 | 84 | v0.5.1 85 | ====== 86 | - ``nsteps`` kwarg added (maximum number of steps). 87 | - More robust setup.py 88 | 89 | v0.5.0 90 | ====== 91 | - Changes to info dict: rename 'nrhs' -> 'nfev', 'njac' -> 'njev', added 'cpu_time', 'success' 92 | 93 | v0.4.1 94 | ====== 95 | - Added support for (first) derivative in output 96 | - Min and max step now allowed to be set 97 | - Check against using dx0=0.0 98 | 99 | v0.4.0 100 | ====== 101 | - New function signature: integrate_predefined and integrate_adaptive now 102 | also return an info dict containing ``nrhs`` and ``njac`` conatining 103 | number of calls to each function made during last integration. 104 | - Expose ``gslodeiv2.steppers`` tuple. 105 | - check_callbable and check_indexing kwargs now defaults to False 106 | 107 | v0.3.3 108 | ====== 109 | - Fix minor memory leak 110 | - Made y read-only in Python callbacks 111 | - Do not overwrite Python error string when callback raises Exception. 112 | 113 | v0.3.2 114 | ====== 115 | - Ship tests with package (e.g.: python -m pytest --pyargs pygslodeiv2) 116 | 117 | v0.3.1 118 | ====== 119 | - Less strict callback checks on python side. 120 | - Minor C++ API clean up. 121 | 122 | 123 | v0.3.0 124 | ====== 125 | - Jacobian callback only need for steppers using it. 126 | 127 | v0.2.0 128 | ====== 129 | - integrate_predefined added. More extensive tesing of steppers. 130 | 131 | v0.1 132 | ==== 133 | - Integration using adaptive step-size supported. 134 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | pygslodeiv2 Copyright (C) 2015-2017 Björn Dahlgren 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | graft external/anyode/include 2 | graft external/anyode/cython_def 3 | include external/anyode/LICENSE 4 | recursive-include pygslodeiv2/include *.hpp *.pxd 5 | include pygslodeiv2/*.pyx 6 | include AUTHORS 7 | include CHANGES.rst 8 | include LICENSE 9 | include README.rst 10 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | pygslodeiv2 2 | =========== 3 | 4 | .. image:: http://hackspett.bjodah.se/api/badges/5/status.svg 5 | :target: http://hackspett.bjodah.se/repos/5 6 | :alt: Build status 7 | .. image:: https://img.shields.io/pypi/v/pygslodeiv2.svg 8 | :target: https://pypi.python.org/pypi/pygslodeiv2 9 | :alt: PyPI version 10 | .. image:: https://img.shields.io/pypi/l/pygslodeiv2.svg 11 | :target: https://github.com/bjodah/pygslodeiv2/blob/master/LICENSE 12 | :alt: License 13 | .. image:: http://artifacts.bjodah.se/pygslodeiv2/branches/master/htmlcov/coverage.svg 14 | :target: http://artifacts.bjodah.se/pygslodeiv2/branches/master/htmlcov/ 15 | :alt: coverage 16 | .. image:: https://zenodo.org/badge/41481237.svg 17 | :target: https://zenodo.org/badge/latestdoi/41481237 18 | :alt: Zenodo DOI 19 | 20 | 21 | `pygslodeiv2 `_ provides a 22 | `Python `_ binding to the 23 | `Ordinary Differential Equation `_ 24 | integration routines exposed by the `odeiv2 interface `_ of 25 | `GSL - GNU Scientific Library `_. 26 | The odeiv2 interface allows a user to numerically integrate (systems of) differential equations. 27 | 28 | The following `stepping functions `_ are available: 29 | 30 | - rk2 31 | - rk4 32 | - rkf45 33 | - rkck 34 | - rk8pd 35 | - rk1imp 36 | - rk2imp 37 | - rk4imp 38 | - bsimp 39 | - msadams 40 | - msbdf 41 | 42 | Note that all implicit steppers (those ending with "imp") and msbdf require a user supplied 43 | callback for calculating the jacobian. 44 | 45 | You may also want to know that you can use ``pygslodeiv2`` from 46 | `pyodesys `_ 47 | which can e.g. derive the Jacobian analytically (using SymPy). ``pyodesys`` also provides 48 | plotting functions, C++ code-generation and more. 49 | 50 | Documentation 51 | ------------- 52 | Autogenerated API documentation for latest stable release is found here: 53 | ``_ 54 | (and the development version for the current master branch are found here: 55 | ``_). 56 | 57 | Installation 58 | ------------ 59 | Simplest way to install is to use the `conda package manager `_: 60 | 61 | :: 62 | 63 | $ conda install -c conda-forge pygslodeiv2 pytest 64 | $ python -m pytest --pyargs pygslodeiv2 65 | 66 | tests should pass. 67 | 68 | Binary distribution is available here: 69 | ``_, conda recipes for stable releases are available here: 70 | ``_. 71 | 72 | Source distribution is available here (requires GSL v1.16 or v2.1 shared lib with headers): 73 | ``_ (with mirrored files kept here: 74 | ``_) 75 | 76 | Examples 77 | -------- 78 | The classic van der Pol oscillator (see `examples/van_der_pol.py `_) 79 | 80 | .. code:: python 81 | 82 | >>> import numpy as np 83 | >>> from pygslodeiv2 import integrate_predefined # also: integrate_adaptive 84 | >>> mu = 1.0 85 | >>> def f(t, y, dydt): 86 | ... dydt[0] = y[1] 87 | ... dydt[1] = -y[0] + mu*y[1]*(1 - y[0]**2) 88 | ... 89 | >>> def j(t, y, Jmat, dfdt): 90 | ... Jmat[0, 0] = 0 91 | ... Jmat[0, 1] = 1 92 | ... Jmat[1, 0] = -1 -mu*2*y[1]*y[0] 93 | ... Jmat[1, 1] = mu*(1 - y[0]**2) 94 | ... dfdt[0] = 0 95 | ... dfdt[1] = 0 96 | ... 97 | >>> y0 = [1, 0]; dt0=1e-8; t0=0.0; atol=1e-8; rtol=1e-8 98 | >>> tout = np.linspace(0, 10.0, 200) 99 | >>> yout, info = integrate_predefined(f, j, y0, tout, dt0, atol, rtol, 100 | ... method='bsimp') # Implicit Bulirsch-Stoer 101 | >>> import matplotlib.pyplot as plt 102 | >>> series = plt.plot(tout, yout) 103 | >>> plt.show() # doctest: +SKIP 104 | 105 | 106 | .. image:: https://raw.githubusercontent.com/bjodah/pygslodeiv2/master/examples/van_der_pol.png 107 | 108 | For more examples see `examples/ `_, and rendered jupyter notebooks here: 109 | ``_ 110 | 111 | 112 | License 113 | ------- 114 | The source code is Open Source and is released under GNU GPL v3. See `LICENSE `_ for further details. 115 | Contributors are welcome to suggest improvements at https://github.com/bjodah/pygslodeiv2 116 | 117 | Author 118 | ------ 119 | Björn I. Dahlgren, contact: 120 | 121 | - gmail address: bjodah 122 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | 3 | matrix: 4 | - TARGET_ARCH: x86 5 | CONDA_PY: 35 6 | CONDA_INSTALL_LOCN: C:\\Miniconda35 7 | 8 | - TARGET_ARCH: x64 9 | CONDA_PY: 35 10 | CONDA_INSTALL_LOCN: C:\\Miniconda35-x64 11 | 12 | platform: 13 | - x64 14 | 15 | install: 16 | # Cywing's git breaks conda-build. https://github.com/conda-forge/conda-smithy-feedstock/pull/2 17 | - cmd: rmdir C:\cygwin /s /q 18 | 19 | # Add path, activate `conda` and update conda. 20 | - cmd: call %CONDA_INSTALL_LOCN%\Scripts\activate.bat 21 | - cmd: conda update --yes --quiet conda 22 | 23 | - cmd: set PYTHONUNBUFFERED=1 24 | 25 | - cmd: conda config --set show_channel_urls true 26 | - cmd: conda install --yes --quiet conda-build 27 | - cmd: conda config --add channels conda-forge 28 | 29 | # Skip .NET project specific build phase. 30 | build: off 31 | 32 | test_script: 33 | - conda.exe build conda-recipe --quiet 34 | -------------------------------------------------------------------------------- /conda-recipe/bld.bat: -------------------------------------------------------------------------------- 1 | set "PYGSLODEIV2_BLAS=gslcblas" 2 | python -m pip install --no-deps --ignore-installed . 3 | -------------------------------------------------------------------------------- /conda-recipe/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | export PYGSLODEIV2_BLAS=openblas 3 | python -m pip install --no-deps --ignore-installed . 4 | -------------------------------------------------------------------------------- /conda-recipe/meta.yaml: -------------------------------------------------------------------------------- 1 | {% set name = "pygslodeiv2" %} 2 | {% set version = "0.9.0+git" %} 3 | {% set variant = "openblas" %} 4 | 5 | package: 6 | name: {{ name|lower }} 7 | version: {{ version }} 8 | 9 | source: 10 | git_url: ../ 11 | 12 | build: 13 | number: 200 14 | skip: true # [win] 15 | skip: true # [osx and py27] 16 | features: 17 | - blas_{{ variant }} # [not win] 18 | 19 | requirements: 20 | build: 21 | - toolchain 22 | - blas 1.1 {{ variant }} # [not win] 23 | - openblas 0.2.20* # [not win] 24 | - python 25 | - setuptools 26 | - pip 27 | - numpy 1.11.* 28 | - gsl 29 | - cython 30 | run: 31 | - blas 1.1 {{ variant }} # [not win] 32 | - openblas 0.2.20* # [not win] 33 | - python 34 | - numpy >=1.11 35 | - gsl 36 | 37 | test: 38 | imports: 39 | - {{ name }} 40 | requires: 41 | - pytest 42 | commands: 43 | - python -m pytest --pyargs {{ name }} 44 | 45 | about: 46 | home: https://github.com/bjodah/{{ name }} 47 | license: GPL-3.0 48 | license_file: LICENSE 49 | summary: 'Python binding for odeiv2 interface from GNU Scientific Library (GSL)' 50 | doc_url: https://bjodah.github.io/{{ name }}/latest 51 | 52 | extra: 53 | recipe-maintainers: 54 | - bjodah 55 | -------------------------------------------------------------------------------- /examples/tests/test_examples.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import glob 4 | import os 5 | import subprocess 6 | import sys 7 | 8 | import pytest 9 | 10 | 11 | tests = glob.glob(os.path.join(os.path.dirname(__file__), '../*.py')) 12 | 13 | 14 | @pytest.mark.parametrize('pypath', tests) 15 | def test_examples(pypath): 16 | py_exe = 'python3' if sys.version_info.major == 3 else 'python' 17 | p = subprocess.Popen([py_exe, pypath]) 18 | assert p.wait() == 0 # SUCCESS==0 19 | 20 | py_exe = 'python3' if sys.version_info.major == 3 else 'python' 21 | p = subprocess.Popen([py_exe, pypath, '--nt', '2']) 22 | assert p.wait() == 0 # SUCCESS==0 23 | -------------------------------------------------------------------------------- /examples/van_der_pol.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "collapsed": false 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "from pygslodeiv2 import integrate_predefined, fpes\n", 12 | "import numpy as np\n", 13 | "from van_der_pol import get_f_and_j" 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": { 20 | "collapsed": false 21 | }, 22 | "outputs": [], 23 | "source": [ 24 | "help(integrate_predefined)" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "metadata": { 31 | "collapsed": false 32 | }, 33 | "outputs": [], 34 | "source": [ 35 | "rhs, jac = get_f_and_j(1.0)\n", 36 | "xout = np.linspace(0, 10, 200)\n", 37 | "yout, info = integrate_predefined(\n", 38 | " rhs, jac, [0, 1], xout, dx0=1e-12, atol=1e-15, rtol=1e-15,\n", 39 | " record_rhs_xvals=True, record_jac_xvals=True, record_order=True,\n", 40 | " record_fpe=True, nsteps=2000)\n", 41 | "print(info['nfev'], info['success'], info['time_wall'])" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": { 48 | "collapsed": false 49 | }, 50 | "outputs": [], 51 | "source": [ 52 | "import matplotlib.pyplot as plt\n", 53 | "%matplotlib inline\n", 54 | "fig, axes = plt.subplots(5, 1, figsize=(16,16))\n", 55 | "for k, ax in zip(['steps', 'rhs', 'jac'], axes.flat):\n", 56 | " ax.vlines(xout if k == 'steps' else info[k + '_xvals'], 0, 1, transform=ax.get_xaxis_transform(),\n", 57 | " colors='darkgreen', alpha=0.006 if k == 'rhs' else 0.5)\n", 58 | " #for x in xout if k == 'steps' else info[k + '_xvals']:\n", 59 | " # ax.axvline(x, c='darkgreen', alpha=0.1)\n", 60 | " ax.plot(xout, yout)\n", 61 | " ax.set_xlim([xout[0], xout[-1]])\n", 62 | " ax.set_ylabel(k)\n", 63 | "axes[-2].plot(xout[1:], info['fpes'][1:] - fpes['FE_INEXACT'])\n", 64 | "axes[-2].set_ylabel('fpes')\n", 65 | "axes[-1].plot(xout, info['orders'])\n", 66 | "axes[-1].set_ylabel('order')\n", 67 | "_ = plt.tight_layout" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "metadata": { 74 | "collapsed": false 75 | }, 76 | "outputs": [], 77 | "source": [ 78 | "info.keys()" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "metadata": { 85 | "collapsed": false 86 | }, 87 | "outputs": [], 88 | "source": [ 89 | "fpes" 90 | ] 91 | } 92 | ], 93 | "metadata": { 94 | "kernelspec": { 95 | "display_name": "Python 3", 96 | "language": "python", 97 | "name": "python3" 98 | }, 99 | "language_info": { 100 | "codemirror_mode": { 101 | "name": "ipython", 102 | "version": 3 103 | }, 104 | "file_extension": ".py", 105 | "mimetype": "text/x-python", 106 | "name": "python", 107 | "nbconvert_exporter": "python", 108 | "pygments_lexer": "ipython3", 109 | "version": "3.5.2" 110 | } 111 | }, 112 | "nbformat": 4, 113 | "nbformat_minor": 0 114 | } 115 | -------------------------------------------------------------------------------- /examples/van_der_pol.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjodah/pygslodeiv2/3e15514f2987aa0e93ecad6dc97efdff9f6fed7e/examples/van_der_pol.png -------------------------------------------------------------------------------- /examples/van_der_pol.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example program integrating an IVP problem of van der Pol oscillator 6 | """ 7 | 8 | from __future__ import (absolute_import, division, print_function) 9 | 10 | import numpy as np 11 | from pygslodeiv2 import integrate_adaptive, integrate_predefined 12 | 13 | 14 | def get_f_and_j(mu): 15 | 16 | def f(t, y, dydt): 17 | dydt[0] = y[1] 18 | dydt[1] = -y[0] + mu*y[1]*(1 - y[0]**2) 19 | 20 | def j(t, y, Jmat, dfdt): 21 | Jmat[0, 0] = 0 22 | Jmat[0, 1] = 1 23 | Jmat[1, 0] = -1 - mu*2*y[1]*y[0] 24 | Jmat[1, 1] = mu*(1 - y[0]**2) 25 | dfdt[:] = 0 26 | 27 | return f, j 28 | 29 | 30 | def integrate_ivp(u0=1.0, v0=0.0, mu=1.0, tend=10.0, dt0=1e-8, nt=0, 31 | t0=0.0, atol=1e-8, rtol=1e-8, plot=False, savefig='None', 32 | method='bsimp', dpi=100, verbose=False): 33 | f, j = get_f_and_j(mu) 34 | if nt > 1: 35 | tout = np.linspace(t0, tend, nt) 36 | yout, info = integrate_predefined( 37 | f, j, [u0, v0], tout, dt0, atol, rtol, 38 | check_indexing=False, method=method) 39 | else: 40 | tout, yout, info = integrate_adaptive( 41 | f, j, [u0, v0], t0, tend, dt0, atol, rtol, 42 | check_indexing=False, method=method) # dfdt[:] also for len == 1 43 | if verbose: 44 | print(info) 45 | if plot: 46 | import matplotlib.pyplot as plt 47 | plt.plot(tout, yout) 48 | if savefig == 'None': 49 | plt.show() 50 | else: 51 | plt.savefig(savefig, dpi=dpi) 52 | 53 | 54 | if __name__ == '__main__': 55 | try: 56 | import argh 57 | argh.dispatch_command(integrate_ivp) 58 | except ImportError: 59 | integrate_ivp() 60 | -------------------------------------------------------------------------------- /pygslodeiv2/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Python binding for odeiv2 in GNU Scientific Library (GSL). 4 | """ 5 | 6 | from __future__ import division, absolute_import 7 | 8 | import numpy as np 9 | 10 | from ._gsl_odeiv2 import adaptive, predefined, requires_jac, steppers, fpes 11 | from ._util import _check_callable, _check_indexing, _ensure_5args 12 | from ._release import __version__ 13 | 14 | 15 | def get_include(): 16 | from pkg_resources import resource_filename, Requirement 17 | return resource_filename(Requirement.parse(__name__), 18 | '%s/include' % __name__) 19 | 20 | 21 | def integrate_adaptive(rhs, jac, y0, x0, xend, atol, rtol, dx0=.0, 22 | dx_min=.0, dx_max=.0, method='bsimp', nsteps=500, 23 | check_callable=False, check_indexing=False, 24 | autorestart=0, return_on_error=False, cb_kwargs=None, **kwargs): 25 | """ Integrates a system of ordinary differential equations (solver chosen output). 26 | 27 | Parameters 28 | ---------- 29 | rhs : callable 30 | Function with signature f(t, y, fout) which modifies fout *inplace*. 31 | jac : callable 32 | Function with signature j(t, y, jmat_out, dfdx_out) which modifies 33 | jmat_out and dfdx_out *inplace*. 34 | y0 : array_like 35 | initial values of the dependent variables 36 | x0 : float 37 | initial value of the independent variable 38 | xend : float 39 | stopping value for the independent variable 40 | atol : float 41 | absolute tolerance 42 | rtol : float 43 | relative tolerance 44 | dx0 : float 45 | initial step-size 46 | dx_min : float 47 | minimum step (default: 0.0) 48 | dx_max : float 49 | maximum step (default: 0.0) 50 | method : str 51 | One of: 'rk2', 'rk4', 'rkf45', 'rkck', 'rk8pd', 'rk1imp', 52 | 'rk2imp', 'rk4imp', 'bsimp', 'msadams', 'msbdf' 53 | nsteps : int 54 | maximum number of steps (default: 500) 55 | check_callable : bool (default: False) 56 | perform signature sanity checks on ``rhs`` and ``jac`` 57 | check_indexing : bool (default: False) 58 | perform item setting sanity checks on ``rhs`` and ``jac``. 59 | autorestart : int 60 | Autorestarts on error (requires autonomous system). 61 | return_on_error : bool 62 | Instead of raising an exception return silently (see info['success']). 63 | record_rhs_xvals : bool 64 | When True: will return x values for rhs calls in ``info['rhs_xvals']``. 65 | record_jac_xvals : bool 66 | When True will return x values for jac calls in ``info['jac_xvals']``. 67 | record_order : bool 68 | When True will return used time stepper order in ``info['orders']``. 69 | record_fpe : bool 70 | When True will return observed floating point errors in ``info['fpes']``. (see ``fpes``) 71 | cb_kwargs: dict 72 | Extra keyword arguments passed to ``rhs``, ``jac`` and possibly ``dx0cb``. 73 | dx0cb : callable 74 | Callback for calculating dx0 (make sure to pass dx0==0.0) to enable. 75 | Signature: ``f(x, y[:]) -> float``. 76 | dx_max_cb: callable 77 | Callback for calculating dx_max. Signature: ``f(x, y[:]) -> float``. 78 | 79 | Returns 80 | ------- 81 | (xout, yout, info): 82 | xout: 1-dimensional array of values for the independent variable 83 | yout: 2-dimensional array of the dependent variables (axis 1) for 84 | values corresponding to xout (axis 0) 85 | info: dictionary with information about the integration 86 | 87 | """ 88 | # Sanity checks to reduce risk of having a segfault: 89 | jac = _ensure_5args(jac) 90 | if check_callable: 91 | _check_callable(rhs, jac, x0, y0) 92 | 93 | if check_indexing: 94 | _check_indexing(rhs, jac, x0, y0) 95 | 96 | return adaptive(rhs, jac, np.ascontiguousarray(y0, dtype=np.float64), x0, 97 | xend, atol, rtol, method, nsteps, dx0, dx_min, dx_max, 98 | autorestart, return_on_error, cb_kwargs, **kwargs) 99 | 100 | 101 | def integrate_predefined(rhs, jac, y0, xout, atol, rtol, dx0=.0, 102 | dx_min=.0, dx_max=.0, method='bsimp', nsteps=500, 103 | check_callable=False, check_indexing=False, 104 | autorestart=0, return_on_error=False, cb_kwargs=None, **kwargs): 105 | """ Integrates a system of ordinary differential equations (user chosen output). 106 | 107 | Parameters 108 | ---------- 109 | rhs : callable 110 | Function with signature f(t, y, fout) which modifies fout *inplace*. 111 | jac : callable 112 | Function with signature j(t, y, jmat_out, dfdx_out) which modifies 113 | jmat_out and dfdx_out *inplace*. 114 | y0 : array_like 115 | initial values of the dependent variables 116 | xout : array_like 117 | values of the independent variable 118 | atol : float 119 | absolute tolerance 120 | rtol : float 121 | relative tolerance 122 | dx0 : float 123 | initial step-size 124 | dx_min : float 125 | minimum step (default: 0.0) 126 | dx_max : float 127 | maximum step (default: 0.0) 128 | method : str 129 | One of: 'rk2', 'rk4', 'rkf45', 'rkck', 'rk8pd', 'rk1imp', 130 | 'rk2imp', 'rk4imp', 'bsimp', 'msadams', 'msbdf'. 131 | nsteps : int 132 | maximum number of steps (default: 500). 133 | check_callable : bool 134 | perform signature sanity checks on ``rhs`` and ``jac``. 135 | check_indexing : bool 136 | perform item setting sanity checks on ``rhs`` and ``jac``. 137 | autorestart : int 138 | Autorestarts on error (requires autonomous system). 139 | return_on_error : bool 140 | Instead of raising an exception return silently (see info['success'] & info['nreached']). 141 | record_rhs_xvals : bool 142 | When True: will return x values for rhs calls in ``info['rhs_xvals']``. 143 | record_jac_xvals : bool 144 | When True will return x values for jac calls in ``info['jac_xvals']``. 145 | record_order : bool 146 | When True will return used time stepper order in ``info['orders']``. 147 | record_fpe : bool 148 | When True will return observed floating point errors in ``info['fpes']``. (see ``fpes``) 149 | cb_kwargs : dict 150 | Extra keyword arguments passed to ``rhs`` and ``jac``. 151 | dx0cb : callable 152 | Callback for calculating dx0 (make sure to pass dx0==0.0) to enable. 153 | Signature: ``f(x, y[:]) -> float``. 154 | dx_max_cb: callable 155 | Callback for calculating dx_max. Signature: ``f(x, y[:]) -> float``. 156 | 157 | Returns 158 | ------- 159 | (result, info): 160 | result: 2-dimensional array of the dependent variables (axis 1) for 161 | values corresponding to xout (axis 0) 162 | info: dictionary with information about the integration 163 | 164 | """ 165 | # Sanity checks to reduce risk of having a segfault: 166 | jac = _ensure_5args(jac) 167 | if check_callable: 168 | _check_callable(rhs, jac, xout[0], y0) 169 | 170 | if check_indexing: 171 | _check_indexing(rhs, jac, xout[0], y0) 172 | 173 | return predefined(rhs, jac, 174 | np.ascontiguousarray(y0, dtype=np.float64), 175 | np.ascontiguousarray(xout, dtype=np.float64), atol, rtol, 176 | method, nsteps, dx0, dx_min, dx_max, 177 | autorestart, return_on_error, cb_kwargs, **kwargs) 178 | -------------------------------------------------------------------------------- /pygslodeiv2/_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | env = { 4 | 'BLAS': 'gslcblas', 5 | 'GSL_LIBS': 'gsl' if os.name == 'nt' else 'gsl,m' 6 | } 7 | -------------------------------------------------------------------------------- /pygslodeiv2/_gsl_odeiv2.pyx: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8; mode: cython -*- 2 | # cython: language_level=3str 3 | # distutils: language = c++ 4 | 5 | from cpython.object cimport PyObject 6 | from libcpp cimport bool 7 | from libcpp.string cimport string 8 | from libcpp.vector cimport vector 9 | cimport numpy as cnp 10 | 11 | from anyode_numpy cimport PyOdeSys 12 | from gsl_odeiv2_cxx cimport styp_from_name, fpes as _fpes 13 | from gsl_odeiv2_anyode cimport simple_adaptive, simple_predefined 14 | 15 | import numpy as np 16 | 17 | ctypedef PyOdeSys[double, int] PyOdeSys_t 18 | 19 | cnp.import_array() # Numpy C-API initialization 20 | 21 | requires_jac = ('rk1imp', 'rk2imp', 'rk4imp', 'bsimp', 'msbdf') 22 | steppers = requires_jac + ('rk2', 'rk4', 'rkf45', 'rkck', 'rk8pd', 'msadams') 23 | fpes = {str(k.decode('utf-8')): v for k, v in dict(_fpes).items()} 24 | 25 | cdef dict get_last_info(PyOdeSys_t * odesys, success=True): 26 | info = {str(k.decode('utf-8')): v for k, v in dict(odesys.current_info.nfo_int).items()} 27 | info.update({str(k.decode('utf-8')): v for k, v in dict(odesys.current_info.nfo_dbl).items()}) 28 | info.update({str(k.decode('utf-8')): np.array(v, dtype=np.float64) for k, v in dict(odesys.current_info.nfo_vecdbl).items()}) 29 | info.update({str(k.decode('utf-8')): np.array(v, dtype=int) for k, v in dict(odesys.current_info.nfo_vecint).items()}) 30 | info['nfev'] = odesys.nfev 31 | info['njev'] = odesys.njev 32 | info['success'] = success 33 | return info 34 | 35 | def adaptive(rhs, jac, cnp.ndarray[cnp.float64_t, mode='c'] y0, double x0, double xend, double atol, 36 | double rtol, str method='bsimp', long int nsteps=500, double dx0=0.0, double dx_min=0.0, 37 | double dx_max=0.0, int autorestart=0, bool return_on_error=False, cb_kwargs=None, 38 | bool record_rhs_xvals=False, bool record_jac_xvals=False, bool record_order=False, 39 | bool record_fpe=False, dx0cb=None, dx_max_cb=None): 40 | cdef: 41 | int ny = y0.shape[y0.ndim - 1] 42 | int mlower=-1, mupper=-1, nquads=0, nroots=0, nnz=-1 43 | PyOdeSys_t * odesys 44 | 45 | if method in requires_jac and jac is None: 46 | raise ValueError("Method requires explicit jacobian callback") 47 | if np.isnan(y0).any(): 48 | raise ValueError("NaN found in y0") 49 | 50 | odesys = new PyOdeSys_t(ny, rhs, jac, NULL, NULL, NULL, 51 | cb_kwargs, mlower, mupper, nquads, nroots, dx0cb, dx_max_cb, nnz) 52 | odesys.record_rhs_xvals = record_rhs_xvals 53 | odesys.record_jac_xvals = record_jac_xvals 54 | odesys.record_order = record_order 55 | odesys.record_fpe = record_fpe 56 | 57 | try: 58 | xout, yout = map(np.asarray, simple_adaptive[PyOdeSys_t]( 59 | odesys, atol, rtol, styp_from_name(method.lower().encode('UTF-8')), 60 | &y0[0], x0, xend, nsteps, dx0, dx_min, dx_max, autorestart, return_on_error)) 61 | info = get_last_info(odesys, False if return_on_error and xout[-1] != xend else True) 62 | info['atol'], info['rtol'] = atol, rtol 63 | return xout, yout.reshape((xout.size, ny)), info 64 | finally: 65 | del odesys 66 | 67 | 68 | def predefined(rhs, jac, 69 | cnp.ndarray[cnp.float64_t, mode='c'] y0, 70 | cnp.ndarray[cnp.float64_t, ndim=1] xout, 71 | double atol, double rtol, str method='bsimp', int nsteps=500, double dx0=0.0, 72 | double dx_min=0.0, double dx_max=0.0, int autorestart=0, 73 | bool return_on_error=False, cb_kwargs=None, bool record_rhs_xvals=False, 74 | bool record_jac_xvals=False, bool record_order=False, bool record_fpe=False, 75 | dx0cb=None, dx_max_cb=None): 76 | cdef: 77 | int ny = y0.shape[y0.ndim - 1] 78 | cnp.ndarray[cnp.float64_t, ndim=2] yout = np.empty((xout.size, ny)) 79 | int nreached 80 | PyOdeSys_t * odesys 81 | int mlower=-1, mupper=-1, nquads=0, nroots=0, nnz=-1 82 | 83 | if method in requires_jac and jac is None: 84 | raise ValueError("Method requires explicit jacobian callback") 85 | if np.isnan(y0).any(): 86 | raise ValueError("NaN found in y0") 87 | odesys = new PyOdeSys_t(ny, rhs, jac, NULL, NULL, NULL, cb_kwargs, 88 | mlower, mupper, nquads, nroots, dx0cb, dx_max_cb, nnz) 89 | odesys.record_rhs_xvals = record_rhs_xvals 90 | odesys.record_jac_xvals = record_jac_xvals 91 | odesys.record_order = record_order 92 | odesys.record_fpe = record_fpe 93 | try: 94 | nreached = simple_predefined[PyOdeSys_t](odesys, atol, rtol, styp_from_name(method.lower().encode('UTF-8')), &y0[0], 95 | xout.size, &xout[0], yout.data, nsteps, 96 | dx0, dx_min, dx_max, autorestart, return_on_error) 97 | info = get_last_info(odesys, success=False if return_on_error and nreached < xout.size else True) 98 | info['nreached'] = nreached 99 | info['atol'], info['rtol'] = atol, rtol 100 | return yout.reshape((xout.size, ny)), info 101 | finally: 102 | del odesys 103 | -------------------------------------------------------------------------------- /pygslodeiv2/_release.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.9.3.dev0+git' 2 | -------------------------------------------------------------------------------- /pygslodeiv2/_util.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from __future__ import division 4 | 5 | import inspect 6 | 7 | import numpy as np 8 | 9 | 10 | def _check_callable(f, j, x0, y0): 11 | ny = len(y0) 12 | _fout = np.empty(ny) 13 | _ret = f(x0, y0, _fout) 14 | if _ret is not None: 15 | raise ValueError("f() must return None") 16 | 17 | if j is None: 18 | return # Not all methods require a jacobian 19 | 20 | _jmat_out = np.empty((ny, ny)) 21 | _dfdx_out = np.empty(ny) 22 | fy = None 23 | _ret = j(x0, y0, _jmat_out, _dfdx_out, fy) 24 | if _ret is not None: 25 | raise ValueError("j() must return None") 26 | 27 | 28 | def _check_indexing(f, j, x0, y0): 29 | ny = len(y0) 30 | _fout_short = np.empty(ny-1) 31 | try: 32 | f(x0, y0, _fout_short) 33 | except (IndexError, ValueError): 34 | pass 35 | else: 36 | raise ValueError("All elements in fout not assigned in f()") 37 | 38 | if j is None: 39 | return # Not all methods require a jacobian 40 | 41 | _dfdx_out = np.empty(ny) 42 | _jmat_out_short = np.empty((ny, ny-1)) 43 | fy = None 44 | try: 45 | j(x0, y0, _jmat_out_short, _dfdx_out, fy) 46 | except (IndexError, ValueError): 47 | pass 48 | else: 49 | raise ValueError("All elements in Jout not assigned in j()") 50 | 51 | _jmat_out = np.empty((ny, ny)) 52 | _dfdx_out_short = np.empty(ny-1) 53 | try: 54 | j(x0, y0, _jmat_out, _dfdx_out_short, fy) 55 | except (IndexError, ValueError): 56 | pass 57 | else: 58 | raise ValueError("All elements in dfdx_out not assigned in j()") 59 | 60 | 61 | def _ensure_5args(func): 62 | """ Conditionally wrap function to ensure 5 input arguments 63 | 64 | Parameters 65 | ---------- 66 | func: callable 67 | with four or five positional arguments 68 | 69 | Returns 70 | ------- 71 | callable which possibly ignores 0 or 1 positional arguments 72 | 73 | """ 74 | if func is None: 75 | return None 76 | 77 | self_arg = 1 if inspect.ismethod(func) else 0 78 | if hasattr(inspect, 'getfullargspec'): 79 | args = inspect.getfullargspec(func)[0] 80 | else: # Python 2: 81 | args = inspect.getargspec(func)[0] 82 | if len(args) == 5 + self_arg: 83 | return func 84 | elif len(args) == 4 + self_arg: 85 | return lambda t, y, J, dfdt, fy=None: func(t, y, J, dfdt) 86 | else: 87 | raise ValueError("Incorrect numer of arguments") 88 | -------------------------------------------------------------------------------- /pygslodeiv2/include/gsl_odeiv2_anyode.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include "anyode/anyode.hpp" 7 | #include "gsl_odeiv2_cxx.hpp" 8 | 9 | 10 | namespace gsl_odeiv2_anyode { 11 | 12 | using gsl_odeiv2_cxx::StepType; 13 | using gsl_odeiv2_cxx::GSLIntegrator; 14 | 15 | 16 | int handle_status_(AnyODE::Status status){ 17 | switch (status){ 18 | case AnyODE::Status::success: 19 | return GSL_SUCCESS; 20 | case AnyODE::Status::recoverable_error: 21 | return 99; // Any non-GSL specific error code 22 | case AnyODE::Status::unrecoverable_error: 23 | return GSL_EBADFUNC; 24 | default: 25 | throw std::runtime_error("impossible (this is for silencing -Wreturn-type)"); 26 | } 27 | } 28 | 29 | template // the *_cb functions allows us to pass C-pointer of a method. 30 | int rhs_cb(double t, const double y[], double ydot[], void *user_data) { 31 | auto& odesys = *static_cast(user_data); 32 | if (odesys.record_rhs_xvals) 33 | odesys.current_info.nfo_vecdbl["rhs_xvals"].push_back(t); 34 | AnyODE::Status status = odesys.rhs(t, y, ydot); 35 | return handle_status_(status); 36 | } 37 | 38 | template 39 | int jac_dense_cb(double t, const double y[], double *dfdy, double dfdt[], void *user_data) { 40 | // callback of req. signature wrapping OdeSys method. 41 | auto& odesys = *static_cast(user_data); 42 | if (odesys.record_jac_xvals) 43 | odesys.current_info.nfo_vecdbl["jac_xvals"].push_back(t); 44 | AnyODE::Status status = odesys.dense_jac_rmaj(t, y, nullptr, dfdy, odesys.get_ny(), dfdt); 45 | return handle_status_(status); 46 | } 47 | 48 | 49 | template 50 | GSLIntegrator get_integrator(OdeSys * odesys, 51 | const double atol, 52 | const double rtol, 53 | const StepType styp, 54 | const double dx0=0.0, 55 | const double dx_min=0.0, 56 | const double dx_max=0.0, 57 | const long int mxsteps=0, 58 | const bool record_order=false, 59 | const bool record_fpe=false 60 | ) 61 | { 62 | const int ny = odesys->get_ny(); 63 | GSLIntegrator integr {rhs_cb, jac_dense_cb, ny, styp, dx0, atol, rtol, static_cast(odesys)}; 64 | integr.record_order = record_order; 65 | integr.record_fpe = record_fpe; 66 | if (dx0 != 0.0) 67 | integr.m_drv.set_init_step(dx0); 68 | if (dx_min != 0.0) 69 | integr.m_drv.set_min_step(dx_min); 70 | if (dx_max != 0.0) 71 | integr.m_drv.set_max_step(dx_max); 72 | if (mxsteps) 73 | integr.m_drv.set_max_num_steps(mxsteps); 74 | return integr; 75 | } 76 | 77 | template 78 | void set_integration_info(OdeSys * odesys, const GSLIntegrator& integrator){ 79 | odesys->current_info.nfo_int["nfev"] = odesys->nfev; 80 | odesys->current_info.nfo_int["njev"] = odesys->njev; 81 | odesys->current_info.nfo_int["n_steps"] = integrator.get_n_steps(); 82 | odesys->current_info.nfo_int["n_failed_steps"] = integrator.get_n_failed_steps(); 83 | } 84 | 85 | template 86 | std::pair, std::vector > 87 | simple_adaptive(OdeSys * const odesys, 88 | const double atol, 89 | const double rtol, 90 | const StepType styp, 91 | const double * const y0, 92 | const double x0, 93 | const double xend, 94 | long int mxsteps=0, 95 | double dx0=0.0, 96 | const double dx_min=0.0, 97 | const double dx_max=0.0, 98 | int autorestart=0, 99 | bool return_on_error=false) 100 | { 101 | if (dx0 == 0.0) 102 | dx0 = odesys->get_dx0(x0, y0); 103 | if (dx0 == 0.0){ 104 | if (x0 == 0) 105 | dx0 = std::numeric_limits::epsilon() * 100; 106 | else 107 | dx0 = std::numeric_limits::epsilon() * 100 * x0; 108 | } 109 | if (mxsteps == 0) 110 | mxsteps = 500; 111 | auto integr = get_integrator(odesys, atol, rtol, styp, dx0, dx_min, dx_max, mxsteps, 112 | odesys->record_order, odesys->record_fpe); 113 | odesys->integrator = static_cast(&integr); 114 | 115 | odesys->current_info.clear(); 116 | if (odesys->record_rhs_xvals) 117 | odesys->current_info.nfo_vecdbl["rhs_xvals"] = {}; 118 | if (odesys->record_jac_xvals) 119 | odesys->current_info.nfo_vecdbl["jac_xvals"] = {}; 120 | 121 | std::time_t cput0 = std::clock(); 122 | auto t_start = std::chrono::high_resolution_clock::now(); 123 | 124 | auto result = integr.adaptive(x0, xend, y0, autorestart, return_on_error, 125 | ((odesys->use_get_dx_max) ? static_cast( 126 | std::bind(&OdeSys::get_dx_max, odesys, std::placeholders::_1 , std::placeholders::_2)) 127 | : gsl_odeiv2_cxx::get_dx_max_fn())); 128 | 129 | odesys->current_info.nfo_dbl["time_cpu"] = (std::clock() - cput0) / (double)CLOCKS_PER_SEC; 130 | odesys->current_info.nfo_dbl["time_wall"] = std::chrono::duration( 131 | std::chrono::high_resolution_clock::now() - t_start).count(); 132 | 133 | if (odesys->record_order) 134 | odesys->current_info.nfo_vecint["orders"] = integr.orders_seen; 135 | if (odesys->record_fpe) 136 | odesys->current_info.nfo_vecint["fpes"] = integr.fpes_seen; 137 | 138 | set_integration_info(odesys, integr); 139 | return result; 140 | } 141 | 142 | template 143 | int simple_predefined(OdeSys * const odesys, 144 | const double atol, 145 | const double rtol, 146 | const StepType styp, 147 | const double * const y0, 148 | const std::size_t nout, 149 | const double * const xout, 150 | double * const yout, 151 | long int mxsteps=0, 152 | double dx0=0.0, 153 | const double dx_min=0.0, 154 | const double dx_max=0.0, 155 | int autorestart=0, 156 | bool return_on_error=false 157 | ) 158 | { 159 | if (dx0 == 0.0) 160 | dx0 = odesys->get_dx0(xout[0], y0); 161 | if (dx0 == 0.0){ 162 | if (xout[0] == 0) 163 | dx0 = std::numeric_limits::epsilon() * 1000; 164 | else 165 | dx0 = std::numeric_limits::epsilon() * 1000 * xout[0]; 166 | } 167 | if (mxsteps == 0) 168 | mxsteps = 500; 169 | auto integr = get_integrator(odesys, atol, rtol, styp, dx0, dx_min, dx_max, mxsteps, 170 | odesys->record_order, odesys->record_fpe); 171 | odesys->integrator = static_cast(&integr); 172 | 173 | odesys->current_info.clear(); 174 | if (odesys->record_rhs_xvals) 175 | odesys->current_info.nfo_vecdbl["rhs_xvals"] = {}; 176 | if (odesys->record_jac_xvals) 177 | odesys->current_info.nfo_vecdbl["jac_xvals"] = {}; 178 | 179 | std::time_t cput0 = std::clock(); 180 | auto t_start = std::chrono::high_resolution_clock::now(); 181 | 182 | int nreached = integr.predefined(nout, xout, y0, yout, autorestart, return_on_error, 183 | ((odesys->use_get_dx_max) ? static_cast( 184 | std::bind(&OdeSys::get_dx_max, odesys, std::placeholders::_1 , std::placeholders::_2)) 185 | : gsl_odeiv2_cxx::get_dx_max_fn())); 186 | 187 | odesys->current_info.nfo_dbl["time_cpu"] = (std::clock() - cput0) / (double)CLOCKS_PER_SEC; 188 | odesys->current_info.nfo_dbl["time_wall"] = std::chrono::duration( 189 | std::chrono::high_resolution_clock::now() - t_start).count(); 190 | 191 | if (odesys->record_order) 192 | odesys->current_info.nfo_vecint["orders"] = integr.orders_seen; 193 | if (odesys->record_fpe) 194 | odesys->current_info.nfo_vecint["fpes"] = integr.fpes_seen; 195 | 196 | set_integration_info(odesys, integr); 197 | return nreached; 198 | } 199 | 200 | } 201 | -------------------------------------------------------------------------------- /pygslodeiv2/include/gsl_odeiv2_anyode.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8; mode: cython -*- 2 | 3 | from libcpp cimport bool 4 | from libcpp.vector cimport vector 5 | from libcpp.utility cimport pair 6 | 7 | from gsl_odeiv2_cxx cimport StepType 8 | 9 | cdef extern from "gsl_odeiv2_anyode.hpp" namespace "gsl_odeiv2_anyode": 10 | 11 | cdef pair[vector[double], vector[double]] simple_adaptive[U]( 12 | U * const, 13 | const double, 14 | const double, 15 | const StepType, 16 | const double * const, 17 | const double, 18 | const double, 19 | const long int, 20 | const double, 21 | const double, 22 | const double, 23 | int, 24 | bool 25 | ) except + 26 | 27 | cdef int simple_predefined[U]( 28 | U * const, 29 | const double, 30 | const double, 31 | const StepType, 32 | const double * const, 33 | const size_t, 34 | const double * const, 35 | double * const, 36 | const long int, 37 | const double, 38 | const double, 39 | const double, 40 | int, 41 | bool 42 | ) except + 43 | -------------------------------------------------------------------------------- /pygslodeiv2/include/gsl_odeiv2_anyode_nogil.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8; mode: cython -*- 2 | 3 | from libcpp cimport bool 4 | from libcpp.vector cimport vector 5 | from libcpp.utility cimport pair 6 | 7 | from gsl_odeiv2_cxx cimport StepType 8 | 9 | cdef extern from "gsl_odeiv2_anyode.hpp" namespace "gsl_odeiv2_anyode": 10 | 11 | cdef pair[vector[double], vector[double]] simple_adaptive[U]( 12 | U * const, 13 | const double, 14 | const double, 15 | const StepType, 16 | const double * const, 17 | const double, 18 | const double, 19 | const long int, 20 | const double, 21 | const double, 22 | const double, 23 | int, 24 | bool 25 | ) except + nogil 26 | 27 | cdef void simple_predefined[U]( 28 | U * const, 29 | const double, 30 | const double, 31 | const StepType, 32 | const double * const, 33 | const size_t, 34 | const double * const, 35 | double * const, 36 | const long int, 37 | const double, 38 | const double, 39 | const double 40 | ) except + nogil 41 | -------------------------------------------------------------------------------- /pygslodeiv2/include/gsl_odeiv2_anyode_parallel.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include "anyode/anyode_parallel.hpp" 5 | #include "gsl_odeiv2_anyode.hpp" 6 | 7 | namespace gsl_odeiv2_anyode_parallel { 8 | 9 | using gsl_odeiv2_cxx::StepType; 10 | using gsl_odeiv2_anyode::simple_adaptive; 11 | using gsl_odeiv2_anyode::simple_predefined; 12 | 13 | using sa_t = std::pair, std::vector >; 14 | 15 | template 16 | std::vector 17 | multi_adaptive(std::vector odesys, // vectorized 18 | const double atol, 19 | const double rtol, 20 | const StepType styp, 21 | const double * const y0, // vectorized 22 | const double * t0, // vectorized 23 | const double * tend, // vectorized 24 | const long int mxsteps, 25 | const double * dx0, // vectorized 26 | const double * dx_min, // vectorized 27 | const double * dx_max, // vectorized 28 | int autorestart=0, 29 | bool return_on_error=false 30 | ){ 31 | const int ny = odesys[0]->get_ny(); 32 | const int nsys = odesys.size(); 33 | auto results = std::vector(nsys); 34 | 35 | anyode_parallel::ThreadException te; 36 | char * num_threads_var = std::getenv("ANYODE_NUM_THREADS"); 37 | int nt = (num_threads_var) ? std::atoi(num_threads_var) : 1; 38 | if (nt < 0) 39 | nt = 1; 40 | #pragma omp parallel for num_threads(nt) // OMP_NUM_THREADS should be 1 for openblas LU (small matrices) 41 | for (int idx=0; idx( 45 | odesys[idx], atol, rtol, styp, y0 + idx*ny, t0[idx], tend[idx], 46 | mxsteps, dx0[idx], dx_min[idx], dx_max[idx], autorestart, return_on_error); 47 | }); 48 | results[idx] = local_result; 49 | } 50 | te.rethrow(); 51 | 52 | return results; 53 | } 54 | 55 | template 56 | std::vector 57 | multi_predefined(std::vector odesys, // vectorized 58 | const double atol, 59 | const double rtol, 60 | const StepType styp, 61 | const double * const y0, // vectorized 62 | const std::size_t nout, 63 | const double * const tout, // vectorized 64 | double * const yout, // vectorized 65 | const long int mxsteps, 66 | const double * dx0, // vectorized 67 | const double * dx_min, // vectorized 68 | const double * dx_max, 69 | int autorestart=0, 70 | bool return_on_error=false 71 | ){ 72 | const int ny = odesys[0]->get_ny(); 73 | const int nsys = odesys.size(); 74 | std::vector result(nsys); 75 | 76 | anyode_parallel::ThreadException te; 77 | #pragma omp parallel for 78 | for (int idx=0; idx( 81 | odesys[idx], atol, rtol, styp, y0 + idx*ny, 82 | nout, tout + idx*nout, yout + idx*ny*nout, 83 | mxsteps, dx0[idx], dx_min[idx], dx_max[idx], 84 | autorestart, return_on_error); 85 | }); 86 | } 87 | te.rethrow(); 88 | return result; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /pygslodeiv2/include/gsl_odeiv2_anyode_parallel.pxd: -------------------------------------------------------------------------------- 1 | # -*- mode: cython -*- 2 | # -*- coding: utf-8 -*- 3 | 4 | from libcpp cimport bool 5 | from libcpp.vector cimport vector 6 | from libcpp.utility cimport pair 7 | from gsl_odeiv2_cxx cimport StepType 8 | 9 | cdef extern from "gsl_odeiv2_anyode_parallel.hpp" namespace "gsl_odeiv2_anyode_parallel": 10 | cdef vector[pair[vector[double], vector[double]]] multi_adaptive[U]( 11 | vector[U*], 12 | double, 13 | double, 14 | StepType, 15 | const double * const, 16 | const double *, 17 | const double *, 18 | long int, 19 | double *, 20 | double *, 21 | double *, 22 | int, 23 | bool 24 | ) except + nogil 25 | 26 | cdef vector[int] multi_predefined[U]( 27 | vector[U*], 28 | double, 29 | double, 30 | StepType, 31 | const double * const, 32 | size_t, 33 | const double * const, 34 | double * const, 35 | long int, 36 | double *, 37 | double *, 38 | double *, 39 | int, 40 | bool 41 | ) except + nogil 42 | -------------------------------------------------------------------------------- /pygslodeiv2/include/gsl_odeiv2_cxx.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | 18 | //pragma STDC FENV_ACCESS on // GCC 5.4 does not seem to support the pragma 19 | 20 | namespace { 21 | class StreamFmt 22 | { 23 | std::stringstream m_s; 24 | public: 25 | StreamFmt() {} 26 | ~StreamFmt() {} 27 | 28 | template 29 | StreamFmt& operator << (const T& v) { 30 | this->m_s << v; 31 | return *this; 32 | } 33 | 34 | std::string str() const { 35 | return this->m_s.str(); 36 | } 37 | operator std::string() const { 38 | return this->m_s.str(); 39 | } 40 | 41 | }; 42 | } 43 | 44 | 45 | namespace gsl_odeiv2_cxx { 46 | 47 | using get_dx_max_fn = std::function< 48 | double(double, const double * const)>; 49 | 50 | static const std::unordered_map fpes {{ 51 | {"FE_INEXACT", FE_INEXACT}, 52 | {"FE_UNDERFLOW", FE_UNDERFLOW}, 53 | {"FE_OVERFLOW", FE_OVERFLOW}, 54 | {"FE_INVALID", FE_INVALID}, 55 | {"FE_DIVBYZERO", FE_DIVBYZERO} 56 | }}; 57 | 58 | std::string get_gslerror_string(int flag){ 59 | switch(flag){ // from gsl_errno.h 60 | case GSL_SUCCESS: 61 | return "GSL_SUCCESS"; 62 | case GSL_FAILURE: 63 | return "GSL_FAILURE"; 64 | case GSL_CONTINUE: 65 | return "GSL_CONTINUE (iteration has not converged)"; 66 | case GSL_EDOM: 67 | return "GSL_EDOM (input domain error, e.g sqrt(-1))"; 68 | case GSL_ERANGE: 69 | return "GSL_ERANGE (output range error, e.g. exp(1e100))"; 70 | case GSL_EFAULT: 71 | return "GSL_EFAULT (invalid pointer)"; 72 | case GSL_EINVAL: 73 | return "GSL_EINVAL (invalid argument supplied by user)"; 74 | case GSL_EFAILED: 75 | return "GSL_EFAILED (generic failure)"; 76 | case GSL_EFACTOR: 77 | return "GSL_EFACTOR (factorization failed)"; 78 | case GSL_ESANITY: 79 | return "GSL_ESANITY (sanity check failed - shouldn't happen)"; 80 | case GSL_ENOMEM: 81 | return "GSL_ENOMEM (malloc failed)"; 82 | case GSL_EBADFUNC: 83 | return "GSL_EBADFUNC (problem with user-supplied function)"; 84 | case GSL_ERUNAWAY: 85 | return "GSL_ERUNAWAY (iterative process is out of control)"; 86 | case GSL_EMAXITER: 87 | return "GSL_EMAXITER (exceeded max number of iterations)"; 88 | case GSL_EZERODIV: 89 | return "GSL_EZERODIV (tried to divide by zero)"; 90 | case GSL_EBADTOL: 91 | return "GSL_EBADTOL (user specified an invalid tolerance)"; 92 | case GSL_ETOL: 93 | return "GSL_ETOL (failed to reach the specified tolerance)"; 94 | case GSL_EUNDRFLW: 95 | return "GSL_EUNDRFLW (underflow)"; 96 | case GSL_EOVRFLW: 97 | return "GSL_EOVRFLW (overflow )"; 98 | case GSL_ELOSS: 99 | return "GSL_ELOSS (loss of accuracy)"; 100 | case GSL_EROUND: 101 | return "GSL_EROUND (failed because of roundoff error)"; 102 | case GSL_EBADLEN: 103 | return "GSL_EBADLEN (matrix, vector lengths are not conformant)"; 104 | case GSL_ENOTSQR: 105 | return "GSL_ENOTSQR (matrix not square)"; 106 | case GSL_ESING: 107 | return "GSL_ESING (apparent singularity detected)"; 108 | case GSL_EDIVERGE: 109 | return "GSL_EDIVERGE (integral or series is divergent)"; 110 | case GSL_EUNSUP: 111 | return "GSL_EUNSUP (requested feature is not supported by the hardware)"; 112 | case GSL_EUNIMPL: 113 | return "GSL_EUNIMPL (requested feature not (yet) implemented)"; 114 | case GSL_ECACHE: 115 | return "GSL_ECACHE (cache limit exceeded)"; 116 | case GSL_ETABLE: 117 | return "GSL_ETABLE (table limit exceeded)"; 118 | case GSL_ENOPROG: 119 | return "GSL_ENOPROG (iteration is not making progress towards solution)"; 120 | case GSL_ENOPROGJ: 121 | return "GSL_ENOPROGJ (jacobian evaluations are not improving the solution)"; 122 | case GSL_ETOLF: 123 | return "GSL_ETOLF (cannot reach the specified tolerance in F)"; 124 | case GSL_ETOLX: 125 | return "GSL_ETOLX (cannot reach the specified tolerance in X)"; 126 | case GSL_ETOLG: 127 | return "GSL_ETOLG (cannot reach the specified tolerance in gradient)"; 128 | case GSL_EOF: 129 | return "GSL_EOF (end of file)"; 130 | default: 131 | return StreamFmt() << "Unkown error code " << flag; 132 | } 133 | } 134 | 135 | 136 | enum class StepType : int {RK2=0, RK4=1, RKF45=2, RKCK=3, RK8PD=4, 137 | RK1IMP=5, RK2IMP=6, RK4IMP=7, BSIMP=8, MSADAMS=9, MSBDF=10}; 138 | 139 | StepType styp_from_name(std::string name){ 140 | if (name == "rk2") 141 | return StepType::RK2; 142 | else if (name == "rk4") 143 | return StepType::RK4; 144 | else if (name == "rkf45") 145 | return StepType::RKF45; 146 | else if (name == "rkck") 147 | return StepType::RKCK; 148 | else if (name == "rk8pd") 149 | return StepType::RK8PD; 150 | else if (name == "rk1imp") 151 | return StepType::RK1IMP; 152 | else if (name == "rk2imp") 153 | return StepType::RK2IMP; 154 | else if (name == "rk4imp") 155 | return StepType::RK4IMP; 156 | else if (name == "bsimp") 157 | return StepType::BSIMP; 158 | else if (name == "msadams") 159 | return StepType::MSADAMS; 160 | else if (name == "msbdf") 161 | return StepType::MSBDF; 162 | else 163 | throw std::runtime_error(StreamFmt() << "Unknown stepper type name: " << name); 164 | } 165 | bool requires_jacobian(StepType styp){ 166 | if ((styp == StepType::RK1IMP) || (styp == StepType::RK2IMP) || 167 | (styp == StepType::RK4IMP) || (styp == StepType::BSIMP) || 168 | (styp == StepType::MSBDF)) 169 | return true; 170 | else 171 | return false; 172 | } 173 | 174 | 175 | const gsl_odeiv2_step_type * get_step_type(int index){ 176 | switch(index){ 177 | case 0: 178 | return gsl_odeiv2_step_rk2; 179 | case 1: 180 | return gsl_odeiv2_step_rk4; 181 | case 2: 182 | return gsl_odeiv2_step_rkf45; 183 | case 3: 184 | return gsl_odeiv2_step_rkck; 185 | case 4: 186 | return gsl_odeiv2_step_rk8pd; 187 | case 5: 188 | return gsl_odeiv2_step_rk1imp; 189 | case 6: 190 | return gsl_odeiv2_step_rk2imp; 191 | case 7: 192 | return gsl_odeiv2_step_rk4imp; 193 | case 8: 194 | return gsl_odeiv2_step_bsimp; 195 | case 9: 196 | return gsl_odeiv2_step_msadams; 197 | case 10: 198 | return gsl_odeiv2_step_msbdf; 199 | default: 200 | throw std::logic_error("Unknown steptype index"); 201 | } 202 | } 203 | 204 | typedef int (*RhsFn)(double t, const double y[], double dydt[], void *params); 205 | typedef int (*JacFn)(double t, const double y[], double *dfdy, double dfdt[], void *params); 206 | 207 | struct Driver { 208 | gsl_odeiv2_driver *m_driver; 209 | Driver(const gsl_odeiv2_system * sys, 210 | const gsl_odeiv2_cxx::StepType styp, 211 | const double init_step, 212 | const double atol, 213 | const double rtol) : m_driver(gsl_odeiv2_driver_alloc_y_new( 214 | sys, get_step_type(static_cast(styp)), init_step, atol, rtol)) 215 | {} 216 | ~Driver() { gsl_odeiv2_driver_free(this->m_driver); } 217 | int set_init_step(const double hstart) { return gsl_odeiv2_driver_reset_hstart(m_driver, hstart); } 218 | int set_min_step(double hmin) { return gsl_odeiv2_driver_set_hmin(m_driver, hmin); } 219 | int set_max_step(double hmax) { return gsl_odeiv2_driver_set_hmax(m_driver, hmax); } 220 | int set_max_num_steps(const unsigned long int nmax) { return gsl_odeiv2_driver_set_nmax(m_driver, nmax); } 221 | unsigned long int get_max_num_steps() { return m_driver->nmax; } 222 | int apply(double * t, const double t1, double y[]){ 223 | return gsl_odeiv2_driver_apply(m_driver, t, t1, y); 224 | } 225 | int reset() { return gsl_odeiv2_driver_reset(m_driver); } 226 | }; 227 | struct Step { 228 | gsl_odeiv2_step *m_step; 229 | Step(const StepType styp, const size_t dim) : 230 | m_step(gsl_odeiv2_step_alloc(get_step_type(static_cast(styp)), dim)) {} 231 | ~Step() { gsl_odeiv2_step_free(m_step); } 232 | int reset() { return gsl_odeiv2_step_reset(m_step); } 233 | unsigned int order() { return gsl_odeiv2_step_order(m_step); } 234 | int set_driver(Driver& d) { return gsl_odeiv2_step_set_driver(m_step, d.m_driver); } 235 | int apply(double t, double h, double y[], double yerr[], const double dydt_in[], 236 | double dydt_out[], const gsl_odeiv2_system * sys) { 237 | return gsl_odeiv2_step_apply(m_step, t, h, y, yerr, dydt_in, dydt_out, sys); 238 | } 239 | }; 240 | struct Control { 241 | gsl_odeiv2_control *m_control; 242 | Control(double eps_abs, double eps_rel, double a_y=1, double a_dydt=0, 243 | const double scale_abs[]=nullptr, size_t dim=0) : 244 | m_control((scale_abs == nullptr) ? 245 | gsl_odeiv2_control_standard_new(eps_abs, eps_rel, a_y, a_dydt) : 246 | gsl_odeiv2_control_scaled_new(eps_abs, eps_rel, a_y, 247 | a_dydt, scale_abs, dim)) {} 248 | ~Control() { gsl_odeiv2_control_free(m_control); } 249 | int set_driver(Driver& d) { return gsl_odeiv2_control_set_driver(m_control, d.m_driver); } 250 | int init(double eps_abs, double eps_rel, double a_y, double a_dydt){ 251 | return gsl_odeiv2_control_init(m_control, eps_abs, eps_rel, a_y, a_dydt); 252 | } 253 | int hadjust(Step& s, const double y[], const double yerr[], const double dydt[], double *h){ 254 | return gsl_odeiv2_control_hadjust(m_control, s.m_step, y, yerr, dydt, h); 255 | } 256 | }; 257 | struct Evolve { 258 | gsl_odeiv2_evolve *m_evolve; 259 | Evolve(size_t dim) : m_evolve(gsl_odeiv2_evolve_alloc(dim)) {} 260 | ~Evolve() { gsl_odeiv2_evolve_free(this->m_evolve); } 261 | int set_driver(Driver& d) { return gsl_odeiv2_evolve_set_driver(m_evolve, d.m_driver); } 262 | int apply(Control& con, Step& step, gsl_odeiv2_system * sys, double *t, 263 | double t1, double *h, double y[]) { 264 | return gsl_odeiv2_evolve_apply(m_evolve, con.m_control, step.m_step, 265 | sys, t, t1, h, y); 266 | } 267 | int reset() { return gsl_odeiv2_evolve_reset(m_evolve); } 268 | }; 269 | 270 | void stderr_handle_error(const char * reason, 271 | const char * file, 272 | int line, 273 | int gsl_errno) { 274 | std::fprintf(stderr, "GSL Error: %s (in %s, line %d, gsl_errno: %d)", reason, file, line, gsl_errno); 275 | } 276 | 277 | struct ErrorHandler { 278 | gsl_error_handler_t *m_ori_handler; 279 | ErrorHandler() { 280 | m_ori_handler = gsl_set_error_handler(&stderr_handle_error); 281 | } 282 | ~ErrorHandler() { 283 | if (m_ori_handler) 284 | this->release(); 285 | } 286 | void release() { 287 | gsl_set_error_handler(m_ori_handler); 288 | } 289 | }; 290 | 291 | struct GSLIntegrator{ 292 | gsl_odeiv2_system m_sys; 293 | Driver m_drv; 294 | Step m_stp; 295 | Control m_ctrl; 296 | Evolve m_evo; 297 | int ny; 298 | 299 | bool record_order = false, record_fpe = false; 300 | std::vector orders_seen, fpes_seen; 301 | 302 | GSLIntegrator(RhsFn rhs_cb, JacFn jac_cb, int ny, const StepType styp, 303 | double dx0, double atol, double rtol, void * user_data, int mxsteps=500) : 304 | m_sys(gsl_odeiv2_system({rhs_cb, jac_cb, static_cast(ny), user_data})), 305 | m_drv(Driver(&(m_sys), styp, dx0, atol, rtol)), 306 | m_stp(Step(styp, ny)), 307 | m_ctrl(Control(atol, rtol)), 308 | m_evo(Evolve(ny)), 309 | ny(ny) 310 | { 311 | this->m_stp.set_driver(this->m_drv); 312 | this->m_ctrl.set_driver(this->m_drv); 313 | this->m_evo.set_driver(this->m_drv); 314 | this->m_drv.set_max_num_steps(mxsteps); 315 | } 316 | 317 | int get_n_steps() const { 318 | // return this->m_drv.m_driver->e->count; 319 | return this->m_evo.m_evolve->count; 320 | } 321 | int get_n_failed_steps() const { 322 | // return this->m_drv.m_driver->e->failed_steps; 323 | return this->m_evo.m_evolve->failed_steps; 324 | } 325 | int get_current_order() { 326 | return gsl_odeiv2_step_order(m_stp.m_step); 327 | } 328 | std::string unsuccessful_msg_(int flag, double current_time, double last_step){ 329 | return StreamFmt() << std::scientific << "[GSL ERROR] Unsuccessful step (t=" 330 | << current_time << ", h=" << last_step << "): " << 331 | get_gslerror_string(flag); 332 | } 333 | std::pair, std::vector > 334 | adaptive(const double x0, 335 | const double xend, 336 | const double * const y0, 337 | int autorestart=0, 338 | bool return_on_error=false, 339 | get_dx_max_fn get_dx_max = get_dx_max_fn() 340 | ){ 341 | ErrorHandler errh; // has side-effects; 342 | unsigned idx = 0; 343 | const unsigned long int mxsteps = this->m_drv.get_max_num_steps(); 344 | std::vector xout; 345 | std::vector yout; 346 | double curr_x = x0; 347 | double curr_dx = this->m_drv.m_driver->h; 348 | xout.push_back(curr_x); 349 | if (record_order) 350 | orders_seen.push_back(get_current_order()); // len(orders_seen) == len(xout) 351 | if (record_fpe){ 352 | std::feclearexcept(FE_ALL_EXCEPT); 353 | fpes_seen.push_back(std::fetestexcept(FE_ALL_EXCEPT)); 354 | } 355 | yout.insert(yout.end(), y0, y0 + ny); 356 | if (curr_x == xend) 357 | goto done; 358 | while (curr_x < xend){ 359 | idx++; 360 | if (idx > mxsteps){ 361 | std::string msg = StreamFmt() << std::scientific << "[GSL_ODEIV2_CXX ERROR] Maximum number of steps reached (at t=" 362 | << curr_x << "): " << mxsteps << '\n'; 363 | if (return_on_error){ 364 | std::cerr << msg << '\n'; 365 | break; 366 | }else{ 367 | throw std::runtime_error(msg); 368 | } 369 | } 370 | if (curr_dx > this->m_drv.m_driver->hmax){ 371 | curr_dx = this->m_drv.m_driver->hmax; 372 | } else if (curr_dx < this->m_drv.m_driver->hmin ) { 373 | curr_dx = this->m_drv.m_driver->hmin; 374 | } 375 | for (int i=0; im_drv.set_max_step(get_dx_max(curr_x, &(*(yout.end() - ny)))); 380 | int info = this->m_evo.apply(this->m_ctrl, this->m_stp, &(this->m_sys), 381 | &curr_x, xend, &curr_dx, &(*(yout.end() - ny))); 382 | xout.push_back(curr_x); 383 | if (record_order) 384 | orders_seen.push_back(get_current_order()); 385 | if (record_fpe){ 386 | fpes_seen.push_back(std::fetestexcept(FE_ALL_EXCEPT)); 387 | std::feclearexcept(FE_ALL_EXCEPT); 388 | } 389 | if (info == GSL_SUCCESS) { 390 | ; 391 | } else if (autorestart) { 392 | this->m_stp.reset(); 393 | this->m_evo.reset(); 394 | this->m_drv.set_max_num_steps(mxsteps - idx); 395 | const double last_x = xout.back(); 396 | auto inner = this->adaptive(0, xend - last_x, &yout[idx-1], autorestart-1, return_on_error); 397 | xout.pop_back(); 398 | for (const auto& v : inner.first) 399 | xout.push_back(v + last_x); 400 | yout.insert(yout.end(), inner.second.begin() + ny, inner.second.end()); 401 | this->m_drv.set_max_num_steps(mxsteps); 402 | break; 403 | } else { 404 | std::string msg; 405 | if (info == GSL_FAILURE) 406 | msg = StreamFmt() << std::scientific 407 | << "gsl_odeiv2_evolve_apply failed at t= " << curr_x 408 | << " with stepsize=" << curr_dx << " (step size too small).\n"; 409 | else 410 | msg = unsuccessful_msg_(info, curr_x, curr_dx); 411 | 412 | if (return_on_error) { 413 | xout.pop_back(); 414 | for (int idx=0; idx, std::vector>(xout, yout); 425 | } 426 | 427 | int predefined(std::size_t nt, 428 | const double * const tout, 429 | const double * const y0, 430 | double * const yout, 431 | int autorestart=0, 432 | bool return_on_error=false, 433 | get_dx_max_fn get_dx_max = get_dx_max_fn() 434 | ){ 435 | ErrorHandler errh; // has side-effects; 436 | double curr_t = tout[0]; 437 | bool error_ = false; 438 | size_t iout; 439 | std::string message; 440 | this->m_drv.reset(); 441 | std::copy(y0, y0 + (this->ny), yout); 442 | if (record_order) 443 | orders_seen.push_back(get_current_order()); 444 | if (record_fpe){ 445 | std::feclearexcept(FE_ALL_EXCEPT); 446 | fpes_seen.push_back(std::fetestexcept(FE_ALL_EXCEPT)); 447 | } 448 | for (iout=1; iout < nt; ++iout){ 449 | std::copy(yout + (this->ny)*(iout-1), 450 | yout + (this->ny)*iout, 451 | yout + (this->ny)*iout); 452 | if (get_dx_max) 453 | this->m_drv.set_max_step(get_dx_max(tout[iout-1], yout + iout*(this->ny))); 454 | int info = this->m_drv.apply(&curr_t, tout[iout], yout + iout*(this->ny)); 455 | if (info == GSL_SUCCESS){ 456 | if (tout[iout] != curr_t){ 457 | error_ = true; 458 | message = "Did not reach requested time."; 459 | } 460 | if (record_order) 461 | orders_seen.push_back(get_current_order()); 462 | if (record_fpe){ 463 | fpes_seen.push_back(std::fetestexcept(FE_ALL_EXCEPT)); 464 | std::feclearexcept(FE_ALL_EXCEPT); 465 | } 466 | } else if (info == GSL_EMAXITER){ 467 | error_ = true; 468 | message = StreamFmt() << std::scientific 469 | << "gsl_odeiv2_driver_apply failed at t= " << tout[iout + 1] 470 | << " with stepsize=" << this->m_drv.m_driver->e->last_step 471 | << " (maximum number of iterations reached)."; 472 | } else if (info == GSL_ENOPROG) { 473 | error_ = true; 474 | message = StreamFmt() << std::scientific 475 | << "gsl_odeiv2_driver_apply failed at t= " << tout[iout + 1] 476 | << " with stepsize=" << this->m_drv.m_driver->e->last_step 477 | << " (step size too small)."; 478 | } else { 479 | error_ = true; 480 | message = StreamFmt() << std::scientific 481 | << "gsl_odeiv2_driver_apply failed at t= " << tout[iout + 1] 482 | << " with stepsize=" << this->m_drv.m_driver->e->last_step 483 | << " (unknown error code: "<< info <<")"; 484 | } 485 | if (error_){ 486 | if (autorestart == 0){ 487 | if (return_on_error) { 488 | iout--; 489 | break; 490 | } else { 491 | throw std::runtime_error(message); 492 | } 493 | } else { 494 | std::array tout_ {{0, tout[iout] - tout[iout-1]}}; 495 | std::vector yout_(ny*2); 496 | int n_reached = this->predefined(2, tout_.data(), yout + (iout-1)*ny, yout_.data(), 497 | autorestart-1, return_on_error); 498 | if (n_reached == 0) 499 | break; 500 | std::memcpy(yout + ny*iout, yout_.data() + ny, ny); 501 | } 502 | } 503 | } 504 | return iout; 505 | } 506 | }; 507 | } 508 | -------------------------------------------------------------------------------- /pygslodeiv2/include/gsl_odeiv2_cxx.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8; mode: cython -*- 2 | 3 | from libcpp cimport bool 4 | from libcpp.string cimport string 5 | from libcpp.unordered_map cimport unordered_map 6 | 7 | cdef extern from "gsl_odeiv2_cxx.hpp" namespace "gsl_odeiv2_cxx": 8 | cdef unordered_map[string, int] fpes 9 | cdef cppclass StepType: 10 | pass 11 | 12 | cdef StepType styp_from_name(string) except + nogil 13 | cdef bool requires_jacobian(StepType) nogil 14 | 15 | 16 | cdef extern from "gsl_odeiv2_cxx.hpp" namespace "gsl_odeiv2_cxx::StepType": 17 | cdef StepType RK2 18 | cdef StepType RK4 19 | cdef StepType RKF45 20 | cdef StepType RKCK 21 | cdef StepType RK8PD 22 | cdef StepType RK1IMP 23 | cdef StepType RK2IMP 24 | cdef StepType RK4IMP 25 | cdef StepType BSIMP 26 | cdef StepType MSADAMS 27 | cdef StepType MSBDF 28 | -------------------------------------------------------------------------------- /pygslodeiv2/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjodah/pygslodeiv2/3e15514f2987aa0e93ecad6dc97efdff9f6fed7e/pygslodeiv2/tests/__init__.py -------------------------------------------------------------------------------- /pygslodeiv2/tests/test_gsl_odeiv2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import gc 3 | import os 4 | import sys 5 | import numpy as np 6 | import pytest 7 | 8 | from pygslodeiv2 import ( 9 | integrate_adaptive, integrate_predefined, requires_jac 10 | ) 11 | 12 | def _get_refcount_None(): 13 | if hasattr(sys, 'getrefcount'): 14 | gc.collect() 15 | gc.collect() 16 | return sys.getrefcount(None) 17 | else: # e.g. pypy 18 | return 0 19 | 20 | 21 | decay_defaults = dict(y0=[0.7, 0.3, 0.5], 22 | xout=np.linspace(0, 3, 31), 23 | dx0=1e-10, atol=1e-8, rtol=1e-8) 24 | decay_default_k = [2.0, 3.0, 4.0] 25 | 26 | decay_analytic = { 27 | 0: lambda y0, k, t: ( 28 | y0[0] * np.exp(-k[0]*t)), 29 | 1: lambda y0, k, t: ( 30 | y0[1] * np.exp(-k[1] * t) + y0[0] * k[0] / (k[1] - k[0]) * 31 | (np.exp(-k[0]*t) - np.exp(-k[1]*t))), 32 | 2: lambda y0, k, t: ( 33 | y0[2] * np.exp(-k[2] * t) + y0[1] * k[1] / (k[2] - k[1]) * 34 | (np.exp(-k[1]*t) - np.exp(-k[2]*t)) + 35 | k[1] * k[0] * y0[0] / (k[1] - k[0]) * 36 | (1 / (k[2] - k[0]) * (np.exp(-k[0]*t) - np.exp(-k[2]*t)) - 37 | 1 / (k[2] - k[1]) * (np.exp(-k[1]*t) - np.exp(-k[2]*t)))) 38 | } 39 | 40 | 41 | def decay_get_Cref(k, y0, tout): 42 | coeffs = list(k) + [0]*(3-len(k)) 43 | return np.column_stack([ 44 | decay_analytic[i](y0, coeffs, tout) for i in range( 45 | min(3, len(k)+1))]) 46 | 47 | 48 | def _get_f_j(k): 49 | k0, k1, k2 = k 50 | 51 | def f(t, y, fout): 52 | fout[0] = -k0*y[0] 53 | fout[1] = k0*y[0] - k1*y[1] 54 | fout[2] = k1*y[1] - k2*y[2] 55 | 56 | def j(t, y, jmat_out, dfdx_out): 57 | jmat_out[0, 0] = -k0 58 | jmat_out[0, 1] = 0 59 | jmat_out[0, 2] = 0 60 | jmat_out[1, 0] = k0 61 | jmat_out[1, 1] = -k1 62 | jmat_out[1, 2] = 0 63 | jmat_out[2, 0] = 0 64 | jmat_out[2, 1] = k1 65 | jmat_out[2, 2] = -k2 66 | dfdx_out[0] = 0 67 | dfdx_out[1] = 0 68 | dfdx_out[2] = 0 69 | return f, j 70 | 71 | methods = [('bsimp', 3e-4), ('msadams', 5), ('rkf45', 0.5), 72 | ('rkck', 0.3), ('rk8pd', 0.04), ('rk4imp', 0.8), 73 | ('msbdf', 23)] 74 | # ['rk2', 'rk4', 'rk1imp', 'rk2imp'] 75 | 76 | 77 | @pytest.mark.parametrize("method,forgiveness", methods) 78 | def test_integrate_adaptive(method, forgiveness): 79 | use_jac = method in requires_jac 80 | k = k0, k1, k2 = 2.0, 3.0, 4.0 81 | y0 = [0.7, 0.3, 0.5] 82 | f, j = _get_f_j(k) 83 | if not use_jac: 84 | j = None 85 | atol, rtol = 1e-8, 1e-8 86 | kwargs = dict(x0=0, xend=3, dx0=1e-10, atol=atol, rtol=rtol, 87 | method=method) 88 | # Run multiple times to catch possible side-effects: 89 | nIter = 101 90 | for ii in range(nIter): 91 | if ii == 1: 92 | nNone1 = _get_refcount_None() 93 | xout, yout, info = integrate_adaptive(f, j, y0, **kwargs) 94 | gc.collect() 95 | nNone2 = _get_refcount_None() 96 | delta = nNone2 - nNone1 97 | assert -nIter//10 < delta < nIter//10 98 | 99 | yref = decay_get_Cref(k, y0, xout) 100 | assert info['success'] 101 | assert info['atol'] == atol and info['rtol'] == rtol 102 | assert np.allclose(yout, yref, 103 | rtol=forgiveness*rtol, 104 | atol=forgiveness*atol) 105 | assert info['nfev'] > 0 106 | if method in requires_jac: 107 | assert info['njev'] > 0 108 | 109 | with pytest.raises(RuntimeError) as excinfo: 110 | integrate_adaptive(f, j, y0, nsteps=7, **kwargs) 111 | assert 'steps' in str(excinfo.value).lower() 112 | assert '7' in str(excinfo.value).lower() 113 | 114 | 115 | @pytest.mark.parametrize("method,forgiveness", methods) 116 | def test_integrate_predefined(method, forgiveness): 117 | use_jac = method in requires_jac 118 | k = k0, k1, k2 = 2.0, 3.0, 4.0 119 | y0 = [0.7, 0.3, 0.5] 120 | f, j = _get_f_j(k) 121 | if not use_jac: 122 | j = None 123 | xout = np.linspace(0, 3, 31) 124 | kwargs = dict(atol=1e-8, rtol=1e-8, dx0=1e-10, method=method) 125 | atol, rtol = 1e-8, 1e-8 126 | # Run twice to catch possible side-effects: 127 | yout, info = integrate_predefined(f, j, y0, xout, **kwargs) 128 | yout, info = integrate_predefined(f, j, y0, xout, **kwargs) 129 | yref = decay_get_Cref(k, y0, xout) 130 | assert info['success'] 131 | assert info['atol'] == atol and info['rtol'] == rtol 132 | assert np.allclose(yout, yref, 133 | rtol=forgiveness*rtol, 134 | atol=forgiveness*atol) 135 | assert info['nfev'] > 0 136 | if method in requires_jac: 137 | assert info['njev'] > 0 138 | if os.name == 'posix': 139 | assert info['time_cpu'] >= 0 140 | assert info['time_wall'] >= 0 141 | 142 | 143 | def test_bad_f(): 144 | k0, k1, k2 = decay_default_k 145 | 146 | def f(t, y, fout): 147 | y[0] = -1 # read-only! should raise ValueError 148 | fout[0] = -k0*y[0] 149 | fout[1] = k0*y[0] - k1*y[1] 150 | fout[2] = k1*y[1] - k2*y[2] 151 | with pytest.raises(ValueError): 152 | yout, info = integrate_predefined(f, None, method='rkck', 153 | check_callable=False, 154 | check_indexing=False, 155 | **decay_defaults) 156 | assert yout # silence pyflakes 157 | 158 | 159 | def test_bad_j(): 160 | k0, k1, k2 = decay_default_k 161 | 162 | def f(t, y, fout): 163 | fout[0] = -k0*y[0] 164 | fout[1] = k0*y[0] - k1*y[1] 165 | fout[2] = k1*y[1] - k2*y[2] 166 | 167 | def j(t, y, jmat_out, dfdx_out): 168 | y[0] = -1 # read-only! should raise ValueError 169 | jmat_out[0, 0] = -k0 170 | jmat_out[0, 1] = 0 171 | jmat_out[0, 2] = 0 172 | jmat_out[1, 0] = k0 173 | jmat_out[1, 1] = -k1 174 | jmat_out[1, 2] = 0 175 | jmat_out[2, 0] = 0 176 | jmat_out[2, 1] = k1 177 | jmat_out[2, 2] = -k2 178 | dfdx_out[0] = 0 179 | dfdx_out[1] = 0 180 | dfdx_out[2] = 0 181 | with pytest.raises(ValueError): 182 | yout, info = integrate_predefined(f, j, method='bsimp', 183 | check_callable=False, 184 | check_indexing=False, 185 | **decay_defaults) 186 | assert yout # silence pyflakes 187 | 188 | 189 | def test_adaptive_return_on_error(): 190 | k = k0, k1, k2 = 2.0, 3.0, 4.0 191 | y0 = [0.7, 0.3, 0.5] 192 | atol, rtol = 1e-8, 1e-8 193 | kwargs = dict(x0=0, xend=3, dx0=1e-10, atol=atol, rtol=rtol, 194 | method='bsimp') 195 | f, j = _get_f_j(k) 196 | xout, yout, info = integrate_adaptive(f, j, y0, nsteps=7, return_on_error=True, **kwargs) 197 | yref = decay_get_Cref(k, y0, xout) 198 | assert np.allclose(yout, yref, rtol=10*rtol, atol=10*atol) 199 | assert xout.size == 8 200 | assert xout[-1] > 1e-6 201 | assert yout.shape[0] == xout.size 202 | assert info['nfev'] > 0 203 | assert info['njev'] > 0 204 | assert info['success'] is False 205 | assert xout[-1] < kwargs['xend'] # obviously not strict 206 | 207 | 208 | def test_predefined_autorestart(): 209 | k = k0, k1, k2 = 2.0, 3.0, 4.0 210 | y0 = [0.7, 0.3, 0.5] 211 | atol, rtol = 1e-8, 1e-8 212 | x0, xend = 0, 3 213 | kwargs = dict(dx0=1e-10, atol=atol, rtol=rtol, 214 | method='bsimp', nsteps=62, 215 | autorestart=10) 216 | f, j = _get_f_j(k) 217 | xout = np.linspace(x0, xend) 218 | yout, info = integrate_predefined(f, j, y0, xout, **kwargs) 219 | yref = decay_get_Cref(k, y0, xout) 220 | assert np.allclose(yout, yref, 221 | rtol=10*rtol, 222 | atol=10*atol) 223 | assert xout[-1] > 1e-6 224 | assert yout.shape[0] == xout.size 225 | assert info['nfev'] > 0 226 | assert info['njev'] > 0 227 | assert info['success'] 228 | assert xout[-1] == xend 229 | 230 | 231 | def test_predefined_return_on_error(): 232 | k = k0, k1, k2 = 2.0, 300.0, 4.0 233 | y0 = [0.7, 0.0, 0.2] 234 | atol, rtol = 1e-12, 1e-12 235 | kwargs = dict(dx0=1e-11, atol=atol, rtol=rtol, method='bsimp', 236 | return_on_error=True, nsteps=10) 237 | f, j = _get_f_j(k) 238 | xout = np.logspace(-10, 1, 5) 239 | yout, info = integrate_predefined(f, j, y0, xout, **kwargs) 240 | yref = decay_get_Cref(k, y0, xout - xout[0]) 241 | assert np.allclose(yout[:info['nreached'], :], yref[:info['nreached'], :], 242 | rtol=10*rtol, atol=10*atol) 243 | assert 2 < info['nreached'] < 5 # not strict 244 | assert yout.shape[0] == xout.size 245 | assert info['nfev'] > 0 246 | assert info['njev'] > 0 247 | assert info['success'] is False 248 | 249 | 250 | def test_dx0cb(): 251 | k = 1e23, 3.0, 4.0 252 | y0 = [.7, .0, .0] 253 | x0, xend = 0, 5 254 | kwargs = dict(atol=1e-8, rtol=1e-8, method='bsimp', dx0cb=lambda x, y: y[0]*1e-30) 255 | f, j = _get_f_j(k) 256 | xout, yout, info = integrate_adaptive(f, j, y0, x0, xend, **kwargs) 257 | yref = decay_get_Cref(k, y0, xout) 258 | assert np.allclose(yout, yref, atol=40*kwargs['atol'], rtol=40*kwargs['rtol']) 259 | assert info['nfev'] > 0 260 | assert info['njev'] > 0 261 | assert info['success'] is True 262 | assert xout[-1] == xend 263 | 264 | 265 | def test_dx_max_cb(): 266 | k = 1e23, 3.0, 4.0 267 | y0 = [.7, .0, .0] 268 | x0, xend = 0, 5 269 | kwargs = dict(atol=1e-8, rtol=1e-8, method='bsimp', dx_max_cb=lambda x, y: 1e-3, nsteps=xend*1050) 270 | f, j = _get_f_j(k) 271 | xout, yout, info = integrate_adaptive(f, j, y0, x0, xend, **kwargs) 272 | yref = decay_get_Cref(k, y0, xout) 273 | assert np.allclose(yout, yref, atol=40*kwargs['atol'], rtol=40*kwargs['rtol']) 274 | assert info['n_steps'] > 5000 275 | assert info['nfev'] > 0 276 | assert info['njev'] > 0 277 | assert info['success'] is True 278 | assert xout[-1] == xend 279 | -------------------------------------------------------------------------------- /scripts/build_conda_recipe.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -ex 2 | # Usage: 3 | # 4 | # $ ./scripts/build_conda_recipe.sh v1.2.3 --python 2.7 --numpy 1.10 5 | # 6 | echo ${1#v}>__conda_version__.txt 7 | cleanup() { 8 | rm __conda_version__.txt 9 | exit 10 | } 11 | trap cleanup INT TERM EXIT 12 | 13 | conda build ${@:2} ./conda-recipe/ 14 | -------------------------------------------------------------------------------- /scripts/check_clean_repo_on_master.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | if [[ $(git rev-parse --abbrev-ref HEAD) != master ]]; then 3 | echo "We are not on the master branch. Aborting..." 4 | exit 1 5 | fi 6 | if [[ ! -z $(git status -s) ]]; then 7 | echo "'git status' show there are some untracked/uncommited changes. Aborting..." 8 | exit 1 9 | fi 10 | if [[ $(head -n 1 CHANGES.rst) == v* ]]; then 11 | if [[ $1 == v* ]] && [[ $(head -n 1 CHANGES.rst) != $1 ]]; then 12 | >&2 echo "CHANGES.rst does not start with: $1" 13 | exit 1 14 | fi 15 | else 16 | >&2 echo "CHANGES.rst does not start with v*" 17 | exit 1 18 | fi 19 | -------------------------------------------------------------------------------- /scripts/ci.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -xeuo pipefail 3 | 4 | export PATH="$(compgen -G /opt-2/gcc-??/bin):$PATH" 5 | export CPLUS_INCLUDE_PATH=$(compgen -G "/opt-3/boost-1.*/include") 6 | 7 | PKG_NAME=${1:-${CI_REPO_NAME##*/}} 8 | 9 | source /opt-3/cpython-v3.11-apt-deb/bin/activate 10 | 11 | #################### Install and test python package #################### 12 | 13 | python3 setup.py sdist 14 | CC=gcc CXX=g++ python3 -m pip install --ignore-installed dist/*.tar.gz 15 | (cd /; python3 -m pytest --pyargs $PKG_NAME) 16 | CC=gcc CXX=g++ python3 -m pip install -e .[all] 17 | python3 -m pip install pytest-cov pytest-flakes matplotlib sphinx numpydoc sphinx_rtd_theme 18 | PYTHONPATH=$(pwd) PYTHON=python3 ./scripts/run_tests.sh --cov $PKG_NAME --cov-report html 19 | ./scripts/coverage_badge.py htmlcov/ htmlcov/coverage.svg 20 | 21 | ./scripts/render_notebooks.sh examples/ 22 | (cd examples/; ../scripts/render_index.sh *.html) 23 | ./scripts/generate_docs.sh 24 | 25 | if [[ ! $(python3 setup.py --version) =~ ^[0-9]+.* ]]; then 26 | set -x 27 | >&2 echo "Bad version string?: $(python3 setup.py --version)" 28 | exit 1 29 | fi 30 | 31 | #################### Run stand-alone tests under ./tests/ #################### 32 | cd tests/ 33 | 34 | make clean 35 | make CC=gcc CXX=g++ EXTRA_FLAGS=-D_GLIBCXX_DEBUG 36 | 37 | make clean 38 | make CC=gcc CXX=g++ EXTRA_FLAGS=-DNDEBUG 39 | 40 | 41 | LLVM_ROOT=$(compgen -G "/opt-2/llvm-??") 42 | 43 | LIBCXX_ROOT=$(compgen -G "/opt-2/libcxx??-asan") 44 | make clean 45 | make \ 46 | CXX=clang++ \ 47 | EXTRA_FLAGS="-fsanitize=address -nostdinc++ -isystem ${LIBCXX_ROOT}/include/c++/v1" \ 48 | LDFLAGS="-nostdlib++ -Wl,-rpath,${LIBCXX_ROOT}/lib -L${LIBCXX_ROOT}/lib" \ 49 | LDLIBS="-lc++" \ 50 | OPENMP_LIB="-Wl,-rpath,${LLVM_ROOT}/lib -lomp" \ 51 | PY_LD_PRELOAD=$(clang++ --print-file-name=libclang_rt.asan.so) 52 | 53 | LIBCXX_ROOT=$(compgen -G "/opt-2/libcxx??-debug") 54 | make clean 55 | make \ 56 | CXX=clang++ \ 57 | EXTRA_FLAGS="-fsanitize=address -nostdinc++ -isystem ${LIBCXX_ROOT}/include/c++/v1" \ 58 | LDFLAGS="-nostdlib++ -Wl,-rpath,${LIBCXX_ROOT}/lib -L${LIBCXX_ROOT}/lib" \ 59 | LDLIBS="-lc++" \ 60 | OPENMP_LIB="-Wl,-rpath,${LLVM_ROOT}/lib -lomp" \ 61 | PY_LD_PRELOAD=$(clang++ --print-file-name=libclang_rt.asan.so) 62 | 63 | cd - 64 | -------------------------------------------------------------------------------- /scripts/coverage_badge.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This script generates a "coverage" badge as a svg file from 6 | the html report from coverage.py 7 | 8 | Usage: 9 | 10 | $ ./coverage_badge.py htmlcov/ coverage.svg 11 | 12 | """ 13 | 14 | from __future__ import (absolute_import, division, print_function) 15 | import os 16 | 17 | # this template was generated from shields.io on 2015-10-11 18 | template = """ 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 34 | coverage 35 | coverage 36 | {1:s}% 37 | {1:s}% 38 | 39 | 40 | """ 41 | 42 | 43 | def get_coverage(htmldir): 44 | for line in open(os.path.join(htmldir, 'index.html'), 'rt'): 45 | if 'pc_cov' in line: 46 | return int(line.split('pc_cov')[1].split( 47 | '>')[1].split('<')[0].rstrip('%')) 48 | raise ValueError("Could not find pc_cov in index.html") 49 | 50 | 51 | def write_cov_badge_svg(path, percent): 52 | colors = '#e05d44 #fe7d37 #dfb317 #a4a61d #97CA00 #4c1'.split() 53 | limits_le = 50, 60, 70, 80, 90, 100 54 | c = next(clr for lim, clr in zip(limits_le, colors) if percent <= lim) 55 | with open(path, 'wt') as f: 56 | f.write(template.format(c, str(percent))) 57 | 58 | if __name__ == '__main__': 59 | import sys 60 | assert len(sys.argv) == 3 61 | cov_percent = get_coverage(sys.argv[1]) 62 | write_cov_badge_svg(sys.argv[2], cov_percent) 63 | -------------------------------------------------------------------------------- /scripts/generate_docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | # 3 | # Usage: 4 | # 5 | # $ ./scripts/generate_docs.sh 6 | # 7 | # Usage if doc/ is actually published in master branch on github: 8 | # 9 | # $ ./scripts/generate_docs.sh my_github_username my_github_repo master 10 | # 11 | NARGS=$# 12 | PKG=$(find . -maxdepth 2 -name __init__.py -print0 | xargs -0 -n1 dirname | xargs basename) 13 | AUTHOR=$(head -n 1 AUTHORS) 14 | sphinx-apidoc --full --force -A "$AUTHOR" --module-first --doc-version=$(python3 setup.py --version) -F -o doc $PKG/ $(find . -type d -name tests) 15 | #sed -i 's/Contents/.. include:: ..\/README.rst\n\nContents/g' doc/index.rst 16 | #echo ".. include:: ../README.rst" >>doc/index.rst 17 | cat <>doc/index.rst 18 | 19 | Overview 20 | ======== 21 | $(tail -n+3 README.rst) 22 | EOF 23 | sed -i "s/'sphinx.ext.viewcode',/'sphinx.ext.viewcode',\n 'sphinx.ext.autosummary',\n 'numpydoc',/g" doc/conf.py 24 | sed -i "s/alabaster/sphinx_rtd_theme/g" doc/conf.py 25 | if [[ $NARGS -eq 3 ]]; then 26 | cat <>doc/conf.py 27 | 28 | context = { 29 | 'conf_py_path': '/doc/', 30 | 'github_user': '$1', 31 | 'github_repo': '$2', 32 | 'github_version': '$3', 33 | 'display_github': True, 34 | 'source_suffix': '.rst', 35 | } 36 | 37 | if 'html_context' in globals(): 38 | html_context.update(context) 39 | else: 40 | html_context = context 41 | EOF 42 | fi 43 | echo "numpydoc_class_members_toctree = False" >>doc/conf.py 44 | ABS_REPO_PATH=$(unset CDPATH && cd "$(dirname "$0")/.." && echo $PWD) 45 | ( cd doc; PYTHONPATH=$ABS_REPO_PATH make html ) 46 | -------------------------------------------------------------------------------- /scripts/post_release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xeu 2 | # Usage: 3 | # 4 | # $ ./scripts/post_release.sh v1.2.3 myserver 5 | # 6 | VERSION=${1#v} 7 | SERVER=$2 8 | PKG=$(find . -maxdepth 2 -name __init__.py -print0 | xargs -0 -n1 dirname | xargs basename) 9 | PKG_UPPER=$(echo $PKG | tr '[:lower:]' '[:upper:]') 10 | SDIST_FILE=dist/${PKG}-$VERSION.tar.gz 11 | if [[ ! -f "$SDIST_FILE" ]]; then 12 | >&2 echo "Nonexistent file $SDIST_FILE" 13 | exit 1 14 | fi 15 | SHA256=$(openssl sha256 "$SDIST_FILE" | cut -f2 -d' ') 16 | if [[ -d "dist/conda-recipe-$VERSION" ]]; then 17 | rm -r "dist/conda-recipe-$VERSION" 18 | fi 19 | cp -r conda-recipe/ dist/conda-recipe-$VERSION 20 | sed -i -E \ 21 | -e "s/\{\% set version(.+)/\{\% set version = \"$VERSION\" \%\}\n\{\% set sha256 = \"$SHA256\" \%\}/" \ 22 | -e "s/git_url:(.+)/fn: \{\{ name \}\}-\{\{ version \}\}.tar.gz\n url: https:\/\/pypi.io\/packages\/source\/\{\{ name\[0\] \}\}\/\{\{ name \}\}\/\{\{ name \}\}-\{\{ version \}\}.tar.gz\n sha256: \{\{ sha256 \}\}/" \ 23 | -e "/cython/d" \ 24 | dist/conda-recipe-$VERSION/meta.yaml 25 | 26 | # ssh $PKG@$SERVER 'mkdir -p ~/public_html/conda-packages' 27 | # for CONDA_PY in 27 35 36; do 28 | # anfilte-build . dist/conda-recipe-$VERSION dist/ --python ${CONDA_PY} 29 | # scp dist/linux-64/${PKG}-${VERSION}-py${CONDA_PY}*.bz2 $PKG@$SERVER:~/public_html/conda-packages/ 30 | # done 31 | ssh $PKG@$SERVER 'mkdir -p ~/public_html/conda-recipes' 32 | scp -r dist/conda-recipe-$VERSION/ $PKG@$SERVER:~/public_html/conda-recipes/ 33 | scp "$SDIST_FILE" "$PKG@$SERVER:~/public_html/releases/" 34 | 35 | ./scripts/update-gh-pages.sh v$VERSION 36 | -------------------------------------------------------------------------------- /scripts/prepare_deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | cp LICENSE doc/_build/html/ 3 | mkdir -p deploy/public_html/branches/"${CI_BRANCH}" 4 | cp -r dist/* htmlcov/ examples/ doc/_build/html/ deploy/public_html/branches/"${CI_BRANCH}"/ 5 | -------------------------------------------------------------------------------- /scripts/rasterize.js: -------------------------------------------------------------------------------- 1 | // From: 2 | // https://raw.githubusercontent.com/ariya/phantomjs/a86ae1948ca5ab20efc5c89ee39d183c33f59232/examples/rasterize.js 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | 7 | // * Redistributions of source code must retain the above copyright 8 | // notice, this list of conditions and the following disclaimer. 9 | // * Redistributions in binary form must reproduce the above copyright 10 | // notice, this list of conditions and the following disclaimer in the 11 | // documentation and/or other materials provided with the distribution. 12 | // * Neither the name of the nor the 13 | // names of its contributors may be used to endorse or promote products 14 | // derived from this software without specific prior written permission. 15 | 16 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | // ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 25 | // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | var page = require('webpage').create(), 28 | system = require('system'), 29 | address, output, size; 30 | 31 | if (system.args.length < 3 || system.args.length > 5) { 32 | console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]'); 33 | console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"'); 34 | console.log(' image (png/jpg output) examples: "1920px" entire page, window width 1920px'); 35 | console.log(' "800px*600px" window, clipped to 800x600'); 36 | phantom.exit(1); 37 | } else { 38 | address = system.args[1]; 39 | output = system.args[2]; 40 | page.viewportSize = { width: 600, height: 600 }; 41 | if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") { 42 | size = system.args[3].split('*'); 43 | page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' } 44 | : { format: system.args[3], orientation: 'portrait', margin: '1cm' }; 45 | } else if (system.args.length > 3 && system.args[3].substr(-2) === "px") { 46 | size = system.args[3].split('*'); 47 | if (size.length === 2) { 48 | pageWidth = parseInt(size[0], 10); 49 | pageHeight = parseInt(size[1], 10); 50 | page.viewportSize = { width: pageWidth, height: pageHeight }; 51 | page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight }; 52 | } else { 53 | console.log("size:", system.args[3]); 54 | pageWidth = parseInt(system.args[3], 10); 55 | pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any 56 | console.log ("pageHeight:",pageHeight); 57 | page.viewportSize = { width: pageWidth, height: pageHeight }; 58 | } 59 | } 60 | if (system.args.length > 4) { 61 | page.zoomFactor = system.args[4]; 62 | } 63 | page.open(address, function (status) { 64 | if (status !== 'success') { 65 | console.log('Unable to load the address!'); 66 | phantom.exit(1); 67 | } else { 68 | window.setTimeout(function () { 69 | page.render(output); 70 | phantom.exit(); 71 | }, 200); 72 | } 73 | }); 74 | } 75 | -------------------------------------------------------------------------------- /scripts/release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xeu 2 | # Usage: 3 | # 4 | # $ ./scripts/release.sh v1.2.3 GITHUB_USER GITHUB_REPO 5 | # 6 | 7 | if [[ $1 != v* ]]; then 8 | echo "Argument does not start with 'v'" 9 | exit 1 10 | fi 11 | VERSION=${1#v} 12 | find . -type f -iname "*.pyc" -exec rm {} + 13 | find . -type f -iname "*.o" -exec rm {} + 14 | find . -type f -iname "*.so" -exec rm {} + 15 | find . -type d -name "__pycache__" -exec rmdir {} + 16 | ./scripts/check_clean_repo_on_master.sh 17 | cd $(dirname $0)/.. 18 | # PKG will be name of the directory one level up containing "__init__.py" 19 | PKG=$(find . -maxdepth 2 -name __init__.py -print0 | xargs -0 -n1 dirname | xargs basename) 20 | ! grep --include "*.py" "will_be_missing_in='$VERSION'" -R $PKG/ # see deprecation() 21 | PKG_UPPER=$(echo $PKG | tr '[:lower:]' '[:upper:]') 22 | ${PYTHON:-python3} setup.py build_ext -i 23 | export PYTHONPATH=$(pwd) 24 | ./scripts/run_tests.sh 25 | env ${PKG_UPPER}_RELEASE_VERSION=v$VERSION python setup.py sdist 26 | env ${PKG_UPPER}_RELEASE_VERSION=v$VERSION ./scripts/generate_docs.sh 27 | 28 | # All went well, add a tag and push it. 29 | git tag -a v$VERSION -m v$VERSION 30 | git push 31 | git push --tags 32 | twine upload dist/${PKG}-$VERSION.tar.gz 33 | 34 | set +x 35 | echo "" 36 | echo " You may now create a new github release at with the tag \"v$VERSION\" and name " 37 | echo " it \"${PKG}-${VERSION}\", (don't foreget to manually attach the new .tar.gz" 38 | echo " file from the ./dist/ directory). Here is a link:" 39 | echo " https://github.com/$2/${3:-$PKG}/releases/new " 40 | echo " Then run:" 41 | echo "" 42 | echo " $ ./scripts/post_release.sh $1 " 43 | echo "" 44 | -------------------------------------------------------------------------------- /scripts/render_index.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | # 3 | # Usage (assuming: shopt -s extglob): 4 | # 5 | # $ cd examples/ && ../scripts/render_index.sh !(index).html 6 | # 7 | mkdir -p thumbs 8 | tmpdir=$(mktemp -d) 9 | trap "rm -r $tmpdir" INT TERM EXIT 10 | cat <index.html 11 | 12 | 13 | 14 | Notebook gallery 15 | 16 | 17 | EOF 18 | for f in $@; do 19 | img=$(basename $f .html).png 20 | wkhtmltopdf $f $tmpdir/$img # --crop-w 1200px --crop-h 900px 21 | convert $tmpdir/$img -resize 400x300 thumbs/$img 22 | cat <>index.html 23 |

24 | 25 |
26 | $f 27 |

28 | EOF 29 | done 30 | cat <>index.html 31 | 32 | 33 | EOF 34 | -------------------------------------------------------------------------------- /scripts/render_notebooks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | QUIET_EXIT_CODE=0 3 | function quiet_unless_fail { 4 | # suppresses function output unless exit status is != 0 5 | OUTPUT_FILE=$(tempfile) 6 | #/bin/rm --force /tmp/suppress.out 2>/dev/null 7 | EXECMD=${1+"$@"} 8 | $EXECMD > ${OUTPUT_FILE} 2>&1 9 | QUIET_EXIT_CODE=$? 10 | if [ ${QUIET_EXIT_CODE} -ne 0 ]; then 11 | cat ${OUTPUT_FILE} 12 | echo "The following command exited with exit status ${QUIET_EXIT_CODE}: ${EXECMD}" 13 | /bin/rm ${OUTPUT_FILE} 14 | fi 15 | /bin/rm ${OUTPUT_FILE} 16 | } 17 | 18 | if [ -f index.ipynb ]; then 19 | sed -i.bak0 's/ipynb/html/' index.ipynb 20 | sed -i.bak1 's/filepath=index.html/filepath=index.ipynb/' index.ipynb # mybinder link fix 21 | fi 22 | set +e 23 | for dir in $@; do 24 | cd $dir 25 | for fname in *.ipynb; do 26 | echo "rendering ${fname}..." 27 | quiet_unless_fail jupyter nbconvert --debug --to=html --ExecutePreprocessor.enabled=True --ExecutePreprocessor.timeout=300 "${fname}" \ 28 | | grep -v -e "^\[NbConvertApp\] content: {'data':.*'image/png'" 29 | if [ ${QUIET_EXIT_CODE} -ne 0 ]; then 30 | exit ${QUIET_EXIT_CODE} 31 | fi 32 | done 33 | cd - 34 | done 35 | set -e 36 | cd examples/ 37 | ../scripts/render_index.sh *.html 38 | -------------------------------------------------------------------------------- /scripts/run_tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Usage 3 | # $ ./scripts/run_tests.sh 4 | # or 5 | # $ ./scripts/run_tests.sh --cov pycvodes --cov-report html 6 | set -ex 7 | ${PYTHON:-python3} -m pytest --pyargs ${CI_REPO_NAME:-$(basename $(realpath $(dirname $BASH_SOURCE)/../))} --doctest-modules --flakes $@ 8 | MPLBACKEND=Agg ${PYTHON:-python3} -m doctest README.rst 9 | -------------------------------------------------------------------------------- /scripts/update-gh-pages.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | # 3 | # Usage: 4 | # 5 | # $ ./scripts/update-gh-pages.sh v0.6.0 origin 6 | # 7 | 8 | tag=${1:-master} 9 | remote=${2:-origin} 10 | 11 | ori_branch=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD) 12 | tmpdir=$(mktemp -d) 13 | cleanup() { 14 | rm -r $tmpdir 15 | } 16 | trap cleanup INT TERM 17 | 18 | cp -r doc/_build/html/ $tmpdir 19 | git ls-files --others | tar cf $tmpdir/untracked.tar -T - 20 | if [[ -d .gh-pages-skeleton ]]; then 21 | cp -r .gh-pages-skeleton $tmpdir 22 | fi 23 | 24 | git fetch $remote 25 | git checkout gh-pages 26 | if [[ $? -ne 0 ]]; then 27 | git checkout --orphan gh-pages 28 | if [[ $? -ne 0 ]]; then 29 | >&2 echo "Failed to switch to 'gh-pages' branch." 30 | cleanup 31 | exit 1 32 | fi 33 | preexisting=0 34 | else 35 | preexisting=1 36 | git pull 37 | fi 38 | 39 | if [[ $preexisting == 1 ]]; then 40 | while [[ "$(git log -1 --pretty=%B)" == Volatile* ]]; do 41 | # overwrite previous docs 42 | git reset --hard HEAD~1 43 | done 44 | else 45 | git reset --hard 46 | fi 47 | 48 | git clean -xfd 49 | if [[ $preexisting == 1 ]]; then 50 | mv v*/ $tmpdir 51 | git rm -rf * > /dev/null 52 | fi 53 | cp -r $tmpdir/html/ $tag 54 | if [[ $preexisting == 1 ]]; then 55 | mv $tmpdir/v*/ . 56 | fi 57 | if [[ -d $tmpdir/.gh-pages-skeleton ]]; then 58 | cp -r $tmpdir/.gh-pages-skeleton/. . 59 | fi 60 | if [[ "$tag" == v* ]]; then 61 | if [[ -L latest ]]; then 62 | rm latest 63 | fi 64 | ln -s $tag latest 65 | commit_msg="Release docs for $tag" 66 | else 67 | if [[ $preexisting == 1 ]]; then 68 | commit_msg="Volatile ($tag) docs" 69 | else 70 | commit_msg="Initial commit" 71 | fi 72 | fi 73 | git add -f . >/dev/null 74 | git commit -m "$commit_msg" 75 | if [[ $preexisting == 1 ]]; then 76 | git push -f $remote gh-pages 77 | else 78 | git push --set-upstream $remote gh-pages 79 | fi 80 | git checkout $ori_branch 81 | tar xf $tmpdir/untracked.tar 82 | cleanup 83 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [tool:pytest] 2 | norecursedirs = .git .cache scripts build dist conda-recipe external 3 | pep8maxlinelength=119 4 | pep8ignore = 5 | doc/conf.py ALL 6 | flakes-ignore = 7 | __init__.py UnusedImport 8 | doc/conf.py ALL 9 | 10 | [upload_sphinx] 11 | upload-dir = doc/_build/html 12 | 13 | # https://github.com/pytest-dev/pytest/issues/1445 14 | [easy_install] 15 | zip_ok = 0 16 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Tested with GSL v1.16 and v2.1 5 | 6 | import io 7 | import os 8 | import re 9 | import pprint 10 | import shutil 11 | import subprocess 12 | import sys 13 | import warnings 14 | 15 | from setuptools import setup 16 | from setuptools.extension import Extension 17 | try: 18 | import cython 19 | except ImportError: 20 | _HAVE_CYTHON = False 21 | else: 22 | _HAVE_CYTHON = True 23 | assert cython # silence pep8 24 | 25 | 26 | pkg_name = 'pygslodeiv2' 27 | url = 'https://github.com/bjodah/' + pkg_name 28 | license = 'GPL-3.0' 29 | 30 | 31 | def _path_under_setup(*args): 32 | return os.path.join(*args) 33 | 34 | release_py_path = _path_under_setup(pkg_name, '_release.py') 35 | config_py_path = _path_under_setup(pkg_name, '_config.py') 36 | env = None # silence pyflakes, 'env' is actually set on the next line 37 | exec(open(config_py_path).read()) 38 | for k, v in list(env.items()): 39 | env[k] = os.environ.get('%s_%s' % (pkg_name.upper(), k), v) 40 | 41 | 42 | _src = {ext: _path_under_setup(pkg_name, '_gsl_odeiv2.' + ext) for ext in "cpp pyx".split()} 43 | if _HAVE_CYTHON and os.path.exists(_src["pyx"]): 44 | # Possible that a new release of Python needs a re-rendered Cython source, 45 | # or that we want to include possible bug-fix to Cython, disable by manually 46 | # deleting .pyx file from source distribution. 47 | USE_CYTHON = True 48 | if os.path.exists(_src['cpp']): 49 | os.unlink(_src['cpp']) # ensure c++ source is re-generated. 50 | else: 51 | USE_CYTHON = False 52 | 53 | package_include = os.path.join(pkg_name, 'include') 54 | 55 | ext_modules = [] 56 | 57 | if len(sys.argv) > 1 and '--help' not in sys.argv[1:] and sys.argv[1] not in ( 58 | '--help-commands', 'egg_info', 'clean', '--version'): 59 | import numpy as np 60 | sources = [_src["pyx" if USE_CYTHON else "cpp"]] 61 | ext_modules = [Extension('%s._gsl_odeiv2' % pkg_name, sources)] 62 | if USE_CYTHON: 63 | from Cython.Build import cythonize 64 | ext_modules = cythonize(ext_modules, include_path=[ 65 | package_include, 66 | os.path.join('external', 'anyode', 'cython_def') 67 | ]) 68 | ext_modules[0].language = 'c++' 69 | ext_modules[0].extra_compile_args = ['-std=c++11'] 70 | ext_modules[0].define_macros = [('ANYODE_NO_LAPACK', '1')] 71 | ext_modules[0].include_dirs = [ 72 | np.get_include(), package_include, 73 | os.path.join('external', 'anyode', 'include')] 74 | ext_modules[0].libraries.extend(env['GSL_LIBS'].split(',')) 75 | ext_modules[0].libraries.extend(env['BLAS'].split(',')) 76 | 77 | _version_env_var = '%s_RELEASE_VERSION' % pkg_name.upper() 78 | RELEASE_VERSION = os.environ.get(_version_env_var, '') 79 | 80 | 81 | if len(RELEASE_VERSION) > 1: 82 | if RELEASE_VERSION[0] != 'v': 83 | raise ValueError("$%s does not start with 'v'" % _version_env_var) 84 | TAGGED_RELEASE = True 85 | __version__ = RELEASE_VERSION[1:] 86 | else: # set `__version__` from _release.py: 87 | TAGGED_RELEASE = False 88 | exec(open(release_py_path).read()) 89 | if __version__.endswith('git'): 90 | try: 91 | _git_version = subprocess.check_output( 92 | ['git', 'describe', '--dirty']).rstrip().decode('utf-8') 93 | except subprocess.CalledProcessError: 94 | warnings.warn("A git-archive is being installed - version information incomplete.") 95 | else: 96 | if 'develop' not in sys.argv: 97 | warnings.warn("Using git to derive version: dev-branches may compete.") 98 | _ver_tmplt = r'\1.post\2' if os.environ.get('CONDA_BUILD', '0') == '1' else r'\1.post\2+\3' 99 | __version__ = re.sub('v([0-9.]+)-(\d+)-(\S+)', _ver_tmplt, _git_version) # .dev < '' < .post 100 | 101 | classifiers = [ 102 | "Development Status :: 4 - Beta", 103 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 104 | 'Operating System :: OS Independent', 105 | 'Topic :: Scientific/Engineering', 106 | 'Topic :: Scientific/Engineering :: Mathematics', 107 | ] 108 | 109 | tests = [ 110 | '%s.tests' % pkg_name, 111 | ] 112 | 113 | with io.open(_path_under_setup(pkg_name, '__init__.py'), 'rt', encoding='utf-8') as f: 114 | short_description = f.read().split('"""')[1].split('\n')[1] 115 | if not 10 < len(short_description) < 255: 116 | warnings.warn("Short description from __init__.py proably not read correctly") 117 | long_descr = io.open(_path_under_setup('README.rst'), encoding='utf-8').read() 118 | if not len(long_descr) > 100: 119 | warnings.warn("Long description from README.rst probably not read correctly.") 120 | _author, _author_email = open(_path_under_setup('AUTHORS'), 'rt').readline().split('<') 121 | 122 | setup_kwargs = dict( 123 | name=pkg_name, 124 | version=__version__, 125 | description=short_description, 126 | long_description=long_descr, 127 | classifiers=classifiers, 128 | author=_author.strip(), 129 | author_email=_author_email.split('>')[0].strip(), 130 | url=url, 131 | license=license, 132 | packages=[pkg_name] + tests, 133 | include_package_data=True, 134 | install_requires=['numpy'] + (['cython'] if USE_CYTHON else []), 135 | setup_requires=['numpy'] + (['cython'] if USE_CYTHON else []), 136 | extras_require={'docs': ['Sphinx', 'sphinx_rtd_theme', 'numpydoc']}, 137 | ext_modules=ext_modules, 138 | ) 139 | 140 | if __name__ == '__main__': 141 | try: 142 | if TAGGED_RELEASE: 143 | # Same commit should generate different sdist 144 | # depending on tagged version (set PYGSLODEIV2_RELEASE_VERSION) 145 | # this will ensure source distributions contain the correct version 146 | shutil.move(release_py_path, release_py_path+'__temp__') 147 | open(release_py_path, 'wt').write( 148 | "__version__ = '{}'\n".format(__version__)) 149 | shutil.move(config_py_path, config_py_path+'__temp__') 150 | open(config_py_path, 'wt').write("env = {}\n".format(pprint.pformat(env))) 151 | setup(**setup_kwargs) 152 | finally: 153 | if TAGGED_RELEASE: 154 | shutil.move(release_py_path+'__temp__', release_py_path) 155 | shutil.move(config_py_path+'__temp__', config_py_path) 156 | -------------------------------------------------------------------------------- /tests/Makefile: -------------------------------------------------------------------------------- 1 | CXX ?= g++ 2 | EXTRA_LIBS ?=-lgsl -lgslcblas -lm 3 | WARNINGS ?= \ 4 | -Wall \ 5 | -Wextra \ 6 | -Wredundant-decls \ 7 | -Wcast-align \ 8 | -Wmissing-include-dirs \ 9 | -Wswitch-enum \ 10 | -Wswitch-default \ 11 | -Winvalid-pch \ 12 | -Wredundant-decls \ 13 | -Wformat=2 \ 14 | -Wmissing-format-attribute \ 15 | -Wformat-nonliteral \ 16 | -Wodr 17 | CXXFLAGS ?= -std=c++11 $(WARNINGS) -Werror -pedantic -g -ggdb -O0 18 | CXXFLAGS += $(EXTRA_FLAGS) 19 | INCLUDE ?= -I../pygslodeiv2/include -I../external/anyode/include 20 | EXTRA_FLAGS ?= 21 | CXXFLAGS += $(EXTRA_FLAGS) 22 | OPENMP_FLAG ?= -fopenmp 23 | OPENMP_LIB ?= -lgomp 24 | 25 | 26 | .PHONY: test clean 27 | 28 | test: test_gsl_odeiv2_anyode test_gsl_odeiv2_anyode_parallel test_gsl_odeiv2_anyode_autorestart test_gsl_odeiv2_cxx _test_gsl_odeiv2_anyode.py 29 | ./test_gsl_odeiv2_anyode --abortx 1 30 | ./test_gsl_odeiv2_anyode_parallel --abortx 1 31 | ./test_gsl_odeiv2_anyode_autorestart --abortx 1 32 | ./test_gsl_odeiv2_cxx --abortx 1 33 | env DISTUTILS_DEBUG=1 CC=$(CXX) CFLAGS="$(EXTRA_FLAGS)" LDFLAGS="$(LDFLAGS)" LD_PRELOAD="$(PY_LD_PRELOAD)" ASAN_OPTIONS=detect_leaks=0 python3 ./_test_gsl_odeiv2_anyode.py 34 | 35 | clean: 36 | rm -f doctest.h 37 | rm -f test_gsl_odeiv2_anyode 38 | rm -f test_gsl_odeiv2_anyode_parallel 39 | rm -f test_gsl_odeiv2_anyode_autorestart 40 | rm -f test_gsl_odeiv2_cxx 41 | 42 | 43 | test_%: test_%.cpp ../pygslodeiv2/include/gsl_odeiv2_cxx.hpp doctest.h testing_utils.hpp 44 | $(CXX) $(CXXFLAGS) $(LDFLAGS) $(INCLUDE) -o $@ $< $(LDLIBS) $(EXTRA_LIBS) 45 | 46 | test_gsl_odeiv2_anyode_parallel: test_gsl_odeiv2_anyode_parallel.cpp ../pygslodeiv2/include/gsl_odeiv2_*.hpp 47 | $(CXX) $(CXXFLAGS) $(LDFLAGS) $(OPENMP_FLAG) $(INCLUDE) -o $@ $< $(LDLIBS) $(EXTRA_LIBS) $(OPENMP_LIB) 48 | 49 | doctest.h: doctest.h.bz2 50 | bunzip2 -k -f $< 51 | -------------------------------------------------------------------------------- /tests/_gsl_odeiv2_anyode.pyx: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8; mode: cython -*- 2 | # distutils: language = c++ 3 | # distutils: extra_compile_args = -std=c++11 4 | # 5 | # pyximport ignores the above settings, see _gsl_odeiv2_cxx.pyxbld 6 | 7 | from gsl_odeiv2_cxx cimport styp_from_name 8 | from gsl_odeiv2_anyode cimport simple_adaptive 9 | 10 | 11 | cdef extern from "testing_utils.hpp": 12 | cppclass Decay: 13 | Decay(double) 14 | 15 | 16 | cdef class PyDecay: 17 | cdef Decay *thisptr 18 | 19 | def __cinit__(self, double k): 20 | self.thisptr = new Decay(k) 21 | 22 | def __dealloc__(self): 23 | del self.thisptr 24 | 25 | def adaptive(self, double y0, double t, str stepper_name='msadams'): 26 | return simple_adaptive[Decay]( 27 | self.thisptr, 1e-10, 1e-10, 28 | styp_from_name(stepper_name.lower().encode('UTF-8')), 29 | &y0, 0.0, t) 30 | -------------------------------------------------------------------------------- /tests/_gsl_odeiv2_anyode.pyxbld: -------------------------------------------------------------------------------- 1 | def make_ext(modname, pyxfilename): 2 | from Cython.Build import cythonize 3 | ext = cythonize([pyxfilename], include_path=['../pygslodeiv2/include', '../external/anyode/cython_def'])[0] 4 | ext.libraries = ['gsl', 'gslcblas', 'm'] 5 | ext.include_dirs=['../pygslodeiv2/include', '../external/anyode/include'] 6 | return ext 7 | -------------------------------------------------------------------------------- /tests/_test_gsl_odeiv2_anyode.py: -------------------------------------------------------------------------------- 1 | from math import exp 2 | 3 | 4 | def test_PyDecay(): 5 | import pyximport 6 | pyximport.install() 7 | from _gsl_odeiv2_anyode import PyDecay 8 | 9 | pd = PyDecay(1.0) 10 | tout, yout = pd.adaptive(1.0, 1.0) 11 | for t, y in zip(tout, yout): 12 | assert abs(y - exp(-t)) < 2e-9 13 | 14 | 15 | if __name__ == '__main__': 16 | test_PyDecay() 17 | -------------------------------------------------------------------------------- /tests/cetsa_case.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | // This is a real-world based test example 3 | 4 | struct OdeSys : public AnyODE::OdeSysBase { 5 | std::vector m_p; 6 | OdeSys(const double * const params); 7 | int get_ny() const override; 8 | AnyODE::Status rhs(double t, 9 | const double * const __restrict__ y, 10 | double * const __restrict__ f) override; 11 | AnyODE::Status dense_jac_cmaj(double t, 12 | const double * const __restrict__ y, 13 | const double * const __restrict__ fy, 14 | double * const __restrict__ jac, 15 | long int ldim, 16 | double * const __restrict__ dfdt=nullptr) override; 17 | AnyODE::Status dense_jac_rmaj(double t, 18 | const double * const __restrict__ y, 19 | const double * const __restrict__ fy, 20 | double * const __restrict__ jac, 21 | long int ldim, 22 | double * const __restrict__ dfdt=nullptr) override; 23 | }; 24 | 25 | 26 | OdeSys::OdeSys(const double * const params) { 27 | m_p.assign(params, params + 13); 28 | } 29 | int OdeSys::get_ny() const { 30 | return 5; 31 | } 32 | AnyODE::Status OdeSys::rhs(double t, 33 | const double * const __restrict__ y, 34 | double * const __restrict__ f) { 35 | AnyODE::ignore(t); 36 | const double x0 = m_p[0]*y[0]; 37 | const double x1 = 0.120272395808565/m_p[0]; 38 | const double x2 = -m_p[9]; 39 | const double x3 = 20836.6122251252*x0*y[3]*exp(x1*(m_p[0]*m_p[10] + x2)); 40 | const double x4 = m_p[0] - 298.15; 41 | const double x5 = log(0.00335401643468053*m_p[0]); 42 | const double x6 = 20836612225.1252*m_p[0]*y[4]*exp(x1*(m_p[0]*(m_p[10] + m_p[12] + m_p[8]*x5) - m_p[11] - m_p[8]*x4 + x2)); 43 | const double x7 = -x3 + x6; 44 | const double x8 = 20836612225.1252*m_p[0]*y[1]; 45 | const double x9 = -m_p[1]; 46 | const double x10 = x8*exp(x1*(m_p[0]*m_p[2] + x9)); 47 | const double x11 = 20836612225.1252*x0*exp(x1*(m_p[0]*(m_p[2] + m_p[3]*x5 + m_p[4]/(m_p[5] + 273.15)) - m_p[3]*x4 - m_p[4] + x9)); 48 | const double x12 = x8*exp(x1*(m_p[0]*m_p[7] - m_p[6])); 49 | 50 | f[0] = x10 - x11 + x7; 51 | f[1] = -x10 + x11 - x12; 52 | f[2] = x12; 53 | f[3] = x7; 54 | f[4] = x3 - x6; 55 | this->nfev++; 56 | return AnyODE::Status::success; 57 | } 58 | 59 | 60 | AnyODE::Status OdeSys::dense_jac_cmaj(double t, 61 | const double * const __restrict__ y, 62 | const double * const __restrict__ fy, 63 | double * const __restrict__ jac, 64 | long int ldim, 65 | double * const __restrict__ dfdt) { 66 | // The AnyODE::ignore(...) calls below are used to generate code free from compiler warnings. 67 | AnyODE::ignore(fy); // Currently we are not using fy (could be done through extensive pattern matching) 68 | AnyODE::ignore(t); 69 | 70 | 71 | const double x0 = 0.120272395808565/m_p[0]; 72 | const double x1 = -m_p[9]; 73 | const double x2 = 20836.6122251252*m_p[0]*exp(x0*(m_p[0]*m_p[10] + x1)); 74 | const double x3 = x2*y[3]; 75 | const double x4 = -x3; 76 | const double x5 = 20836612225.1252*m_p[0]; 77 | const double x6 = -m_p[1]; 78 | const double x7 = m_p[0] - 298.15; 79 | const double x8 = log(0.00335401643468053*m_p[0]); 80 | const double x9 = x5*exp(x0*(m_p[0]*(m_p[2] + m_p[3]*x8 + m_p[4]/(m_p[5] + 273.15)) - m_p[3]*x7 - m_p[4] + x6)); 81 | const double x10 = x5*exp(x0*(m_p[0]*m_p[2] + x6)); 82 | const double x11 = x2*y[0]; 83 | const double x12 = -x11; 84 | const double x13 = x5*exp(x0*(m_p[0]*(m_p[10] + m_p[12] + m_p[8]*x8) - m_p[11] - m_p[8]*x7 + x1)); 85 | const double x14 = x5*exp(x0*(m_p[0]*m_p[7] - m_p[6])); 86 | 87 | jac[ldim*0 + 0] = x4 - x9; 88 | jac[ldim*0 + 1] = x9; 89 | jac[ldim*0 + 2] = 0; 90 | jac[ldim*0 + 3] = x4; 91 | jac[ldim*0 + 4] = x3; 92 | 93 | jac[ldim*1 + 0] = x10; 94 | jac[ldim*1 + 1] = -x10 - x14; 95 | jac[ldim*1 + 2] = x14; 96 | jac[ldim*1 + 3] = 0; 97 | jac[ldim*1 + 4] = 0; 98 | 99 | jac[ldim*2 + 0] = 0; 100 | jac[ldim*2 + 1] = 0; 101 | jac[ldim*2 + 2] = 0; 102 | jac[ldim*2 + 3] = 0; 103 | jac[ldim*2 + 4] = 0; 104 | 105 | jac[ldim*3 + 0] = x12; 106 | jac[ldim*3 + 1] = 0; 107 | jac[ldim*3 + 2] = 0; 108 | jac[ldim*3 + 3] = x12; 109 | jac[ldim*3 + 4] = x11; 110 | 111 | jac[ldim*4 + 0] = x13; 112 | jac[ldim*4 + 1] = 0; 113 | jac[ldim*4 + 2] = 0; 114 | jac[ldim*4 + 3] = x13; 115 | jac[ldim*4 + 4] = -x13; 116 | 117 | if (dfdt){ 118 | dfdt[0] = 0; 119 | dfdt[1] = 0; 120 | dfdt[2] = 0; 121 | dfdt[3] = 0; 122 | dfdt[4] = 0; 123 | } 124 | this->njev++; 125 | return AnyODE::Status::success; 126 | } 127 | 128 | AnyODE::Status OdeSys::dense_jac_rmaj(double t, 129 | const double * const __restrict__ y, 130 | const double * const __restrict__ fy, 131 | double * const __restrict__ jac, 132 | long int ldim, 133 | double * const __restrict__ dfdt) { 134 | // The AnyODE::ignore(...) calls below are used to generate code free from compiler warnings. 135 | AnyODE::ignore(fy); // Currently we are not using fy (could be done through extensive pattern matching) 136 | AnyODE::ignore(t); 137 | 138 | 139 | const double x0 = 0.120272395808565/m_p[0]; 140 | const double x1 = -m_p[9]; 141 | const double x2 = 20836.6122251252*m_p[0]*exp(x0*(m_p[0]*m_p[10] + x1)); 142 | const double x3 = x2*y[3]; 143 | const double x4 = -x3; 144 | const double x5 = 20836612225.1252*m_p[0]; 145 | const double x6 = -m_p[1]; 146 | const double x7 = m_p[0] - 298.15; 147 | const double x8 = log(0.00335401643468053*m_p[0]); 148 | const double x9 = x5*exp(x0*(m_p[0]*(m_p[2] + m_p[3]*x8 + m_p[4]/(m_p[5] + 273.15)) - m_p[3]*x7 - m_p[4] + x6)); 149 | const double x10 = x5*exp(x0*(m_p[0]*m_p[2] + x6)); 150 | const double x11 = x2*y[0]; 151 | const double x12 = -x11; 152 | const double x13 = x5*exp(x0*(m_p[0]*(m_p[10] + m_p[12] + m_p[8]*x8) - m_p[11] - m_p[8]*x7 + x1)); 153 | const double x14 = x5*exp(x0*(m_p[0]*m_p[7] - m_p[6])); 154 | 155 | jac[ldim*0 + 0] = x4 - x9; 156 | jac[ldim*0 + 1] = x10; 157 | jac[ldim*0 + 2] = 0; 158 | jac[ldim*0 + 3] = x12; 159 | jac[ldim*0 + 4] = x13; 160 | 161 | jac[ldim*1 + 0] = x9; 162 | jac[ldim*1 + 1] = -x10 - x14; 163 | jac[ldim*1 + 2] = 0; 164 | jac[ldim*1 + 3] = 0; 165 | jac[ldim*1 + 4] = 0; 166 | 167 | jac[ldim*2 + 0] = 0; 168 | jac[ldim*2 + 1] = x14; 169 | jac[ldim*2 + 2] = 0; 170 | jac[ldim*2 + 3] = 0; 171 | jac[ldim*2 + 4] = 0; 172 | 173 | jac[ldim*3 + 0] = x4; 174 | jac[ldim*3 + 1] = 0; 175 | jac[ldim*3 + 2] = 0; 176 | jac[ldim*3 + 3] = x12; 177 | jac[ldim*3 + 4] = x13; 178 | 179 | jac[ldim*4 + 0] = x3; 180 | jac[ldim*4 + 1] = 0; 181 | jac[ldim*4 + 2] = 0; 182 | jac[ldim*4 + 3] = x11; 183 | jac[ldim*4 + 4] = -x13; 184 | 185 | if (dfdt){ 186 | dfdt[0] = 0; 187 | dfdt[1] = 0; 188 | dfdt[2] = 0; 189 | dfdt[3] = 0; 190 | dfdt[4] = 0; 191 | } 192 | this->njev++; 193 | return AnyODE::Status::success; 194 | } 195 | -------------------------------------------------------------------------------- /tests/doctest.h.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bjodah/pygslodeiv2/3e15514f2987aa0e93ecad6dc97efdff9f6fed7e/tests/doctest.h.bz2 -------------------------------------------------------------------------------- /tests/doctest.h.url: -------------------------------------------------------------------------------- 1 | https://github.com/doctest/doctest/releases/download/v2.4.11/doctest.h 2 | -------------------------------------------------------------------------------- /tests/test_gsl_odeiv2_anyode.cpp: -------------------------------------------------------------------------------- 1 | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN 2 | #include "doctest.h" 3 | #include "gsl_odeiv2_anyode.hpp" 4 | #include "testing_utils.hpp" 5 | 6 | 7 | TEST_CASE( "decay_adaptive" ) { 8 | Decay odesys(1.0); 9 | double y0 = 1.0; 10 | double dx0 = 1e-9; 11 | long int mxsteps = 500; 12 | auto tout_yout = gsl_odeiv2_anyode::simple_adaptive(&odesys, 1e-10, 1e-10, 13 | gsl_odeiv2_cxx::StepType::MSADAMS, 14 | &y0, 0.0, 1.0, mxsteps, dx0); 15 | auto& tout = tout_yout.first; 16 | auto& yout = tout_yout.second; 17 | REQUIRE( tout.size() == yout.size() ); 18 | for (uint i = 0; i < tout.size(); ++i){ 19 | REQUIRE( std::abs(std::exp(-tout[i]) - yout[i]) < 1e-8 ); 20 | } 21 | REQUIRE( odesys.current_info.nfo_int["nfev"] > 1 ); 22 | REQUIRE( odesys.current_info.nfo_int["nfev"] < 997 ); 23 | REQUIRE( odesys.current_info.nfo_int["n_steps"] > 1 ); 24 | REQUIRE( odesys.current_info.nfo_int["n_steps"] < 997 ); 25 | } 26 | 27 | 28 | TEST_CASE( "decay_adaptive_get_dx_max" ) { 29 | Decay odesys(1.0); 30 | double y0 = 1.0; 31 | double dx0 = 1e-9; 32 | odesys.use_get_dx_max = true; 33 | auto tout_yout = gsl_odeiv2_anyode::simple_adaptive(&odesys, 1e-10, 1e-10, 34 | gsl_odeiv2_cxx::StepType::MSADAMS, 35 | &y0, 0.0, 1.0, 2100, dx0, 0.0, 1e-3); 36 | auto& tout = tout_yout.first; 37 | auto& yout = tout_yout.second; 38 | REQUIRE( tout.size() == yout.size() ); 39 | for (uint i = 0; i < tout.size(); ++i){ 40 | REQUIRE( std::abs(std::exp(-tout[i]) - yout[i]) < 1e-8 ); 41 | } 42 | REQUIRE( odesys.current_info.nfo_int["n_steps"] > 2000 ); 43 | } 44 | 45 | 46 | TEST_CASE( "decay_adaptive_dx_max" ) { 47 | Decay odesys(1.0); 48 | double y0 = 1.0; 49 | double dx0 = 1e-9; 50 | auto tout_yout = gsl_odeiv2_anyode::simple_adaptive(&odesys, 1e-10, 1e-10, 51 | gsl_odeiv2_cxx::StepType::MSADAMS, 52 | &y0, 0.0, 1.0, 1100, dx0, 0.0, 1e-3); 53 | auto& tout = tout_yout.first; 54 | auto& yout = tout_yout.second; 55 | REQUIRE( tout.size() == yout.size() ); 56 | for (uint i = 0; i < tout.size(); ++i){ 57 | REQUIRE( std::abs(std::exp(-tout[i]) - yout[i]) < 1e-8 ); 58 | } 59 | REQUIRE( odesys.current_info.nfo_int["n_steps"] > 998 ); 60 | } 61 | -------------------------------------------------------------------------------- /tests/test_gsl_odeiv2_anyode_autorestart.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN 3 | #include "doctest.h" 4 | #include "anyode/anyode.hpp" 5 | #include "gsl_odeiv2_anyode.hpp" 6 | #include "cetsa_case.hpp" 7 | #include 8 | 9 | 10 | TEST_CASE( "adaptive_autorestart" ) { 11 | std::vector p = {{298.15, 39390, -135.3, 18010, 44960, 48.2, 65919.5, -93.8304, 1780, 3790, 57.44, 19700, -157.4}}; 12 | std::vector y0 = {{8.99937e-07, 0.000693731, 0.000264211, 0.000340312, 4.11575e-05}}; 13 | double t0=0, tend=60; 14 | OdeSys odesys(&p[0]); 15 | 16 | const long int mxsteps=0; 17 | const double dx0=0.0; 18 | const double dx_min=0.0; 19 | const double dx_max=0.0; 20 | int autorestart=2; 21 | 22 | auto tout_yout = gsl_odeiv2_anyode::simple_adaptive(&odesys, 1e-8, 1e-8, gsl_odeiv2_cxx::StepType::BSIMP, 23 | &y0[0], t0, tend, mxsteps, dx0, dx_min, dx_max, autorestart); 24 | auto& tout = tout_yout.first; 25 | auto& yout = tout_yout.second; 26 | const int ref = tout.size() * odesys.get_ny(); 27 | REQUIRE( ref == yout.size() ); 28 | REQUIRE( odesys.current_info.nfo_int["n_steps"] > 1 ); 29 | REQUIRE( odesys.current_info.nfo_int["n_steps"] < 997 ); 30 | } 31 | -------------------------------------------------------------------------------- /tests/test_gsl_odeiv2_anyode_parallel.cpp: -------------------------------------------------------------------------------- 1 | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN 2 | #include "doctest.h" 3 | #include "gsl_odeiv2_anyode_parallel.hpp" 4 | #include "testing_utils.hpp" 5 | 6 | TEST_CASE( "decay_adaptive" ) { 7 | std::vector k {{ 2.0, 3.0}}; 8 | Decay odesys1(k[0]); 9 | Decay odesys2(k[1]); 10 | std::vector systems {{ &odesys1, &odesys2 }}; 11 | std::vector y0 {{ 5.0, 7.0 }}; 12 | std::vector t0 {{ 1.0, 3.0 }}; // delta = 2 13 | std::vector tend {{ 2.0, 5.0 }}; // delta = 3 14 | int mxsteps = 0; // => default 15 | double atol = 1e-10; 16 | std::vector dx0 {{ 1e-10, 1e-10 }}; 17 | std::vector dx_min {{ 1e-16, 1e-16 }}; 18 | std::vector dx_max {{ 1.0, 1.0 }}; 19 | 20 | auto result = gsl_odeiv2_anyode_parallel::multi_adaptive( 21 | systems, atol, 1e-10, gsl_odeiv2_cxx::StepType::RKCK, &y0[0], &t0[0], &tend[0], 22 | mxsteps, &dx0[0], &dx_min[0], &dx_max[0]); 23 | for (int idx=0; idx<2; ++idx){ 24 | const auto& tout = result[idx].first; 25 | const auto& yout = result[idx].second; 26 | for (unsigned j=0; jcurrent_info.nfo_int["n_steps"] > 1 ); 30 | REQUIRE( systems[idx]->current_info.nfo_int["n_steps"] < 997 ); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/test_gsl_odeiv2_cxx.cpp: -------------------------------------------------------------------------------- 1 | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN 2 | #include "doctest.h" 3 | #include "gsl_odeiv2_cxx.hpp" 4 | #include "testing_utils.hpp" 5 | 6 | 7 | TEST_CASE( "methods" ) { 8 | const int ny = 1; 9 | void * user_data = nullptr; 10 | double dx0 = 1e-12, atol=1e-8, rtol=1e-8; 11 | auto intgr = gsl_odeiv2_cxx::GSLIntegrator( 12 | rhs_cb, nullptr, ny, gsl_odeiv2_cxx::StepType::MSADAMS, 13 | dx0, atol, rtol, user_data); 14 | std::vector y0(1, 1.0); 15 | std::vector tout {{0.0, 1.0}}; 16 | std::vector yout(2); 17 | intgr.predefined(tout.size(), &tout[0], &y0[0], &yout[0]); 18 | double yref = std::exp(-tout[1]); 19 | REQUIRE( std::abs(yout[1] - yref) < 1e-7 ); 20 | // REQUIRE( intgr.get_n_steps() > 3 ); // m_drv, m_evo don't share n_steps for some reason 21 | // REQUIRE( intgr.get_n_steps() < 100 ); // m_drv, m_evo don't share n_steps for some reason 22 | } 23 | 24 | double get_dx_max(double /* x */, const double * const /* y */){ 25 | return 1e-3; 26 | } 27 | 28 | TEST_CASE( "adaptive" ) { 29 | const int ny = 1; 30 | bool return_on_error = false; 31 | int autorestart = 0; 32 | void * user_data = nullptr; 33 | double dx0 = 1e-12, atol=1e-9, rtol=1e-9; 34 | auto intgr = gsl_odeiv2_cxx::GSLIntegrator( 35 | rhs_cb, nullptr, ny, gsl_odeiv2_cxx::StepType::MSADAMS, 36 | dx0, atol, rtol, user_data); 37 | intgr.m_drv.set_max_num_steps(1019); 38 | std::vector y0(1, 1.0); 39 | double xend = 1.0; 40 | auto xout_yout = intgr.adaptive(0.0, xend, &y0[0], autorestart, 41 | return_on_error, get_dx_max); 42 | auto& xout = xout_yout.first; 43 | auto& yout = xout_yout.second; 44 | REQUIRE( xout[0] == 0.0 ); 45 | REQUIRE( yout[0] == 1.0 ); 46 | int nt = xout.size(); 47 | for (int idx=1; idx 0 ); 50 | REQUIRE( xout[idx] <= 1 ); 51 | REQUIRE( std::abs(yout[idx] - yref) < 1e-8 ); 52 | } 53 | REQUIRE( intgr.get_n_steps() > 1000 ); 54 | } 55 | 56 | double get_dx_max2(double /* x */, const double * const /* y */){ 57 | return 1e-3; 58 | } 59 | 60 | TEST_CASE( "predefined" ) { 61 | const int ny = 1; 62 | bool return_on_error = false; 63 | int autorestart = 0; 64 | void * user_data = nullptr; 65 | double dx0 = 1e-12, atol=1e-9, rtol=1e-9; 66 | auto intgr = gsl_odeiv2_cxx::GSLIntegrator( 67 | rhs_cb, nullptr, ny, gsl_odeiv2_cxx::StepType::MSADAMS, 68 | dx0, atol, rtol, user_data); 69 | intgr.m_drv.set_max_num_steps(1019); 70 | int nt = 702; 71 | double tend = 2.0; 72 | std::vector tout(702); 73 | for (int idx=0; idx yout(nt*ny); 76 | std::vector y0(1, 1.0); 77 | auto nout = intgr.predefined(nt, &tout[0], &y0[0], &yout[0], autorestart, 78 | return_on_error, get_dx_max2); 79 | for (int idx=0; idx 1000 ); // m_drv, m_evo don't share n_steps for some reason 85 | } 86 | -------------------------------------------------------------------------------- /tests/testing_utils.hpp: -------------------------------------------------------------------------------- 1 | #include "anyode/anyode.hpp" 2 | 3 | int rhs_cb(double t, const double * const y, double * const f, void * user_data){ 4 | AnyODE::ignore(t); AnyODE::ignore(user_data); 5 | f[0] = -y[0]; 6 | return 0; 7 | } 8 | 9 | struct Decay : public AnyODE::OdeSysBase { 10 | double m_k; 11 | 12 | Decay(double k) : m_k(k) {} 13 | int get_ny() const override { return 1; } 14 | AnyODE::Status rhs(double t, const double * const __restrict__ y, double * const __restrict__ f) override { 15 | AnyODE::ignore(t); 16 | f[0] = -y[0]; 17 | this->nfev++; 18 | return AnyODE::Status::success; 19 | } 20 | double get_dx_max(double /* t */, const double * const /* y */) override { 21 | return 5e-4; 22 | } 23 | }; 24 | --------------------------------------------------------------------------------