-
Notifications
You must be signed in to change notification settings - Fork 34
/
ilamblib.py
2746 lines (2484 loc) · 96.3 KB
/
ilamblib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import os
import re
from copy import deepcopy
import cftime as cf
import numpy as np
from cf_units import Unit
from mpi4py import MPI
from netCDF4 import Dataset
from pkg_resources import get_distribution, parse_version
from scipy.interpolate import NearestNDInterpolator
from ILAMB.Regions import Regions
logger = logging.getLogger("%i" % MPI.COMM_WORLD.rank)
class VarNotInFile(Exception):
def __str__(self):
return "VarNotInFile"
class VarNotMonthly(Exception):
def __str__(self):
return "VarNotMonthly"
class VarNotInModel(Exception):
def __str__(self):
return "VarNotInModel"
class SiteNotInModel(Exception):
def __str__(self):
return "SiteNotInModel"
class VarsNotComparable(Exception):
def __str__(self):
return "VarNotComparable"
class VarNotOnTimeScale(Exception):
def __str__(self):
return "VarNotOnTimeScale"
class UnknownUnit(Exception):
def __str__(self):
return "UnknownUnit"
class AreasNotInModel(Exception):
def __str__(self):
return "AreasNotInModel"
class MisplacedData(Exception):
def __str__(self):
return "MisplacedData"
class NotTemporalVariable(Exception):
def __str__(self):
return "NotTemporalVariable"
class NotSpatialVariable(Exception):
def __str__(self):
return "NotSpatialVariable"
class UnitConversionError(Exception):
def __str__(self):
return "UnitConversionError"
class AnalysisError(Exception):
def __str__(self):
return "AnalysisError"
class NotLayeredVariable(Exception):
def __str__(self):
return "NotLayeredVariable"
class NotDatasiteVariable(Exception):
def __str__(self):
return "NotDatasiteVariable"
class MonotonicityError(Exception):
def __str__(self):
return "MonotonicityError"
def FixDumbUnits(unit):
r"""Try to fix the dumb units people insist on using.
Parameters
----------
unit : str
the trial unit
Returns
-------
unit : str
the fixed unit
"""
# Various synonyms for 1
if unit.lower().strip() in ["unitless", "n/a", "none"]:
unit = "1"
# Remove the C which so often is used to mean carbon but actually means coulomb
tokens = re.findall(r"[\w']+", unit)
for i, token in enumerate(tokens):
if token.endswith("C"):
try:
if Unit(token[:-1]).is_convertible(Unit("g")):
unit = unit.replace(token, token[:-1])
elif (i > 0) and Unit(tokens[i - 1]).is_convertible(Unit("g")):
unit = unit.replace(" C", "")
except:
pass
# ... and Nitrogen
for i, token in enumerate(tokens):
if token.endswith("N"):
try:
if Unit(token[:-1]).is_convertible(Unit("g")):
unit = unit.replace(token, token[:-1])
elif (i > 0) and Unit(tokens[i - 1]).is_convertible(Unit("g")):
unit = unit.replace(" N", "")
except:
pass
return unit
def GenerateDistinctColors(N, saturation=0.67, value=0.67):
r"""Generates a series of distinct colors.
Computes N distinct colors using HSV color space, holding the
saturation and value levels constant and linearly vary the
hue. Colors are returned as a RGB tuple.
Parameters
----------
N : int
number of distinct colors to generate
saturation : float, optional
argument of HSV color space
value : float, optional
argument of HSV color space
Returns
-------
RGB_tuples : list
list of N distinct RGB tuples
"""
from colorsys import hsv_to_rgb
HSV_tuples = [(x / float(N), saturation, value) for x in range(N)]
RGB_tuples = list(map(lambda x: hsv_to_rgb(*x), HSV_tuples))
return RGB_tuples
def GuessAlpha(t):
"""Guess at what point in the time interval is the given time.
Although part of the CF standard, many datasets do not have the
bounds specifed on the time variable. This is complicated by the
many conventions that groups have regarding at what point in the
time interval the time is reported. In the absence of given
bounds, we guess here at what convention was used.
Parameters
----------
t: netCDF4.Variable
the dataset or array representing the times of the intervals
Returns
-------
alpha: float
estimated location in the time interval where the given time
is defined
"""
if t.size == 1:
return 0.5
t0 = cf.num2date(t[0], t.units, calendar=t.calendar)
t1 = cf.num2date(t[1], t.units, calendar=t.calendar)
dt = (t1 - t0).total_seconds() / 3600 / 24
if np.allclose(dt, 365.0, atol=10):
# annual: assumes that the first time entry represents the beginning of a decade
y0 = cf.date2num(
cf.datetime(10 * (t0.year / 10), 1, 1), t.units, calendar=t.calendar
)
alpha = np.round((t[0] - y0) / dt, 1).clip(0, 1)
elif np.allclose(dt, 30, atol=4):
# monthly: assumes that the first time entry represents the beginning of a year
m0 = cf.date2num(cf.datetime(t0.year, 1, 1), t.units, calendar=t.calendar)
alpha = np.round((t[0] - m0) / dt, 1).clip(0, 1)
elif dt < 0.9:
# sub-daily: assumes that the first time entry represents the beginning of a day
h0 = cf.date2num(
cf.datetime(t0.year, t0.month, t0.day), t.units, calendar=t.calendar
)
alpha = np.round((t[0] - h0) / dt, 1)
else:
msg = "GuessAlpha for dt = %f [d] not implemented yet" % (dt)
raise ValueError(msg)
return alpha
def CreateTimeBounds(t, alpha=0.5):
"""Create time bounds from a time array.
Parameters
----------
t: netCDF4.Variable or numpy.ndarray
the dataset or array representing the times of the intervals
alpha: float
the fraction of the interval to use to set the bounds
Returns
-------
tb: numpy.ndarray (t.size,2)
the bounds of the given time array
Notes
-----
Using alpha = 0.5 will create bounds in the middle of each time
point. An alpha = 0 will use the given time as the beginning of
the interval and alpha = 1 will use the given time as the end of
the interval.
"""
if (alpha < 0) + (alpha > 1):
msg = "Alpha out of bounds, should be (0 <= %g <= 1)" % alpha
raise ValueError(msg)
if t.size == 1:
return np.asarray([[t[0], t[0]]])
dt = np.diff(t)
dt = np.hstack([dt[0], dt, dt[-1]])
tb = np.asarray([t - alpha * dt[:-1], t + (1.0 - alpha) * dt[+1:]]).T
return tb
def ConvertCalendar(t, units, calendar):
""" """
return cf.date2num(
cf.datetime(t.year, t.month, t.day, t.hour, t.minute, t.second),
units,
calendar=calendar,
)
def GetTime(var, t0=None, tf=None, convert_calendar=True, ignore_time_array=True):
""" """
# New method of handling time does not like my biggest/smallest time convention
if t0 is not None:
if np.allclose(t0, -1e20):
t0 = None
if tf is not None:
if np.allclose(tf, +1e20):
tf = None
# Get parent dataset/group
dset = var.group()
vname = "%s:%s" % (dset.filepath(), var.name)
CB = None
# What is the time dimension called in the dataset/variable?
time_name = [name for name in var.dimensions if "time" in name.lower()]
if len(time_name) == 0:
return None, None, None, None, None, None
elif len(time_name) > 1:
msg = "Ambiguous 'time' dimension in the variable %s, one of these [%s]" % (
vname,
",".join(time_name),
)
raise IOError(msg)
time_name = time_name[0]
t = dset.variables[time_name]
# Check for units on time
if "units" not in t.ncattrs():
msg = "No units given in the time variable in %s:%s" % (
dset.filepath(),
time_name,
)
raise ValueError(msg)
if "calendar" not in t.ncattrs():
msg = "No calendar given in the time variable in %s:%s" % (
dset.filepath(),
time_name,
)
raise ValueError(msg)
# If no time bounds we create them
time_bnds_name = t.bounds if "bounds" in t.ncattrs() else None
if time_bnds_name is not None:
if time_bnds_name not in dset.variables.keys():
msg = (
"Time bounds specified in %s as %s, but not a variable in the dataset, found these [%s]"
% (time_name, time_bnds_name, dset.variables.keys())
)
raise IOError(msg)
tb = dset.variables[time_bnds_name][...]
else:
tb = CreateTimeBounds(t, alpha=GuessAlpha(t))
if "climatology" in t.ncattrs():
clim_name = t.climatology
if clim_name not in dset.variables.keys():
msg = (
"Climatology bounds specified in %s as %s, but not a variable in the dataset, found these [%s]"
% (time_name, clim_name, dset.variables.keys())
)
raise IOError(msg)
CB = dset.variables[clim_name][...]
if not np.allclose(CB.shape, [12, 2]):
msg = "ILAMB only supports annual cycle style climatologies"
raise IOError(msg)
CB = np.round(CB[0, :] / 365.0 + 1850.0)
# Convert the input beginning/ending time to the current calendar/datum
if t0 is not None:
t0 = cf.num2date(t0, units="days since 1850-1-1 00:00:00", calendar="noleap")
t0 = ConvertCalendar(t0, t.units, t.calendar)
if t0 > tb[-1, 1]:
return None, None, None, None, None, None
if tf is not None:
tf = cf.num2date(tf, units="days since 1850-1-1 00:00:00", calendar="noleap")
tf = ConvertCalendar(tf, t.units, t.calendar)
if tf < tb[0, 0]:
return None, None, None, None, None, None
# Subset by the desired initial and final times
dt = np.diff(tb, axis=1)[:, 0]
begin = 0
end = t.size - 1
if t0 is not None:
begin = np.where(t0 > (tb[:, 0] - 0.01 * dt))[0]
begin = begin[-1] if begin.size > 0 else 0
if tf is not None:
end = np.where(tf < (tb[:, 1] + 0.01 * dt))[0]
end = end[0] if end.size > 0 else t.size - 1
T = np.asarray(t[begin : (end + 1)])
TB = np.asarray(tb[begin : (end + 1)])
if ignore_time_array:
T = TB.mean(axis=1)
# Are the time intervals consecutively
if not np.allclose(TB[1:, 0], TB[:-1, 1]):
msg = "Time intervals defined in %s:%s are not continuous" % (
dset.filepath(),
time_bnds_name,
)
raise ValueError(msg)
# Do the times lie in the bounds
TF = (T >= TB[:, 0]) * (T <= TB[:, 1])
if not TF.all():
index = ["%d" % i for i in np.where(~TF)[0]]
msg = (
"Times at indices [%s] do not fall inside of the corresponding bounds in %s:%s and %s"
% (",".join(index), dset.filepath(), time_name, time_bnds_name)
)
raise ValueError(msg)
# Convert time array to ILAMB default calendar / datum
try:
datum_shift = (
cf.num2date(0, "days since 1850-1-1 00:00:00", calendar=t.calendar)
- cf.num2date(0, t.units, calendar=t.calendar)
).total_seconds()
except:
msg = "Error in computing the datum: t.units = %s, t.calendar = %s" % (
t.units,
t.calendar,
)
raise ValueError(msg)
if (abs(datum_shift) > 60) or (convert_calendar and t.calendar != "noleap"):
T = cf.num2date(T, units=t.units, calendar=t.calendar)
TB = cf.num2date(TB, units=t.units, calendar=t.calendar)
for index, x in np.ndenumerate(T):
T[index] = ConvertCalendar(
x,
"days since 1850-1-1 00:00:00",
"noleap" if convert_calendar else t.calendar,
)
for index, x in np.ndenumerate(TB):
TB[index] = ConvertCalendar(
x,
"days since 1850-1-1 00:00:00",
"noleap" if convert_calendar else t.calendar,
)
cal = "noleap" if convert_calendar else t.calendar
return T.astype(float), TB.astype(float), CB, begin, end, cal
def CellAreas(lat, lon, lat_bnds=None, lon_bnds=None):
"""Given arrays of latitude and longitude, return cell areas in square meters.
Parameters
----------
lat : numpy.ndarray
a 1D array of latitudes which represent cell centroids
lon : numpy.ndarray
a 1D array of longitudes which represent cell centroids
Returns
-------
areas : numpy.ndarray
a 2D array of cell areas in [m2]
"""
from ILAMB.constants import earth_rad
if lat_bnds is not None and lon_bnds is not None:
return earth_rad**2 * np.outer(
(
np.sin(lat_bnds[:, 1] * np.pi / 180.0)
- np.sin(lat_bnds[:, 0] * np.pi / 180.0)
),
(lon_bnds[:, 1] - lon_bnds[:, 0]) * np.pi / 180.0,
)
x = np.zeros(lon.size + 1)
x[1:-1] = 0.5 * (lon[1:] + lon[:-1])
x[0] = lon[0] - 0.5 * (lon[1] - lon[0])
x[-1] = lon[-1] + 0.5 * (lon[-1] - lon[-2])
if x.max() > 181:
x -= 180
x = x.clip(-180, 180)
x *= np.pi / 180.0
y = np.zeros(lat.size + 1)
y[1:-1] = 0.5 * (lat[1:] + lat[:-1])
y[0] = lat[0] - 0.5 * (lat[1] - lat[0])
y[-1] = lat[-1] + 0.5 * (lat[-1] - lat[-2])
y = y.clip(-90, 90)
y *= np.pi / 180.0
dx = earth_rad * (x[1:] - x[:-1])
dy = earth_rad * (np.sin(y[1:]) - np.sin(y[:-1]))
areas = np.outer(dx, dy).T
return areas
def GlobalLatLonGrid(res, **keywords):
r"""Generates a latitude/longitude grid at a desired resolution
Computes 1D arrays of latitude and longitude values which
correspond to cell interfaces and centroids at a given resolution.
Parameters
----------
res : float
the desired resolution of the grid in degrees
from_zero : boolean
sets longitude convention { True:(0,360), False:(-180,180) }
Returns
-------
lat_bnd : numpy.ndarray
a 1D array of latitudes which represent cell interfaces
lon_bnd : numpy.ndarray
a 1D array of longitudes which represent cell interfaces
lat : numpy.ndarray
a 1D array of latitudes which represent cell centroids
lon : numpy.ndarray
a 1D array of longitudes which represent cell centroids
"""
from_zero = keywords.get("from_zero", False)
res_lat = keywords.get("res_lat", res)
res_lon = keywords.get("res_lon", res)
nlon = int(360.0 / res_lon) + 1
nlat = int(180.0 / res_lat) + 1
lon_bnd = np.linspace(-180, 180, nlon)
if from_zero:
lon_bnd += 180
lat_bnd = np.linspace(-90, 90, nlat)
lat = 0.5 * (lat_bnd[1:] + lat_bnd[:-1])
lon = 0.5 * (lon_bnd[1:] + lon_bnd[:-1])
return lat_bnd, lon_bnd, lat, lon
def NearestNeighborInterpolation(lat1, lon1, data1, lat2, lon2):
r"""Interpolates globally grided data at another resolution
Parameters
----------
lat1 : numpy.ndarray
a 1D array of latitudes of cell centroids corresponding to the
source data
lon1 : numpy.ndarray
a 1D array of longitudes of cell centroids corresponding to the
source data
data1 : numpy.ndarray
an array of data to be interpolated of shape = (lat1.size,lon1.size,...)
lat2 : numpy.ndarray
a 1D array of latitudes of cell centroids corresponding to the
target resolution
lon2 : numpy.ndarray
a 1D array of longitudes of cell centroids corresponding to the
target resolution
Returns
-------
data2 : numpy.ndarray
an array of interpolated data of shape = (lat2.size,lon2.size,...)
"""
rows = np.apply_along_axis(np.argmin, 1, np.abs(lat2[:, np.newaxis] - lat1))
cols = np.apply_along_axis(np.argmin, 1, np.abs(lon2[:, np.newaxis] - lon1))
data2 = data1[np.ix_(rows, cols)]
return data2
def TrueError(
lat1_bnd, lon1_bnd, lat1, lon1, data1, lat2_bnd, lon2_bnd, lat2, lon2, data2
):
r"""Computes the pointwise difference between two sets of gridded data
To obtain the pointwise error we populate a list of common cell
interfaces and then interpolate both input arrays to the composite
grid resolution using nearest-neighbor interpolation.
Parameters
----------
lat1_bnd, lon1_bnd, lat1, lon1 : numpy.ndarray
1D arrays corresponding to the latitude/longitudes of the cell
interfaces/centroids
data1 : numpy.ndarray
an array of data to be interpolated of shape = (lat1.size,lon1.size,...)
lat2_bnd, lon2_bnd, lat2, lon2 : numpy.ndarray
1D arrays corresponding to the latitude/longitudes of the cell
interfaces/centroids
data2 : numpy.ndarray
an array of data to be interpolated of shape = (lat2.size,lon2.size,...)
Returns
-------
lat_bnd, lon_bnd, lat, lon : numpy.ndarray
1D arrays corresponding to the latitude/longitudes of the cell
interfaces/centroids of the resulting error
error : numpy array
an array of the pointwise error of shape = (lat.size,lon.size,...)
"""
# combine limits, sort and remove duplicates
lat_bnd = np.hstack((lat1_bnd, lat2_bnd))
lat_bnd.sort()
lat_bnd = np.unique(lat_bnd)
lon_bnd = np.hstack((lon1_bnd, lon2_bnd))
lon_bnd.sort()
lon_bnd = np.unique(lon_bnd)
# need centroids of new grid for nearest-neighbor interpolation
lat = 0.5 * (lat_bnd[1:] + lat_bnd[:-1])
lon = 0.5 * (lon_bnd[1:] + lon_bnd[:-1])
# interpolate datasets at new grid
d1 = NearestNeighborInterpolation(lat1, lon1, data1, lat, lon)
d2 = NearestNeighborInterpolation(lat2, lon2, data2, lat, lon)
# relative to the first grid/data
error = d2 - d1
return lat_bnd, lon_bnd, lat, lon, error
def SympifyWithArgsUnits(expression, args, units):
"""Uses symbolic algebra to determine the final unit of an expression.
Parameters
----------
expression : str
the expression whose units you wish to simplify
args : dict
a dictionary of numpy arrays whose keys are the
variables written in the input expression
units : dict
a dictionary of strings representing units whose keys are the
variables written in the input expression
"""
from sympy import postorder_traversal, sympify
expression = sympify(expression)
# try to convert all arguments to same units if possible, it
# catches most use cases
keys = list(args.keys())
for i, key0 in enumerate(keys):
for key in keys[(i + 1) :]:
try:
Unit(units[key]).convert(args[key], Unit(units[key0]), inplace=True)
units[key] = units[key0]
except:
pass
for expr in postorder_traversal(expression):
ekey = str(expr)
if expr.is_Add:
# if there are scalars in the expression, these will not
# be in the units dictionary. Add them and give them an
# implicit unit of 1
keys = [str(arg) for arg in expr.args]
for key in keys:
if key not in units:
units[key] = "1"
# if we are adding, all arguments must have the same unit.
key0 = keys[0]
for key in keys:
Unit(units[key]).convert(np.ones(1), Unit(units[key0]))
units[key] = units[key0]
units[ekey] = "%s" % (units[key0])
elif expr.is_Pow:
# if raising to a power, just create the new unit
keys = [str(arg) for arg in expr.args]
units[ekey] = "(%s)%s" % (units[keys[0]], keys[1])
elif expr.is_Mul:
# just create the new unit
keys = [str(arg) for arg in expr.args]
units[ekey] = " ".join(
["(%s)" % units[key] for key in keys if key in units]
)
return sympify(str(expression), locals=args), units[ekey]
def ComputeIndexingArrays(lat2d, lon2d, lat, lon):
"""Blah.
Parameters
----------
lat : numpy.ndarray
A 1D array of latitudes of cell centroids
lon : numpy.ndarray
A 1D array of longitudes of cell centroids
"""
# Prepare the interpolator
points = np.asarray([lat2d.flatten(), lon2d.flatten()]).T
values = np.asarray(
[
(
np.arange(lat2d.shape[0])[:, np.newaxis] * np.ones(lat2d.shape[1])
).flatten(),
(
np.ones(lat2d.shape[0])[:, np.newaxis] * np.arange(lat2d.shape[1])
).flatten(),
]
).T
fcn = NearestNDInterpolator(points, values)
LAT, LON = np.meshgrid(lat, lon, indexing="ij")
gmap = fcn(LAT.flatten(), LON.flatten()).astype(int)
return gmap[:, 0].reshape(LAT.shape), gmap[:, 1].reshape(LAT.shape)
def ExtendAnnualCycle(time, cycle_data, cycle_time):
ind = np.abs((time[:, np.newaxis] % 365) - (cycle_time % 365)).argmin(axis=1)
assert (ind.max() < 12) * (ind.min() >= 0)
return cycle_data[ind]
def FromNetCDF4(
filename,
variable_name,
alternate_vars=[],
t0=None,
tf=None,
group=None,
convert_calendar=True,
):
"""Extracts data from a netCDF4 datafile for use in a Variable object.
Intended to be used inside of the Variable constructor. Some of
the return arguments will be None depending on the contents of the
netCDF4 file.
Parameters
----------
filename : str
Name of the netCDF4 file from which to extract a variable
variable_name : str
Name of the variable to extract from the netCDF4 file
alternate_vars : list of str, optional
A list of possible alternate variable names to find
t0 : float, optional
If temporal, specifying the initial time can reduce memory
usage and speed up access time.
tf : float, optional
If temporal, specifying the final time can reduce memory
usage and speed up access time.
Returns
-------
data : numpy.ma.masked_array
The array which contains the data which constitutes the variable
unit : str
The unit of the input data
name : str
The name of the variable, will be how it is saved in an output netCDF4 file
time : numpy.ndarray
A 1D array of times in days since 1850-01-01 00:00:00
time_bnds : numpy.ndarray
A 1D array of time bounds in days since 1850-01-01 00:00:00
lat : numpy.ndarray
A 1D array of latitudes of cell centroids
lon : numpy.ndarray
A 1D array of longitudes of cell centroids
area : numpy.ndarray
A 2D array of the cell areas
ndata : int
Number of data sites this data represents
depth_bnds : numpy.ndarray
A 1D array of the depth boundaries of each cell
"""
try:
dset = Dataset(filename, mode="r")
if parse_version(get_distribution("netCDF4").version) >= parse_version("1.4.1"):
dset.set_always_mask(False)
if group is None:
grp = dset
else:
grp = dset.groups[group]
except RuntimeError:
raise RuntimeError("Unable to open the file: %s" % filename)
found = False
if variable_name in grp.variables.keys():
found = True
var = grp.variables[variable_name]
else:
while alternate_vars.count(None) > 0:
alternate_vars.pop(alternate_vars.index(None))
for var_name in alternate_vars:
if var_name in grp.variables.keys():
found = True
var = grp.variables[var_name]
if not found:
alternate_vars.insert(0, variable_name)
raise RuntimeError(
"Unable to find [%s] in the file: %s" % (",".join(alternate_vars), filename)
)
# Copy attributes into a dictionary
attr = {attr: var.getncattr(attr) for attr in var.ncattrs()}
# Check on dimensions
time_name = [name for name in var.dimensions if "time" in name.lower()]
lat_name = [name for name in var.dimensions if "lat" in name.lower()]
lon_name = [name for name in var.dimensions if "lon" in name.lower()]
data_name = [
name
for name in var.dimensions
if name.lower() in ["data", "lndgrid", "gridcell"]
]
missed = [
name
for name in var.dimensions
if name not in (time_name + lat_name + lon_name + data_name)
]
# Lat/lon might be indexing arrays, find their shape
shp = None
if (
len(lat_name) == 0
and len(lon_name) == 0
and len(missed) >= 2
and len(data_name) == 0
):
# remove these dimensions from the missed variables
i, j = var.dimensions[-2], var.dimensions[-1]
if i in missed:
missed.pop(missed.index(i))
if j in missed:
missed.pop(missed.index(j))
if i in grp.variables and j in grp.variables:
i = grp.variables[i]
j = grp.variables[j]
if np.issubdtype(i.dtype, np.integer) and np.issubdtype(
j.dtype, np.integer
):
shp = [len(i), len(j)]
# Lat/lon might just be sizes
if len(lat_name) == 1 and len(lon_name) == 1:
if not (lat_name[0] in grp.variables and lon_name[0] in grp.variables):
shp = [len(grp.dimensions[lat_name[0]]), len(grp.dimensions[lon_name[0]])]
# If these were sizes, then we need to find the correct 2D lat/lon arrays
if shp is not None:
# We want to remove any false positives we might find. I don't
# want to consider variables which are 'bounds' or dimensions
# of others, nor those that don't have the correct shape.
bnds = [
grp.variables[v].bounds
for v in grp.variables
if "bounds" in grp.variables[v].ncattrs()
]
dims = [v for v in grp.variables if (v in grp.dimensions)]
poss = [
v
for v in grp.variables
if (
v not in dims
and v not in bnds
and np.allclose(shp, grp.variables[v].shape)
if len(shp) == len(grp.variables[v].shape)
else False
)
]
lat_name = [name for name in poss if "lat" in name.lower()]
lon_name = [name for name in poss if "lon" in name.lower()]
# If still ambiguous, look inside the variable attributes for
# the presence of the variable name to give further
# preference.
attrs = [str(var.getncattr(attr)) for attr in var.ncattrs()]
if len(lat_name) == 0:
raise ValueError(
"Unable to find values for the latitude dimension in %s" % (filename)
)
if len(lat_name) > 1:
tmp_name = [
name for name in lat_name if np.any([name in attr for attr in attrs])
]
if len(tmp_name) > 0:
lat_name = tmp_name
if len(lon_name) == 0:
raise ValueError(
"Unable to find values for the longitude dimension in %s" % (filename)
)
if len(lon_name) > 1:
tmp_name = [
name for name in lon_name if np.any([name in attr for attr in attrs])
]
if len(tmp_name) > 0:
lon_name = tmp_name
# A final attempt to figure out what dimensions the data is
if shp is None and not lat_name and not lon_name and "coordinates" in var.ncattrs():
dims = var.getncattr("coordinates").split()
lat_name = [dims[0]]
lon_name = [dims[1]]
# Lat dimension
if len(lat_name) == 1:
lat_name = lat_name[0]
lat_bnd_name = (
grp.variables[lat_name].bounds
if (
lat_name in grp.variables
and "bounds" in grp.variables[lat_name].ncattrs()
)
else None
)
if lat_bnd_name not in grp.variables:
lat_bnd_name = None
elif len(lat_name) >= 1:
raise ValueError(
"Ambiguous choice of values for the latitude dimension [%s] in %s"
% (",".join(lat_name), filename)
)
else:
lat_name = None
lat_bnd_name = None
# Lon dimension
if len(lon_name) == 1:
lon_name = lon_name[0]
lon_bnd_name = (
grp.variables[lon_name].bounds
if (
lon_name in grp.variables
and "bounds" in grp.variables[lon_name].ncattrs()
)
else None
)
if lon_bnd_name not in grp.variables:
lon_bnd_name = None
elif len(lon_name) >= 1:
raise ValueError(
"Ambiguous choice of values for the longitude dimension [%s] in %s"
% (",".join(lon_name), filename)
)
else:
lon_name = None
lon_bnd_name = None
# Data dimension
if len(data_name) == 1:
data_name = data_name[0]
elif len(data_name) >= 1:
raise ValueError(
"Ambiguous choice of values for the data dimension [%s] in %s"
% (",".join(data_name), filename)
)
else:
data_name = None
# The layered dimension is whatever is leftover since its name
# could be many things
if len(missed) == 1:
depth_name = missed[0]
depth_bnd_name = (
grp.variables[depth_name].bounds
if (
depth_name in grp.variables
and "bounds" in grp.variables[depth_name].ncattrs()
)
else None
)
if depth_bnd_name not in grp.variables:
depth_bnd_name = None
elif len(missed) >= 1:
raise ValueError(
"Ambiguous choice of values for the layered dimension [%s] in %s"
% (",".join(missed), filename)
)
else:
depth_name = None
depth_bnd_name = None
# Based on present values, get dimensions and bounds
t = None
t_bnd = None
lat = None
lat_bnd = None
lon = None
lon_bnd = None
depth = None
depth_bnd = None
data = None
cbounds = None
t, t_bnd, cbounds, begin, end, calendar = GetTime(
var, t0=t0, tf=tf, convert_calendar=convert_calendar
)
# Are there uncertainties?
v_bnd = None
if "bounds" in var.ncattrs():
v_bnd = var.bounds
v_bnd = grp.variables[v_bnd] if v_bnd in grp.variables.keys() else None
if begin is None:
v = var[...]
if v_bnd:
v_bnd = v_bnd[...]
else:
v = var[begin : (end + 1), ...]
if v_bnd:
v_bnd = v_bnd[begin : (end + 1), ...]
if lat_name is not None:
lat = grp.variables[lat_name][...]
if lat_bnd_name is not None:
lat_bnd = grp.variables[lat_bnd_name][...]
if lon_name is not None:
lon = grp.variables[lon_name][...]
if lon_bnd_name is not None:
lon_bnd = grp.variables[lon_bnd_name][...]
if depth_name is not None:
dunit = None
if "units" in grp.variables[depth_name].ncattrs():
dunit = grp.variables[depth_name].units
depth = grp.variables[depth_name][...]
if depth_bnd_name is not None:
depth_bnd = grp.variables[depth_bnd_name][...]
if dunit is not None:
if not (
Unit(dunit).is_convertible(Unit("m"))
or Unit(dunit).is_convertible(Unit("Pa"))
):
raise ValueError(
"Units [%s] not compatible with [m,Pa] of the layered dimension [%s] in %s"
% (dunit, depth_name, filename)
)
if Unit(dunit).is_convertible(Unit("m")):
depth = Unit(dunit).convert(depth, Unit("m"), inplace=True)
if depth_bnd is not None:
depth_bnd = Unit(dunit).convert(depth_bnd, Unit("m"), inplace=True)
if Unit(dunit).is_convertible(Unit("Pa")):
# FIX: converts the pressure to meters, but assumes it
# is coming from the atmosphere. This will be
# problematic for ocean quantities.
depth = Unit(dunit).convert(depth, Unit("Pa"), inplace=True)
Pb = 101325.0
Tb = 273.15
R = 8.3144598
g = 9.80665
M = 0.0289644
depth = -np.log(depth / Pb) * R * Tb / M / g
if depth_bnd is not None:
depth_bnd = Unit(dunit).convert(depth_bnd, Unit("Pa"), inplace=True)
depth_bnd = -np.log(depth_bnd / Pb) * R * Tb / M / g
if data_name is not None: