rasterix 0.1a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ ci:
2
+ autoupdate_schedule: quarterly
3
+
4
+ repos:
5
+ - repo: https://github.com/astral-sh/ruff-pre-commit
6
+ # Ruff version.
7
+ rev: "v0.11.4"
8
+ hooks:
9
+ - id: ruff
10
+ args: ["--fix", "--show-fixes"]
11
+ - id: ruff-format
12
+
13
+ - repo: https://github.com/pre-commit/mirrors-prettier
14
+ rev: "v4.0.0-alpha.8"
15
+ hooks:
16
+ - id: prettier
17
+
18
+ - repo: https://github.com/pre-commit/pre-commit-hooks
19
+ rev: v5.0.0
20
+ hooks:
21
+ - id: check-yaml
22
+ - id: trailing-whitespace
23
+ - id: end-of-file-fixer
24
+ - id: check-docstring-first
25
+
26
+ - repo: https://github.com/executablebooks/mdformat
27
+ rev: 0.7.22
28
+ hooks:
29
+ - id: mdformat
30
+ additional_dependencies:
31
+ - mdformat-black
32
+ - mdformat-myst
33
+
34
+ # - repo: https://github.com/kynan/nbstripout
35
+ # rev: 0.8.1
36
+ # hooks:
37
+ # - id: nbstripout
38
+ # args: [--extra-keys=metadata.kernelspec metadata.language_info.version]
39
+
40
+ - repo: https://github.com/codespell-project/codespell
41
+ rev: v2.4.1
42
+ hooks:
43
+ - id: codespell
44
+ additional_dependencies:
45
+ - tomli
46
+
47
+ - repo: https://github.com/abravalheri/validate-pyproject
48
+ rev: v0.24.1
49
+ hooks:
50
+ - id: validate-pyproject
51
+
52
+ - repo: https://github.com/rhysd/actionlint
53
+ rev: v1.7.7
54
+ hooks:
55
+ - id: actionlint
56
+ files: ".github/workflows/"
57
+ args:
58
+ [
59
+ "-ignore",
60
+ "SC1090",
61
+ "-ignore",
62
+ "SC2046",
63
+ "-ignore",
64
+ "SC2086",
65
+ "-ignore",
66
+ "SC2129",
67
+ "-ignore",
68
+ "SC2155",
69
+ ]
rasterix-0.1a1/LICENSE ADDED
@@ -0,0 +1,191 @@
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, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form, made
34
+ available under the License, as indicated by a copyright notice that is included
35
+ in or attached to the work (an example is provided in the Appendix below).
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work
47
+ by the copyright owner or by an individual or Legal Entity authorized to submit
48
+ on behalf of the copyright owner. For the purposes of this definition,
49
+ "submitted" means any form of electronic, verbal, or written communication sent
50
+ to the Licensor or its representatives, including but not limited to
51
+ communication on electronic mailing lists, source code control systems, and
52
+ issue tracking systems that are managed by, or on behalf of, the Licensor for
53
+ the purpose of discussing and improving the Work, but excluding communication
54
+ that is conspicuously marked or otherwise designated in writing by the copyright
55
+ owner as "Not a Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License.
62
+
63
+ Subject to the terms and conditions of this License, each Contributor hereby
64
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65
+ irrevocable copyright license to reproduce, prepare Derivative Works of,
66
+ publicly display, publicly perform, sublicense, and distribute the Work and such
67
+ Derivative Works in Source or Object form.
68
+
69
+ 3. Grant of Patent License.
70
+
71
+ Subject to the terms and conditions of this License, each Contributor hereby
72
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73
+ irrevocable (except as stated in this section) patent license to make, have
74
+ made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75
+ such license applies only to those patent claims licensable by such Contributor
76
+ that are necessarily infringed by their Contribution(s) alone or by combination
77
+ of their Contribution(s) with the Work to which such Contribution(s) was
78
+ submitted. If You institute patent litigation against any entity (including a
79
+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80
+ Contribution incorporated within the Work constitutes direct or contributory
81
+ patent infringement, then any patent licenses granted to You under this License
82
+ for that Work shall terminate as of the date such litigation is filed.
83
+
84
+ 4. Redistribution.
85
+
86
+ You may reproduce and distribute copies of the Work or Derivative Works thereof
87
+ in any medium, with or without modifications, and in Source or Object form,
88
+ provided that You meet the following conditions:
89
+
90
+ You must give any other recipients of the Work or Derivative Works a copy of
91
+ this License; and
92
+ You must cause any modified files to carry prominent notices stating that You
93
+ changed the files; and
94
+ You must retain, in the Source form of any Derivative Works that You distribute,
95
+ all copyright, patent, trademark, and attribution notices from the Source form
96
+ of the Work, excluding those notices that do not pertain to any part of the
97
+ Derivative Works; and
98
+ If the Work includes a "NOTICE" text file as part of its distribution, then any
99
+ Derivative Works that You distribute must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, excluding those notices
101
+ that do not pertain to any part of the Derivative Works, in at least one of the
102
+ following places: within a NOTICE text file distributed as part of the
103
+ Derivative Works; within the Source form or documentation, if provided along
104
+ with the Derivative Works; or, within a display generated by the Derivative
105
+ Works, if and wherever such third-party notices normally appear. The contents of
106
+ the NOTICE file are for informational purposes only and do not modify the
107
+ License. You may add Your own attribution notices within Derivative Works that
108
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+ provided that such additional attribution notices cannot be construed as
110
+ modifying the License.
111
+ You may add Your own copyright statement to Your modifications and may provide
112
+ additional or different license terms and conditions for use, reproduction, or
113
+ distribution of Your modifications, or for any such Derivative Works as a whole,
114
+ provided Your use, reproduction, and distribution of the Work otherwise complies
115
+ with the conditions stated in this License.
116
+
117
+ 5. Submission of Contributions.
118
+
119
+ Unless You explicitly state otherwise, any Contribution intentionally submitted
120
+ for inclusion in the Work by You to the Licensor shall be under the terms and
121
+ conditions of this License, without any additional terms or conditions.
122
+ Notwithstanding the above, nothing herein shall supersede or modify the terms of
123
+ any separate license agreement you may have executed with Licensor regarding
124
+ such Contributions.
125
+
126
+ 6. Trademarks.
127
+
128
+ This License does not grant permission to use the trade names, trademarks,
129
+ service marks, or product names of the Licensor, except as required for
130
+ reasonable and customary use in describing the origin of the Work and
131
+ reproducing the content of the NOTICE file.
132
+
133
+ 7. Disclaimer of Warranty.
134
+
135
+ Unless required by applicable law or agreed to in writing, Licensor provides the
136
+ Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138
+ including, without limitation, any warranties or conditions of TITLE,
139
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140
+ solely responsible for determining the appropriateness of using or
141
+ redistributing the Work and assume any risks associated with Your exercise of
142
+ permissions under this License.
143
+
144
+ 8. Limitation of Liability.
145
+
146
+ In no event and under no legal theory, whether in tort (including negligence),
147
+ contract, or otherwise, unless required by applicable law (such as deliberate
148
+ and grossly negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special, incidental,
150
+ or consequential damages of any character arising as a result of this License or
151
+ out of the use or inability to use the Work (including but not limited to
152
+ damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153
+ any and all other commercial damages or losses), even if such Contributor has
154
+ been advised of the possibility of such damages.
155
+
156
+ 9. Accepting Warranty or Additional Liability.
157
+
158
+ While redistributing the Work or Derivative Works thereof, You may choose to
159
+ offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160
+ other liability obligations and/or rights consistent with this License. However,
161
+ in accepting such obligations, You may act only on Your own behalf and on Your
162
+ sole responsibility, not on behalf of any other Contributor, and only if You
163
+ agree to indemnify, defend, and hold each Contributor harmless for any liability
164
+ incurred by, or claims asserted against, such Contributor by reason of your
165
+ accepting any such warranty or additional liability.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ APPENDIX: How to apply the Apache License to your work
170
+
171
+ To apply the Apache License to your work, attach the following boilerplate
172
+ notice, with the fields enclosed by brackets "[]" replaced with your own
173
+ identifying information. (Don't include the brackets!) The text should be
174
+ enclosed in the appropriate comment syntax for the file format. We also
175
+ recommend that a file or class name and description of purpose be included on
176
+ the same "printed page" as the copyright notice for easier identification within
177
+ third-party archives.
178
+
179
+ Copyright 2014-2025 Deepak Cherian
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,26 @@
1
+ Metadata-Version: 2.4
2
+ Name: rasterix
3
+ Version: 0.1a1
4
+ Summary: Raster extensions for Xarray
5
+ License-Expression: Apache-2.0
6
+ Keywords: xarray
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Natural Language :: English
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: affine
19
+ Requires-Dist: pandas>=2
20
+ Requires-Dist: numpy>=2
21
+ Requires-Dist: xarray>=2025
22
+ Dynamic: license-file
23
+
24
+ # rasterix: Raster tricks for Xarray
25
+
26
+ <img src="rasterix.png" width="400">
@@ -0,0 +1,3 @@
1
+ # rasterix: Raster tricks for Xarray
2
+
3
+ <img src="rasterix.png" width="400">
@@ -0,0 +1,150 @@
1
+ # Design for a RasterIndex
2
+
3
+ ## TL;DR
4
+
5
+ 1. We propose designing a RasterIndex that can handle many ways of expressing a raster → model space transformation.
6
+ 1. We propose that this RasterIndex _record_ the information for this transformation (e.g. `GeoTransform`) _internally_ and remove that information from the dataset when constructed.
7
+ 1. Since the information is recorded internally, a user must intentionally write the transformation back to the dataset, destroying the index while doing so, and then write to disk.
8
+
9
+ ## Goals:
10
+
11
+ ### UX goals:
12
+
13
+ 1. Make it easy to read a GeoTIFF with CRS and raster -> model space transformation information in to Xarray with appropriate indexes. There are at least two indexes: one associated with the CRS; and one with the transformation.
14
+ 1. The raster ↔ model transformation information can be ambiguous, so an explicit API should be provided.
15
+ 1. [RPCs](http://geotiff.maptools.org/rpc_prop.html):
16
+ > The RPC model in a GeoTIFF file is supplementary to all other GeoTIFF tags and not directly related. That is, it is possible to have a conventional set of GeoTIFF tags (such as a tiepoint + pixel scale + projected coordinate system description) along with the RPCCoefficientTag. The RPCCoefficientTag is always describing a transformation to WGS84, regardless of what geographic coordinate system might be described in the coordinate system description tags of the GeoTIFF file. It is also possible to have only the RPCCoefficientTag tag and no other GeoTIFF tags.
17
+ 1. [GeoTransform is not in the GeoTIFF standard](https://docs.ogc.org/is/19-008r4/19-008r4.html). Instead that uses ModelTiepointTag, ModelPixelScaleTag, ModelTransformationTag.
18
+ 1. [GCPs are ambiguous](https://gdal.org/en/stable/user/raster_data_model.html#gcps):
19
+ > The GDAL data model does not imply a transformation mechanism that must be generated from the GCPs … this is left to the application. However 1st to 5th order polynomials are common.
20
+ 1. [And for extra fun](https://gdal.org/en/stable/user/raster_data_model.html#gcps):
21
+ > Normally a dataset will contain either an affine geotransform, GCPs or neither. It is uncommon to have both, and it is undefined which is authoritative.
22
+
23
+ ### Index design goals:
24
+
25
+ 1. The CRS Index allows us to assert CRS compliance during alignment. This is provided by XProj.
26
+ 1. The transform index should allow us to:
27
+ 1. Do accurate alignment in pixel space unaffected by floating-point inaccuracies in model-space;
28
+ 1. All possible transforms have **offsets** which means they need to be kept up-to-date during slicing.
29
+ 1. Allow extracting metadata necessary to accurately represent the information on disk.
30
+
31
+ ## Some complications
32
+
33
+ ### Handling projections
34
+
35
+ 1. There are at least 5 ways to record a raster ⇒ model space transformation.
36
+ 1. Information for these transforms may be stored in many places depending on the reading library:
37
+ 1. `ds.spatial_ref.attrs`(rioxarray stores GeoTransform, gcps here)
38
+ 1. `ds.band_data.attrs` (rioxarray stores TIEPOINTS here)
39
+ 1. `ds.attrs` possibly since this would be the most direct way to map TIFF tags
40
+ 1. It seems possible to store RPCs as either arrays or as attrs.
41
+
42
+ We'd like a design that is extensible to handle all 5 (or more) cases; again suggesting an explicit lower-level API.
43
+
44
+ ### Composing with CRSIndex
45
+
46
+ [One unanswered question so far is](https://github.com/benbovy/xproj/issues/22#issuecomment-2789459387)
47
+
48
+ > I think the major decision is "who handles the spatial_ref / grid mapping variable". Should it be exclusively handled by xproj.CRSIndex? Or should it be bound to a geospatial index such as rasterix.RasterIndex, xvec.GeometryIndex, xoak.S2PointIndex, etc.?
49
+
50
+ i.e. does the Index wrap CRSIndex too, or compose with it.
51
+ Some points:
52
+
53
+ 1. reprojection requires handling both the transform and the CRS.
54
+ 1. the EDR-like selection API is similar.
55
+
56
+ Importantly, GDAL chooses to write GeoTransform to the `grid_mapping` variable in netCDF which _also_ records CRS information.
57
+
58
+ This gives us two options:
59
+
60
+ 1. RasterIndex wraps CRSIndex too and handles everything.
61
+ 1. RasterIndex extracts projection information, however it is stored (e.g. GeoTransform), and tracks it internally. Any functionality that relies on both the transformation and CRS will need to be built as an accessor layer.
62
+
63
+ Below is a proposal for (2).
64
+
65
+ ## Proposal for transform index
66
+
67
+ We design RasterIndex as a wrapper around **one** of many transform based indexes:
68
+
69
+ 1. AffineTransformIndex ↔ GeoTransform
70
+ 1. ModelTransformationIndex ↔ ModelTransformationTag
71
+ 1. ModelTiepointScaleIndex ↔ ModelTiepointTag + ModelPixelScaleTag
72
+ 1. GCPIndex ↔ Ground Control Points
73
+ 1. RPCIndex ↔ Rational Polynomial Coefficients
74
+ 1. Subsampled auxiliary coordinates, detailed in [CF section 8.3](https://cfconventions.org/Data/cf-conventions/cf-conventions-1.12/cf-conventions.html#compression-by-coordinate-subsampling) and equivalent to GDAL's [geolocation arrays](https://gdal.org/en/stable/development/rfc/rfc4_geolocate.html) with `PIXEL_STEP` and/or LINE_STEP\` > 1.
75
+
76
+ Each of the wrapped index has an associated transform:
77
+
78
+ ```python
79
+ @dataclass
80
+ class RasterTransform:
81
+ rpc: RPC | None # rpcs
82
+ tiepoint_scale : ModelTiepointAndScale | None # ModelTiepointTag, ModelPixelScaleTag
83
+ gcps: GroundControlPoints | None
84
+ transformation : ModelTransformation | None
85
+ geotransform : Affine | None # GeoTransform
86
+
87
+ def from_geotransform(attrs: dict) -> Self:
88
+ ...
89
+
90
+ def from_tiepoints(attrs: dict) -> Self:
91
+ ...
92
+
93
+ def from_gcps(gcps: ?) -> Self:
94
+ ...
95
+
96
+ def from_rpcs(?) -> Self:
97
+ ...
98
+
99
+ def from_geolocation_arrays(?) -> Self:
100
+ ...
101
+ ```
102
+
103
+ ### Read-time
104
+
105
+ These transforms are constructed by **popping** the relevant information from a user-provided source.
106
+ This is analogous to an "encode/decode" workflow we currently have in Xarray.
107
+
108
+ ```python
109
+ transform = rasterix.RasterTransform.from_geotransform(ds.spatial_ref.attrs)
110
+ # transform = rasterix.RasterTransform.from_tiepoints(ds.band_data.attrs)
111
+ ```
112
+
113
+ By **popping** the information, the transformation is stored _only_ on the index, and must be rewritten back to the dataset by the user when writing to the disk. This is the RioXarray pattern.
114
+
115
+ Once a transform is constructed, we could do
116
+
117
+ ```python
118
+ index = RasterIndex.from_transform(transform, dims_and_sizes=...)
119
+ ds = ds.assign_coords(xr.Coordinates.from_xindex(index))
120
+ ds = ds.set_xindex("spatial_ref", xproj.CRSIndex)
121
+ ```
122
+
123
+ ### Write-time
124
+
125
+ Before write, we must write the transform (similar to rioxarray) and _destroy_ the RasterIndex instance.
126
+ This seems almost required since there are many ways of recording the transformation information on the dataset; and many of these approaches might be used in the same dataset.
127
+
128
+ ```python
129
+ # encodes the internal RasterTransform in attributes of the `to` variable
130
+ # destroys the RasterIndex
131
+ ds = ds.rasterix.write_transform(to: Hashable | rasterix.SELF, formats=["geotransform", "tiepoint"])
132
+ ds.rio.to_raster()
133
+ ```
134
+
135
+ Here:
136
+
137
+ 1. `SELF` could mean write to the object (Dataset | DataArray) attrs
138
+ 1. `formats` allow you to record the same information in multiple ways
139
+ 1. `.rio.write_transform` could just dispatch to this method.
140
+
141
+ ## Appendix
142
+
143
+ ### Encode/decode workflow for subsampled coordinates
144
+
145
+ Taking the example 8.3 from [CF section 8.3](https://cfconventions.org/Data/cf-conventions/cf-conventions-1.12/cf-conventions.html#compression-by-coordinate-subsampling), the decode step may consist in:
146
+
147
+ 1. turn the tie point coordinate variables `lat(tp_yc, tp_xc)` and `lon(tp_yc, tp_xc)` into `lat(yc, xc)` and `lon(yc, xc)` in to Xarray coordinates associated with a custom transformation index that stores only the tie points. In other words, uncompress the dimensions of the `lat` & `lon` coordinates without uncompressing their data.
148
+ 1. also remove the tie point index variables and the interpolation variable, and track their data / metadata internally in the index
149
+
150
+ The encode step would then consist in restoring the compressed tie point coordinate & index variables as well as the interpolation variable.
@@ -0,0 +1,191 @@
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "0",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Raster dataset examples\n",
9
+ "\n",
10
+ "Written by ChatGPT.\n",
11
+ "\n",
12
+ "## GeoTiffs with GCPs and Tiepoints"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "execution_count": null,
18
+ "id": "1",
19
+ "metadata": {},
20
+ "outputs": [],
21
+ "source": [
22
+ "import numpy as np\n",
23
+ "import rasterio\n",
24
+ "from rasterio.control import GroundControlPoint\n",
25
+ "from rasterio.transform import Affine\n",
26
+ "\n",
27
+ "# Define file path for output GeoTIFF\n",
28
+ "output_tiff = \"output_with_gcps_tiepoints.tif\"\n",
29
+ "\n",
30
+ "# Create a dummy raster (100x100) with random values\n",
31
+ "width, height = 100, 100\n",
32
+ "data = np.random.randint(0, 255, (1, height, width), dtype=np.uint8)\n",
33
+ "\n",
34
+ "# Define Affine transformation (default identity)\n",
35
+ "transform = Affine.translation(0, 0) * Affine.scale(1, -1)\n",
36
+ "\n",
37
+ "# Define Ground Control Points (GCPs)\n",
38
+ "gcps = [\n",
39
+ " GroundControlPoint(row=10, col=20, x=-122.123, y=37.456, z=50),\n",
40
+ " GroundControlPoint(row=30, col=40, x=-122.456, y=37.789, z=60),\n",
41
+ " GroundControlPoint(row=50, col=60, x=-122.789, y=38.123, z=55),\n",
42
+ "]\n",
43
+ "\n",
44
+ "# Define Tie Points (Model Tiepoints)\n",
45
+ "tie_points = [\n",
46
+ " (0, 0, 0, -122.1, 37.4, 0),\n",
47
+ " (50, 50, 0, -122.2, 37.5, 0),\n",
48
+ "]\n",
49
+ "\n",
50
+ "# Create a new GeoTIFF with GCPs\n",
51
+ "with rasterio.open(\n",
52
+ " output_tiff,\n",
53
+ " \"w\",\n",
54
+ " driver=\"GTiff\",\n",
55
+ " height=height,\n",
56
+ " width=width,\n",
57
+ " count=1,\n",
58
+ " dtype=rasterio.uint8,\n",
59
+ " crs=\"EPSG:4326\", # Define coordinate reference system (WGS84)\n",
60
+ " transform=transform,\n",
61
+ ") as dst:\n",
62
+ " dst.write(data)\n",
63
+ "\n",
64
+ " # Add Ground Control Points\n",
65
+ " dst.gcps = (gcps, dst.crs)\n",
66
+ "\n",
67
+ " # Add Tie Points as metadata\n",
68
+ " dst.update_tags(TIEPOINTS=str(tie_points))\n",
69
+ "\n",
70
+ "print(f\"GeoTIFF with GCPs and Tie Points saved as {output_tiff}\")"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": null,
76
+ "id": "2",
77
+ "metadata": {},
78
+ "outputs": [],
79
+ "source": [
80
+ "import xarray as xr\n",
81
+ "\n",
82
+ "xr.open_dataset(\"output_with_gcps_tiepoints.tif\", engine=\"rasterio\")"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "execution_count": null,
88
+ "id": "3",
89
+ "metadata": {},
90
+ "outputs": [],
91
+ "source": [
92
+ "import rasterio\n",
93
+ "\n",
94
+ "# Open the saved GeoTIFF\n",
95
+ "output_tiff = \"output_with_gcps_tiepoints.tif\"\n",
96
+ "\n",
97
+ "with rasterio.open(output_tiff) as dataset:\n",
98
+ " print(\"GeoTransform (Affine Transformation):\")\n",
99
+ " print(dataset.transform)\n",
100
+ " print(dataset.gcps)\n",
101
+ " print(dataset.tags())"
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "markdown",
106
+ "id": "4",
107
+ "metadata": {},
108
+ "source": [
109
+ "## GDAL netCDF with GeoTransform\n",
110
+ "\n",
111
+ "rasterio cannot write to netCDF"
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": null,
117
+ "id": "5",
118
+ "metadata": {},
119
+ "outputs": [],
120
+ "source": [
121
+ "import numpy as np\n",
122
+ "from osgeo import gdal, osr\n",
123
+ "\n",
124
+ "# Define the output netCDF file\n",
125
+ "output_file = \"output.nc\"\n",
126
+ "\n",
127
+ "# Define raster dimensions\n",
128
+ "cols = 10 # Number of columns\n",
129
+ "rows = 10 # Number of rows\n",
130
+ "bands = 1 # Number of bands\n",
131
+ "\n",
132
+ "# Define geotransform (Origin X, Pixel Width, Rotation, Origin Y, Rotation, Pixel Height)\n",
133
+ "geotransform = [100.0, 30.0, 0.0, 200.0, 0.0, -30.0] # Example values\n",
134
+ "\n",
135
+ "# Define a spatial reference (WGS84 in this case)\n",
136
+ "srs = osr.SpatialReference()\n",
137
+ "srs.ImportFromEPSG(4326) # WGS84\n",
138
+ "proj_wkt = srs.ExportToWkt()\n",
139
+ "\n",
140
+ "# Create a new netCDF file using GDAL\n",
141
+ "driver = gdal.GetDriverByName(\"netCDF\")\n",
142
+ "dataset = driver.Create(output_file, cols, rows, bands, gdal.GDT_Float32)\n",
143
+ "\n",
144
+ "# Set geotransform and projection\n",
145
+ "dataset.SetGeoTransform(geotransform)\n",
146
+ "dataset.SetProjection(proj_wkt)\n",
147
+ "\n",
148
+ "# Create some dummy data (a simple gradient)\n",
149
+ "data = np.arange(cols * rows, dtype=np.float32).reshape(rows, cols)\n",
150
+ "\n",
151
+ "# Write data to the first band\n",
152
+ "band = dataset.GetRasterBand(1)\n",
153
+ "band.WriteArray(data)\n",
154
+ "band.SetNoDataValue(-9999) # Set a no-data value\n",
155
+ "\n",
156
+ "# Flush and close dataset\n",
157
+ "band.FlushCache()\n",
158
+ "dataset = None\n",
159
+ "\n",
160
+ "print(f\"NetCDF file '{output_file}' created with geotransform and projection.\")"
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "execution_count": null,
166
+ "id": "6",
167
+ "metadata": {},
168
+ "outputs": [],
169
+ "source": [
170
+ "import xarray as xr\n",
171
+ "\n",
172
+ "xr.open_dataset(\"output.nc\")"
173
+ ]
174
+ }
175
+ ],
176
+ "metadata": {
177
+ "language_info": {
178
+ "codemirror_mode": {
179
+ "name": "ipython",
180
+ "version": 3
181
+ },
182
+ "file_extension": ".py",
183
+ "mimetype": "text/x-python",
184
+ "name": "python",
185
+ "nbconvert_exporter": "python",
186
+ "pygments_lexer": "ipython3"
187
+ }
188
+ },
189
+ "nbformat": 4,
190
+ "nbformat_minor": 5
191
+ }