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.
pyarea/nav.py ADDED
@@ -0,0 +1,2837 @@
1
+ __author__ = 'jano'
2
+ import collections
3
+ import datetime
4
+ import logging
5
+ import math
6
+ import struct
7
+
8
+ import numba
9
+ import numpy as np
10
+ from numpy import nan
11
+
12
+ from pyarea import utils
13
+
14
+ _njit = numba.njit
15
+
16
+ logger = logging.getLogger('nav')
17
+
18
+ class AreaNav():
19
+
20
+
21
+ # The codes below are the four characters of the first nav word, as in VisAD's AREAnav (the short ones are padded)
22
+
23
+ # Code value in AREA files used to designate DMSP navigation
24
+ DMSP = 'DMRP'
25
+
26
+ # Code value in AREA files used to designate GMSX (GMS) navigation
27
+ GMSX = 'GMSX'
28
+
29
+ # Code value in AREA files used to designate GOES (GOES D-H) navigation
30
+ GOES = 'GOES'
31
+
32
+ # Code value in AREA files used to designate GEOS navigation
33
+ GEOS = 'GEOS'
34
+
35
+ # Code value in AREA files used to designate GVAR (GOES I-M) navigation
36
+ GVAR = 'GVAR'
37
+
38
+ # Code value in AREA files used to designate MOLL (Mollweide) navigation
39
+ MOLL = 'MOLL'
40
+
41
+ # Code value in AREA files used to designate MSAT (Meteosat) navigation
42
+ MSAT = 'MSAT'
43
+
44
+ # Code value in AREA files used to designate MSGT navigation
45
+ MSGT = 'MSGT'
46
+
47
+ # Code value in AREA files used to designate MSG navigation
48
+ MSG = 'MSG '
49
+
50
+ # Code value in AREA files used to designate POES (TIROS) navigation
51
+ POES = 'TIRO'
52
+
53
+ # Code value in AREA files used to designate RADR (radar) navigation
54
+ RADR = 'RADR'
55
+
56
+ # Code value in AREA files used to designate RECT (rectilinear) navigation
57
+ RECT = 'RECT'
58
+
59
+ # Code value in AREA files used to designate PS (polar stereographic) navigation
60
+ PS = 'PS '
61
+
62
+ # Code value in AREA files used to designate MERC (mercator) navigation
63
+ MERC = 'MERC'
64
+
65
+ # Code value in AREA files used to designate TANC (tangent cone) navigation
66
+ TANC = 'TANC'
67
+
68
+ # Code value in AREA files used to designate SIN (sinusoidal cone) navigation
69
+ SIN = 'SIN '
70
+
71
+ # Code value in AREA files used to designate LAMB (lambert conformal)navigation
72
+ LAMB = 'LAMB'
73
+
74
+ # Code value in AREA files used to designate Lat/Lon
75
+ LALO = 'LALO'
76
+
77
+ # Code value in AREA files used to designate KALP
78
+ KALP = 'KALP'
79
+
80
+ # Code value in AREA files used to designate ABIS
81
+ ABIS = 'ABIS'
82
+
83
+ #ABI GOES R
84
+ ABIN = 'ABIN'
85
+
86
+ # Code value for specifying Latitude/Longitude transformations
87
+ LL = 123
88
+
89
+ # Code value for specifying Cartesian (X/Y) transformations
90
+ XY = 234
91
+
92
+ # "Line" index in line/element array
93
+ indexLine=1
94
+ # "Element" index in line/element array
95
+ indexEle=0
96
+ # "Latitude" index in latitude/longitude array
97
+ indexLat=0
98
+ # "Longitude" index in latitude/longitude array
99
+ indexLon=1
100
+
101
+ isLineFlipped = False
102
+ lineOffset = 0.0
103
+
104
+ # the following are ancillary info set by the set/get
105
+ # public methods Res, Mag, and Start
106
+ resLine = 1.
107
+ resElement = 1
108
+ magLine = 1.
109
+ magElement = 1.
110
+ startLine = 0
111
+ startElement = 0.
112
+ startImageLine = 0.
113
+ startImageElement = 0.
114
+ ##COMMON attrs added by jano purposefully
115
+ PI = math.pi
116
+ DEG = 180. / PI
117
+ RAD = PI / 180. # degrees to radians conversion pi/180
118
+ STTYPE = 0 # word position of satellite type
119
+
120
+ # VisAD builds these with the static AREAnav.makeAreaNav, which switches on the first nav word.
121
+ # Here AreaNav(navblock=..., byte_order=..., int_format=...) picks the subclass named <nav type>Nav in the same way.
122
+ def __new__(cls, *args, **kwargs):
123
+ if 'navblock' not in kwargs:
124
+ raise RuntimeError('Can not create {} instance without a navigation block'.format( cls.__name__))
125
+ if 'byte_order' not in kwargs:
126
+ raise RuntimeError(f'Can not create {cls.__name__} instance without knowing byte_order. '
127
+ 'Please supply "byte_order" argument.')
128
+ if 'int_format' not in kwargs:
129
+ raise RuntimeError(f'Can not create {cls.__name__} instance without knowing format. '
130
+ 'Please supply "int_format" argument.')
131
+
132
+ navblock= kwargs.get('navblock')
133
+
134
+
135
+ byte_order= kwargs.get('byte_order')
136
+ int_format= kwargs.get('int_format')
137
+ navtype = struct.unpack(f'{byte_order}4s', struct.pack(f'{byte_order}{int_format}', navblock[0]))[0]
138
+ navtype = navtype.decode(errors='replace')
139
+
140
+ #evaluate dynamically, does have the advantage of being self updateable
141
+ # a concrete subclass is built directly (its __init__ validates the block);
142
+ # only AreaNav itself has to find the right subclass from the nav type
143
+ nav_classes = cls.get_subclasses() if cls is AreaNav else [cls]
144
+
145
+
146
+
147
+ # dynamically create the new class
148
+ for klass in nav_classes:
149
+ if cls is not AreaNav or klass.__name__ == navtype.strip() + 'Nav':
150
+ inst = object.__new__(klass)
151
+ inst.navtype = navtype
152
+ inst.byte_order = byte_order
153
+ inst.int_format = int_format
154
+ return inst
155
+
156
+ # VisAD's makeAreaNav throws a McIDASException here
157
+ supported = sorted(klass.__name__[:-len('Nav')] for klass in nav_classes)
158
+ raise NotImplementedError(f'Navigation for {navtype!r} data is not implemented. '
159
+ f'Supported: {", ".join(supported)}')
160
+
161
+ def toLatLon(self, linele=None):
162
+ raise RuntimeError('Abstract method. Should be implemented by subclasses')
163
+
164
+ def toLinEle(self, latlon=None):
165
+ raise RuntimeError('Abstract method. Should be implemented by subclasses')
166
+
167
+ def areaCoordtoImageCoord(self, linele=None, newvals=None):
168
+ """AREAnav.areaCoordToImageCoord: ``[[elements], [lines]]`` of the AREA (file) to the image, NaN stays NaN."""
169
+ n = len(linele[0])
170
+ if newvals is None:
171
+ newvals = [[nan] * n, [nan] * n]
172
+
173
+ for i in range(n):
174
+ line, elem = linele[self.indexLine][i], linele[self.indexEle][i]
175
+ if line == line:
176
+ if self.isLineFlipped: # account for flipped coordinates
177
+ line = self.lineOffset - line
178
+ newvals[self.indexLine][i] = (self.startImageLine
179
+ + (self.resLine * (line - self.startLine)) / self.magLine)
180
+ if elem == elem:
181
+ newvals[self.indexEle][i] = (self.startImageElement
182
+ + (self.resElement * (elem - self.startElement)) / self.magElement)
183
+ return newvals
184
+
185
+ def imageCoordToAreaCoord(self, linele=None, newvals=None):
186
+ """AREAnav.imageCoordToAreaCoord: the inverse of :meth:`areaCoordtoImageCoord`."""
187
+ n = len(linele[0])
188
+ if newvals is None:
189
+ newvals = [[nan] * n, [nan] * n]
190
+
191
+ for i in range(n):
192
+ line, elem = linele[self.indexLine][i], linele[self.indexEle][i]
193
+ if line == line:
194
+ area_line = self.startLine + (self.magLine * (line - self.startImageLine)) / self.resLine
195
+ if self.isLineFlipped: # account for flipped coordinates
196
+ area_line = self.lineOffset - area_line
197
+ newvals[self.indexLine][i] = area_line
198
+ if elem == elem:
199
+ newvals[self.indexEle][i] = (self.startElement
200
+ + (self.magElement * (elem - self.startImageElement)) / self.resElement)
201
+ return newvals
202
+
203
+ def canApproximateWithSpline(self):
204
+ return True
205
+
206
+ def setFlipLineCoordinates(self, line):
207
+ """Treat the lines as counted from the bottom: ``line`` is the offset, as AREAnav.setFlipLineCoordinates."""
208
+ self.isLineFlipped = True
209
+ self.lineOffset = float(line)
210
+
211
+ def isFlippedLineCoordinates(self):
212
+ return self.isLineFlipped
213
+
214
+ def getLineOffset(self):
215
+ return float(self.lineOffset)
216
+
217
+ def getSubpoint(self):
218
+ """``(lat, lon)`` of the subpoint, NaN for navigations that have none, as AREAnav.getSubpoint."""
219
+ return nan, nan
220
+
221
+ def __str__(self):
222
+ return self.navtype
223
+
224
+ def setImageStart(self, start_line, start_elem):
225
+ self.startImageLine = float(start_line)
226
+ self.startImageElement = float(start_elem)
227
+
228
+ def setStart(self, start_line, start_elem):
229
+ self.startLine = start_line
230
+ self.startElement = start_elem
231
+ def setRes(self, resLine, resElement):
232
+ self.resLine = resLine
233
+ self.resElement = resElement
234
+ def setMag(self, magLine, magElement):
235
+ self.magLine = magLine
236
+ self.magElement = magElement
237
+
238
+ def _area_to_image(self, line, elem):
239
+ """AREA (file) coordinates to GVAR image coordinates."""
240
+ if self.isLineFlipped:
241
+ line = self.lineOffset - line
242
+ return (self.startImageLine + self.resLine * (line - self.startLine) / self.magLine,
243
+ self.startImageElement + self.resElement * (elem - self.startElement) / self.magElement)
244
+
245
+ def _image_to_area(self, line, elem):
246
+ """GVAR image coordinates to AREA (file) coordinates."""
247
+ line = self.startLine + self.magLine * (line - self.startImageLine) / self.resLine
248
+ if self.isLineFlipped:
249
+ line = self.lineOffset - line
250
+ return line, self.startElement + self.magElement * (elem - self.startImageElement) / self.resElement
251
+
252
+ @classmethod
253
+ def get_subclasses(cls):
254
+
255
+ subs = set(cls.__subclasses__())
256
+ return subs.union(*(i.get_subclasses() for i in subs))
257
+
258
+
259
+
260
+ _GvarParams = collections.namedtuple(
261
+ "_GvarParams",
262
+ "instr ff doff elvmax elvln scnpx scnmax pma rma "
263
+ "b00 b01 b02 b10 b11 b12 b20 b21 b22 xs0 xs1 xs2 aebe2c aebe3c aebe4c q3 east",
264
+ )
265
+
266
+
267
+ @_njit
268
+ def _gvar_to_latlon(rl, rp, p):
269
+ """Image line/pixel (flat float arrays, GVAR image coordinates) to geodetic lat/lon in degrees.
270
+
271
+ This is the GVAR "lpoint" computation of the Operations Ground Equipment interface document, ported from the
272
+ McIDAS ``nvxgvar`` code. NaN in, or a line of sight that misses the Earth, gives NaN.
273
+ """
274
+ n = rl.size
275
+ lat = np.full(n, np.nan)
276
+ lon = np.full(n, np.nan)
277
+ for i in range(n):
278
+ line = rl[i]
279
+ pixel = rp[i]
280
+ if not (np.isfinite(line) and np.isfinite(pixel)):
281
+ continue
282
+ # the sounder routines take the sounder resolution into account, so pretend the image is at resolution 1
283
+ if p.instr == 2:
284
+ line = (line + 9.0) / 10.0
285
+ pixel = (pixel + 9.0) / 10.0
286
+ # elevation and scan angles of the line and pixel
287
+ if p.instr == 1:
288
+ alpha0 = p.elvmax - (line - 4.5) * p.elvln
289
+ else:
290
+ alpha0 = p.elvmax - (line - 2.5) * p.elvln
291
+ zeta0 = (pixel - 1.0) * p.scnpx - p.scnmax
292
+ # second order origin offset correction
293
+ alpha = alpha0 - alpha0 * zeta0 * p.doff
294
+ zeta = zeta0 + 0.5 * alpha0 * alpha0 * p.doff
295
+ # trigonometric functions of the angles, corrected for the roll and pitch misalignments
296
+ ca = math.cos(alpha)
297
+ sa = math.sin(alpha)
298
+ cz = math.cos(zeta)
299
+ da = alpha - p.pma * sa * (p.ff / cz + math.tan(zeta)) - p.rma * (1.0 - ca / cz)
300
+ dz = zeta + p.ff * p.rma * sa
301
+ cz = math.cos(dz)
302
+ # pointing vector in instrument coordinates, then in earth fixed coordinates
303
+ g0 = math.sin(dz)
304
+ g1 = -cz * math.sin(da)
305
+ g2 = cz * math.cos(da)
306
+ e0 = p.b00 * g0 + p.b01 * g1 + p.b02 * g2
307
+ e1 = p.b10 * g0 + p.b11 * g1 + p.b12 * g2
308
+ e2 = p.b20 * g0 + p.b21 * g1 + p.b22 * g2
309
+ # intersect the pointing vector with the earth surface (a quadratic equation)
310
+ q1 = e0 * e0 + e1 * e1 + p.aebe2c * e2 * e2
311
+ q2 = p.xs0 * e0 + p.xs1 * e1 + p.aebe2c * p.xs2 * e2
312
+ d = q2 * q2 - q1 * p.q3
313
+ if abs(d) < 1e-9:
314
+ d = 0.0
315
+ if d < 0.0: # points off the earth
316
+ continue
317
+ d = math.sqrt(d)
318
+ h = -(q2 + d) / q1
319
+ u0 = p.xs0 + h * e0
320
+ u1 = p.xs1 + h * e1
321
+ u2 = p.xs2 + h * e2
322
+ # sine of the geocentric latitude, then the geodetic latitude and the longitude
323
+ d1 = u2 / math.sqrt(u0 * u0 + u1 * u1 + u2 * u2)
324
+ lat[i] = math.atan(p.aebe2c * d1 / math.sqrt(1.0 - d1 * d1)) * 57.29577951308232
325
+ lon[i] = math.atan2(u1, u0) * 57.29577951308232 * p.east
326
+ return lat, lon
327
+
328
+
329
+ @_njit
330
+ def _gvar_to_image(lat, lon, p):
331
+ """Geodetic lat/lon in degrees (flat float arrays) to image line/pixel (GVAR image coordinates).
332
+
333
+ The inverse of :func:`_gvar_to_latlon` (the "gpoint" routine). NaN where the point is not visible from the
334
+ satellite, or where lat or lon is NaN.
335
+ """
336
+ n = lat.size
337
+ line = np.full(n, np.nan)
338
+ pixel = np.full(n, np.nan)
339
+ for i in range(n):
340
+ if not (abs(lat[i]) <= 90.0 and np.isfinite(lon[i])):
341
+ continue
342
+ rlat = lat[i] * 0.017453292519943295
343
+ rlon = lon[i] * 0.017453292519943295 * p.east
344
+ # sine of the geodetic latitude and of the geocentric latitude
345
+ sing = math.sin(rlat)
346
+ w1 = p.aebe4c * sing * sing
347
+ slat = ((0.375 * w1 - 0.5) * w1 + 1.0) * sing / p.aebe2c
348
+ # local earth radius at the point, and its cartesian coordinates
349
+ w2 = slat * slat
350
+ w1 = p.aebe3c * w2
351
+ w1 = (0.375 * w1 - 0.5) * w1 + 1.0
352
+ u2 = slat * w1
353
+ w2 = w1 * math.sqrt(1.0 - w2)
354
+ u0 = w2 * math.cos(rlon)
355
+ u1 = w2 * math.sin(rlon)
356
+ # pointing vector from the instrument to the point
357
+ f0 = u0 - p.xs0
358
+ f1 = u1 - p.xs1
359
+ f2 = u2 - p.xs2
360
+ w2 = u0 * f0 + u1 * f1 + u2 * f2 * p.aebe2c
361
+ if not w2 <= 0.0: # not visible
362
+ continue
363
+ # the pointing vector in instrument coordinates
364
+ t0 = p.b00 * f0 + p.b10 * f1 + p.b20 * f2
365
+ t1 = p.b01 * f0 + p.b11 * f1 + p.b21 * f2
366
+ t2 = p.b02 * f0 + p.b12 * f1 + p.b22 * f2
367
+ # scan and elevation angles, corrected for the roll and pitch misalignments
368
+ gam = math.atan(t0 / math.sqrt(t1 * t1 + t2 * t2))
369
+ alf = -math.atan(t1 / t2)
370
+ w1 = math.sin(alf)
371
+ w2 = math.cos(gam)
372
+ alpha1 = alf + p.rma * (1.0 - math.cos(alf) / w2) + p.pma * w1 * (p.doff / w2 + math.tan(gam))
373
+ gam = gam - p.ff * p.rma * w1
374
+ alf = alpha1 + alpha1 * gam * p.doff
375
+ gam = gam - 0.5 * alpha1 * alpha1 * p.doff
376
+ # fractional line and pixel numbers
377
+ tmplin = (p.elvmax - alf) / p.elvln
378
+ tmplin = tmplin + 4.5 if p.instr == 1 else tmplin + 2.5
379
+ tmpele = (p.scnmax + gam) / p.scnpx + 1.0
380
+ # sounder navigation returns resolution 10 values
381
+ if p.instr == 2:
382
+ tmplin = tmplin * 10.0 - 9.0
383
+ tmpele = tmpele * 10.0 - 9.0
384
+ line[i] = tmplin
385
+ pixel[i] = tmpele
386
+ return line, pixel
387
+
388
+
389
+ class GVARNav(AreaNav):
390
+
391
+ isEastPositive = True
392
+
393
+
394
+ NOMORB=42164.365 # nominal radial distance of instrument (km)
395
+ AE=6378.137 # earth equatorial radius (km)
396
+ FER=1.-(6356.7533/AE) # earth flattening coeff = 1-(be/ae)
397
+ AEBE2= 1./(1-FER)**2
398
+ AEBE3= AEBE2-1.
399
+ AEBE4=((1.-FER)**4.)-1.
400
+
401
+ xs = [nan] * 3 # normalized s/c position in ecef coordinates
402
+ #bt= [[nan for i in range(3)], [nan for i in range(3)], [nan for i in range(3)] ]
403
+ bt = np.empty((3,3))
404
+ bt[:] = np.nan
405
+ #print bt
406
+ # ecef to instrument coordinates transformation
407
+ q3 = nan # used in subrtn lpoint
408
+ pitch = roll = yaw = nan # pitch,roll,yaw angles of instrument (rad)
409
+ pma = nan # pitch misalignment of instrument (rad)
410
+ rma = nan # roll misalignment of instrument (rad)
411
+
412
+ incmax = [6136, 2805] # number of increments per cycle
413
+
414
+ elvmax = [0.220896, 0.22089375] # bounds in elevation (radians)
415
+ scnmax= [0.24544,0.2454375] # bounds in scan angle (radians)
416
+ elvinc = [8.e-6, 17.5e-6] # change in elevation angle per increment (rad)
417
+ scninc = [16.e-6, 35.e-6] # change in scan angle per increment (radians)
418
+ elvln = [28.e-6, 280.e-6] # elevation angle per detector line (radians)
419
+ scnpx = [16.e-6, 280.e-6 ]# scan angle per pixel (radians)
420
+ nsnom = [.220896, .22089375] # north-south center of instrument (=4.5 x incmax x elvinc)
421
+
422
+ ewnom = [.24544, .2454375] # east-west center of instrument (=2.5 x incmax x sncinc)
423
+
424
+ STTYPE = 0 # position of instrument type
425
+ IDNTFR = 1
426
+ IMCACT = 2 # position of imc active flag
427
+ IYFLIP = 3 # position of yaw flip enabled flag
428
+ REFLON = 5 # position of reference longitude
429
+ REFDIS = 6 # position of reference distance from nominal
430
+ REFLAT = 7 # position of reference latitude
431
+ REFYAW = 8 # position of reference yaw
432
+ RATROL = 9 # position of reference attitude roll
433
+ RATPTC = 10 # position of reference attitude pitch
434
+ RATYAW = 11 # position of reference attitude yaw
435
+ ETIME = 12 # position of epoch time
436
+ EDTIME = 14 # location of delta from epoch time
437
+ IMCROL = 15 # location of image motion compensation roll
438
+ IMCPTC = 16 # location of image motion compensation pitch
439
+ IMCYAW = 17 # location of image motion compensation yaw
440
+
441
+ # ldr1-13: location of longitude delta from reference parameters
442
+ LDR1 = 18
443
+ LDR2 = 19
444
+ LDR3 = 20
445
+ LDR4 = 21
446
+ LDR5 = 22
447
+ LDR6 = 23
448
+ LDR7 = 24
449
+ LDR8 = 25
450
+ LDR9 = 26
451
+ LDR10 = 27
452
+ LDR11 = 28
453
+ LDR12 = 29
454
+ LDR13 = 30
455
+
456
+ # rddr1-11: location of radial distance delta from reference parameters
457
+ RDDR1 = 31
458
+ RDDR2 = 32
459
+ RDDR3 = 33
460
+ RDDR4 = 34
461
+ RDDR5 = 35
462
+ RDDR6 = 36
463
+ RDDR7 = 37
464
+ RDDR8 = 38
465
+ RDDR9 = 39
466
+ RDDR10 = 40
467
+ RDDR11 = 41
468
+
469
+ # dgl1-9: location of geocentric latitude delta parameters
470
+ DGL1 = 42
471
+ DGL2 = 43
472
+ DGL3 = 44
473
+ DGL4 = 45
474
+ DGL5 = 46
475
+ DGL6 = 47
476
+ DGL7 = 48
477
+ DGL8 = 49
478
+ DGL9 = 50
479
+
480
+ # doy1-9: location of orbit yaw delta parameters
481
+ DOY1 = 51
482
+ DOY2 = 52
483
+ DOY3 = 53
484
+ DOY4 = 54
485
+ DOY5 = 55
486
+ DOY6 = 56
487
+ DOY7 = 57
488
+ DOY8 = 58
489
+ DOY9 = 59
490
+
491
+ EXPTIM = 61 # exponential start time from epoch
492
+ RAAWDS = 62 # location of start of roll attitude angle words
493
+ PAAWDS = 129 # location of start of pitch attitude angle words
494
+ YAAWDS = 184 # location of start of yaw attitude angle words
495
+ RMAWDS = 257 # location of start of roll misalignment angle words
496
+ PMAWDS = 312 # location of start of pitch misalignment angle words
497
+
498
+ IMGDAY = 367 # position of image day value (yyddd)
499
+ IMGTM = 368 # position of image time value (hhmmss)
500
+ IMGSND = 369 # location of imager/sounder instrument flag
501
+ ISTIM = 226
502
+
503
+ # the following four words were added 5-26-94 to comply w/ the new elug...
504
+ # numbering started at 380 because these same parameters are used
505
+ # in the nav message sent from the ingestor to evx, and we had to
506
+ # start somewhere after the 378 nav parameters
507
+
508
+ IOFNC = 379
509
+ IOFEC = 380
510
+ IOFNI = 381
511
+ IOFEI = 382
512
+
513
+ MXCDSZ=5*128 # maximum directory block entry size
514
+
515
+ OASIZE = 336 # size of gvar orbit and attitude set
516
+ PCOEFS = 117 # start of pitch coefficients
517
+ RMACFS = 227 # start of rma coefficients
518
+ CUTOF1 = 115 # first dividing poin o&a set (128 word sets)
519
+ CUTOF2 = 225 # second dividing poin o&a set (128 word sets)
520
+
521
+ IMCFLG = 7 # bit # in sscan for imc active flag
522
+ FLPFLG = 15 # bit # in sscan for yaw flip enabled flat
523
+ iflip = None # value of FLPFLG
524
+
525
+ # now some variables that are shared among the methods...
526
+
527
+ aec = ts = dr = lam = dlat = dyaw = phi = psi = imc = nan
528
+ aebe2c = aebe3c = aebe4c = ferc = nan
529
+ instr = itype = None
530
+ sublat = sublon = nan
531
+ rlat = rlon = gam = alf = nan
532
+ subpoint = [nan] * 2
533
+
534
+ RELLST = ( ( 4, 10), ( 13, 63), ( 65, 94),
535
+ ( 98, 100), (103, 105), (108, 110), (113, 115),
536
+ (116, 118), (120, 149), (153, 155), (158, 160),
537
+ (163, 165), (168, 170), (171, 173), (175, 204),
538
+ (208, 210), (213, 215), (218, 220), (223, 225),
539
+ (226, 228), (230, 259), (263, 265), (268, 270),
540
+ (273, 275), (278, 283), (285, 314), (318, 320),
541
+ (323, 325), (328, 330), (333, 335))
542
+
543
+ def __init__(self, navblock=None, auxblock=None, **kwargs):
544
+ """
545
+ doc
546
+ """
547
+
548
+ #python is not java but i declare this so I do not lose the track of instance vars
549
+
550
+ te = u = sinu = cosu = nan
551
+ sinoi = cosoi = slat = asc = sinasc = cosasc = nan
552
+ syaw = w = sw = cw = s2w = c2w = nan
553
+ sw1 = cw1 = sw3 = cw3 = nan
554
+ secs = wa = nan
555
+ imgtim = epoch = r = nan
556
+ #b = [[nan for i in range(3)], [nan for i in range(3)], [nan for i in range(3)] ]
557
+ b = np.empty((3,3))
558
+ b[:] = np.nan
559
+ year = day = hour = minuts = nan
560
+ rparms = [nan] * self.MXCDSZ
561
+ # rellst two dimensional array of location of float in o&a set
562
+
563
+ # these are filled in below; every instance needs its own, not the lists and array shared through the class
564
+ self.xs = [nan] * 3
565
+ self.bt = np.full((3, 3), nan)
566
+ self.subpoint = [nan] * 2
567
+ self.elvmax = list(GVARNav.elvmax)
568
+ self.scnmax = list(GVARNav.scnmax)
569
+
570
+ # initialize the earth radius constants
571
+ self.aec = self.AE
572
+ self.ferc = self.FER
573
+ self.aebe2c = self.AEBE2
574
+ self.aebe3c = float(self.AEBE3)
575
+ self.aebe4c = float(self.AEBE4)
576
+
577
+
578
+ navtype = struct.unpack(f'{self.byte_order}4s',
579
+ struct.pack(f'{self.byte_order}{self.int_format}', navblock[self.STTYPE]))[0]
580
+ navtype = navtype.decode()
581
+
582
+ if navtype != self.GVAR:
583
+ raise Exception(f'Invalid navigation type {navtype}')
584
+
585
+
586
+ self.itype = 1
587
+ #convert to float, no Gould bullshit like in C, just int to float, same order of course
588
+
589
+ for i in range(self.MXCDSZ):
590
+ rparms[i] = struct.unpack(f'{self.byte_order}f',
591
+ struct.pack(f'{self.byte_order}{self.int_format}', navblock[i]))[0]
592
+
593
+
594
+
595
+ #divide floats as per OGE
596
+ for i, e in enumerate(self.RELLST):
597
+ li, ui = e
598
+ offset = 1
599
+ if li > self.CUTOF1:
600
+ offset = 13
601
+ if li > self.CUTOF2:
602
+ offset = 31
603
+ for j in range(li, ui + 1): # RELLST bounds are inclusive, as in VisAD
604
+
605
+ if (j == 13 or j == 60 or (j - 7) % 55 == 0) and j != 7:
606
+ rparms[j+offset] = navblock[j+offset] / 100.
607
+ else:
608
+ rparms[j + offset] = navblock[j + offset] / 10000000.
609
+
610
+ self.instr = navblock[self.IMGSND]
611
+
612
+
613
+
614
+
615
+ # ----------------------------------------------------------
616
+ # new code from kath kelly for sounder nav - 10/27/??
617
+ # because change to elug -- nadir postion is avabile in
618
+ # signal and should be used to compute values instead
619
+ # of making them hardwired...
620
+
621
+
622
+ self.nadnsc = navblock[self.IOFNC]
623
+ self.nadnsi = navblock[self.IOFNI]
624
+ self.nadewc = navblock[self.IOFEC]
625
+ self.nadewi = navblock[self.IOFEI]
626
+
627
+ if self.nadnsc != 0 and self.nadnsi != 0 and self.nadewc != 0 and self.nadewi != 0:
628
+ if self.instr == 1:
629
+ self.elvmax[0] = (self.nadnsc* self.incmax[0]+self.nadnsi)*self.elvinc[0]
630
+ else:
631
+ self.elvmax[1]=( (9-self.nadnsc)*self.incmax[1]-self.nadnsi)*self.elvinc[1]
632
+ self.scnmax[self.instr-1] = (self.nadewc*self.incmax[self.instr-1]+self.nadewi)*self.scninc[self.instr-1]
633
+
634
+
635
+ # end of new code from kathy kelly
636
+ # ----------------------------------------------------------
637
+ #compute image time and epoch
638
+
639
+ #java and c code uses this computation to get to epoch time in minutes
640
+ #this could nevertheless be a source of rounding error
641
+ #but hey, python has all this figured out through timedelta
642
+
643
+ year = 1900 + navblock[self.IMGDAY] // 1000
644
+ day = navblock[self.IMGDAY] - navblock[self.IMGDAY] // 1000 * 1000
645
+ # VisAD: rparms[IMGTM] = (float) iparms[IMGTM] / 1000.f, then integer arithmetic on its integer part
646
+ rparms[self.IMGTM] = np.float32(navblock[self.IMGTM]) / np.float32(1000.)
647
+ hhmmss = int(rparms[self.IMGTM])
648
+ hour = hhmmss // 10000
649
+ minuts = hhmmss // 100 - hour * 100
650
+ secs = float(rparms[self.IMGTM] - np.float32(100 * minuts) - np.float32(10000 * hour))
651
+
652
+
653
+
654
+
655
+
656
+ j = day + 1461 * (year + 4799) // 4 - 3 * ((year + 4899) // 100) // 4 - 2465022
657
+
658
+ imgtim = float( j * 1440. + hour * 60. + minuts + (secs / 60.))
659
+
660
+
661
+ # the epoch is decoded below, in minutes since 1950-01-01 like imgtim. imgtim follows VisAD (a float
662
+ # holding hhmmss.mmm, as the word counts milliseconds); decoding the day and time words with
663
+ # utils.yyyddd_hhmmss2datetime would differ by up to 0.016 s from that float.
664
+ jan_1_1950 = datetime.datetime(1950, 1, 1)
665
+ bcdtime = utils.bcd_words_to_datetime(navblock[self.ETIME], navblock[self.ETIME+1])
666
+
667
+
668
+
669
+ diff1 = bcdtime - jan_1_1950
670
+ epoch = diff1.total_seconds()/60. # orbit and attitude epoch, minutes since 1950-01-01
671
+
672
+
673
+ self.imc = 0 if ( (navblock[self.IMCACT] & (1 << self.IMCFLG)) != 0 ) else 1
674
+ self.iflip = -1 if ( (navblock[self.IYFLIP] & (1 << self.FLPFLG)) != 0) else 1
675
+ #print self.imc, self.iflip, imgtim
676
+ # print self.imc
677
+ # print self.iflip
678
+
679
+ # assign reference values to the subsatellite longitude and
680
+ # latitude, the radial distance and the orbit yaw.
681
+ self.lam = rparms[self.REFLON]
682
+
683
+ self.dr = rparms[self.REFDIS]
684
+
685
+ self.phi = rparms[self.REFLAT]
686
+
687
+ self.psi = rparms[self.REFYAW]
688
+
689
+
690
+ self.subpoint[0] = rparms[self.REFLAT] / self.RAD
691
+ self.subpoint[1] = rparms[self.REFLON] / self.RAD
692
+
693
+
694
+ # assign reference values to the attitudes and misalignments
695
+ self.roll = rparms[self.RATROL]
696
+ self.pitch = rparms[self.RATPTC]
697
+ self.yaw = rparms[self.RATYAW]
698
+
699
+
700
+ self.rma = 0.
701
+ self.pma = 0.
702
+ # if imc is off, compute changes in the instrument orbit
703
+ if self.imc != 0:
704
+ # set reference radial distance, latitude and orbit yaw to zero
705
+ self.dr = 0.
706
+ self.phi = 0.
707
+ self.psi = 0.
708
+
709
+ # compute time since epoch (in minutes)
710
+ self.ts = imgtim - epoch
711
+ # computes orbit angle and the related trigonometric functions.
712
+ # earth rotational rate=.729115e-4 (RAD/s)
713
+ w = 0.729115e-4 * 60.0 * self.ts
714
+ sw = math.sin(w)
715
+ cw = math.cos(w)
716
+ sw1 = math.sin(0.927 * w)
717
+ cw1 = math.cos(0.927 * w)
718
+ s2w = math.sin(2. * w)
719
+ c2w = math.cos(2. * w)
720
+ sw3 = math.sin(1.9268 * w)
721
+ cw3 = math.cos(1.9268 * w)
722
+
723
+ # computes change in the imc longitude from the reference
724
+ self.lam = self.lam + rparms[self.LDR1] + (rparms[self.LDR2] + rparms[self.LDR3] * w) * w \
725
+ + (rparms[self.LDR10] * sw1 + rparms[self.LDR11] * cw1 + rparms[self.LDR4] * sw \
726
+ + rparms[self.LDR5] * cw + rparms[self.LDR6] * s2w + rparms[self.LDR7] * c2w \
727
+ + rparms[self.LDR8] * sw3 + rparms[self.LDR9] * cw3
728
+ + w * (rparms[self.LDR12] * sw + rparms[self.LDR13] * cw)) * 2.
729
+
730
+ # computes change in radial distance from the reference (km)
731
+ self.dr = self.dr + rparms[self.RDDR1] + rparms[self.RDDR2] * cw + rparms[self.RDDR3] * sw \
732
+ + rparms[self.RDDR4] * c2w + rparms[self.RDDR5] * s2w + rparms[self.RDDR6]*cw3 \
733
+ + rparms[self.RDDR7] * sw3 + rparms[self.RDDR8] * cw1 \
734
+ + rparms[self.RDDR9] * sw1 + w * (rparms[self.RDDR10] * cw + rparms[self.RDDR11] * sw)
735
+ # computes the sine of the change in the geocentric latitude
736
+ self.dlat = rparms[self.DGL1] + rparms[self.DGL2] * cw + rparms[self.DGL3] * sw \
737
+ + rparms[self.DGL4] * c2w + rparms[self.DGL5] * s2w + w * (rparms[self.DGL6] * cw \
738
+ + rparms[self.DGL7] * sw) + rparms[self.DGL8] * cw1 + rparms[self.DGL9] * sw1
739
+
740
+ # computes geocentric latitude by using an expansion for arcsine
741
+ self.phi = self.phi + self.dlat * (1. + self.dlat * self.dlat / 6.)
742
+
743
+ # computes sine of the change in the orbit yaw
744
+ self.dyaw = rparms[self.DOY1] + rparms[self.DOY2] * sw + rparms[self.DOY3] * cw \
745
+ + rparms[self.DOY4] * s2w + rparms[self.DOY5] * c2w \
746
+ + w * (rparms[self.DOY6] * sw + rparms[self.DOY7] * cw) \
747
+ + rparms[self.DOY8] * sw1 + rparms[self.DOY9] * cw1
748
+ # computes the orbit yaw by using an expansion for arcsine.
749
+ self.psi = self.psi + self.dyaw * (1. + self.dyaw * self.dyaw / 6.)
750
+
751
+ # calculation of changes in the instrument orbit ends here
752
+
753
+ # conversion of the imc longitude and orbit yaw to the subinstrument
754
+ # longitude and the orbit inclination (ref: goes-pcc-tm-2473, inputs
755
+ # required for earth location and gridding by sps, june 6, 1988)
756
+ slat = math.sin(self.phi)
757
+ syaw = math.sin(self.psi)
758
+ sinoi = slat * slat + syaw * syaw
759
+ cosoi = math.sqrt(1. - sinoi)
760
+ sinoi = math.sqrt(sinoi)
761
+
762
+ if slat == 0.0 and syaw == 0.0:
763
+ u = 0.0
764
+ else:
765
+ u = math.atan2(slat, syaw)
766
+ sinu = math.sin(u)
767
+ cosu = math.cos(u)
768
+
769
+ # computes longitude of the ascending node
770
+ asc = self.lam - u
771
+ sinasc = math.sin(asc)
772
+ cosasc = math.cos(asc)
773
+
774
+ # computes the subinstrument geographic latitude
775
+ self.sublat = math.atan(self.aebe2c * math.tan(self.phi))
776
+
777
+ # computes the subinstrument longitude
778
+ self.sublon = asc + math.atan2(cosoi * sinu, cosu)
779
+
780
+ # computes the spacecraft to earth fixed coordinates transformation
781
+ # matrix:
782
+ # (vector in ecef coordinates) = b * (vector in s/c coordinates)
783
+
784
+ b[0][1] = -sinasc * sinoi
785
+ b[1][1] = cosasc * sinoi
786
+ b[2][1] = -cosoi
787
+ b[0][2] = -cosasc * cosu + sinasc * sinu * cosoi
788
+ b[1][2] = -sinasc * cosu - cosasc * sinu * cosoi
789
+ b[2][2] = -slat
790
+ b[0][0] = -cosasc * sinu - sinasc * cosu * cosoi
791
+ b[1][0] = -sinasc * sinu + cosasc * cosu * cosoi
792
+ b[2][0] = cosu * sinoi
793
+
794
+ # computes the normalized spacecraft position vector in earth fixed
795
+ # coordinates - xs.
796
+ r = (self.NOMORB + self.dr) / self.aec
797
+ self.xs[0] = -b[0][2] * r
798
+ self.xs[1] = -b[1][2] * r
799
+ self.xs[2] = -b[2][2] * r
800
+
801
+ # precomputes q3 (used in lpoint funciton (now in navToLatLon() )
802
+
803
+ self.q3 = self.xs[0] * self.xs[0] + self.xs[1] * self.xs[1] + self.aebe2c * self.xs[2] * self.xs[2] - 1.0
804
+
805
+ # computes the attitudes and misalignments if imc is off
806
+ if self.imc != 0:
807
+ # the solar orbit angle
808
+ wa = rparms[61-1] * self.ts
809
+ # the difference between the current time, ts, and the exponential time, iparms(62); both times are
810
+ # since epoch
811
+ te = self.ts - rparms[self.EXPTIM]
812
+ # roll, pitch and yaw, with their misalignments
813
+ self.roll = self.roll + self.gatt(self.RAAWDS, rparms, navblock, wa, te)
814
+ self.pitch = self.pitch + self.gatt(self.PAAWDS, rparms, navblock, wa, te)
815
+ self.yaw = self.yaw + self.gatt(self.YAAWDS, rparms, navblock, wa, te)
816
+ self.rma = float(self.gatt(self.RMAWDS, rparms, navblock, wa, te))
817
+ self.pma = float(self.gatt(self.PMAWDS, rparms, navblock, wa, te))
818
+ # the earth sensor compensation, if needed
819
+ self.roll = self.roll + rparms[self.IMCROL]
820
+ self.pitch = self.pitch + rparms[self.IMCPTC]
821
+ self.yaw = self.yaw + rparms[self.IMCYAW]
822
+ # end if (imc...)
823
+ #this needs to be fixed, those params are passed for no reason as they are instance
824
+ self.inst2e(self.roll, self.pitch, self.yaw, b, self.bt)
825
+
826
+
827
+
828
+ def gatt(self, k, floatblock, intblock, wa, te):
829
+ """
830
+ k = starting position of a parameter subset in the real o&a set
831
+ floatblock(mxcdxz) = input o&a parameter set
832
+ intblock(mxcdxz) = input o&a parameter set
833
+ double wa = input solar orbit angle in radians
834
+ double te = input exponential time delay from epoch (minutes)
835
+ """
836
+ # local variables
837
+
838
+ #ir, jr = mr = att
839
+
840
+ # constant component
841
+ att = floatblock[k + 2]
842
+
843
+ # computes the exponential term
844
+ if te >= 0:
845
+ att = att + floatblock[k] * math.exp(-te / floatblock[k + 1])
846
+
847
+
848
+ # extracts the number of sinusoids
849
+ ir = float(intblock[k + 3])
850
+ i = int(ir)
851
+
852
+ # calculation of sinusoids
853
+
854
+ for j in range(1, i + 1):
855
+ att = att + floatblock[k + 2 * j + 2] * math.cos(wa * float(j) + floatblock[k + 2 * j + 3])
856
+
857
+
858
+ # pointer to the number of monomial sinusoids
859
+ k = k + 34
860
+
861
+ # extarct number of monomial sinusoids
862
+ ir = float(intblock[k])
863
+ kkk = int(intblock[k])
864
+
865
+
866
+ # computes monomial sinusoids
867
+
868
+ for term in range(1, kkk+1):
869
+
870
+ ll = k + 5 * term # order of sinusoid
871
+ jr = float(intblock[ll - 4])
872
+
873
+ # order of monomial sinusoid
874
+ mr = float(intblock[ll - 3])
875
+ att = att + (floatblock[ll - 2] * math.pow((wa - floatblock[ll]), mr)
876
+ * math.cos(jr * wa + floatblock[ll - 1]))
877
+
878
+
879
+ return att
880
+
881
+ def inst2e(self, r, p, y, a, at):
882
+ """
883
+ r = roll angle in radians
884
+ p = pitch angle in radians
885
+ y = yaw angle in radians
886
+ a(3,3) = spacecraft to ecef coordinates transformation matrix
887
+ at(3,3)= instrument to ecef coordinates transformation matrix
888
+ """
889
+ #rpy = [[nan for i in range(3)], [nan for i in range(3)], [nan for i in range(3)]]
890
+ rpy = np.empty((3,3))
891
+ rpy[:] = np.nan
892
+
893
+ # we compute instrument to body coordinates transformation
894
+ # matrix by using a small angle approximation of trigonometric
895
+ # funktions of the roll, pitch and yaw.
896
+ rpy[0][0] = 1. - 0.5 * (p * p + y * y)
897
+ rpy[0][1] = -y
898
+ rpy[0][2] = p
899
+ rpy[1][0] = y + p * r
900
+ rpy[1][1] = 1. - 0.5 * (y * y + r * r)
901
+ rpy[1][2] = -r
902
+ rpy[2][0] = -p + r * y
903
+ rpy[2][1] = r + p * y
904
+ rpy[2][2] = 1. - 0.5 * (p * p + r * r)
905
+
906
+ # multiplication of matrices a and rpy
907
+
908
+
909
+ for i in range(3):
910
+ for j in range(3):
911
+ at[i][j] = a[i][0] * rpy[0][j] + a[i][1] * rpy[1][j] +a[i][2] * rpy[2][j]
912
+
913
+
914
+ def _kernel_params(self):
915
+ """The scalar constants the numba kernels need, for the instrument (imager or sounder) of this file."""
916
+ k = self.instr - 1
917
+ bt, xs = self.bt, self.xs
918
+ return _GvarParams(
919
+ instr=int(self.instr),
920
+ ff=float(-self.iflip) if self.instr == 2 else float(self.iflip),
921
+ doff=float(self.scnmax[k] - self.ewnom[k]),
922
+ elvmax=float(self.elvmax[k]), elvln=float(self.elvln[k]),
923
+ scnpx=float(self.scnpx[k]), scnmax=float(self.scnmax[k]),
924
+ pma=float(self.pma), rma=float(self.rma),
925
+ b00=float(bt[0][0]), b01=float(bt[0][1]), b02=float(bt[0][2]),
926
+ b10=float(bt[1][0]), b11=float(bt[1][1]), b12=float(bt[1][2]),
927
+ b20=float(bt[2][0]), b21=float(bt[2][1]), b22=float(bt[2][2]),
928
+ xs0=float(xs[0]), xs1=float(xs[1]), xs2=float(xs[2]),
929
+ aebe2c=float(self.aebe2c), aebe3c=float(self.aebe3c), aebe4c=float(self.aebe4c),
930
+ q3=float(self.q3), east=1.0 if self.isEastPositive else -1.0,
931
+ )
932
+
933
+ def to_latlon(self, line, elem):
934
+ """Convert line/element (AREA/file coordinates, any shape, broadcast together) to ``(lat, lon)`` degrees.
935
+
936
+ East longitude is positive. NaN where the line of sight misses the Earth, or the input is NaN.
937
+ """
938
+ line, elem = np.broadcast_arrays(np.asarray(line, dtype=float), np.asarray(elem, dtype=float))
939
+ image_line, image_elem = self._area_to_image(line, elem)
940
+ lat, lon = _gvar_to_latlon(np.ascontiguousarray(image_line).ravel(), np.ascontiguousarray(image_elem).ravel(),
941
+ self._kernel_params())
942
+ return lat.reshape(line.shape), lon.reshape(line.shape)
943
+
944
+ def to_lin_ele(self, lat, lon):
945
+ """Convert lat/lon degrees (east positive, any shape, broadcast together) to ``(line, element)``.
946
+
947
+ The result is in AREA (file) coordinates. NaN where the point is not visible from the satellite.
948
+ """
949
+ lat, lon = np.broadcast_arrays(np.asarray(lat, dtype=float), np.asarray(lon, dtype=float))
950
+ image_line, image_elem = _gvar_to_image(np.ascontiguousarray(lat).ravel(), np.ascontiguousarray(lon).ravel(),
951
+ self._kernel_params())
952
+ line, elem = self._image_to_area(image_line, image_elem)
953
+ return line.reshape(lat.shape), elem.reshape(lat.shape)
954
+
955
+ def toLatLon(self, linele=None):
956
+ """Convert ``[[elements], [lines]]`` (file coordinates; elements first) to ``[[lats], [lons]]``."""
957
+ lat, lon = self.to_latlon(linele[self.indexLine], linele[self.indexEle])
958
+ return [lat, lon]
959
+
960
+ def toLinEle(self, latlon=None):
961
+ """Convert ``[[lats], [lons]]`` to ``[[elements], [lines]]`` in file coordinates."""
962
+ line, elem = self.to_lin_ele(latlon[self.indexLat], latlon[self.indexLon])
963
+ out = [None, None]
964
+ out[self.indexLine], out[self.indexEle] = line, elem
965
+ return out
966
+
967
+ def toLatLon2(self, lines=None, cols=None):
968
+ """Array version of :meth:`toLatLon`: ``lines`` and ``cols`` (broadcast together) to ``(lat, lon)``."""
969
+ return self.to_latlon(lines, cols)
970
+
971
+ def toLinEle2(self, lats=None, lons=None):
972
+ """Array version of :meth:`toLinEle`: ``lats`` and ``lons`` to ``(lines, cols)``, NaN where not visible."""
973
+ return self.to_lin_ele(lats, lons)
974
+
975
+ def getSubpoint(self):
976
+
977
+ return self.sublat * self.DEG, self.sublon * self.DEG
978
+
979
+
980
+ def _float_bits(words):
981
+ """Reinterpret 32-bit integer words (already decoded from the file's byte order) as floats, like intBitsToFloat."""
982
+ return np.asarray(words, dtype=np.int64).astype(np.uint32).view(np.float32)
983
+
984
+
985
+ @_njit
986
+ def _value_to_grid(sx, sy, vx, vy, length_x, length_y, pos):
987
+ """``Gridded2DSet.valueToGrid`` (VisAD) in float32: the grid coordinates of the points (vx, vy).
988
+
989
+ ``sx`` and ``sy`` are the x and y of the ``length_x`` x ``length_y`` grid points, x running fastest; ``pos`` is the
990
+ orientation of the grid. The grid box of the previous point is the first guess, and so is the choice of triangle.
991
+ """
992
+ n = vx.shape[0]
993
+ grid_x = np.full(n, np.nan, dtype=np.float32)
994
+ grid_y = np.full(n, np.nan, dtype=np.float32)
995
+ gx = (length_x - 1) // 2
996
+ gy = (length_y - 1) // 2
997
+ lowertri = True
998
+ one = np.float32(1.0)
999
+ for i in range(n):
1000
+ if i != 0 and grid_x[i - 1] != grid_x[i - 1]: # the last point had no solution: start in the middle again
1001
+ gx = (length_x - 1) // 2
1002
+ gy = (length_y - 1) // 2
1003
+ for _ in range(2 * (length_x + length_y)):
1004
+ k0 = gy * length_x + gx
1005
+ k1 = k0 + 1
1006
+ k2 = (gy + 1) * length_x + gx
1007
+ k3 = k2 + 1
1008
+ v0x, v0y, v1x, v1y = sx[k0], sy[k0], sx[k1], sy[k1]
1009
+ v2x, v2y, v3x, v3y = sx[k2], sy[k2], sx[k3], sy[k3]
1010
+ px, py = vx[i], vy[i]
1011
+ # the diagonal D-B and the distances P-B and P-D are used in both triangles
1012
+ bdx, bdy = v2x - v1x, v2y - v1y
1013
+ bpx, bpy = px - v1x, py - v1y
1014
+ dpx, dpy = px - v2x, py - v2y
1015
+ ogx, ogy = gx, gy
1016
+ if lowertri:
1017
+ abx, aby = v1x - v0x, v1y - v0y
1018
+ dax, day = v0x - v2x, v0y - v2y
1019
+ apx, apy = px - v0x, py - v0y
1020
+ tval1 = abx * apy - aby * apx
1021
+ tval2 = bdx * bpy - bdy * bpx
1022
+ tval3 = dax * dpy - day * dpx
1023
+ test1 = (tval1 == 0) or ((tval1 > 0) == pos)
1024
+ test2 = (tval2 == 0) or ((tval2 > 0) == pos)
1025
+ test3 = (tval3 == 0) or ((tval3 > 0) == pos)
1026
+ if not test1 and not test2: # up and right
1027
+ gx += 1
1028
+ gy -= 1
1029
+ elif not test2 and not test3: # down and left
1030
+ gx -= 1
1031
+ gy += 1
1032
+ elif not test1 and not test3: # up and left
1033
+ gx -= 1
1034
+ gy -= 1
1035
+ elif not test1: # up
1036
+ gy -= 1
1037
+ elif not test3: # left
1038
+ gx -= 1
1039
+ gx = min(max(gx, 0), length_x - 2)
1040
+ gy = min(max(gy, 0), length_y - 2)
1041
+ if gx == ogx and gy == ogy and test2: # the right triangle: solve with the reverse interpolation
1042
+ grid_x[i] = (((px - v0x) * (v2y - v0y) + (v0y - py) * (v2x - v0x))
1043
+ / ((v1x - v0x) * (v2y - v0y) + (v0y - v1y) * (v2x - v0x)) + np.float32(gx))
1044
+ grid_y[i] = (((px - v0x) * (v1y - v0y) + (v0y - py) * (v1x - v0x))
1045
+ / ((v2x - v0x) * (v1y - v0y) + (v0y - v2y) * (v1x - v0x)) + np.float32(gy))
1046
+ break
1047
+ lowertri = False
1048
+ else:
1049
+ bcx, bcy = v3x - v1x, v3y - v1y
1050
+ cdx, cdy = v2x - v3x, v2y - v3y
1051
+ cpx, cpy = px - v3x, py - v3y
1052
+ tval1 = bcx * bpy - bcy * bpx
1053
+ tval2 = cdx * cpy - cdy * cpx
1054
+ tval3 = bdx * dpy - bdy * dpx
1055
+ test1 = (tval1 == 0) or ((tval1 > 0) == pos)
1056
+ test2 = (tval2 == 0) or ((tval2 > 0) == pos)
1057
+ test3 = (tval3 == 0) or ((tval3 < 0) == pos)
1058
+ if not test1 and not test3: # up and right
1059
+ gx += 1
1060
+ gy -= 1
1061
+ elif not test2 and not test3: # down and left
1062
+ gx -= 1
1063
+ gy += 1
1064
+ elif not test1 and not test2: # down and right
1065
+ gx += 1
1066
+ gy += 1
1067
+ elif not test1: # right
1068
+ gx += 1
1069
+ elif not test2: # down
1070
+ gy += 1
1071
+ gx = min(max(gx, 0), length_x - 2)
1072
+ gy = min(max(gy, 0), length_y - 2)
1073
+ if gx == ogx and gy == ogy and test3:
1074
+ grid_x[i] = (((v3x - px) * (v1y - v3y) + (py - v3y) * (v1x - v3x))
1075
+ / ((v2x - v3x) * (v1y - v3y) - (v2y - v3y) * (v1x - v3x)) + np.float32(gx)) + one
1076
+ grid_y[i] = (((v2y - v3y) * (v3x - px) + (v2x - v3x) * (py - v3y))
1077
+ / ((v1x - v3x) * (v2y - v3y) - (v2x - v3x) * (v1y - v3y)) + np.float32(gy)) + one
1078
+ break
1079
+ lowertri = True
1080
+ if (grid_x[i] >= length_x - 0.5 or grid_y[i] >= length_y - 0.5
1081
+ or grid_x[i] <= -0.5 or grid_y[i] <= -0.5):
1082
+ grid_x[i] = np.nan
1083
+ grid_y[i] = np.nan
1084
+ return grid_x, grid_y
1085
+
1086
+
1087
+ class LALONav(AreaNav):
1088
+ """Navigation from tables of latitude and longitude, nav type LALO (Kalpana-1 and others).
1089
+
1090
+ Port of ``edu.wisc.ssec.mcidas.LALOnav`` (``laloutil.c`` of McIDAS-X). The nav block describes a grid of
1091
+ ``rows`` x ``cols`` tie points, one every ``latres`` image lines and ``lonres`` image elements from the image
1092
+ position ``ulline``/``ulelem``, and the aux block holds the float32 latitude and longitude of each of them. Words of
1093
+ the nav block (counted from 1): 66 and 67 the number of rows and columns, 68-71 the minimum and maximum latitude
1094
+ and longitude (floats), 72 and 73 the line and element spacing, 74 and 75 the table position inside the image
1095
+ (unused), 76 and 77 the image line and element of the first tie point, 78 the size of the aux block, 79 and 80
1096
+ the byte offsets of the latitude and longitude tables within the aux block.
1097
+
1098
+ ``to_latlon`` interpolates between the four surrounding tie points like the Java, which truncates the line and
1099
+ element to a whole number of image pixels first. Tie points with a latitude or longitude outside -90 to 90 and
1100
+ -180 to 360 are missing (stored as 0, 0), and so is any pixel next to one. ``to_lin_ele`` is
1101
+ ``Gridded2DSet.valueToGrid`` of VisAD, which interpolates linearly on the two triangles of each grid box (not
1102
+ bilinearly as ``to_latlon`` does), so the two directions differ slightly between the tie points.
1103
+ """
1104
+
1105
+ labels = {1: 'LALO', 66: 'rows', 67: 'columns', 68: 'minimum latitude', 69: 'minimum longitude',
1106
+ 70: 'maximum latitude', 71: 'maximum longitude', 72: 'line spacing', 73: 'element spacing',
1107
+ 76: 'image line of the first tie point', 77: 'image element of the first tie point',
1108
+ 78: 'size of the aux block', 79: 'byte offset of the latitudes', 80: 'byte offset of the longitudes'}
1109
+
1110
+ def __init__(self, navblock=None, auxblock=None, **kwargs):
1111
+ if self.navtype.strip() != self.LALO:
1112
+ raise ValueError(f'Invalid navigation type: {self.navtype!r}')
1113
+ if len(navblock) < 80:
1114
+ raise ValueError(f'The LALO navigation block has {len(navblock)} words, 80 are needed.')
1115
+ if auxblock is None or len(auxblock) == 0:
1116
+ raise ValueError('LALO navigation needs the aux block of the file, which holds the latitudes '
1117
+ 'and longitudes.')
1118
+ self.rows, self.cols = int(navblock[65]), int(navblock[66])
1119
+ bounds = _float_bits(navblock[67:71])
1120
+ self.minlat, self.minlon, self.maxlat, self.maxlon = (float(v) for v in bounds)
1121
+ self.latres, self.lonres = int(navblock[71]), int(navblock[72])
1122
+ self.latpoint, self.lonpoint = int(navblock[73]), int(navblock[74])
1123
+ self.ulline, self.ulelem = int(navblock[75]), int(navblock[76])
1124
+ self.aux_size, self.lat_aux_offset, self.lon_aux_offset = (int(v) for v in navblock[77:80])
1125
+ if self.rows < 1 or self.cols < 1:
1126
+ raise ValueError(f'The LALO navigation block has {self.rows} rows and {self.cols} columns.')
1127
+ if self.latres < 1 or self.lonres < 1:
1128
+ raise ValueError(f'The LALO tie point spacing is {self.latres} lines by {self.lonres} elements.')
1129
+ self.lrlin = self.ulline + (self.rows - 1) * self.latres
1130
+ self.lrele = self.ulelem + (self.cols - 1) * self.lonres
1131
+
1132
+ self.numPoints = self.rows * self.cols
1133
+ begin_lat, begin_lon = self.lat_aux_offset // 4, self.lon_aux_offset // 4
1134
+ if min(begin_lat, begin_lon) < 0 or max(begin_lat, begin_lon) + self.numPoints > len(auxblock):
1135
+ raise ValueError(f'The LALO tables ({self.numPoints} values at words {begin_lat} and {begin_lon}) '
1136
+ f'do not fit in the aux block of {len(auxblock)} words.')
1137
+ # the tables are floats in the byte order the aux block was written in, which for a McFETCH file need not be
1138
+ # the order of the rest of the file (a little-endian Kalpana-1 file has big-endian tables): take the order that
1139
+ # gives the most usable tie points
1140
+ best = None
1141
+ for swap in (False, True):
1142
+ words = np.asarray(auxblock, dtype=np.int64).astype(np.uint32)
1143
+ aux = (words.byteswap() if swap else words).view(np.float32)
1144
+ lat = aux[begin_lat:begin_lat + self.numPoints]
1145
+ lon = aux[begin_lon:begin_lon + self.numPoints]
1146
+ with np.errstate(invalid='ignore'):
1147
+ usable = int(((lat >= -90.0) & (lat <= 90.0) & (lon >= -180.0) & (lon <= 360.0)
1148
+ & ~((lat == 0.0) & (lon == 0.0))).sum())
1149
+ if best is None or usable > best[0]:
1150
+ best = (usable, lat, lon)
1151
+ self.latData, self.lonData = best[1].copy(), best[2].copy()
1152
+ with np.errstate(invalid='ignore'):
1153
+ bad = (self.latData < -90.0) | (self.latData > 90.0) | (self.lonData < -180.0) | (self.lonData > 360.0)
1154
+ self.latData[bad] = 0.0 # LAT_MISSING and LON_MISSING of the Java
1155
+ self.lonData[bad] = 0.0
1156
+ self._samples = None
1157
+
1158
+ def to_latlon(self, line, elem):
1159
+ """Convert line/element (AREA/file coordinates, any shape, broadcast together) to ``(lat, lon)`` degrees.
1160
+
1161
+ NaN outside the table, where a neighbouring tie point is missing, and where the input is NaN.
1162
+ """
1163
+ line, elem = np.broadcast_arrays(np.asarray(line, dtype=float), np.asarray(elem, dtype=float))
1164
+ image_line, image_elem = self._area_to_image(line, elem)
1165
+ rlin, rele = image_line.ravel(), image_elem.ravel()
1166
+ lat = np.full(rlin.shape, np.nan)
1167
+ lon = np.full(rlin.shape, np.nan)
1168
+ with np.errstate(invalid='ignore'):
1169
+ inside = ((rlin >= self.ulline) & (rlin <= self.lrlin) & (rele >= self.ulelem) & (rele <= self.lrele))
1170
+ if inside.any():
1171
+ # the Java truncates to whole image pixels (int) before it takes the cell and the fractions
1172
+ dline = np.trunc(rlin[inside]).astype(np.int64) - self.ulline
1173
+ delem = np.trunc(rele[inside]).astype(np.int64) - self.ulelem
1174
+ row, col = dline // self.latres, delem // self.lonres
1175
+ tl = row * self.cols + col
1176
+ tr, bl = tl + 1, tl + self.cols
1177
+ br = bl + 1
1178
+ last_row = row >= self.rows - 1
1179
+ bl = np.where(last_row, tl, bl)
1180
+ br = np.where(last_row, bl + 1, br)
1181
+ last_col = col >= self.cols - 1
1182
+ tr = np.where(last_col, tl, tr)
1183
+ br = np.where(last_col, bl, br)
1184
+
1185
+ frac_row = (dline % self.latres).astype(np.float32) / np.float32(self.latres)
1186
+ frac_col = (delem % self.lonres).astype(np.float32) / np.float32(self.lonres)
1187
+ missing = np.zeros(tl.shape, dtype=bool)
1188
+ values = []
1189
+ for table in (self.latData, self.lonData):
1190
+ values.append([table[i] for i in (tl, tr, bl, br)])
1191
+ for corner in range(4):
1192
+ missing |= (values[0][corner] == 0.0) & (values[1][corner] == 0.0)
1193
+ out = []
1194
+ for tl_v, tr_v, bl_v, br_v in values:
1195
+ ax, bx, cx = tr_v - tl_v, bl_v - tl_v, (tl_v + br_v) - (bl_v + tr_v)
1196
+ out.append(ax * frac_col + bx * frac_row + cx * frac_row * frac_col + tl_v)
1197
+ lat[inside] = np.where(missing, np.nan, out[0])
1198
+ lon[inside] = np.where(missing, np.nan, out[1])
1199
+ return lat.reshape(line.shape), lon.reshape(line.shape)
1200
+
1201
+ def to_lin_ele(self, lat, lon):
1202
+ """Convert lat/lon degrees (east positive, any shape, broadcast together) to ``(line, element)``.
1203
+
1204
+ The result is in AREA (file) coordinates, NaN where VisAD finds no grid box for the point (outside the table,
1205
+ or next to a missing tie point). Like the Java this is ``Gridded2DSet.valueToGrid`` in float32: a walk over
1206
+ the grid triangles that starts in the middle of the table and carries on from the box of the previous point.
1207
+ A longitude is compared with the table as it is (0 to 360 tables need 0 to 360 longitudes).
1208
+ """
1209
+ lat, lon = np.broadcast_arrays(np.asarray(lat, dtype=float), np.asarray(lon, dtype=float))
1210
+ if self.rows < 2 or self.cols < 2: # VisAD refuses, and the Java returns null
1211
+ grid_x = grid_y = np.full(lat.size, np.nan, dtype=np.float32)
1212
+ else:
1213
+ if self._samples is None:
1214
+ with np.errstate(invalid='ignore'):
1215
+ missing = (self.latData == 0.0) & (self.lonData == 0.0)
1216
+ self._samples = (np.where(missing, np.float32(np.nan), self.lonData).astype(np.float32),
1217
+ np.where(missing, np.float32(np.nan), self.latData).astype(np.float32))
1218
+ sample_x, sample_y = self._samples
1219
+ with np.errstate(invalid='ignore'):
1220
+ # the orientation of the grid, from its first box (Gridded2DSet.Pos)
1221
+ xpos = ((sample_x[1] - sample_x[0]) * (sample_y[self.cols + 1] - sample_y[1])
1222
+ - (sample_y[1] - sample_y[0]) * (sample_x[self.cols + 1] - sample_x[1]))
1223
+ grid_x, grid_y = _value_to_grid(sample_x, sample_y, np.ascontiguousarray(lon.ravel(), dtype=np.float32),
1224
+ np.ascontiguousarray(lat.ravel(), dtype=np.float32), self.cols, self.rows,
1225
+ bool(xpos > 0))
1226
+ line = self.ulline + self.latres * grid_y.astype(float)
1227
+ elem = self.ulelem + self.lonres * grid_x.astype(float)
1228
+ line, elem = self._image_to_area(line, elem)
1229
+ return line.reshape(lat.shape), elem.reshape(lat.shape)
1230
+
1231
+ def toLatLon(self, linele=None):
1232
+ """Convert ``[[elements], [lines]]`` (file coordinates; elements first) to ``[[lats], [lons]]``."""
1233
+ lat, lon = self.to_latlon(linele[self.indexLine], linele[self.indexEle])
1234
+ out = [None, None]
1235
+ out[self.indexLat], out[self.indexLon] = lat, lon
1236
+ return out
1237
+
1238
+ def toLinEle(self, latlon=None):
1239
+ """Convert ``[[lats], [lons]]`` to ``[[elements], [lines]]`` in file coordinates."""
1240
+ line, elem = self.to_lin_ele(latlon[self.indexLat], latlon[self.indexLon])
1241
+ out = [None, None]
1242
+ out[self.indexLine], out[self.indexEle] = line, elem
1243
+ return out
1244
+
1245
+ def toLatLon2(self, lines=None, cols=None):
1246
+ """Array version of :meth:`toLatLon`: ``lines`` and ``cols`` (broadcast together) to ``(lat, lon)``."""
1247
+ return self.to_latlon(lines, cols)
1248
+
1249
+ def toLinEle2(self, lats=None, lons=None):
1250
+ """Array version of :meth:`toLinEle`: ``lats`` and ``lons`` to ``(lines, cols)``, NaN where not found."""
1251
+ return self.to_lin_ele(lats, lons)
1252
+
1253
+
1254
+ # the nav block of a "GOES" file starts with the 4 ASCII bytes of the nav type code AreaNav already defines
1255
+ GOES_MAGIC = AreaNav.GOES.encode("ascii")
1256
+
1257
+ _RDPDG = np.pi / 180.0
1258
+
1259
+ _EQUATORIAL_RADIUS_KM = 6378.137
1260
+
1261
+
1262
+ def _icon1(yymmdd):
1263
+ """YYMMDD -> YYDDD (year/day-of-year), per nvxgoes ICON1."""
1264
+ num = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
1265
+ year = (yymmdd // 10000) % 100
1266
+ month = (yymmdd // 100) % 100
1267
+ day = yymmdd % 100
1268
+ if month < 1 or month > 12:
1269
+ month = 1
1270
+ julday = day + num[month - 1]
1271
+ if year % 4 == 0 and month > 2:
1272
+ julday += 1
1273
+ return 1000 * year + julday
1274
+
1275
+
1276
+ def _check_magic(iarr, endian):
1277
+ expected = int.from_bytes(GOES_MAGIC, "big" if endian == ">" else "little")
1278
+ got = int(iarr[0]) & 0xFFFFFFFF
1279
+ if got != expected:
1280
+ raise ValueError(
1281
+ f"Not a GOES nav block (word 1 = {iarr[0]!r}, expected "
1282
+ f"{expected!r} for endian={endian!r}; if you're sure the "
1283
+ f"raw bytes are b'GOES', this is probably an endian "
1284
+ f"mismatch -- pass the same endian PregvarAreaFile detected)"
1285
+ )
1286
+
1287
+
1288
+ # Scalar constants handed to _to_latlon_kernel() as one immutable bundle
1289
+ # (numba treats a namedtuple of floats as a plain struct), instead of a
1290
+ # ~45-argument call. Built by GOESNav._kernel_params().
1291
+ _KernelParams = collections.namedtuple(
1292
+ "_KernelParams",
1293
+ [
1294
+ # scan / image geometry
1295
+ "numsen", "tmpscl", "pictim", "piclin", "radlin", "radele",
1296
+ "picele", "gamma", "gamdot",
1297
+ # spin-axis rotation matrix (b..) and attitude matrix (rotm..)
1298
+ "b11", "b12", "b13", "b21", "b22", "b23", "b31", "b32", "b33",
1299
+ "rotm11", "rotm13", "rotm21", "rotm23", "rotm31", "rotm33",
1300
+ # earth model and earth-rotation terms
1301
+ "bsq_over_asq", "asq", "bsq", "emega", "xref", "rdpdg",
1302
+ # Kepler orbit (see GOESNav._satvec_init())
1303
+ "tdife", "xmmc", "oeccen", "srome2", "epsiln",
1304
+ "px", "py", "pz", "qx", "qy", "qz",
1305
+ ],
1306
+ )
1307
+
1308
+
1309
+ def _anomaly_hours(semima, oeccen, xmeana):
1310
+ """Return the time in hours that the orbit takes to reach the mean anomaly ``xmeana`` (degrees)."""
1311
+ re = 6378.388
1312
+ gracon = 0.07436574
1313
+ axmmc = gracon * (np.sqrt(re / semima)) ** 3
1314
+ xmanom = (np.pi / 180.0) * xmeana
1315
+ return (xmanom - oeccen * np.sin(xmanom)) / (60.0 * axmmc)
1316
+
1317
+
1318
+ def _day_rollover(time):
1319
+ """Wrap a time in hours into [0, 24) and return it with the whole-day shift that was applied."""
1320
+ if time > 48.0:
1321
+ return time - 48.0, 2
1322
+ if time > 24.0:
1323
+ return time - 24.0, 1
1324
+ if time < -24.0:
1325
+ return time + 48.0, -2
1326
+ if time < 0.0:
1327
+ return time + 24.0, -1
1328
+ return time, 0
1329
+
1330
+
1331
+ def _add_days(ietimy, iday):
1332
+ """Shift a YYDDD epoch by ``iday`` days, following nvxgoes' year rollover."""
1333
+ jyear = (ietimy // 1000) % 100 + 1000
1334
+ jday = ietimy % 1000 + iday
1335
+ if jday < 1:
1336
+ jyear -= 1
1337
+ jday += utils.leapyear(jyear)
1338
+ elif jday > utils.leapyear(jyear):
1339
+ jday += utils.leapyear(jyear)
1340
+ jyear += 1
1341
+ return 1000 * (jyear % 100) + jday
1342
+
1343
+
1344
+ def _epoch(ietimy, ietimh, anomaly_hours):
1345
+ """Move the orbit epoch (YYDDD, HHMMSS) back to perigee, ``anomaly_hours`` earlier."""
1346
+ time, iday = _day_rollover(utils.mcPI2F(ietimh) - anomaly_hours)
1347
+ if iday != 0:
1348
+ ietimy = _add_days(ietimy, iday)
1349
+ return ietimy, utils.mcF2PI(time)
1350
+
1351
+
1352
+ def _validate_nav_words(iarr):
1353
+ """Raise ValueError if the nav block lacks usable orbit, pointing or spin parameters."""
1354
+ problems = (
1355
+ ((iarr[6:12] <= 0).all(),
1356
+ "Invalid orbital parameters (all <= 0) -- this file's nav block has no real orbital elements."),
1357
+ (iarr[4] == 0, "Invalid orbit type"),
1358
+ (not iarr[12:15].any(), "Invalid ascension/declination parameters"),
1359
+ (iarr[15] == 0, "Invalid spin period"),
1360
+ )
1361
+ for failed, message in problems:
1362
+ if failed:
1363
+ raise ValueError(message)
1364
+
1365
+
1366
+ def _has_beta_scan_times(iss):
1367
+ """Tell whether satellite source ``iss`` records the first/last scan line times in its nav block."""
1368
+ return iss > 25 or iss == 12
1369
+
1370
+
1371
+ @_njit
1372
+ def _kepler_position(samtim, p):
1373
+ """Return the satellite position (satx, saty, satz) at time ``samtim``.
1374
+
1375
+ Kepler's equation is solved by fixed-point iteration (see GOESNav._satvec()).
1376
+ """
1377
+ xmanom = p.xmmc * (p.tdife + samtim * 60.0)
1378
+ ecanm1 = xmanom
1379
+ ecanom = ecanm1
1380
+ for _ in range(20):
1381
+ ecanom = xmanom + p.oeccen * math.sin(ecanm1)
1382
+ if abs(ecanom - ecanm1) < p.epsiln:
1383
+ break
1384
+ ecanm1 = ecanom
1385
+ xomega = math.cos(ecanom) - p.oeccen
1386
+ yomega = p.srome2 * math.sin(ecanom)
1387
+ return (
1388
+ xomega * p.px + yomega * p.qx,
1389
+ xomega * p.py + yomega * p.qy,
1390
+ xomega * p.pz + yomega * p.qz,
1391
+ )
1392
+
1393
+
1394
+ @_njit
1395
+ def _scan_line_state(parlin, p):
1396
+ """Return everything that depends only on the scan-line group ``parlin``.
1397
+
1398
+ That is the sample time, the satellite position, the attitude rotation
1399
+ angle and the cos/sin of the earth-rotation angle.
1400
+ """
1401
+ samtim = p.tmpscl * parlin + p.pictim
1402
+ sat = _kepler_position(samtim, p)
1403
+ xcor = p.b11 * sat[0] + p.b12 * sat[1] + p.b13 * sat[2]
1404
+ ycor = p.b21 * sat[0] + p.b22 * sat[1] + p.b23 * sat[2]
1405
+ rot = math.atan2(ycor, xcor) + math.pi
1406
+ angle = p.emega * samtim + p.xref
1407
+ return samtim, sat, rot, math.cos(angle), math.sin(angle)
1408
+
1409
+
1410
+ @_njit
1411
+ def _line_of_sight(ylin, yele, p):
1412
+ """Return the line-of-sight vector (elo, emo, eno) for the scan angles ``ylin`` / ``yele``."""
1413
+ coslin, sinlin = math.cos(ylin), math.sin(ylin)
1414
+ sinele, cosele = math.sin(yele), math.cos(yele)
1415
+
1416
+ eli = p.rotm11 * coslin - p.rotm13 * sinlin
1417
+ emi = p.rotm21 * coslin - p.rotm23 * sinlin
1418
+ eni = p.rotm31 * coslin - p.rotm33 * sinlin
1419
+ temp = eli
1420
+ eli = cosele * eli + sinele * emi
1421
+ emi = -sinele * temp + cosele * emi
1422
+
1423
+ return (
1424
+ p.b11 * eli + p.b21 * emi + p.b31 * eni,
1425
+ p.b12 * eli + p.b22 * emi + p.b32 * eni,
1426
+ p.b13 * eli + p.b23 * emi + p.b33 * eni,
1427
+ )
1428
+
1429
+
1430
+ @_njit
1431
+ def _intersect_earth(sat, los, p):
1432
+ """Intersect a line of sight with the earth ellipsoid.
1433
+
1434
+ Returns ``(hit, point)``; ``hit`` is False (and ``point`` meaningless)
1435
+ where the line of sight misses the earth.
1436
+ """
1437
+ satx, saty, satz = sat
1438
+ elo, emo, eno = los
1439
+ onemsq = 1.0 - p.bsq_over_asq
1440
+ aq = p.bsq_over_asq + onemsq * eno * eno
1441
+ bq = 2.0 * ((elo * satx + emo * saty) * p.bsq_over_asq + eno * satz)
1442
+ cq = (satx * satx + saty * saty) * p.bsq_over_asq + satz * satz - p.bsq
1443
+ rad = bq * bq - 4.0 * aq * cq
1444
+ if rad < 1.0:
1445
+ return False, (0.0, 0.0, 0.0)
1446
+ s = -(bq + math.sqrt(rad)) / (2.0 * aq)
1447
+ return True, (satx + elo * s, saty + emo * s, satz + eno * s)
1448
+
1449
+
1450
+ @_njit
1451
+ def _geodetic_latlon(point, ct, st, p):
1452
+ """Rotate an earth-surface point into the earth-fixed frame and return (lat, lon), East positive."""
1453
+ x, y, z = point
1454
+ x1 = ct * x + st * y
1455
+ y1 = -st * x + ct * y
1456
+ if x1 == 0.0 and y1 == 0.0:
1457
+ return np.nan, np.nan
1458
+ a = math.atan(z / math.sqrt(x1 * x1 + y1 * y1))
1459
+ lat = math.atan2(p.asq * math.sin(a), p.bsq * math.cos(a)) / p.rdpdg
1460
+ lon = math.atan2(y1, x1) / p.rdpdg
1461
+ return lat, lon
1462
+
1463
+
1464
+ @_njit
1465
+ def _to_latlon_kernel(xlin, xele, p):
1466
+ """Convert flattened line/element image coordinates to (lat, lon) in degrees.
1467
+
1468
+ Longitude is East positive.
1469
+
1470
+ The satellite position and the quantities derived only from it
1471
+ (earth-rotation angle, attitude rotation) depend on the scan-line
1472
+ group (`parlin`) alone, so they are recomputed only when `parlin`
1473
+ changes from one pixel to the next. For a (line, element) grid
1474
+ flattened in C order -- lines varying slowest -- that is once per
1475
+ line group instead of once per pixel; any other ordering is still
1476
+ correct, just without the saving.
1477
+ """
1478
+ n = xlin.shape[0]
1479
+ lat = np.empty(n, dtype=np.float64)
1480
+ lon = np.empty(n, dtype=np.float64)
1481
+
1482
+ have_line = False
1483
+ last_parlin = 0.0
1484
+ samtim = rot = ct = st = 0.0
1485
+ sat = (0.0, 0.0, 0.0)
1486
+
1487
+ for i in range(n):
1488
+ parlin = (np.rint(xlin[i]) - 1.0) // p.numsen + 1.0
1489
+ if (not have_line) or parlin != last_parlin:
1490
+ have_line = True
1491
+ last_parlin = parlin
1492
+ samtim, sat, rot, ct, st = _scan_line_state(parlin, p)
1493
+
1494
+ ylin = (xlin[i] - p.piclin) * p.radlin
1495
+ yele = (xele[i] - p.picele + p.gamma + p.gamdot * samtim) * p.radele - rot
1496
+ hit, point = _intersect_earth(sat, _line_of_sight(ylin, yele, p), p)
1497
+ if hit:
1498
+ lat[i], lon[i] = _geodetic_latlon(point, ct, st, p)
1499
+ else:
1500
+ lat[i] = np.nan
1501
+ lon[i] = np.nan
1502
+ return lat, lon
1503
+
1504
+
1505
+
1506
+ class GOESNav(AreaNav):
1507
+ """Navigation for pre-GVAR SMS/GOES-1..7 VISSR/VAS AREA files (nav type "GOES").
1508
+
1509
+ Port of edu.wisc.ssec.mcidas.GOESnav (itself a port of the McIDAS-X
1510
+ nvxgoes codicil), with the per-pixel earth location compiled by numba
1511
+ when it is installed. The image-coordinate setup is the usual AreaNav
1512
+ one: call :meth:`setImageStart`, :meth:`setRes`, :meth:`setStart` and
1513
+ :meth:`setMag` (``AreaFile.navigation`` does this for you).
1514
+
1515
+ ``toLatLon``/``toLinEle`` take and return ``[[elements], [lines]]`` /
1516
+ ``[[lats], [lons]]`` lists like the other navigation classes;
1517
+ :meth:`to_latlon` and :meth:`to_lin_ele` are the array versions.
1518
+ """
1519
+
1520
+ isEastPositive = True
1521
+
1522
+ def __init__(self, navblock=None, auxblock=None, **kwargs):
1523
+ """Set up the navigation from the nav block words.
1524
+
1525
+ Requires a nav block with real, populated orbital elements.
1526
+
1527
+ Args:
1528
+ navblock: Raw nav-block words as signed 32-bit ints (0-based;
1529
+ ``navblock[0]`` is the 4 ASCII bytes ``GOES``).
1530
+ auxblock: Unused, kept for the AreaNav interface.
1531
+ **kwargs: ``byte_order`` ('>' or '<') and ``int_format`` as
1532
+ passed by :class:`AreaNav`; the byte order is needed
1533
+ because the ``GOES`` magic word is 4 ASCII bytes
1534
+ reinterpreted as an int32 in the file's byte order.
1535
+ """
1536
+ iarr = np.asarray(navblock, dtype=np.int64)
1537
+ _check_magic(iarr, self.byte_order)
1538
+ _validate_nav_words(iarr)
1539
+
1540
+ self.navday = int(iarr[1]) % 100000
1541
+ self._set_constants()
1542
+ self._set_orbit(iarr)
1543
+ self._set_scan_geometry(iarr)
1544
+ self._set_attitude(iarr)
1545
+ self._set_spin_axis(iarr)
1546
+ self._set_timing(iarr)
1547
+ self._satvec_init()
1548
+
1549
+ def _set_constants(self):
1550
+ """Set the earth model and earth-rotation constants."""
1551
+ self.emega = 0.26251617
1552
+ self.ab = 40546851.22
1553
+ self.asq = 40683833.48
1554
+ self.bsq = 40410330.18
1555
+ self.r = 6371.221
1556
+ self.rdpdg = 1.745329252e-02
1557
+ self.bsq_over_asq = self.bsq / self.asq
1558
+ self.rsq = self.r ** 2
1559
+
1560
+ def _set_orbit(self, iarr):
1561
+ """Set the Kepler orbital elements and the orbit epoch from the nav block."""
1562
+ ietimy = _icon1(int(iarr[4]))
1563
+ ietimh = 100 * (int(iarr[5]) // 100) + round(0.6 * (int(iarr[5]) % 100))
1564
+ self.semima = iarr[6] / 100.0
1565
+ self.oeccen = iarr[7] / 1000000.0
1566
+ self.orbinc = iarr[8] / 1000.0
1567
+ xmeana = iarr[9] / 1000.0
1568
+ self.perhel = iarr[10] / 1000.0
1569
+ self.asnode = iarr[11] / 1000.0
1570
+ self.ietimy, self.ietimh = _epoch(ietimy, ietimh, _anomaly_hours(self.semima, self.oeccen, xmeana))
1571
+
1572
+ def _set_scan_geometry(self, iarr):
1573
+ """Set the spin-scan geometry: picture center, spin rate and angles per line/element."""
1574
+ piclin = float(iarr[14])
1575
+ if iarr[14] >= 1000000:
1576
+ piclin = piclin / 10000.0
1577
+ self.piclin = piclin
1578
+
1579
+ spinra = iarr[15] / 1000.0
1580
+ if spinra < 300.0:
1581
+ spinra = 60000.0 / spinra
1582
+ self.tmpscl = spinra / 3600000.0
1583
+
1584
+ deglin = utils.mcPI2F(int(iarr[16]))
1585
+ lintot = int(iarr[17])
1586
+ degele = utils.mcPI2F(int(iarr[18]))
1587
+ ieltot = int(iarr[19])
1588
+ self.numsen = max((lintot // 100000) % 100, 1)
1589
+ totlin = self.numsen * (lintot % 100000)
1590
+ self.radlin = self.rdpdg * deglin / (totlin - 1.0)
1591
+ self.radele = self.rdpdg * degele / (ieltot - 1.0)
1592
+ self.picele = (1.0 + ieltot) / 2.0
1593
+
1594
+ def _set_attitude(self, iarr):
1595
+ """Set the attitude rotation matrix from pitch, yaw, roll and skew."""
1596
+ cpitch = self.rdpdg * utils.mcPI2F(int(iarr[20]))
1597
+ cyaw = self.rdpdg * utils.mcPI2F(int(iarr[21]))
1598
+ croll = self.rdpdg * utils.mcPI2F(int(iarr[22]))
1599
+ skew = 0.0 if utils.is_mcmissing(iarr[28]) else iarr[28] / 100000.0
1600
+
1601
+ pskew = np.arctan2(skew, self.radlin / self.radele)
1602
+ stp, ctp = np.sin(cpitch), np.cos(cpitch)
1603
+ sty, cty = np.sin(cyaw - pskew), np.cos(cyaw - pskew)
1604
+ str_, ctr = np.sin(croll), np.cos(croll)
1605
+ self.rotm11 = ctr * ctp
1606
+ self.rotm13 = sty * str_ * ctp + cty * stp
1607
+ self.rotm21 = -str_
1608
+ self.rotm23 = sty * ctr
1609
+ self.rotm31 = -ctr * stp
1610
+ self.rotm33 = cty * ctp - sty * str_ * stp
1611
+ self.rfact = self.rotm31 ** 2 + self.rotm33 ** 2
1612
+ self.roasin = np.arctan2(self.rotm31, self.rotm33)
1613
+
1614
+ def _set_spin_axis(self, iarr):
1615
+ """Set the spin-axis rotation matrix from the declination and right ascension."""
1616
+ dec = utils.mcPI2F(int(iarr[12])) * self.rdpdg
1617
+ sindec, cosdec = np.sin(dec), np.cos(dec)
1618
+ ras = utils.mcPI2F(int(iarr[13])) * self.rdpdg
1619
+ sinras, cosras = np.sin(ras), np.cos(ras)
1620
+ self.b11 = -sinras
1621
+ self.b12 = cosras
1622
+ self.b13 = 0.0
1623
+ self.b21 = -sindec * cosras
1624
+ self.b22 = -sindec * sinras
1625
+ self.b23 = cosdec
1626
+ self.b31 = cosdec * cosras
1627
+ self.b32 = cosdec * sinras
1628
+ self.b33 = sindec
1629
+
1630
+ def _set_timing(self, iarr):
1631
+ """Set the earth-rotation reference, the picture time and the scan line times."""
1632
+ # navday has a two digit year; as in the year counted from 1900 that timdif takes, 00 to 29 mean 2000 to 2029
1633
+ navday = self.navday + 100000 if self.navday // 1000 < 30 else self.navday
1634
+ raha = utils.timdif(74001, 0, navday, 0) * 1.00273791 / 4.0 + 100.26467
1635
+ self.xref = (raha % 360.0) * self.rdpdg
1636
+ self.pictim = utils.mcPI2F(int(iarr[2]))
1637
+ self.gamma = float(iarr[38]) / 100.0
1638
+ self.gamdot = float(iarr[39]) / 100.0
1639
+ self._set_scan_times(iarr)
1640
+
1641
+ def _set_scan_times(self, iarr):
1642
+ """Set the first/last scan line numbers and times."""
1643
+ if iarr[30] > 0 and _has_beta_scan_times(int(iarr[1]) // 100000):
1644
+ self.scan1 = float(iarr[30])
1645
+ self.time1 = utils.mcPI2F(int(iarr[31]))
1646
+ self.scan2 = float(iarr[34])
1647
+ self.time2 = utils.mcPI2F(int(iarr[35]))
1648
+ else:
1649
+ self.scan1 = 1.0
1650
+ self.time1 = self.pictim
1651
+ self.scan2 = float(int(iarr[17]) % 100000)
1652
+ self.time2 = self.time1 + self.scan2 * self.tmpscl
1653
+
1654
+ def _satvec_init(self):
1655
+ """Precompute the orbital-plane basis vectors used by _satvec().
1656
+
1657
+ Only called for the normal Kepler-propagated constructor.
1658
+ """
1659
+ rdpdg = np.pi / 180.0
1660
+ re = 6378.388
1661
+ gracon = 0.07436574
1662
+
1663
+ o = rdpdg * self.orbinc
1664
+ p = rdpdg * self.perhel
1665
+ a = rdpdg * self.asnode
1666
+ so, co = np.sin(o), np.cos(o)
1667
+ sp, cp = np.sin(p) * self.semima, np.cos(p) * self.semima
1668
+ sa, ca = np.sin(a), np.cos(a)
1669
+ self._px = cp * ca - sp * sa * co
1670
+ self._py = cp * sa + sp * ca * co
1671
+ self._pz = sp * so
1672
+ self._qx = -sp * ca - cp * sa * co
1673
+ self._qy = -sp * sa + cp * ca * co
1674
+ self._qz = cp * so
1675
+ self._srome2 = np.sqrt(1.0 - self.oeccen) * np.sqrt(1.0 + self.oeccen)
1676
+ self._xmmc = gracon * re * np.sqrt(re / self.semima) / self.semima
1677
+
1678
+ iey = (self.ietimy // 1000) % 100
1679
+ ied = self.ietimy % 1000
1680
+ iefac = (iey - 1) // 4 + 1
1681
+ de = 365 * (iey - 1) + iefac + ied - 1
1682
+ te = 1440.0 * de + 60.0 * utils.mcPI2F(self.ietimh)
1683
+
1684
+ inavy = (self.navday // 1000) % 100
1685
+ inavd = self.navday % 1000
1686
+ infac = (inavy - 1) // 4 + 1
1687
+ dnav = 365 * (inavy - 1) + infac + inavd - 1
1688
+
1689
+ self._tdife = dnav * 1440.0 - te
1690
+ self._epsiln = 1.0e-8
1691
+
1692
+ def _satvec(self, samtim):
1693
+ """Return the satellite position (x, y, z) at time ``samtim``.
1694
+
1695
+ ``samtim`` may be a numpy array; the result is ECI-ish arrays
1696
+ (Earth-center-to-satellite, in the pre-earth-rotation frame that
1697
+ to_latlon()/get_subpoint() then rotate by (emega*samtim+xref)).
1698
+
1699
+ Kepler's-equation solve from real orbital elements (fixed-point
1700
+ iteration, matching the Java's plain loop).
1701
+ """
1702
+ samtim = np.asarray(samtim, dtype=np.float64)
1703
+
1704
+ timsam = samtim * 60.0
1705
+ diftim = self._tdife + timsam
1706
+ xmanom = self._xmmc * diftim
1707
+ ecanm1 = xmanom.copy()
1708
+ ecanom = ecanm1
1709
+ for _ in range(20):
1710
+ ecanom = xmanom + self.oeccen * np.sin(ecanm1)
1711
+ if np.all(np.abs(ecanom - ecanm1) < self._epsiln):
1712
+ ecanm1 = ecanom
1713
+ break
1714
+ ecanm1 = ecanom
1715
+ xomega = np.cos(ecanom) - self.oeccen
1716
+ yomega = self._srome2 * np.sin(ecanom)
1717
+ x = xomega * self._px + yomega * self._qx
1718
+ y = xomega * self._py + yomega * self._qy
1719
+ z = xomega * self._pz + yomega * self._qz
1720
+ return x, y, z
1721
+
1722
+ def _nxyzll(self, x, y, z):
1723
+ """Convert earth-fixed x, y, z to geodetic (lat, lon) in degrees, with lon positive West."""
1724
+ with np.errstate(invalid="ignore", divide="ignore"):
1725
+ a = np.arctan(z / np.sqrt(x * x + y * y))
1726
+ lat = np.arctan2(self.asq * np.sin(a), self.bsq * np.cos(a)) / self.rdpdg
1727
+ lon = -np.arctan2(y, x) / self.rdpdg
1728
+ bad = (x == 0.0) & (y == 0.0)
1729
+ lat = np.where(bad, np.nan, lat)
1730
+ lon = np.where(bad, np.nan, lon)
1731
+ return lat, lon
1732
+
1733
+ def _area_to_image(self, line, elem):
1734
+ """AREAnav.areaCoordToImageCoord, unflipped case."""
1735
+ img_line = self.startImageLine + (self.resLine * (line - self.startLine)) / self.magLine
1736
+ img_elem = self.startImageElement + (self.resElement * (elem - self.startElement)) / self.magElement
1737
+ return img_line, img_elem
1738
+
1739
+ def _image_to_area(self, line, elem):
1740
+ """AREAnav.imageCoordToAreaCoord, unflipped case."""
1741
+ area_line = self.startLine + (self.magLine * (line - self.startImageLine)) / self.resLine
1742
+ area_elem = self.startElement + (self.magElement * (elem - self.startImageElement)) / self.resElement
1743
+ return area_line, area_elem
1744
+
1745
+ def _kernel_params(self):
1746
+ """Bundle the scalar constants _to_latlon_kernel() needs."""
1747
+ return _KernelParams(
1748
+ numsen=float(self.numsen), tmpscl=float(self.tmpscl),
1749
+ pictim=float(self.pictim), piclin=float(self.piclin),
1750
+ radlin=float(self.radlin), radele=float(self.radele),
1751
+ picele=float(self.picele), gamma=float(self.gamma),
1752
+ gamdot=float(self.gamdot),
1753
+ b11=float(self.b11), b12=float(self.b12), b13=float(self.b13),
1754
+ b21=float(self.b21), b22=float(self.b22), b23=float(self.b23),
1755
+ b31=float(self.b31), b32=float(self.b32), b33=float(self.b33),
1756
+ rotm11=float(self.rotm11), rotm13=float(self.rotm13),
1757
+ rotm21=float(self.rotm21), rotm23=float(self.rotm23),
1758
+ rotm31=float(self.rotm31), rotm33=float(self.rotm33),
1759
+ bsq_over_asq=float(self.bsq_over_asq), asq=float(self.asq),
1760
+ bsq=float(self.bsq), emega=float(self.emega),
1761
+ xref=float(self.xref), rdpdg=float(self.rdpdg),
1762
+ tdife=float(self._tdife), xmmc=float(self._xmmc),
1763
+ oeccen=float(self.oeccen), srome2=float(self._srome2),
1764
+ epsiln=float(self._epsiln),
1765
+ px=float(self._px), py=float(self._py), pz=float(self._pz),
1766
+ qx=float(self._qx), qy=float(self._qy), qz=float(self._qz),
1767
+ )
1768
+
1769
+ def to_latlon(self, line, elem):
1770
+ """Convert line/element (AREA/file coordinates) to (lat, lon) in degrees.
1771
+
1772
+ East positive / North positive. NaN where the line of sight misses
1773
+ the earth ellipsoid. Accepts any broadcastable pair of arrays and
1774
+ returns arrays of the broadcast shape.
1775
+ """
1776
+ line, elem = np.broadcast_arrays(
1777
+ np.asarray(line, dtype=np.float64),
1778
+ np.asarray(elem, dtype=np.float64),
1779
+ )
1780
+ shape = line.shape
1781
+ xlin, xele = self._area_to_image(line, elem)
1782
+ lat, lon = _to_latlon_kernel(
1783
+ np.ascontiguousarray(xlin).ravel(),
1784
+ np.ascontiguousarray(xele).ravel(),
1785
+ self._kernel_params(),
1786
+ )
1787
+ return lat.reshape(shape), lon.reshape(shape)
1788
+
1789
+ def get_subpoint(self):
1790
+ """Return the satellite nadir (lat, lon) in degrees, east positive.
1791
+
1792
+ Evaluated at time `time1` (nominal image start time, or first-beta
1793
+ scan time for VAS-era files). Used by get_nadir_sampling() to center
1794
+ the uniform-sampling grid, and a cheap cross-check of the orbital
1795
+ solution.
1796
+ """
1797
+ samtim = self.time1
1798
+ satx, saty, satz = self._satvec(np.asarray(samtim))
1799
+ ct = np.cos(self.emega * samtim + self.xref)
1800
+ st = np.sin(self.emega * samtim + self.xref)
1801
+ x1 = ct * satx + st * saty
1802
+ y1 = -st * satx + ct * saty
1803
+ lat, lon = self._nxyzll(x1, y1, satz)
1804
+ return float(lat), float(-lon) # East positive
1805
+
1806
+ def get_nadir_sampling(self):
1807
+ """Return the sub-satellite point, altitude and nadir pixel spacing.
1808
+
1809
+ The spacing is that of the AREA grid this object was built for.
1810
+
1811
+ Returns a dict with ``sub_lon`` / ``sub_lat`` (degrees, east/north
1812
+ positive), ``altitude`` (metres above the equatorial radius, at
1813
+ the nominal image time) and ``line_step`` / ``elem_step`` (metres
1814
+ between neighbouring AREA lines / elements at nadir). The steps
1815
+ come from the scan angle per full-resolution line/element
1816
+ (``radlin`` / ``radele``) scaled by the AREA directory's
1817
+ line/element resolution factors.
1818
+ """
1819
+ sub_lat, sub_lon = self.get_subpoint()
1820
+ satx, saty, satz = self._satvec(np.asarray(self.time1))
1821
+ altitude_m = (float(np.sqrt(satx ** 2 + saty ** 2 + satz ** 2)) - _EQUATORIAL_RADIUS_KM) * 1000.0
1822
+ return {
1823
+ "sub_lon": sub_lon,
1824
+ "sub_lat": sub_lat,
1825
+ "altitude": altitude_m,
1826
+ "line_step": altitude_m * self.radlin * self.resLine / self.magLine,
1827
+ "elem_step": altitude_m * self.radele * self.resElement / self.magElement,
1828
+ }
1829
+
1830
+ def getSubpoint(self):
1831
+ """Return the satellite nadir ``(lat, lon)`` in degrees (AreaNav naming)."""
1832
+ return self.get_subpoint()
1833
+
1834
+ def toLatLon(self, linele=None):
1835
+ """Convert ``[[elements], [lines]]`` (file coordinates; elements first) to ``[[lats], [lons]]``."""
1836
+ lat, lon = self.to_latlon(np.asarray(linele[self.indexLine], dtype=float),
1837
+ np.asarray(linele[self.indexEle], dtype=float))
1838
+ return [lat, lon]
1839
+
1840
+ def _nllxyz(self, lat, lon):
1841
+ """Lat/lon in degrees (north and west positive) to earth-centred x, y, z in km (Daly, 1978)."""
1842
+ ylat1 = np.arctan2(self.bsq * np.sin(self.rdpdg * lat), self.asq * np.cos(self.rdpdg * lat))
1843
+ ylon = -self.rdpdg * lon
1844
+ snlt, cslt = np.sin(ylat1), np.cos(ylat1)
1845
+ tnlt = (snlt / cslt) ** 2
1846
+ r = self.ab * np.sqrt((1.0 + tnlt) / (self.bsq + self.asq * tnlt))
1847
+ return r * cslt * np.cos(ylon), r * cslt * np.sin(ylon), r * snlt
1848
+
1849
+ def to_lin_ele(self, lat, lon):
1850
+ """Convert lat/lon (degrees, east and north positive) to ``(line, element)`` file coordinates.
1851
+
1852
+ The line is always returned; the element is NaN where the point
1853
+ is not visible from the satellite, as in the Java original.
1854
+ """
1855
+ lat, lon = np.broadcast_arrays(np.asarray(lat, dtype=np.float64), np.asarray(lon, dtype=np.float64))
1856
+ valid = np.abs(lat) <= 90.0
1857
+ x1, y1, z = self._nllxyz(np.where(valid, lat, 0.0), -np.where(valid, lon, 0.0))
1858
+
1859
+ samtim = self.time1
1860
+ oldlin = None
1861
+ for i in range(2):
1862
+ xsat, ysat, zsat = self._satvec(samtim)
1863
+ xht = np.sqrt(xsat ** 2 + ysat ** 2 + zsat ** 2)
1864
+ ct, st = np.cos(self.emega * samtim + self.xref), np.sin(self.emega * samtim + self.xref)
1865
+ x = ct * x1 - st * y1
1866
+ y = st * x1 + ct * y1
1867
+ vcste1, vcste2, vcste3 = x - xsat, y - ysat, z - zsat
1868
+ vcses3 = self.b31 * vcste1 + self.b32 * vcste2 + self.b33 * vcste3
1869
+ znorm = np.sqrt(vcste1 ** 2 + vcste2 ** 2 + vcste3 ** 2)
1870
+ x3 = vcses3 / znorm
1871
+ umv = np.arctan2(x3, np.sqrt(self.rfact - x3 ** 2)) - self.roasin
1872
+ xlin = self.piclin - umv / self.radlin
1873
+ if i == 0:
1874
+ samtim = self.time2
1875
+ oldlin = xlin
1876
+
1877
+ scnnum = ((oldlin + xlin) / 2.0 - 1.0) / self.numsen
1878
+ scnfrc = (scnnum - self.scan1) / (self.scan2 - self.scan1)
1879
+ xlin = oldlin + scnfrc * (xlin - oldlin)
1880
+ samtim = self.time1 + self.tmpscl * (scnnum - self.scan1)
1881
+ xsat, ysat, zsat = self._satvec(samtim)
1882
+ cosa = x * xsat + y * ysat + z * zsat
1883
+ ctst = 0.0001 * self.r * xht + self.rsq
1884
+
1885
+ xsats1 = self.b11 * xsat + self.b12 * ysat + self.b13 * zsat
1886
+ ysats2 = self.b21 * xsat + self.b22 * ysat + self.b23 * zsat
1887
+ ct, st = np.cos(self.emega * samtim + self.xref), np.sin(self.emega * samtim + self.xref)
1888
+ x = ct * x1 - st * y1
1889
+ y = st * x1 + ct * y1
1890
+ vcste1, vcste2, vcste3 = x - xsat, y - ysat, z - zsat
1891
+ vcses1 = self.b11 * vcste1 + self.b12 * vcste2 + self.b13 * vcste3
1892
+ vcses2 = self.b21 * vcste1 + self.b22 * vcste2 + self.b23 * vcste3
1893
+ vcses3 = self.b31 * vcste1 + self.b32 * vcste2 + self.b33 * vcste3
1894
+ xnorm = np.sqrt(vcste1 ** 2 + vcste2 ** 2 + vcste3 ** 2 - vcses3 ** 2)
1895
+ ynorm = np.sqrt(xsats1 ** 2 + ysats2 ** 2)
1896
+ znorm = np.sqrt(vcste1 ** 2 + vcste2 ** 2 + vcste3 ** 2)
1897
+ x3 = vcses3 / znorm
1898
+ umv = np.arctan2(x3, np.sqrt(self.rfact - x3 ** 2)) - self.roasin
1899
+ u = self.rotm11 * np.cos(umv) + self.rotm13 * np.sin(umv)
1900
+ v = self.rotm21 * np.cos(umv) + self.rotm23 * np.sin(umv)
1901
+ with np.errstate(invalid="ignore", divide="ignore"):
1902
+ xele = self.picele + np.arcsin((xsats1 * vcses2 - ysats2 * vcses1) / (xnorm * ynorm)) / self.radele
1903
+ xele = xele + np.arctan2(v, u) / self.radele - self.gamma - self.gamdot * samtim
1904
+
1905
+ xlin = np.where(valid, xlin, np.nan)
1906
+ xele = np.where(valid & (cosa >= ctst), xele, np.nan)
1907
+ return self._image_to_area(xlin, xele)
1908
+
1909
+ def toLinEle(self, latlon=None):
1910
+ """Convert ``[[lats], [lons]]`` to ``[[elements], [lines]]`` file coordinates."""
1911
+ line, elem = self.to_lin_ele(np.asarray(latlon[self.indexLat], dtype=float),
1912
+ np.asarray(latlon[self.indexLon], dtype=float))
1913
+ out = [None, None]
1914
+ out[self.indexLine], out[self.indexEle] = line, elem
1915
+ return out
1916
+
1917
+
1918
+ class RECTNav(AreaNav):
1919
+ """Navigation for rectangular (equirectangular, "plate carree") latitude/longitude AREA files, nav type RECT.
1920
+
1921
+ Port of ``edu.wisc.ssec.mcidas.RECTnav``. Image line and element are linear in latitude and longitude.
1922
+ """
1923
+
1924
+ labels = {1: 'test',
1925
+ 2: 'a particular image row number',
1926
+ 3: 'latitude corresponding to word 2, degrees x10000',
1927
+ 4: 'a particular image column number',
1928
+ 5: 'longitude corresponding to word 4, degrees x10000',
1929
+ 6: 'latitude degrees/image line, degrees x10000',
1930
+ 7: 'longitude degrees/image line, degrees x10000',
1931
+ 8: 'radius of the planet, meters',
1932
+ 9: 'eccentricity of the planet, x1000000',
1933
+ 10: 'coordinate type, >= 0 planetodetic, < 0 planetocentric',
1934
+ 11: 'longitude convention, >= 0 west positive, < 0 west negative'
1935
+ }
1936
+
1937
+ def __init__(self, navblock=None, auxblock=None, **kwargs):
1938
+ inavblock = navblock
1939
+ self.itype = 2
1940
+ self.iwest = 1 if inavblock[10] >= 0 else -1
1941
+
1942
+ self.xrow = inavblock[1]
1943
+ self.xcol = inavblock[3]
1944
+ # words 12 to 15 are the powers of ten the values above are scaled by; 0 means the default, 4
1945
+ self.zslat = inavblock[2] / 10. ** (inavblock[11] or 4)
1946
+ self.zslon = inavblock[4] / 10. ** (inavblock[12] or 4)
1947
+ self.zdlat = float(inavblock[5]) / 10. ** (inavblock[13] or 4)
1948
+ self.zdlon = float(inavblock[6]) / 10. ** (inavblock[14] or 4)
1949
+ if self.xcol == 1:
1950
+ self.zslon = self.zslon - 180.0 * self.iwest
1951
+
1952
+ def to_latlon(self, line, elem, lon_circular=True):
1953
+ """Convert line/element (file coordinates, any shape, broadcast together) to ``(lat, lon)`` degrees.
1954
+
1955
+ NaN where the latitude is outside +-90, or the longitude is more than 180 degrees from the reference
1956
+ longitude. With ``lon_circular`` longitudes are wrapped into -180 to 180.
1957
+ """
1958
+ line, elem = np.broadcast_arrays(np.asarray(line, dtype=float), np.asarray(elem, dtype=float))
1959
+ image_line, image_elem = self._area_to_image(line, elem)
1960
+ xldif = self.xrow - image_line
1961
+ if self.xcol == 1:
1962
+ xlon = self.zslon + 180 * self.iwest - self.iwest * (image_elem - self.xcol) * self.zdlon
1963
+ else:
1964
+ xlon = self.zslon + self.iwest * (self.xcol - image_elem) * self.zdlon
1965
+ xlat = self.zslat + xldif * self.zdlat
1966
+ with np.errstate(invalid="ignore"):
1967
+ xlat = np.where(np.abs(xlat) > 90, np.nan, xlat)
1968
+ xlon = np.where((xlon > self.zslon + 180) | (xlon < self.zslon - 180), np.nan, xlon)
1969
+ if lon_circular:
1970
+ xlon = np.where(xlon < -180, xlon + 360, xlon)
1971
+ xlon = np.where(xlon > 180, xlon - 360, xlon)
1972
+ invalid = np.isnan(xlat) | np.isnan(xlon)
1973
+ lat = np.where(invalid, np.nan, xlat)
1974
+ lon = np.where(invalid, np.nan, -xlon if self.iwest == 1 else xlon)
1975
+ return lat, lon
1976
+
1977
+ def to_lin_ele(self, lat, lon):
1978
+ """Convert lat/lon degrees (any shape, broadcast together) to ``(line, element)`` in file coordinates."""
1979
+ lat, lon = np.broadcast_arrays(np.asarray(lat, dtype=float), np.asarray(lon, dtype=float))
1980
+ xlon = -lon if self.iwest == 1 else lon
1981
+ with np.errstate(invalid="ignore"):
1982
+ xlon = np.where(xlon > self.zslon + 180, xlon - 360, np.where(xlon < self.zslon - 180, xlon + 360, xlon))
1983
+ xlin = self.xrow - (lat - self.zslat) / self.zdlat
1984
+ if self.xcol == 1:
1985
+ xele = self.xcol - (xlon - self.zslon - 180 * self.iwest) / (self.zdlon * self.iwest)
1986
+ else:
1987
+ xele = self.xcol - (xlon - self.zslon) / (self.zdlon * self.iwest)
1988
+ return self._image_to_area(xlin, xele)
1989
+
1990
+ def toLatLon(self, linele=None, lon_circular=True):
1991
+ """Convert ``[[elements], [lines]]`` (file coordinates; elements first) to ``[[lats], [lons]]``."""
1992
+ lat, lon = self.to_latlon(linele[self.indexLine], linele[self.indexEle], lon_circular)
1993
+ out = [None, None]
1994
+ out[self.indexLat], out[self.indexLon] = lat, lon
1995
+ return out
1996
+
1997
+ def toLinEle(self, latlon=None):
1998
+ """Convert ``[[lats], [lons]]`` to ``[[elements], [lines]]`` in file coordinates."""
1999
+ line, elem = self.to_lin_ele(latlon[self.indexLat], latlon[self.indexLon])
2000
+ out = [None, None]
2001
+ out[self.indexLine], out[self.indexEle] = line, elem
2002
+ return out
2003
+
2004
+ def __str__(self):
2005
+ s = ''
2006
+ s += 'itype %i \n' % self.itype
2007
+ s += 'xrow %i \n' % self.xrow
2008
+ s += 'xcol %i \n' % self.xcol
2009
+ s += 'iwest %i \n' % self.iwest
2010
+ s += 'zslat %.6f \n' % self.zslat
2011
+ s += 'zslon %.6f \n' % self.zslon
2012
+ s += 'zdlat %.6f \n' % self.zdlat
2013
+ s += 'zdlon %.6f \n' % self.zdlon
2014
+ return s
2015
+
2016
+
2017
+ _CDR = math.pi / 180.0
2018
+ _CRD = 180.0 / math.pi
2019
+
2020
+
2021
+ _F32 = np.float32
2022
+
2023
+
2024
+ def _unit(v):
2025
+ """McIDAS mg1200: the vectors along the first axis scaled to length 1 (the zero vector stays zero)."""
2026
+ length = np.sqrt((v * v).sum(axis=0))
2027
+ with np.errstate(invalid='ignore', divide='ignore'):
2028
+ return np.where(length == 0.0, 0.0, v / length)
2029
+
2030
+
2031
+ def _cross(a, b):
2032
+ """McIDAS mg1210."""
2033
+ return np.cross(a, b, axis=0)
2034
+
2035
+
2036
+ def _unit_cross(a, b):
2037
+ """McIDAS mg1220."""
2038
+ return _unit(_cross(a, b))
2039
+
2040
+
2041
+ def _angle(a, b):
2042
+ """McIDAS mg1230: the angle between two vectors, 0 for a zero vector."""
2043
+ dot = (a * b).sum(axis=0)
2044
+ squares = (a * a).sum(axis=0) * (b * b).sum(axis=0)
2045
+ with np.errstate(invalid='ignore', divide='ignore'):
2046
+ cosine = dot / np.sqrt(squares)
2047
+ cosine = np.where((cosine > 1.0) & (cosine - 1.0 < 0.000001), 1.0, cosine)
2048
+ return np.where(squares == 0.0, 0.0, np.arccos(cosine))
2049
+
2050
+
2051
+ class GMSXNav(AreaNav):
2052
+ """Navigation of GMS stretched VISSR data (``GMSX``), a numpy port of the ``GMSXnav`` class of VisAD.
2053
+
2054
+ VisAD ported it from McIDAS' nvxgmsx.dlm. The orbit and attitude block is decoded when the object is made, and
2055
+ ``to_latlon`` and ``to_lin_ele`` work on arrays. Like the Java, they use the visible channel's frame (mode 1):
2056
+ the infrared images of GMS are addressed in the same line and element numbers, at a lower resolution.
2057
+ """
2058
+
2059
+ HPAI = math.pi / 2.0
2060
+ DPAI = math.pi * 2.0
2061
+ EA = 6378136.0
2062
+ EF = 1.0 / 298.257
2063
+
2064
+ def __init__(self, navblock=None, auxblock=None, **kwargs):
2065
+ navtype = struct.unpack('{byte_order:s}4s'.format(byte_order=self.byte_order),
2066
+ struct.pack('{byte_order:s}{format_str:s}'.format(byte_order=self.byte_order,
2067
+ format_str=self.int_format),
2068
+ navblock[self.STTYPE]))[0]
2069
+ if navtype.decode(errors='replace') != self.GMSX:
2070
+ raise Exception(f'Invalid navigation type {navtype}')
2071
+
2072
+ # the data words are the ones between the text words at the start of each 128 word piece of the block:
2073
+ # words 1 to 126, then 127 words from each of 128, 256, 384 and 512
2074
+ words = np.asarray(navblock, dtype=np.int64)
2075
+ if words.size < 639:
2076
+ raise ValueError(f'A GMSX navigation block has 640 words, not {words.size}')
2077
+ pieces = [words[1:127]] + [words[start:start + 127] for start in (128, 256, 384, 512)]
2078
+ self.resLin = np.zeros(4, dtype=np.float32)
2079
+ self.resEle = np.zeros(4, dtype=np.float32)
2080
+ self.rlic = np.zeros(4, dtype=np.float32)
2081
+ self.relmfc = np.zeros(4, dtype=np.float32)
2082
+ self.senssu = np.zeros(4, dtype=np.float32)
2083
+ self.rline = np.zeros(4, dtype=np.float32)
2084
+ self.relem = np.zeros(4, dtype=np.float32)
2085
+ self.vmis = np.zeros(3, dtype=np.float32)
2086
+ self.elmis = np.zeros((3, 3), dtype=np.float32)
2087
+ self.orbt1 = np.zeros((35, 8), dtype=np.float64)
2088
+ self.atit = np.zeros((10, 10), dtype=np.float64)
2089
+ # The block is a stream of bytes the producer wrote, not integers. VisAD takes the bytes of each word most
2090
+ # significant first, which is right when the words were read big endian. Written by a little endian machine
2091
+ # the words come out swapped and the values are nonsense, so the other order is the one to use then.
2092
+ for order in ('>', '<'):
2093
+ data = (np.concatenate(pieces) & 0xFFFFFFFF).astype(order + 'u4').tobytes()
2094
+ self.bParms = np.zeros(3200, dtype=np.uint8)
2095
+ self.bParms[:len(data)] = np.frombuffer(data, dtype=np.uint8)
2096
+ self.decOABlock(form=0)
2097
+ if abs(self.subLat) <= 90.0 and abs(self.subLon) <= 360.0 and 0.0 < self.dspin < 1.0e4:
2098
+ break
2099
+ else: # nothing plausible (an empty block, say): keep VisAD's reading
2100
+ data = (np.concatenate(pieces) & 0xFFFFFFFF).astype('>u4').tobytes()
2101
+ self.bParms[:len(data)] = np.frombuffer(data, dtype=np.uint8)
2102
+ self.decOABlock(form=0)
2103
+
2104
+ def sv01000(self, offset, size, power):
2105
+ """Scaled integer R*size.power at ``offset`` of the block: sign and magnitude, big endian, over 10**power."""
2106
+ raw = bytes(self.bParms[offset:offset + size])
2107
+ magnitude = int.from_bytes(raw, 'big') & ((1 << (8 * size - 1)) - 1)
2108
+ value = magnitude / 10.0 ** power
2109
+ return -value if raw[0] & 0x80 else value
2110
+
2111
+ def decOABlock(self, form=0):
2112
+ """Decode the orbit and attitude block (``form`` 0 is the short form, 1 the long one).
2113
+
2114
+ The offsets are those of GMSXnav, which counts the sub-blocks from 0 but starts at ``(i - 1) * stride``.
2115
+ """
2116
+ sv = self.sv01000
2117
+ self.dtims = sv(0, 6, 8)
2118
+ self.dspin = sv(240, 6, 8)
2119
+ self.resLin[:] = [sv(6, 4, 8)] + [sv(10, 4, 8)] * 3
2120
+ self.resEle[:] = [sv(14, 4, 10)] + [sv(18, 4, 10)] * 3
2121
+ self.rlic[:] = [sv(22, 4, 4), sv(26, 4, 4), sv(110, 4, 4), sv(114, 4, 4)]
2122
+ self.relmfc[:] = [sv(30, 4, 4), sv(34, 4, 4), sv(118, 4, 4), sv(122, 4, 4)]
2123
+ self.senssu[:] = [sv(38, 4, 0)] + [sv(42, 4, 0)] * 3
2124
+ self.rline[:] = [sv(46, 4, 0)] + [sv(50, 4, 0)] * 3
2125
+ self.relem[:] = [sv(54, 4, 0)] + [sv(58, 4, 0)] * 3
2126
+ self.vmis[:] = [sv(62, 4, 10), sv(66, 4, 10), sv(70, 4, 10)]
2127
+ # misalignment matrix, column by column
2128
+ for k, (row, column, power) in enumerate([(0, 0, 7), (1, 0, 10), (2, 0, 10), (0, 1, 10), (1, 1, 7),
2129
+ (2, 1, 10), (0, 2, 10), (1, 2, 10), (2, 2, 7)]):
2130
+ self.elmis[row, column] = sv(74 + 4 * k, 4, power)
2131
+ self.subLon = np.float32(sv(198, 6, 6))
2132
+ self.subLat = np.float32(sv(204, 6, 6))
2133
+ for i in range(10):
2134
+ j = (i - 1) * 64 + 256 if form == 1 else (i - 1) * 48 + 256
2135
+ self.atit[0, i] = sv(j, 6, 8)
2136
+ self.atit[2, i] = sv(j + 12, 6, 8)
2137
+ self.atit[3, i] = sv(j + 18, 6, 11)
2138
+ self.atit[4, i] = sv(j + 24, 6, 8)
2139
+ self.atit[5, i] = sv(j + 30, 6, 8)
2140
+ for i in range(8):
2141
+ j = (i - 1) * 256 + 896 if form == 1 else (i - 1) * 200 + 736
2142
+ self.orbt1[0, i] = sv(j, 6, 8)
2143
+ self.orbt1[8, i] = sv(j + 48, 6, 6)
2144
+ self.orbt1[9, i] = sv(j + 54, 6, 6)
2145
+ self.orbt1[10, i] = sv(j + 60, 6, 6)
2146
+ self.orbt1[14, i] = sv(j + 84, 6, 8)
2147
+ self.orbt1[17, i] = sv(j + 102, 6, 8)
2148
+ self.orbt1[18, i] = sv(j + 108, 6, 8)
2149
+ # nutation and precession matrix, column by column
2150
+ for k, (offset, power) in enumerate([(128, 12), (134, 14), (140, 14), (146, 14), (152, 12),
2151
+ (158, 16), (164, 12), (170, 16), (176, 12)]):
2152
+ self.orbt1[19 + k, i] = sv(j + offset, 6, power)
2153
+
2154
+ def _orbit_and_attitude(self, rtim):
2155
+ """Satellite position, spin axis and sun direction at the times ``rtim`` (mg1100 and mg1110).
2156
+
2157
+ Returns ``beta, sat, sp, ss``; NaN where the time is outside the orbit or attitude predictions
2158
+ (VisAD silently keeps the values of the previous call there).
2159
+ """
2160
+ n = rtim.size
2161
+ orbit_times, atit_times = self.orbt1[0], self.atit[0]
2162
+ sat = np.full((3, n), nan)
2163
+ sitagt = np.full(n, nan)
2164
+ sunalp = np.full(n, nan)
2165
+ sundel = np.full(n, nan)
2166
+ npa = np.full((3, 3, n), nan)
2167
+ found = np.zeros(n, dtype=bool)
2168
+ o = self.orbt1
2169
+ for i in range(7):
2170
+ use = ~found & (rtim > orbit_times[i]) & (rtim < orbit_times[i + 1])
2171
+ if not use.any():
2172
+ continue
2173
+ found |= use
2174
+ delt = (rtim[use] - orbit_times[i]) / (orbit_times[i + 1] - orbit_times[i])
2175
+ for axis, row in enumerate((8, 9, 10)):
2176
+ sat[axis, use] = o[row, i] + (o[row, i + 1] - o[row, i]) * delt
2177
+ gst_step = o[14, i + 1] - o[14, i]
2178
+ if gst_step < 0.0:
2179
+ gst_step += 360.0
2180
+ sitagt[use] = (o[14, i] + gst_step * delt) * _CDR
2181
+ sun_step = o[17, i + 1] - o[17, i]
2182
+ if sun_step > 0.0:
2183
+ sun_step -= 360.0
2184
+ sunalp[use] = (o[17, i] + sun_step * delt) * _CDR
2185
+ sundel[use] = (o[18, i] + (o[18, i + 1] - o[18, i]) * delt) * _CDR
2186
+ for k, (row, column) in enumerate([(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2)]):
2187
+ npa[row, column, use] = o[19 + k, i]
2188
+
2189
+ beta = np.full(n, nan)
2190
+ attalp = np.full(n, nan)
2191
+ attdel = np.full(n, nan)
2192
+ found = np.zeros(n, dtype=bool)
2193
+ a = self.atit
2194
+ for i in range(9):
2195
+ use = ~found & (rtim >= atit_times[i]) & (rtim < atit_times[i + 1])
2196
+ if not use.any():
2197
+ continue
2198
+ found |= use
2199
+ delt = (rtim[use] - atit_times[i]) / (atit_times[i + 1] - atit_times[i])
2200
+ attalp[use] = a[2, i] + (a[2, i + 1] - a[2, i]) * delt
2201
+ attdel[use] = a[3, i] + (a[3, i + 1] - a[3, i]) * delt
2202
+ beta_step = a[4, i + 1] - a[4, i]
2203
+ if beta_step > 0.0:
2204
+ beta_step -= 360.0 * _CDR
2205
+ beta[use] = a[4, i] + beta_step * delt
2206
+
2207
+ cos_del = np.cos(attdel)
2208
+ att1 = np.array([np.sin(attdel), cos_del * -np.sin(attalp), cos_del * np.cos(attalp)])
2209
+ att2 = np.einsum('ijn,jn->in', npa, att1)
2210
+ sin_gst, cos_gst = np.sin(sitagt), np.cos(sitagt)
2211
+ att3 = np.array([cos_gst * att2[0] + sin_gst * att2[1], -sin_gst * att2[0] + cos_gst * att2[1], att2[2]])
2212
+ sp = _unit(att3)
2213
+ cos_sundel = np.cos(sundel)
2214
+ ss = np.array([cos_sundel * np.cos(sunalp), cos_sundel * np.sin(sunalp), np.sin(sundel)])
2215
+ return beta, sat, sp, ss
2216
+
2217
+ def _spin_axes(self, beta, sp, ss):
2218
+ """The unit vectors ``sx`` and ``sy`` of the VISSR frame, with ``sp`` the spin axis."""
2219
+ sw1 = _unit_cross(sp, ss)
2220
+ sw2 = _unit_cross(sw1, sp)
2221
+ sx = _unit(sw1 * np.sin(beta) + sw2 * np.cos(beta))
2222
+ return sx, _unit_cross(sp, sx)
2223
+
2224
+ def _scan_time(self, line, elem):
2225
+ """Time (MJD) at which the VISSR scanned image ``line`` and ``elem``; each sensor takes a line of a scan."""
2226
+ sens, rsamp = _F32(self.senssu[0]), _F32(self.resEle[0])
2227
+ whole = np.rint(((line.astype(_F32) - _F32(1)) / sens).astype(float))
2228
+ fraction = (elem.astype(_F32) * rsamp).astype(float) / self.DPAI
2229
+ return (whole + fraction) / (self.dspin * 1440.0) + self.dtims
2230
+
2231
+ def _image_to_latlon(self, line, elem):
2232
+ """VISSR image line and element (mode -1 of mgivsr) to latitude and longitude, NaN if the Earth is missed."""
2233
+ rstep, rsamp, rfcl, rfcp = (float(self.resLin[0]), float(self.resEle[0]), float(self.rlic[0]),
2234
+ float(self.relmfc[0]))
2235
+ beta, sat, sp, ss = self._orbit_and_attitude(self._scan_time(line, elem))
2236
+ sx, sy = self._spin_axes(beta, sp, ss)
2237
+ pc, ps = np.cos(rstep * (line - rfcl)), np.sin(rstep * (line - rfcl))
2238
+ qc, qs = np.cos(rsamp * (elem - rfcp)), np.sin(rsamp * (elem - rfcp))
2239
+ elmis = self.elmis.astype(float)
2240
+ sw1 = np.array([elmis[r, 0] * pc + elmis[r, 2] * ps for r in range(3)])
2241
+ sw2 = np.array([qc * sw1[0] - qs * sw1[1], qs * sw1[0] + qc * sw1[1], sw1[2]])
2242
+ sl = _unit(sx * sw2[0] + sy * sw2[1] + sp * sw2[2])
2243
+ de = (1.0 - self.EF) ** 2
2244
+ dda = de * (sl[0] ** 2 + sl[1] ** 2) + sl[2] ** 2
2245
+ ddb = de * (sat[0] * sl[0] + sat[1] * sl[1]) + sat[2] * sl[2]
2246
+ ddc = de * (sat[0] ** 2 + sat[1] ** 2 - self.EA ** 2) + sat[2] ** 2
2247
+ dd = ddb * ddb - dda * ddc
2248
+ with np.errstate(invalid='ignore', divide='ignore'):
2249
+ root = np.sqrt(dd)
2250
+ dk1, dk2 = (-ddb + root) / dda, (-ddb - root) / dda
2251
+ dk = np.where(np.abs(dk1) < np.abs(dk2), dk1, dk2)
2252
+ hit = sat + dk * sl
2253
+ lat = np.arctan(hit[2] / (de * np.sqrt(hit[0] ** 2 + hit[1] ** 2)))
2254
+ lon = np.arctan2(hit[1], hit[0])
2255
+ missed = ~((dd >= 0.0) & (dda != 0.0))
2256
+ lat = np.where(missed, nan, lat * _CRD).astype(_F32).astype(float)
2257
+ lon = np.where(missed, nan, lon * _CRD).astype(_F32).astype(float)
2258
+ return lat, lon
2259
+
2260
+ def _latlon_to_image(self, lat, lon):
2261
+ """Latitude and longitude (mode 1 of mgivsr) to VISSR image line and element, NaN if not seen."""
2262
+ rstep, rsamp, rfcl, rfcp = (float(self.resLin[0]), float(self.resEle[0]), float(self.rlic[0]),
2263
+ float(self.relmfc[0]))
2264
+ sens = _F32(self.senssu[0])
2265
+ n = lat.size
2266
+ vmis = self.vmis.astype(float)
2267
+ dlat, dlon = lat.astype(_F32).astype(float) * _CDR, lon.astype(_F32).astype(float) * _CDR
2268
+ ee = 2.0 * self.EF - self.EF * self.EF
2269
+ en = self.EA / np.sqrt(1.0 - ee * np.sin(dlat) ** 2)
2270
+ stn1 = np.array([en * np.cos(dlat) * np.cos(dlon), en * np.cos(dlat) * np.sin(dlon),
2271
+ (en * (1.0 - ee)) * np.sin(dlat)])
2272
+ with np.errstate(invalid='ignore', divide='ignore'):
2273
+ rio = (rfcl - np.arctan(np.sin(dlat) / (6.610689 - np.cos(dlat))) / rstep).astype(_F32)
2274
+ rtim = self.dtims + (rio / sens).astype(float) / 1440.0 / self.dspin
2275
+ ri = np.full(n, nan)
2276
+ rj = np.full(n, nan)
2277
+ active = np.isfinite(rtim)
2278
+ for _ in range(100):
2279
+ if not active.any():
2280
+ break
2281
+ index = np.flatnonzero(active)
2282
+ beta, sat, sp, ss = self._orbit_and_attitude(rtim[index])
2283
+ sx, sy = self._spin_axes(beta, sp, ss)
2284
+ sl = _unit(stn1[:, index] - sat)
2285
+ sw2 = _cross(sp, sl)
2286
+ sw3 = _cross(sy, sw2)
2287
+ tp = _angle(sy, sw2)
2288
+ tp = np.where((sp * sw3).sum(axis=0) < 0.0, -tp, tp)
2289
+ tl = _angle(sp, sl)
2290
+ new_i = ((self.HPAI - tl).astype(_F32) / _F32(rstep) + _F32(rfcl) - _F32(vmis[1] / rstep)).astype(float)
2291
+ new_j = (tp / rsamp + rfcp + vmis[2] / rsamp - (self.HPAI - tl) * math.tan(vmis[0]) / rsamp).astype(_F32)
2292
+ ri[index], rj[index] = new_i, new_j.astype(float)
2293
+ moved = np.abs(new_i - rio[index]) >= 1.0
2294
+ ok = np.isfinite(new_i) & np.isfinite(new_j)
2295
+ again = index[moved & ok]
2296
+ fraction = (new_j[moved & ok].astype(_F32) * _F32(rsamp)).astype(float) / self.DPAI
2297
+ whole = np.rint(((new_i[moved & ok].astype(_F32) - _F32(1)) / sens).astype(float))
2298
+ rtim[again] = (whole + fraction) / (self.dspin * 1440.0) + self.dtims
2299
+ rio[again] = new_i[moved & ok].astype(_F32)
2300
+ active = np.zeros(n, dtype=bool)
2301
+ active[again] = True
2302
+ else:
2303
+ ri[active] = rj[active] = nan # did not settle
2304
+ rftl, rftp = float(_F32(self.rline[0] + 0.5)), float(_F32(self.relem[0] + 0.5))
2305
+ with np.errstate(invalid='ignore'):
2306
+ outside = ~((ri >= 0) & (ri <= rftl) & (rj >= 0) & (rj <= rftp))
2307
+ return np.where(outside, nan, ri), np.where(outside, nan, rj)
2308
+
2309
+ def to_latlon(self, line, elem):
2310
+ """Convert line/element (AREA/file coordinates, any shape, broadcast together) to ``(lat, lon)`` degrees.
2311
+
2312
+ East longitude is positive. NaN for the side of the Earth the satellite does not see, and where the line of
2313
+ sight misses the Earth.
2314
+ """
2315
+ line, elem = np.broadcast_arrays(np.asarray(line, dtype=float), np.asarray(elem, dtype=float))
2316
+ image_line, image_elem = self._area_to_image(line, elem)
2317
+ lat, lon = self._image_to_latlon(np.ravel(image_line).astype(float), np.ravel(image_elem).astype(float))
2318
+ lon = np.where(lon > 180, lon - 360, lon)
2319
+ lon = np.where(lon < -180, lon + 360, lon)
2320
+ with np.errstate(invalid='ignore'):
2321
+ hidden = (np.abs(lon) > 180) | ((-lon > 90 - self.subLon) & (-lon < 270 - self.subLon))
2322
+ lat, lon = np.where(hidden, nan, lat), np.where(hidden, nan, lon)
2323
+ return lat.reshape(line.shape), lon.reshape(line.shape)
2324
+
2325
+ def to_lin_ele(self, lat, lon):
2326
+ """Convert lat/lon degrees (east positive, any shape, broadcast together) to ``(line, element)``.
2327
+
2328
+ The result is in AREA (file) coordinates. NaN where the point is not seen from the satellite. A longitude
2329
+ outside -180 to 180 is wrapped into it (VisAD rejects it).
2330
+ """
2331
+ lat, lon = np.broadcast_arrays(np.asarray(lat, dtype=float), np.asarray(lon, dtype=float))
2332
+ flat_lat, flat_lon = np.ravel(lat).astype(float), np.ravel(lon).astype(float)
2333
+ flat_lon = np.where(flat_lon > 180.0, flat_lon - 360.0, flat_lon)
2334
+ flat_lon = np.where(flat_lon < -180.0, flat_lon + 360.0, flat_lon)
2335
+ with np.errstate(invalid='ignore'):
2336
+ usable = (np.abs(flat_lat) <= 90.0) & (np.abs(flat_lon) <= 180.0) \
2337
+ & ~((-flat_lon > 90 - self.subLon) & (-flat_lon < 270 - self.subLon))
2338
+ image_line = np.full(flat_lat.shape, nan)
2339
+ image_elem = np.full(flat_lat.shape, nan)
2340
+ if usable.any():
2341
+ image_line[usable], image_elem[usable] = self._latlon_to_image(flat_lat[usable], flat_lon[usable])
2342
+ line, elem = self._image_to_area(image_line, image_elem)
2343
+ return line.reshape(lat.shape), elem.reshape(lat.shape)
2344
+
2345
+ def toLatLon(self, linele=None):
2346
+ """Convert ``[[elements], [lines]]`` (file coordinates; elements first) to ``[[lats], [lons]]``."""
2347
+ lat, lon = self.to_latlon(linele[self.indexLine], linele[self.indexEle])
2348
+ return [lat, lon]
2349
+
2350
+ def toLinEle(self, latlon=None):
2351
+ """Convert ``[[lats], [lons]]`` to ``[[elements], [lines]]`` in file coordinates."""
2352
+ line, elem = self.to_lin_ele(latlon[self.indexLat], latlon[self.indexLon])
2353
+ out = [None, None]
2354
+ out[self.indexLine], out[self.indexEle] = line, elem
2355
+ return out
2356
+
2357
+ def scan_time(self, line, elem):
2358
+ """Time (MJD) at which the VISSR scanned the image line and element (AREA/file coordinates)."""
2359
+ line, elem = np.broadcast_arrays(np.asarray(line, dtype=float), np.asarray(elem, dtype=float))
2360
+ image_line, image_elem = self._area_to_image(line, elem)
2361
+ return self._scan_time(np.ravel(image_line), np.ravel(image_elem)).reshape(line.shape)
2362
+
2363
+ def getSubpoint(self):
2364
+ return float(self.subLat), float(self.subLon)
2365
+
2366
+
2367
+
2368
+
2369
+ # The constants of ABINnav.java (nvxabin.dlm of McIDAS-X): the GRS 80 ellipsoid of the GOES-R fixed grid.
2370
+ _ABIN_DH = 42164.16 # radius of the satellite orbit, km
2371
+ _ABIN_REQ = 6378.137 # radius of the Earth at the equator, km
2372
+ _ABIN_RPO = 6356.7523 # radius of the Earth at the poles, km
2373
+ _ABIN_FP = 1.006803 # (equatorial / polar radius) squared, as McIDAS has it
2374
+ _ABIN_D = _ABIN_DH * _ABIN_DH - _ABIN_REQ * _ABIN_REQ
2375
+
2376
+
2377
+ class ABINNav(AreaNav):
2378
+ """Navigation for GOES-R ABI fixed grid AREA files, nav type ABIN.
2379
+
2380
+ Port of ``edu.wisc.ssec.mcidas.ABINnav`` (``nvxabin.dlm`` of McIDAS-X). The image line and element give the
2381
+ ABI scan angles linearly, and the angles give the Earth location on the ellipsoid, as in the GOES-R Product
2382
+ User's Guide. Words of the nav block: 2 and 3 the line and element offsets of the scan angles and 4 and 5 their
2383
+ scale factors (radians x 1e8), 6 the subpoint longitude (degrees east x 10), 7 the base resolution.
2384
+ """
2385
+
2386
+ labels = {1: 'ABIN',
2387
+ 2: 'line offset of the scan angle, radians x 1e8',
2388
+ 3: 'element offset of the scan angle, radians x 1e8',
2389
+ 4: 'line scale factor, radians per line x 1e8',
2390
+ 5: 'element scale factor, radians per element x 1e8',
2391
+ 6: 'subpoint longitude, degrees east x 10',
2392
+ 7: 'base resolution'}
2393
+
2394
+ def __init__(self, navblock=None, auxblock=None, **kwargs):
2395
+ if self.navtype.strip() != self.ABIN:
2396
+ raise ValueError(f'Invalid navigation type: {self.navtype!r}')
2397
+ if len(navblock) < 7:
2398
+ raise ValueError(f'The ABIN navigation block has {len(navblock)} words, 7 are needed.')
2399
+ self.loff = navblock[1] / 100000000.0
2400
+ self.coff = navblock[2] / 100000000.0
2401
+ self.lfac = navblock[3] / 100000000.0
2402
+ self.cfac = navblock[4] / 100000000.0
2403
+ self.plon = navblock[5] / 10.0
2404
+ self.bres = float(navblock[6])
2405
+
2406
+ def to_latlon(self, line, elem):
2407
+ """Convert line/element (AREA/file coordinates, any shape, broadcast together) to ``(lat, lon)`` degrees.
2408
+
2409
+ East longitude is positive, in -180 to 180. NaN where the line of sight misses the Earth, or the input is NaN.
2410
+ """
2411
+ line, elem = np.broadcast_arrays(np.asarray(line, dtype=float), np.asarray(elem, dtype=float))
2412
+ image_line, image_elem = self._area_to_image(line, elem)
2413
+ dh, fp = _ABIN_DH, _ABIN_FP
2414
+ with np.errstate(invalid='ignore', divide='ignore'):
2415
+ # image coordinates are in base resolution units; the scan angles are linear in the pixels
2416
+ xlin = (image_line - (self.bres - 1) / 2.0) / self.bres
2417
+ xele = (image_elem - (self.bres - 1) / 2.0) / self.bres
2418
+ theta_goes = xlin * self.lfac + self.loff
2419
+ lamda_goes = xele * self.cfac + self.coff
2420
+ # GOES to GEOS scan angles
2421
+ theta_geos = np.arcsin(np.sin(theta_goes) * np.cos(lamda_goes))
2422
+ lamda_geos = np.arctan(np.tan(lamda_goes) / np.cos(theta_goes))
2423
+ cosx, cosy = np.cos(lamda_geos), np.cos(theta_geos)
2424
+ sinx, siny = np.sin(lamda_geos), np.sin(theta_geos)
2425
+
2426
+ a = dh * cosx * cosy
2427
+ k = cosy * cosy + fp * siny * siny
2428
+ sdd = a * a - k * _ABIN_D
2429
+ misses = sdd < 0.0
2430
+ sn = (a - np.sqrt(np.where(misses, 0.0, sdd))) / k
2431
+ s1 = dh - sn * cosx * cosy
2432
+ s2 = sn * sinx * cosy
2433
+ s3 = -(sn * siny)
2434
+ sxy = np.sqrt(s1 * s1 + s2 * s2)
2435
+ lon = np.degrees(np.arctan(s2 / s1) + math.radians(self.plon))
2436
+ lat = np.degrees(np.arctan(-(fp * s3 / sxy)))
2437
+ lon = np.where(lon > 180, lon - 360.0, np.where(lon < -180, lon + 360.0, lon))
2438
+ return np.where(misses, np.nan, lat), np.where(misses, np.nan, lon)
2439
+
2440
+ def to_lin_ele(self, lat, lon):
2441
+ """Convert lat/lon degrees (east positive, any shape, broadcast together) to ``(line, element)``.
2442
+
2443
+ The result is in AREA (file) coordinates. NaN where the point is on the far side of the Earth. As in
2444
+ VisAD, a point just beyond the limb still gets the scan angles it would have.
2445
+ """
2446
+ lat, lon = np.broadcast_arrays(np.asarray(lat, dtype=float), np.asarray(lon, dtype=float))
2447
+ dh, req2, rpo2 = _ABIN_DH, _ABIN_REQ ** 2, _ABIN_RPO ** 2
2448
+ with np.errstate(invalid='ignore', divide='ignore'):
2449
+ geographic_lat = np.radians(lat)
2450
+ dlon = np.radians(lon) - math.radians(self.plon)
2451
+ geocentric_lat = np.arctan(rpo2 / req2 * np.tan(geographic_lat))
2452
+ cos_gc = np.cos(geocentric_lat)
2453
+ r_earth = _ABIN_RPO / np.sqrt(1.0 - (req2 - rpo2) / req2 * cos_gc * cos_gc)
2454
+ r_1 = dh - r_earth * cos_gc * np.cos(dlon)
2455
+ r_2 = -(r_earth * cos_gc * np.sin(dlon))
2456
+ r_3 = r_earth * np.sin(geocentric_lat)
2457
+ lamda = np.arcsin(-(r_2 / np.sqrt(r_1 * r_1 + r_2 * r_2 + r_3 * r_3)))
2458
+ theta = np.arctan(r_3 / r_1)
2459
+ xlin = (theta - self.loff) / self.lfac * self.bres + (self.bres - 1) / 2.0
2460
+ xele = (lamda - self.coff) / self.cfac * self.bres + (self.bres - 1) / 2.0
2461
+ far_side = r_1 > dh
2462
+ line, elem = self._image_to_area(np.where(far_side, np.nan, xlin), np.where(far_side, np.nan, xele))
2463
+ return line, elem
2464
+
2465
+ def toLatLon(self, linele=None):
2466
+ """Convert ``[[elements], [lines]]`` (file coordinates; elements first) to ``[[lats], [lons]]``."""
2467
+ lat, lon = self.to_latlon(linele[self.indexLine], linele[self.indexEle])
2468
+ out = [None, None]
2469
+ out[self.indexLat], out[self.indexLon] = lat, lon
2470
+ return out
2471
+
2472
+ def toLinEle(self, latlon=None):
2473
+ """Convert ``[[lats], [lons]]`` to ``[[elements], [lines]]`` in file coordinates."""
2474
+ line, elem = self.to_lin_ele(latlon[self.indexLat], latlon[self.indexLon])
2475
+ out = [None, None]
2476
+ out[self.indexLine], out[self.indexEle] = line, elem
2477
+ return out
2478
+
2479
+ def toLatLon2(self, lines=None, cols=None):
2480
+ """Array version of :meth:`toLatLon`: ``lines`` and ``cols`` (broadcast together) to ``(lat, lon)``."""
2481
+ return self.to_latlon(lines, cols)
2482
+
2483
+ def toLinEle2(self, lats=None, lons=None):
2484
+ """Array version of :meth:`toLinEle`: ``lats`` and ``lons`` to ``(lines, cols)``, NaN where not visible."""
2485
+ return self.to_lin_ele(lats, lons)
2486
+
2487
+
2488
+ # The constants of GEOSnav.java (nvxgeos.dlm of McIDAS-X): EUMETSAT's LRIT/HRIT Global Specification (CGMS 03).
2489
+ _GEOS_RADPOL = 6356.5838 # radius of the Earth at the poles, km
2490
+ _GEOS_RADEQ = 6378.1690 # radius of the Earth at the equator, km
2491
+ _GEOS_X42 = 42164.0 # radius of the satellite orbit, km
2492
+ _GEOS_FP = 1.006803 # (equatorial / polar radius) squared, as in the forward formulas
2493
+ _GEOS_FP_INVERSE = 0.993243 # (polar / equatorial radius) squared, as in the inverse formulas
2494
+ _GEOS_D = 1737121856.0 # X42 ** 2 - RADEQ ** 2, typed in as a constant in the Java
2495
+
2496
+
2497
+ class GEOSNav(AreaNav):
2498
+ """Navigation for geostationary AREA files laid out as in the LRIT/HRIT specification, nav type GEOS.
2499
+
2500
+ Port of ``edu.wisc.ssec.mcidas.GEOSnav`` (``nvxgeos.dlm`` of McIDAS-X), used for Himawari, COMS-1 and the
2501
+ MPEF/OSIS products. The image line and element are the HRIT column and line numbers (``COFF``, ``LOFF``,
2502
+ ``CFAC``, ``LFAC``), with the scan angle in units of 2**-16 degrees. Words of the nav block: 2 and 3 the line and
2503
+ element offsets (x 10), 4 and 5 the line and element scale factors (x 10), 6 the subpoint longitude (degrees east
2504
+ x 10), 7 the base resolution (default 1) and 8 the pixel offset flag (1 for the half pixel convention of AHI).
2505
+ """
2506
+
2507
+ labels = {1: 'GEOS',
2508
+ 2: 'line offset (LOFF) x 10',
2509
+ 3: 'element offset (COFF) x 10',
2510
+ 4: 'line scale factor (LFAC) x 10',
2511
+ 5: 'element scale factor (CFAC) x 10',
2512
+ 6: 'subpoint longitude, degrees east x 10',
2513
+ 7: 'base resolution',
2514
+ 8: 'pixel offset flag (1: half pixel adjustment as for AHI)'}
2515
+
2516
+ def __init__(self, navblock=None, auxblock=None, **kwargs):
2517
+ if self.navtype.strip() != self.GEOS:
2518
+ raise ValueError(f'Invalid navigation type: {self.navtype!r}')
2519
+ if len(navblock) < 6:
2520
+ raise ValueError(f'The GEOS navigation block has {len(navblock)} words, 6 are needed.')
2521
+ self.loff = int(navblock[1])
2522
+ self.coff = int(navblock[2])
2523
+ self.lfac = int(navblock[3])
2524
+ self.cfac = int(navblock[4])
2525
+ self.plon = int(navblock[5])
2526
+ self.bres = int(navblock[6]) if len(navblock) > 6 and navblock[6] > 0 else 1
2527
+ self.pixelOffsetFlag = int(navblock[7]) if len(navblock) > 7 and navblock[7] > 0 else 0
2528
+
2529
+ def to_latlon(self, line, elem):
2530
+ """Convert line/element (AREA/file coordinates, any shape, broadcast together) to ``(lat, lon)`` degrees.
2531
+
2532
+ East longitude is positive, in -180 to 180. NaN where the line of sight misses the Earth, or the input is NaN.
2533
+ """
2534
+ line, elem = np.broadcast_arrays(np.asarray(line, dtype=float), np.asarray(elem, dtype=float))
2535
+ image_line, image_elem = self._area_to_image(line, elem)
2536
+ bres = self.bres
2537
+ shift = (bres - 1) / 2.0 if self.pixelOffsetFlag == 1 else bres - 1
2538
+ with np.errstate(invalid='ignore', divide='ignore'):
2539
+ xlin = (image_line + shift) / bres
2540
+ xele = (image_elem + shift) / bres
2541
+ # the scan angles, in radians
2542
+ x = np.radians((xele - self.coff / 10.0) * 65536.0 / (self.cfac / 10.0))
2543
+ y = np.radians((xlin - self.loff / 10.0) * 65536.0 / (self.lfac / 10.0))
2544
+ cosx, cosy, sinx, siny = np.cos(x), np.cos(y), np.sin(x), np.sin(y)
2545
+
2546
+ aux = _GEOS_X42 * cosx * cosy
2547
+ aux2 = cosy * cosy + _GEOS_FP * siny * siny
2548
+ sdd = aux * aux - aux2 * _GEOS_D
2549
+ misses = sdd < 0.0
2550
+ sn = (aux - np.sqrt(np.where(misses, 0.0, sdd))) / aux2
2551
+ s1 = _GEOS_X42 - sn * cosx * cosy
2552
+ s2 = sn * sinx * cosy
2553
+ s3 = -sn * siny
2554
+ sxy = np.sqrt(s1 * s1 + s2 * s2)
2555
+ lon = np.degrees(np.arctan(s2 / s1)) + self.plon / 10.0
2556
+ lat = np.degrees(np.arctan(_GEOS_FP * s3 / sxy))
2557
+ lon = np.where(lon > 180.0, lon - 360.0, np.where(lon < -180.0, lon + 360.0, lon))
2558
+ return np.where(misses, np.nan, lat), np.where(misses, np.nan, lon)
2559
+
2560
+ def to_lin_ele(self, lat, lon):
2561
+ """Convert lat/lon degrees (east positive, any shape, broadcast together) to ``(line, element)``.
2562
+
2563
+ The result is in AREA (file) coordinates. NaN where the point is not seen from the satellite.
2564
+ """
2565
+ lat, lon = np.broadcast_arrays(np.asarray(lat, dtype=float), np.asarray(lon, dtype=float))
2566
+ r_pol2, r_eq2 = _GEOS_RADPOL ** 2, _GEOS_RADEQ ** 2
2567
+ bres = self.bres
2568
+ shift = (bres - 1) / 2.0 if self.pixelOffsetFlag == 1 else bres - 1
2569
+ with np.errstate(invalid='ignore', divide='ignore'):
2570
+ dlon = np.radians(lon) - math.radians(self.plon / 10.0)
2571
+ c_lat = np.arctan(_GEOS_FP_INVERSE * np.tan(np.radians(lat)))
2572
+ cosc_lat = np.cos(c_lat)
2573
+ rl = _GEOS_RADPOL / np.sqrt(1.0 - ((r_eq2 - r_pol2) / r_eq2) * cosc_lat * cosc_lat)
2574
+ r1 = _GEOS_X42 - rl * cosc_lat * np.cos(dlon)
2575
+ r2 = -rl * cosc_lat * np.sin(dlon)
2576
+ r3 = rl * np.sin(c_lat)
2577
+ rn = np.sqrt(r1 * r1 + r2 * r2 + r3 * r3)
2578
+
2579
+ # is the point visible from the satellite?
2580
+ ad2 = r1 * r1 + r2 * r2 + r3 * r3 * r_eq2 / r_pol2
2581
+ bd = _GEOS_X42 * r1
2582
+ delta2 = bd * bd - ad2 * (_GEOS_X42 ** 2 - r_eq2)
2583
+ halfsom = bd * rn / ad2
2584
+ visible = (delta2 >= 0.0) & (rn <= halfsom)
2585
+
2586
+ x = np.degrees(np.arctan(-r2 / r1))
2587
+ y = np.degrees(np.arcsin(-r3 / rn))
2588
+ xele = self.coff / 10.0 + x / 65536.0 * self.cfac / 10.0
2589
+ xlin = self.loff / 10.0 + y / 65536.0 * self.lfac / 10.0
2590
+ rlin = np.where(visible, xlin * bres - shift, np.nan)
2591
+ rele = np.where(visible, xele * bres - shift, np.nan)
2592
+ return self._image_to_area(rlin, rele)
2593
+
2594
+ def toLatLon(self, linele=None):
2595
+ """Convert ``[[elements], [lines]]`` (file coordinates; elements first) to ``[[lats], [lons]]``."""
2596
+ lat, lon = self.to_latlon(linele[self.indexLine], linele[self.indexEle])
2597
+ out = [None, None]
2598
+ out[self.indexLat], out[self.indexLon] = lat, lon
2599
+ return out
2600
+
2601
+ def toLinEle(self, latlon=None):
2602
+ """Convert ``[[lats], [lons]]`` to ``[[elements], [lines]]`` in file coordinates."""
2603
+ line, elem = self.to_lin_ele(latlon[self.indexLat], latlon[self.indexLon])
2604
+ out = [None, None]
2605
+ out[self.indexLine], out[self.indexEle] = line, elem
2606
+ return out
2607
+
2608
+ def toLatLon2(self, lines=None, cols=None):
2609
+ """Array version of :meth:`toLatLon`: ``lines`` and ``cols`` (broadcast together) to ``(lat, lon)``."""
2610
+ return self.to_latlon(lines, cols)
2611
+
2612
+ def toLinEle2(self, lats=None, lons=None):
2613
+ """Array version of :meth:`toLinEle`: ``lats`` and ``lons`` to ``(lines, cols)``, NaN where not visible."""
2614
+ return self.to_lin_ele(lats, lons)
2615
+
2616
+
2617
+ # The constants of MSATnav.java (nvxmsat.dlm of McIDAS-X), the Meteosat first generation images
2618
+ _MSAT_NOMORB = 42164.0 # nominal radial distance of the satellite, km
2619
+ _MSAT_EARTH_RADIUS = 6378.155 # radius of the Earth at the equator, km
2620
+ _MSAT_H = _MSAT_NOMORB - _MSAT_EARTH_RADIUS # height of the satellite above the equatorial radius
2621
+ _MSAT_FLATTENING = 1.0 / 297.0
2622
+ _MSAT_RP = _MSAT_EARTH_RADIUS / (1.0 + _MSAT_FLATTENING) # radius of the Earth at the poles
2623
+ _MSAT_DELTA = 18.0 / 2500.0 # degrees of scan angle per step of 2 image pixels
2624
+
2625
+
2626
+ class MSATNav(AreaNav):
2627
+ """Navigation for Meteosat first generation (MET-1 to MET-7) AREA files, nav type MSAT.
2628
+
2629
+ Port of ``edu.wisc.ssec.mcidas.MSATnav`` (``nvxmsat.dlm`` of McIDAS-X). The images are 5000 x 5000 pixels (two
2630
+ image pixels per step of the 2500 x 2500 scan grid, ``18/2500`` degrees each) and the Earth is an ellipsoid with a
2631
+ flattening of 1/297. Words of the nav block (counted from 1): 4, 5 and 6 the three offsets of the scan grid and 7
2632
+ the longitude of the subpoint as a packed integer (DDDMMSS, west positive as in McIDAS).
2633
+
2634
+ The reverse direction of the Java hard-codes the centre of the grid (5000 lines, i.e. 1250 for word 6), so
2635
+ ``to_lin_ele`` is only the inverse of ``to_latlon`` for files whose third offset is 1250, which is the case for
2636
+ the real ones.
2637
+ """
2638
+
2639
+ labels = {1: 'MSAT',
2640
+ 4: 'offset 1 of the scan grid',
2641
+ 5: 'offset 2 of the scan grid',
2642
+ 6: 'offset 3 of the scan grid (1250)',
2643
+ 7: 'subpoint longitude, packed DDDMMSS, west positive'}
2644
+
2645
+ def __init__(self, navblock=None, auxblock=None, **kwargs):
2646
+ if self.navtype.strip() != self.MSAT:
2647
+ raise ValueError(f'Invalid navigation type: {self.navtype!r}')
2648
+ if len(navblock) < 7:
2649
+ raise ValueError(f'The MSAT navigation block has {len(navblock)} words, 7 are needed.')
2650
+ self.ioff = tuple(int(v) for v in navblock[3:6])
2651
+ self.sublon = utils.mcPI2F(navblock[6])
2652
+
2653
+ def to_latlon(self, line, elem):
2654
+ """Convert line/element (AREA/file coordinates, any shape, broadcast together) to ``(lat, lon)`` degrees.
2655
+
2656
+ East longitude is positive. NaN where the line of sight misses the Earth, or the input is NaN.
2657
+ """
2658
+ line, elem = np.broadcast_arrays(np.asarray(line, dtype=float), np.asarray(elem, dtype=float))
2659
+ image_line, image_elem = self._area_to_image(line, elem)
2660
+ r, h, a, rp = _MSAT_EARTH_RADIUS, _MSAT_H, _MSAT_FLATTENING, _MSAT_RP
2661
+ with np.errstate(invalid='ignore', divide='ignore'):
2662
+ x = np.radians((1250.5 - image_elem / 2.0) * _MSAT_DELTA)
2663
+ y = np.radians((self.ioff[2] - (image_line / 2.0 + self.ioff[1] - self.ioff[0])) * _MSAT_DELTA)
2664
+ rs = r + h
2665
+ tanx, tany = np.tan(x), np.tan(y)
2666
+ val1 = 1.0 + tanx * tanx
2667
+ val2 = 1.0 + (tany * tany) * ((1.0 + a) * (1.0 + a))
2668
+ yk = rs / r
2669
+ misses = (val1 * val2) > ((yk * yk) / (yk * yk - 1))
2670
+ vmu = (rs - r * np.sqrt(yk * yk - (yk * yk - 1) * val1 * val2)) / (val1 * val2)
2671
+ # the reference longitude of the Java is 0: cos = 1 and sin = 0
2672
+ xt = rs + vmu * (-1.0)
2673
+ yt = -(vmu * tanx)
2674
+ zt = vmu * tany / np.cos(x)
2675
+ teta = np.arcsin(zt / rp)
2676
+ lat = np.degrees(np.arctan(np.tan(teta) * r / rp))
2677
+ lon = -(-np.degrees(np.arctan(yt / xt)) + self.sublon) # the subpoint is west positive; east positive out
2678
+ return np.where(misses, np.nan, lat), np.where(misses, np.nan, lon)
2679
+
2680
+ def to_lin_ele(self, lat, lon):
2681
+ """Convert lat/lon degrees (east positive, any shape, broadcast together) to ``(line, element)``.
2682
+
2683
+ The result is in AREA (file) coordinates. NaN where the point is not seen from the satellite (with the test of
2684
+ the Java, which compares with the height of the satellite above the equatorial radius).
2685
+ """
2686
+ lat, lon = np.broadcast_arrays(np.asarray(lat, dtype=float), np.asarray(lon, dtype=float))
2687
+ r, h, rp = _MSAT_EARTH_RADIUS, _MSAT_H, _MSAT_RP
2688
+ with np.errstate(invalid='ignore', divide='ignore'):
2689
+ xfi = np.radians(lat)
2690
+ xla = np.radians(lon + self.sublon)
2691
+ rom = (r * rp) / np.sqrt(rp * rp * np.cos(xfi) * np.cos(xfi) + r * r * np.sin(xfi) * np.sin(xfi))
2692
+ y = np.sqrt(h * h + rom * rom - 2 * h * rom * np.cos(xfi) * np.cos(xla))
2693
+ invisible = (y * y + rom * rom) > h * h
2694
+ rs = r + h
2695
+ teta = np.arctan((rp / r) * np.tan(xfi))
2696
+ xt = r * np.cos(teta) * np.cos(xla)
2697
+ yt = r * np.cos(teta) * np.sin(xla)
2698
+ zt = rp * np.sin(teta)
2699
+ # the reference longitude of the Java is 0: cos = 1 and sin = 0
2700
+ px = np.arctan(yt / (xt - rs))
2701
+ py = np.arctan(zt * ((np.tan(px) * 0.0 - 1.0) / (xt - rs)) * np.cos(px))
2702
+ xr = np.degrees(px) / _MSAT_DELTA
2703
+ yr = np.degrees(py) / _MSAT_DELTA
2704
+ xr = (1250.5 - xr) * 2
2705
+ yr = 5000 - (yr + self.ioff[2] + self.ioff[1] - self.ioff[0]) * 2
2706
+ return self._image_to_area(np.where(invisible, np.nan, yr), np.where(invisible, np.nan, xr))
2707
+
2708
+ def toLatLon(self, linele=None):
2709
+ """Convert ``[[elements], [lines]]`` (file coordinates; elements first) to ``[[lats], [lons]]``."""
2710
+ lat, lon = self.to_latlon(linele[self.indexLine], linele[self.indexEle])
2711
+ out = [None, None]
2712
+ out[self.indexLat], out[self.indexLon] = lat, lon
2713
+ return out
2714
+
2715
+ def toLinEle(self, latlon=None):
2716
+ """Convert ``[[lats], [lons]]`` to ``[[elements], [lines]]`` in file coordinates."""
2717
+ line, elem = self.to_lin_ele(latlon[self.indexLat], latlon[self.indexLon])
2718
+ out = [None, None]
2719
+ out[self.indexLine], out[self.indexEle] = line, elem
2720
+ return out
2721
+
2722
+ def toLatLon2(self, lines=None, cols=None):
2723
+ """Array version of :meth:`toLatLon`: ``lines`` and ``cols`` (broadcast together) to ``(lat, lon)``."""
2724
+ return self.to_latlon(lines, cols)
2725
+
2726
+ def toLinEle2(self, lats=None, lons=None):
2727
+ """Array version of :meth:`toLinEle`: ``lats`` and ``lons`` to ``(lines, cols)``, NaN where not visible."""
2728
+ return self.to_lin_ele(lats, lons)
2729
+
2730
+
2731
+ class MSGTNav(AreaNav):
2732
+ """Navigation for Meteosat second generation (MET-8 to MET-11) AREA files, nav type MSGT.
2733
+
2734
+ Port of ``edu.wisc.ssec.mcidas.MSGTnav`` (``nvxmsgt.dlm`` of McIDAS-X). The image is on the 11136 x 11136 grid of
2735
+ the high resolution visible channel; three of its pixels make one pixel of the 3712 x 3712 SEVIRI grid, which is
2736
+ the grid of the HRIT scan angles. Both the lines and the elements are counted from the north-west corner of the
2737
+ image, and the Earth is the ellipsoid with a flattening of 1/297 of Meteosat first generation. Words of the nav
2738
+ block (counted from 1): 2 and 3 the line and element offsets of the scan grid (LOFF and COFF, x 10), 4 and 5 its
2739
+ line and element factors (LFAC and CFAC, the HRIT values in units of 2**-16 degree times 1e6 / 2**16, so the
2740
+ scan angle step is ``1e6 / factor`` degrees) and 6 the subpoint longitude in degrees x 10000, west positive.
2741
+ """
2742
+
2743
+ labels = {1: 'MSGT',
2744
+ 2: 'line offset (LOFF) x 10',
2745
+ 3: 'element offset (COFF) x 10',
2746
+ 4: 'line factor (LFAC), 1e6 / degrees per step',
2747
+ 5: 'element factor (CFAC), 1e6 / degrees per step',
2748
+ 6: 'subpoint longitude, degrees x 10000, west positive'}
2749
+
2750
+ def __init__(self, navblock=None, auxblock=None, **kwargs):
2751
+ if self.navtype.strip() != self.MSGT:
2752
+ raise ValueError(f'Invalid navigation type: {self.navtype!r}')
2753
+ if len(navblock) < 6:
2754
+ raise ValueError(f'The MSGT navigation block has {len(navblock)} words, 6 are needed.')
2755
+ self.loff, self.coff, self.lfac, self.cfac = (int(v) for v in navblock[1:5])
2756
+ if self.lfac == 0 or self.cfac == 0:
2757
+ raise ValueError(f'The MSGT scale factors are {self.lfac} and {self.cfac}; they cannot be 0.')
2758
+ self.sublon = -int(navblock[5]) / 10000.0 # east positive
2759
+ self.deltax = 1.0 / (self.cfac / 1000000.0)
2760
+ self.deltay = 1.0 / (self.lfac / 1000000.0)
2761
+
2762
+ def to_latlon(self, line, elem):
2763
+ """Convert line/element (AREA/file coordinates, any shape, broadcast together) to ``(lat, lon)`` degrees.
2764
+
2765
+ East longitude is positive. NaN where the line of sight misses the Earth, or the input is NaN.
2766
+ """
2767
+ line, elem = np.broadcast_arrays(np.asarray(line, dtype=float), np.asarray(elem, dtype=float))
2768
+ image_line, image_elem = self._area_to_image(line, elem)
2769
+ r, h, a, rp = _MSAT_EARTH_RADIUS, _MSAT_H, _MSAT_FLATTENING, _MSAT_RP
2770
+ rs = r + h
2771
+ yk = rs / r
2772
+ with np.errstate(invalid='ignore', divide='ignore'):
2773
+ xlin = ((11136.0 - image_line + 1.0) + 2.0) / 3.0
2774
+ xele = ((11136.0 - image_elem + 1.0) + 2.0) / 3.0
2775
+ xr = np.radians((xele - self.coff / 10.0) * self.deltax)
2776
+ yr = np.radians((xlin - self.loff / 10.0) * self.deltay)
2777
+ tanx, tany = np.tan(xr), np.tan(yr)
2778
+ v1 = 1.0 + tanx * tanx
2779
+ v2 = 1.0 + (tany * tany) * ((1.0 + a) * (1.0 + a))
2780
+ misses = (v1 * v2) > ((yk * yk) / (yk * yk - 1))
2781
+ vmu = (rs - r * np.sqrt(yk * yk - (yk * yk - 1) * v1 * v2)) / (v1 * v2)
2782
+ xt = rs - vmu
2783
+ yt = -vmu * tanx
2784
+ zt = vmu * tany / np.cos(xr)
2785
+ teta = np.arcsin(zt / rp)
2786
+ lat = np.degrees(np.arctan(np.tan(teta) * r / rp))
2787
+ lon = np.degrees(np.arctan(yt / xt)) + self.sublon
2788
+ return np.where(misses, np.nan, lat), np.where(misses, np.nan, lon)
2789
+
2790
+ def to_lin_ele(self, lat, lon):
2791
+ """Convert lat/lon degrees (east positive, any shape, broadcast together) to ``(line, element)``.
2792
+
2793
+ The result is in AREA (file) coordinates. NaN where the point is not seen from the satellite (with the test of
2794
+ the Java, which compares with the height of the satellite above the equatorial radius), or the input is NaN.
2795
+ """
2796
+ lat, lon = np.broadcast_arrays(np.asarray(lat, dtype=float), np.asarray(lon, dtype=float))
2797
+ r, h, rp = _MSAT_EARTH_RADIUS, _MSAT_H, _MSAT_RP
2798
+ rs = r + h
2799
+ with np.errstate(invalid='ignore', divide='ignore'):
2800
+ xfi = np.radians(lat)
2801
+ xla = np.radians(lon - self.sublon)
2802
+ rom = r * rp / np.sqrt(rp * rp * np.cos(xfi) * np.cos(xfi) + r * r * np.sin(xfi) * np.sin(xfi))
2803
+ y = np.sqrt(h * h + rom * rom - 2.0 * h * rom * np.cos(xfi) * np.cos(xla))
2804
+ invisible = (y * y + rom * rom) > h * h
2805
+ teta = np.arctan((rp / r) * np.tan(xfi))
2806
+ xt = r * np.cos(teta) * np.cos(xla)
2807
+ yt = r * np.cos(teta) * np.sin(xla)
2808
+ zt = rp * np.sin(teta)
2809
+ px = np.arctan(yt / (xt - rs))
2810
+ py = np.arctan(-zt / (xt - rs) * np.cos(px))
2811
+ xele = self.coff / 10.0 + np.degrees(px) / self.deltax
2812
+ xlin = self.loff / 10.0 + np.degrees(py) / self.deltay
2813
+ rlin = 11136.0 - (xlin * 3.0 - 2.0) + 1.0
2814
+ rele = 11136.0 - (xele * 3.0 - 2.0) + 1.0
2815
+ return self._image_to_area(np.where(invisible, np.nan, rlin), np.where(invisible, np.nan, rele))
2816
+
2817
+ def toLatLon(self, linele=None):
2818
+ """Convert ``[[elements], [lines]]`` (file coordinates; elements first) to ``[[lats], [lons]]``."""
2819
+ lat, lon = self.to_latlon(linele[self.indexLine], linele[self.indexEle])
2820
+ out = [None, None]
2821
+ out[self.indexLat], out[self.indexLon] = lat, lon
2822
+ return out
2823
+
2824
+ def toLinEle(self, latlon=None):
2825
+ """Convert ``[[lats], [lons]]`` to ``[[elements], [lines]]`` in file coordinates."""
2826
+ line, elem = self.to_lin_ele(latlon[self.indexLat], latlon[self.indexLon])
2827
+ out = [None, None]
2828
+ out[self.indexLine], out[self.indexEle] = line, elem
2829
+ return out
2830
+
2831
+ def toLatLon2(self, lines=None, cols=None):
2832
+ """Array version of :meth:`toLatLon`: ``lines`` and ``cols`` (broadcast together) to ``(lat, lon)``."""
2833
+ return self.to_latlon(lines, cols)
2834
+
2835
+ def toLinEle2(self, lats=None, lons=None):
2836
+ """Array version of :meth:`toLinEle`: ``lats`` and ``lons`` to ``(lines, cols)``, NaN where not visible."""
2837
+ return self.to_lin_ele(lats, lons)