├── .cargo └── config.toml ├── .codecov.yaml ├── .codespellrc ├── .coveragerc ├── .cruft.json ├── .flake8 ├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ ├── label_sync.yml │ ├── pre-commit.yml │ └── sub_package_update.yml ├── .gitignore ├── .isort.cfg ├── .pre-commit-config.yaml ├── .readthedocs.yaml ├── .rtd-environment.yml ├── .ruff.toml ├── CHANGELOG.rst ├── Cargo.toml ├── LICENSE ├── MANIFEST.in ├── README.md ├── RELEASING.md ├── asv.conf.json ├── benchmarks ├── __init__.py ├── benchmark.py ├── benchmark_plot.py ├── benchmarks.py └── pyinst.py ├── changelog └── README.rst ├── docs ├── Makefile ├── conf.py ├── index.rst ├── make.bat ├── streamtracer.rst └── whatsnew │ ├── changelog.rst │ └── index.rst ├── pyproject.toml ├── pytest.ini ├── python └── streamtracer │ ├── __init__.py │ ├── streamline.py │ ├── tests │ ├── __init__.py │ └── test_streamline.py │ └── version.py ├── src ├── field.rs ├── interp.rs ├── lib.rs ├── test_field.rs ├── test_interp.rs ├── test_tracer.rs └── trace.rs └── tox.ini /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | # See https://pyo3.rs/v0.17.1/building_and_distribution.html#macos 2 | [target.x86_64-apple-darwin] 3 | rustflags = [ 4 | "-C", "link-arg=-undefined", 5 | "-C", "link-arg=dynamic_lookup", 6 | ] 7 | 8 | [target.aarch64-apple-darwin] 9 | rustflags = [ 10 | "-C", "link-arg=-undefined", 11 | "-C", "link-arg=dynamic_lookup", 12 | ] 13 | -------------------------------------------------------------------------------- /.codecov.yaml: -------------------------------------------------------------------------------- 1 | comment: off 2 | coverage: 3 | status: 4 | project: 5 | default: 6 | threshold: 0.2% 7 | 8 | codecov: 9 | require_ci_to_pass: false 10 | notify: 11 | wait_for_ci: true 12 | -------------------------------------------------------------------------------- /.codespellrc: -------------------------------------------------------------------------------- 1 | [codespell] 2 | skip = *.asdf,*.fits,*.fts,*.header,*.json,*.xsh,*cache*,*egg*,*extern*,.git,.idea,.tox,_build,*truncated,*.svg,.asv_env,.history 3 | ignore-words-list = 4 | alog, 5 | crate, 6 | nd, 7 | nin, 8 | observ, 9 | ot, 10 | te, 11 | upto, 12 | afile, 13 | precessed, 14 | precess 15 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = 3 | streamtracer/conftest.py 4 | streamtracer/*setup_package* 5 | streamtracer/extern/* 6 | streamtracer/version* 7 | */streamtracer/conftest.py 8 | */streamtracer/*setup_package* 9 | */streamtracer/extern/* 10 | */streamtracer/version* 11 | 12 | [report] 13 | exclude_lines = 14 | # Have to re-enable the standard pragma 15 | pragma: no cover 16 | # Don't complain about packages we have installed 17 | except ImportError 18 | # Don't complain if tests don't hit assertions 19 | raise AssertionError 20 | raise NotImplementedError 21 | # Don't complain about script hooks 22 | def main(.*): 23 | # Ignore branches that don't pertain to this version of Python 24 | pragma: py{ignore_python_version} 25 | # Don't complain about IPython completion helper 26 | def _ipython_key_completions_ 27 | # typing.TYPE_CHECKING is False at runtime 28 | if TYPE_CHECKING: 29 | # Ignore typing overloads 30 | @overload 31 | -------------------------------------------------------------------------------- /.cruft.json: -------------------------------------------------------------------------------- 1 | { 2 | "template": "https://github.com/sunpy/package-template", 3 | "commit": "1bdd28c1e2d725d9ae9d9c0b6ad682d75687f45d", 4 | "checkout": null, 5 | "context": { 6 | "cookiecutter": { 7 | "package_name": "streamtracer", 8 | "module_name": "streamtracer", 9 | "short_description": "Python wrapped fortran to calculate streamlines", 10 | "author_name": "The SunPy Developers", 11 | "author_email": "sunpy@googlegroups.com", 12 | "project_url": "https://sunpy.org", 13 | "github_repo": "sunpy/streamtracer", 14 | "sourcecode_url": "https://github.com/sunpy/streamtracer", 15 | "download_url": "https://pypi.org/project/streamtracer", 16 | "documentation_url": "https://docs.sunpy.org/projects/streamtracer", 17 | "changelog_url": "https://docs.sunpy.org/projects/streamtracer/en/stable/whatsnew/changelog.html", 18 | "issue_tracker_url": "https://github.com/sunpy/streamtracer/issues", 19 | "license": "GNU GPL v3+", 20 | "minimum_python_version": "3.10", 21 | "use_compiled_extensions": "n", 22 | "enable_dynamic_dev_versions": "n", 23 | "include_example_code": "n", 24 | "include_cruft_update_github_workflow": "y", 25 | "use_extended_ruff_linting": "y", 26 | "_sphinx_theme": "sunpy", 27 | "_parent_project": "", 28 | "_install_requires": "", 29 | "_copy_without_render": [ 30 | "docs/_templates", 31 | "docs/_static", 32 | ".github/workflows/sub_package_update.yml" 33 | ], 34 | "_template": "https://github.com/sunpy/package-template", 35 | "_commit": "1bdd28c1e2d725d9ae9d9c0b6ad682d75687f45d" 36 | } 37 | }, 38 | "directory": null 39 | } 40 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = 3 | # missing-whitespace-around-operator 4 | E225 5 | # missing-whitespace-around-arithmetic-operator 6 | E226 7 | # line-too-long 8 | E501 9 | # unused-import 10 | F401 11 | # undefined-local-with-import-star 12 | F403 13 | # redefined-while-unused 14 | F811 15 | # Line break occurred before a binary operator 16 | W503, 17 | # Line break occurred after a binary operator 18 | W504 19 | max-line-length = 110 20 | exclude = 21 | .git 22 | __pycache__ 23 | docs/conf.py 24 | build 25 | streamtracer/__init__.py 26 | rst-directives = 27 | plot 28 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "github-actions" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | - package-ecosystem: "Cargo" 13 | directory: "/" 14 | schedule: 15 | interval: "monthly" 16 | groups: 17 | rust: # group all rust deps into a single PR 18 | patterns: 19 | - "*" 20 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # Main CI Workflow 2 | name: CI 3 | 4 | on: 5 | push: 6 | branches: 7 | - 'main' 8 | - '*.*' 9 | - '!*backport*' 10 | tags: 11 | - 'v*' 12 | - '!*dev*' 13 | - '!*pre*' 14 | - '!*post*' 15 | pull_request: 16 | # Allow manual runs through the web UI 17 | workflow_dispatch: 18 | schedule: 19 | # ┌───────── minute (0 - 59) 20 | # │ ┌───────── hour (0 - 23) 21 | # │ │ ┌───────── day of the month (1 - 31) 22 | # │ │ │ ┌───────── month (1 - 12 or JAN-DEC) 23 | # │ │ │ │ ┌───────── day of the week (0 - 6 or SUN-SAT) 24 | - cron: '0 7 * * 3' # Every Wed at 07:00 UTC 25 | 26 | concurrency: 27 | group: ${{ github.workflow }}-${{ github.ref }} 28 | cancel-in-progress: true 29 | 30 | jobs: 31 | rust: 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v4 35 | - uses: hecrj/setup-rust-action@v2 36 | - run: cargo test 37 | 38 | core: 39 | needs: [rust] 40 | uses: OpenAstronomy/github-actions-workflows/.github/workflows/tox.yml@v1 41 | with: 42 | submodules: false 43 | coverage: codecov 44 | toxdeps: tox-pypi-filter 45 | envs: | 46 | - linux: py313 47 | secrets: 48 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 49 | 50 | sdist_verify: 51 | runs-on: ubuntu-latest 52 | steps: 53 | - uses: actions/checkout@v4 54 | - uses: actions/setup-python@v5 55 | with: 56 | python-version: '3.12' 57 | - run: python -m pip install -U --user build 58 | - run: python -m build . --sdist 59 | - run: python -m pip install -U --user twine 60 | - run: python -m twine check dist/* 61 | 62 | test: 63 | needs: [core, sdist_verify, rust] 64 | uses: sunpy/github-actions-workflows/.github/workflows/tox.yml@main 65 | with: 66 | submodules: false 67 | coverage: codecov 68 | toxdeps: tox-pypi-filter 69 | envs: | 70 | - windows: py311 71 | - macos: py310 72 | - linux: py312 73 | - linux: py310-oldestdeps 74 | - linux: py312 75 | runs-on: ubuntu-24.04-arm 76 | - linux: py313-devdeps 77 | secrets: 78 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 79 | 80 | docs: 81 | needs: [core] 82 | uses: OpenAstronomy/github-actions-workflows/.github/workflows/tox.yml@v1 83 | with: 84 | default_python: '3.12' 85 | submodules: false 86 | pytest: false 87 | toxdeps: tox-pypi-filter 88 | libraries: | 89 | apt: 90 | - graphviz 91 | envs: | 92 | - linux: build_docs 93 | 94 | publish: 95 | # Build wheels on PRs only when labelled. Releases will only be published if tagged ^v.* 96 | # see https://github-actions-workflows.openastronomy.org/en/latest/publish.html#upload-to-pypi 97 | if: | 98 | github.event_name != 'pull_request' || 99 | ( 100 | github.event_name == 'pull_request' && 101 | contains(github.event.pull_request.labels.*.name, 'Run publish') 102 | ) 103 | needs: [test, docs] 104 | uses: sunpy/github-actions-workflows/.github/workflows/publish.yml@main 105 | with: 106 | sdist: true 107 | test_extras: 'tests' 108 | test_command: 'pytest -p no:warnings --doctest-rst --pyargs streamtracer' 109 | submodules: false 110 | targets: | 111 | - cp3{10,11,12,13}-manylinux_x86_64 112 | - cp3{10,11,12,13}-musllinux_x86_64 113 | - cp3{10,11,12,13}-macosx_x86_64 114 | - cp3{10,11,12,13}-macosx_arm64 115 | - cp3{10,11,12,13}-win_amd64 116 | - target: cp3{10,11,12,13}-manylinux_aarch64 117 | runs-on: ubuntu-24.04-arm 118 | secrets: 119 | pypi_token: ${{ secrets.pypi_token }} 120 | 121 | notify: 122 | if: always() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') 123 | needs: [publish] 124 | runs-on: ubuntu-latest 125 | steps: 126 | - uses: Cadair/matrix-notify-action@main 127 | with: 128 | matrix_token: ${{ secrets.matrix_access_token }} 129 | github_token: ${{ secrets.GITHUB_TOKEN }} 130 | homeserver: ${{ secrets.matrix_homeserver }} 131 | roomid: '!jfEXWJFdXwYnBWsiqk:openastronomy.org' 132 | ignore_pattern: '.*Load.*' 133 | summarise_success: true 134 | workflow_description: 'in sunpy/streamtracer' 135 | -------------------------------------------------------------------------------- /.github/workflows/label_sync.yml: -------------------------------------------------------------------------------- 1 | name: Label Sync 2 | on: 3 | workflow_dispatch: 4 | schedule: 5 | # ┌───────── minute (0 - 59) 6 | # │ ┌───────── hour (0 - 23) 7 | # │ │ ┌───────── day of the month (1 - 31) 8 | # │ │ │ ┌───────── month (1 - 12 or JAN-DEC) 9 | # │ │ │ │ ┌───────── day of the week (0 - 6 or SUN-SAT) 10 | - cron: '0 0 * * *' # run every day at midnight UTC 11 | 12 | # Give permissions to write issue labels 13 | permissions: 14 | issues: write 15 | 16 | jobs: 17 | label_sync: 18 | runs-on: ubuntu-latest 19 | name: Label Sync 20 | steps: 21 | - uses: srealmoreno/label-sync-action@850ba5cef2b25e56c6c420c4feed0319294682fd 22 | with: 23 | config-file: https://raw.githubusercontent.com/sunpy/.github/main/labels.yml 24 | -------------------------------------------------------------------------------- /.github/workflows/pre-commit.yml: -------------------------------------------------------------------------------- 1 | name: pre-commit 2 | 3 | on: 4 | pull_request: 5 | 6 | concurrency: 7 | group: ${{ github.workflow }}-${{ github.ref }} 8 | cancel-in-progress: true 9 | 10 | jobs: 11 | run: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v3 15 | - uses: actions/setup-python@v4 16 | with: 17 | python-version: 3.x 18 | - uses: pre-commit/action@v3.0.1 19 | - uses: pre-commit-ci/lite-action@v1.1.0 20 | if: always() 21 | -------------------------------------------------------------------------------- /.github/workflows/sub_package_update.yml: -------------------------------------------------------------------------------- 1 | # This template is taken from the cruft example code, for further information please see: 2 | # https://cruft.github.io/cruft/#automating-updates-with-github-actions 3 | name: Automatic Update from package template 4 | permissions: 5 | contents: write 6 | pull-requests: write 7 | 8 | on: 9 | # Allow manual runs through the web UI 10 | workflow_dispatch: 11 | schedule: 12 | # ┌───────── minute (0 - 59) 13 | # │ ┌───────── hour (0 - 23) 14 | # │ │ ┌───────── day of the month (1 - 31) 15 | # │ │ │ ┌───────── month (1 - 12 or JAN-DEC) 16 | # │ │ │ │ ┌───────── day of the week (0 - 6 or SUN-SAT) 17 | - cron: '0 7 * * 1' # Every Monday at 7am UTC 18 | 19 | jobs: 20 | update: 21 | runs-on: ubuntu-latest 22 | strategy: 23 | fail-fast: true 24 | steps: 25 | - uses: actions/checkout@v4 26 | 27 | - uses: actions/setup-python@v5 28 | with: 29 | python-version: "3.11" 30 | 31 | - name: Install Cruft 32 | run: python -m pip install git+https://github.com/Cadair/cruft@patch-p1 33 | 34 | - name: Check if update is available 35 | continue-on-error: false 36 | id: check 37 | run: | 38 | CHANGES=0 39 | if [ -f .cruft.json ]; then 40 | if ! cruft check; then 41 | CHANGES=1 42 | fi 43 | else 44 | echo "No .cruft.json file" 45 | fi 46 | 47 | echo "has_changes=$CHANGES" >> "$GITHUB_OUTPUT" 48 | 49 | - name: Run update if available 50 | id: cruft_update 51 | if: steps.check.outputs.has_changes == '1' 52 | run: | 53 | git config --global user.email "${{ github.actor }}@users.noreply.github.com" 54 | git config --global user.name "${{ github.actor }}" 55 | 56 | cruft_output=$(cruft update --skip-apply-ask --refresh-private-variables) 57 | echo $cruft_output 58 | git restore --staged . 59 | 60 | if [[ "$cruft_output" == *"Failed to cleanly apply the update, there may be merge conflicts."* ]]; then 61 | echo merge_conflicts=1 >> $GITHUB_OUTPUT 62 | else 63 | echo merge_conflicts=0 >> $GITHUB_OUTPUT 64 | fi 65 | 66 | - name: Check if only .cruft.json is modified 67 | id: cruft_json 68 | if: steps.check.outputs.has_changes == '1' 69 | run: | 70 | git status --porcelain=1 71 | if [[ "$(git status --porcelain=1)" == " M .cruft.json" ]]; then 72 | echo "Only .cruft.json is modified. Exiting workflow early." 73 | echo "has_changes=0" >> "$GITHUB_OUTPUT" 74 | else 75 | echo "has_changes=1" >> "$GITHUB_OUTPUT" 76 | fi 77 | 78 | - name: Create pull request 79 | if: steps.cruft_json.outputs.has_changes == '1' 80 | uses: peter-evans/create-pull-request@v7 81 | with: 82 | token: ${{ secrets.GITHUB_TOKEN }} 83 | add-paths: "." 84 | commit-message: "Automatic package template update" 85 | branch: "cruft/update" 86 | delete-branch: true 87 | draft: ${{ steps.cruft_update.outputs.merge_conflicts == '1' }} 88 | title: "Updates from the package template" 89 | labels: | 90 | No Changelog Entry Needed 91 | body: | 92 | This is an autogenerated PR, which will applies the latest changes from the [SunPy Package Template](https://github.com/sunpy/package-template). 93 | If this pull request has been opened as a draft there are conflicts which need fixing. 94 | 95 | **To run the CI on this pull request you will need to close it and reopen it.** 96 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### Python: https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | tmp/ 8 | 9 | # C extensions 10 | .coverage 11 | *.so 12 | .asv/* 13 | # Distribution / packaging 14 | .Python 15 | pip-wheel-metadata/ 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | share/python-wheels/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | MANIFEST 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | cover/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | # automodapi 78 | docs/api 79 | docs/sg_execution_times.rst 80 | 81 | # PyBuilder 82 | .pybuilder/ 83 | target/ 84 | 85 | # Jupyter Notebook 86 | .ipynb_checkpoints 87 | 88 | # IPython 89 | profile_default/ 90 | ipython_config.py 91 | 92 | # pyenv 93 | # For a library or package, you might want to ignore these files since the code is 94 | # intended to run in multiple environments; otherwise, check them in: 95 | # .python-version 96 | 97 | # pipenv 98 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 99 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 100 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 101 | # install all needed dependencies. 102 | #Pipfile.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Rope project settings 132 | .ropeproject 133 | 134 | # mkdocs documentation 135 | /site 136 | 137 | # mypy 138 | .mypy_cache/ 139 | 140 | # Pyre type checker 141 | .pyre/ 142 | 143 | # IDE 144 | # PyCharm 145 | .idea 146 | 147 | # Spyder project settings 148 | .spyderproject 149 | .spyproject 150 | 151 | ### VScode: https://raw.githubusercontent.com/github/gitignore/master/Global/VisualStudioCode.gitignore 152 | .vscode/* 153 | .vs/* 154 | 155 | ### https://raw.github.com/github/gitignore/master/Global/OSX.gitignore 156 | .DS_Store 157 | .AppleDouble 158 | .LSOverride 159 | 160 | # Icon must ends with two \r. 161 | Icon 162 | 163 | # Thumbnails 164 | ._* 165 | 166 | # Files that might appear on external disk 167 | .Spotlight-V100 168 | .Trashes 169 | 170 | ### Linux: https://raw.githubusercontent.com/github/gitignore/master/Global/Linux.gitignore 171 | *~ 172 | 173 | # temporary files which can be created if a process still has a handle open of a deleted file 174 | .fuse_hidden* 175 | 176 | # KDE directory preferences 177 | .directory 178 | 179 | # Linux trash folder which might appear on any partition or disk 180 | .Trash-* 181 | 182 | # .nfs files are created when an open file is removed but is still being accessed 183 | .nfs* 184 | 185 | # pytype static type analyzer 186 | .pytype/ 187 | 188 | # General 189 | .DS_Store 190 | .AppleDouble 191 | .LSOverride 192 | 193 | # Icon must end with two \r 194 | Icon 195 | 196 | 197 | # Thumbnails 198 | ._* 199 | 200 | # Files that might appear in the root of a volume 201 | .DocumentRevisions-V100 202 | .fseventsd 203 | .Spotlight-V100 204 | .TemporaryItems 205 | .Trashes 206 | .VolumeIcon.icns 207 | .com.apple.timemachine.donotpresent 208 | 209 | # Directories potentially created on remote AFP share 210 | .AppleDB 211 | .AppleDesktop 212 | Network Trash Folder 213 | Temporary Items 214 | .apdisk 215 | 216 | ### Windows: https://raw.githubusercontent.com/github/gitignore/master/Global/Windows.gitignore 217 | 218 | # Windows thumbnail cache files 219 | Thumbs.db 220 | ehthumbs.db 221 | ehthumbs_vista.db 222 | 223 | # Dump file 224 | *.stackdump 225 | 226 | # Folder config file 227 | [Dd]esktop.ini 228 | 229 | # Recycle Bin used on file shares 230 | $RECYCLE.BIN/ 231 | 232 | # Windows Installer files 233 | *.cab 234 | *.msi 235 | *.msix 236 | *.msm 237 | *.msp 238 | 239 | # Windows shortcuts 240 | *.lnk 241 | 242 | ### Extra Python Items and SunPy Specific 243 | docs/whatsnew/latest_changelog.txt 244 | examples/**/*.csv 245 | figure_test_images* 246 | tags 247 | baseline 248 | 249 | # Release script 250 | .github_cache 251 | 252 | # Misc Stuff 253 | .history 254 | *.orig 255 | .tmp 256 | node_modules/ 257 | package-lock.json 258 | package.json 259 | .prettierrc 260 | 261 | # Log files generated by 'vagrant up' 262 | *.log 263 | 264 | # Rust specific stuff 265 | target/* 266 | Cargo.lock 267 | 268 | # other streamtracer things 269 | benchmarks/*.csv 270 | -------------------------------------------------------------------------------- /.isort.cfg: -------------------------------------------------------------------------------- 1 | [settings] 2 | balanced_wrapping = true 3 | skip = 4 | docs/conf.py 5 | streamtracer/__init__.py 6 | default_section = THIRDPARTY 7 | include_trailing_comma = true 8 | known_astropy = astropy, asdf 9 | known_sunpy = sunpy 10 | known_first_party = streamtracer 11 | length_sort = false 12 | length_sort_sections = stdlib 13 | line_length = 110 14 | multi_line_output = 3 15 | no_lines_before = LOCALFOLDER 16 | sections = STDLIB, THIRDPARTY, ASTROPY, SUNPY, FIRSTPARTY, LOCALFOLDER 17 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | # This should be before any formatting hooks like isort 3 | - repo: https://github.com/astral-sh/ruff-pre-commit 4 | rev: "v0.11.12" 5 | hooks: 6 | - id: ruff 7 | args: ["--fix"] 8 | - repo: https://github.com/PyCQA/isort 9 | rev: 6.0.1 10 | hooks: 11 | - id: isort 12 | exclude: ".*(.fits|.fts|.fit|.header|.txt|tca.*|extern.*|streamtracer/extern)$" 13 | - repo: https://github.com/pre-commit/pre-commit-hooks 14 | rev: v5.0.0 15 | hooks: 16 | - id: check-ast 17 | - id: check-case-conflict 18 | - id: trailing-whitespace 19 | exclude: ".*(.fits|.fts|.fit|.header|.txt)$" 20 | - id: check-yaml 21 | - id: debug-statements 22 | - id: check-added-large-files 23 | args: ["--enforce-all", "--maxkb=1054"] 24 | - id: end-of-file-fixer 25 | exclude: ".*(.fits|.fts|.fit|.header|.txt|tca.*|.json)$|^CITATION.rst$" 26 | - id: mixed-line-ending 27 | exclude: ".*(.fits|.fts|.fit|.header|.txt|tca.*)$" 28 | - repo: https://github.com/codespell-project/codespell 29 | rev: v2.4.1 30 | hooks: 31 | - id: codespell 32 | args: [ "--write-changes" ] 33 | # Run mypy type validation 34 | - repo: https://github.com/pre-commit/mirrors-mypy 35 | rev: 'v1.10.0' 36 | hooks: 37 | - id: mypy 38 | additional_dependencies: [types-setuptools] 39 | # Python code formatting 40 | - repo: https://github.com/psf/black 41 | rev: 24.4.2 42 | hooks: 43 | - id: black 44 | # Rust code formatting 45 | - repo: https://github.com/FeryET/pre-commit-rust 46 | rev: v1.1.0 47 | hooks: 48 | - id: cargo-check 49 | - id: clippy 50 | args: ["--allow-staged", "--fix", "--", "-A", "clippy::needless_return", "-W", "clippy::implicit_return"] 51 | - id: fmt 52 | ci: 53 | autofix_prs: false 54 | autoupdate_schedule: "quarterly" 55 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | build: 4 | os: ubuntu-lts-latest 5 | tools: 6 | python: "mambaforge-latest" 7 | jobs: 8 | post_checkout: 9 | - git fetch --unshallow || true 10 | pre_install: 11 | - git update-index --assume-unchanged .rtd-environment.yml docs/conf.py 12 | 13 | conda: 14 | environment: .rtd-environment.yml 15 | 16 | sphinx: 17 | builder: html 18 | configuration: docs/conf.py 19 | fail_on_warning: false 20 | 21 | formats: 22 | - htmlzip 23 | 24 | python: 25 | install: 26 | - method: pip 27 | extra_requirements: 28 | - docs 29 | path: . 30 | -------------------------------------------------------------------------------- /.rtd-environment.yml: -------------------------------------------------------------------------------- 1 | name: streamtracer 2 | channels: 3 | - conda-forge 4 | dependencies: 5 | - python=3.12 6 | - pip 7 | - graphviz!=2.42.*,!=2.43.* 8 | - rust 9 | -------------------------------------------------------------------------------- /.ruff.toml: -------------------------------------------------------------------------------- 1 | target-version = "py310" 2 | line-length = 120 3 | exclude = [ 4 | ".git,", 5 | "__pycache__", 6 | "build", 7 | "streamtracer/version.py", 8 | ] 9 | 10 | [lint] 11 | select = [ 12 | "E", 13 | "F", 14 | "W", 15 | "UP", 16 | "PT", 17 | "BLE", 18 | "A", 19 | "C4", 20 | "INP", 21 | "PIE", 22 | "T20", 23 | "RET", 24 | "TID", 25 | "PTH", 26 | "PD", 27 | "PLC", 28 | "PLE", 29 | "FLY", 30 | "NPY", 31 | "PERF", 32 | "RUF", 33 | ] 34 | extend-ignore = [ 35 | # pycodestyle (E, W) 36 | "E501", # ignore line length will use a formatter instead 37 | # pyupgrade (UP) 38 | "UP038", # Use | in isinstance - not compatible with models and is slower 39 | # pytest (PT) 40 | "PT001", # Always use pytest.fixture() 41 | "PT023", # Always use () on pytest decorators 42 | # flake8-pie (PIE) 43 | "PIE808", # Disallow passing 0 as the first argument to range 44 | # flake8-use-pathlib (PTH) 45 | "PTH123", # open() should be replaced by Path.open() 46 | # Ruff (RUF) 47 | "RUF003", # Ignore ambiguous quote marks, doesn't allow ' in comments 48 | "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` 49 | "RUF013", # PEP 484 prohibits implicit `Optional` 50 | "RUF015", # Prefer `next(iter(...))` over single element slice 51 | ] 52 | 53 | [lint.per-file-ignores] 54 | "setup.py" = [ 55 | "INP001", # File is part of an implicit namespace package. 56 | ] 57 | "conftest.py" = [ 58 | "INP001", # File is part of an implicit namespace package. 59 | ] 60 | "docs/conf.py" = [ 61 | "E402" # Module imports not at top of file 62 | ] 63 | "docs/*.py" = [ 64 | "INP001", # File is part of an implicit namespace package. 65 | ] 66 | "examples/**.py" = [ 67 | "T201", # allow use of print in examples 68 | "INP001", # File is part of an implicit namespace package. 69 | ] 70 | "__init__.py" = [ 71 | "E402", # Module level import not at top of cell 72 | "F401", # Unused import 73 | "F403", # from {name} import * used; unable to detect undefined names 74 | "F405", # {name} may be undefined, or defined from star imports 75 | ] 76 | "test_*.py" = [ 77 | "E402", # Module level import not at top of cell 78 | ] 79 | "benchmarks/*.py" = [ 80 | "NPY002", # TODO: Generator API 81 | ] 82 | 83 | [lint.pydocstyle] 84 | convention = "numpy" 85 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | 2.4.1 (2025-04-09) 2 | ================== 3 | 4 | Breaking Changes 5 | ---------------- 6 | 7 | - Increased version of pyo3 and numpy to account for "Risk of buffer overflow" exploit (`#201 `__) 8 | 9 | 10 | 2.4.0 (2025-03-13) 11 | ================== 12 | 13 | Breaking Changes 14 | ---------------- 15 | 16 | - The minimum supported version for macos binaries is now Sierra (10.12). (`#192 `__) 17 | 18 | 19 | 2.3.0 20 | ===== 21 | 22 | * Add support for Python 3.13 `#176 `__ 23 | * Minor docstring formatting fixes, refactor input argument validation, and fix bug when tracing in +/-1 direction `#172 `__ 24 | * Build binaries for aarch64 on native runners `#167 `__ 25 | 26 | 2.2.0 27 | ===== 28 | 29 | * Improved performance of the Rust streamtracing algorithm, so it is now close to or faster than the old FORTRAN version. 30 | 31 | 2.1.0 32 | ===== 33 | 34 | * Wheels for Python 3.12 are now built and published on PyPI. 35 | * Rust code is now parallelized and while still not as fast as the old FORTRAN version, is near parity. 36 | 37 | 2.0.1 38 | ===== 39 | 40 | * streamtracer now includes wheels for Python 3.11, and these have now been uploaded to PyPI as a release (version 2.0.0 was only ever uploaded as an alpha). 41 | * streamtracer is now available on conda-forge. 42 | * streamtracer still does not work in parallel, if you require parallel stream tracing then for now either: 43 | 44 | * Downgrade to version 1.2.0 45 | * Manually run several instances of the streamtracer in parallel 46 | 47 | 2.0.0 48 | ===== 49 | 50 | * The low level streamline tracing code has been ported from FORTRAN to Rust. 51 | This has several benefits on the development side, and from a user perspective brings the first built wheels for Windows 🪟🎉 52 | The new code is **not** *yet* parallelized, so when tracing multiple streamlines on multiple cores runs slower than version 1. 53 | Version 2.1 (hopefully coming soon!) should implement parallel line tracing. 54 | * The minimum supported Python version is now 3.8. 55 | 56 | 1.2.0 57 | ===== 58 | 59 | New features 60 | ------------ 61 | 62 | * Added the ability to trace field lines through non-uniformly spaced grids. 63 | To do this pass a list of grid coordinates to the new ``grid_coords`` argument in `-streamtracer.Grid`. 64 | 65 | Bug fixes 66 | --------- 67 | 68 | * Fixed coordinate values returned by `streamtracer.Grid.xcoords` etc. 69 | Previously the origin coordinate was interpreted negative what it should be. 70 | This doesn't affect any traced streamlines. 71 | 72 | 1.1.2 73 | ===== 74 | 75 | * Fixed the example code listed above. 76 | 77 | 1.1.1 78 | ===== 79 | 80 | * Fixed wheel building to use the oldest supported version of numpy for each major version of python. 81 | This fixes errors like "module compiled against API version 0xe but this version of numpy is 0xd" that were in the 1.1.0 wheels. 82 | 83 | 1.1.0 84 | ===== 85 | 86 | * Fixed handling of steps going out of bounds. 87 | Previously, in the forward direction a single step would be saved out of bounds, but in the backwards direction the streamline ended before going out of bounds. 88 | Now both the forward and negative directions both save a single out of bounds step in each stream line. 89 | * Linux and macOS binary distributions (wheels) are now automatically built and uploaded, meaning you should no longer need a FORTRAN compiler installed locally to use streamtracer. 90 | * Minor performance and memory improvements have been made. 91 | 92 | 1.0.1 93 | ===== 94 | 95 | * Fix compilation issues on MacOS Big Sur. 96 | 97 | 1.0.0 98 | ===== 99 | 100 | * Nothing major, just re-versioning to a stable release number. 101 | 102 | 0.1.2 103 | ===== 104 | 105 | * Make sure to install numpy before trying to install streamtracer. 106 | 107 | 0.1.1 108 | ===== 109 | 110 | * Added validation for the ``max_steps`` argument to :class:`-streamtracer.StreamTracer`. 111 | 112 | 0.1.0 113 | ===== 114 | 115 | * First streamtracer release. 116 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "streamtracer" 3 | # rc versions in rust landhave the format x.y.z-rc.q 4 | version = "2.4.1" 5 | edition = "2021" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | [lib] 9 | name = "streamtracer" 10 | crate-type = ["cdylib"] 11 | 12 | [dependencies] 13 | pyo3 = {version = "0.24.1", features = ["extension-module"]} 14 | numpy = "0.24" # I think this should follow the pyo3 version, but it can be slow to release 15 | num-traits = "0.2" 16 | num-derive = "0.4" 17 | rayon = "1.10" 18 | ndarray = {version = "0.16", features = ["rayon"]} 19 | 20 | [dev-dependencies] 21 | float_eq = "1.0.0" 22 | 23 | [lints.clippy] 24 | needless_return = "allow" 25 | implicit_return = "warn" 26 | 27 | [profile.release] 28 | codegen-units = 1 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | # Exclude specific files 2 | # Prune folders 3 | prune build 4 | prune docs/_build 5 | prune docs/api 6 | global-exclude *.pyc *.o 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # streamtracer 2 | 3 | Fast streamline tracing in python 4 | 5 | [![Documentation Status](https://readthedocs.org/projects/streamtracer/badge/?version=stable)](https://docs.sunpy.org/projects/streamtracer/en/stable/?badge=stable) 6 | [![Build Status](https://github.com/sunpy/streamtracer/actions/workflows/ci.yml/badge.svg)](https://github.com/sunpy/streamtracer/actions/workflows/ci.yml) 7 | [![codecov](https://codecov.io/gh/sunpy/streamtracer/graph/badge.svg?token=4AzS0q7VPY)](https://codecov.io/gh/sunpy/streamtracer) 8 | 9 | ## Documentation 10 | 11 | For full documentation, including installation instructions, see 12 | https://docs.sunpy.org/projects/streamtracer 13 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | # How to do a Release 2 | 3 | 1) Update versions in pyproject.toml and Cargo.toml 4 | 2) Render changelog 5 | 3) Tag 6 | 4) Push 7 | 5) Profit 8 | -------------------------------------------------------------------------------- /asv.conf.json: -------------------------------------------------------------------------------- 1 | { 2 | // The version of the config file format. Do not change, unless 3 | // you know what you are doing. 4 | "version": 1, 5 | 6 | // The name of the project being benchmarked 7 | "project": "streamtracer", 8 | 9 | // The project's homepage 10 | "project_url": "https://github.com/dstansby/streamtracer", 11 | 12 | // The URL or local path of the source code repository for the 13 | // project being benchmarked 14 | "repo": ".", 15 | 16 | // The Python project's subdirectory in your repo. If missing or 17 | // the empty string, the project is assumed to be located at the root 18 | // of the repository. 19 | // "repo_subdir": "", 20 | 21 | // Customizable commands for building, installing, and 22 | // uninstalling the project. See asv.conf.json documentation. 23 | // 24 | // "install_command": ["in-dir={env_dir} python -mpip install {wheel_file}"], 25 | // "uninstall_command": ["return-code=any python -mpip uninstall -y {project}"], 26 | // "build_command": [ 27 | // "python setup.py build", 28 | // "PIP_NO_BUILD_ISOLATION=false python -mpip wheel --no-deps --no-index -w {build_cache_dir} {build_dir}" 29 | // ], 30 | 31 | // List of branches to benchmark. If not provided, defaults to "master" 32 | // (for git) or "default" (for mercurial). 33 | "branches": ["main"], // for git 34 | // "branches": ["default"], // for mercurial 35 | 36 | // The DVCS being used. If not set, it will be automatically 37 | // determined from "repo" by looking at the protocol in the URL 38 | // (if remote), or by looking for special directories, such as 39 | // ".git" (if local). 40 | // "dvcs": "git", 41 | 42 | // The tool to use to create environments. May be "conda", 43 | // "virtualenv" or other value depending on the plugins in use. 44 | // If missing or the empty string, the tool will be automatically 45 | // determined by looking for tools on the PATH environment 46 | // variable. 47 | "environment_type": "virtualenv", 48 | 49 | // timeout in seconds for installing any dependencies in environment 50 | // defaults to 10 min 51 | //"install_timeout": 600, 52 | 53 | // the base URL to show a commit for the project. 54 | "show_commit_url": "https://github.com/dstansby/streamtracer/commit/", 55 | 56 | // The Pythons you'd like to test against. If not provided, defaults 57 | // to the current version of Python used to run `asv`. 58 | // "pythons": ["2.7", "3.6"], 59 | 60 | // The list of conda channel names to be searched for benchmark 61 | // dependency packages in the specified order 62 | // "conda_channels": ["conda-forge", "defaults"], 63 | 64 | // The matrix of dependencies to test. Each key is the name of a 65 | // package (in PyPI) and the values are version numbers. An empty 66 | // list or empty string indicates to just test against the default 67 | // (latest) version. null indicates that the package is to not be 68 | // installed. If the package to be tested is only available from 69 | // PyPi, and the 'environment_type' is conda, then you can preface 70 | // the package name by 'pip+', and the package will be installed via 71 | // pip (with all the conda available packages installed first, 72 | // followed by the pip installed packages). 73 | // 74 | "matrix": { 75 | "numpy": [""], 76 | }, 77 | // "matrix": { 78 | // "numpy": ["1.6", "1.7"], 79 | // "six": ["", null], // test with and without six installed 80 | // "pip+emcee": [""], // emcee is only available for install with pip. 81 | // }, 82 | 83 | // Combinations of libraries/python versions can be excluded/included 84 | // from the set to test. Each entry is a dictionary containing additional 85 | // key-value pairs to include/exclude. 86 | // 87 | // An exclude entry excludes entries where all values match. The 88 | // values are regexps that should match the whole string. 89 | // 90 | // An include entry adds an environment. Only the packages listed 91 | // are installed. The 'python' key is required. The exclude rules 92 | // do not apply to includes. 93 | // 94 | // In addition to package names, the following keys are available: 95 | // 96 | // - python 97 | // Python version, as in the *pythons* variable above. 98 | // - environment_type 99 | // Environment type, as above. 100 | // - sys_platform 101 | // Platform, as in sys.platform. Possible values for the common 102 | // cases: 'linux2', 'win32', 'cygwin', 'darwin'. 103 | // 104 | // "exclude": [ 105 | // {"python": "3.2", "sys_platform": "win32"}, // skip py3.2 on windows 106 | // {"environment_type": "conda", "six": null}, // don't run without six on conda 107 | // ], 108 | // 109 | // "include": [ 110 | // // additional env for python2.7 111 | // {"python": "2.7", "numpy": "1.8"}, 112 | // // additional env if run on windows+conda 113 | // {"platform": "win32", "environment_type": "conda", "python": "2.7", "libpython": ""}, 114 | // ], 115 | 116 | // The directory (relative to the current directory) that benchmarks are 117 | // stored in. If not provided, defaults to "benchmarks" 118 | // "benchmark_dir": "benchmarks", 119 | 120 | // The directory (relative to the current directory) to cache the Python 121 | // environments in. If not provided, defaults to "env" 122 | "env_dir": ".asv/env", 123 | 124 | // The directory (relative to the current directory) that raw benchmark 125 | // results are stored in. If not provided, defaults to "results". 126 | "results_dir": ".asv/results", 127 | 128 | // The directory (relative to the current directory) that the html tree 129 | // should be written to. If not provided, defaults to "html". 130 | "html_dir": ".asv/html", 131 | 132 | // The number of characters to retain in the commit hashes. 133 | // "hash_length": 8, 134 | 135 | // `asv` will cache results of the recent builds in each 136 | // environment, making them faster to install next time. This is 137 | // the number of builds to keep, per environment. 138 | // "build_cache_size": 2, 139 | 140 | // The commits after which the regression search in `asv publish` 141 | // should start looking for regressions. Dictionary whose keys are 142 | // regexps matching to benchmark names, and values corresponding to 143 | // the commit (exclusive) after which to start looking for 144 | // regressions. The default is to start from the first commit 145 | // with results. If the commit is `null`, regression detection is 146 | // skipped for the matching benchmark. 147 | // 148 | // "regressions_first_commits": { 149 | // "some_benchmark": "352cdf", // Consider regressions only after this commit 150 | // "another_benchmark": null, // Skip regression detection altogether 151 | // }, 152 | 153 | // The thresholds for relative change in results, after which `asv 154 | // publish` starts reporting regressions. Dictionary of the same 155 | // form as in ``regressions_first_commits``, with values 156 | // indicating the thresholds. If multiple entries match, the 157 | // maximum is taken. If no entry matches, the default is 5%. 158 | // 159 | // "regressions_thresholds": { 160 | // "some_benchmark": 0.01, // Threshold of 1% 161 | // "another_benchmark": 0.5, // Threshold of 50% 162 | // }, 163 | } 164 | -------------------------------------------------------------------------------- /benchmarks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunpy/streamtracer/3463da16019af25f9e7f51463a6ac7395fb9ab41/benchmarks/__init__.py -------------------------------------------------------------------------------- /benchmarks/benchmark.py: -------------------------------------------------------------------------------- 1 | import time 2 | import importlib.metadata 3 | 4 | import matplotlib.pyplot as plt 5 | import numpy as np 6 | import pandas as pd 7 | 8 | from streamtracer import StreamTracer, VectorGrid 9 | 10 | # Support old 1.x versions 11 | __version__ = importlib.metadata.version("streamtracer") 12 | 13 | nsteps = 1000 14 | step_size = 0.1 15 | tracer = StreamTracer(nsteps, step_size) 16 | 17 | field = np.random.rand(*(180, 360, 50, 3)) 18 | grid_spacing = [1, 2, 3] 19 | grid = VectorGrid(field, grid_spacing) 20 | 21 | seedlist = 2 ** np.arange(17) 22 | times = [] 23 | for nseeds in seedlist: 24 | dts = [] 25 | for _ in range(5): 26 | # Trace from middle of field 27 | seeds = np.repeat([[90, 180, 25]], nseeds, axis=0) 28 | t = time.time() 29 | tracer.trace(seeds, grid) 30 | dts.append(time.time() - t) 31 | assert len(tracer.xs) == nseeds 32 | times += [np.mean(dts)] 33 | 34 | 35 | pd.DataFrame({"nseeds": seedlist, "time": times}).to_csv( 36 | f"v{__version__.replace('.', '')}.csv" 37 | ) 38 | 39 | fig, ax = plt.subplots() 40 | 41 | ax.plot(seedlist, times, marker=".") 42 | ax.set_xlabel("n seeds") 43 | ax.set_ylabel("time (s)") 44 | ax.set_xscale("log") 45 | ax.set_yscale("log") 46 | plt.show() 47 | -------------------------------------------------------------------------------- /benchmarks/benchmark_plot.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | import matplotlib.pyplot as plt 4 | import pandas as pd 5 | 6 | fig, ax = plt.subplots() 7 | 8 | version_names = { 9 | "120": "v1.2 (FORTRAN)", 10 | "200": "v2.0 (Rust)", 11 | "210dev0": "v2.1 (Rust Parallel)", 12 | } 13 | 14 | files = Path().glob("v*.csv") 15 | 16 | for file in files: 17 | label = version_names.get(file.stem[1:], file.stem) 18 | data = pd.read_csv(file) 19 | 20 | ax.plot(data["nseeds"], data["time"], label=label, marker="o") 21 | 22 | ax.legend() 23 | ax.set_xscale("log") 24 | ax.set_yscale("log") 25 | ax.set_xlabel("Number of seeds") 26 | ax.set_ylabel("Time / seconds") 27 | ax.set_title("Comparison of streamtracer performance for different versions") 28 | plt.show() 29 | -------------------------------------------------------------------------------- /benchmarks/benchmarks.py: -------------------------------------------------------------------------------- 1 | # Write the benchmarking functions here. 2 | # See "Writing benchmarks" in the asv docs for more information. 3 | import numpy as np 4 | 5 | from streamtracer import StreamTracer, VectorGrid 6 | 7 | 8 | class TimeSuite: 9 | def setup(self): 10 | self.tracer = StreamTracer(1000, 0.1) 11 | # A uniform field pointing in the x direction 12 | v = np.zeros((100, 100, 100, 3)) 13 | # Make all vectors point in the x-direction 14 | v[:, :, :, 0] = 1 15 | spacing = [1, 1, 1] 16 | self.grid = VectorGrid(v, spacing) 17 | 18 | def time_uniform_grid(self): 19 | # Check that tracing thought a uniform field gives sensible results 20 | seed = np.array([0, 0, 0]) 21 | seed = np.tile(seed, (1000, 1)) 22 | self.tracer.trace(seed, self.grid) 23 | 24 | 25 | """ 26 | class MemSuite: 27 | def mem_list(self): 28 | return [0] * 256 29 | """ 30 | -------------------------------------------------------------------------------- /benchmarks/pyinst.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from pyinstrument import Profiler 3 | 4 | from streamtracer import StreamTracer, VectorGrid 5 | 6 | profiler = Profiler() 7 | profiler.start() 8 | 9 | nsteps = 1000 10 | step_size = 0.1 11 | tracer = StreamTracer(nsteps, step_size) 12 | 13 | field = np.random.rand(*(180, 360, 50, 3)) 14 | grid_spacing = [1, 2, 3] 15 | grid = VectorGrid(field, grid_spacing) 16 | seeds = np.repeat([[90, 180, 25]], 2**10, axis=0) 17 | tracer.trace(seeds, grid) 18 | 19 | profiler.stop() 20 | 21 | profiler.print(show_all=True) 22 | -------------------------------------------------------------------------------- /changelog/README.rst: -------------------------------------------------------------------------------- 1 | ========= 2 | Changelog 3 | ========= 4 | 5 | .. note:: 6 | 7 | This README was adapted from the pytest changelog readme under the terms of the MIT licence. 8 | 9 | This directory contains "news fragments" which are short files that contain a small **ReST**-formatted text that will be added to the next ``CHANGELOG``. 10 | 11 | The ``CHANGELOG`` will be read by users, so this description should be aimed at SunPy users instead of describing internal changes which are only relevant to the developers. 12 | 13 | Make sure to use full sentences with correct case and punctuation, for example:: 14 | 15 | Add support for Helioprojective coordinates in `sunpy.coordinates.frames`. 16 | 17 | Please try to use Sphinx intersphinx using backticks. 18 | 19 | Each file should be named like ``.[.].rst``, where ```` is a pull request number, ``COUNTER`` is an optional number if a PR needs multiple entries with the same type and ```` is one of: 20 | 21 | * ``breaking``: A change which requires users to change code and is not backwards compatible. (Not to be used for removal of deprecated features.) 22 | * ``feature``: New user facing features and any new behavior. 23 | * ``bugfix``: Fixes a reported bug. 24 | * ``doc``: Documentation addition or improvement, like rewording an entire session or adding missing docs. 25 | * ``deprecation``: Feature deprecation 26 | * ``removal``: Feature removal. 27 | * ``trivial``: A change which has no user facing effect or is tiny change. 28 | 29 | So for example: ``123.feature.rst``, ``456.bugfix.rst``. 30 | 31 | If you are unsure what pull request type to use, don't hesitate to ask in your PR. 32 | 33 | Note that the ``towncrier`` tool will automatically reflow your text, so it will work best if you stick to a single paragraph, but multiple sentences and links are OK and encouraged. 34 | You can install ``towncrier`` and then run ``towncrier --draft`` if you want to get a preview of how your change will look in the final release notes. 35 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | import datetime 8 | 9 | from packaging.version import Version 10 | 11 | # -- Project information ----------------------------------------------------- 12 | 13 | # The full version, including alpha/beta/rc tags 14 | from streamtracer import __version__ 15 | 16 | _version = Version(__version__) 17 | version = release = str(_version) 18 | # Avoid "post" appearing in version string in rendered docs 19 | if _version.is_postrelease: 20 | version = release = _version.base_version 21 | # Avoid long githashes in rendered Sphinx docs 22 | elif _version.is_devrelease: 23 | version = release = f"{_version.base_version}.dev{_version.dev}" 24 | is_development = _version.is_devrelease 25 | is_release = not (_version.is_prerelease or _version.is_devrelease) 26 | 27 | project = "streamtracer" 28 | author = "The SunPy Developers, David Stansby" 29 | copyright = f"{datetime.datetime.now().year}, {author}" # noqa: A001 30 | 31 | # Home page 32 | master_doc = "index" 33 | 34 | # -- General configuration --------------------------------------------------- 35 | 36 | # Wrap large function/method signatures 37 | maximum_signature_line_length = 80 38 | 39 | # Add any Sphinx extension module names here, as strings. They can be 40 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 41 | # ones. 42 | extensions = [ 43 | "sphinx.ext.napoleon", 44 | "jupyter_sphinx", 45 | "sphinx.ext.mathjax", 46 | "sphinx_automodapi.automodapi", 47 | "sphinx_automodapi.smart_resolver", 48 | "sphinx_changelog", 49 | ] 50 | 51 | # Add any paths that contain templates here, relative to this directory. 52 | # templates_path = ["_templates"] 53 | 54 | # List of patterns, relative to source directory, that match files and 55 | # directories to ignore when looking for source files. 56 | # This pattern also affects html_static_path and html_extra_path. 57 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] 58 | 59 | # The suffix(es) of source filenames. 60 | # You can specify multiple suffix as a list of string: 61 | source_suffix = ".rst" 62 | 63 | # The master toctree document. 64 | master_doc = "index" 65 | 66 | # Treat everything in single ` as a Python reference. 67 | default_role = "py:obj" 68 | 69 | # -- Options for intersphinx extension --------------------------------------- 70 | 71 | # Example configuration for intersphinx: refer to the Python standard library. 72 | intersphinx_mapping = {"python": ("https://docs.python.org/", None)} 73 | 74 | # -- Options for HTML output ------------------------------------------------- 75 | 76 | # The theme to use for HTML and HTML Help pages. See the documentation for 77 | # a list of builtin themes. 78 | html_theme = "sunpy" 79 | 80 | # Render inheritance diagrams in SVG 81 | graphviz_output_format = "svg" 82 | 83 | graphviz_dot_args = [ 84 | "-Nfontsize=10", 85 | "-Nfontname=Helvetica Neue, Helvetica, Arial, sans-serif", 86 | "-Efontsize=10", 87 | "-Efontname=Helvetica Neue, Helvetica, Arial, sans-serif", 88 | "-Gfontsize=10", 89 | "-Gfontname=Helvetica Neue, Helvetica, Arial, sans-serif", 90 | ] 91 | 92 | # Add any paths that contain custom static files (such as style sheets) here, 93 | # relative to this directory. They are copied after the builtin static files, 94 | # so a file named "default.css" will overwrite the builtin "default.css". 95 | # html_static_path = ["_static"] 96 | 97 | # By default, when rendering docstrings for classes, sphinx.ext.autodoc will 98 | # make docs with the class-level docstring and the class-method docstrings, 99 | # but not the __init__ docstring, which often contains the parameters to 100 | # class constructors across the scientific Python ecosystem. The option below 101 | # will append the __init__ docstring to the class-level docstring when rendering 102 | # the docs. For more options, see: 103 | # https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autoclass_content 104 | autoclass_content = "both" 105 | 106 | # -- Other options ---------------------------------------------------------- 107 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | ************ 2 | streamtracer 3 | ************ 4 | 5 | streamtracer is a Python package for rapid streamline tracing on regularly spaced grids. 6 | The actual streamline tracing is done at a low level in Rust, with a nice Python API provided on top. 7 | 8 | .. toctree:: 9 | :maxdepth: 1 10 | 11 | streamtracer 12 | whatsnew/index 13 | 14 | Installing 15 | ========== 16 | 17 | It is possible to install streamtracer in one go with: 18 | 19 | .. code-block:: bash 20 | 21 | pip install streamtracer 22 | 23 | or using conda with: 24 | 25 | .. code-block:: bash 26 | 27 | conda install -c conda-forge streamtracer 28 | 29 | There are wheels available for Linux, macOS and Windows. 30 | If you need to compile from source, you will need to have a Rust compiler installed. 31 | 32 | If you have problems installing, please open an issue at https://github.com/sunpy/streamtracer/issues 33 | 34 | Usage 35 | ===== 36 | 37 | To use, create a :class:`streamtracer.StreamTracer` object 38 | 39 | .. jupyter-execute:: 40 | 41 | import numpy as np 42 | from streamtracer import StreamTracer, VectorGrid 43 | 44 | nsteps = 10000 45 | step_size = 0.1 46 | tracer = StreamTracer(nsteps, step_size) 47 | 48 | and a :class:`streamtracer.VectorGrid` 49 | 50 | .. jupyter-execute:: 51 | 52 | field = np.ones((10, 10, 10, 3)) 53 | grid_spacing = [1, 2, 1] 54 | grid = VectorGrid(field, grid_spacing) 55 | 56 | This can then be used to trace lines through a 3D cartesian vector field 57 | 58 | .. jupyter-execute:: 59 | 60 | seeds = np.array([[0, 0, 0], [0, 0, 1]]) 61 | tracer.trace(seeds, grid) 62 | 63 | and the traced field lines can be accessed via. the ``.xs`` attribute 64 | 65 | .. jupyter-execute:: 66 | 67 | print(f'Number of traced lines: {len(tracer.xs)}') 68 | line_lengths = [len(x) for x in tracer.xs] 69 | print(f'Line lengths: {line_lengths}') 70 | 71 | For more information see the :mod:`streamtracer` API docs. 72 | 73 | Boundary handling 74 | ================= 75 | 76 | When the stream tracer steps outside the boundary of the grid, the first point outside the grid is saved in the traced stream line. 77 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/streamtracer.rst: -------------------------------------------------------------------------------- 1 | .. automodapi:: streamtracer 2 | :no-inheritance-diagram: 3 | -------------------------------------------------------------------------------- /docs/whatsnew/changelog.rst: -------------------------------------------------------------------------------- 1 | .. _changelog: 2 | 3 | ************** 4 | Full Changelog 5 | ************** 6 | 7 | .. changelog:: 8 | :towncrier: ../../ 9 | :towncrier-skip-if-empty: 10 | :changelog_file: ../../CHANGELOG.rst 11 | -------------------------------------------------------------------------------- /docs/whatsnew/index.rst: -------------------------------------------------------------------------------- 1 | .. _whatsnew: 2 | 3 | *************** 4 | Release History 5 | *************** 6 | 7 | This page documents the releases for streamtracer 8 | 9 | .. toctree:: 10 | :maxdepth: 1 11 | 12 | changelog 13 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "maturin>=1.0,<2.0", 4 | ] 5 | build-backend = "maturin" 6 | 7 | [project] 8 | name = "streamtracer" 9 | description = "Python library to calculate streamlines" 10 | readme = { file = "README.md", content-type = "text/markdown" } 11 | license = { file = "LICENSE" } 12 | requires-python = ">=3.10" 13 | authors = [ 14 | {name = "The SunPy Developers", email="sunpy@googlegroups.com"}, 15 | {name = "David Stansby"}, 16 | {name = "Lars Mejnertsen"} 17 | ] 18 | classifiers = [ 19 | "Development Status :: 5 - Production/Stable", 20 | "Intended Audience :: Science/Research", 21 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 22 | "Natural Language :: English", 23 | "Operating System :: OS Independent", 24 | "Programming Language :: Python", 25 | "Programming Language :: Python :: 3", 26 | "Programming Language :: Python :: 3.10", 27 | "Programming Language :: Python :: 3.11", 28 | "Programming Language :: Python :: 3.12", 29 | "Programming Language :: Python :: 3.13", 30 | "Topic :: Scientific/Engineering :: Physics", 31 | ] 32 | version = "2.4.1" 33 | dependencies = [ 34 | "numpy>=1.23", 35 | "packaging>=21.3", 36 | ] 37 | 38 | [project.optional-dependencies] 39 | tests = [ 40 | "pytest", 41 | "pytest-doctestplus", 42 | "pytest-cov", 43 | "pytest-xdist", 44 | ] 45 | docs = [ 46 | "sphinx", 47 | "sphinx-automodapi", 48 | "sphinx-changelog", 49 | "sunpy-sphinx-theme", 50 | "packaging", 51 | "jupyter-sphinx", 52 | "sphinx-changelog", 53 | ] 54 | 55 | [project.urls] 56 | Homepage = "https://sunpy.org" 57 | "Source Code" = "https://github.com/sunpy/streamtracer" 58 | Download = "https://pypi.org/project/streamtracer" 59 | Documentation = "https://docs.sunpy.org/projects/streamtracer" 60 | Changelog = "https://docs.sunpy.org/projects/streamtracer/en/stable/whatsnew/changelog.html" 61 | "Issue Tracker" = "https://github.com/sunpy/streamtracer/issues" 62 | 63 | [tool.maturin] 64 | python-source = "python" 65 | module-name = "streamtracer._streamtracer_rust" 66 | 67 | [tool.cibuildwheel] 68 | before-build = "rustup show" 69 | environment = {"PATH" = "$PATH:$HOME/.cargo/bin"} 70 | 71 | [tool.cibuildwheel.linux] 72 | before-all = "curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain stable -y" 73 | 74 | [tool.cibuildwheel.macos] 75 | environment = {"MACOSX_DEPLOYMENT_TARGET" = "10.12"} 76 | before-all = "rustup target add aarch64-apple-darwin; rustup target add x86_64-apple-darwin" 77 | 78 | [tool.setuptools_scm] 79 | version_file = "streamtracer/version.py" 80 | 81 | [tool.gilesbot] 82 | [tool.gilesbot.pull_requests] 83 | enabled = true 84 | 85 | [tool.gilesbot.towncrier_changelog] 86 | enabled = true 87 | verify_pr_number = true 88 | changelog_skip_label = "No Changelog Entry Needed" 89 | help_url = "https://github.com/sunpy/streamtracer/blob/main/changelog/README.rst" 90 | 91 | changelog_missing_long = "There isn't a changelog file in this pull request. Please add a changelog file to the `changelog/` directory following the instructions in the changelog [README](https://github.com/sunpy/streamtracer/blob/main/changelog/README.rst)." 92 | 93 | type_incorrect_long = "The changelog file you added is not one of the allowed types. Please use one of the types described in the changelog [README](https://github.com/sunpy/streamtracer/blob/main/changelog/README.rst)" 94 | 95 | number_incorrect_long = "The number in the changelog file you added does not match the number of this pull request. Please rename the file." 96 | 97 | # TODO: This should be in towncrier.toml but Giles currently only works looks in 98 | # pyproject.toml we should move this back when it's fixed. 99 | [tool.towncrier] 100 | package = "streamtracer" 101 | filename = "CHANGELOG.rst" 102 | directory = "changelog/" 103 | issue_format = "`#{issue} `__" 104 | title_format = "{version} ({project_date})" 105 | 106 | [[tool.towncrier.type]] 107 | directory = "breaking" 108 | name = "Breaking Changes" 109 | showcontent = true 110 | 111 | [[tool.towncrier.type]] 112 | directory = "deprecation" 113 | name = "Deprecations" 114 | showcontent = true 115 | 116 | [[tool.towncrier.type]] 117 | directory = "removal" 118 | name = "Removals" 119 | showcontent = true 120 | 121 | [[tool.towncrier.type]] 122 | directory = "feature" 123 | name = "New Features" 124 | showcontent = true 125 | 126 | [[tool.towncrier.type]] 127 | directory = "bugfix" 128 | name = "Bug Fixes" 129 | showcontent = true 130 | 131 | [[tool.towncrier.type]] 132 | directory = "doc" 133 | name = "Documentation" 134 | showcontent = true 135 | 136 | [[tool.towncrier.type]] 137 | directory = "trivial" 138 | name = "Internal Changes" 139 | showcontent = true 140 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | minversion = 7.0 3 | testpaths = 4 | docs 5 | python 6 | norecursedirs = 7 | .tox 8 | build 9 | docs/_build 10 | docs/generated 11 | *.egg-info 12 | examples 13 | streamtracer/_dev 14 | .history 15 | streamtracer/extern 16 | doctest_plus = enabled 17 | doctest_optionflags = 18 | NORMALIZE_WHITESPACE 19 | FLOAT_CMP 20 | ELLIPSIS 21 | text_file_format = rst 22 | addopts = 23 | --doctest-rst 24 | -p no:unraisableexception 25 | -p no:threadexception 26 | filterwarnings = 27 | # Turn all warnings into errors so they do not pass silently. 28 | error 29 | # Do not fail on pytest config issues (i.e. missing plugins) but do show them 30 | always::pytest.PytestConfigWarning 31 | # A list of warnings to ignore follows. If you add to this list, you MUST 32 | # add a comment or ideally a link to an issue that explains why the warning 33 | # is being ignored 34 | -------------------------------------------------------------------------------- /python/streamtracer/__init__.py: -------------------------------------------------------------------------------- 1 | from .streamline import * 2 | from .version import version as __version__ 3 | -------------------------------------------------------------------------------- /python/streamtracer/streamline.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from streamtracer._streamtracer_rust import trace_streamlines 4 | 5 | __all__ = ["StreamTracer", "VectorGrid"] 6 | 7 | 8 | class VectorGrid: 9 | """ 10 | A grid of vectors. 11 | 12 | .. note:: 13 | 14 | If any of *cyclic* are ``True``, then the grid values on each side of the 15 | cyclic dimension **must** match, e.g. if ``cyclic=[False, True, False]``, 16 | ``vectors[:, 0, :, :]`` must equal ``vectors[:, -1, :, :]``. 17 | 18 | Parameters 19 | ---------- 20 | vectors : array-like 21 | A (nx, ny, nz, 3) shaped array. The three values at (i, j, k, :) 22 | specify the (x, y, z) components of the vector at index (i, j, k). 23 | grid_spacing : array-like, optional 24 | A (3,) shaped array, that contains the grid spacings in the (x, y, z) 25 | directions. If not specified ``grid_coords`` must be specified. 26 | origin_coord : [`float`, `float`, `float`], optional 27 | The coordinate of the ``vectors[0, 0, 0, :]`` vector at the corner of 28 | the box. Defaults to ``[0, 0, 0]``. This is not used if ``grid_coords`` 29 | is specified. 30 | cyclic : [`bool`, `bool`, `bool`], optional 31 | Whether to have cyclic boundary conditions in each of the (x, y, z) 32 | directions. Defaults to ``[False, False, False]``. 33 | grid_coords : list[array], optional 34 | A list of length 3 storing the (x, y, z) coordinates of the grid. If not 35 | specified ``grid_spacing`` must be specified. 36 | """ 37 | 38 | def __init__( 39 | self, 40 | vectors, 41 | grid_spacing=None, 42 | origin_coord=None, 43 | cyclic=None, 44 | *, 45 | grid_coords=None, 46 | ): 47 | if grid_spacing is not None and grid_coords is not None: 48 | raise ValueError( 49 | 'Only one of "grid_spacing" and "grid_coords" can be specified.' 50 | ) 51 | if grid_spacing is None and grid_coords is None: 52 | raise ValueError( 53 | 'One of "grid_spacing" and "grid_coords" must be specified.' 54 | ) 55 | if grid_coords is not None and origin_coord is not None: 56 | raise ValueError( 57 | 'Specifying both "grid_coords" and "origin_coord" is ambiguous.' 58 | ) 59 | self.grid_spacing = grid_spacing 60 | self.vectors = vectors 61 | self.cyclic = cyclic 62 | self.coords = grid_coords 63 | self.origin_coord = origin_coord 64 | 65 | @property 66 | def grid_spacing(self): 67 | """ 68 | Physical spacing between grid points along each axis. 69 | """ 70 | return self._grid_spacing 71 | 72 | @grid_spacing.setter 73 | def grid_spacing(self, val): 74 | if val is not None: 75 | val = np.array(val) 76 | if val.shape != (3,): 77 | raise ValueError( 78 | f"grid spacing must have shape (3,), got " f"{val.shape}" 79 | ) 80 | self._grid_spacing = val 81 | 82 | @property 83 | def vectors(self): 84 | """ 85 | Three-dimensional vector field through which the streamlines will be traced. 86 | """ 87 | return self._vectors 88 | 89 | @vectors.setter 90 | def vectors(self, val): 91 | if len(val.shape) != 4: 92 | raise ValueError("vectors must be a 4D array") 93 | if val.shape[-1] != 3: 94 | raise ValueError( 95 | "vectors must have shape (nx, ny, nz, 3), " f"got {val.shape}" 96 | ) 97 | self._vectors = val 98 | 99 | @property 100 | def coords(self): 101 | """ 102 | The physical coordinates along each axis of the grid. 103 | """ 104 | return self._coords 105 | 106 | @coords.setter 107 | def coords(self, val): 108 | if val is not None: 109 | if len(val) != 3: 110 | raise ValueError("coords must be len(3)") 111 | for i, dim in zip(range(3), ["x", "y", "z"]): 112 | shape = np.array(val[i]).shape 113 | if shape != (self.vectors.shape[i],): 114 | raise ValueError( 115 | f"Expected {self.vectors.shape[i]} {dim} " 116 | f"coordinates but got {shape}" 117 | ) 118 | self._coords = val 119 | 120 | @property 121 | def cyclic(self): 122 | """ 123 | Boolean describing whether to have cyclic boundary conditions in each of the (x, y, z) 124 | directions. 125 | """ 126 | return self._cyclic 127 | 128 | @cyclic.setter 129 | def cyclic(self, val): 130 | if val is None: 131 | val = [False, False, False] 132 | dims = {0: "x", 1: "y", 2: "z"} 133 | s = [slice(None)] * 4 134 | for i, c in enumerate(val): 135 | if c: 136 | slc = s.copy() 137 | slc[i] = slice(0, 1) 138 | side1 = self.vectors[tuple(slc)] 139 | slc[i] = slice(-1, None) 140 | side2 = self.vectors[tuple(slc)] 141 | 142 | np.testing.assert_equal( 143 | side1, 144 | side2, 145 | err_msg=f"grid values in dimension {dims[i]} (size {self.vectors.shape[i]}) " 146 | "do not match on each side of the cube", 147 | ) 148 | self._cyclic = np.array(val, dtype=bool) 149 | 150 | @property 151 | def origin_coord(self): 152 | """ 153 | The physical coordinate corresponding to the index at ``(0,0,0)``. 154 | """ 155 | return self._origin_coord 156 | 157 | @origin_coord.setter 158 | def origin_coord(self, val): 159 | if val is None: 160 | if self.grid_spacing is not None: 161 | self._origin_coord = np.array([0, 0, 0]) 162 | else: 163 | self._origin_coord = np.array( 164 | [self.xcoords[0], self.ycoords[0], self.zcoords[0]] 165 | ) 166 | else: 167 | self._origin_coord = np.array(val) 168 | 169 | def _get_coords(self, i): 170 | if self.grid_spacing is not None: 171 | return ( 172 | self.grid_spacing[i] * np.arange(self.vectors.shape[i]) 173 | + self.origin_coord[i] 174 | ) 175 | return self.coords[i] 176 | 177 | @property 178 | def xcoords(self): 179 | """ 180 | Physical coordinates corresponding to grid points in the x-direction. 181 | """ 182 | return self._get_coords(0) 183 | 184 | @property 185 | def ycoords(self): 186 | """ 187 | Physical coordinates corresponding to grid points in the y-direction. 188 | """ 189 | return self._get_coords(1) 190 | 191 | @property 192 | def zcoords(self): 193 | """ 194 | Physical coordinates corresponding to grid points in the z-direction. 195 | """ 196 | return self._get_coords(2) 197 | 198 | 199 | class StreamTracer: 200 | """ 201 | A streamline tracing class. 202 | 203 | Parameters 204 | ---------- 205 | max_steps : `int` 206 | Number of steps available for each line. The maximum number of points 207 | on a single stream line is ``max_steps``. 208 | step_size : `float` 209 | Step size as a the fraction of cell size. 210 | """ 211 | 212 | def __init__(self, max_steps, step_size): 213 | self.max_steps = max_steps 214 | self.ds = step_size 215 | self.xs = None 216 | 217 | @property 218 | def xs(self): 219 | """ 220 | List of the coordinates along each streamline. 221 | 222 | List of three-dimensional coordinates for each streamline. 223 | Each strealine coordinate has a shape ``(n,3)``, where ``n`` can, in principle, vary 224 | from one streamline to the next. 225 | """ 226 | return self._xs 227 | 228 | @xs.setter 229 | def xs(self, val): 230 | self._xs = val 231 | 232 | @property 233 | def ROT(self): 234 | """ 235 | Reason(s) of termination. 236 | 237 | Integer array with shape ``len(xs)`` if traced in one direction, 238 | or ``(len(xs), 2)`` if traced in both directions. 239 | Can take the following values: 240 | 241 | - -1: Encountered a NaN 242 | - 1: Reached maximum available steps 243 | - 2: Out of bounds 244 | """ 245 | return self._ROT 246 | 247 | @ROT.setter 248 | def ROT(self, val): 249 | self._ROT = val 250 | 251 | @property 252 | def max_steps(self): 253 | """ 254 | Number of steps available for each line. 255 | 256 | The maximum number of points on a single stream line is ``max_steps``. 257 | """ 258 | return self._max_steps 259 | 260 | @max_steps.setter 261 | def max_steps(self, val): 262 | if not isinstance(val, int): 263 | raise ValueError(f"max_steps must be an integer (got {type(val)})") 264 | 265 | if not val > 0: 266 | raise ValueError("max_steps must be greater than zero " f"(got {val})") 267 | 268 | self._max_steps = val 269 | 270 | def trace(self, seeds, grid, direction=0): 271 | """ 272 | Trace streamlines. 273 | 274 | This traces streamlines from a series of seeds, through a vector 275 | field. 276 | 277 | Parameters 278 | ---------- 279 | seeds : array-like with shape ``(n, 3)`` 280 | Seed points. 281 | grid : `VectorGrid` 282 | Grid of field vectors. 283 | direction : `int`, optional 284 | Integration direction. ``0`` for both directions, ``1`` for 285 | forward, or ``-1`` for backwards. 286 | """ 287 | if not isinstance(grid, VectorGrid): 288 | raise ValueError("grid must be an instance of StreamTracer") 289 | self.grid = grid 290 | self.x0 = seeds.copy() 291 | self.n_lines = seeds.shape[0] 292 | 293 | field = grid.vectors 294 | 295 | cyclic = grid.cyclic 296 | seeds = np.atleast_2d(seeds) 297 | 298 | # Validate shapes 299 | if len(seeds.shape) != 2: 300 | raise ValueError("seeds must be a 2D array") 301 | if seeds.shape[1] != 3: 302 | raise ValueError(f"seeds must have shape (n, 3), got {seeds.shape}") 303 | 304 | seeds = (seeds - grid.origin_coord).astype(np.float64) 305 | xcoords = (grid.xcoords - grid.origin_coord[0]).astype(np.float64) 306 | ycoords = (grid.ycoords - grid.origin_coord[1]).astype(np.float64) 307 | zcoords = (grid.zcoords - grid.origin_coord[2]).astype(np.float64) 308 | 309 | if direction == 1 or direction == -1: 310 | # Calculate streamlines 311 | self.xs, self.ns, self.ROT = trace_streamlines( 312 | seeds, 313 | xcoords, 314 | ycoords, 315 | zcoords, 316 | field, 317 | cyclic, 318 | direction, 319 | self.ds, 320 | self.max_steps, 321 | ) 322 | 323 | self.xs += grid.origin_coord 324 | # Reduce the size of the arrays 325 | self.xs = [xi[:ni, :] for xi, ni in zip(self.xs, self.ns)] 326 | 327 | elif direction == 0: 328 | # Calculate forward streamline 329 | xs_f, ns_f, ROT_f = trace_streamlines( 330 | seeds, 331 | xcoords, 332 | ycoords, 333 | zcoords, 334 | field, 335 | cyclic, 336 | 1, 337 | self.ds, 338 | self.max_steps, 339 | ) 340 | # Calculate backward streamline 341 | xs_r, ns_r, ROT_r = trace_streamlines( 342 | seeds, 343 | xcoords, 344 | ycoords, 345 | zcoords, 346 | field, 347 | cyclic, 348 | -1, 349 | self.ds, 350 | self.max_steps, 351 | ) 352 | 353 | xs_f += grid.origin_coord 354 | xs_r += grid.origin_coord 355 | 356 | # Stack the forward and reverse arrays 357 | self.xs = [ 358 | np.vstack([xri[int(nr) - 1 : 0 : -1, :], xfi[: int(nf)]]) 359 | for xri, xfi, nr, nf in zip(xs_r, xs_f, ns_r, ns_f) 360 | ] 361 | self.n_lines = np.fromiter([len(xsi) for xsi in self.xs], int) 362 | 363 | self.ROT = np.vstack([ROT_f, ROT_r]).T 364 | else: 365 | raise ValueError(f"Direction must be -1, 1 or 0 (got {direction})") 366 | 367 | # Filter out nans 368 | self.xs = [xi[~np.any(np.isnan(xi), axis=1), :] for xi in self.xs] 369 | -------------------------------------------------------------------------------- /python/streamtracer/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunpy/streamtracer/3463da16019af25f9e7f51463a6ac7395fb9ab41/python/streamtracer/tests/__init__.py -------------------------------------------------------------------------------- /python/streamtracer/tests/test_streamline.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pytest 3 | 4 | from streamtracer import StreamTracer, VectorGrid 5 | 6 | 7 | @pytest.fixture 8 | def tracer(): 9 | return StreamTracer(2000, 0.1) 10 | 11 | 12 | @pytest.fixture 13 | def uniform_x_field(): 14 | # A uniform field pointing in the x direction 15 | v = np.zeros((101, 101, 101, 3)) 16 | # Make all vectors point in the x-direction 17 | v[:, :, :, 0] = 1 18 | spacing = [1, 1, 1] 19 | return VectorGrid(v, spacing) 20 | 21 | 22 | @pytest.mark.parametrize( 23 | ("direction", "ROTs"), 24 | [ 25 | (1, np.array([2, 2, 2])), 26 | (-1, np.array([2, 2, 2])), 27 | (0, np.array([[2, 2], [2, 2], [2, 2]])), 28 | ], 29 | ) 30 | def test_rot(tracer, uniform_x_field, direction, ROTs): 31 | seeds = np.array([[50, 50, 50], [50, 50, 50], [50, 50, 50]]) 32 | tracer.trace(seeds, uniform_x_field, direction=direction) 33 | np.testing.assert_equal(tracer.ROT, ROTs) 34 | 35 | 36 | @pytest.mark.parametrize("x0", [0, 50]) 37 | def test_different_seeds(tracer, uniform_x_field, x0): 38 | # Check that different seed points give sensible results 39 | seed = np.array([0, x0, x0]) 40 | tracer.trace(seed, uniform_x_field) 41 | 42 | sline = tracer.xs[0] 43 | # Check that y, z coordinates are all zero 44 | np.testing.assert_equal(sline[:, 1], x0) 45 | np.testing.assert_equal(sline[:, 2], x0) 46 | 47 | 48 | @pytest.mark.parametrize("vec_len", [1, 2]) 49 | def test_uniform_field(tracer, uniform_x_field, vec_len): 50 | # Check that tracing thought a uniform field gives sensible results 51 | seed = np.array([0, 0, 0]) 52 | uniform_x_field.vectors *= vec_len 53 | tracer.trace(seed, uniform_x_field) 54 | assert isinstance(tracer.xs[0], np.ndarray) 55 | assert len(tracer.xs) == len(tracer.ROT) 56 | 57 | sline = tracer.xs[0] 58 | # Check that y, z coordinates are all zero 59 | np.testing.assert_almost_equal(sline[:, 0], np.linspace(0, 100, 1001)) 60 | np.testing.assert_equal(sline[:, 1], 0) 61 | np.testing.assert_equal(sline[:, 2], 0) 62 | 63 | # Check that streamline always goes in a positive direction 64 | assert np.all(np.diff(sline[:, 0]) > 0) 65 | # Check that there are 100 * 0.1 = 1000 steps in the streamline 66 | assert sline.shape[0] == 1001 67 | 68 | 69 | def test_trace_direction(tracer, uniform_x_field): 70 | # Check that the direction keyword argument works 71 | seed = np.array([0, 0, 0]) 72 | tracer.trace(seed, uniform_x_field, direction=1) 73 | sline = tracer.xs[0] 74 | assert np.all(sline[:, 0] >= 0) 75 | 76 | tracer.trace(seed, uniform_x_field, direction=-1) 77 | sline = tracer.xs[0] 78 | 79 | assert np.all(sline[:, 0] <= 0) 80 | 81 | 82 | def test_cyclic(uniform_x_field): 83 | # Check the cyclic option 84 | maxsteps = 4 85 | tracer = StreamTracer(maxsteps, 0.1) 86 | seed = np.array([99.95, 50, 50]) 87 | 88 | uniform_x_field.cyclic = [True, False, False] 89 | tracer.trace(seed, uniform_x_field, direction=1) 90 | fline = tracer.xs[0] 91 | # Check that the tracer uses all the steps available 92 | assert len(fline) == maxsteps 93 | assert tracer.max_steps == maxsteps 94 | # Check that the cyclic boundary works properly 95 | np.testing.assert_equal(fline[0, :], seed) 96 | np.testing.assert_almost_equal(fline[1, :], np.array([0.05, 50, 50])) 97 | np.testing.assert_almost_equal(fline[2, :], np.array([0.15, 50, 50])) 98 | 99 | # Check that going the other way across the boundary (through zero) works 100 | seed = np.array([0.1, 50, 50]) 101 | tracer.trace(seed, uniform_x_field, direction=-1) 102 | fline = tracer.xs[0] 103 | np.testing.assert_equal(fline[0, :], seed) 104 | np.testing.assert_almost_equal(fline[1, :], np.array([0, 50, 50])) 105 | np.testing.assert_almost_equal(fline[2, :], np.array([99.9, 50, 50])) 106 | 107 | # Check that turning cyclic off interrupts the tracing 108 | uniform_x_field.cyclic = [False, False, False] 109 | # Going forwards 110 | seed = np.array([99.9, 50, 50]) 111 | tracer.trace(seed, uniform_x_field, direction=1) 112 | assert len(tracer.xs[0]) == 2 113 | 114 | # Going backwards 115 | seed = np.array([0.1, 50, 50]) 116 | tracer.trace(seed, uniform_x_field, direction=-1) 117 | assert len(tracer.xs[0]) == 2 118 | 119 | 120 | @pytest.mark.parametrize("ds", [0.1, 0.2]) 121 | @pytest.mark.parametrize("origin_coord", [[0, 0, 0], [1, 1, 1]]) 122 | def test_origin(tracer, origin_coord, ds): 123 | # A uniform field pointing in the x direction 124 | v = np.zeros((4, 4, 4, 3)) 125 | # Make all vectors point in the x-direction 126 | v[:, :, :, 0] = 1 127 | spacing = [1, 1, 1] 128 | grid = VectorGrid(v, spacing, origin_coord=origin_coord) 129 | 130 | seed = np.array([2.0, 2.0, 2.0]) 131 | tracer = StreamTracer(100, ds) 132 | tracer.trace(seed, grid, direction=1) 133 | 134 | fline = tracer.xs[0] 135 | # Check first field line coordinate is the seed 136 | np.testing.assert_equal(fline[0, :], seed) 137 | # Should stop before the edge of the box 138 | end_coord = seed 139 | end_coord[0] = grid.xcoords[-1] - ds 140 | np.testing.assert_almost_equal(fline[-1, :], end_coord) 141 | 142 | 143 | def test_cyclic_field(): 144 | # A uniform field pointing in the x direction 145 | v = np.zeros((100, 100, 100, 3)) 146 | # Make all vectors point in the x-direction 147 | v[:, :, :, 0] = 1 148 | # Mismatch vectors on the x-faces 149 | v[0, :, :, 0] = -1 150 | 151 | spacing = [1, 1, 1] 152 | cyclic = [True, False, False] 153 | with pytest.raises(AssertionError, match="Arrays are not equal"): 154 | VectorGrid(v, spacing, cyclic=cyclic) 155 | 156 | # Check that with cyclic off no error is thrown 157 | cyclic = [False, False, False] 158 | VectorGrid(v, spacing, cyclic=cyclic) 159 | 160 | 161 | def test_grid_points(): 162 | # A uniform field pointing in the x direction 163 | v = np.zeros((100, 100, 100, 3)) 164 | # Make all vectors point in the x-direction 165 | spacing = [2, 3, 4] 166 | origin_coord = [4, 9, 16] 167 | grid = VectorGrid(v, spacing, origin_coord=origin_coord) 168 | assert grid.xcoords[0] == 4 169 | assert grid.xcoords[1] == 6 170 | assert grid.xcoords[-1] == 4 + 99 * 2 171 | 172 | assert grid.ycoords[0] == 9 173 | assert grid.ycoords[1] == 12 174 | assert grid.ycoords[-1] == 9 + 99 * 3 175 | 176 | assert grid.zcoords[0] == 16 177 | assert grid.zcoords[1] == 20 178 | assert grid.zcoords[-1] == 16 + 99 * 4 179 | 180 | 181 | def test_bad_input(tracer, uniform_x_field): 182 | # Check input validation 183 | seed = np.array([0, 0, 0]) 184 | with pytest.raises(ValueError, match="seeds must be a 2D array"): 185 | tracer.trace(np.array([[[1], [1]], [[1], [1]]]), uniform_x_field) 186 | 187 | with pytest.raises(ValueError, match="seeds must have shape"): 188 | tracer.trace(np.array([1, 1]), uniform_x_field) 189 | 190 | with pytest.raises(ValueError, match="grid must be an instance of StreamTracer"): 191 | tracer.trace(seed, 1) 192 | 193 | with pytest.raises(ValueError, match="Direction must be -1, 1 or 0"): 194 | tracer.trace(seed, uniform_x_field, direction=2) 195 | 196 | with pytest.raises(ValueError, match="vectors must be a 4D array"): 197 | VectorGrid(np.array([1]), [1, 1, 1]) 198 | 199 | with pytest.raises(ValueError, match="vectors must have shape"): 200 | VectorGrid(np.zeros((1, 1, 1, 2)), [1, 1, 1]) 201 | 202 | with pytest.raises(ValueError, match="grid spacing must have shape"): 203 | VectorGrid(np.zeros((1, 1, 1, 3)), [1, 1]) 204 | 205 | 206 | @pytest.mark.parametrize( 207 | ("val", "errstr"), 208 | [ 209 | (0.1, "max_steps must be an integer"), 210 | (0, "max_steps must be greater than zero"), 211 | (-1, "max_steps must be greater than zero"), 212 | ], 213 | ) 214 | def test_invalid_max_steps(val, errstr): 215 | with pytest.raises(ValueError, match=errstr): 216 | StreamTracer(val, 0.1) 217 | 218 | 219 | # Paramatrize to make sure behaviour is same in x,y,z directions 220 | @pytest.mark.parametrize("dirs", [0, 1, 2]) 221 | def test_bounds(dirs): 222 | v = np.zeros((3, 3, 3, 3)) 223 | # Make all vectors point along the specified dimension 224 | v[:, :, :, dirs] = 1 225 | spacing = [1, 1, 1] 226 | grid = VectorGrid(v, spacing) 227 | 228 | seed = np.array([[0.5, 0.5, 0.5]]) 229 | tracer = StreamTracer(max_steps=10, step_size=1.0) 230 | tracer.trace(seed, grid) 231 | expected = np.roll(np.array([1.5, 0.5, 0.5]), dirs) 232 | assert (tracer.xs[0][-1, :] == expected).all() 233 | expected = np.array([0.5, 0.5, 0.5]) 234 | assert (tracer.xs[0][0, :] == expected).all() 235 | 236 | 237 | def test_direction_change(): 238 | # Test custom (non-uniform) grid coordinates 239 | # A uniform field pointing in the x direction 240 | v = np.zeros((4, 4, 4, 3)) 241 | # Make first layer of vectors point in x-direction 242 | v[0:2, :, :, 0] = 1 243 | # After that layer, make vectors point in y-direction 244 | v[2:4, :, :, 1] = 1 245 | grid = VectorGrid(v, grid_spacing=[1, 1, 1]) 246 | 247 | seed = np.array([0, 0, 0]) 248 | step_size = 0.1 249 | tracer = StreamTracer(100, step_size) 250 | tracer.trace(seed, grid) 251 | 252 | sline = tracer.xs[0] 253 | # Check that initial steps are in x-direction 254 | # Check diff in y/z directions is zero 255 | assert np.allclose(np.diff(sline[0:10, 1:2]), 0) 256 | # Check there's a diff in x direction 257 | assert np.allclose(np.diff(sline[0:10, 0]), 0.1) 258 | 259 | # Check that field line changes direction 260 | assert sline[0, 1] == 0 261 | # Check that fline leaves box in y-direction 262 | assert sline[-1, 1] > 3 - step_size 263 | assert 0 < sline[-1, 0] < 3 264 | 265 | 266 | def test_coords(): 267 | # Test custom (non-uniform) grid coordinates 268 | # A uniform field pointing in the x direction 269 | v = np.zeros((4, 4, 4, 3)) 270 | # Make all vectors point diagonally from one corner to the other 271 | v[:, :, :, :] = 1 272 | xcoords = [0, 1, 2, 10] 273 | ycoords = [0, 3, 6, 10] 274 | zcoords = [0, 8, 9, 10] 275 | grid = VectorGrid(v, grid_coords=[xcoords, ycoords, zcoords]) 276 | 277 | seed = np.array([0, 0, 0]) 278 | tracer = StreamTracer(100, 1) 279 | tracer.trace(seed, grid) 280 | 281 | # Check that step sizes are all 1 282 | sline = tracer.xs[0] 283 | ds = np.diff(np.linalg.norm(sline, axis=1)) 284 | np.testing.assert_equal(ds[0], 1) 285 | np.testing.assert_almost_equal(ds[1:], 1) 286 | 287 | # Check that first/last steps are outside box 288 | assert np.all(sline[0] < 0 + tracer.ds) 289 | assert np.all(sline[-1] > 10 - tracer.ds) 290 | -------------------------------------------------------------------------------- /python/streamtracer/version.py: -------------------------------------------------------------------------------- 1 | import importlib.metadata as _meta 2 | 3 | from packaging.version import parse as _parse 4 | 5 | version = _meta.version("streamtracer") 6 | _version = _parse(version) 7 | major, minor, bugfix = [*_version.release, 0][:3] 8 | release = not _version.is_devrelease 9 | -------------------------------------------------------------------------------- /src/field.rs: -------------------------------------------------------------------------------- 1 | //! Structure for representing a 3D vector field defined on the corners 2 | //! of a rectilinear grid. 3 | use numpy::ndarray::{array, s, Array1, ArrayView1, ArrayView4}; 4 | 5 | use crate::interp::interp_trilinear; 6 | 7 | /// Enum denoting whether a point is in or out of the bounds 8 | /// of a VectorField grid. 9 | pub enum Bounds { 10 | /// A position vector is in bounds. 11 | In, 12 | /// A position vector is out of bounds. 13 | Out, 14 | } 15 | 16 | /// A 3D vector field defined at grid corners. 17 | pub struct VectorField<'a> { 18 | /// Grid points along x dimension. Must start at 0. 19 | pub xgrid: ArrayView1<'a, f64>, 20 | /// Grid points along y dimension. Must start at 0. 21 | pub ygrid: ArrayView1<'a, f64>, 22 | /// Grid points along z dimension. Must start at 0. 23 | pub zgrid: ArrayView1<'a, f64>, 24 | /// Vector values at each grid point. Must be shape 25 | /// (nx, ny, ny, 3), where (nx, ny, nz) are the number 26 | /// of coordinates along dimension. 27 | pub values: ArrayView4<'a, f64>, 28 | /// Whether each dimension should be treated as cyclic 29 | /// or not. Must be shape (3,). 30 | cyclic: ArrayView1<'a, bool>, 31 | /// Number of x coordinates. 32 | nx: usize, 33 | /// Number of y coordinates. 34 | ny: usize, 35 | /// Number of z coordinates. 36 | nz: usize, 37 | 38 | /// Upper boundaries 39 | upper_bounds: Array1, 40 | } 41 | 42 | impl VectorField<'_> { 43 | /// Create a new VectorField, checking for appropriate array shapes. 44 | pub fn new<'a>( 45 | xgrid: ArrayView1<'a, f64>, 46 | ygrid: ArrayView1<'a, f64>, 47 | zgrid: ArrayView1<'a, f64>, 48 | values: ArrayView4<'a, f64>, 49 | cyclic: ArrayView1<'a, bool>, 50 | ) -> VectorField<'a> { 51 | // Do some shape checking 52 | let nx = xgrid.len(); 53 | let ny = ygrid.len(); 54 | let nz = zgrid.len(); 55 | let field_shape = values.shape(); 56 | 57 | assert_eq!(field_shape[0], nx); 58 | assert_eq!(field_shape[1], ny); 59 | assert_eq!(field_shape[2], nz); 60 | assert_eq!(field_shape[3], 3); 61 | 62 | assert_eq!(cyclic.shape()[0], 3); 63 | 64 | // Check first coordinates are zero. 65 | assert_eq!(xgrid[0], 0.); 66 | assert_eq!(ygrid[0], 0.); 67 | assert_eq!(zgrid[0], 0.); 68 | 69 | let upper_bounds = array![xgrid[nx - 1], ygrid[ny - 1], zgrid[nz - 1]]; 70 | 71 | return VectorField { 72 | xgrid, 73 | ygrid, 74 | zgrid, 75 | values, 76 | cyclic, 77 | nx, 78 | ny, 79 | nz, 80 | upper_bounds, 81 | }; 82 | } 83 | 84 | /// Return grid index of the cell containing `x`. 85 | pub fn grid_idx(&self, x: ArrayView1) -> Array1 { 86 | // Output array 87 | let mut grid_idx = array![self.nx - 2, self.ny - 2, self.nz - 2]; 88 | 89 | // x 90 | for i in 0..self.nx - 1 { 91 | if x[0] >= self.xgrid[[i]] && x[0] < self.xgrid[[i + 1]] { 92 | grid_idx[0] = i; 93 | break; 94 | } 95 | } 96 | // y 97 | for i in 0..self.ny - 1 { 98 | if x[1] >= self.ygrid[[i]] && x[1] < self.ygrid[[i + 1]] { 99 | grid_idx[1] = i; 100 | break; 101 | } 102 | } 103 | // z 104 | for i in 0..self.nz - 1 { 105 | if x[2] >= self.zgrid[[i]] && x[2] < self.zgrid[[i + 1]] { 106 | grid_idx[2] = i; 107 | break; 108 | } 109 | } 110 | 111 | return grid_idx; 112 | } 113 | 114 | /// Get vector at position `x` using tri-linear interpolation. 115 | pub fn vector_at_position(&self, x0: ArrayView1) -> Array1 { 116 | let cell_idx = self.grid_idx(x0); 117 | let cell_origin = array![ 118 | self.xgrid[cell_idx[0]], 119 | self.ygrid[cell_idx[1]], 120 | self.zgrid[cell_idx[2]] 121 | ]; 122 | let cell_size = array![ 123 | self.xgrid[cell_idx[0] + 1] - cell_origin[0], 124 | self.ygrid[cell_idx[1] + 1] - cell_origin[1], 125 | self.zgrid[cell_idx[2] + 1] - cell_origin[2] 126 | ]; 127 | 128 | // Distance along each cell edge in normalised units 129 | let cell_dist: Array1 = (x0.to_owned() - cell_origin) / cell_size; 130 | 131 | // Eight corners of the cube that the position vector is 132 | // currently in 133 | let vec_cube = self.values.slice(s![ 134 | cell_idx[0]..(cell_idx[0] + 2), 135 | cell_idx[1]..(cell_idx[1] + 2), 136 | cell_idx[2]..(cell_idx[2] + 2), 137 | .. 138 | ]); 139 | 140 | let mut vector_at_pos = array![0., 0., 0.]; 141 | // Loop over vector components 142 | for i in 0..3 { 143 | vector_at_pos[[i]] = interp_trilinear(&vec_cube.slice(s![.., .., .., i]), &cell_dist); 144 | } 145 | return vector_at_pos; 146 | } 147 | 148 | /// If any of the dimensions of the grid are cyclic, wrap a coordinate. 149 | pub fn wrap_cyclic(&self, mut x: Array1) -> Array1 { 150 | if self.cyclic[0] { 151 | x[0] = (x[0] + self.xgrid[self.nx - 1]) % self.upper_bounds[0]; 152 | } 153 | if self.cyclic[1] { 154 | x[1] = (x[1] + self.ygrid[self.ny - 1]) % self.upper_bounds[1]; 155 | } 156 | if self.cyclic[2] { 157 | x[2] = (x[2] + self.zgrid[self.nz - 1]) % self.upper_bounds[2]; 158 | } 159 | 160 | return x; 161 | } 162 | 163 | /// Check whether a coordinate is in bounds of the grid. 164 | pub fn check_bounds(&self, x: ArrayView1) -> Bounds { 165 | if (x[0] < self.xgrid[0]) 166 | || (x[0] > self.xgrid[self.nx - 1]) 167 | || (x[1] < self.ygrid[0]) 168 | || (x[1] > self.ygrid[self.ny - 1]) 169 | || (x[2] < self.zgrid[0]) 170 | || (x[2] > self.zgrid[self.nz - 1]) 171 | { 172 | return Bounds::Out; 173 | } 174 | return Bounds::In; 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/interp.rs: -------------------------------------------------------------------------------- 1 | //! Helper functions for interpolation. 2 | 3 | use numpy::ndarray::{Array1, ArrayBase, Data, Ix3}; 4 | 5 | /// Trilinear-interpolation of a scalar defined on 6 | /// the eight corners of a cuboid. 7 | /// 8 | /// # Arguments 9 | /// 10 | /// * `values` - Values on the eight cube corners. Must be shape `(2, 2, 2)`. 11 | /// * `x` - Coordinate to interpolate at. Components must be `>= 0` and `<=1`. Must be shape `(3,)`. 12 | pub fn interp_trilinear(values: &ArrayBase, x: &Array1) -> f64 13 | where 14 | S: Data, 15 | { 16 | if values.dim() != (2, 2, 2) { 17 | panic!("Interp values are not the right shape {:?}", values.shape()); 18 | } 19 | let m_x = 1. - x; 20 | 21 | let mut c: [f64; 4] = [0.0; 4]; 22 | // Interpolate over x 23 | for iy in 0..2 { 24 | for iz in 0..2 { 25 | let iix = (2 * iy) + iz; 26 | c[iix] = values[[0, iy, iz]] * m_x[[0]] + values[[1, iy, iz]] * x[[0]]; 27 | } 28 | } 29 | 30 | // Interpolate over y 31 | let mut c1: [f64; 2] = [0.0; 2]; 32 | for iz in 0..2 { 33 | c1[iz] = c[iz] * m_x[[1]] + c[iz + 2] * x[[1]]; 34 | } 35 | 36 | // Interpolate over z 37 | return c1[0] * m_x[[2]] + c1[1] * x[[2]]; 38 | } 39 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate contains code for tracing streamlines through a 3D vector field defined 2 | //! on rectilinear grids. 3 | #![warn(missing_docs)] 4 | pub mod field; 5 | pub mod interp; 6 | pub mod trace; 7 | 8 | #[cfg(test)] 9 | mod test_field; 10 | mod test_interp; 11 | mod test_tracer; 12 | 13 | use numpy::{ 14 | ndarray::Array, IntoPyArray, PyArray1, PyArray3, PyReadonlyArray1, PyReadonlyArray2, 15 | PyReadonlyArray4, 16 | }; 17 | use pyo3::prelude::{pymodule, Bound, PyModule, PyResult, Python}; 18 | 19 | #[pymodule] 20 | #[pyo3(name = "_streamtracer_rust")] 21 | fn streamtracer(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> { 22 | #[pyfn(m)] 23 | #[allow(clippy::too_many_arguments)] 24 | #[allow(clippy::type_complexity)] 25 | fn trace_streamlines<'py>( 26 | py: Python<'py>, 27 | seeds: PyReadonlyArray2, 28 | xgrid: PyReadonlyArray1, 29 | ygrid: PyReadonlyArray1, 30 | zgrid: PyReadonlyArray1, 31 | values: PyReadonlyArray4, 32 | cyclic: PyReadonlyArray1, 33 | direction: i32, 34 | step_size: f64, 35 | max_steps: usize, 36 | ) -> ( 37 | Bound<'py, PyArray3>, 38 | Bound<'py, PyArray1>, 39 | Bound<'py, PyArray1>, 40 | ) { 41 | let (statuses, xs) = trace::trace_streamlines( 42 | seeds.as_array(), 43 | xgrid.as_array(), 44 | ygrid.as_array(), 45 | zgrid.as_array(), 46 | values.as_array(), 47 | cyclic.as_array(), 48 | direction, 49 | step_size, 50 | max_steps, 51 | ); 52 | 53 | let mut termination_reasons = Array::zeros(statuses.len()); 54 | let mut n_points = Array::zeros(statuses.len()); 55 | for (i, status) in statuses.iter().enumerate() { 56 | termination_reasons[[i]] = status.rot as i64; 57 | n_points[[i]] = status.n_points as i64; 58 | } 59 | 60 | return ( 61 | xs.into_pyarray(py), 62 | n_points.into_pyarray(py), 63 | termination_reasons.into_pyarray(py), 64 | ); 65 | } 66 | 67 | return Ok(()); 68 | } 69 | -------------------------------------------------------------------------------- /src/test_field.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod field_tests { 3 | use float_eq::assert_float_eq; 4 | use numpy::ndarray::{array, s, Array, Array4}; 5 | 6 | use super::super::field::VectorField; 7 | 8 | #[test] 9 | fn test_grid_idx() { 10 | let xgrid = array![0., 0.2, 0.3]; 11 | let ygrid = array![0., 1.1, 1.2, 1.3]; 12 | let zgrid = array![0.0, 1.0, 50.0, 56.0, 100.0]; 13 | let mut field: Array4 = Array::zeros((3, 4, 5, 3)); 14 | field.slice_mut(s![2, 2.., 2.., 0]).fill(1.); 15 | let cyclic = array![true, false, true]; 16 | let f = VectorField::new( 17 | xgrid.view(), 18 | ygrid.view(), 19 | zgrid.view(), 20 | field.view(), 21 | cyclic.view(), 22 | ); 23 | 24 | let x = array![0.15, 1.05, 0.05]; 25 | assert_eq!(f.grid_idx(x.view()), array![0, 0, 0]); 26 | 27 | let x = array![0.25, 1.05, 0.05]; 28 | assert_eq!(f.grid_idx(x.view()), array![1, 0, 0]); 29 | 30 | let x = array![0.25, 1.15, 53.0]; 31 | assert_eq!(f.grid_idx(x.view()), array![1, 1, 2]); 32 | } 33 | 34 | #[test] 35 | fn test_vector_at_position() { 36 | let xgrid = array![0., 0.2, 0.3]; 37 | let ygrid = array![0., 1.1, 1.2, 1.3]; 38 | let zgrid = array![0.0, 1.0, 50.0, 56.0, 100.0]; 39 | let mut field: Array4 = Array::zeros((3, 4, 5, 3)); 40 | field.slice_mut(s![2, 2.., 2.., 0]).fill(1.); 41 | let cyclic = array![true, false, true]; 42 | let f = VectorField::new( 43 | xgrid.view(), 44 | ygrid.view(), 45 | zgrid.view(), 46 | field.view(), 47 | cyclic.view(), 48 | ); 49 | 50 | let mut x = array![0.15, 1.05, 0.05]; 51 | 52 | assert_eq!(f.vector_at_position(x.view()), array![0., 0., 0.]); 53 | 54 | // Exactly on a grid boundary in {y, z}, halfway along in {x} 55 | x = array![0.25, 1.2, 50.0]; 56 | assert_eq!(f.vector_at_position(x.view()), array![0.5, 0., 0.]); 57 | 58 | // Exactly on a grid boundary in {y, z}, 3/4 along in {x} 59 | x = array![0.275, 1.2, 50.0]; 60 | let vec = f.vector_at_position(x.view()); 61 | let expected = array![0.75, 0., 0.]; 62 | for i in 0..2 { 63 | assert_float_eq!(vec[i], expected[i], abs <= 0.000_000_1); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/test_interp.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod interp_tests { 3 | use super::super::interp; 4 | use numpy::ndarray::array; 5 | 6 | #[test] 7 | fn test_interp_trilin() { 8 | let values = array![[[0., 1.], [0., 1.]], [[0., 1.], [0., 1.]]]; 9 | let a = array![0.3, 0.2, 0.4]; 10 | let b = interp::interp_trilinear(&values, &a); 11 | assert_eq!(b, 0.4); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/test_tracer.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod tests { 3 | use numpy::ndarray::{array, s, Array}; 4 | 5 | use super::super::field::VectorField; 6 | use super::super::trace::{trace_streamline, TracerStatus}; 7 | 8 | #[test] 9 | fn test_uniform_field() { 10 | let xgrid = Array::range(0., 10.1, 0.5); 11 | let ygrid = Array::range(0., 10.1, 0.5); 12 | let zgrid = Array::range(0., 10.1, 0.5); 13 | // Create a vector field pointing in the x direction 14 | let mut field = Array::zeros((xgrid.len(), ygrid.len(), zgrid.len(), 3)); 15 | field.slice_mut(s![.., .., .., 0]).fill(1.); 16 | 17 | let cyclic = array![false, false, false]; 18 | let f = VectorField::new( 19 | xgrid.view(), 20 | ygrid.view(), 21 | zgrid.view(), 22 | field.view(), 23 | cyclic.view(), 24 | ); 25 | 26 | let seed = array![5., 5., 5.]; 27 | let direction = 1; 28 | let step_size = 0.1; 29 | 30 | // Should take 50 steps before going out of bounds 31 | let max_steps = 100; 32 | let result = trace_streamline(seed.view(), &f, &direction, &step_size, max_steps); 33 | assert_eq![result.status.n_points, 51]; 34 | assert_eq![result.status.rot, TracerStatus::OutOfBounds]; 35 | 36 | let max_steps = 10; 37 | let result = trace_streamline(seed.view(), &f, &direction, &step_size, max_steps); 38 | assert_eq![result.status.n_points, max_steps]; 39 | assert_eq![result.status.rot, TracerStatus::RanOutOfSteps]; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/trace.rs: -------------------------------------------------------------------------------- 1 | //! Streamline tracing functionality. 2 | use ndarray::parallel::prelude::*; 3 | use num_derive::ToPrimitive; 4 | use numpy::ndarray::{ 5 | stack, Array, Array1, Array2, Array3, ArrayView1, ArrayView2, ArrayView4, Axis, 6 | }; 7 | 8 | use crate::field::{Bounds, VectorField}; 9 | /// Enum denoting status of the streamline tracer 10 | #[derive(PartialEq, Debug, ToPrimitive, Clone, Copy)] 11 | pub enum TracerStatus { 12 | /// Still running 13 | Running, 14 | /// Ran out of steps 15 | RanOutOfSteps = 1, 16 | /// Stepped out of bounds 17 | OutOfBounds = 2, 18 | } 19 | 20 | /// A single stream line status 21 | #[derive(Clone)] 22 | pub struct StreamlineStatus { 23 | /// Reason of termination 24 | pub rot: TracerStatus, 25 | /// Number of valid coordinates returned 26 | /// Can be used to slice away extra bits of the array that were not 27 | /// used for tracing using `xs.slice(s![:n_points, ..])`. 28 | pub n_points: usize, 29 | } 30 | 31 | /// A result of tracing a streamline 32 | pub struct StreamlineResult { 33 | /// The status of a trace 34 | pub status: StreamlineStatus, 35 | /// The array of line coordinates that were traced 36 | pub line: Array2, 37 | } 38 | 39 | /// Trace streamlines 40 | /// 41 | /// # Parameters 42 | /// 43 | /// * `seeds` - Seed points for streamlines. Must be shape (nseeds, 3). 44 | /// * `field` - Vector field to track through. 45 | /// * `direction` - Direction to trace in, `1` for forwards, `-1` for backwards. 46 | /// * `step_size` - Size of each individual step to take. 47 | /// * `max_steps` - Maximum number of steps to take per streamline. 48 | /// This directly sets the size of the output streamline array. 49 | #[allow(clippy::too_many_arguments)] 50 | pub fn trace_streamlines<'a>( 51 | seeds: ArrayView2<'a, f64>, 52 | xgrid: ArrayView1<'a, f64>, 53 | ygrid: ArrayView1<'a, f64>, 54 | zgrid: ArrayView1<'a, f64>, 55 | values: ArrayView4<'a, f64>, 56 | cyclic: ArrayView1<'a, bool>, 57 | direction: i32, 58 | step_size: f64, 59 | max_steps: usize, 60 | ) -> (Vec, Array3) { 61 | let field = VectorField::new(xgrid, ygrid, zgrid, values, cyclic); 62 | 63 | // Trace from each seed in turn 64 | let (statuses, extracted_lines): (Vec, Vec>) = seeds 65 | .axis_iter(Axis(0)) 66 | .into_par_iter() 67 | .map(|seed| { 68 | let result = trace_streamline(seed, &field, &direction, &step_size, max_steps); 69 | return (result.status, result.line); 70 | }) 71 | .unzip(); 72 | 73 | let extracted_lines_views: Vec> = extracted_lines 74 | .iter() 75 | .map(|arr| return arr.view()) 76 | .collect(); 77 | let xs = stack(Axis(0), &extracted_lines_views).unwrap(); 78 | return (statuses, xs); 79 | } 80 | 81 | /// Trace a single streamline 82 | /// 83 | /// # Parameters 84 | /// - `x0`: Streamline seed point. 85 | /// - `field`: Vector field to trace through. 86 | /// - `direction`: Direction to trace in. Can be 1 for forwards or -1 for backwards. 87 | /// - `step_size`: Step size to take. 88 | /// - `max_steps`: The maximum number of steps to take. 89 | pub fn trace_streamline( 90 | x0: ArrayView1, 91 | field: &VectorField, 92 | direction: &i32, 93 | step_size: &f64, 94 | max_steps: usize, 95 | ) -> StreamlineResult { 96 | // Tracer status 97 | let mut xs = Array::zeros((max_steps, 3)); 98 | let mut status = TracerStatus::Running; 99 | // Number of points traced 100 | let mut n_points: usize = 1; 101 | // Fold direction into the definition of step size, 102 | // using sign(step_size) to determine step direction 103 | let step = (*step_size) * (*direction as f64); 104 | 105 | // Create output array 106 | // Take a copy of input seed 107 | let mut x = Array::zeros(3); 108 | x.assign(&x0); 109 | 110 | // Take streamline steps 111 | for i in 0..max_steps { 112 | // Copy current coordinate 113 | for j in 0..3 { 114 | xs[[i, j]] = x[[j]]; 115 | } 116 | // +1 to account for the initial point 117 | n_points = i + 1; 118 | // Take a single step 119 | // Updates `x` in place. 120 | x = rk4_update(x, field, &step); 121 | x = field.wrap_cyclic(x); 122 | // Check new point isn't out of bounds 123 | match field.check_bounds(x.view()) { 124 | Bounds::Out => { 125 | status = TracerStatus::OutOfBounds; 126 | break; 127 | } 128 | Bounds::In => { 129 | continue; 130 | } 131 | } 132 | } 133 | 134 | // Finished tracing maximum steps 135 | if status == TracerStatus::Running { 136 | status = TracerStatus::RanOutOfSteps; 137 | } 138 | 139 | return StreamlineResult { 140 | status: StreamlineStatus { 141 | rot: status, 142 | n_points, 143 | }, 144 | line: xs, 145 | }; 146 | } 147 | 148 | // Update a coordinate (`x`) by taking a single RK4 step 149 | fn rk4_update(mut x: Array1, field: &VectorField, step_size: &f64) -> Array1 { 150 | let mut xu = x.clone(); 151 | let k1 = stream_function(xu.view(), field, step_size); 152 | 153 | xu = x.clone() + 0.5 * k1.clone(); 154 | let k2 = stream_function(xu.view(), field, step_size); 155 | 156 | xu = x.clone() + 0.5 * k2.clone(); 157 | let k3 = stream_function(xu.view(), field, step_size); 158 | 159 | xu = x.clone() + k3.clone(); 160 | let k4 = stream_function(xu.view(), field, step_size); 161 | 162 | let step = (k1 + 2. * k2 + 2. * k3 + k4) / 6.; 163 | x = x + step; 164 | return x; 165 | } 166 | 167 | /// Return the step that a linear tracing method would take 168 | /// at a given position. 169 | fn stream_function(x: ArrayView1, field: &VectorField, step_size: &f64) -> Array1 { 170 | let vec = field.vector_at_position(x); 171 | let vmag = (vec[[0]].powf(2.) + vec[[1]].powf(2.) + vec[[2]].powf(2.)).sqrt(); 172 | return (*step_size) * vec / vmag; 173 | } 174 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | min_version = 4.0 3 | requires = 4 | tox-pypi-filter>=0.14 5 | envlist = 6 | py{310,311,312,313} 7 | py312-devdeps 8 | py310-oldestdeps 9 | codestyle 10 | build_docs 11 | 12 | [testenv] 13 | pypi_filter = https://raw.githubusercontent.com/sunpy/sunpy/main/.test_package_pins.txt 14 | # Run the tests in a temporary directory to make sure that we don't import 15 | # the package from the source tree 16 | change_dir = .tmp/{envname} 17 | description = 18 | run tests 19 | oldestdeps: with the oldest supported version of key dependencies 20 | devdeps: with the latest developer version of key dependencies 21 | pass_env = 22 | # A variable to tell tests we are on a CI system 23 | CI 24 | # Custom compiler locations (such as ccache) 25 | CC 26 | # Location of locales (needed by sphinx on some systems) 27 | LOCALE_ARCHIVE 28 | # If the user has set a LC override we should follow it 29 | LC_ALL 30 | set_env = 31 | MPLBACKEND = agg 32 | devdeps: PIP_EXTRA_INDEX_URL = https://pypi.anaconda.org/astropy/simple https://pypi.anaconda.org/scientific-python-nightly-wheels/simple 33 | deps = 34 | # For packages which publish nightly wheels this will pull the latest nightly 35 | devdeps: numpy>=0.0.dev0 36 | oldestdeps: minimum_dependencies 37 | # The following indicates which extras_require will be installed 38 | extras = 39 | tests 40 | commands_pre = 41 | oldestdeps: minimum_dependencies streamtracer --filename requirements-min.txt 42 | oldestdeps: pip install -r requirements-min.txt 43 | pip freeze --all --no-input 44 | commands = 45 | # To amend the pytest command for different factors you can add a line 46 | # which starts with a factor like `online: --remote-data=any \` 47 | # If you have no factors which require different commands this is all you need: 48 | pytest \ 49 | -vvv \ 50 | -r fEs \ 51 | --pyargs streamtracer \ 52 | --cov-report=xml \ 53 | --cov=streamtracer \ 54 | --cov-config={toxinidir}/.coveragerc \ 55 | {toxinidir}/docs \ 56 | {posargs} 57 | 58 | [testenv:codestyle] 59 | pypi_filter = 60 | skip_install = true 61 | description = Run all style and file checks with pre-commit 62 | deps = 63 | pre-commit 64 | commands = 65 | pre-commit install-hooks 66 | pre-commit run --color always --all-files --show-diff-on-failure 67 | 68 | [testenv:build_docs] 69 | description = invoke sphinx-build to build the HTML docs 70 | change_dir = 71 | docs 72 | extras = 73 | docs 74 | commands = 75 | sphinx-build --color -W --keep-going -b html -d _build/.doctrees . _build/html {posargs} 76 | --------------------------------------------------------------------------------