├── .github └── workflows │ ├── build.yml │ ├── doc_deploy.yml │ ├── lint.yml │ ├── pypi.yml │ └── sonarcloud.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .zenodo.json ├── CITATION.cff ├── LICENSE ├── README.md ├── docs ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── common_ops.md ├── data_loading.md ├── img │ └── sarxarray_logo.png ├── index.md ├── manipulations.md ├── notebooks │ ├── demo_sarxarray.ipynb │ └── download_button │ │ └── main.html └── setup.md ├── examples ├── archive │ ├── ALOS2_SEU_p36_coherence2.ipynb │ ├── ALOS2_sarxarray_datamodel.ipynb │ └── S1_sarxarray_datamodel.ipynb ├── demo_sarxarray.ipynb └── demo_sarxarray_spider.ipynb ├── mkdocs.yml ├── pyproject.toml ├── sarxarray ├── __init__.py ├── _io.py ├── conf.py ├── stack.py └── utils.py ├── setup.py ├── sonar-project.properties └── tests ├── __init__.py ├── data ├── scene_0.binaray ├── scene_1.binaray └── zarrs │ ├── slcs_example.zarr │ ├── .zattrs │ ├── .zgroup │ ├── .zmetadata │ ├── azimuth │ │ ├── 0 │ │ ├── .zarray │ │ └── .zattrs │ ├── imag │ │ ├── .zarray │ │ ├── .zattrs │ │ ├── 0.0.0 │ │ ├── 0.0.1 │ │ └── 0.0.2 │ ├── range │ │ ├── 0 │ │ ├── .zarray │ │ └── .zattrs │ ├── real │ │ ├── .zarray │ │ ├── .zattrs │ │ ├── 0.0.0 │ │ ├── 0.0.1 │ │ └── 0.0.2 │ └── time │ │ ├── 0 │ │ ├── .zarray │ │ └── .zattrs │ ├── slcs_example_broken_dim.zarr │ ├── .zattrs │ ├── .zgroup │ ├── .zmetadata │ ├── azimuth │ │ ├── 0 │ │ ├── .zarray │ │ └── .zattrs │ ├── imag │ │ ├── .zarray │ │ ├── .zattrs │ │ └── 0.0 │ ├── range │ │ ├── 0 │ │ ├── .zarray │ │ └── .zattrs │ └── real │ │ ├── .zarray │ │ ├── .zattrs │ │ └── 0.0 │ └── slcs_example_broken_vars.zarr │ ├── .zattrs │ ├── .zgroup │ ├── .zmetadata │ ├── azimuth │ ├── 0 │ ├── .zarray │ └── .zattrs │ ├── imag │ ├── .zarray │ ├── .zattrs │ ├── 0.0.0 │ ├── 0.0.1 │ └── 0.0.2 │ ├── range │ ├── 0 │ ├── .zarray │ └── .zattrs │ └── time │ ├── 0 │ ├── .zarray │ └── .zattrs ├── test_io.py ├── test_stack.py └── test_utils.py /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run: 2 | # 1. install Python dependencies 3 | # 2. build python package 4 | # 3. run unit tests 5 | # 4. Build documentation 6 | 7 | 8 | name: Python Package 9 | 10 | on: 11 | push: 12 | branches: [ "main" ] 13 | pull_request: 14 | branches: [ "main" ] 15 | 16 | jobs: 17 | build_and_test: 18 | 19 | runs-on: ${{ matrix.os }} 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | os: ['ubuntu-latest', 'macos-latest', 'windows-latest'] 24 | python-version: ["3.10", "3.11", "3.12"] 25 | 26 | steps: 27 | - uses: actions/checkout@v4 28 | - name: Set up Python ${{ matrix.python-version }} 29 | uses: actions/setup-python@v5 30 | with: 31 | python-version: ${{ matrix.python-version }} 32 | - name: Install dependencies 33 | run: | 34 | python -m pip install --upgrade pip 35 | python -m pip install build 36 | python -m pip install .[dev] 37 | - name: Build 38 | run: | 39 | python -m build 40 | - name: Unit tests 41 | run: | 42 | pytest tests/ 43 | 44 | build_doc: 45 | runs-on: ${{ matrix.os }} 46 | strategy: 47 | fail-fast: false 48 | matrix: 49 | os: ['ubuntu-latest'] 50 | python-version: ["3.10", "3.11", "3.12"] 51 | 52 | steps: 53 | - uses: actions/checkout@v4 54 | - name: Set up Python ${{ matrix.python-version }} 55 | uses: actions/setup-python@v5 56 | with: 57 | python-version: ${{ matrix.python-version }} 58 | - name: Install dependencies 59 | run: | 60 | python -m pip install --upgrade pip 61 | python -m pip install mkdocs mkdocs-material mkdocs-jupyter mkdocstrings[python] mkdocs-gen-files 62 | - name: Build docs 63 | run: | 64 | mkdocs build 65 | -------------------------------------------------------------------------------- /.github/workflows/doc_deploy.yml: -------------------------------------------------------------------------------- 1 | # Deploy documentation when new release created 2 | 3 | name: Deploy docs 4 | 5 | on: 6 | release: 7 | types: 8 | - published 9 | 10 | 11 | jobs: 12 | build: 13 | name: Deploy docs 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Checkout main 17 | uses: actions/checkout@v4 18 | with: 19 | fetch-depth: 0 20 | - name: Set up Python 3.10 21 | uses: actions/setup-python@v5 22 | with: 23 | python-version: "3.10" 24 | - name: Install dependencies 25 | run: | 26 | python -m pip install .[docs] 27 | - name: Deploy docs 28 | run: mkdocs gh-deploy --force 29 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Ruff lint 2 | on: [push, pull_request] 3 | jobs: 4 | ruff: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v4 8 | - uses: astral-sh/ruff-action@v3 -------------------------------------------------------------------------------- /.github/workflows/pypi.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | publish: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - name: Set up Python 13 | uses: actions/setup-python@v5 14 | with: 15 | python-version: "3.10" 16 | - name: Install dependencies 17 | run: | 18 | python -m pip install --upgrade pip 19 | python -m pip install build 20 | python -m build 21 | - name: Publish package 22 | uses: pypa/gh-action-pypi-publish@release/v1 23 | with: 24 | user: __token__ 25 | password: ${{ secrets.PYPI_TOKEN }} 26 | -------------------------------------------------------------------------------- /.github/workflows/sonarcloud.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: 3 | push: 4 | branches: [ "main" ] 5 | pull_request: 6 | branches: [ "main" ] 7 | jobs: 8 | sonarqube: 9 | name: SonarQube 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | with: 14 | fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis 15 | - name: SonarQube Scan 16 | uses: SonarSource/sonarqube-scan-action@v4 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any 19 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Local debuging directory 2 | .debug/ 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | cover/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | .pybuilder/ 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | # For a library or package, you might want to ignore these files since the code is 90 | # intended to run in multiple environments; otherwise, check them in: 91 | # .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # poetry 101 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 102 | # This is especially recommended for binary packages to ensure reproducibility, and is more 103 | # commonly ignored for libraries. 104 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 105 | #poetry.lock 106 | 107 | # pdm 108 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 109 | #pdm.lock 110 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 111 | # in version control. 112 | # https://pdm.fming.dev/#use-with-ide 113 | .pdm.toml 114 | 115 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 116 | __pypackages__/ 117 | 118 | # Celery stuff 119 | celerybeat-schedule 120 | celerybeat.pid 121 | 122 | # SageMath parsed files 123 | *.sage.py 124 | 125 | # Environments 126 | .env 127 | .venv 128 | env/ 129 | venv/ 130 | ENV/ 131 | env.bak/ 132 | venv.bak/ 133 | 134 | # Spyder project settings 135 | .spyderproject 136 | .spyproject 137 | 138 | # Rope project settings 139 | .ropeproject 140 | 141 | # mkdocs documentation 142 | /site 143 | 144 | # mypy 145 | .mypy_cache/ 146 | .dmypy.json 147 | dmypy.json 148 | 149 | # Pyre type checker 150 | .pyre/ 151 | 152 | # pytype static type analyzer 153 | .pytype/ 154 | 155 | # Cython debug symbols 156 | cython_debug/ 157 | 158 | # VSCode 159 | .vscode -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/astral-sh/ruff-pre-commit 3 | # Ruff version. 4 | rev: v0.6.4 5 | hooks: 6 | # Run the linter. 7 | - id: ruff 8 | # Run the formatter. 9 | - id: ruff-format -------------------------------------------------------------------------------- /.zenodo.json: -------------------------------------------------------------------------------- 1 | { 2 | "creators": [ 3 | { 4 | "affiliation": "Netherlands eScience Center", 5 | "name": "Ku, Ou", 6 | "orcid": "0000-0002-5373-5209" 7 | }, 8 | { 9 | "affiliation": "Netherlands eScience Center", 10 | "name": "Alidoost, Fakhereh (Sarah)" 11 | }, 12 | { 13 | "name": "Chandramouli, Pranav" 14 | }, 15 | { 16 | "affiliation": "Netherlands eScience Center", 17 | "name": "Nattino, Francesco" 18 | }, 19 | { 20 | "affiliation": "Delft University of Technology", 21 | "name": "van Leijen, Freek", 22 | "orcid": "0000-0002-2582-9267" 23 | }, 24 | { 25 | "affiliation": "Delft University of Technology", 26 | "name": "Jansen, Niels", 27 | "orcid": "0009-0009-1736-9801" 28 | } 29 | ], 30 | "description": "SARXarray is an open-source Xarray extension for Synthetic Aperture Radar (SAR) data.", 31 | "keywords": [ 32 | "earth-observation", 33 | "sar", 34 | "insar", 35 | "radar", 36 | "distributed computation" 37 | ], 38 | "license": { 39 | "id": "Apache-2.0" 40 | }, 41 | "title": "sarxarray" 42 | } 43 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | # This CITATION.cff file was generated with cffinit. 2 | # Visit https://bit.ly/cffinit to generate yours today! 3 | 4 | cff-version: 1.2.0 5 | title: sarxarray 6 | abstract: "SARXarray is an open-source Xarray extension for Synthetic Aperture Radar (SAR) data." 7 | message: >- 8 | If you use this software, please cite it using the 9 | metadata from this file. 10 | type: software 11 | authors: 12 | - given-names: Ou 13 | family-names: Ku 14 | email: o.ku@esciencecenter.nl 15 | affiliation: Netherlands eScience Center 16 | orcid: 'https://orcid.org/0000-0002-5373-5209' 17 | - given-names: Fakhereh (Sarah) 18 | family-names: Alidoost 19 | - given-names: Pranav 20 | family-names: Chandramouli 21 | - given-names: Francesco 22 | family-names: Nattino 23 | - given-names: Freek 24 | family-names: van Leijen 25 | identifiers: 26 | - type: doi 27 | value: 10.5281/zenodo.7717112 28 | description: Zenodo 29 | repository-code: 'https://github.com/TUDelftGeodesy/sarxarray' 30 | keywords: 31 | - earth-observation 32 | - sar 33 | - insar 34 | - radar 35 | - distributed computation 36 | license: Apache-2.0 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SarXarray 2 | 3 | [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.7717027.svg)](https://doi.org/10.5281/zenodo.7717027) 4 | [![PyPI](https://img.shields.io/pypi/v/sarxarray.svg?colorB=blue)](https://pypi.python.org/project/sarxarray/) 5 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=TUDelftGeodesy_sarxarray&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=TUDelftGeodesy_sarxarray) 6 | [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/7980/badge)](https://www.bestpractices.dev/projects/7980) 7 | [![Build](https://github.com/TUDelftGeodesy/sarxarray/actions/workflows/build.yml/badge.svg)](https://github.com/TUDelftGeodesy/sarxarray/actions/workflows/build.yml) 8 | [![License](https://img.shields.io/github/license/TUDelftGeodesy/sarxarray)](https://opensource.org/licenses/Apache-2.0) 9 | 10 | 11 | SARXarray is an open-source Xarray extension for Synthetic Aperture Radar (SAR) data. It is especially designed to work with large volume complex data, e.g. Single Look Complex (SLC) data, as well as derived products such as interferogram stacks. 12 | 13 | 14 | ## Installation 15 | 16 | SARXarray can be installed from PyPI: 17 | 18 | ```sh 19 | pip install sarxarray 20 | ``` 21 | 22 | or from the source: 23 | 24 | ```sh 25 | git clone git@github.com:TUDelftGeodesy/sarxarray.git 26 | cd sarxarray 27 | pip install . 28 | ``` 29 | 30 | Note that Python version `>=3.10` is required for SARXarray. 31 | 32 | ## Documentation 33 | 34 | For more information on usage and examples of SARXarray, please refer to the [documentation](https://tudelftgeodesy.github.io/sarxarray/). 35 | 36 | ## License 37 | 38 | Copyright (c) 2022 - 2025, Netherlands eScience Center & Delft University of Technology 39 | 40 | Apache Software License 2.0 41 | -------------------------------------------------------------------------------- /docs/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | This project adheres to [Semantic Versioning](http://semver.org/). 5 | 6 | 7 | [0.1.0] - 2023-11-06 8 | ******************** 9 | 10 | Added 11 | ----- 12 | 13 | The first version of the SARXarray package. The following functionalities are implemented: 14 | - Data loading function for large SAR/interferogram stack; 15 | - Basic SAR raster operations: multi-look, coherence, and MRM; 16 | - Scatterer selection based on amplitude dispersion; 17 | - Relevant docs and tests. 18 | -------------------------------------------------------------------------------- /docs/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | This code of conduct is adapted from the 4 | [Git Code of Conduct](https://github.com/git/git/blob/master/CODE_OF_CONDUCT.md). 5 | 6 | ## Our Pledge 7 | 8 | We as members, contributors, and leaders pledge to make participation in our 9 | community a harassment-free experience for everyone, regardless of age, body 10 | size, visible or invisible disability, ethnicity, sex characteristics, gender 11 | identity and expression, level of experience, education, socio-economic status, 12 | nationality, personal appearance, race, religion, or sexual identity 13 | and orientation. 14 | 15 | We pledge to act and interact in ways that contribute to an open, welcoming, 16 | diverse, inclusive, and healthy community. 17 | 18 | ## Our Standards 19 | 20 | Examples of behavior that contributes to a positive environment for our 21 | community include: 22 | 23 | * Demonstrating empathy and kindness toward other people 24 | * Being respectful of differing opinions, viewpoints, and experiences 25 | * Giving and gracefully accepting constructive feedback 26 | * Accepting responsibility and apologizing to those affected by our mistakes, 27 | and learning from the experience 28 | * Focusing on what is best not just for us as individuals, but for the 29 | overall community 30 | 31 | Examples of unacceptable behavior include: 32 | 33 | * The use of sexualized language or imagery, and sexual attention or 34 | advances of any kind 35 | * Trolling, insulting or derogatory comments, and personal or political attacks 36 | * Public or private harassment 37 | * Publishing others' private information, such as a physical or email 38 | address, without their explicit permission 39 | * Other conduct which could reasonably be considered inappropriate in a 40 | professional setting 41 | 42 | ## Enforcement Responsibilities 43 | 44 | Project maintainers are responsible for clarifying and enforcing our standards of 45 | acceptable behavior and will take appropriate and fair corrective action in 46 | response to any behavior that they deem inappropriate, threatening, offensive, 47 | or harmful. 48 | 49 | Project maintainers have the right and responsibility to remove, edit, or reject 50 | comments, commits, code, wiki edits, issues, and other contributions that are 51 | not aligned to this Code of Conduct, and will communicate reasons for moderation 52 | decisions when appropriate. 53 | 54 | ## Scope 55 | 56 | This Code of Conduct applies both within project spaces and in public spaces when 57 | an individual is representing the project or its community. Examples of representing 58 | a project or community include using an official project e-mail address, posting via 59 | an official social media account, or acting as an appointed representative at an 60 | online or offline event. Representation of a project may be further defined and 61 | clarified by project maintainers. 62 | 63 | ## Enforcement 64 | 65 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 66 | reported by contacting the project team at team-atlas@esciencecenter.nl. 67 | 68 | All complaints will be reviewed and investigated promptly and fairly. 69 | 70 | All Project maintainers are obligated to respect the privacy and security of the 71 | reporter of any incident. 72 | 73 | ## Attribution 74 | 75 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, 76 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html -------------------------------------------------------------------------------- /docs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | # SARXarray Contributing Guidelines 3 | 4 | 5 | We welcome any kind of contribution to our software, from a simple comment 6 | or question to a full fledged [pull request](https://help.github.com/articles/about-pull-requests/). 7 | Please read and follow our [Code of Conduct](./CODE_OF_CONDUCT.md). 8 | 9 | A contribution can be one of the following cases: 10 | 11 | - you have a question; 12 | - you think you may have found a bug (including unexpected behavior); 13 | - you want to make some kind of change to the code base (e.g. to fix a bug, to add a new feature, to update documentation). 14 | 15 | The sections below outline the steps in each case. 16 | 17 | ## You have a question 18 | 19 | - use the search functionality in [GitHub issue](https://github.com/TUDelftGeodesy/sarxarray/issues) 20 | to see if someone already filed the same issue; 21 | - if your issue search did not yield any relevant results, create a new issue; 22 | - add the "question" label; include other labels when relevant. 23 | 24 | ## You think you may have found a bug 25 | 26 | - use the search functionality in [GitHub issue](https://github.com/TUDelftGeodesy/sarxarray/issues) to see if someone already filed the same issue; 27 | - if your issue search did not yield any relevant results, create a new issue, making sure to provide enough information to the rest of the community to understand the cause and context of the problem. Depending on the issue, you may want to include: 28 | - the [SHA hashcode](https://help.github.com/articles/autolinked-references-and-urls/#commit-shas>) of the commit that is causing your problem; 29 | - some identifying information (name and version number) for dependencies you're using; 30 | - information about the operating system; 31 | - add relevant labels to the newly created issue. 32 | 33 | ## You want to make some kind of change to the code base 34 | 35 | - (**important**) announce your plan to the rest of the community *before you start working*. This announcement should be in the form of a (new) issue; 36 | - (**important**) wait until some kind of consensus is reached about your idea being a good idea; 37 | - if needed, fork the repository to your own Github profile and create your own feature branch off of the latest master commit. While working on your feature branch, make sure to stay up to date with the master branch by pulling in changes, possibly from the 'upstream' repository (follow the instructions from GitHub: [instruction 1: configuring a remote for a fork](https://help.github.com/articles/configuring-a-remote-for-a-fork/) and [instruction 2: syncing a fork](https://help.github.com/articles/syncing-a-fork/)); 38 | - install the pre-commit hooks by running `pre-commit install` in the project root directory; 39 | - make sure the existing tests still work by running, e.g. `pytest tests`; 40 | - add your own tests (if necessary); 41 | - update or expand the documentation; 42 | - make sure the linting tests pass by running `ruff` in the project root directory: `ruff check .`; 43 | - [push](http://rogerdudler.github.io/git-guide/) your feature branch to (your fork of) the sarxarray repository on GitHub; 44 | - create the pull request, e.g. following [the instructions: creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 45 | 46 | In case you feel like you've made a valuable contribution, but you don't know how to write or run tests for it, or how to generate the documentation: don't let this discourage you from making the pull request; we can help you! Just go ahead and submit the pull request, but keep in mind that you might be asked to append additional commits to your pull request. -------------------------------------------------------------------------------- /docs/common_ops.md: -------------------------------------------------------------------------------- 1 | # Common SLC operations 2 | 3 | > Details about the common operations in this page are coming soon... 4 | 5 | Common SAR processings can be performed by SARXarray. Below are some examples: 6 | 7 | ## Multi-look 8 | 9 | Multi-look by a windowsize of e.g. 2 in azimuth dimension and 4 in range dimension: 10 | 11 | ```python 12 | stack_multilook = stack.slcstack.multi_look((2,4)) 13 | ``` 14 | 15 | ## Coherence 16 | Compute coherence between two SLCs: 17 | 18 | ```python 19 | from sarxarray import complex_coherence 20 | slc1 = stack.complex.isel(time=0) # first image 21 | slc2 = stack.complex.isel(time=2) # third image 22 | window = (4,4) 23 | 24 | coherence = complex_coherence(slc1, slc2, window) 25 | ``` 26 | 27 | ## Mean-Reflection-Map (MRM) 28 | ```python 29 | mrm = stack_multilook.slcstack.mrm() 30 | ``` 31 | 32 | ```python 33 | from matplotlib import pyplot as plt 34 | fig, ax = plt.subplots() 35 | ax.imshow(mrm) 36 | mrm.plot(ax=ax, robust=True, cmap='gray') 37 | ``` 38 | 39 | ## Point selection 40 | A selection based on temporal properties per pixel can be performed. For example, we can select the Point Scatterers (PS) by normalized temporal dispersion of `amplitude`: 41 | 42 | ```python 43 | ps = stack.slcstack.point_selection(threshold=0.25, method="amplitude_dispersion") 44 | ``` 45 | -------------------------------------------------------------------------------- /docs/data_loading.md: -------------------------------------------------------------------------------- 1 | # Usage 2 | 3 | ## Input data format 4 | 5 | SARXarray works with coregistered SLC/interferogram stack. SARXarray provides a reader to perform lazy loading on data stacks in different file formats, including binary format. However, we recommend to store the coregistered stack in [`zarr`](https://zarr.readthedocs.io/en/stable/) format, and directly load them as an Xarray object by [`xarray.open_zarr`](https://docs.xarray.dev/en/stable/generated/xarray.open_zarr.html). 6 | 7 | 8 | ## Loading coregistered SLC stack in binary format 9 | 10 | If the stack is saved in binary format, it can be read by `SARXarray` under two pre-requisites: 11 | 12 | 1. All SLCs/interferograms have the same known raster size and data type; 13 | 2. All SLCs/interferograms have been resampled to the same raster grid. 14 | 15 | For example, let's consider a case of a stack with three SLCs: 16 | 17 | ```python 18 | import numpy as np 19 | list_slcs = ['data/slc_1.raw', 'data/slc_2.raw', 'data/slc_3.raw'] 20 | shape = (10018, 68656) # (azimuth, range) 21 | dtype = np.complex64 22 | ``` 23 | 24 | We built a list `list_slcs` with the paths to the SLCs. In this case they are stored in the same directory called `data`. The shape of each SLC should be provided, i.e.: `10018` pixels in `azimuth` direction, and `68656` in range direction. The data type is `numpy.complex64`. 25 | 26 | The coregistered SLC stack can be read using the `from_binary` function: 27 | 28 | ```python 29 | import sarxarray 30 | 31 | stack = sarxarray.from_binary(list_slcs, shape, dtype=dtype) 32 | ``` 33 | You can also skip the `dtype` argument since it's defaulted to `numpy.complex64`. The stack will be read as an `xarray.Dataset` object, with data variables lazily loaded as `Dask Array`: 34 | 35 | ```python 36 | print(stack) 37 | ``` 38 | 39 | ```output 40 | 41 | Dimensions: (azimuth: 10018, range: 68656, time: 3) 42 | Coordinates: 43 | * azimuth (azimuth) int64 0 1 2 3 4 5 ... 10013 10014 10015 10016 10017 44 | * range (range) int64 0 1 2 3 4 5 ... 68650 68651 68652 68653 68654 68655 45 | * time (time) int64 0 1 2 46 | Data variables: 47 | complex (azimuth, range, time) complex64 dask.array 48 | amplitude (azimuth, range, time) float32 dask.array 49 | phase (azimuth, range, time) float32 dask.array 50 | ``` 51 | 52 | The loading chunk size can also be specified manually: 53 | 54 | ```python 55 | stack_smallchunk = sarxarray.from_binary(list_slcs, shape, chunks=(2000, 2000)) 56 | ``` 57 | 58 | -------------------------------------------------------------------------------- /docs/img/sarxarray_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TUDelftGeodesy/sarxarray/017f039ec17f53e03d73f0e7d848922013d57e32/docs/img/sarxarray_logo.png -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # SARXarray 2 | 3 | SARXarray is an open-source Xarray extension for Synthetic Aperture Radar (SAR) data. 4 | 5 | SARXarray is especially designed to work with complex data, that is, containing both the phase and amplitude of the data. The extension can handle coregistered stacks of Single Look Complex (SLC) data, as well as derived products such as interferogram stacks. 6 | It utilizes Xarray’s support on labeled multi-dimensional datasets to stress the space-time character of the image stacks. Dask Array is implemented to support parallel computation. 7 | 8 | SARXarry supports the following functionalities: 9 | 10 | 1. Chunk-wise reading/writing of coregistered SLC or interferogram stacks; 11 | 12 | 2. Basic operations on complex data, e.g., averaging along axis and complex conjugate multiplication; 13 | 14 | 3. Specific SAR data operations, e.g., multi-looking and coherence estimation. 15 | 16 | All the above functionalities can be scaled up to a Hyper-Performance Computation (HPC) system. 17 | 18 | -------------------------------------------------------------------------------- /docs/manipulations.md: -------------------------------------------------------------------------------- 1 | # Manipulate an SLC stack as an Xarray 2 | 3 | The loaded stack can be manipulated as an `Xarray.Dataset` instance. 4 | 5 | Slice the SLC stack in 3D: 6 | 7 | ```python 8 | stack.isel(azimuth=range(1000,2000), range=range(1500,2500), time=range(2,5)) 9 | ``` 10 | 11 | Select the `amplitude` attribute 12 | ```python 13 | amp = stack['amplitude'] 14 | ``` 15 | 16 | Compute stack and persist in memory: 17 | ```python 18 | stack = stack.compute() 19 | ``` 20 | -------------------------------------------------------------------------------- /docs/notebooks/download_button/main.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 | {% if page.nb_url %} 5 | 6 | {% include ".icons/material/download.svg" %} 7 | 8 | {% endif %} 9 | 10 | {{ super() }} 11 | {% endblock content %} -------------------------------------------------------------------------------- /docs/setup.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | SARXarray can be installed from PyPI: 4 | 5 | ```sh 6 | pip install sarxarray 7 | ``` 8 | 9 | or from the source: 10 | 11 | ```sh 12 | git clone git@github.com:TUDelftGeodesy/sarxarray.git 13 | cd sarxarray 14 | pip install . 15 | ``` 16 | 17 | Note that Python version `>=3.10` is required for SARXarray. 18 | 19 | ## Tips 20 | 21 | We strongly recommend installing separately from your default Python environment. E.g. you can use environment manager (e.g. [mamba](https://mamba.readthedocs.io/en/latest/mamba-installation.html)) to create a separate environment. 22 | -------------------------------------------------------------------------------- /examples/archive/ALOS2_SEU_p36_coherence2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "e25d56aa-5366-41f4-8fff-e7a52926c83a", 6 | "metadata": { 7 | "tags": [] 8 | }, 9 | "source": [ 10 | "
\n", 11 | " \n", 12 | "
\n", 13 | "\n", 14 | "### ALOS-2 - InSAR datamodel based on sarxarray" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 1, 20 | "id": "60ed1b4f-30a0-4b1e-90c6-8dee1f76ea99", 21 | "metadata": { 22 | "tags": [] 23 | }, 24 | "outputs": [], 25 | "source": [ 26 | "import numpy as np\n", 27 | "from pathlib import Path\n", 28 | "import sarxarray\n", 29 | "import matplotlib.pyplot as plt\n", 30 | "\n", 31 | "import xarray as xr\n", 32 | "import rioxarray\n", 33 | "from scipy.ndimage import uniform_filter\n", 34 | "from scipy.spatial import KDTree\n", 35 | "from tqdm import tqdm\n", 36 | "import time\n", 37 | "from datetime import datetime\n", 38 | "\n", 39 | "from matplotlib.dates import DateFormatter, DayLocator\n", 40 | "from matplotlib.ticker import MultipleLocator\n", 41 | "from skimage.util import view_as_windows\n", 42 | "\n", 43 | "from scipy.linalg import svd\n", 44 | "from scipy.linalg import inv\n", 45 | "from scipy.linalg import pinv\n", 46 | "from scipy.ndimage import generic_filter, label\n", 47 | "\n", 48 | "import cv2 as cv\n", 49 | "import matplotlib.colors as colors\n", 50 | "\n", 51 | "from scipy.interpolate import griddata\n", 52 | "import re\n", 53 | "import os\n", 54 | "import bisect" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "id": "fd603ee6-6cb1-462e-acfd-6cb02cbd7fcf", 60 | "metadata": {}, 61 | "source": [ 62 | "### Specify path of file location" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 2, 68 | "id": "6ac51b80-8173-4fb6-87c4-8db1f66b7154", 69 | "metadata": { 70 | "tags": [] 71 | }, 72 | "outputs": [], 73 | "source": [ 74 | "path = Path('data_alos2_seus_p36/')" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": 3, 80 | "id": "67a43521-cb3a-48ca-b100-7ee2e2296a13", 81 | "metadata": { 82 | "tags": [] 83 | }, 84 | "outputs": [ 85 | { 86 | "data": { 87 | "text/plain": [ 88 | "[PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20140917/cint_srd.raw'),\n", 89 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20150204/cint_srd.raw'),\n", 90 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20150916/cint_srd.raw'),\n", 91 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20160914/cint_srd.raw'),\n", 92 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20170201/cint_srd.raw'),\n", 93 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20180117/cint_srd.raw'),\n", 94 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20180328/cint_srd.raw'),\n", 95 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20181024/cint_srd.raw'),\n", 96 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20190102/cint_srd.raw'),\n", 97 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20190327/cint_srd.raw'),\n", 98 | " PosixPath('data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/20200101/cint_srd.raw')]" 99 | ] 100 | }, 101 | "execution_count": 3, 102 | "metadata": {}, 103 | "output_type": "execute_result" 104 | } 105 | ], 106 | "source": [ 107 | "list_ifgs = [p for p in path.rglob('*cint_srd.raw') if not str(p).endswith('20180117\\cint_srd.raw')]\n", 108 | "list_ifgs.sort()\n", 109 | "list_ifgs" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": 4, 115 | "id": "03335612-69bd-4292-99d1-56d14ad1cd47", 116 | "metadata": { 117 | "tags": [] 118 | }, 119 | "outputs": [ 120 | { 121 | "ename": "IndexError", 122 | "evalue": "list index out of range", 123 | "output_type": "error", 124 | "traceback": [ 125 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 126 | "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)", 127 | "Cell \u001b[0;32mIn[4], line 6\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;28mlen\u001b[39m(list_ifgs)):\n\u001b[1;32m 5\u001b[0m prep_date_string \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mstr\u001b[39m(list_ifgs[i])\n\u001b[0;32m----> 6\u001b[0m date \u001b[38;5;241m=\u001b[39m \u001b[43mprep_date_string\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msplit\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;130;43;01m\\\\\u001b[39;49;00m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m2\u001b[39;49m\u001b[43m]\u001b[49m\n\u001b[1;32m 7\u001b[0m date_list\u001b[38;5;241m.\u001b[39mappend(date)\n\u001b[1;32m 9\u001b[0m date_to_add \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124m20180117\u001b[39m\u001b[38;5;124m'\u001b[39m \u001b[38;5;66;03m# USERCHANGE 2\u001b[39;00m\n", 128 | "\u001b[0;31mIndexError\u001b[0m: list index out of range" 129 | ] 130 | } 131 | ], 132 | "source": [ 133 | "# Create date list to keep track of each radar image\n", 134 | "\n", 135 | "date_list = []\n", 136 | "for i in range(len(list_ifgs)):\n", 137 | " prep_date_string = str(list_ifgs[i])\n", 138 | " date = prep_date_string.split('\\\\')[2]\n", 139 | " date_list.append(date)\n", 140 | "\n", 141 | "date_to_add = '20180117' # USERCHANGE 2\n", 142 | "\n", 143 | "# Find the index where the new date should be inserted\n", 144 | "insert_index = bisect.bisect_left(date_list, date_to_add)\n", 145 | "\n", 146 | "# Insert the new date at the calculated index\n", 147 | "date_list.insert(insert_index, date_to_add)\n", 148 | " \n", 149 | "date_list" 150 | ] 151 | }, 152 | { 153 | "cell_type": "markdown", 154 | "id": "eac3d816-46f2-4135-b987-434b04749d64", 155 | "metadata": {}, 156 | "source": [ 157 | "### Metadata\n", 158 | "Information about the shape can be extracted from ifgs.res files and are denoted using 'nlines' and 'npixels', respectively." 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": null, 164 | "id": "4c1aa081-d05d-4203-92f5-72e3af9c1e38", 165 | "metadata": { 166 | "tags": [] 167 | }, 168 | "outputs": [], 169 | "source": [ 170 | "# Open the metadata ifgs.res file\n", 171 | "\n", 172 | "filepath = str(path) + '/' + 'process_StEustatius_fixed_mtiming_dembased_20180117/' + date_list[0] + '/ifgs.res'\n", 173 | "\n", 174 | "with open(filepath, 'r') as file:\n", 175 | " content = file.read()\n", 176 | " \n", 177 | "# Look through DORIS V5 'ifgs.res' file for shape\n", 178 | "\n", 179 | "lines = r'Number of lines \\(multilooked\\):\\s+(\\d+)'\n", 180 | "pixels = r'Number of pixels \\(multilooked\\):\\s+(\\d+)'\n", 181 | "match_lines = re.search(lines, content)\n", 182 | "match_pixels = re.search(pixels, content)\n", 183 | "\n", 184 | "if match_lines:\n", 185 | " \n", 186 | " # Extract the number of lines from the matched pattern\n", 187 | " \n", 188 | " num_lines = int(match_lines.group(1))\n", 189 | " print(f\"Number of lines: {num_lines}\")\n", 190 | "else:\n", 191 | " print(\"Not found in the file.\")\n", 192 | "\n", 193 | "if match_pixels:\n", 194 | " \n", 195 | " # Extract the number of pixels from the matched pattern\n", 196 | " \n", 197 | " num_pixels = int(match_pixels.group(1))\n", 198 | " print(f\"Number of pixels: {num_pixels}\")\n", 199 | "else:\n", 200 | " print(\"Not found in the file.\")" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "id": "2d3712c1-9c62-4dfd-847e-f081eebfa758", 207 | "metadata": { 208 | "tags": [] 209 | }, 210 | "outputs": [], 211 | "source": [ 212 | "shape=(num_lines, num_pixels) # obtained from ifgs.res --> nlines= rows ; npixels = columns\n", 213 | "dtype = np.dtype([('re', np.float32), ('im', np.float32)])" 214 | ] 215 | }, 216 | { 217 | "cell_type": "markdown", 218 | "id": "8282f092-5c78-435f-983b-e886601e4bd7", 219 | "metadata": {}, 220 | "source": [ 221 | "### Loading the raw interferogram into a `xarray.Dataset`" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "id": "655c9644-e54c-4d47-9903-58cb647df1b9", 228 | "metadata": { 229 | "tags": [] 230 | }, 231 | "outputs": [], 232 | "source": [ 233 | "# Create xarray.Dataset object from .raw file\n", 234 | "\n", 235 | "ifg_stack = sarxarray.from_binary(list_ifgs, shape, dtype=dtype)\n", 236 | "\n", 237 | "ifg_stack = ifg_stack.chunk({\"azimuth\":500, \"range\":500, \"time\":1 }) # set custom chunk sizes\n", 238 | "ifg_stack.complex" 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": null, 244 | "id": "14809620-038e-42d5-8dba-184e56a71574", 245 | "metadata": { 246 | "tags": [] 247 | }, 248 | "outputs": [], 249 | "source": [ 250 | "plt.imshow(ifg_stack.phase.isel(time=5))\n", 251 | "ifg_stack.phase.isel(time=5).plot(robust=True, cmap='jet') # cmap='jet'" 252 | ] 253 | }, 254 | { 255 | "cell_type": "markdown", 256 | "id": "7d89b718-dae1-4562-96a3-89429d083afa", 257 | "metadata": {}, 258 | "source": [ 259 | "### Pair Selection" 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": null, 265 | "id": "152eb6c9-b651-4244-9937-a03cdbabce68", 266 | "metadata": { 267 | "tags": [] 268 | }, 269 | "outputs": [], 270 | "source": [ 271 | "metadata = open(\"data_alos2_seus_p36/process_StEustatius_fixed_mtiming_dembased_20180117/baselines_alos2_p36_20180117.txt\") # USERCHANGE 6\n", 272 | "\n", 273 | "metadata = metadata.readlines()\n", 274 | "metadata" 275 | ] 276 | }, 277 | { 278 | "cell_type": "code", 279 | "execution_count": null, 280 | "id": "9f6fa103-f7df-4bee-9ced-f593fb641738", 281 | "metadata": { 282 | "tags": [] 283 | }, 284 | "outputs": [], 285 | "source": [ 286 | "B_perp = []\n", 287 | "B_date = []\n", 288 | "date_list = []\n", 289 | "\n", 290 | "for i in range(len(metadata)):\n", 291 | " split_string = metadata[i].split()\n", 292 | " split_string_subset = metadata[i].split('/')[0]\n", 293 | " \n", 294 | " date_list.append(split_string_subset)\n", 295 | " B_perp.append(float(split_string[3]))\n", 296 | " B_date.append(split_string_subset)\n", 297 | " \n", 298 | "format = '%Y%m%d'\n", 299 | "\n", 300 | "B_T = []\n", 301 | "for i in B_date:\n", 302 | " formatted = datetime.strptime(i, format)\n", 303 | " B_T.append(formatted.date())\n", 304 | " \n", 305 | "# Remove the mother value (BL = 0)\n", 306 | "B_perp_original = B_perp.copy()\n", 307 | "\n", 308 | "idx_remove = B_perp.index(0.0)\n", 309 | "B_perp.pop(idx_remove)" 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": null, 315 | "id": "cc267376-5c59-4c70-8fb3-c6b54cea0e39", 316 | "metadata": { 317 | "tags": [] 318 | }, 319 | "outputs": [], 320 | "source": [ 321 | "# Calculate spatio-temporal baselines for all possible combinations\n", 322 | "\n", 323 | "def B_combinations(B_perp, B_T, date_list, idx_remove):\n", 324 | " \n", 325 | " # Baselines (Bms_perp & Bms_T) for all the unique combinations\n", 326 | "\n", 327 | " B_perp_combo = []\n", 328 | " B_T_combo = []\n", 329 | " date_list_combo = []\n", 330 | " \n", 331 | " for i in range(len(B_T)):\n", 332 | " for j in range(len(B_T)):\n", 333 | " if(j > i): \n", 334 | " t_combo = (B_T[i]-B_T[j])\n", 335 | " B_T_combo.append(t_combo.days)\n", 336 | " \n", 337 | " date_combo = (date_list[i] + '-' + date_list[j])\n", 338 | " date_list_combo.append(date_combo)\n", 339 | "\n", 340 | " for i in range(len(B_perp)):\n", 341 | " for j in range(len(B_perp)):\n", 342 | " if(i > j):\n", 343 | " perp_combo = B_perp[i] - B_perp[j]\n", 344 | " B_perp_combo.append(perp_combo)\n", 345 | " \n", 346 | " # Combine with original list to get all possible combinations (+ original)\n", 347 | " \n", 348 | " B_perp_comp = B_perp_combo.copy()\n", 349 | " B_perp_comp[idx_remove:idx_remove] = B_perp\n", 350 | " \n", 351 | " return B_perp_comp, B_T_combo, date_list_combo, t_combo" 352 | ] 353 | }, 354 | { 355 | "cell_type": "code", 356 | "execution_count": null, 357 | "id": "9b2c5d91-14fe-4d58-9845-cf463f82abc6", 358 | "metadata": { 359 | "tags": [] 360 | }, 361 | "outputs": [], 362 | "source": [ 363 | "def mod_coh(B_perp, B_T, B_perp_max, B_T_max):\n", 364 | " coh_modelled = max((1 - (np.abs(B_perp)/B_perp_max)),0) * max((1 - (np.abs(B_T)/B_T_max)),0)\n", 365 | " return coh_modelled\n", 366 | "\n", 367 | "# if both negative ; should not be taken into account --> 0 per element;\n", 368 | "# for now linear behaviour, could be refined to have quadratic e.g." 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "execution_count": null, 374 | "id": "a70d0666-6bd8-478a-9e04-a07ef4be389b", 375 | "metadata": { 376 | "tags": [] 377 | }, 378 | "outputs": [], 379 | "source": [ 380 | "B_perp_comp, B_T_comp,date_list_combo,t_combo = B_combinations(B_perp, B_T, date_list, idx_remove)\n", 381 | "len(B_T_comp)\n", 382 | "\n", 383 | "coh_modelled = []\n", 384 | "for i in range(len(B_perp_comp)):\n", 385 | " coh = mod_coh(B_perp_comp[i], B_T_comp[i], 14500, 1152)\n", 386 | " coh_modelled.append(coh) " 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": null, 392 | "id": "8bd484d9-a852-4ae0-8974-528ba001908b", 393 | "metadata": { 394 | "tags": [] 395 | }, 396 | "outputs": [], 397 | "source": [ 398 | "# Pair selection algorithm\n", 399 | "\n", 400 | "selection_idx = [i for i, val in enumerate(coh_modelled) if val > 0.3]\n", 401 | "\n", 402 | "pair_selection = []\n", 403 | "B_perp_sel = []\n", 404 | "B_T_sel = []\n", 405 | "for i in selection_idx:\n", 406 | " selection = date_list_combo[i]\n", 407 | " pair_selection.append(selection)\n", 408 | " \n", 409 | "len(pair_selection)" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": null, 415 | "id": "36ac7854-4028-4b30-bb57-2aa7241cf924", 416 | "metadata": { 417 | "tags": [] 418 | }, 419 | "outputs": [], 420 | "source": [ 421 | "pair_selection" 422 | ] 423 | }, 424 | { 425 | "cell_type": "code", 426 | "execution_count": null, 427 | "id": "df5ad9d7-97d8-4c51-943c-045420ef5438", 428 | "metadata": { 429 | "tags": [] 430 | }, 431 | "outputs": [], 432 | "source": [ 433 | "# Plot baseline configuration PSI\n", 434 | "\n", 435 | "plt.figure(figsize=(20,10))\n", 436 | "plt.scatter(B_T,B_perp_original, marker='^',zorder=2, color=['red' if i==0 else 'blue' for i in B_perp_original])\n", 437 | "\n", 438 | "for i in range(len(B_T)):\n", 439 | " if B_perp_original[i] == 0:\n", 440 | " for j in range(len(B_T)):\n", 441 | " if i != j and B_perp_original[j] != 0:\n", 442 | " plt.plot([B_T[i], B_T[j]], [B_perp_original[i], B_perp_original[j]], color='grey', linestyle='-',linewidth=0.5, zorder=1)\n", 443 | "\n", 444 | "# Set the x-axis label format\n", 445 | "\n", 446 | "date_formatter = DateFormatter('%b %Y') # Format: Month Year\n", 447 | "plt.gca().xaxis.set_major_formatter(date_formatter)\n", 448 | "\n", 449 | "# Set the x-axis tick locator\n", 450 | "\n", 451 | "plt.gca().xaxis.set_major_locator(DayLocator(interval=200))\n", 452 | "\n", 453 | "plt.grid()\n", 454 | "plt.title('ALOS-2 p36 St.Eustatius - Single-Mother Configuration')\n", 455 | "plt.xlabel('Date')\n", 456 | "plt.ylabel('Perpendicular Baseline [m]')\n", 457 | "# plt.xticks(rotation=90)\n", 458 | "plt.show()" 459 | ] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "execution_count": null, 464 | "id": "fcd84ba6-208f-4924-8575-965005c9cc29", 465 | "metadata": { 466 | "tags": [] 467 | }, 468 | "outputs": [], 469 | "source": [ 470 | "# Plot baseline configuration SBAS\n", 471 | "\n", 472 | "plt.figure(figsize=(20,10))\n", 473 | "plt.scatter(B_T,B_perp_original, marker='^',zorder=2, color=['red' if i==0 else 'blue' for i in B_perp_original])\n", 474 | "\n", 475 | "# Connect lines between the pair selection result\n", 476 | "\n", 477 | "start = []\n", 478 | "end = []\n", 479 | "for pair in pair_selection:\n", 480 | " start_date, end_date = pair.split('-')[0], pair.split('-')[1]\n", 481 | " start_date = datetime.strptime(start_date, '%Y%m%d').date()\n", 482 | " end_date = datetime.strptime(end_date, '%Y%m%d').date()\n", 483 | " \n", 484 | " start.append(start_date)\n", 485 | " end.append(end_date)\n", 486 | "\n", 487 | "for i in range(len(start)):\n", 488 | " idx_i = B_T.index(start[i])\n", 489 | " idx_j = B_T.index(end[i])\n", 490 | " plt.plot([B_T[idx_i], B_T[idx_j]], [B_perp_original[idx_i], B_perp_original[idx_j]], color='grey', linestyle='-', linewidth=0.5, zorder=1)\n", 491 | "\n", 492 | "# Set the x-axis label format\n", 493 | "\n", 494 | "date_formatter = DateFormatter('%b %Y') # Format: Month Year\n", 495 | "plt.gca().xaxis.set_major_formatter(date_formatter)\n", 496 | "\n", 497 | "# Set the x-axis tick locator\n", 498 | "\n", 499 | "plt.gca().xaxis.set_major_locator(DayLocator(interval=365))\n", 500 | "\n", 501 | "plt.grid()\n", 502 | "plt.title('ALOS-2 p36 St.Eustatius - Short-Baseline Configuration')\n", 503 | "plt.xlabel('Date')\n", 504 | "plt.ylabel('Perpendicular Baseline [m]')\n", 505 | "plt.show()" 506 | ] 507 | }, 508 | { 509 | "cell_type": "code", 510 | "execution_count": null, 511 | "id": "43c8f700-4b6c-43e8-beef-b3944c098e79", 512 | "metadata": { 513 | "tags": [] 514 | }, 515 | "outputs": [], 516 | "source": [ 517 | "# split_string_subset = pair_selection[0].split('-')[0]\n", 518 | "output = []\n", 519 | "for i in range(len(pair_selection)):\n", 520 | " split_string0 = pair_selection[i].split('-')[0]\n", 521 | " split_string1 = pair_selection[i].split('-')[1]\n", 522 | " output.append(split_string0)\n", 523 | " output.append(split_string1)\n", 524 | "\n", 525 | "unique_list = list(set(output))\n", 526 | "unique_list.sort()\n", 527 | "\n", 528 | "len(unique_list)" 529 | ] 530 | }, 531 | { 532 | "cell_type": "code", 533 | "execution_count": null, 534 | "id": "a8c608e6-a61b-4982-99ad-931c765886e6", 535 | "metadata": { 536 | "tags": [] 537 | }, 538 | "outputs": [], 539 | "source": [ 540 | "pair_selection_dict = {}\n", 541 | "\n", 542 | "mother_str = '20180117'\n", 543 | "mother_idx = unique_list.index(mother_str)\n", 544 | "\n", 545 | "for pair in pair_selection:\n", 546 | " \n", 547 | " # Retrieve the first date from a unique and ordered list and use it as the key\n", 548 | " \n", 549 | " key = pair.split('-')[0]\n", 550 | " index_key = date_list.index(key) ##### !!!!!!!!!!!!!!!!!!!!!!!!!!! CHANGED FROM unique_list.index to this because one data pair not combined in this case\n", 551 | " \n", 552 | " value_toAdd = pair.split('-')[1]\n", 553 | " index_value_toAdd = date_list.index(value_toAdd) ##### !!!!!!!!!!!!!!!!!!!!!!!!!!! CHANGED FROM unique_list.index to this because one data pair not combined in this case\n", 554 | " \n", 555 | " if(index_key in pair_selection_dict):\n", 556 | " combination_list = pair_selection_dict[index_key]\n", 557 | " combination_list.append(index_value_toAdd)\n", 558 | " pair_selection_dict[index_key] = combination_list\n", 559 | " else:\n", 560 | " pair_selection_dict[index_key] = [index_value_toAdd]\n", 561 | "\n", 562 | "pair_selection_dict" 563 | ] 564 | }, 565 | { 566 | "cell_type": "markdown", 567 | "id": "d9d0cad5-2d86-4caa-bb53-607f63de4440", 568 | "metadata": {}, 569 | "source": [ 570 | "### Interferogram Generation" 571 | ] 572 | }, 573 | { 574 | "cell_type": "code", 575 | "execution_count": null, 576 | "id": "07096cfb-5171-4044-8d7b-c6c587247be0", 577 | "metadata": { 578 | "tags": [] 579 | }, 580 | "outputs": [], 581 | "source": [ 582 | "# Method 2 - Phasor = total radar measurement per pixel\n", 583 | "\n", 584 | "f_mother = 'slave_rsmp.raw' # Load complex data of mother to obtain amplitude\n", 585 | "\n", 586 | "shape=(num_lines, num_pixels) # obtained from ifgs.res --> nlines = rows ; npixels = columns\n", 587 | "dtype = np.dtype([('re', np.float32), ('im', np.float32)])\n", 588 | "\n", 589 | "mother = [p for p in path.rglob('*slave_rsmp.raw')]\n", 590 | "mother = [p for p in mother if '20180117\\slave_rsmp.raw' in str(p)]\n", 591 | "mother.sort()\n", 592 | "mother\n", 593 | "\n", 594 | "mother = sarxarray.from_binary(mother, shape, dtype=dtype)\n", 595 | "mother = mother.chunk({\"azimuth\":200, \"range\":200, \"time\":1 }) # set custom chunk sizes" 596 | ] 597 | }, 598 | { 599 | "cell_type": "code", 600 | "execution_count": null, 601 | "id": "f6c12c1a-6b3d-4805-8320-ae3015712bc4", 602 | "metadata": { 603 | "tags": [] 604 | }, 605 | "outputs": [], 606 | "source": [ 607 | "def calc_angle(x,y,z):\n", 608 | " func = lambda x,y,z: np.angle((y*np.conj(x))/(z)**2)\n", 609 | " pha = xr.apply_ufunc(func, x, y, z, dask='allowed')\n", 610 | " return pha" 611 | ] 612 | }, 613 | { 614 | "cell_type": "code", 615 | "execution_count": null, 616 | "id": "0ac1e731-cda0-44e4-a541-88bb603fbdd0", 617 | "metadata": { 618 | "tags": [] 619 | }, 620 | "outputs": [], 621 | "source": [ 622 | "def SBAS_structure_m2(i,j):\n", 623 | " \n", 624 | " P0i = phasor.isel(time=i)\n", 625 | " P0j = phasor.isel(time=j)\n", 626 | " \n", 627 | " comp = (P0i*np.conj(P0j))/(mother.amplitude)**2\n", 628 | " amp = np.abs(comp)\n", 629 | " phase = calc_angle(P0j,P0i,mother.amplitude) \n", 630 | " \n", 631 | " stack_SBAS_combo = xr.DataArray.to_dataset(comp, dim=None, name='complex', promote_attrs=False)\n", 632 | " stack_SBAS_combo['amplitude'] = amp\n", 633 | " stack_SBAS_combo['phase'] = phase\n", 634 | " \n", 635 | " return stack_SBAS_combo " 636 | ] 637 | }, 638 | { 639 | "cell_type": "code", 640 | "execution_count": null, 641 | "id": "06ad51e3-fd47-427d-8d6c-108954df287b", 642 | "metadata": { 643 | "tags": [] 644 | }, 645 | "outputs": [], 646 | "source": [ 647 | "# PAIR SELECTION ALGORITHM\n", 648 | "phasor = ifg_stack.complex\n", 649 | "\n", 650 | "t_count = 0\n", 651 | "coords = []\n", 652 | "first_skip = False\n", 653 | "\n", 654 | "i_correction = 0\n", 655 | "j_correction = 0\n", 656 | "\n", 657 | "for i in range(len(ifg_stack.time)):\n", 658 | " \n", 659 | " # Check if key = i exists in dict of pairs\n", 660 | " # else skip/continue\n", 661 | "\n", 662 | " if(i not in pair_selection_dict):\n", 663 | " continue\n", 664 | "\n", 665 | " # Retrieve the list that are paired with key = i\n", 666 | " pairs = pair_selection_dict[i]\n", 667 | " \n", 668 | " # Correction of the indexes after the mother_idx\n", 669 | " j_correction = 0 # correction for the j has to reset after every i-loop\n", 670 | " if(i > mother_idx):\n", 671 | " i_correction = 1\n", 672 | "\n", 673 | " for j in pairs:\n", 674 | " \n", 675 | " if(j > mother_idx):\n", 676 | " j_correction = 1\n", 677 | " \n", 678 | " # mother check\n", 679 | " if(i == mother_idx):\n", 680 | " toAdd = ifg_stack.isel(time=j-j_correction) # CHANGE THIS LINE TO GET CORRECT IFG GET i if mother =j and vice versa.\n", 681 | " elif(j == mother_idx):\n", 682 | " toAdd = ifg_stack.isel(time=i-i_correction)\n", 683 | " else:\n", 684 | " toAdd = SBAS_structure_m2(i-i_correction,j-j_correction)\n", 685 | "\n", 686 | " # If count is zero, create initial stack_SBAS_combo, else concat to stack_SBAS_combo \n", 687 | " if(t_count == 0):\n", 688 | " stack_SBAS_combo = toAdd\n", 689 | " else:\n", 690 | " stack_SBAS_combo = xr.concat([stack_SBAS_combo, toAdd], \"time\")\n", 691 | " \n", 692 | " coords.append(t_count)\n", 693 | " t_count+=1\n", 694 | "\n", 695 | "stack_SBAS_combo = stack_SBAS_combo.assign_coords(time=coords)\n", 696 | "\n", 697 | "stack_SBAS_combo" 698 | ] 699 | }, 700 | { 701 | "cell_type": "markdown", 702 | "id": "8f390bee-eaef-48e5-bbea-340f0e2746ce", 703 | "metadata": {}, 704 | "source": [ 705 | "### Coherence" 706 | ] 707 | }, 708 | { 709 | "cell_type": "code", 710 | "execution_count": null, 711 | "id": "ef2b5b46-eba1-41d8-b20a-e4dfd96e17f5", 712 | "metadata": { 713 | "tags": [] 714 | }, 715 | "outputs": [], 716 | "source": [ 717 | "# Coherence = magnitude of an ifg pixels/product of the magnitudes of the original image’s pixels.\n", 718 | "\n", 719 | "f_mother = 'slave_rsmp.raw' # Load complex data of mother to obtain amplitude\n", 720 | "\n", 721 | "shape=(num_lines, num_pixels) # obtained from ifgs.res --> nlines = rows ; npixels = columns\n", 722 | "dtype = np.dtype([('re', np.float32), ('im', np.float32)])\n", 723 | "\n", 724 | "list_daughters = [p for p in path.rglob('*slave_rsmp.raw')]\n", 725 | "list_daughters.sort()\n", 726 | "\n", 727 | "# # Path to remove\n", 728 | "\n", 729 | "path_to_mother_rsmp = Path('caroline/Share/projects/antilles/stacks/alos2/alos2_sm3_p36_f340/process_StEustatius_fixed_mtiming_dembased/process_StEustatius_fixed_mtiming_dembased_20180117/20180117/slave_rsmp.raw')\n", 730 | "\n", 731 | "# # Convert path_to_remove to a string\n", 732 | "\n", 733 | "string_to_remove = str(path_to_mother_rsmp)\n", 734 | "\n", 735 | "# # Filter out the path based on the string\n", 736 | "\n", 737 | "list_daughters = [path for path in list_daughters if str(path) != string_to_remove]\n", 738 | "list_daughters\n", 739 | "\n", 740 | "daughters_stack = sarxarray.from_binary(list_daughters, shape, dtype=dtype)\n", 741 | "daughters_stack = daughters_stack.chunk({\"azimuth\":200, \"range\":200, \"time\":1 }) # set custom chunk sizes" 742 | ] 743 | }, 744 | { 745 | "cell_type": "code", 746 | "execution_count": null, 747 | "id": "ad4d3bff-c6b6-45e1-921e-46f8023610c1", 748 | "metadata": { 749 | "tags": [] 750 | }, 751 | "outputs": [], 752 | "source": [ 753 | "# Slice the daughters_stack data array into two parts along the t-dim\n", 754 | "\n", 755 | "daughters_stack_before = daughters_stack.isel(time=slice(None, mother_idx))\n", 756 | "daughters_stack_after = daughters_stack.isel(time=slice(mother_idx, None))\n", 757 | "\n", 758 | "# Concatenate the two parts with the mother data\n", 759 | "\n", 760 | "daughter_mother_stack_sub = xr.concat([daughters_stack_before, mother],dim=\"time\")\n", 761 | "daughter_mother_stack = xr.concat([daughter_mother_stack_sub, daughters_stack_after],dim=\"time\")\n", 762 | "daughter_mother_stack = daughter_mother_stack.assign_coords(time=np.arange(0,len(daughters_stack.time)+1,1))\n", 763 | "daughter_mother_stack" 764 | ] 765 | }, 766 | { 767 | "cell_type": "code", 768 | "execution_count": null, 769 | "id": "77ccd076-16f0-4fa8-b0d4-378a4634a6a2", 770 | "metadata": { 771 | "tags": [] 772 | }, 773 | "outputs": [], 774 | "source": [ 775 | "# Find zeros in the daughter_mother_stack and alter zero_replacement accordingly\n", 776 | "\n", 777 | "zero_replacement = 0.01\n", 778 | "\n", 779 | "for t in range(len(daughter_mother_stack.time)):\n", 780 | " if (daughter_mother_stack.isel(time=t).amplitude == 0).any(dim=(\"azimuth\", \"range\")):\n", 781 | " print(f\"mother.amplitude contains zero values for time {t}.\")\n", 782 | " \n", 783 | " # Get the amplitude values for each t-dim\n", 784 | " amplitude_values = daughter_mother_stack[\"amplitude\"].isel(time=t).values\n", 785 | " \n", 786 | " # Replace zeros with the set replacement value\n", 787 | " amplitude_values[amplitude_values == 0] = zero_replacement\n", 788 | " # print(daughter_mother_stack[\"amplitude\"][t, :, :].shape)\n", 789 | " \n", 790 | " # Update the dataset\n", 791 | " daughter_mother_stack.amplitude.loc[dict(time=t)] = amplitude_values\n", 792 | " else:\n", 793 | " print(f\"No zeros found for time {t}\")" 794 | ] 795 | }, 796 | { 797 | "cell_type": "code", 798 | "execution_count": null, 799 | "id": "7ead08a7-d263-4366-85e6-de0c54d6362d", 800 | "metadata": { 801 | "tags": [] 802 | }, 803 | "outputs": [], 804 | "source": [ 805 | "def moving_average(data, N):\n", 806 | " \n", 807 | " # Determine the number of rows & columns in the output raster\n", 808 | " \n", 809 | " nrows = shape[0] - N[0] + 1\n", 810 | " ncols = shape[1] - N[1] + 1\n", 811 | " \n", 812 | " # Specify a different window size in x and y direction\n", 813 | " window_size = (22,8)\n", 814 | "\n", 815 | " # Apply the uniform filter\n", 816 | " filtered_arr = uniform_filter(data, size=window_size)\n", 817 | " \n", 818 | " return filtered_arr, nrows, ncols" 819 | ] 820 | }, 821 | { 822 | "cell_type": "code", 823 | "execution_count": null, 824 | "id": "61a09b7a-2844-403e-9c3b-ad30b33a31f9", 825 | "metadata": { 826 | "tags": [] 827 | }, 828 | "outputs": [], 829 | "source": [ 830 | "def calc_mags_SLC(SLC_data, windowsize):\n", 831 | " av_mag_SLC = [] \n", 832 | " \n", 833 | " for i in range(len(SLC_data.time)):\n", 834 | " mag_A_i, nrows, ncols = moving_average((SLC_data.amplitude.isel(time=i).values)**2, windowsize)\n", 835 | " av_mag_SLC.append(mag_A_i)\n", 836 | " \n", 837 | " return av_mag_SLC " 838 | ] 839 | }, 840 | { 841 | "cell_type": "code", 842 | "execution_count": null, 843 | "id": "83906ba7-9482-4b66-89a4-9414d20de1fa", 844 | "metadata": { 845 | "tags": [] 846 | }, 847 | "outputs": [], 848 | "source": [ 849 | "def calc_mav_ifg(ifg_data, windowsize):\n", 850 | " av_I = [] \n", 851 | " \n", 852 | " for i in range(len(ifg_data.time)):\n", 853 | " \n", 854 | " # calculate moving average of the combinations\n", 855 | " mag_I_count, nrows_I, ncols_I = moving_average(ifg_data.complex.isel(time=i).values, windowsize)\n", 856 | " av_I.append(mag_I_count)\n", 857 | " \n", 858 | " return av_I " 859 | ] 860 | }, 861 | { 862 | "cell_type": "code", 863 | "execution_count": null, 864 | "id": "21b3e630-5814-443f-8be3-5c23520560e9", 865 | "metadata": { 866 | "tags": [] 867 | }, 868 | "outputs": [], 869 | "source": [ 870 | "## This code needs to run once\n", 871 | "\n", 872 | "# Calculate mag for all the 11 times\n", 873 | "av_mag_SLC = calc_mags_SLC(daughter_mother_stack, np.array([22,8]))\n", 874 | "\n", 875 | "# Calculate mag for all the 32 times\n", 876 | "av_I = calc_mav_ifg(stack_SBAS_combo, np.array([22,8]))\n", 877 | "\n", 878 | "# Create initial data variables\n", 879 | "av_I_first, nrows_first, ncols_first = moving_average(stack_SBAS_combo.complex.isel(time=0).values, np.array([22,8]))\n", 880 | "first_coh = np.abs(av_I_first/(np.sqrt(av_mag_SLC[0]) * np.sqrt(av_mag_SLC[1])))" 881 | ] 882 | }, 883 | { 884 | "cell_type": "code", 885 | "execution_count": null, 886 | "id": "4f220daa-d8d6-41cb-b1b7-c6a0fb01c0c6", 887 | "metadata": { 888 | "tags": [] 889 | }, 890 | "outputs": [], 891 | "source": [ 892 | "# New coherence\n", 893 | "\n", 894 | "def calc_coherence(first_coh, it_length, av_I, av_Ai, nrows, ncols, date_list):\n", 895 | "\n", 896 | " #################################################################\n", 897 | " # INPUT:\n", 898 | " # first_coh = first coherence I01, to set up xarray datastructure\n", 899 | " # av_I = phasor (ifg.complex) post moving average\n", 900 | " # av_A0 = original amplitude SLC's post moving average\n", 901 | " \n", 902 | " # OUTPUT:\n", 903 | " # coh_combo_stack = coherence ALL possible combo's [numpy array]\n", 904 | " #################################################################\n", 905 | " \n", 906 | " # prepare list with dates; start by filling first one\n", 907 | " \n", 908 | " date_title = []\n", 909 | " \n", 910 | " first_date = date_list[0] + '-' + date_list[1]\n", 911 | " date_title.insert(0, first_date)\n", 912 | " \n", 913 | " # Create data array\n", 914 | " shape_subset = daughter_mother_stack.dims['azimuth'],daughter_mother_stack.dims['range']\n", 915 | " coh_combo_stack = xr.DataArray(first_coh, \n", 916 | " coords={'azimuth': np.arange(0,shape_subset[0], 1, dtype=int),\n", 917 | " 'range': np.arange(0, shape_subset[1], 1, dtype=int)}, \n", 918 | " dims=[\"azimuth\",\"range\"])\n", 919 | " count = 1\n", 920 | " coords = []\n", 921 | " coords.append(count-1)\n", 922 | " \n", 923 | " first_skipped = False\n", 924 | " \n", 925 | " \n", 926 | "# for i in range(len(pair_selection_dict)):\n", 927 | " for i in pair_selection_dict:\n", 928 | " pairs = pair_selection_dict[i]\n", 929 | " for j in pairs:\n", 930 | " \n", 931 | " # check to skip combinations with the same time and only do unique combinations\n", 932 | " if(j > i):\n", 933 | " \n", 934 | " # first is already present\n", 935 | " if(first_skipped):\n", 936 | " \n", 937 | "# # calculate mag of the combinations\n", 938 | "# mag_I_count, nrows_I, ncols_I = moving_average(stack_SBAS_combo.amplitude.isel(time=count).values, np.array([20,4]))\n", 939 | "\n", 940 | " # calc coh\n", 941 | " coherence = np.abs(av_I[count])/(np.sqrt(av_Ai[i]) * np.sqrt(av_Ai[j]))\n", 942 | " \n", 943 | " # prep date titles\n", 944 | " date = date_list[i] + '-' + date_list[j]\n", 945 | " date_title.append(date)\n", 946 | " # date_title = 0\n", 947 | " \n", 948 | " # add no data values to obtain same size as input shape\n", 949 | " coh_toAdd = np.zeros((shape_subset[0],shape_subset[1]))\n", 950 | " coh_toAdd[:] = np.nan\n", 951 | " coh_toAdd[0:coherence.shape[0], 0:coherence.shape[1]] = coherence\n", 952 | " \n", 953 | " # convert to data-array structure\n", 954 | " coh_toAdd = xr.DataArray(coh_toAdd, \n", 955 | " coords={'azimuth': np.arange(0, shape_subset[0], 1, dtype=int),\n", 956 | " 'range': np.arange(0, shape_subset[1], 1, dtype=int)}, \n", 957 | " dims=[\"azimuth\",\"range\"])\n", 958 | " \n", 959 | " # Add coh to the data-array\n", 960 | " coh_combo_stack = xr.concat([coh_combo_stack, coh_toAdd], dim=\"time\")\n", 961 | " \n", 962 | "\n", 963 | " # Go to the next combination\n", 964 | " coords.append(count)\n", 965 | " count+=1 \n", 966 | " \n", 967 | " # Make true after the first combination: i=0, j=1\n", 968 | " first_skipped = True\n", 969 | " \n", 970 | " coh_combo_stack = coh_combo_stack.astype(np.float32)\n", 971 | " coh_combo_stack = coh_combo_stack.assign_coords(time=coords)\n", 972 | " coh_combo_stack = xr.DataArray.to_dataset(coh_combo_stack, dim=None, name='coherence', promote_attrs=False)\n", 973 | " \n", 974 | " return coh_combo_stack, date_title" 975 | ] 976 | }, 977 | { 978 | "cell_type": "code", 979 | "execution_count": null, 980 | "id": "357e8677-1bf5-43c2-b5ca-c32ef8cb68c7", 981 | "metadata": { 982 | "tags": [] 983 | }, 984 | "outputs": [], 985 | "source": [ 986 | "coh_combo_stack, date_title = calc_coherence(first_coh, len(pair_selection_dict), av_I, av_mag_SLC, nrows_first, ncols_first, date_list)" 987 | ] 988 | }, 989 | { 990 | "cell_type": "code", 991 | "execution_count": null, 992 | "id": "64ad0d31-d7b7-4612-8b7a-12fb31fa0451", 993 | "metadata": { 994 | "tags": [] 995 | }, 996 | "outputs": [], 997 | "source": [ 998 | "np.nanmax(coh_combo_stack.coherence.isel(time=0).values)" 999 | ] 1000 | }, 1001 | { 1002 | "cell_type": "code", 1003 | "execution_count": null, 1004 | "id": "cf205ac2", 1005 | "metadata": {}, 1006 | "outputs": [], 1007 | "source": [ 1008 | "max_idx = coh_combo_stack['coherence'].isel(time=0).argmax(['azimuth', 'range'])\n", 1009 | "int(max_idx['azimuth'].values), int(max_idx['range'].values)" 1010 | ] 1011 | }, 1012 | { 1013 | "cell_type": "code", 1014 | "execution_count": null, 1015 | "id": "aeac7a87-2173-42b8-9adf-73d2b3f0fc94", 1016 | "metadata": { 1017 | "tags": [] 1018 | }, 1019 | "outputs": [], 1020 | "source": [ 1021 | "# first_coh = np.abs(av_I_first/(np.sqrt(av_mag_SLC[0]) * np.sqrt(av_mag_SLC[1])))\n", 1022 | "\n", 1023 | "np.abs(av_I[0][int(max_idx['azimuth'].values),int(max_idx['range'].values)])/(np.sqrt(av_mag_SLC[0][int(max_idx['azimuth'].values),int(max_idx['range'].values)])*np.sqrt(av_mag_SLC[1][int(max_idx['azimuth'].values),int(max_idx['range'].values)]))" 1024 | ] 1025 | }, 1026 | { 1027 | "cell_type": "code", 1028 | "execution_count": null, 1029 | "id": "642d3c23-d157-43d0-8d14-f93361100a9a", 1030 | "metadata": { 1031 | "tags": [] 1032 | }, 1033 | "outputs": [], 1034 | "source": [ 1035 | "plt.imshow(coh_combo_stack.coherence.isel(time=1))\n", 1036 | "coh_combo_stack.coherence.isel(time=1).plot(robust=True, cmap='bone')" 1037 | ] 1038 | }, 1039 | { 1040 | "cell_type": "code", 1041 | "execution_count": null, 1042 | "id": "eb56336e-5dbc-41ca-aaaf-920c9b24d8d7", 1043 | "metadata": { 1044 | "tags": [] 1045 | }, 1046 | "outputs": [], 1047 | "source": [ 1048 | "plt.hist(coh_combo_stack.coherence.isel(time=0).values)" 1049 | ] 1050 | }, 1051 | { 1052 | "cell_type": "markdown", 1053 | "id": "613ecc66-a052-4f3c-881a-69e48bf32349", 1054 | "metadata": {}, 1055 | "source": [ 1056 | "### Create interferograms from SLC's" 1057 | ] 1058 | }, 1059 | { 1060 | "cell_type": "code", 1061 | "execution_count": null, 1062 | "id": "76b15e05-924c-4339-8408-2c77c747fe02", 1063 | "metadata": { 1064 | "tags": [] 1065 | }, 1066 | "outputs": [], 1067 | "source": [ 1068 | "def calc_angle(x,y):\n", 1069 | " func = lambda x,y: np.angle((y*np.conj(x)))\n", 1070 | " pha = xr.apply_ufunc(func, x, y, dask='allowed')\n", 1071 | " return pha" 1072 | ] 1073 | }, 1074 | { 1075 | "cell_type": "code", 1076 | "execution_count": null, 1077 | "id": "ac6a48c2-8706-4b58-96a7-c6aa05933584", 1078 | "metadata": { 1079 | "tags": [] 1080 | }, 1081 | "outputs": [], 1082 | "source": [ 1083 | "P_mother = mother.complex.isel(time=0)\n", 1084 | "\n", 1085 | "t_count = 0\n", 1086 | "for i in range(len(daughters_stack.time)):\n", 1087 | " \n", 1088 | " P_daughter = daughters_stack.complex.isel(time=i)\n", 1089 | "\n", 1090 | " comp = P_mother*np.conj(P_daughter)\n", 1091 | " amp = np.abs(comp)\n", 1092 | " phase = calc_angle(P_daughter,P_mother)\n", 1093 | " \n", 1094 | " stack_compare = xr.DataArray.to_dataset(comp, dim=None, name='complex', promote_attrs=False)\n", 1095 | " stack_compare['amplitude'] = amp\n", 1096 | " stack_compare['phase'] = phase\n", 1097 | " \n", 1098 | " stack_compare.coords['time'] = ('time', [i])\n", 1099 | " \n", 1100 | " if t_count == 0:\n", 1101 | " ifg_stack_compare = stack_compare\n", 1102 | " else:\n", 1103 | " ifg_stack_compare = xr.concat([ifg_stack_compare, stack_compare], \"time\")\n", 1104 | " \n", 1105 | " t_count += 1" 1106 | ] 1107 | }, 1108 | { 1109 | "cell_type": "code", 1110 | "execution_count": null, 1111 | "id": "f3cb8df3", 1112 | "metadata": {}, 1113 | "outputs": [], 1114 | "source": [ 1115 | "ifg_stack_compare" 1116 | ] 1117 | }, 1118 | { 1119 | "cell_type": "code", 1120 | "execution_count": null, 1121 | "id": "1fee2653-de57-412e-be7c-62c4ec1b9423", 1122 | "metadata": { 1123 | "tags": [] 1124 | }, 1125 | "outputs": [], 1126 | "source": [ 1127 | "# Using cint_srd from Doris\n", 1128 | "\n", 1129 | "plt.imshow(ifg_stack.amplitude.isel(time=0))\n", 1130 | "ifg_stack.amplitude.isel(time=0).plot(robust=True, cmap='jet') # cmap='jet'" 1131 | ] 1132 | }, 1133 | { 1134 | "cell_type": "code", 1135 | "execution_count": null, 1136 | "id": "9fb844d8-8a8d-4d5b-b66e-39043dafdc5d", 1137 | "metadata": { 1138 | "tags": [] 1139 | }, 1140 | "outputs": [], 1141 | "source": [ 1142 | "# Using SLC's from Doris\n", 1143 | "\n", 1144 | "plt.imshow(ifg_stack_compare.amplitude.isel(time=0))\n", 1145 | "ifg_stack_compare.amplitude.isel(time=0).plot(robust=True, cmap='jet') # cmap='jet'" 1146 | ] 1147 | }, 1148 | { 1149 | "cell_type": "code", 1150 | "execution_count": null, 1151 | "id": "5eab07e9-87b0-4dda-8a81-08328b2a3737", 1152 | "metadata": { 1153 | "tags": [] 1154 | }, 1155 | "outputs": [], 1156 | "source": [ 1157 | "diff_amp = ifg_stack_compare.amplitude.isel(time=0) - ifg_stack.amplitude.isel(time=0)\n", 1158 | "\n", 1159 | "plt.imshow(diff_amp)\n", 1160 | "diff_amp.plot(robust=True, cmap='jet') # cmap='jet\n", 1161 | "plt.show()" 1162 | ] 1163 | }, 1164 | { 1165 | "cell_type": "markdown", 1166 | "id": "dffb9249", 1167 | "metadata": {}, 1168 | "source": [ 1169 | "**Repeat steps to calculate new SBAS combinations & corresponding coherence** " 1170 | ] 1171 | }, 1172 | { 1173 | "cell_type": "code", 1174 | "execution_count": null, 1175 | "id": "e449a4ec", 1176 | "metadata": { 1177 | "tags": [] 1178 | }, 1179 | "outputs": [], 1180 | "source": [ 1181 | "def calc_angle(x,y,z):\n", 1182 | " func = lambda x,y,z: np.angle((y*np.conj(x))/(z)**2)\n", 1183 | " pha = xr.apply_ufunc(func, x, y, z, dask='allowed')\n", 1184 | " return pha" 1185 | ] 1186 | }, 1187 | { 1188 | "cell_type": "code", 1189 | "execution_count": null, 1190 | "id": "8afce7ef", 1191 | "metadata": {}, 1192 | "outputs": [], 1193 | "source": [ 1194 | "# PAIR SELECTION ALGORITHM\n", 1195 | "phasor = ifg_stack_compare.complex\n", 1196 | "\n", 1197 | "t_count = 0\n", 1198 | "coords = []\n", 1199 | "first_skip = False\n", 1200 | "\n", 1201 | "i_correction = 0\n", 1202 | "j_correction = 0\n", 1203 | "\n", 1204 | "for i in range(len(ifg_stack_compare.time)):\n", 1205 | " \n", 1206 | " # Check if key = i exists in dict of pairs\n", 1207 | " # else skip/continue\n", 1208 | "\n", 1209 | " if(i not in pair_selection_dict):\n", 1210 | " continue\n", 1211 | "\n", 1212 | " # Retrieve the list that are paired with key = i\n", 1213 | " pairs = pair_selection_dict[i]\n", 1214 | " \n", 1215 | " # Correction of the indexes after the mother_idx\n", 1216 | " j_correction = 0 # correction for the j has to reset after every i-loop\n", 1217 | " if(i > mother_idx):\n", 1218 | " i_correction = 1\n", 1219 | "\n", 1220 | " for j in pairs:\n", 1221 | " \n", 1222 | " if(j > mother_idx):\n", 1223 | " j_correction = 1\n", 1224 | " \n", 1225 | " # mother check\n", 1226 | " if(i == mother_idx):\n", 1227 | " toAdd = ifg_stack_compare.isel(time=j-j_correction) # CHANGE THIS LINE TO GET CORRECT IFG GET i if mother =j and vice versa.\n", 1228 | " elif(j == mother_idx):\n", 1229 | " toAdd = ifg_stack_compare.isel(time=i-i_correction)\n", 1230 | " else:\n", 1231 | " toAdd = SBAS_structure_m2(i-i_correction,j-j_correction)\n", 1232 | "\n", 1233 | " # If count is zero, create initial stack_SBAS_combo, else concat to stack_SBAS_combo \n", 1234 | " if(t_count == 0):\n", 1235 | " stack_SBAS_combo_compare = toAdd\n", 1236 | " else:\n", 1237 | " stack_SBAS_combo_compare = xr.concat([stack_SBAS_combo_compare, toAdd], \"time\")\n", 1238 | " \n", 1239 | " coords.append(t_count)\n", 1240 | " t_count+=1\n", 1241 | "\n", 1242 | "stack_SBAS_combo_compare = stack_SBAS_combo_compare.assign_coords(time=coords)\n", 1243 | "\n", 1244 | "stack_SBAS_combo_compare" 1245 | ] 1246 | }, 1247 | { 1248 | "cell_type": "code", 1249 | "execution_count": null, 1250 | "id": "aefcb5a0", 1251 | "metadata": { 1252 | "tags": [] 1253 | }, 1254 | "outputs": [], 1255 | "source": [ 1256 | "## This code needs to run once\n", 1257 | "\n", 1258 | "# Calculate mag for all the 11 times\n", 1259 | "av_mag_SLC = calc_mags_SLC(daughter_mother_stack, np.array([22,8]))\n", 1260 | "\n", 1261 | "# Calculate mag for all the 32 times\n", 1262 | "av_I = calc_mav_ifg(stack_SBAS_combo_compare, np.array([22,8]))\n", 1263 | "\n", 1264 | "# Create initial data variables\n", 1265 | "av_I_first, nrows_first, ncols_first = moving_average(stack_SBAS_combo_compare.complex.isel(time=0).values, np.array([22,8]))\n", 1266 | "first_coh = np.abs(av_I_first/(np.sqrt(av_mag_SLC[0]) * np.sqrt(av_mag_SLC[1])))" 1267 | ] 1268 | }, 1269 | { 1270 | "cell_type": "code", 1271 | "execution_count": null, 1272 | "id": "acd3aeea", 1273 | "metadata": { 1274 | "tags": [] 1275 | }, 1276 | "outputs": [], 1277 | "source": [ 1278 | "coh_combo_stack, date_title = calc_coherence(first_coh, len(pair_selection_dict), av_I, av_mag_SLC, nrows_first, ncols_first, date_list)" 1279 | ] 1280 | }, 1281 | { 1282 | "cell_type": "code", 1283 | "execution_count": null, 1284 | "id": "6a88deed", 1285 | "metadata": { 1286 | "tags": [] 1287 | }, 1288 | "outputs": [], 1289 | "source": [ 1290 | "np.nanmax(coh_combo_stack.coherence.isel(time=0).values)" 1291 | ] 1292 | }, 1293 | { 1294 | "cell_type": "code", 1295 | "execution_count": null, 1296 | "id": "7d522936", 1297 | "metadata": {}, 1298 | "outputs": [], 1299 | "source": [ 1300 | "max_idx = coh_combo_stack['coherence'].isel(time=0).argmax(['azimuth', 'range'])\n", 1301 | "int(max_idx['azimuth'].values), int(max_idx['range'].values)" 1302 | ] 1303 | }, 1304 | { 1305 | "cell_type": "code", 1306 | "execution_count": null, 1307 | "id": "a4dd2ef2", 1308 | "metadata": { 1309 | "tags": [] 1310 | }, 1311 | "outputs": [], 1312 | "source": [ 1313 | "# first_coh = np.abs(av_I_first/(np.sqrt(av_mag_SLC[0]) * np.sqrt(av_mag_SLC[1])))\n", 1314 | "\n", 1315 | "np.abs(av_I[0][int(max_idx['azimuth'].values),int(max_idx['range'].values)])/(np.sqrt(av_mag_SLC[0][int(max_idx['azimuth'].values),int(max_idx['range'].values)])*np.sqrt(av_mag_SLC[1][int(max_idx['azimuth'].values),int(max_idx['range'].values)]))" 1316 | ] 1317 | }, 1318 | { 1319 | "cell_type": "code", 1320 | "execution_count": null, 1321 | "id": "5d659785", 1322 | "metadata": { 1323 | "tags": [] 1324 | }, 1325 | "outputs": [], 1326 | "source": [ 1327 | "plt.imshow(coh_combo_stack.coherence.isel(time=1))\n", 1328 | "coh_combo_stack.coherence.isel(time=1).plot(robust=True, cmap='bone')" 1329 | ] 1330 | }, 1331 | { 1332 | "cell_type": "code", 1333 | "execution_count": null, 1334 | "id": "bcccf9bf", 1335 | "metadata": {}, 1336 | "outputs": [], 1337 | "source": [ 1338 | "plt.hist(coh_combo_stack.coherence.isel(time=0).values)" 1339 | ] 1340 | } 1341 | ], 1342 | "metadata": { 1343 | "kernelspec": { 1344 | "display_name": "Python 3 (ipykernel)", 1345 | "language": "python", 1346 | "name": "python3" 1347 | }, 1348 | "language_info": { 1349 | "codemirror_mode": { 1350 | "name": "ipython", 1351 | "version": 3 1352 | }, 1353 | "file_extension": ".py", 1354 | "mimetype": "text/x-python", 1355 | "name": "python", 1356 | "nbconvert_exporter": "python", 1357 | "pygments_lexer": "ipython3", 1358 | "version": "3.10.12" 1359 | } 1360 | }, 1361 | "nbformat": 4, 1362 | "nbformat_minor": 5 1363 | } 1364 | -------------------------------------------------------------------------------- /examples/archive/ALOS2_sarxarray_datamodel.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "id": "0000f704", 7 | "metadata": {}, 8 | "source": [ 9 | "
\n", 10 | " \n", 11 | "
\n", 12 | "\n", 13 | "### InSAR data model based on xarray(/dask)" 14 | ] 15 | }, 16 | { 17 | "attachments": {}, 18 | "cell_type": "markdown", 19 | "id": "dd55e99c", 20 | "metadata": {}, 21 | "source": [ 22 | "**Steps:**\n", 23 | "- Load a raw interferogram (complex(Re, Im)) in binary format into a `xarray.Dataset` object\n", 24 | "- Visualize the phase\n", 25 | "- Load raw coherence into a `xarray.Dataset` object" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "id": "2a2dde59", 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "import sarxarray\n", 36 | "import numpy as np\n", 37 | "from pathlib import Path\n", 38 | "import matplotlib.pyplot as plt\n", 39 | "\n", 40 | "from tqdm import tqdm\n", 41 | "from skimage.util import view_as_windows\n", 42 | "import xarray as xr" 43 | ] 44 | }, 45 | { 46 | "attachments": {}, 47 | "cell_type": "markdown", 48 | "id": "b061f841", 49 | "metadata": {}, 50 | "source": [ 51 | "**Specify path of file location**" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "id": "f2c73db6", 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "path = Path('data/') # CHANGE to local data directory" 62 | ] 63 | }, 64 | { 65 | "attachments": {}, 66 | "cell_type": "markdown", 67 | "id": "68688461", 68 | "metadata": {}, 69 | "source": [ 70 | "### Interferogram\n", 71 | "\n", 72 | "**List the interferograms (.raw files) to be read**" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": null, 78 | "id": "6a41a772", 79 | "metadata": {}, 80 | "outputs": [], 81 | "source": [ 82 | "f_ifg = 'cint_srd.raw' # string\n", 83 | "\n", 84 | "list_ifgs = [p/f_ifg for p in path.rglob(\"????????\")]\n", 85 | "list_ifgs" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "id": "39f2b3b1", 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [ 95 | "# Create list with dates\n", 96 | "# Mother = 20180108\n", 97 | "\n", 98 | "date_list = []\n", 99 | "for i in range(len(list_ifgs)):\n", 100 | " prep_date_string = str(list_ifgs[i])\n", 101 | " date = prep_date_string.split('\\\\')[3]\n", 102 | " date_list.append(date)\n", 103 | "date_list" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": null, 109 | "id": "5f427128", 110 | "metadata": {}, 111 | "outputs": [], 112 | "source": [ 113 | "# Take the mother-mother ifg out\n", 114 | "\n", 115 | "mother_str = '20180108'\n", 116 | "mother_idx = date_list.index(mother_str)\n", 117 | "\n", 118 | "list_ifgs_without_mother = list_ifgs[0:mother_idx]+list_ifgs[(mother_idx+1):10]\n", 119 | "list_ifgs_without_mother" 120 | ] 121 | }, 122 | { 123 | "attachments": {}, 124 | "cell_type": "markdown", 125 | "id": "f804a2db", 126 | "metadata": {}, 127 | "source": [ 128 | "**Metadata**\n", 129 | "\n", 130 | "Information about the shape can be found in the ifgs.res files and are denoted using 'nlines' and 'npixels', respectively." 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": null, 136 | "id": "d5001030", 137 | "metadata": {}, 138 | "outputs": [], 139 | "source": [ 140 | "# Metadata\n", 141 | "\n", 142 | "shape=(5500, 1800) # obtained from ifgs.res --> nlines = rows ; npixels = columns\n", 143 | "dtype = np.dtype([('re', np.float32), ('im', np.float32)])" 144 | ] 145 | }, 146 | { 147 | "attachments": {}, 148 | "cell_type": "markdown", 149 | "id": "2391bec2", 150 | "metadata": {}, 151 | "source": [ 152 | "**Loading the raw interferogram into a `xarray.Dataset`**" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": null, 158 | "id": "068c9e9e", 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "# Create xarray.Dataset object from .raw file\n", 163 | "\n", 164 | "ifg_stack = sarxarray.from_binary(list_ifgs_without_mother, shape, dtype=dtype)\n", 165 | "ifg_stack = ifg_stack.chunk({\"azimuth\":500, \"range\":500, \"time\":1 }) # set custom chunk sizes\n", 166 | "\n", 167 | "ifg_stack" 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "execution_count": null, 173 | "id": "90bbe917", 174 | "metadata": {}, 175 | "outputs": [], 176 | "source": [ 177 | "phase = ifg_stack.phase\n", 178 | "amplitude = ifg_stack.amplitude\n", 179 | "phasor = ifg_stack.complex # contains P00, P01, P02" 180 | ] 181 | }, 182 | { 183 | "cell_type": "code", 184 | "execution_count": null, 185 | "id": "1713b6ff", 186 | "metadata": {}, 187 | "outputs": [], 188 | "source": [ 189 | "phase" 190 | ] 191 | }, 192 | { 193 | "attachments": {}, 194 | "cell_type": "markdown", 195 | "id": "35fbf1d5", 196 | "metadata": {}, 197 | "source": [ 198 | "**Visualize the phase**" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "id": "f62f6ba0", 205 | "metadata": {}, 206 | "outputs": [], 207 | "source": [ 208 | "# Visualize first figure\n", 209 | "\n", 210 | "fig,ax = plt.subplots(1,1)\n", 211 | "phase_i = phase.isel(time=1)\n", 212 | "ax.imshow(phase_i)\n", 213 | "phase_i.plot(robust=True, ax=ax, cmap='jet') # cmap='jet'" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "id": "fc138b15", 220 | "metadata": {}, 221 | "outputs": [], 222 | "source": [ 223 | "# Visualize 3/9 figures\n", 224 | "\n", 225 | "phase_ex = ifg_stack.phase.isel(time=slice(3,6)) \n", 226 | "phase_ex.plot(x=\"range\", y=\"azimuth\", col=\"time\", col_wrap=3, cmap='jet')" 227 | ] 228 | }, 229 | { 230 | "cell_type": "code", 231 | "execution_count": null, 232 | "id": "dcbd8ad8", 233 | "metadata": {}, 234 | "outputs": [], 235 | "source": [ 236 | "fig, axs = plt.subplots(3,3, figsize=(25, 25), facecolor='w', edgecolor='k')\n", 237 | "fig.subplots_adjust(hspace = .25, wspace=.1)\n", 238 | "\n", 239 | "axs = axs.ravel()\n", 240 | "\n", 241 | "for i in tqdm(range(len(ifg_stack.time))):\n", 242 | " phase_i = phase.isel(time=i)\n", 243 | " axs[i].imshow(phase_i)\n", 244 | " phase_i.plot(robust=True, ax=axs[i], cmap='jet') # cmap='jet'\n" 245 | ] 246 | }, 247 | { 248 | "attachments": {}, 249 | "cell_type": "markdown", 250 | "id": "922c88c2", 251 | "metadata": {}, 252 | "source": [ 253 | "**MRM (Mean Reflection Map)**" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": null, 259 | "id": "1eca61bb", 260 | "metadata": {}, 261 | "outputs": [], 262 | "source": [ 263 | "# Creating a MRM (Mean Reflection Map) of a subset of the stack\n", 264 | "\n", 265 | "mrm = ifg_stack.slcstack.mrm() # go 3D to 2D --> only azimuth & range for amplitude\n", 266 | "mrm" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": null, 272 | "id": "5a3a705e", 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "mrm_subset = mrm[1000:2000, 500:2000] # Create subset using 2 indexes: azimuth & range\n", 277 | "\n", 278 | "mrm_subset = mrm_subset.compute() # manually trigger loading of this array’s data from disk or a remote source into memory and return a new array\n", 279 | "mrm_subset" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": null, 285 | "id": "c057d232", 286 | "metadata": {}, 287 | "outputs": [], 288 | "source": [ 289 | "# Visualize\n", 290 | "\n", 291 | "fig, ax = plt.subplots()\n", 292 | "ax.imshow(mrm_subset)\n", 293 | "mrm_subset.plot(robust=True, ax=ax)" 294 | ] 295 | }, 296 | { 297 | "attachments": {}, 298 | "cell_type": "markdown", 299 | "id": "5383bc10", 300 | "metadata": {}, 301 | "source": [ 302 | "**Load raw coherence**" 303 | ] 304 | }, 305 | { 306 | "cell_type": "code", 307 | "execution_count": null, 308 | "id": "19f49546", 309 | "metadata": {}, 310 | "outputs": [], 311 | "source": [ 312 | "f_coh = 'coherence.raw' # string\n", 313 | "\n", 314 | "list_coh = [p/f_coh for p in path.rglob(\"????????\")]\n", 315 | "list_coh = list_coh[0:mother_idx] + list_coh[mother_idx+1:10] # do not include coherence of mother-mother ifg" 316 | ] 317 | }, 318 | { 319 | "cell_type": "code", 320 | "execution_count": null, 321 | "id": "498a84a1", 322 | "metadata": {}, 323 | "outputs": [], 324 | "source": [ 325 | "# Metadata\n", 326 | "\n", 327 | "shape=(275, 450) # obtained from ifgs.res --> nlines = rows ; npixels = columns\n", 328 | "\n", 329 | "# Create xarray.Dataset object from .raw file\n", 330 | "\n", 331 | "coh_stack = sarxarray.from_binary(list_coh, shape, dtype=np.float32)\n", 332 | "coh_stack = coh_stack.chunk({\"azimuth\":100, \"range\":100, \"time\":1 }) # set custom chunk sizes\n", 333 | "coh_stack" 334 | ] 335 | }, 336 | { 337 | "cell_type": "code", 338 | "execution_count": null, 339 | "id": "c42d0256", 340 | "metadata": {}, 341 | "outputs": [], 342 | "source": [ 343 | "# Visualize coherence\n", 344 | "\n", 345 | "fig,ax = plt.subplots(1,1)\n", 346 | "\n", 347 | "for i in tqdm(range(len(coh_stack.time))):\n", 348 | " coh_i = coh_stack.amplitude.isel(time=i)\n", 349 | " plt.imshow(coh_i)\n", 350 | " coh_i.plot(robust=True, cmap='bone',vmax=0.7,vmin=0) # cmap='jet'\n", 351 | " plt.show() " 352 | ] 353 | }, 354 | { 355 | "attachments": {}, 356 | "cell_type": "markdown", 357 | "id": "7c5def54", 358 | "metadata": {}, 359 | "source": [ 360 | "**Load slave_rsmp - to get original amplitude of SLC's e.g.**" 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": null, 366 | "id": "c055740f", 367 | "metadata": {}, 368 | "outputs": [], 369 | "source": [ 370 | "path_mother = Path('data_mother') \n", 371 | "f_mother = 'slave_rsmp.raw' # Load complex data of mother to obtain amplitude\n", 372 | "\n", 373 | "shape=(5500, 1800) # obtained from ifgs.res --> nlines = rows ; npixels = columns\n", 374 | "dtype = np.dtype([('re', np.float32), ('im', np.float32)])\n", 375 | "\n", 376 | "mother = [p/f_mother for p in path_mother.rglob(\"????????\")]\n", 377 | "\n", 378 | "mother = sarxarray.from_binary(mother, shape, dtype=dtype)\n", 379 | "mother = mother.chunk({\"azimuth\":500, \"range\":500, \"time\":1 }) # set custom chunk sizes\n", 380 | "mother.amplitude" 381 | ] 382 | }, 383 | { 384 | "attachments": {}, 385 | "cell_type": "markdown", 386 | "id": "37097076", 387 | "metadata": {}, 388 | "source": [ 389 | "**Multi-looking**" 390 | ] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": null, 395 | "id": "1e091e14", 396 | "metadata": {}, 397 | "outputs": [], 398 | "source": [ 399 | "def multilooking(data, window_size, variable_name):\n", 400 | " \n", 401 | " # Generate patches\n", 402 | " \n", 403 | " patches_real = view_as_windows(np.real(data), window_size, step=window_size) # step is important as its value can result in overlapping or non overlapping patches\n", 404 | " \n", 405 | " # Compute the mean of each patch\n", 406 | " \n", 407 | " real_mean = np.nanmean(patches_real, axis=(2, 3)) # the 3rd and 4th axes represent the window dimensions\n", 408 | " \n", 409 | " # Consider the imaginary part; in the case input data is a complex number\n", 410 | " \n", 411 | " if not np.all(np.imag(data) == 0): # if imaginary\n", 412 | " \n", 413 | " patches_imag = view_as_windows(np.imag(data), window_size, step=window_size)\n", 414 | " \n", 415 | " # Compute the mean of each patch\n", 416 | " \n", 417 | " imag_mean = np.nanmean(patches_imag, axis=(2, 3))\n", 418 | " \n", 419 | " # Combine the real and imaginary part\n", 420 | " \n", 421 | " output_array = real_mean + 1j * imag_mean\n", 422 | " \n", 423 | " # Save as xarray dataset\n", 424 | " \n", 425 | " comp = xr.DataArray(output_array, dims=None)\n", 426 | " ph = xr.DataArray(np.angle(output_array), dims=('azimuth','range'))\n", 427 | " amp = xr.DataArray(np.abs(output_array), dims=('azimuth','range'))\n", 428 | " \n", 429 | " output_array = xr.DataArray(comp, \n", 430 | " coords={'azimuth': np.arange(0, np.shape(output_array)[0], 1, dtype=int),\n", 431 | " 'range': np.arange(0, np.shape(output_array)[1], 1, dtype=int)}, \n", 432 | " dims=[\"azimuth\",\"range\"])\n", 433 | " output_array= output_array.to_dataset(name='complex')\n", 434 | "\n", 435 | " output_array['amplitude'] = amp\n", 436 | " output_array['phase'] = ph\n", 437 | " \n", 438 | " else:\n", 439 | " \n", 440 | " output_array = real_mean\n", 441 | " \n", 442 | " # Save as xarray dataset\n", 443 | " \n", 444 | " output_array = xr.DataArray(output_array, \n", 445 | " coords={'azimuth': np.arange(0, np.shape(output_array)[0], 1, dtype=int),\n", 446 | " 'range': np.arange(0, np.shape(output_array)[1], 1, dtype=int)}, \n", 447 | " dims=[\"azimuth\",\"range\"])\n", 448 | " output_array = output_array.to_dataset(name=variable_name)\n", 449 | " \n", 450 | " return output_array" 451 | ] 452 | }, 453 | { 454 | "cell_type": "code", 455 | "execution_count": null, 456 | "id": "f34afe60", 457 | "metadata": {}, 458 | "outputs": [], 459 | "source": [ 460 | "# Apply multilooking\n", 461 | "\n", 462 | "first_skip = False\n", 463 | "count = 0\n", 464 | "coords = []\n", 465 | "\n", 466 | "window_size = (22,10)\n", 467 | "\n", 468 | "ifg_ml0 = multilooking(ifg_stack.complex.isel(time=0).values, window_size=window_size, variable_name='complex')\n", 469 | "\n", 470 | "for i in range(len(ifg_stack.time)):\n", 471 | " if(first_skip):\n", 472 | " toAdd_ifg = multilooking(ifg_stack.complex.isel(time=i).values, window_size=window_size, variable_name='complex')\n", 473 | " ifg_ml0 = xr.concat([ifg_ml0, toAdd_ifg], dim=\"time\")\n", 474 | " first_skip = True \n", 475 | " \n", 476 | " coords.append(count)\n", 477 | " count+=1 \n", 478 | " \n", 479 | "ifg_ml = ifg_ml0.assign_coords(time=coords)" 480 | ] 481 | }, 482 | { 483 | "cell_type": "code", 484 | "execution_count": null, 485 | "id": "d1c036c7", 486 | "metadata": {}, 487 | "outputs": [], 488 | "source": [ 489 | "fig, axs = plt.subplots(3,3, figsize=(25, 25), facecolor='w', edgecolor='k')\n", 490 | "fig.subplots_adjust(hspace = .25, wspace=.1)\n", 491 | "\n", 492 | "axs = axs.ravel()\n", 493 | "\n", 494 | "for i in tqdm(range(len(ifg_ml.time))):\n", 495 | " axs[i].imshow(ifg_ml.phase.isel(time=i))\n", 496 | " ifg_ml.phase.isel(time=i).plot(robust=True, ax=axs[i], cmap='jet') # cmap='jet'" 497 | ] 498 | } 499 | ], 500 | "metadata": { 501 | "kernelspec": { 502 | "display_name": "Python 3 (ipykernel)", 503 | "language": "python", 504 | "name": "python3" 505 | }, 506 | "language_info": { 507 | "codemirror_mode": { 508 | "name": "ipython", 509 | "version": 3 510 | }, 511 | "file_extension": ".py", 512 | "mimetype": "text/x-python", 513 | "name": "python", 514 | "nbconvert_exporter": "python", 515 | "pygments_lexer": "ipython3", 516 | "version": "3.10.9" 517 | } 518 | }, 519 | "nbformat": 4, 520 | "nbformat_minor": 5 521 | } 522 | -------------------------------------------------------------------------------- /examples/archive/S1_sarxarray_datamodel.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "id": "0000f704", 7 | "metadata": {}, 8 | "source": [ 9 | "
\n", 10 | " \n", 11 | "
\n", 12 | "\n", 13 | "### InSAR data model based on xarray(/dask)" 14 | ] 15 | }, 16 | { 17 | "attachments": {}, 18 | "cell_type": "markdown", 19 | "id": "dd55e99c", 20 | "metadata": {}, 21 | "source": [ 22 | "**Steps:**\n", 23 | "- Load a raw interferogram (complex(Re, Im)) in binary format into a `xarray.Dataset` object\n", 24 | "- Visualize the phase\n", 25 | "- Geocoding\n", 26 | "- MRM\n", 27 | "- Load 'slave_rsmp'" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "id": "2a2dde59", 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "import sarxarray\n", 38 | "import numpy as np\n", 39 | "from pathlib import Path\n", 40 | "import matplotlib.pyplot as plt\n", 41 | "\n", 42 | "from tqdm import tqdm\n", 43 | "import re\n", 44 | "from skimage.util import view_as_windows\n", 45 | "import xarray as xr" 46 | ] 47 | }, 48 | { 49 | "attachments": {}, 50 | "cell_type": "markdown", 51 | "id": "b061f841", 52 | "metadata": {}, 53 | "source": [ 54 | "**Specify path of file location**" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "id": "f2c73db6", 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "path = Path('data_s1/') # CHANGE to local data directory" 65 | ] 66 | }, 67 | { 68 | "attachments": {}, 69 | "cell_type": "markdown", 70 | "id": "68688461", 71 | "metadata": {}, 72 | "source": [ 73 | "### Interferogram\n", 74 | "\n", 75 | "**List the interferograms (.raw files) to be read**" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "id": "6d45378c", 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "# Open the metadata ifgs.res file\n", 86 | "\n", 87 | "filepath = 'data_s1/20190226/ifgs.res' # example with fir\n", 88 | "\n", 89 | "with open(filepath, 'r') as file:\n", 90 | " content = file.read()\n", 91 | "\n", 92 | "# Look through DORIS V5 'ifgs.res' file for shape\n", 93 | "\n", 94 | "lines = r'Number of lines \\(multilooked\\):\\s+(\\d+)'\n", 95 | "pixels = r'Number of pixels \\(multilooked\\):\\s+(\\d+)'\n", 96 | "match_lines = re.search(lines, content)\n", 97 | "match_pixels = re.search(pixels, content)\n", 98 | "\n", 99 | "if match_lines:\n", 100 | " # Extract the number of lines from the matched pattern\n", 101 | " num_lines = int(match_lines.group(1))\n", 102 | " print(f\"Number of lines: {num_lines}\")\n", 103 | "else:\n", 104 | " print(\"Not found in the file.\")\n", 105 | "\n", 106 | "if match_pixels:\n", 107 | " # Extract the number of lines from the matched pattern\n", 108 | " num_pixels = int(match_pixels.group(1))\n", 109 | " print(f\"Number of pixels: {num_pixels}\")\n", 110 | "else:\n", 111 | " print(\"Not found in the file.\")" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "id": "6a41a772", 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "f_ifg = 'cint_srd.raw' # string\n", 122 | "\n", 123 | "list_ifgs = [p / f_ifg for p in path.rglob(\"????????\") if len(p.parts) < 3] # exclude: WindowsPath('.../.../ifgs.res/cint_srd.raw'),\n", 124 | "list_ifgs" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "id": "39f2b3b1", 131 | "metadata": {}, 132 | "outputs": [], 133 | "source": [ 134 | "# Create list with dates\n", 135 | "# Mother = 20180108\n", 136 | "\n", 137 | "date_list = []\n", 138 | "\n", 139 | "for i in range(len(list_ifgs)):\n", 140 | " prep_date_string = str(list_ifgs[i])\n", 141 | " date = prep_date_string.split('\\\\')[1]\n", 142 | " date_list.append(date)\n", 143 | " \n", 144 | "date_list" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": null, 150 | "id": "5f427128", 151 | "metadata": {}, 152 | "outputs": [], 153 | "source": [ 154 | "# Take the mother-mother ifg out\n", 155 | "\n", 156 | "mother_str = '20190403'\n", 157 | "mother_idx = date_list.index(mother_str)\n", 158 | "\n", 159 | "list_ifgs_without_mother = list_ifgs[0:mother_idx]+list_ifgs[(mother_idx+1):]\n", 160 | "list_ifgs_without_mother" 161 | ] 162 | }, 163 | { 164 | "attachments": {}, 165 | "cell_type": "markdown", 166 | "id": "f804a2db", 167 | "metadata": {}, 168 | "source": [ 169 | "**Metadata**\n", 170 | "\n", 171 | "Information about the shape can be found in the ifgs.res files and are denoted using 'nlines' and 'npixels', respectively." 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "id": "d5001030", 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "# Metadata\n", 182 | "\n", 183 | "shape=(num_lines, num_pixels) # obtained from ifgs.res --> nlines = rows ; npixels = columns\n", 184 | "dtype = np.dtype([('re', np.float32), ('im', np.float32)])" 185 | ] 186 | }, 187 | { 188 | "attachments": {}, 189 | "cell_type": "markdown", 190 | "id": "2391bec2", 191 | "metadata": {}, 192 | "source": [ 193 | "**Loading the raw interferogram into a `xarray.Dataset`**" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": null, 199 | "id": "068c9e9e", 200 | "metadata": {}, 201 | "outputs": [], 202 | "source": [ 203 | "# Create xarray.Dataset object from .raw file\n", 204 | "\n", 205 | "ifg_stack = sarxarray.from_binary(list_ifgs_without_mother, shape, dtype=dtype)\n", 206 | "ifg_stack" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": null, 212 | "id": "6f59c0c7", 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "# Create subset to obtain region of interest\n", 217 | "\n", 218 | "ifg_subset = ifg_stack.isel(azimuth=range(600,1350),range=range(14400,16400))\n", 219 | "ifg_subset = ifg_subset.chunk({\"azimuth\":200, \"range\":200, \"time\":1 }) # set custom chunk sizes\n", 220 | "\n", 221 | "ifg_subset" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "id": "90bbe917", 228 | "metadata": {}, 229 | "outputs": [], 230 | "source": [ 231 | "phase = ifg_subset.phase\n", 232 | "amplitude = ifg_subset.amplitude\n", 233 | "phasor = ifg_subset.complex # contains P00, P01, P02" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": null, 239 | "id": "1713b6ff", 240 | "metadata": {}, 241 | "outputs": [], 242 | "source": [ 243 | "phase" 244 | ] 245 | }, 246 | { 247 | "attachments": {}, 248 | "cell_type": "markdown", 249 | "id": "35fbf1d5", 250 | "metadata": {}, 251 | "source": [ 252 | "**Visualize the phase**" 253 | ] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": null, 258 | "id": "f62f6ba0", 259 | "metadata": {}, 260 | "outputs": [], 261 | "source": [ 262 | "# Visualize first figure\n", 263 | "\n", 264 | "fig,ax = plt.subplots(1,1)\n", 265 | "phase_i = phase.isel(time=1)\n", 266 | "ax.imshow(phase_i)\n", 267 | "phase_i.plot(robust=True, ax=ax, cmap='jet') # cmap='jet'" 268 | ] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "execution_count": null, 273 | "id": "dcbd8ad8", 274 | "metadata": {}, 275 | "outputs": [], 276 | "source": [ 277 | "fig, axs = plt.subplots(3,3, figsize=(25, 25), facecolor='w', edgecolor='k')\n", 278 | "fig.subplots_adjust(hspace = .25, wspace=.1)\n", 279 | "\n", 280 | "axs = axs.ravel()\n", 281 | "\n", 282 | "for i in tqdm(range(len(ifg_stack.time))):\n", 283 | " phase_i = phase.isel(time=i)\n", 284 | " axs[i].imshow(phase_i)\n", 285 | " phase_i.plot(robust=True, ax=axs[i], cmap='jet') # cmap='jet'\n" 286 | ] 287 | }, 288 | { 289 | "attachments": {}, 290 | "cell_type": "markdown", 291 | "id": "88c5cf91", 292 | "metadata": {}, 293 | "source": [ 294 | "**Geocoding**" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": null, 300 | "id": "6a6e8df0", 301 | "metadata": {}, 302 | "outputs": [], 303 | "source": [ 304 | "path_mother = Path('data_mother_s1') # path to folder containing phi and lam raw\n", 305 | "shape=(1456, 20442)\n", 306 | "\n", 307 | "f_lat = [path_mother/'phi.raw']\n", 308 | "f_lon = [path_mother/'lam.raw']\n", 309 | "f_lon" 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": null, 315 | "id": "11854a62", 316 | "metadata": {}, 317 | "outputs": [], 318 | "source": [ 319 | "lat = sarxarray.from_binary(f_lat, shape, vlabel='lat', dtype=np.float32)\n", 320 | "lon = sarxarray.from_binary(f_lon, shape, vlabel='lon', dtype=np.float32)" 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "execution_count": null, 326 | "id": "48424687", 327 | "metadata": {}, 328 | "outputs": [], 329 | "source": [ 330 | "lat_subset = lat.isel(azimuth=range(600,1350),range=range(14400,16400))\n", 331 | "lon_subset = lon.isel(azimuth=range(600,1350),range=range(14400,16400))" 332 | ] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "execution_count": null, 337 | "id": "42f25666", 338 | "metadata": {}, 339 | "outputs": [], 340 | "source": [ 341 | "ifg_subset_geo = ifg_subset.assign_coords(lat = ((\"azimuth\", \"range\"), lat_subset.squeeze().lat.data), lon = ((\"azimuth\", \"range\"), lon_subset.squeeze().lon.data))" 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "id": "a44b6902", 348 | "metadata": {}, 349 | "outputs": [], 350 | "source": [ 351 | "ifg_subset_geo\n", 352 | "\n", 353 | "# np.max(ifg_subset_geo.coords['lat'].values)\n", 354 | "# np.min(ifg_subset_geo.coords['lat'].values)" 355 | ] 356 | }, 357 | { 358 | "cell_type": "code", 359 | "execution_count": null, 360 | "id": "3d4c36cb", 361 | "metadata": {}, 362 | "outputs": [], 363 | "source": [ 364 | "phase_geo = ifg_subset_geo.phase\n", 365 | "pbar = tqdm(total=len(ifg_stack.time))\n", 366 | "\n", 367 | "fig, axs = plt.subplots(3,3, figsize=(25, 25), facecolor='w', edgecolor='k')\n", 368 | "fig.subplots_adjust(hspace = .25, wspace=.1)\n", 369 | "\n", 370 | "axs = axs.ravel()\n", 371 | "\n", 372 | "for i in range(len(ifg_stack.time)):\n", 373 | " phase_geo_i = phase_geo.isel(time=i)\n", 374 | " axs[i].imshow(phase_geo_i,extent=[ifg_subset_geo.coords['lon'].min(), ifg_subset_geo.coords['lon'].max(),\n", 375 | " ifg_subset_geo.coords['lat'].min(), ifg_subset_geo.coords['lat'].max()], cmap='jet', interpolation='none')\n", 376 | " phase_geo_i.plot(x='lon', y='lat', ax=axs[i], cmap='jet')\n", 377 | " pbar.update(1)\n", 378 | "pbar.close()" 379 | ] 380 | }, 381 | { 382 | "attachments": {}, 383 | "cell_type": "markdown", 384 | "id": "922c88c2", 385 | "metadata": {}, 386 | "source": [ 387 | "**MRM (Mean Reflection Map)**" 388 | ] 389 | }, 390 | { 391 | "cell_type": "code", 392 | "execution_count": null, 393 | "id": "1eca61bb", 394 | "metadata": {}, 395 | "outputs": [], 396 | "source": [ 397 | "# Creating a MRM (Mean Reflection Map) of a subset of the stack\n", 398 | "\n", 399 | "mrm = ifg_stack.slcstack.mrm() # go 3D to 2D --> only azimuth & range for amplitude\n", 400 | "mrm" 401 | ] 402 | }, 403 | { 404 | "cell_type": "code", 405 | "execution_count": null, 406 | "id": "5a3a705e", 407 | "metadata": {}, 408 | "outputs": [], 409 | "source": [ 410 | "mrm_subset = mrm[1000:1200, 14500:15100] # Create subset using 2 indexes: azimuth & range\n", 411 | "# mrm_subset = mrm[600:1350, 14400:16400]\n", 412 | "mrm_subset = mrm_subset.compute() # manually trigger loading of this array’s data from disk or a remote source into memory and return a new array\n", 413 | "mrm_subset" 414 | ] 415 | }, 416 | { 417 | "cell_type": "code", 418 | "execution_count": null, 419 | "id": "c057d232", 420 | "metadata": {}, 421 | "outputs": [], 422 | "source": [ 423 | "# Visualize\n", 424 | "\n", 425 | "fig, ax = plt.subplots()\n", 426 | "ax.imshow(mrm_subset)\n", 427 | "mrm_subset.plot(robust=True, ax=ax)" 428 | ] 429 | }, 430 | { 431 | "attachments": {}, 432 | "cell_type": "markdown", 433 | "id": "412b4f59", 434 | "metadata": {}, 435 | "source": [ 436 | "**Load slave_rsmp - to get original amplitude of SLC's e.g.**" 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": null, 442 | "id": "99878365", 443 | "metadata": {}, 444 | "outputs": [], 445 | "source": [ 446 | "path_mother = Path('data_mother_s1') \n", 447 | "f_mother = 'slave_rsmp.raw' # Load complex data of mother to obtain amplitude\n", 448 | "\n", 449 | "shape=(1456, 20442) # obtained from ifgs.res --> nlines = rows ; npixels = columns\n", 450 | "dtype = np.dtype([('re', np.int16), ('im', np.int16)])\n", 451 | "\n", 452 | "mother = [p/f_mother for p in path_mother.rglob(\"????????\")]\n", 453 | "\n", 454 | "mother = sarxarray.from_binary(mother, shape, dtype=dtype)\n", 455 | "mother = mother.chunk({\"azimuth\":200, \"range\":200, \"time\":1 }) # set custom chunk sizes\n", 456 | "mother = mother.sel(azimuth=range(600,1350),range=range(14400,16400))\n", 457 | "mother.amplitude" 458 | ] 459 | }, 460 | { 461 | "attachments": {}, 462 | "cell_type": "markdown", 463 | "id": "9e830339", 464 | "metadata": {}, 465 | "source": [ 466 | "**Multi-looking**" 467 | ] 468 | }, 469 | { 470 | "cell_type": "code", 471 | "execution_count": null, 472 | "id": "36cf3227", 473 | "metadata": {}, 474 | "outputs": [], 475 | "source": [ 476 | "def multilooking(data, window_size, variable_name):\n", 477 | " \n", 478 | " # Generate patches\n", 479 | " \n", 480 | " patches_real = view_as_windows(np.real(data), window_size, step=window_size) # step is important as its value can result in overlapping or non overlapping patches\n", 481 | " \n", 482 | " # Compute the mean of each patch\n", 483 | " \n", 484 | " real_mean = np.nanmean(patches_real, axis=(2, 3)) # the 3rd and 4th axes represent the window dimensions\n", 485 | " \n", 486 | " # Consider the imaginary part; in the case input data is a complex number\n", 487 | " \n", 488 | " if not np.all(np.imag(data) == 0): # if imaginary\n", 489 | " \n", 490 | " patches_imag = view_as_windows(np.imag(data), window_size, step=window_size)\n", 491 | " \n", 492 | " # Compute the mean of each patch\n", 493 | " \n", 494 | " imag_mean = np.nanmean(patches_imag, axis=(2, 3))\n", 495 | " \n", 496 | " # Combine the real and imaginary part\n", 497 | " \n", 498 | " output_array = real_mean + 1j * imag_mean\n", 499 | " \n", 500 | " # Save as xarray dataset\n", 501 | " \n", 502 | " comp = xr.DataArray(output_array, dims=None)\n", 503 | " ph = xr.DataArray(np.angle(output_array), dims=('azimuth','range'))\n", 504 | " amp = xr.DataArray(np.abs(output_array), dims=('azimuth','range'))\n", 505 | " \n", 506 | " output_array = xr.DataArray(comp, \n", 507 | " coords={'azimuth': np.arange(0, np.shape(output_array)[0], 1, dtype=int),\n", 508 | " 'range': np.arange(0, np.shape(output_array)[1], 1, dtype=int)}, \n", 509 | " dims=[\"azimuth\",\"range\"])\n", 510 | " output_array= output_array.to_dataset(name='complex')\n", 511 | "\n", 512 | " output_array['amplitude'] = amp\n", 513 | " output_array['phase'] = ph\n", 514 | " \n", 515 | " else:\n", 516 | " \n", 517 | " output_array = real_mean\n", 518 | " \n", 519 | " # Save as xarray dataset\n", 520 | " \n", 521 | " output_array = xr.DataArray(output_array, \n", 522 | " coords={'azimuth': np.arange(0, np.shape(output_array)[0], 1, dtype=int),\n", 523 | " 'range': np.arange(0, np.shape(output_array)[1], 1, dtype=int)}, \n", 524 | " dims=[\"azimuth\",\"range\"])\n", 525 | " output_array = output_array.to_dataset(name=variable_name)\n", 526 | " \n", 527 | " return output_array" 528 | ] 529 | }, 530 | { 531 | "cell_type": "code", 532 | "execution_count": null, 533 | "id": "2e686f61", 534 | "metadata": {}, 535 | "outputs": [], 536 | "source": [ 537 | "# Apply multilooking\n", 538 | "\n", 539 | "first_skip = False\n", 540 | "count = 0\n", 541 | "coords = []\n", 542 | "\n", 543 | "window_size = (3,11)\n", 544 | "\n", 545 | "ifg_ml0 = multilooking(ifg_subset.complex.isel(time=0).values, window_size=window_size, variable_name='complex')\n", 546 | "\n", 547 | "for i in range(len(ifg_subset.time)):\n", 548 | " if(first_skip):\n", 549 | " toAdd_ifg = multilooking(ifg_subset.complex.isel(time=i).values, window_size=window_size, variable_name='complex')\n", 550 | " ifg_ml0 = xr.concat([ifg_ml0, toAdd_ifg], dim=\"time\")\n", 551 | " first_skip = True \n", 552 | " \n", 553 | " coords.append(count)\n", 554 | " count+=1 \n", 555 | " \n", 556 | "ifg_ml = ifg_ml0.assign_coords(time=coords)" 557 | ] 558 | }, 559 | { 560 | "cell_type": "code", 561 | "execution_count": null, 562 | "id": "6f20e8de", 563 | "metadata": {}, 564 | "outputs": [], 565 | "source": [ 566 | "fig, axs = plt.subplots(3,3, figsize=(25, 25), facecolor='w', edgecolor='k')\n", 567 | "fig.subplots_adjust(hspace = .25, wspace=.1)\n", 568 | "\n", 569 | "axs = axs.ravel()\n", 570 | "\n", 571 | "for i in tqdm(range(len(ifg_ml.time))):\n", 572 | " axs[i].imshow(ifg_ml.phase.isel(time=i))\n", 573 | " ifg_ml.phase.isel(time=i).plot(robust=True, ax=axs[i], cmap='jet') # cmap='jet'" 574 | ] 575 | } 576 | ], 577 | "metadata": { 578 | "kernelspec": { 579 | "display_name": "Python 3 (ipykernel)", 580 | "language": "python", 581 | "name": "python3" 582 | }, 583 | "language_info": { 584 | "codemirror_mode": { 585 | "name": "ipython", 586 | "version": 3 587 | }, 588 | "file_extension": ".py", 589 | "mimetype": "text/x-python", 590 | "name": "python", 591 | "nbconvert_exporter": "python", 592 | "pygments_lexer": "ipython3", 593 | "version": "3.10.9" 594 | } 595 | }, 596 | "nbformat": 4, 597 | "nbformat_minor": 5 598 | } 599 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: SARXarray Documentation 2 | repo_url: https://github.com/TUDelftGeodesy/sarxarray/ 3 | repo_name: SARXarray 4 | 5 | nav: 6 | - Getting started: 7 | - About SARXarray: index.md 8 | - Installation: setup.md 9 | - Usage: 10 | - Data loading: data_loading.md 11 | - Common SLC operations: common_ops.md 12 | - Other manipulations: manipulations.md 13 | - Notebook page: notebooks/demo_sarxarray.ipynb 14 | - Conributing guide: CONTRIBUTING.md 15 | - Change Log: CHANGELOG.md 16 | 17 | 18 | theme: 19 | name: material 20 | custom_dir: docs/notebooks/download_button 21 | logo: img/sarxarray_logo.png 22 | palette: 23 | # Palette toggle for light mode 24 | - scheme: default 25 | toggle: 26 | icon: material/weather-sunny 27 | name: Switch to dark mode 28 | primary: black 29 | accent: red 30 | 31 | # Palette toggle for dark mode 32 | - scheme: slate 33 | toggle: 34 | icon: material/weather-night 35 | name: Switch to light mode 36 | primary: black 37 | accent: pink 38 | features: 39 | - navigation.instant 40 | - navigation.tabs 41 | - navigation.tabs.sticky 42 | - content.code.copy 43 | 44 | plugins: 45 | - mkdocs-jupyter: 46 | include_source: True 47 | - search 48 | - mkdocstrings: 49 | handlers: 50 | python: 51 | options: 52 | docstring_style: google 53 | docstring_options: 54 | ignore_init_summary: no 55 | merge_init_into_class: yes 56 | show_submodules: no 57 | 58 | markdown_extensions: 59 | - pymdownx.highlight: 60 | anchor_linenums: true 61 | - pymdownx.superfences 62 | 63 | extra: 64 | generator: false -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "sarxarray" 7 | version = "1.0.2" 8 | requires-python = ">=3.10" 9 | dependencies = [ 10 | "dask[complete]", 11 | "xarray", 12 | "numpy", 13 | "distributed", 14 | "zarr", 15 | ] 16 | description = "Xarray extension for Synthetic Aperture Radar (SAR) data" 17 | readme = "README.md" 18 | license = {file = "LICENSE"} 19 | authors = [ 20 | {name = "Ou Ku", email = "o.ku@esciencecenter.nl"}, 21 | {name = "Fakhereh Sarah Alidoost"}, 22 | {name = "Pranav Chandramouli"}, 23 | {name = "Francesco Nattino"}, 24 | {name = "Freek van Leijen"}, 25 | ] 26 | keywords = ["radar", "sar", "insar", "earth observation", "distributed computing"] 27 | classifiers=[ 28 | 'Development Status :: 3 - Alpha', 29 | 'Intended Audience :: Developers', 30 | 'License :: OSI Approved :: Apache Software License', 31 | 'Natural Language :: English', 32 | 'Programming Language :: Python :: 3.10', 33 | 'Programming Language :: Python :: 3.11', 34 | 'Programming Language :: Python :: 3.12', 35 | ] 36 | 37 | [project.urls] 38 | repository = "https://github.com/TUDelftGeodesy/sarxarray" 39 | doi = "https://doi.org/10.5281/zenodo.7717112" 40 | documentation = "https://tudelftgeodesy.github.io/sarxarray/" 41 | changelog = "https://tudelftgeodesy.github.io/sarxarray/CHANGELOG/" 42 | 43 | [project.optional-dependencies] 44 | dev = [ 45 | "pytest", 46 | "pytest-cov", 47 | "pycodestyle", 48 | "ruff", 49 | "pre-commit", 50 | ] 51 | docs = [ 52 | "mkdocs", 53 | "mkdocs-material", 54 | "mkdocs-jupyter", 55 | "mkdocstrings[python]", 56 | "mkdocs-gen-files", 57 | ] 58 | demo = [ 59 | "jupyterlab", 60 | "matplotlib", 61 | ] 62 | 63 | [tool.setuptools] 64 | packages = ["sarxarray"] 65 | 66 | [tool.pytest.ini_options] 67 | minversion = "6.0" 68 | addopts = "--cov --cov-report term" 69 | testpaths = [ 70 | "tests", 71 | ] 72 | 73 | [tool.coverage.run] 74 | branch = true 75 | source = ["sarxarray"] 76 | 77 | [tool.ruff] 78 | select = [ 79 | "E", # pycodestyle 80 | "F", # pyflakes 81 | "B", # flake8-bugbear 82 | "D", # pydocstyle 83 | "I", # isort 84 | "N", # PEP8-naming 85 | "UP", # pyupgrade (upgrade syntax to current syntax) 86 | "PLE", # Pylint error https://github.com/charliermarsh/ruff#error-ple 87 | ] 88 | ignore = [ 89 | "D100", "D101", "D104", "D105", "D106", "D107", "D203", "D213", "D413" 90 | ] # docstring style 91 | 92 | line-length = 88 93 | exclude = ["docs", "build", "examples"] 94 | # Allow unused variables when underscore-prefixed. 95 | dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" 96 | target-version = "py310" 97 | 98 | [tool.ruff.per-file-ignores] 99 | "tests/**" = ["D"] 100 | -------------------------------------------------------------------------------- /sarxarray/__init__.py: -------------------------------------------------------------------------------- 1 | from sarxarray import stack 2 | from sarxarray._io import from_binary, from_dataset 3 | from sarxarray.utils import complex_coherence, multi_look 4 | 5 | __all__ = ("stack", "from_binary", "from_dataset", "multi_look", "complex_coherence") 6 | -------------------------------------------------------------------------------- /sarxarray/_io.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import math 3 | 4 | import dask 5 | import dask.array as da 6 | import numpy as np 7 | import xarray as xr 8 | 9 | from .conf import _dtypes, _memsize_chunk_mb 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | # Example: https://docs.dask.org/en/stable/array-creation.html#memory-mapping 14 | 15 | 16 | def from_dataset(ds: xr.Dataset) -> xr.Dataset: 17 | """Create a SLC stack or from an Xarray Dataset. 18 | 19 | This function create tasks graph converting the two data variables of complex data: 20 | `real` and `imag`, to three variables: `complex`, `amplitude`, and `phase`. 21 | 22 | The function is intented for an SLC stack in `xr.Dataset` loaded from a Zarr file. 23 | 24 | For other datasets, such as lat, lon, etc., please use `xr.open_zarr` directly. 25 | 26 | Parameters 27 | ---------- 28 | ds : xr.Dataset 29 | SLC stack loaded from a Zarr file. 30 | Must have three dimensions: `(azimuth, range, time)`. 31 | Must have two variables: `real` and `imag`. 32 | 33 | Returns 34 | ------- 35 | xr.Dataset 36 | Converted SLC stack. 37 | An xarray.Dataset with three dimensions: `(azimuth, range, time)`, and 38 | three variables: `complex`, `amplitude`, `phase`. 39 | 40 | Raises 41 | ------ 42 | ValueError 43 | The input dataset should have three dimensions: `(azimuth, range, time)`. 44 | ValueError 45 | The input dataset should have the following variables: `('real', 'imag')`. 46 | """ 47 | # Check ds should have the following dimensions: (azimuth, range, time) 48 | if any(dim not in ds.dims for dim in ["azimuth", "range", "time"]): 49 | raise ValueError( 50 | "The input dataset should have three dimensions: (azimuth, range, time)." 51 | ) 52 | 53 | # Check ds should have the following variables: ("real", "imag") 54 | if any(var not in ds.variables for var in ["real", "imag"]): 55 | raise ValueError( 56 | "The input dataset should have the following variables: ('real', 'imag')." 57 | ) 58 | 59 | # Construct the three datavariables: complex, amplitude, and phase 60 | ds["complex"] = ds["real"] + 1j * ds["imag"] 61 | ds = ds.slcstack._get_amplitude() 62 | ds = ds.slcstack._get_phase() 63 | 64 | # Remove the original real and imag variables 65 | ds = ds.drop_vars(["real", "imag"]) 66 | 67 | return ds 68 | 69 | 70 | def from_binary( 71 | slc_files, shape, vlabel="complex", dtype=np.complex64, chunks=None, ratio=1 72 | ): 73 | """Read a SLC stack or relabted variables from binary files. 74 | 75 | Parameters 76 | ---------- 77 | slc_files : Iterable 78 | Paths to the SLC files. 79 | shape : Tuple 80 | Shape of each SLC file, in (n_azimuth, n_range) 81 | vlabel : str, optional 82 | Name of the variable to read, by default "complex". 83 | dtype : numpy.dtype, optional 84 | Data type of the file to read, by default np.float32 85 | chunks : list, optional 86 | 2-D chunk size, by default None 87 | ratio: 88 | Ratio of resolutions (azimuth/range), by default 1 89 | 90 | Returns 91 | ------- 92 | xarray.Dataset 93 | An xarray.Dataset with three dimensions: (azimuth, range, time). 94 | 95 | """ 96 | # Check dtype 97 | if not np.dtype(dtype).isbuiltin: 98 | if not all([name in (("re", "im")) for name in dtype.names]): 99 | raise TypeError( 100 | "The customed dtype should have only two field names: " 101 | '"re" and "im". For example: ' 102 | 'dtype = np.dtype([("re", np.float32), ("im", np.float32)]).' 103 | ) 104 | 105 | # Initialize stack as a Dataset 106 | coords = { 107 | "azimuth": range(shape[0]), 108 | "range": range(shape[1]), 109 | "time": range(len(slc_files)), 110 | } 111 | ds_stack = xr.Dataset(coords=coords) 112 | 113 | # Calculate appropriate chunk size if not user-defined 114 | if chunks is None: 115 | chunks = _calc_chunksize(shape, dtype, ratio) 116 | 117 | # Read in all SLCs 118 | slcs = None 119 | for f_slc in slc_files: 120 | if slcs is None: 121 | slcs = _mmap_dask_array(f_slc, shape, dtype, chunks).reshape( 122 | (shape[0], shape[1], 1) 123 | ) 124 | else: 125 | slc = _mmap_dask_array(f_slc, shape, dtype, chunks).reshape( 126 | (shape[0], shape[1], 1) 127 | ) 128 | slcs = da.concatenate([slcs, slc], axis=2) 129 | 130 | # unpack the customized dtype 131 | if not np.dtype(dtype).isbuiltin: 132 | meta_arr = np.array((), dtype=_dtypes["complex"]) 133 | slcs = da.apply_gufunc(_unpack_complex, "()->()", slcs, meta=meta_arr) 134 | 135 | ds_stack = ds_stack.assign({vlabel: (("azimuth", "range", "time"), slcs)}) 136 | 137 | # If reading complex data, automatically 138 | if vlabel == "complex": 139 | ds_stack = ds_stack.slcstack._get_amplitude() 140 | ds_stack = ds_stack.slcstack._get_phase() 141 | 142 | return ds_stack 143 | 144 | 145 | def _mmap_dask_array(filename, shape, dtype, chunks): 146 | """Create a Dask array from raw binary data by memory mapping. 147 | 148 | This method is particularly effective if the file is already 149 | in the file system cache and if arbitrary smaller subsets are 150 | to be extracted from the Dask array without optimizing its 151 | chunking scheme. 152 | It may perform poorly on Windows if the file is not in the file 153 | system cache. On Linux it performs well under most circumstances. 154 | 155 | Parameters 156 | ---------- 157 | filename : str 158 | The path to the file that contains raw binary data. 159 | shape : tuple 160 | Total shape of the data in the file 161 | dtype: 162 | NumPy dtype of the data in the file 163 | chunks : int, optional 164 | Chunk size for the outermost axis. The other axes remain unchunked. 165 | 166 | Returns 167 | ------- 168 | dask.array.Array 169 | Dask array matching :code:`shape` and :code:`dtype`, backed by 170 | memory-mapped chunks. 171 | """ 172 | load = dask.delayed(_mmap_load_chunk) 173 | range_chunks = [] 174 | for azimuth_index in range(0, shape[0], chunks[0]): 175 | azimuth_chunks = [] 176 | # Truncate the last chunk if necessary 177 | azimuth_chunk_size = min(chunks[0], shape[0] - azimuth_index) 178 | for range_index in range(0, shape[1], chunks[1]): 179 | # Truncate the last chunk if necessary 180 | range_chunk_size = min(chunks[1], shape[1] - range_index) 181 | chunk = dask.array.from_delayed( 182 | load( 183 | filename, 184 | shape=shape, 185 | dtype=dtype, 186 | sl1=slice(azimuth_index, azimuth_index + azimuth_chunk_size), 187 | sl2=slice(range_index, range_index + range_chunk_size), 188 | ), 189 | shape=(azimuth_chunk_size, range_chunk_size), 190 | dtype=dtype, 191 | ) 192 | azimuth_chunks.append(chunk) 193 | range_chunk = da.concatenate(azimuth_chunks, axis=1) 194 | range_chunks.append(range_chunk) 195 | return da.concatenate(range_chunks, axis=0) 196 | 197 | 198 | def _mmap_load_chunk(filename, shape, dtype, sl1, sl2): 199 | """Memory map the given file with overall shape and dtype. 200 | 201 | It returns a slice specified by :code:`sl1` in azimuth direction and 202 | :code:`sl2` in range direction. 203 | 204 | Parameters 205 | ---------- 206 | filename : str 207 | The path to the file that contains raw binary data. 208 | shape : tuple 209 | Total shape of the data in the file 210 | dtype: 211 | NumPy dtype of the data in the file 212 | sl1: 213 | Slice object in azimuth direction that can be used for indexing or 214 | slicing a NumPy array to extract a chunk 215 | sl2: 216 | Slice object in range direction that can be used for indexing or slicing 217 | a NumPy array to extract a chunk 218 | 219 | Returns 220 | ------- 221 | numpy.memmap or numpy.ndarray 222 | View into memory map created by indexing with :code:`sl1` and 223 | :code:`sl2`, or NumPy ndarray in case no view can be created. 224 | """ 225 | data = np.memmap(filename, mode="r", shape=shape, dtype=dtype) 226 | return data[sl1, sl2] 227 | 228 | 229 | def _unpack_complex(complex): 230 | return complex["re"] + 1j * complex["im"] 231 | 232 | 233 | def _calc_chunksize(shape: tuple, dtype: np.dtype, ratio: int): 234 | """Calculate an optimal chunking size. 235 | 236 | It calculates an optimal chunking size in the azimuth and range direction 237 | for reading with dask and store it in variable `chunks`. 238 | 239 | Parameters 240 | ---------- 241 | shape : tuple 242 | Total shape of the data in the file 243 | dtype: 244 | NumPy dtype of the data in the file 245 | ratio: 246 | Ratio of resolutions (azimuth/range) 247 | 248 | Returns 249 | ------- 250 | chunks: tuple 251 | Chunk sizes (as multiples of 1000) in the azimuth and range direction. 252 | Default value of [-1, -1] when unmodified activates this function. 253 | """ 254 | n_elements = ( 255 | _memsize_chunk_mb * 1024 * 1024 / np.dtype(dtype).itemsize 256 | ) # Optimal number of elements for a memory size of 100mb (first number) 257 | chunks_ra = ( 258 | int(math.ceil((n_elements / ratio) ** 0.5 / 1000.0)) * 1000 259 | ) # Chunking size in range direction up to nearest thousand 260 | chunks_az = chunks_ra * ratio 261 | 262 | # Regulate chunk to the size of each dim 263 | chunks_az = min(chunks_az, shape[0]) 264 | chunks_ra = min(chunks_ra, shape[1]) 265 | 266 | chunks = (chunks_az, chunks_ra) 267 | 268 | return chunks 269 | -------------------------------------------------------------------------------- /sarxarray/conf.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | # Standard data types in sarxarray: 4 | _dtypes = dict(int=np.int32, float=np.float32, complex=np.complex64) 5 | 6 | # Optimal memory size of a chunk, in MB 7 | _memsize_chunk_mb = 100 8 | -------------------------------------------------------------------------------- /sarxarray/stack.py: -------------------------------------------------------------------------------- 1 | import dask.array as da 2 | import numpy as np 3 | import xarray as xr 4 | 5 | from .conf import _dtypes 6 | from .utils import multi_look 7 | 8 | 9 | @xr.register_dataset_accessor("slcstack") 10 | class Stack: 11 | def __init__(self, xarray_obj): 12 | self._obj = xarray_obj 13 | 14 | def _get_amplitude(self): 15 | meta_arr = np.array((), dtype=_dtypes["float"]) 16 | amplitude = da.apply_gufunc( 17 | _compute_amp, "()->()", self._obj.complex, meta=meta_arr 18 | ) 19 | self._obj = self._obj.assign( 20 | {"amplitude": (("azimuth", "range", "time"), amplitude)} 21 | ) 22 | return self._obj 23 | 24 | def _get_phase(self): 25 | meta_arr = np.array((), dtype=_dtypes["float"]) 26 | phase = da.apply_gufunc( 27 | _compute_phase, "()->()", self._obj.complex, meta=meta_arr 28 | ) 29 | self._obj = self._obj.assign({"phase": (("azimuth", "range", "time"), phase)}) 30 | return self._obj 31 | 32 | def mrm(self): 33 | """Compute a Mean Reflection Map (MRM).""" 34 | t_order = list(self._obj.dims.keys()).index("time") # Time dimension order 35 | return self._obj.amplitude.mean(axis=t_order) 36 | 37 | def point_selection(self, threshold, method="amplitude_dispersion", chunks=1000): 38 | """Select pixels from a Stack, and return a Space-Time Matrix. 39 | 40 | The selection method is defined by `method` and `threshold`. 41 | The selected pixels will be reshaped to (space, time), where `space` is 42 | the number of selected pixels. The unselected pixels will be discarded. 43 | The original `azimuth` and `range` coordinates will be persisted. 44 | 45 | Parameters 46 | ---------- 47 | threshold : float 48 | Threshold value for selection 49 | method : str, optional 50 | Method of selection, by default "amplitude_dispersion" 51 | chunks : int, optional 52 | Chunk size in the space dimension, by default 1000 53 | 54 | Returns 55 | ------- 56 | xarray.Dataset 57 | An xarray.Dataset with two dimensions: (space, time). 58 | """ 59 | match method: 60 | case "amplitude_dispersion": 61 | # Amplitude dispersion thresholding 62 | # Note there can be NaN values in the amplitude dispersion 63 | # However NaN values will not pass this threshold 64 | mask = self._amp_disp() < threshold 65 | case _: 66 | raise NotImplementedError 67 | 68 | # Get the 1D index on space dimension 69 | mask_1d = mask.stack(space=("azimuth", "range")).drop_vars( 70 | ["azimuth", "range", "space"] 71 | ) 72 | index = mask_1d.space.data[mask_1d.data] # Evaluate the mask 73 | 74 | # Reshape from Stack ("azimuth", "range", "time") to Space-Time Matrix 75 | # ("space", "time") 76 | stacked = self._obj.stack(space=("azimuth", "range")) 77 | stm = stacked.drop_vars( 78 | ["space", "azimuth", "range"] 79 | ) # this will also drop azimuth and range 80 | stm = stm.assign_coords( 81 | { 82 | "azimuth": (["space"], stacked.azimuth.data), 83 | "range": (["space"], stacked.range.data), 84 | } 85 | ) # keep azimuth and range index 86 | 87 | # Apply selection 88 | stm_masked = stm.sel(space=index) 89 | 90 | # Re-order the dimensions to 91 | # community preferred ("space", "time") order 92 | # Since there are dask arrays in stm_masked, 93 | # this operation is lazy. 94 | # Therefore its effect can be observed after evaluation 95 | stm_masked = stm_masked.transpose("space", "time") 96 | 97 | # Rechunk is needed because after apply maksing, 98 | # the chunksize will be in consistant 99 | stm_masked = stm_masked.chunk( 100 | { 101 | "space": chunks, 102 | "time": -1, 103 | } 104 | ) 105 | 106 | return stm_masked 107 | 108 | def _amp_disp(self, chunk_azimuth=500, chunk_range=500): 109 | # Time dimension order 110 | t_order = list(self._obj.dims.keys()).index("time") 111 | 112 | # Rechunk to make temporal operation more efficient 113 | amplitude = self._obj.amplitude.chunk( 114 | {"azimuth": chunk_azimuth, "range": chunk_range, "time": -1} 115 | ) 116 | 117 | # Compoute amplitude dispersion 118 | # By defalut, the mean and std function from Xarray will skip NaN values 119 | # However, if there is NaN value in time series, we want to discard the pixel 120 | # Therefore, we set skipna=False 121 | # Adding epsilon to avoid zero division 122 | amplitude_dispersion = amplitude.std(axis=t_order, skipna=False) / ( 123 | amplitude.mean(axis=t_order, skipna=False) + np.finfo(amplitude.dtype).eps 124 | ) 125 | 126 | return amplitude_dispersion 127 | 128 | def multi_look( 129 | self, window_size, method="coarsen", statistics="mean", compute=True 130 | ): 131 | """Perform multi-looking on a Stack, and return a Stack. 132 | 133 | Parameters 134 | ---------- 135 | data : xarray.Dataset 136 | The data to be multi-looked. 137 | window_size : tuple 138 | Window size for multi-looking, in the format of (azimuth, range) 139 | method : str, optional 140 | Method of multi-looking, by default "coarsen" 141 | statistics : str, optional 142 | Statistics method for multi-looking, by default "mean" 143 | compute : bool, optional 144 | Whether to compute the result, by default True. If False, the result 145 | will be `dask.delayed.Delayed`. This is useful when the multi_look 146 | is used as an intermediate result. 147 | 148 | Returns 149 | ------- 150 | xarray.Dataset 151 | An `xarray.Dataset` with coarsen shape if 152 | `compute` is True, otherwise a `dask.delayed.Delayed` object. 153 | """ 154 | return multi_look(self._obj, window_size, method, statistics, compute) 155 | 156 | 157 | def _compute_amp(complex): 158 | return np.abs(complex) 159 | 160 | 161 | def _compute_phase(complex): 162 | return np.angle(complex) 163 | -------------------------------------------------------------------------------- /sarxarray/utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import xarray as xr 3 | from dask.delayed import Delayed, delayed 4 | 5 | 6 | def multi_look(data, window_size, method="coarsen", statistics="mean", compute=True): 7 | """Perform multi-looking on a Stack, and return a Stack. 8 | 9 | Parameters 10 | ---------- 11 | data : xarray.Dataset or xarray.DataArray 12 | The data to be multi-looked. 13 | window_size : tuple 14 | Window size for multi-looking, in the format of (azimuth, range) 15 | method : str, optional 16 | Method of multi-looking, by default "coarsen" 17 | statistics : str, optional 18 | Statistics method for multi-looking, by default "mean" 19 | compute : bool, optional 20 | Whether to compute the result, by default True. If False, the result 21 | will be `dask.delayed.Delayed`. This is useful when the multi_look 22 | is used as an intermediate result. 23 | 24 | Returns 25 | ------- 26 | xarray.Dataset or xarray.DataArray 27 | An `xarray.Dataset` or `xarray.DataArray` with coarsen shape if 28 | `compute` is True, otherwise a `dask.delayed.Delayed` object. 29 | """ 30 | # validate the input 31 | _validate_multi_look_inputs(data, window_size, method, statistics) 32 | 33 | # chunk data if not already chunked 34 | if isinstance(data, Delayed) or not data.chunks: 35 | data = data.chunk("auto") 36 | 37 | # get the chunk size 38 | if isinstance(data, Delayed): 39 | chunks = "auto" 40 | else: 41 | chunks = _get_chunks(data, window_size) 42 | 43 | # add new atrrs here because Delayed objects are immutable 44 | data.attrs["multi-look"] = f"{method}-{statistics}" 45 | 46 | # define custom coordinate function to define new coordinates starting 47 | # from 0: the inputs `reshaped` and `axis` are output of 48 | # `coarsen_reshape` internal function and are passed to the `coord_func` 49 | def _custom_coord_func(reshaped, axis): 50 | if axis[0] == 1 or axis[0] == 2: 51 | return np.arange(0, reshaped.shape[0], 1, dtype=int) 52 | else: 53 | return reshaped.flatten() 54 | 55 | if method == "coarsen": 56 | # TODO: if boundary and size should be configurable 57 | multi_looked = data.coarsen( 58 | {"azimuth": window_size[0], "range": window_size[1]}, 59 | boundary="trim", 60 | side="left", 61 | coord_func=_custom_coord_func, 62 | ) 63 | 64 | # apply statistics 65 | stat_functions = { 66 | "mean": multi_looked.mean, 67 | "median": multi_looked.median, 68 | } 69 | 70 | stat_function = stat_functions[statistics] 71 | if compute: 72 | multi_looked = stat_function(keep_attrs=True) 73 | else: 74 | multi_looked = delayed(stat_function)(keep_attrs=True) 75 | 76 | # Rechunk is needed because shape of the data will be changed after 77 | # multi-looking 78 | multi_looked = multi_looked.chunk(chunks) 79 | 80 | return multi_looked 81 | 82 | 83 | def complex_coherence( 84 | reference: xr.DataArray, other: xr.DataArray, window_size, compute=True 85 | ): 86 | """Calculate complex coherence of two images. 87 | 88 | Assume two images reference (R) and other (O), the complex coherence is 89 | defined as: 90 | numerator = mean(R * O`) in a window 91 | denominator = mean(R * R`) * mean(O * O`) in a window 92 | coherence = abs( numerator / sqrt(denominator) ), 93 | See the equationin chapter 28 in http://doris.tudelft.nl/software/doris_v4.02.pdf 94 | 95 | Parameters 96 | ---------- 97 | reference : xarray.DataArray 98 | The reference image to calculate complex coherence with. 99 | other : xarray.DataArray 100 | The other image to calculate complex coherence with. 101 | window_size : tuple 102 | Window size for multi-looking, in the format of (azimuth, range) 103 | compute : bool, optional 104 | Whether to compute the result, by default True. If False, the result 105 | will be `dask.delayed.Delayed`. This is useful when the complex_coherence 106 | is used as an intermediate result. 107 | 108 | Returns 109 | ------- 110 | xarray.DataArray 111 | An `xarray.DataArray` if `compute` is True, 112 | otherwise a `dask.delayed.Delayed` object. 113 | """ 114 | # check if the two images have the same shape 115 | if ( 116 | reference.azimuth.size != other.azimuth.size 117 | or reference.range.size != other.range.size 118 | ): 119 | raise ValueError("The two images have different shape.") 120 | 121 | # check if dtype is complex 122 | if reference.dtype != np.complex64 or other.dtype != np.complex64: 123 | raise ValueError("The dtype of the two images must be complex64.") 124 | 125 | # calculate the numerator of the equation 126 | da = reference * other.conj() 127 | numerator = multi_look( 128 | da, window_size, method="coarsen", statistics="mean", compute=compute 129 | ) 130 | 131 | # calculate the denominator of the equation 132 | da = reference * reference.conj() 133 | reference_mean = multi_look( 134 | da, window_size, method="coarsen", statistics="mean", compute=compute 135 | ) 136 | 137 | da = other * other.conj() 138 | other_mean = multi_look( 139 | da, window_size, method="coarsen", statistics="mean", compute=compute 140 | ) 141 | 142 | denominator = reference_mean * other_mean 143 | 144 | # calculate the coherence 145 | def _compute_coherence(numerator, denominator): 146 | return np.abs(numerator / np.sqrt(denominator)) 147 | 148 | if compute: 149 | coherence = _compute_coherence(numerator, denominator) 150 | else: 151 | coherence = delayed(_compute_coherence)(numerator, denominator) 152 | 153 | return coherence 154 | 155 | 156 | def _validate_multi_look_inputs(data, window_size, method, statistics): 157 | # check if data is xarray 158 | if not isinstance(data, xr.Dataset | xr.DataArray): 159 | raise TypeError("The data must be an xarray.Dataset or xarray.DataArray.") 160 | 161 | # check if azimuth, range are in the dimensions 162 | if not {"azimuth", "range"}.issubset(data.dims): 163 | raise ValueError("The data must have azimuth and range dimensions.") 164 | 165 | # check if window_size is valid 166 | if window_size[0] > data.azimuth.size or window_size[1] > data.range.size: 167 | raise ValueError("Window size is larger than data size.") 168 | 169 | # check if method is valid 170 | if method not in ["coarsen"]: 171 | raise ValueError("The method must be one of ['coarsen'].") 172 | 173 | # check if statistics is valid 174 | if statistics not in ["mean", "median"]: 175 | raise ValueError("The statistics must be one of ['mean', 'median'].") 176 | 177 | 178 | def _get_chunks(data, window_size): 179 | if isinstance(data, xr.Dataset): 180 | chunks = { 181 | "azimuth": data.chunks["azimuth"][0], 182 | "range": data.chunks["range"][0], 183 | } 184 | if "time" in data.dims: 185 | chunks["time"] = data.chunks["time"][0] 186 | elif isinstance(data, xr.DataArray): 187 | chunks = {"azimuth": data.chunks[0][0], "range": data.chunks[1][0]} 188 | if "time" in data.dims: 189 | chunks["time"] = data.chunks[2][0] 190 | 191 | # check if window_size is smaller than chunks size 192 | if window_size[0] > chunks["azimuth"] or window_size[1] > chunks["range"]: 193 | raise ValueError( 194 | f"Window size ({window_size}) should be smaller than chunk size ({chunks})" 195 | ) 196 | 197 | # calculate new chunck size based on the window size and the existing chunk 198 | # size 199 | chunks["azimuth"] = int(np.ceil(chunks["azimuth"] / window_size[0])) 200 | chunks["range"] = int(np.ceil(chunks["range"] / window_size[1])) 201 | 202 | return chunks 203 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """The setup script.""" 2 | 3 | from setuptools import setup 4 | 5 | setup() 6 | -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | sonar.organization=tudelftgeodesy 2 | sonar.projectKey=TUDelftGeodesy_sarxarray 3 | sonar.host.url=https://sonarcloud.io 4 | sonar.sources=sarxarray/ 5 | sonar.tests=tests/ 6 | sonar.links.homepage=https://github.com/TUDelftGeodesy/sarxarray 7 | sonar.links.issue=https://github.com/TUDelftGeodesy/sarxarray/issues 8 | sonar.links.ci=https://github.com/TUDelftGeodesy/sarxarray/actions 9 | sonar.python.coverage.reportPaths=coverage.xml 10 | sonar.python.xunit.reportPath=xunit-result.xml 11 | sonar.python.pylint.reportPaths=pylint-report.txt 12 | sonar.python.version= 3.10, 3.11 -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TUDelftGeodesy/sarxarray/017f039ec17f53e03d73f0e7d848922013d57e32/tests/__init__.py -------------------------------------------------------------------------------- /tests/data/scene_0.binaray: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TUDelftGeodesy/sarxarray/017f039ec17f53e03d73f0e7d848922013d57e32/tests/data/scene_0.binaray -------------------------------------------------------------------------------- /tests/data/scene_1.binaray: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TUDelftGeodesy/sarxarray/017f039ec17f53e03d73f0e7d848922013d57e32/tests/data/scene_1.binaray -------------------------------------------------------------------------------- /tests/data/zarrs/slcs_example.zarr/.zattrs: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /tests/data/zarrs/slcs_example.zarr/.zgroup: -------------------------------------------------------------------------------- 1 | { 2 | "zarr_format": 2 3 | } -------------------------------------------------------------------------------- /tests/data/zarrs/slcs_example.zarr/.zmetadata: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | ".zattrs": {}, 4 | ".zgroup": { 5 | "zarr_format": 2 6 | }, 7 | "azimuth/.zarray": { 8 | "chunks": [ 9 | 350 10 | ], 11 | "compressor": { 12 | "blocksize": 0, 13 | "clevel": 5, 14 | "cname": "lz4", 15 | "id": "blosc", 16 | "shuffle": 1 17 | }, 18 | "dtype": "