Repository navigation
Expand file tree
/
Copy pathutil.py
More file actions
3928 lines (2863 loc) · 132 KB
/
Copy pathutil.py
File metadata and controls
3928 lines (2863 loc) · 132 KB
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
from __future__ import (absolute_import, division, print_function)
import os
from sys import version_info
from copy import copy
from collections import OrderedDict
from collections.abc import Iterable, Mapping
from itertools import product, tee
from types import GeneratorType
import datetime as dt
from inspect import getmodule
try:
from inspect import signature
except ImportError:
from inspect import getargspec
try:
from inspect import getargvalues
except ImportError:
from inspect import getgeneratorlocals
# Needed for Python 3.4 to use apply_defaults
try:
from inspect import _empty, _VAR_POSITIONAL, _VAR_KEYWORD
except ImportError:
pass
import numpy as np
import numpy.ma as ma
from .config import xarray_enabled
from .constants import default_fill, ALL_TIMES
from .py3compat import (viewitems, viewkeys, isstr, py3range)
from .cache import cache_item, get_cached_item
from .geobnds import GeoBounds, NullGeoBounds
from .coordpair import CoordPair
from .projection import getproj
if xarray_enabled():
from xarray import DataArray
_COORD_PAIR_MAP = {"XLAT": ("XLAT", "XLONG"),
"XLONG": ("XLAT", "XLONG"),
"XLAT_M": ("XLAT_M", "XLONG_M"),
"XLONG_M": ("XLAT_M", "XLONG_M"),
"XLAT_U": ("XLAT_U", "XLONG_U"),
"XLONG_U": ("XLAT_U", "XLONG_U"),
"XLAT_V": ("XLAT_V", "XLONG_V"),
"XLONG_V": ("XLAT_V", "XLONG_V"),
"CLAT": ("CLAT", "CLONG"),
"CLONG": ("CLAT", "CLONG")}
_COORD_VARS = ("XLAT", "XLONG", "XLAT_M", "XLONG_M", "XLAT_U", "XLONG_U",
"XLAT_V", "XLONG_V", "CLAT", "CLONG")
_LAT_COORDS = ("XLAT", "XLAT_M", "XLAT_U", "XLAT_V", "CLAT")
_LON_COORDS = ("XLONG", "XLONG_M", "XLONG_U", "XLONG_V", "CLONG")
_TIME_COORD_VARS = ("XTIME",)
def is_time_coord_var(varname):
"""Return True if the input variable name is a time coordinate.
Args:
varname (:obj:`str`): The input variable name.
Returns:
:obj:`bool`: True if the input variable is a time coordinate,
otherwise False.
"""
return varname in _TIME_COORD_VARS
def get_coord_pairs(coord_varname):
"""Return a :obj:`tuple` for the variable names of the coordinate pair used
for the 2D curvilinear coordinate variable.
For example, the 'XLAT' variable will have coordinate variables of
('XLAT', 'XLONG') since the 'XLAT' variable itself is two-dimensional.
Args:
coord_varname (:obj:`str`): The coordinate variable name.
Returns:
:obj:`bool`: True if the time index is :data:`wrf.ALL_TIMES` or
:obj:`None`, otherwise False.
"""
return _COORD_PAIR_MAP[coord_varname]
def is_multi_time_req(timeidx):
"""Return True if the requested time index is for :data:`wrf.ALL_TIMES` or
:obj:`None`.
Args:
timeidx (:obj:`int`, :data:`wrf.ALL_TIMES`, or :obj:`None`): The
requested time index.
Returns:
:obj:`bool`: True if the time index is :data:`wrf.ALL_TIMES` or
:obj:`None`, otherwise False.
"""
return timeidx is None
def is_multi_file(wrfin):
"""Return True if the input argument is an iterable.
Args:
wrfin (:class:`netCDF4.Dataset`, :class:`Nio.NioFile`, or an \
iterable): WRF-ARW NetCDF
data as a :class:`netCDF4.Dataset`, :class:`Nio.NioFile`
or an iterable sequence of the aforementioned types.
Returns:
:obj:`bool`: True if the input is an iterable. False if the input
is a single NetCDF file object.
"""
return (isinstance(wrfin, Iterable) and not isstr(wrfin))
def has_time_coord(wrfnc):
"""Return True if the input file or sequence contains the time
coordinate variable.
The time coordinate is named 'XTIME'.
Args:
wrfnc (:class:`netCDF4.Dataset` or :class:`Nio.NioFile`): A single
NetCDF file object.
Returns:
:obj:`bool`: True if the netcdf file contains the time coordinate
variable, False otherwise.
"""
return "XTIME" in wrfnc.variables
def is_mapping(wrfin):
"""Return True if the input file or sequence is a mapping type.
Args:
wrfin (:class:`netCDF4.Dataset`, :class:`Nio.NioFile`, or an \
iterable): WRF-ARW NetCDF
data as a :class:`netCDF4.Dataset`, :class:`Nio.NioFile`
or an iterable sequence of the aforementioned types.
Returns:
:obj:`bool`: True if the input is a mapping type, False otherwise.
"""
return isinstance(wrfin, Mapping)
def _generator_copy(gen):
"""Return a copy of a generator.
This function instantiates a new generator object using the arguments
passed to the original.
Args:
gen (:class:`types.GeneratorType`): A generator object.
Note:
In order for this to work correctly, the generator cannot modify
the original construction arguments.
Returns:
:class:`types.GeneratorType`: A copy of the generator object.
"""
funcname = gen.__name__
# This is for generator expressions. Only solution is to tee the
# original generator.
if funcname == "<genexpr>":
return tee(gen)
try:
argvals = getargvalues(gen.gi_frame)
except NameError:
argvals = getgeneratorlocals(gen)
module = getmodule(gen.gi_frame)
if module is not None:
try:
try:
argd = {key: argvals.locals[key] for key in argvals.args}
res = module.get(funcname)(**argd)
except AttributeError:
res = getattr(module, funcname)(**argd)
except Exception:
# This is the old way it used to work, but it looks like this was
# fixed by Python.
try:
res = module.get(funcname)(**argvals.locals)
except AttributeError:
res = getattr(module, funcname)(**argvals.locals)
else:
# Created in jupyter or the python interpreter
import __main__
try:
argd = {key: argvals.locals[key] for key in argvals.args}
res = getattr(__main__, funcname)(**argd)
except Exception:
# This was the old way it used to work, but appears to have
# been fixed by Python.
res = getattr(__main__, funcname)(**argvals.locals)
return res
def test():
q = [1, 2, 3]
for i in q:
yield i
class TestGen(object):
def __init__(self, count=3):
self._total = count
self._i = 0
def __iter__(self):
return self
def next(self):
if self._i >= self._total:
raise StopIteration
else:
val = self._i
self._i += 1
return val
# Python 3
def __next__(self):
return self.next()
def latlon_coordvars(ncvars):
"""Return the first found latitude and longitude coordinate names from a
NetCDF variable dictionary.
This function searches the dictionary structure for NetCDF variables
and returns the first found latitude and longitude coordinate
names (typically 'XLAT' and 'XLONG').
Args:
ncvars (:obj:`dict`): A NetCDF variable dictionary object.
Returns:
:obj:`tuple`: The latitude and longitude coordinate name pairs as
(lat_coord_name, lon_coord_name).
"""
lat_coord = None
lon_coord = None
for name in _LAT_COORDS:
if name in viewkeys(ncvars):
lat_coord = name
break
for name in _LON_COORDS:
if name in viewkeys(ncvars):
lon_coord = name
break
return lat_coord, lon_coord
def is_coordvar(varname):
"""Returns True if the variable is a coordinate variable.
Args:
varname (:obj:`str`): The variable name.
Returns:
:obj:`bool`: True if the variable is a coordinate variable,
otherwise False.
"""
return varname in _COORD_VARS
class IterWrapper(Iterable):
"""A wrapper class for generators and custom iterable classes that returns
a new iterator to the start of the sequence when
:meth:`IterWrapper.__iter__` is called.
If the wrapped object is a generator, a copy of the generator is
constructed and returned when :meth:`IterWrapper.__iter__` is called.
If the wrapped object is a custom type, then the :meth:`copy.copy` is
called and a new instance is returned. In both cases, the original
iterable object is unchanged.
Note:
Do not increment the wrapped iterable outside of this wrapper.
"""
def __init__(self, wrapped):
"""Initialize an :class:`wrf.IterWrapper` object.
Args:
wrapped (an iterable object): Any iterable object that contains the
*__iter__* method.
"""
self._wrapped = wrapped
def __iter__(self):
"""Return an iterator to the start of the sequence.
Returns:
An iterator to the start of the sequence.
"""
if isinstance(self._wrapped, GeneratorType):
gen_copy = _generator_copy(self._wrapped)
# If a tuple comes back, then this is a generator expression,
# so store the first tee'd item, then return the other
if isinstance(gen_copy, tuple):
self._wrapped = gen_copy[0]
return gen_copy[1]
return gen_copy
else:
obj_copy = copy(self._wrapped)
return obj_copy.__iter__()
def get_iterable(wrfseq):
"""Returns a resettable iterable object.
In this context, resettable means that when :meth:`object.__iter__`
is called, the iterable returned always points to the first element
in the sequence, similar to how the list and tuple behave.
Args:
wrfseq (iterable): An iterable type, which includes lists, tuples,
dictionaries, generators, and user-defined classes.
Returns:
iterable: A resettable iterator object.
"""
if not is_multi_file(wrfseq):
return wrfseq
else:
if not is_mapping(wrfseq):
if isinstance(wrfseq, (list, tuple, IterWrapper)):
return wrfseq
else:
return IterWrapper(wrfseq) # generator/custom iterable class
else:
if isinstance(wrfseq, dict):
return wrfseq
else:
return dict(wrfseq) # generator/custom iterable dict class
# Helper to extract masked arrays from DataArrays that convert to NaN
def to_np(array):
"""Return the :class:`numpy.ndarray` contained in an
:class:`xarray.DataArray` instance.
If the :class:`xarray.DataArray` instance does not contain a *_FillValue*
or *missing_value* attribute, then this routine simply returns the
:attr:`xarray.DataArray.values` attribute. If the
:class:`xarray.DataArray` object contains a *_FillValue* or *missing_value*
attribute, then this routine returns a :class:`numpy.ma.MaskedArray`
instance, where the NaN values (used by xarray to represent missing data)
are replaced with the fill value.
If the object passed in to this routine is not an
:class:`xarray.DataArray` instance, then this routine simply returns the
passed in object. This is useful in situations where you do not know
if you have an :class:`xarray.DataArray` or a :class:`numpy.ndarray` and
simply want a :class:`numpy.ndarray` returned.
Args:
array (:class:`xarray.DataArray`, :class:`numpy.ndarray`, or any \
object): Can be any object type, but is generally
used with :class:`xarray.DataArray` or :class:`numpy.ndarray`.
Returns:
:class:`numpy.ndarray` or :class:`numpy.ma.MaskedArray`: The
extracted array or the *array* object if *array* is not a
:class:`xarray.DataArray` object..
"""
try:
fill_value = array.attrs["_FillValue"]
except AttributeError:
result = array # Not a DataArray
except KeyError:
result = array.values # Does not have missing values
else:
result = ma.masked_invalid(array.values, copy=False)
result.set_fill_value(fill_value)
return result
# Helper utilities for metadata
class either(object):
"""A callable class that determines which variable is present in the
file.
This is used in situations where the same variable type has different names
depending on the type of file used. For example, in a WRF output file,
'P' is used for pressure, whereas in a met_em file, pressure is named
'PRES'.
Methods:
__call__(wrfin): Return the variable that is present in the file.
Args:
wrfin (:class:`netCDF4.Dataset`, :class:`Nio.NioFile`, or an \
iterable): WRF-ARW NetCDF
data as a :class:`netCDF4.Dataset`, :class:`Nio.NioFile`
or an iterable sequence of the aforementioned types.
Returns:
:obj:`str`: The variable name that is present in the file.
Attributes:
varnames (sequence): A sequence of possible variable names.
"""
def __init__(self, *varnames):
"""Initialize an :class:`either` object.
Args:
*varnames (sequence): A sequence of possible variable names.
"""
self.varnames = varnames
def __call__(self, wrfin):
if is_multi_file(wrfin):
if not is_mapping(wrfin):
wrfin = next(iter(wrfin))
else:
entry = wrfin[next(iter(viewkeys(wrfin)))]
return self(entry)
for varname in self.varnames:
if varname in wrfin.variables:
return varname
raise ValueError("{} are not valid variable names".format(
self.varnames))
# This should look like:
# [(0, (-3,-2)), # variable 1
# (1, -1)] # variable 2
class combine_dims(object):
"""A callable class that mixes dimension sizes from different function
arguments.
This callable object is used for determining the output size for the
extension module functions. The class is initialized with a sequence of
pairs, where the first value is the function argument index. The second
value is the dimension index(es) to use. The second value can be a
single integer or a sequence if multiple dimensions are used.
Methods:
__call__(*args): Return a tuple with the combined dimension sizes.
Args:
*args: The function arguments from which to extract the
dimensions sizes.
Returns:
:obj:`tuple`: The shape for the combined dimensions.
Attributes:
pairs (sequence): A sequence representing how to combine the
dimensions.
Example:
.. code-block:: python
# Take the -3, and -2 dimension sizes from argument 0
# Then take the -1 dimension size from argument 1
pairs = [(0, (-3, -2), (1, -1)]
combo = combine_dims(pairs)
"""
def __init__(self, pairs):
"""Initialize a :class:`combine_dims` object.
Args:
pairs (sequence): A sequence where each element is a pair
(:obj:`tuple`), with the first element being the function
argument index and the second value being either an integer
or sequence for the dimension size indexes to use.
"""
self.pairs = pairs
def __call__(self, *args):
result = []
for pair in self.pairs:
var = args[pair[0]]
dimidxs = pair[1]
if isinstance(dimidxs, Iterable):
for dimidx in dimidxs:
result.append(var.shape[dimidx])
else:
result.append(var.shape[dimidxs])
return tuple(result)
class from_var(object):
"""A callable class that retrieves attributes from the function argument.
If the function argument is not of type :class:`xarray.DataArray`, then
None will be returned.
It is assumed that the function has been wrapped using the :mod:`wrapt`
module.
Methods:
__call__(wrapped, *args, **kwargs): Return the attribute found in \
the function arguments.
Args:
wrapped: The wrapped function, as used by the :mod:`wrapt`
module.
*args: The function arguments.
**kwargs: The function keyword arguments.
Returns:
:obj:`object`: The requested attribute.
Attributes:
varname (:obj:`str`): The variable name.
attribute (:obj:`str`): The attribute name.
"""
def __init__(self, varname, attribute):
"""Initialize a :class:`from_var` object.
Args:
varname (:obj:`str`): The variable name.
attribute (:obj:`str`): The attribute name.
"""
self.varname = varname
self.attribute = attribute
def __call__(self, wrapped, *args, **kwargs):
vard = from_args(wrapped, (self.varname,), *args, **kwargs)
var = None
if vard is not None:
var = vard[self.varname]
try:
return var.attrs.get(self.attribute, None)
except AttributeError:
return None
def _corners_moved(wrfnc, first_ll_corner, first_ur_corner, latvar, lonvar):
"""Return True if the corner points have moved.
This function is used to test for a moving domain, since the WRF output
does not set any flags in the file for this. The test will be performed
for all time steps in the NetCDF file.
Args:
wrfnc (:class:`netCDF4.Dataset` or :class:`Nio.NioFile`): A single
NetCDF file object.
first_ll_corner (:obj:`tuple`): A (latitude, longitude) pair for the
lower left corner found in the initial file.
first_ur_corner (:obj:`tuple`): A (latitude, longitude) pair for the
upper right corner found in the initial file.
latvar (:obj:`str`): The latitude variable name to use.
lonvar (:obj:`str`: The longitude variable name to use.
Returns:
:obj:`bool`: True if the corner points have moved, False otherwise.
"""
lats = wrfnc.variables[latvar][:]
lons = wrfnc.variables[lonvar][:]
# Need to check all times
for i in py3range(lats.shape[-3]):
start_idxs = [0] * len(lats.shape) # PyNIO does not support ndim
start_idxs[-3] = i
start_idxs = tuple(start_idxs)
end_idxs = [-1] * len(lats.shape)
end_idxs[-3] = i
end_idxs = tuple(end_idxs)
if (first_ll_corner[0] != lats[start_idxs]
or first_ll_corner[1] != lons[start_idxs]
or first_ur_corner[0] != lats[end_idxs]
or first_ur_corner[1] != lons[end_idxs]):
return True
return False
def is_moving_domain(wrfin, varname=None, latvar=either("XLAT", "XLAT_M"),
lonvar=either("XLONG", "XLONG_M"), _key=None):
"""Return True if the domain is a moving nest.
This function is used to test for a moving domain, since the WRF output
does not set any flags in the file for this. The test will be performed
for all files in any sequences and across all times in each file.
This result is cached internally, so this potentially lengthy check is
only done one time for any given *wrfin* parameter.
Args:
wrfin (:class:`netCDF4.Dataset`, :class:`Nio.NioFile`, or an \
iterable): WRF-ARW NetCDF
data as a :class:`netCDF4.Dataset`, :class:`Nio.NioFile`
or an iterable sequence of the aforementioned types.
varname (:obj:`str`, optional): A specific NetCDF variable to test,
which must contain a 'coordinates' attribute. If unspecified,
The *latvar* and *lonvar* parameters are used. Default is None.
first_ur_corner (:obj:`tuple`): A (latitude, longitude) pair for the
upper right corner found in the initial file.
latvar (:obj:`str` or :class:`either`, optional): The latitude variable
name. Default is :class:`either('XLAT', 'XLAT_M')`.
lonvar (:obj:`str` or :class:`either`, optional): The latitude variable
name. Default is :class:`either('XLAT', 'XLAT_M')`.
_key (:obj:`int`, optional): A caching key. This is used for internal
purposes only. Default is None.
Returns:
:obj:`bool`: True if the domain is a moving nest, False otherwise.
"""
if isinstance(latvar, either):
latvar = latvar(wrfin)
if isinstance(lonvar, either):
lonvar = lonvar(wrfin)
# In case it's just a single file
if not is_multi_file(wrfin):
wrfin = [wrfin]
# Slow, but safe. Compare the corner points to the first item and see
# any move. User iterator protocol in case wrfin is not a list/tuple.
if not is_mapping(wrfin):
wrf_iter = iter(wrfin)
first_wrfnc = next(wrf_iter)
else:
# Currently only checking the first dict entry.
dict_key = next(iter(viewkeys(wrfin)))
entry = wrfin[dict_key]
key = _key[dict_key] if _key is not None else None
return is_moving_domain(entry, varname, latvar, lonvar, key)
# The long way of checking all lat/lon corner points. Doesn't appear
# to be a shortcut in the netcdf files.
if varname is not None:
try:
coord_str = getattr(first_wrfnc.variables[varname], "coordinates")
# scipy.io.netcdf stores attributes as bytes rather than str
if isinstance(coord_str, str):
coord_names = coord_str.split()
else:
coord_names = coord_str.decode().split()
except AttributeError:
# Variable doesn't have a coordinates attribute, use the
# arguments
lon_coord = lonvar
lat_coord = latvar
else:
for name in coord_names:
if name in _LAT_COORDS:
lat_coord = name
continue
if name in _LON_COORDS:
lon_coord = name
continue
else:
lon_coord = lonvar
lat_coord = latvar
# See if there is a cached value
product = "is_moving_{}_{}".format(lat_coord, lon_coord)
moving = get_cached_item(_key, product)
if moving is not None:
return moving
# Need to search all the files
lats = first_wrfnc.variables[lat_coord][:]
lons = first_wrfnc.variables[lon_coord][:]
zero_idxs = [0]*len(lats.shape) # PyNIO doesn't have ndim
last_idxs = list(zero_idxs)
last_idxs[-2:] = [-1]*2
zero_idxs = tuple(zero_idxs)
last_idxs = tuple(last_idxs)
lat0 = lats[zero_idxs]
lat1 = lats[last_idxs]
lon0 = lons[zero_idxs]
lon1 = lons[last_idxs]
ll_corner = (lat0, lon0)
ur_corner = (lat1, lon1)
# Need to check if the first file is moving, might be a single
# file with multiple times
if _corners_moved(first_wrfnc, ll_corner, ur_corner, lat_coord, lon_coord):
cache_item(_key, product, True)
return True
# Now check any additional files
while True:
try:
wrfnc = next(wrf_iter)
except StopIteration:
break
else:
if _corners_moved(wrfnc, ll_corner, ur_corner,
lat_coord, lon_coord):
cache_item(_key, product, True)
return True
cache_item(_key, product, False)
return False
def _get_global_attr(wrfnc, attr):
"""Return the global attribute.
Args:
wrfnc (:class:`netCDF4.Dataset`, :class:`Nio.NioFile`): A single
WRF NetCDF file object.
attr (:obj:`str`): The attribute name.
Returns:
:obj:`object`: The global attribute.
"""
val = getattr(wrfnc, attr, None)
# PyNIO puts single values in to an array
if isinstance(val, np.ndarray):
if len(val) == 1:
return val[0]
return val
def extract_global_attrs(wrfin, attrs):
"""Return the global attribute(s).
If the *wrfin* parameter is a sequence, then only the first element is
used, so the entire sequence must have the same global attributes.
Args:
wrfin (:class:`netCDF4.Dataset`, :class:`Nio.NioFile`, or an \
iterable): WRF-ARW NetCDF
data as a :class:`netCDF4.Dataset`, :class:`Nio.NioFile`
or an iterable sequence of the aforementioned types.
attrs (:obj:`str`, sequence): The attribute name
or a sequence of attribute names.
Returns:
:obj:`dict`: A mapping of attribute_name to value.
"""
if isstr(attrs):
attrlist = [attrs]
else:
attrlist = attrs
multifile = is_multi_file(wrfin)
if multifile:
if not is_mapping(wrfin):
wrfin = next(iter(wrfin))
else:
entry = wrfin[next(iter(viewkeys(wrfin)))]
return extract_global_attrs(entry, attrs)
return {attr: _get_global_attr(wrfin, attr) for attr in attrlist}
def extract_dim(wrfin, dim):
"""Return the dimension size for the specified dimension name.
Args:
wrfin (:class:`netCDF4.Dataset`, :class:`Nio.NioFile`, or an \
iterable): WRF-ARW NetCDF
data as a :class:`netCDF4.Dataset`, :class:`Nio.NioFile`
or an iterable sequence of the aforementioned types.
dim (:obj:`str`): The dimension name.
Returns:
:obj:`int`: The dimension size.
"""
if is_multi_file(wrfin):
if not is_mapping(wrfin):
wrfin = next(iter(wrfin))
else:
entry = wrfin[next(iter(viewkeys(wrfin)))]
return extract_dim(entry, dim)
d = wrfin.dimensions[dim]
if not isinstance(d, int):
try:
return len(d) # netCDF4
except TypeError: # scipy.io.netcdf
# Scipy can't handled unlimited dimensions, so now we have to
# figure it out
try:
s = wrfin.variables["P"].shape
except Exception:
raise ValueError("unsupported NetCDF reader")
else:
return s[-4]
return d # PyNIO
def _combine_dict(wrfdict, varname, timeidx, method, meta, _key):
"""Return an array object from a mapping input.
The resulting array is the combination of all sequences associated with
each key in the dictionary. The leftmost dimension will be the keys. The
rightmost dimensions are the dimensions for the aggregated sequences of
arrays, using either the 'cat' or 'join' *method* parameter value.
If dictionaries are nested, then the outermost dictionary keys will be the
leftmost dimension, followed by each subsequent dictionary's keys.
If the order of the keys (and leftmost dimension ordering) matters, it is
recommended that an :class:`OrderedDict` be used instead of a normal
dictionary. Otherwise, the leftmost dimension will be ordered by the
iteration order.
Args:
wrfdict (mapping): A mapping of key to an array or
key to a sequence of arrays.
varname (:obj:`str`) : The variable name.
timeidx (:obj:`int` or :data:`wrf.ALL_TIMES`, optional): The
desired time index. This value can be a positive integer,
negative integer, or
:data:`wrf.ALL_TIMES` (an alias for None) to return
all times in the file or sequence. The default is 0.
method (:obj:`str`, optional): The aggregation method to use for
sequences. Must be either 'cat' or 'join'.
'cat' combines the data along the Time dimension.
'join' creates a new dimension for the file index.
The default is 'cat'.
meta (:obj:`bool`, optional): Set to False to disable metadata and
return :class:`numpy.ndarray` instead of
:class:`xarray.DataArray`. Default is True.
_key (:obj:`int`, optional): Cache key for the coordinate variables.
This is used for internal purposes only. Default is None.
Returns:
:class:`xarray.DataArray` or :class:`numpy.ndarray`: If xarray is
enabled and the *meta* parameter is True, then the result will be a
:class:`xarray.DataArray` object. Otherwise, the result will be a
:class:`numpy.ndarray` object with no metadata.
"""
keynames = []
numkeys = len(wrfdict)
key_iter = iter(viewkeys(wrfdict))
first_key = next(key_iter)
keynames.append(first_key)
is_moving = is_moving_domain(wrfdict, varname, _key=_key)
_cache_key = _key[first_key] if _key is not None else None
first_array = _extract_var(wrfdict[first_key], varname,
timeidx, is_moving=is_moving, method=method,
squeeze=False, cache=None, meta=meta,
_key=_cache_key)
# Create the output data numpy array based on the first array
outdims = [numkeys]
outdims += first_array.shape
outdata = np.empty(outdims, first_array.dtype)
outdata[0, :] = first_array[:]
idx = 1
while True:
try:
key = next(key_iter)
except StopIteration: