pyarea 0.2.0__py3-none-any.whl

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,3 @@
1
+ from pyarea.navigation import area_navigation, hrit_navigation, proj4_navigation
2
+
3
+ __all__ = ['area_navigation', 'hrit_navigation', 'proj4_navigation']
@@ -0,0 +1,183 @@
1
+ import numpy as np
2
+
3
+ from pyarea.navigation import hrit_navigation as hnav
4
+ from pyarea.navigation import proj4_navigation as pnav
5
+
6
+
7
+ def test_chunk_intersection(af=None, points=None, lon0=None, gt=None):
8
+ """
9
+ test if a chunk of image represented by four corners intersects an AreaFile
10
+ :param af: str, path tothe pyarea file
11
+ :param points: iter of 4 points (line, column) in range 0-number of lines in the image, 0-number of columns in the image
12
+ :param lon0: SSp longitude of the image (geos)
13
+ :param gt: geotransform
14
+ :return:
15
+ """
16
+
17
+
18
+ nv = 1e30
19
+ nav = af.navigation
20
+ top, bottom, left, right = af.areabox
21
+ yres, xres = af.resolution
22
+ top*=yres
23
+ bottom*=yres
24
+ left*=xres
25
+ right*=xres
26
+ for e in points:
27
+ l, c = e
28
+ lat, lon = pnav.lc2ll(l=l, c=c, ssp=lon0, gt=gt)
29
+ if lat == nv or lon == nv:
30
+ continue
31
+ else:
32
+ area_cs, area_ls = nav.toLinEle(latlon=[[lat], [lon]])
33
+ area_l = area_ls[0]
34
+ area_c = area_cs[0]
35
+
36
+ if (top <= area_l < bottom) and (left <=area_c < right):
37
+ return True
38
+ return False
39
+
40
+
41
+
42
+
43
+
44
+ def reproject_area2geos(af=None, out_resolution=2000, out_ssp=None, use_proj_navigation=False, reproject_in_chunks=False, return_gdalinfo=False):
45
+ """
46
+ Reproject an McIDAS pyarea file featuring GVAR navigation to geostationary projection
47
+ :param in_area_file: pyarea file obj from pyarea lib
48
+ :param out_resolution: int, the resoution of the geostationary reprojected data (meters)
49
+ :param out_ssp: number (usually float), the SSP of the output geostationary file, if not supplied it is taken and rounded from the Area file
50
+ :param use_proj_navigation: bool, if true, proj4 based navigation will be used
51
+ :param reproject_in_chunks: bool, if true a ckunk based approach will be employed to avoid memory issues
52
+ :param return_gdalinfo, bool, if true then geotransform nad projection string are returned as a tuple
53
+ :return: 2D numpy array representing the reprojected data
54
+
55
+ Notes:
56
+ The reprojection is performed by creating index grids on Y and X axis in geostationary
57
+ projection and then reprojecting these grids to lat/lon index grids. These can be done using proj4 or HRIT based navigation
58
+ The geographical index grids are then transformed into GVAR index grids (Area file coordinates not Image coordinates)
59
+ For a detailed account consult https://www.ssec.wisc.edu/mcidas/doc/learn_guide/2015/sat-1.html
60
+ The pyarea file index grids are the used to fetch the pixels from input pyarea file and reproject
61
+ using nearest neighbour to geostationary projection
62
+
63
+ """
64
+ try:
65
+
66
+
67
+
68
+ navigation = af.navigation # GVAR
69
+ data = af.data.squeeze()
70
+ # imshow(data)
71
+ # show()
72
+ anl, anc = data.shape # dimensions of input pyarea file data
73
+ # the dimensions of the dataset
74
+ offset = hnav.compute_offset(out_resolution)
75
+ scale_fact = hnav.compute_scale_factor(out_resolution)
76
+
77
+ nl = nc = 2 * offset # the output image has same size in each dimension
78
+ # allocate output
79
+ out_geos_data = np.zeros((nl, nc), dtype=data.dtype)
80
+
81
+
82
+ # SS longitude
83
+ lon0 = navigation.subpoint[1] if out_ssp is None else out_ssp
84
+ lon0 = int(round(lon0))
85
+ # compute GeoTranform
86
+ half_width = offset * out_resolution
87
+ geotr = -half_width, out_resolution, 0, half_width, 0, -out_resolution
88
+ nsegs = 5 # split the full diska space into 5X5
89
+ seg_len = nl / nsegs
90
+
91
+ if use_proj_navigation:
92
+ if not reproject_in_chunks:
93
+ l, c = np.mgrid[0:nl, 0:nc]
94
+ lats, lons = pnav.lc2ll(l=l, c=c, ssp=lon0, gt=geotr)
95
+
96
+ else:
97
+ for i in range(nsegs):
98
+ sl = i * seg_len
99
+ el = sl + seg_len
100
+ for j in range(nsegs):
101
+ sc = j * seg_len
102
+ ec = sc + seg_len
103
+ corners = ((sl + 1, sc + 1), (sl + 1, ec + 1), (el + 1, sc + 1), (el + 1, ec + 1))
104
+ should_continue = test_chunk_intersection(af=af, points=corners, lon0=lon0, gt=geotr)
105
+ if should_continue:
106
+ l, c = np.mgrid[sl:el, sc:ec]
107
+ lats, lons = pnav.lc2ll(l=l, c=c, ssp=lon0, gt=geotr)
108
+ navigation = af.navigation # GVAR
109
+ area_l, area_c = navigation.toLinEle2(lats=lats, lons=lons) # toLineEle2 is fatser than toLineEle
110
+ # mask the invalid indices
111
+ lmask = (area_l >= 0) & (area_l < anl)
112
+ cmask = (area_c >= 0) & (area_c < anc)
113
+ m = lmask & cmask
114
+ # reproject
115
+ marea_l = np.floor(area_l[m]).astype(np.int32)
116
+ marea_c = np.floor(area_c[m]).astype(np.int32)
117
+ out_geos_data[sl:el, sc:ec][m] = data[marea_l, marea_c]
118
+
119
+ if return_gdalinfo:
120
+ proj4_str = '+proj=geos +a=6378169.0 +b=6356583.8 +h=35785831.0 +lon_0=%.2f +units=m' % lon0
121
+ gdal_info = geotr, proj4_str
122
+ return out_geos_data, gdal_info
123
+ return out_geos_data
124
+
125
+ else: # HRIT based reprojection
126
+ if not reproject_in_chunks:
127
+ lats, lons = hnav.lc2ll(c=np.arange(1, nl + 1), l=np.arange(1, nc + 1), lon0=lon0, cfac=scale_fact,
128
+ lfac=scale_fact, coff=offset, loff=offset)
129
+ else:
130
+ for i in range(nsegs):
131
+ sl = i * seg_len
132
+ el = sl + seg_len
133
+ for j in range(nsegs):
134
+ sc = j * seg_len
135
+ ec = sc + seg_len
136
+ corners = ((sl + 1, sc + 1), (sl + 1, ec + 1), (el + 1, sc + 1), (el + 1, ec + 1))
137
+
138
+ should_continue = test_chunk_intersection(af=af, points=corners, lon0=lon0, gt=geotr)
139
+ if should_continue:
140
+ l, c = np.ogrid[sl + 1:el + 1, sc + 1:ec + 1]
141
+ lats, lons = hnav.lc2ll(c=c.squeeze(), l=l.squeeze(), lon0=lon0, cfac=scale_fact,
142
+ lfac=scale_fact, coff=offset, loff=offset)
143
+ navigation = af.navigation # GVAR
144
+ area_l, area_c = navigation.toLinEle2(lats=lats, lons=lons)
145
+ # mask the invalid indices
146
+ lmask = (area_l >= 0) & (area_l < anl)
147
+ cmask = (area_c >= 0) & (area_c < anc)
148
+ m = lmask & cmask
149
+ # reproject
150
+ marea_l = np.floor(area_l[m]).astype(np.int32)
151
+ marea_c = np.floor(area_c[m]).astype(np.int32)
152
+ out_geos_data[sl:el, sc:ec][m] = data[marea_l, marea_c]
153
+
154
+ if return_gdalinfo:
155
+ proj4_str = '+proj=geos +a=6378169.0 +b=6356583.8 +h=35785831.0 +lon_0=%.2f +units=m' % lon0
156
+ gdal_info = geotr, proj4_str
157
+ return out_geos_data, gdal_info
158
+ return out_geos_data
159
+
160
+
161
+ # continue as now we have the lats and lons and the code is the same
162
+ area_l, area_c = navigation.toLinEle2(lats=lats, lons=lons)
163
+
164
+
165
+
166
+ # mask the invalid indices
167
+ lmask = (area_l >= 0) & (area_l < anl)
168
+ cmask = (area_c >= 0) & (area_c < anc)
169
+
170
+ m = lmask & cmask
171
+
172
+ # reproject
173
+ marea_l = np.floor(area_l[m]).astype(np.int32)
174
+ marea_c = np.floor(area_c[m]).astype(np.int32)
175
+
176
+ out_geos_data[m] = data[marea_l, marea_c]
177
+ if return_gdalinfo:
178
+ proj4_str = '+proj=geos +a=6378169.0 +b=6356583.8 +h=35785831.0 +lon_0=%.2f +units=m' % lon0
179
+ gdal_info = geotr, proj4_str
180
+ return out_geos_data, gdal_info
181
+ return out_geos_data
182
+ finally:
183
+ af.close() # the close functin does nothing in case the pyarea file is not opened form a file, perhaps it should clear the memory. However python does not guarantee that "del" operator does the job of dealocationg when invoked
@@ -0,0 +1,475 @@
1
+ __author__ = 'jano'
2
+
3
+
4
+
5
+ """
6
+ Generic HRIT based navigation of geostationary images.
7
+ This module performs navigation of images from geostatinary to LATLON anv viceversa
8
+ Four coordinate systems are used :
9
+
10
+ 1. l-c, index grid coordinates, 0-number of lines, 0, number of columns
11
+ 2. y-x, intermediary satellite coordinates, radians, the pixel size as viewed from the satellite
12
+ 3. lat-lon, degrees
13
+ 4. Y-X, meters
14
+
15
+ """
16
+
17
+ import numpy as np
18
+
19
+ DEG = np.pi / 180
20
+ RAD = 1.0 / DEG
21
+ satdist = 42164. #Distance from Earths center to virtual satellite (Rs)
22
+ req = 6378.1370 #Earths equatorial radius (req)
23
+ rpol = 6356.7523 #Earths polar radius (rpol)
24
+
25
+
26
+ #the column offset and line scaling factor for 1KM resolution
27
+
28
+ OFFSET_1000M = 5500
29
+ SCALE_FACTOR_1000M = 40932549
30
+
31
+
32
+ def compute_offset(resolution=None):
33
+ """
34
+ Computes the column/line offset of a given image
35
+ :param resolution:, number float, the image resolution
36
+ :return: the column/line offset navigation coefficient
37
+ """
38
+ scale_fact = 1000 / float(resolution)
39
+ return int(round(OFFSET_1000M * scale_fact))
40
+
41
+
42
+ def compute_scale_factor(resolution=None):
43
+ """
44
+ Computes the column/line scaling factor for a given image
45
+ :param resolution: number, float, the image resolution
46
+ :return: the column line navigation scaling factor
47
+ """
48
+ scale_fact = 1000/float(resolution)
49
+ return int(round(SCALE_FACTOR_1000M * scale_fact))
50
+
51
+
52
+ def get_navigation_dict(resolution=None, nl=None, nc=None):
53
+ """
54
+ COmputes a the navigation dictionary for a given image
55
+ :param resolution: number, float, the image resolution
56
+ :param nl: number, int, the number of lines in the image
57
+ :param nc: number, nc the number of columns in the image
58
+ :return: dict, the navigatio doictionary of image.
59
+ The navigation dictionary contains folowing parameters:
60
+ RESOLUTION, NL, NC, COFF, LOFF, CFAC, CLFAC
61
+ """
62
+ nav_dict = dict()
63
+ nav_dict['RESOLUTION'] = float(resolution)
64
+ nav_dict['NL'] = int(nl)
65
+ nav_dict['NC'] = int(nc)
66
+
67
+ scaling_factor = compute_scale_factor(resolution=resolution)
68
+ offset = compute_offset(resolution=resolution)
69
+
70
+ nav_dict['COFF'] = offset
71
+ nav_dict['LOFF'] = offset
72
+ nav_dict['CFAC'] = scaling_factor
73
+ nav_dict['LFAC'] = scaling_factor
74
+ return nav_dict
75
+
76
+
77
+
78
+
79
+
80
+
81
+ def ll2yx(lat=None, lon=None, lon0=None ):
82
+ """
83
+ Transform lat/lon coordinates to intermediary or satellite(x,y) coordinates expressed in degrees
84
+ These step difference between these coordinates is supposed to be the native resolution of the satellite
85
+ (This is how satellite looks at the earth)
86
+ For details consult http://www.cgms-info.org/documents/cgms-lrit-hrit-global-specification-%28v2-8-of-30-oct-2013%29.pdf
87
+ section 4.4.3.1
88
+
89
+ constants used here (http://www.data.jma.go.jp/mscweb/en/himawari89/space_segment/hsd_sample/HS_D_users_guide_en_v11.pdf)
90
+ 0.993243 - rpol2 / req2
91
+ 0.00675701 - (req2 - rpol2) / req2
92
+ 6356.5838 - Earths polar radius (rpol) [km]
93
+
94
+ :param lat: latitude, float/int or 1D numpy array of dtype float, int,
95
+ :param lon: longitude, float/int or 1D numpy array of dtype float, int
96
+ :param lon_0:, subsatellite longitude, float, int
97
+ :return: a tuple representing (intermediary) satellite coordinates(degrees) corresponding to the lat/lon. It the arguments are numpy arrays
98
+ then the tuple consists of 2 2D arrays, else 2 scalars
99
+ """
100
+ if lat is None or lon is None:
101
+ return None, None
102
+
103
+ try:
104
+ #broadcasting is faster here
105
+ lat = lat[:,np.newaxis]
106
+ lon = lon[np.newaxis,:]
107
+ except Exception: # scalar version, r
108
+ pass
109
+
110
+
111
+ c_lat = np.arctan(((rpol**2)/(req**2)) * np.tan(lat * DEG))
112
+ rl = rpol / np.sqrt(1. - ((((req**2)-(rpol**2))/(req**2)) * np.cos(c_lat) * np.cos(c_lat)))
113
+
114
+ r1 = satdist - (rl * np.cos(c_lat) * np.cos((lon - lon0) * DEG))
115
+ r2 = -rl * np.cos(c_lat) * np.sin((lon - lon0) * DEG)
116
+ r3 = rl * np.sin(c_lat)
117
+ rn = np.sqrt((r1 * r1) + (r2 * r2) + (r3 * r3))
118
+
119
+ y = None
120
+ x = None
121
+ #isvisible = rn*rn + np.square(rl*c_lat)
122
+ #if isvisible> np.square(satdist):
123
+ # return y,x
124
+
125
+ x = np.arctan(-r2 / r1) * RAD
126
+ y = np.arcsin(-r3 / rn) * RAD
127
+ return y, x
128
+
129
+ def yx2ll(y=None, x=None, lon0=None ):
130
+ """
131
+ Transform intermediary or satellite(x,y) coordinates expressed in degrees to lat/lon coordinates.
132
+ http://2014.cgms-info.SatErthCenterDistanceorg/documents/cgms-lrit-hrit-global-specification-%28v2-8-of-30-oct-2013%29.pdf
133
+
134
+ constants used here (http://www.data.jma.go.jp/mscweb/en/himawari89/space_segment/hsd_sample/HS_D_users_guide_en_v11.pdf)
135
+ 42164. - Distance from satellite to Earth center in kilometers
136
+ 1.006739501 - req2 / rpol2
137
+ 1737122264.0- Coefficient for Sd (Rs2 - req2)
138
+
139
+ :param y: satellite coordinates, float
140
+ :param x: satellite coordinates, float
141
+ :param lon_0:, subsatellite longitude, float, int
142
+ :return: longitude, latitude
143
+ Note Jano. if the input is 1D thne broadcasting is used and, i have found out that LAT/LON indices were flipped so
144
+ I transposed thme back to tor correct position.
145
+ This behaviour might not be present in case 2D input is used
146
+ TODO: verify this 1D/2D behaviour
147
+ """
148
+ if y is None or x is None:
149
+ return None, None
150
+ try:
151
+ # broadcasting is faster here
152
+ x = x[:, np.newaxis]
153
+ y = y[np.newaxis, :]
154
+ except Exception: # scalar version, r
155
+ pass
156
+
157
+
158
+ # converts to radians
159
+ x = x*DEG
160
+ y = y*DEG
161
+
162
+ lon0Rad = lon0*DEG
163
+
164
+ #### PARTIAL CALCULATIONS for better overview ####
165
+ sdp1 = satdist * np.cos(x) * np.cos(y)
166
+ sdp1sq = (sdp1**2)
167
+ sdp2 = (np.cos(y)**2) + (((req**2)/(rpol**2)) * (np.sin(y)**2))
168
+
169
+ sdp3 = sdp1sq - sdp2 * ((satdist**2)-(req**2))
170
+ vis_mask = sdp3 < 0
171
+ # if sdp3 < 0:
172
+ # return None, None
173
+ ####
174
+ sdp3[vis_mask] = np.nan
175
+ sd = np.sqrt(sdp3)
176
+
177
+ snp1 = (satdist * np.cos(x) * np.cos(y)) - sd
178
+ snp2 = (np.cos(y) * np.cos(y)) + (((req**2)/(rpol**2)) * np.sin(y) * np.sin(y))
179
+
180
+ sn = snp1 / snp2
181
+ s1 = satdist - sn * np.cos(x) * np.cos(y)
182
+ s2 = sn * np.sin(x) * np.cos(y)
183
+ s3 = -sn * np.sin(y)
184
+ #s3 = sn * np.sin(y)
185
+ sxy = ((s1 * s1) + (s2 * s2))**0.5
186
+ lon = np.arctan(s2 / s1) + lon0Rad
187
+ lat = np.arctan(((req**2)/(rpol**2)) * (s3 / sxy))
188
+
189
+ # converts to degrees
190
+ lonDeg = lon * RAD
191
+ latDeg = lat * RAD
192
+
193
+ # Solution of 180deg meridian
194
+ lonDeg = ((lonDeg + 180.0) % 360.0) - 180.0
195
+ # rlatDeg = np.where(vis_mask, latDeg, np.nan)
196
+ # rlonDeg = np.where(vis_mask, lonDeg, np.nan)
197
+ return latDeg.T, lonDeg.T #this is a bug??? I had to do this because when using broadcasting the resulting index matrices were rotated
198
+
199
+ def yx2lc(y=None, x=None, lfac=None, cfac=None, coff=None, loff=None):
200
+ """
201
+ Scaling function that transforms intermediary satellite coordinates expressed in degrees into satellite line column coordinates
202
+ or pixel indices of the original satellite image.
203
+ The definition is as follows:
204
+ c = COFF + nint(x * 2**-16 * CFAC)
205
+ l = LOFF + nint(y * 2 **-16 * LFAC)
206
+
207
+ For details consult http://2014.cgms-info.org/documents/cgms-lrit-hrit-global-specification-%28v2-8-of-30-oct-2013%29.pdf
208
+ section 4.4.4
209
+ TODO: I really need to do some experimentation to understand precisely how are the args derived
210
+
211
+
212
+ :param y: satellite coordinates for Y axis corresponding to a specific LATLON
213
+ :param x: satellite coordinates for X axis corresponding to a specific LATLON
214
+ :param lfac: line scaling factor,
215
+ :param cfac: column scaling factor
216
+ :param coff: column offset
217
+ :param loff: line offset offset
218
+ :return a tuple representing line coordinates (indices) and column coordinates (indices)
219
+ These coordinates can be used to extract counts form the original hrit data
220
+
221
+
222
+ """
223
+ if y is None or x is None:
224
+ return None, None
225
+
226
+ return np.floor(0.5 + loff+ y*lfac*2**-16).astype(np.uint16), np.floor(0.5 + coff+ x*cfac*2**-16).astype(np.uint16)
227
+
228
+ def lc2yx(c=None,l=None,loff=None,coff=None,cfac=None,lfac=None):
229
+ """
230
+ Scaling function that transforms satellite line column coordinates or pixel indices of the
231
+ original satellite image into intermediary satellite coordinates expressed in degrees.
232
+ Derived from:
233
+ c = COFF + nint(x * 2**-16 * CFAC)
234
+ l = LOFF + nint(y * 2 **-16 * LFAC)
235
+ to:
236
+ x = c - COFF / 2**-16 * CFAC
237
+ :param c: column coordinates, int
238
+ :param l: line coordinates, int
239
+ :param lfac: line scaling factor
240
+ :param cfac: column scaling factor
241
+ :param coff: column offset
242
+ :param loff: line offset offset
243
+ :return satellite coordinates x,y
244
+
245
+ """
246
+ if c is None or l is None:
247
+ return None, None
248
+
249
+ x = (c - coff) / ((2**-16) * cfac)
250
+ y = (l - loff) / ((2**-16) * lfac)
251
+ return y,x
252
+
253
+ def ll2lc(lat=None, lon=None, lon0=None, cfac=None, lfac=None, coff=None, loff=None, nl=None, nc=None):
254
+ """
255
+ Converts lat/lon to raw line/col. Basically a container forlatlon2yx and yx2lc
256
+
257
+ Many JMA HRIT images have geometry registration issues. These issues can be corrected by using information from Header 130 located in channel corresponding segments
258
+
259
+
260
+ :param lat: latitude, float/int or 1D numpy array of dtype float, int,
261
+ :param lon: longitude, float/int or 1D numpy array of dtype float, int
262
+ :param lfac: line scaling factor
263
+ :param cfac: column scaling factor
264
+ :param coff: column offset
265
+ :param loff: line offset offset
266
+ :param nl: int, number of lines in the image
267
+ :param nc: int, number of columns in the image
268
+ :return a tuple representing line coordinates (indices) and column coordinates (indices) or a typke of None if the coordinates are outside the nl and nc .
269
+ LC space is bigger than LATLON therefore return coords are checked to be in 0-NL|NC range.
270
+ """
271
+
272
+ y, x = ll2yx(lat=lat, lon=lon, lon0=lon0 )
273
+ l, c = yx2lc(y=y, x=x, lfac=lfac, cfac=cfac, coff=coff, loff=loff)
274
+
275
+ if np.all(np.logical_and(l>=0, l<nl)) and np.all(np.logical_and(c>=0, c<nc)):
276
+ return l, c
277
+ else:
278
+ return None, None
279
+
280
+ def lc2ll(c=None, l=None, lon0=None, cfac=None, lfac=None,coff=None, loff=None):
281
+ """
282
+ Converts raw line/col to lat/lon. A container for lc2yx and yx2ll
283
+
284
+ :param c: column coordinates, int or numpy array of ints
285
+ :param l: line coordinates, int or numpy array of ints
286
+ :param lon0: subsatelitte point
287
+ :param lfac: line scaling factor
288
+ :param cfac: column scaling factor
289
+ :param coff: column offset
290
+ :param loff: line offset offset
291
+ :return
292
+ """
293
+ if c is None or l is None:
294
+ return None, None
295
+
296
+ y,x = lc2yx(c=c, l=l, loff=loff, coff=coff, cfac=cfac, lfac=lfac)
297
+ return yx2ll(y=y, x=x, lon0=lon0)
298
+
299
+
300
+ def offset_lc(l=None, c=None, loff=None, coff=None, orig_loff=None, orig_coff=None):
301
+ """
302
+ Offsets original line/col coordinates with offset values from the header 130.
303
+
304
+ :param l: line coordinates, int or numpy array of ints,
305
+ :param c: column coordinates, int or numpy array of ints
306
+ :param loff: line offets, numy array of floats, having same size as l
307
+ :param coff: column offets, numpy array of floats having same size as c
308
+ :param orig_loff:, int, float, the default line offset form header 3
309
+ :param orig_coff:, int, float,, the defauylt column offset
310
+ :return:
311
+ """
312
+
313
+ return np.floor(l-orig_loff + loff).astype(np.uint16), np.floor(c-orig_coff + coff).astype(np.uint16)
314
+
315
+ def YX2lc(X=None,Y=None, coff=None, loff=None, resolution=None):
316
+ """
317
+ Transforms Geostationary coordinates X/Y to raw line/col
318
+ http://lists.osgeo.org/pipermail/gdal-dev/2007-November/014954.html
319
+ c = COFF + X / ColumnDirGridStep
320
+ :param X: geostationary MTSAT x axis coordinate
321
+ :param Y: geostationary MTSAT y axis coordinate
322
+ :param loff: line offset
323
+ :param coff: column offset
324
+ :param resolution:
325
+ :return:
326
+ """
327
+
328
+ if Y is None or X is None:
329
+ return None, None
330
+
331
+ c = np.floor(0.5 + coff + X / resolution).astype(np.uint16)
332
+ l = np.floor(0.5 + abs(loff - Y / resolution)).astype(np.uint16)
333
+
334
+ return l, c
335
+
336
+ def lc2YX(c=None,l=None, coff=None, loff=None, resolution=None):
337
+ """
338
+ Derived DIRECTLY from the linear relationship between the lc coordinates and geostationary coordinates
339
+ Transforms raw LC into geostationary coordinates XY
340
+ derived from http://lists.osgeo.org/pipermail/gdal-dev/2007-November/014954.html
341
+ c = COFF + X / resolution
342
+
343
+
344
+ :param l: line coordinates, int or numpy array of ints,
345
+ :param c: column coordinates, int or numpy array of ints
346
+ :param loff: line offset
347
+ :param coff: column offset
348
+ :param resolution:
349
+ :return: geostationary X,Y coordinates in meters
350
+ Note by Jano
351
+ -loff -l is necessary here not l-loff because in geostationary projection Y and X have both negative values
352
+ depending on which quadrant they do fall
353
+ """
354
+ if c is None or l is None:
355
+ return None, None
356
+ try:
357
+ c = np.asarray(c)
358
+ l = np.asarray(l)
359
+ except TypeError:
360
+ pass
361
+ X = (c-coff)*float(resolution) + resolution/2.
362
+ Y = (loff-l)*float(resolution) - resolution/2.
363
+ return Y, X
364
+
365
+ def yx2YX(y=None, x=None, cfac=None, lfac=None, resolution=None):
366
+ """
367
+ Transforms intermediary satellite coordinates expressed in degrees into geostationary coordinates XY
368
+ http://lists.osgeo.org/pipermail/gdal-dev/2007-November/014954.html
369
+ X = x * CFAC * resolution / (2**16)
370
+
371
+ :param y: satellite coordinates for Y axis
372
+ :param x: satellite coordinates for X axis
373
+ :param lfac: line scaling factor
374
+ :param cfac: column scaling factor
375
+ :param resolution:
376
+ :return: geostationary MTSAT YX
377
+ Note by Jano
378
+ -lfac is necessary here because the in geostationary projection Y and X have both negative values
379
+ depending on which quadrant they do fall
380
+ this ahould be actually handled by 2 resoilutions, one for each axis and the Y resolution is NEGATIVE
381
+
382
+ """
383
+ if y is None or x is None:
384
+ return None, None
385
+
386
+ X = (x * cfac * resolution) / (2**16)
387
+ Y = (y * -lfac * resolution) / (2**16)
388
+
389
+ return Y,X
390
+
391
+ def YX2yx(Y=None, X=None, cfac=None, lfac=None, resolution=None):
392
+ """
393
+ Geostationary YX to intermediary satellite coordinates expressed in degrees
394
+ http://lists.osgeo.org/pipermail/gdal-dev/2007-November/014954.html
395
+ x = X * (2**16) / (CFAC * resolution)
396
+
397
+ :param l: line coordinates, int or numpy array of ints,
398
+ :param c: column coordinates, int or numpy array of ints
399
+ :param lfac: line scaling factor
400
+ :param cfac: column scaling factor
401
+ :param resolution
402
+ :return intermediary satellite coordinates expressed in degrees
403
+ #note by jano
404
+ -lfac is necessary here to account for quadrants as the LC space does not change sign and the geostationary space does
405
+
406
+ """
407
+ if Y is None or X is None:
408
+ return None, None
409
+
410
+ x = X*(2**16) / (cfac * resolution)
411
+ y = Y*(2**16) / (-lfac * resolution)
412
+
413
+ return y, x
414
+
415
+ def YX2ll(Y=None, X=None, cfac=None, lfac=None, resolution=None, lon0=None):
416
+ """
417
+ Geostationary YX to latitude longitude, container for two functions
418
+ :param X: geostationary x axis coordinate
419
+ :param Y: geostationary y axis coordinate
420
+ :param loff: line offset
421
+ :param coff: column offset
422
+ :param resolution:
423
+ :return: latitude, longitude
424
+ """
425
+
426
+ if Y is None or X is None:
427
+ return None, None
428
+
429
+ y,x = YX2yx(Y=Y, X=X, cfac=cfac, lfac=lfac, resolution=resolution)
430
+ return yx2ll(y=y, x=x,lon0=lon0)
431
+
432
+
433
+ def ll2YX(lat=None, lon=None, lon0=None, cfac=None, lfac=None, resolution=None):
434
+ """
435
+ Latitude/Longitude to Geostationary YX
436
+ :param lat: latitude, int,
437
+ :param lon: longitude, int
438
+ :param loff: line offset
439
+ :param coff: column offset
440
+ :param resolution:
441
+ :return: geostationary MTSAT X,Y coordinates in meters
442
+ """
443
+
444
+ if lat is None or lon is None:
445
+ return None, None
446
+
447
+ y,x = ll2yx(lat=lat, lon=lon, lon0=lon0)
448
+ Y,X = yx2YX(y=y, x=x, cfac=cfac, lfac=lfac, resolution=resolution)
449
+
450
+ return Y,X
451
+
452
+
453
+ def reproject_geos_2_latlon(array_in=None, bbox=None, ssp=None, resolution=None):
454
+ """
455
+ Reprojects a geostatioanry image (2D array) in a spatial context defined by input image
456
+ a sub-satellite point and resolution and output geographic bounding box.
457
+ :param array_in: 2D numpy array, input image
458
+ :param bbox: instance of bounding_box object, the pyarea in geographic coordinates that will be reprojected from the input image
459
+ :param ssp: number, float, input image sub-satellite point in degrees
460
+ :param resolution: number, float, input image resolution in meters
461
+ :return: 2D numpy array representing the reprojected input image
462
+ """
463
+ nl, nc = array_in.shape
464
+ nav_dict = get_navigation_dict(resolution=resolution, nl=nl, nc=nc)
465
+ cfac = nav_dict['CFAC']
466
+ lfac = nav_dict['LFAC']
467
+ coff = nav_dict['COFF']
468
+ loff = nav_dict['LOFF']
469
+
470
+ # get 1D lats and lons
471
+ lats = bbox.latitudes()
472
+
473
+ lons = bbox.longitudes()
474
+ valid_l, valid_c = ll2lc(lat=lats, lon=lons, lon0=ssp, cfac=cfac, lfac=lfac, coff=coff, loff=loff, nl=nl, nc=nc)
475
+ return array_in[valid_l, valid_c]