-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathavariable.py
1933 lines (1619 loc) · 64.2 KB
/
avariable.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
# Automatically adapted for numpy.oldnumeric Aug 01, 2007 by
# Further modified to be pure new numpy June 24th 2008
"CDMS Variable objects, abstract interface"
import numpy
import string
import re
import warnings
from .cdmsobj import CdmsObj
import cdms2
from .slabinterface import Slab
from .sliceut import splitSliceExt, splitSlice
from .error import CDMSError
from .axis import axisMatchIndex, axisMatchAxis, axisMatches, unspecified, CdtimeTypes, AbstractAxis
from . import selectors
import copy
from .mvCdmsRegrid import CdmsRegrid, getBoundList, _getCoordList
from regrid2.mvGenericRegrid import guessPeriodicity
# import PropertiedClasses
from .convention import CF1
from .grid import AbstractRectGrid
# import internattr
from six import string_types
InvalidRegion = "Invalid region: "
OutOfRange = "Coordinate interval is out of range or intersection has no data: "
NotImplemented = "Child of AbstractVariable failed to implement: "
# Backward compatibility with numpy behavior
_numeric_compatibility = False
# False: return scalars from 0-D slices
# MV axis=None by default
# True: return 0-D arrays
# MV axis=1 by default
def getMinHorizontalMask(var):
"""
Get the minimum mask associated with 'x' and 'y'
(i.e. with the min number of ones) across all axes
Parameters
----------
var : CDMS variable with a mask
N/A : None
Returns
-------
mask array or None : if order 'x' and 'y' were not found
"""
from distarray import MultiArrayIter
if not hasattr(var, 'mask'):
return None
shp = var.shape
ndims = len(shp)
order = var.getOrder() # e.g. 'zxty-', ndims = 5
# run a few checks
numX = order.count('x')
numY = order.count('y')
num_ = order.count('-')
hasXY = (numX == 1) and (numY == 1)
if numX + numY + num_ < 2:
msg = """
Not able to locate the horizontal (y, x) axes for order = %s in getMinHorizontalMask
""" % str(order)
raise CDMSError(msg)
ps = [] # index position of x/y, e.g. [1,3]
es = [] # end indices, sizes of x/y axes
nonHorizShape = []
found = False
for i in range(ndims - 1, -1, -1):
# iterate backwards because the horizontal
# axes are more likely to be last
o = order[i]
# curvilinear coordinates have '-' in place of
# x or y, also check for '-' but exit if we think
# we found the x and y coords
if not found and (o in 'xy') or (not hasXY and o == '-'):
ps = [i, ] + ps
es = [shp[i], ] + es
if len(ps) == 2:
found = True
else:
nonHorizShape = [shp[i], ] + nonHorizShape
if len(ps) == 2:
# found all the horizontal axes, start with mask
# set to invalid everywhere
mask = numpy.ones(es, numpy.bool8)
# iterate over all non-horizontal axes, there can be as
# many as you want...
for it in MultiArrayIter(nonHorizShape):
inds = it.getIndices() # (i0, i1, i2)
# build the slice operator, there are three parts
# (head, middle, and tail), some parts may be
# missing
# slce = 'i0,' + ':,' + 'i1,' + ':,' + 'i2,'
slce = ('%d,' * ps[0]) % tuple(inds[:ps[0]]) + ':,' \
+ ('%d,' * (ps[1] - ps[0] - 1)) % tuple(inds[ps[0]:ps[1] - 1]) \
+ ':,' + ('%d,' * (ndims - ps[1] - 1)
) % tuple(inds[ps[1] - 1:])
# evaluate the slice for this time, level....
mask &= eval('var.mask[' + slce + ']')
return mask
else:
msg = """
Could not find all the horizontal axes for order = %s in getMinHorizontalMask
""" % str(order)
raise CDMSError(msg)
return None
def setNumericCompatibility(mode):
global _numeric_compatibility
if mode is True or mode == 'on':
_numeric_compatibility = True
elif mode is False or mode == 'off':
_numeric_compatibility = False
def getNumericCompatibility():
return _numeric_compatibility
class AbstractVariable(CdmsObj, Slab):
"""Not to be called by users.
Parameters
----------
variableNode
is the variable tree node, if any.
parent
is the containing dataset instance.
"""
def info(self, flag=None, device=None):
Slab.info(self, flag, device)
def __init__(self, parent=None, variableNode=None):
if variableNode is not None and variableNode.tag != 'variable':
raise CDMSError('Node is not a variable node')
CdmsObj.__init__(self, variableNode)
val = self.__cdms_internals__ + ['id', 'domain']
self.___cdms_internals__ = val
Slab.__init__(self)
self.id = None # Transient variables key on this to create a default ID
self.parent = parent
self._grid_ = None # Variable grid, if any
if not hasattr(self, 'missing_value'):
self.missing_value = None
else:
if isinstance(self.missing_value, bytes):
self.missing_value = None
elif isinstance(self.missing_value, string_types):
self.missing_value = None
elif numpy.isnan(self.missing_value):
self.missing_value = None
# Reminder: children to define self.shape and set self.id
def __array__(self, t=None, context=None): # Numeric, ufuncs call this
return numpy.ma.filled(self.getValue(squeeze=0))
def __call__(self, *args, **kwargs):
"""
Selection of a subregion using selectors.
Parameters
----------
raw : if set to 1, return numpy.ma only
squeeze : if set to 1, eliminate any dimension of length 1
grid : if given, result is regridded ont this grid
order : if given, result is permuted into this order
Returns
-------
Subregion selected
"""
# separate options from selector specs
d = kwargs.copy()
raw = d.setdefault('raw', 0)
squeeze = d.setdefault('squeeze', 0)
grid = d.setdefault('grid', None)
order = d.setdefault('order', None)
del d['squeeze'], d['grid'], d['order'], d['raw']
# make the selector
s = selectors.Selector(*args, **d)
# get the selection
return s.unmodified_select(self, raw=raw,
squeeze=squeeze,
order=order,
grid=grid)
select = __call__
def rank(self):
return len(self.shape)
def _returnArray(self, ar, squeeze, singles=None):
# ar is a Numeric array, numpy.ma, or scalar, possibly numpy.ma.masked.
# job is to make sure we return an numpy.ma or a scalar.
# If singles is not None, squeeze dimension indices in singles
inf = 1.8e308
if isinstance(ar, cdms2.tvariable.TransientVariable):
result = numpy.ma.array(ar._data, mask=ar.mask)
# already numpy.ma, only need squeeze.
elif numpy.ma.isMaskedArray(ar):
result = ar
elif isinstance(ar, numpy.ndarray):
missing = self.getMissing()
if missing is None:
result = numpy.ma.masked_array(ar)
elif missing == inf or missing != missing: # (x!=x) ==> x is NaN
result = numpy.ma.masked_object(ar, missing, copy=0)
elif ar.dtype.char == 'c' or ar.dtype.char == 'S':
# umath.equal is not implemented
resultmask = (ar == missing)
if not resultmask.any():
resultmask = numpy.ma.nomask
result = numpy.ma.masked_array(
ar, mask=resultmask, fill_value=missing).astype(str)
else:
result = numpy.ma.masked_values(ar, missing, copy=0)
elif ar is numpy.ma.masked:
return ar
else: # scalar, but it might be the missing value
missing = self.getMissing()
if missing is None:
return ar # scalar
else:
result = numpy.ma.masked_values(ar, missing, copy=0)
squoze = 0
if squeeze:
n = 1
newshape = []
for s in result.shape:
if s == 1:
squoze = 1
continue
else:
n = n * s
newshape.append(s)
elif singles is not None:
n = 1
newshape = []
oldshape = result.shape
for i in range(len(oldshape)):
if i in singles:
squoze = 1
continue
else:
s = oldshape[i]
n = n * s
newshape.append(s)
else:
n = numpy.ma.size(result)
if n == 1 and squeeze:
return numpy.ma.ravel(result)[0] # scalar or masked
if squoze:
result.shape = newshape
return result
def generateGridkey(self, convention, vardict):
"""Determine if the variable is gridded.
Parameters
----------
convention : Metadata convention class
vardict : Variable metedata
Returns
-------
((latname, lonname, order, maskname, class), lat, lon) if gridded
(None, None, None) if not gridded """
lat, nlat = convention.getVarLatId(self, vardict)
lon, nlon = convention.getVarLonId(self, vardict)
if (lat is not None) and (lat is lon):
raise CDMSError(
"Axis %s is both a latitude and longitude axis! Check standard_name and/or axis attributes." %
lat.id)
# Check for 2D grid
if (lat is None) or (lon is None):
return None, lat, lon
# Check for a rectilinear grid
if isinstance(lat, AbstractAxis) and isinstance(
lon, AbstractAxis) and (lat.rank() == lon.rank() == 1):
return self.generateRectGridkey(lat, lon), lat, lon
# Check for a curvilinear grid:
if lat.rank() == lon.rank() == 2:
# check that they are defined on the same indices as self
vardomain = self.getAxisIds()
allok = 1
for axisid in lat.getAxisIds():
if axisid not in vardomain:
allok = 0
break
if allok:
for axisid in lon.getAxisIds():
if axisid not in vardomain:
allok = 0
break
# It's a curvilinear grid
if allok:
if hasattr(lat, 'maskid'):
maskid = lat.maskid
else:
maskid = ''
return (lat.id, lon.id, 'yx', maskid, 'curveGrid'), lat, lon
# Check for a generic grid:
if lat.rank() == lon.rank() == 1:
# check that they are defined on the same indices as self
vardomain = self.getAxisIds()
allok = 1
for axisid in lat.getAxisIds():
if axisid not in vardomain:
allok = 0
break
if allok:
for axisid in lon.getAxisIds():
if axisid not in vardomain:
allok = 0
break
# It's a generic grid
if allok:
if hasattr(lat, 'maskid'):
maskid = lat.maskid
else:
maskid = ''
return (lat.id, lon.id, 'yx', maskid, 'genericGrid'), lat, lon
return None, lat, lon
def generateRectGridkey(self, lat, lon):
"""Determine if the variable is gridded, rectilinear.
Parameters
----------
lat : latitude axis
lon : longitude axis
Returns
-------
(latname, lonname, order, maskname, class) if gridded, None if not gridded."""
ilat = ilon = -1
k = 0
for axis in self.getAxisList():
if axis is lon:
ilon = k
elif axis is lat:
ilat = k
k += 1
if ilat == -1:
raise CDMSError(
"Cannot find latitude axis; check standard_name and/or axis attributes")
if ilon == -1:
raise CDMSError(
"Cannot find longitude axis; check standard_name and/or axis attributes")
if ilat < ilon:
order = "yx"
else:
order = "xy"
gridkey = (lat.id, lon.id, order, '', 'rectGrid')
return gridkey
def isAbstractCoordinate(self):
return 0
# Set the variable grid
def setGrid(self, grid):
if grid is None:
gridok = 1
else:
alist = [d[0] for d in self.getDomain()]
gridok = grid.checkAxes(alist)
if not gridok:
raise CDMSError(
"grid does not match axes for variable %s" %
self.id)
self._grid_ = grid
def getDomain(self):
"Get the list of axes"
raise CDMSError("getDomain not overriden in child")
def getConvention(self):
"Get the metadata convention associated with this object."
if hasattr(self, 'parent') and self.parent is not None:
result = self.parent._convention_
else:
result = CF1
return result
# A child class may want to override this
def getAxis(self, n):
"""Get the n-th axis.
Parameters
----------
n : Axis number
Returns
-------
if n < 0: n = n + self.rank()
self.getDomain()[n][0]"""
if n < 0:
n = n + self.rank()
return self.getDomain()[n][0]
def getAxisIndex(self, axis_spec):
"""Get the index of the axis specificed by axis_spec.
Parameters
----------
axis_spec :
Returns
-------
the axis index or -1 if no match is found.
"""
for i in range(self.rank()):
if axisMatches(self.getAxis(i), axis_spec):
return i
return -1
def hasCellData(self):
"""
If any of the variable's axis has explicit bounds, we have cell data
otherwise we have point data.
Returns
-------
True or False if axis has cell data.
"""
for axis in self.getAxisList():
if (axis.getExplicitBounds() is not None):
return True
return False
def getAxisListIndex(self, axes=None, omit=None, order=None):
"""Get Axis List Index
Returns
-------
a list of indices of axis objects
Notes
-----
If axes is **not** `None`, include only certain axes.
less the ones specified in omit.
If axes is `None`, use all axes of this variable.
Other specificiations are as for axisMatchIndex.
"""
return axisMatchIndex(self.getAxisList(), axes, omit, order)
def getAxisList(self, axes=None, omit=None, order=None):
"""Get the list of axis objects
Notes
If axes is **not** `None`, include only certain axes.
If omit is **not** `None`, omit those specified by omit.
Arguments omit or axes may be as specified in axisMatchAxis
order is an optional string determining the output order
"""
alist = [d[0] for d in self.getDomain()]
return axisMatchAxis(alist, axes, omit, order)
def getAxisIds(self):
"""Get a list of axis identifiers.
Returns
-------
array list of axis ids"""
return [x[0].id for x in self.getDomain()]
# Return the grid
def getGrid(self):
return self._grid_
def getMissing(self, asarray=0):
"""Get Missing
Parameters
----------
asarray : '0' : scalar
'1' : numpy array
Returns
-------
the missing value as a scalar, or as a numpy array if asarray==1"""
if hasattr(self, 'missing_value'):
try:
mv = self.missing_value.item()
except BaseException:
mv = self.missing_value
if mv is None and hasattr(self, '_FillValue'):
mv = self._FillValue
if asarray == 0 and isinstance(mv, numpy.ndarray):
mv = mv[0]
if isinstance(mv, string_types) and self.dtype.char not in [
'?', 'c', 'O', 'S']:
try:
mv = float(mv)
except BaseException:
if hasattr(self, '_FillValue'):
try:
mv = float(self._FillValue)
except BaseException:
mv = None
else:
mv = None
return mv
def _setmissing(self, name, value):
self.setMissing(value)
def setMissing(self, value):
"""Set the missing value.
Parameters
----------
value : scalar, a single-valued numpy array, or None.
Note :
The value is cast to the same type as the variable."""
# Check for None first, so that constructors can
# set missing_value before typecode() is initialized.
if value is None:
self._basic_set('missing_value', value)
return
selftype = self.typecode()
valuetype = type(value)
if valuetype is numpy.ndarray:
value = value.astype(selftype).item()
elif isinstance(value, numpy.floating) or isinstance(value, numpy.integer):
value = numpy.array([value], selftype)
elif valuetype in [float, int, int, complex]:
try:
value = numpy.array([value], selftype)
# Set fill value when ar[i:j] returns a masked value
except BaseException:
value = numpy.array(
[numpy.ma.default_fill_value(self)], selftype)
# '?' for Boolean and object
elif isinstance(value, (str, numpy.string_, numpy.str,
numpy.string0, numpy.str_)) and selftype in ['?', 'c', 'O', 'S']:
pass
else:
raise CDMSError('Invalid missing value %s' % repr(value))
self.missing_value = value
def getTime(self):
"""Get the first time dimension.
Returns
-------
First Time dimension axis or `None`.
"""
for k in range(self.rank()):
axis = self.getAxis(k)
if axis.isTime():
return axis
break
else:
return None
def getForecastTime(self):
"""Get the first forecast time dimension.
Returns
-------
First forecast time dimension axis or `None`.
"""
for k in range(self.rank()):
axis = self.getAxis(k)
if axis.isForecast():
return axis
break
else:
return None
def getForecast(self):
return self.getForecastTime()
def getLevel(self):
"""Get the first vertical level dimension in the domain.
Returns
-------
First vertical level dimension axis or `None`.
"""
for k in range(self.rank()):
axis = self.getAxis(k)
if axis.isLevel():
return axis
break
else:
return None
def getLatitude(self):
"""Get the first latitude dimension.
Returns
-------
First latitude dimension axis or `None`.
"""
grid = self.getGrid()
if grid is not None:
result = grid.getLatitude()
else:
result = None
if result is None:
for k in range(self.rank()):
result = self.getAxis(k)
if result.isLatitude():
break
else:
result = None
return result
def getLongitude(self):
"""Get the first longitude dimension.
Returns
-------
First longitude dimension axis or `None`.
"""
grid = self.getGrid()
if grid is not None:
result = grid.getLongitude()
else:
result = None
if result is None:
for k in range(self.rank()):
result = self.getAxis(k)
if result.isLongitude():
break
else:
result = None
return result
# Get an order string, such as "tzyx"
def getOrder(self, ids=0):
"""
Get Order
Parameters
----------
id : 0 or 1
Returns
-------
the order string, such as t, z, y, x (time, level, lat, lon).
Notes
* if ids == 0 (the default) for an axis that is not t,z,x,y
the order string will contain a (-) character in that location.
The result string will be of the same length as the number
of axes. This makes it easy to loop over the dimensions.
* if ids == 1 those axes will be represented in the order
string as (id) where id is that axis' id. The result will
be suitable for passing to order2index to get the
corresponding axes, and to orderparse for dividing up into
components.
"""
order = ""
for k in range(self.rank()):
axis = self.getAxis(k)
if axis.isLatitude():
order = order + "y"
elif axis.isLongitude():
order = order + "x"
elif axis.isLevel():
order = order + "z"
elif axis.isTime():
order = order + "t"
elif ids:
order = order + '(' + axis.id + ')'
else:
order = order + "-"
return order
def subSlice(self, *specs, **keys):
speclist = self._process_specs(specs, keys)
numericSqueeze = keys.get('numericSqueeze', 0)
# Get a list of single-index specs
if numericSqueeze:
singles = self._single_specs(specs)
else:
singles = None
slicelist = self.specs2slices(speclist, force=1)
d = self.expertSlice(slicelist)
squeeze = keys.get('squeeze', 0)
raw = keys.get('raw', 0)
order = keys.get('order', None)
grid = keys.get('grid', None)
# Force result to have these axes
forceaxes = keys.get('forceaxes', None)
raweasy = raw == 1 and order is None and grid is None
if not raweasy:
if forceaxes is None:
axes = []
allaxes = [None] * self.rank()
for i in range(self.rank()):
slice = slicelist[i]
if squeeze and numpy.ma.size(d, i) == 1:
continue
elif numericSqueeze and i in singles:
continue
# Don't wrap square-bracket slices
axis = self.getAxis(i).subaxis(
slice.start, slice.stop, slice.step, wrap=(
numericSqueeze == 0))
axes.append(axis)
allaxes[i] = axis
else:
axes = forceaxes
# Slice the grid, if non-rectilinear. Don't carry rectilinear grids, since
# they can be inferred from the domain.
selfgrid = self.getGrid()
if selfgrid is None or isinstance(selfgrid, AbstractRectGrid):
resultgrid = None
else:
alist = [item[0] for item in self.getDomain()]
gridslices, newaxes = selfgrid.getGridSlices(
alist, allaxes, slicelist)
# If one of the grid axes was squeezed, the result grid is None
if None in newaxes:
resultgrid = None
else:
resultgrid = selfgrid.subSlice(
*gridslices, **{'forceaxes': newaxes})
resultArray = self._returnArray(d, squeeze, singles=singles)
if self.isEncoded():
resultArray = self.decode(resultArray)
newmissing = resultArray.fill_value
else:
newmissing = self.getMissing()
if raweasy:
return resultArray
elif len(axes) > 0:
# If forcing use of input axes, make sure they are not copied.
# Same if the grid is not rectilinear - this is when forceaxes is
# set.
copyaxes = (forceaxes is None) and (resultgrid is None)
result = TransientVariable(resultArray,
copy=0,
fill_value=newmissing,
axes=axes,
copyaxes=copyaxes,
grid=resultgrid,
attributes=self.attributes,
id=self.id)
if grid is not None:
order2 = grid.getOrder()
if order is None:
order = order2
elif order != order2:
raise CDMSError('grid, order options not compatible.')
result = result.reorder(order).regrid(grid)
if raw == 0:
return result
else:
return result.getSlice(squeeze=0, raw=1)
else: # Return numpy.ma for zero rank, so that __cmp__ works.
return resultArray
def getSlice(self, *specs, **keys):
"""getSlice takes arguments of the following forms and produces
a return array.
Parameters
----------
raw : if set to 1, return numpy.ma only
squeeze : if set to 1, eliminate any dimension of length 1
grid : if given, result is regridded ont this grid.
order : if given, result is permuted into this order
numericSqueeze : if index slice is given, eliminate that dimension.
isitem : if given, result is return as a scaler for 0-D data
Notes
There can be zero or more positional arguments, each of the form:
#. a single integer n, meaning slice(n, n+1)
#. an instance of the slice class
#. a tuple, which will be used as arguments to create a slice
#. `None` or `:`, which means a slice covering that entire dimension
#. Ellipsis (...), which means to fill the slice list with `:`
leaving only enough room at the end for the remaining positional arguments
There can be keyword arguments of the form key = value, where
key can be one of the names `time`, `level`, `latitude`, or
`longitude`. The corresponding value can be any of (1)-(5) above.
There must be no conflict between the positional arguments and
the keywords.
In (1)-(5) negative numbers are treated as offsets from the end
of that dimension, as in normal Python indexing.
"""
# Turn on squeeze and raw options by default.
keys['numericSqueeze'] = keys.get('numericSqueeze', 0)
keys['squeeze'] = keys.get('squeeze', 1 - keys['numericSqueeze'])
keys['raw'] = keys.get('raw', 1)
keys['order'] = keys.get('order', None)
keys['grid'] = keys.get('grid', None)
isitem = keys.get('isitem', 0)
result = self.subSlice(*specs, **keys)
# return a scalar for 0-D slices
if isitem and result.size == 1 and (
not _numeric_compatibility) and not result.mask.item():
result = result.item()
return result
def expertSlice(self, slicelist):
raise CDMSError(NotImplemented + 'expertSlice')
def getRegion(self, *specs, **keys):
""" Read a region of data. A region is an n-dimensional rectangular region specified in coordinate space.
Parameters
----------
slice : is an argument list, each item of which has one of the following forms:
* x, where x is a scalar
* Map the scalar to the index of the closest coordinate value.
* (x, y)
* Map the half-open coordinate interval [x,y) to index interval.
* (x, y, 'cc')
* Map the closed interval [x,y] to index interval. Other options
are 'oo' (open), 'oc' (open on the left), and 'co'
(open on the right, the default).
* (x, y, 'co', cycle)
* Map the coordinate interval with wraparound. If no cycle is
specified, wraparound will occur iff axis.isCircular() is true.
Ellipsis : Represents the full range of all dimensions bracketed by non-Ellipsis items.
None, colon : Represents the full range of one dimension.
Notes
Only one dimension may be wrapped.
Example
Suppose the variable domain is `(time, level, lat, lon)`. Then
>>> getRegion((10, 20), 850, Ellipsis,(-180, 180))
retrieves :
* all times t such that 10.<=t<20.
* level 850.
* all values of all dimensions between level and lon (namely, lat).
* longitudes x such that -180<=x<180. This will be wrapped unless lon.topology=='linear'.
"""
# By default, squeeze and raw options are on
keys['squeeze'] = keys.get('squeeze', 1)
keys['raw'] = keys.get('raw', 1)
keys['order'] = keys.get('order', None)
keys['grid'] = keys.get('grid', None)
return self.subRegion(*specs, **keys)
def subRegion(self, *specs, **keys):
speclist = self._process_specs(specs, keys)
slicelist = self.reg_specs2slices(speclist)
squeeze = keys.get('squeeze', 0)
raw = keys.get('raw', 0)
order = keys.get('order', None)
grid = keys.get('grid', None)
raweasy = raw == 1 and order is None and grid is None
if grid is not None and order is None:
order = grid.getOrder()
# Check if any slice wraps around.
wrapdim = -1
axes = []
circulardim = None
for idim in range(len(slicelist)):
item = slicelist[idim]
axis = self.getAxis(idim)
axislen = len(axis)
if(axis.isCircular()):
circulardim = idim
wraptest1 = (axis.isCircular() and speclist[idim] != unspecified)
start, stop = item.start, item.stop
wraptest2 = not (
(start is None or (
0 <= start < axislen)) and (
stop is None or (
0 <= stop <= axislen)))
if (wraptest1 and wraptest2):
if wrapdim >= 0:
raise CDMSError("Too many dimensions wrap around.")
wrapdim = idim
break
else:
# No wraparound, just read the data
# redo the speclist -> slice if passed circular test but not
# wrapped test
if(circulardim is not None):
slicelist = self.reg_specs2slices(speclist, force=circulardim)
d = {'raw': raw,
'squeeze': squeeze,
'order': order,
'grid': grid,
}
return self.subSlice(*slicelist, **d)
#
# get the general wrap slice (indices that are neg -> pos and vica versa)
#
wrapslice = slicelist[wrapdim]
wrapaxis = self.getAxis(wrapdim)
length = len(wrapaxis)
#
# shift the wrap slice to the positive side and calc number of cycles shifted
#
wb = wrapslice.start
we = wrapslice.stop
ws = wrapslice.step
size = length
cycle = self.getAxis(wrapdim).getModulo()
#
# ncycle:
# number of cycles for slicing purposes and
# resetting world coordinate from the positive only direction
#
# ncyclesrev:
# resetting the world coordinate for reversed direction
#
ncycles = 0
ncyclesrev = 0