-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaverager.py
More file actions
1330 lines (1238 loc) · 48.3 KB
/
averager.py
File metadata and controls
1330 lines (1238 loc) · 48.3 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 print_function
import numpy
import numpy.ma
import cdms2
import MV2
try:
basestring
except NameError:
basestring = str
class AveragerError (Exception):
pass
def _check_axisoptions(x, axisoptions):
"""
Checks the axis=options to make sure that it is valid
:param x: A CDMS TransientVariable
:type x: cdms.tvariable.TransientVariable
:param axisoptions: String containing axis options
:type axisoptions: str
"""
axlist = cdms2.orderparse(axisoptions)
if Ellipsis in axlist:
raise AveragerError(
'Error: Ellipsis (...) not allowed in axis options')
try:
cdms2.order2index(x.getAxisList(), axisoptions)
return axlist
except BaseException:
raise AveragerError(
'Error: You have specified an invalid axis= option.')
def __myGetAxisWeights(x, i, axisoptions=None):
"""
Assume x is an MV2 duh! and get the weights associated with axis index i.
index i can be any of the dimensions in x whose bounds are available.
If bounds are not available then an error is raised.
"""
if x.getAxis(i).isLatitude():
Lataxis = x.getAxis(i)
xgr = cdms2.createGenericGrid(
Lataxis[:],
numpy.array(
list(
range(1)),
numpy.float),
latBounds=Lataxis.getBounds())
xlatwt, xlonwt = xgr.getWeights()
return xlatwt
elif x.getAxis(i).isLongitude():
Lonaxis = x.getAxis(i)
xgr = cdms2.createGenericGrid(
numpy.array(
list(
range(1)),
numpy.float),
Lonaxis[:],
lonBounds=Lonaxis.getBounds())
xlatwt, xlonwt = xgr.getWeights()
return xlonwt
else:
axis_bounds = x.getAxis(i).getBounds()
if axis_bounds is None:
ax = x.getAxis(i)
if axisoptions is not None:
axo = cdms2.orderparse(axisoptions)
if (i in axo) or (ax.isTime() and 't' in axo) or (
ax.isLevel() and 'z' in axo) or ('(' + ax.id + ')' in axo):
raise AveragerError(
'Bounds not available to compute weights on dimension: ' + ax.id)
else:
axis_wts = numpy.ones(x.getAxis(i)[:].shape)
else:
raise AveragerError(
'Bounds not available to compute weights for dimension: ' + ax.id)
else:
axis_wts = abs(axis_bounds[..., 1] - axis_bounds[..., 0])
return axis_wts
# end of if is axis_bounds:
# end of if x.getAxis(i).isLatitude():
def getAxisWeight(x, i):
"""
This returns the axis weights as generated by __myGetAxisWeights except it
is returned as an MV2!
:param x: A CDMS TransientVariable
:type x: cdms.tvariable.TransientVariable
:param i: The index of an axis on x
:type i: int
:returns: A CDMS TransientVariable containing the axis weights
:rtype: cdms.tvariable.TransientVariable
"""
try:
wts = __myGetAxisWeights(x, i)
axis_i = x.getAxis(i)
wtTV = cdms2.createVariable(wts, axes=[axis_i])
except BaseException:
raise AveragerError('Could not get weights.')
return wtTV
def __myGetAxisWeightsByName(x, name):
"""
Get the weights associated with axis name.
The name can be any of the dimensions in x whose bounds are available.
If bounds are not available then an error is raised.
This is a slight modifications on the _myGetAxisWeight. The only difference
is that the name is used to define the axis instead of the index.
"""
if x.getAxisList(axes=name)[0].isLatitude():
Lataxis = x.getAxisList(axes=name)[0]
xgr = cdms2.createGenericGrid(
Lataxis[:],
numpy.array(
list(
range(1)),
numpy.float),
latBounds=Lataxis.getBounds())
xlatwt, xlonwt = xgr.getWeights()
return xlatwt
elif x.getAxisList(axes=name)[0].isLongitude():
Lonaxis = x.getAxisList(axes=name)[0]
xgr = cdms2.createGenericGrid(
numpy.array(
list(
range(1)),
numpy.float),
Lonaxis[:],
lonBounds=Lonaxis.getBounds())
xlatwt, xlonwt = xgr.getWeights()
return xlonwt
else:
axis_bounds = x.getAxisList(axes=name)[0].getBounds()
if not axis_bounds:
raise AveragerError('Bounds not available to compute weights')
else:
axis_wts = abs(axis_bounds[..., 1] - axis_bounds[..., 0])
return axis_wts
def getAxisWeightByName(x, name):
"""
A hook provided to facilitate the VCDAT GUI.
This returns the axis weights as generated by __myGetAxisWeights except it
is returned as an MV2!
:param x: A CDMS TransientVariable
:type x: cdms.tvariable.TransientVariable
:param name: String name of an axis
:type name: str
"""
try:
wts = __myGetAxisWeightsByName(x, name)
axis_name = x.getAxisList(axes=name)[0]
wtTV = cdms2.createVariable(wts, axes=[axis_name])
except BaseException:
raise AveragerError('Could not get weights.')
return wtTV
def area_weights(ds, axisoptions=None):
"""
Calculates masked area weights.
Author: Charles Doutriaux: doutriaux@llnl.gov
Modified version using CDAT 3.0 by Paul Dubois
Further modified by Krishna AchutaRao to return weights in all axes.
:param ds: A CDMS TransientVariable
:type ds: cdms.tvariable.TransientVariable
:param axisoptions: String containing axis options
:type axisoptions: str
:returns: A masked array of the same dimensions as ds containing area weights, but masked where ds is masked.
:rtype: cdms.tvariable.TransientVariable
"""
#
__DEBUG__ = 0
#
if __DEBUG__:
print('Incoming axisoptions = ', axisoptions)
if __DEBUG__:
print('Shape of Incoming data = ', ds.shape)
seenlon = 0
seenlat = 0
if 'x' in list(ds.getOrder()):
seenlon = 1
if 'y' in list(ds.getOrder()):
seenlat = 1
#
if seenlat and seenlon:
if __DEBUG__:
print('Found both latitude and longitude')
initial_order = ds.getOrder()
if __DEBUG__:
print('initial_order= ', initial_order)
initial_order_list = list(initial_order)
if '-' in initial_order_list:
loc = initial_order_list.index('-')
axisid = '(' + ds.getAxis(loc).id + ')'
initial_order_list[loc] = axisid
initial_order = "".join(initial_order_list)
if __DEBUG__:
print('Changed initial_order = ', initial_order)
# end of if '-' in initial_order_list:
ds = ds(order='...yx')
dsorder = ds.getOrder()
if __DEBUG__:
print('Reordered ds ', dsorder)
Lataxisindex = list(dsorder).index('y')
Lonaxisindex = list(dsorder).index('x')
if __DEBUG__:
print(
'Lataxisindex = ',
Lataxisindex,
' Lonaxisindex = ',
Lonaxisindex)
dsgr = ds.getGrid()
latwts, lonwts = dsgr.getWeights()
wt = numpy.outer(numpy.array(latwts), numpy.array(lonwts))
# At this point wt is an nlat by nlong matrix
# Now the problem is to propagate this two-dimensional weight mask
# through the other dimensions. To do this we shuffle these two dimensions
# to the front of the shape, resize wt, and then permute it back to
# the order of the dimensions in ds.
s = ds.shape
for i in range(len(s) - 1, -1, -1):
if (i != Lataxisindex) and (i != Lonaxisindex):
newaxiswt = __myGetAxisWeights(ds, i, axisoptions)
wtlist = list(wt.shape)
if __DEBUG__:
print('Before Inserting newdim', wtlist)
wtlist.insert(0, newaxiswt.shape[0])
if __DEBUG__:
print('After inserting newdim ', wtlist)
new_wtshape = tuple(wtlist)
wt = numpy.resize(wt, new_wtshape)
if __DEBUG__:
print(
'After inserting dimension ',
i,
' shape of wt = ',
wt.shape)
new_newaxiswt_shape = list(newaxiswt.shape)
for nn in range(1, len(wt.shape), 1):
new_newaxiswt_shape.append(1)
newaxiswt = numpy.resize(newaxiswt, tuple(new_newaxiswt_shape))
wt = wt * newaxiswt
# end of if (i != Lataxisindex) and (i != Lonaxisindex):
# end of for i in range(len(s)):
wt = cdms2.createVariable(
numpy.ma.masked_array(
wt,
numpy.ma.getmask(ds)),
axes=ds.getAxisList())
result = wt(order=initial_order)
if __DEBUG__:
print('Returning something of order', result.getOrder())
return result
else:
wt = __myGetAxisWeights(ds, 0, axisoptions)
if __DEBUG__:
print('Initial', wt.shape)
for i in range(1, len(ds.shape)):
wt_newshape = tuple(list(ds.shape)[:i + 1])
if __DEBUG__:
print('wt_newshape = ', wt_newshape)
wt = numpy.resize(wt, wt_newshape)
if __DEBUG__:
print('After wt resize wt.shape = ', wt.shape)
newaxiswt = __myGetAxisWeights(ds, i)
newaxiswt = numpy.resize(newaxiswt, wt.shape)
wt = wt * newaxiswt
if __DEBUG__:
print('After axis ', i, ' wt has shape ', wt.shape)
# end of for i in range(2, len(ds.shape)):
if __DEBUG__:
print('Final Shape of Weight = ', wt.shape)
return cdms2.createVariable(numpy.ma.masked_array(
wt, numpy.ma.getmask(ds)), axes=ds.getAxisList())
# end of if seenlat and seenlon:
def __check_each_weight_option(x, ax, index, wtopt):
"""
This does the checking of individual weight options. It fills in the weights
if 'generate' is an option used i.e if getWeights is needed.
"""
#
__DEBUG__ = 0
#
if __DEBUG__:
print('Inside __check_each_weight_option, index = ',
index, 'axis = ', ax, ' wtopt = ', wtopt)
#
# Check the types etc.....
#
if MV2.isMaskedVariable(wtopt):
#
# wtopt is an MV2
#
if __DEBUG__:
print('I have a Masked Variable of shape', wtopt.shape)
#
try:
if __DEBUG__:
print(
'****Order of axes in wtopt (originally) = ',
MV2.getorder(wtopt))
wtopt = wtopt(order=ax)
if __DEBUG__:
print(
'****Order of axes in wtopt (finally) = ',
MV2.getorder(wtopt))
except BaseException:
raise AveragerError(
'The MV2 passed does not have an axis matching ' + str(ax))
# end of try:
if numpy.ma.shape(wtopt(order=ax)[:])[0] != len(x.getAxis(index)[:]):
# We have an MV2 whose length is not the same as that of the
# corresponding axis for x
raise AveragerError(
'The Masked Variable passed does not match the length of axis ' + str(ax))
# end of if numpy.ma.shape(wtopt(order=ax)[:])[0] !=
# len(x.getAxis(index)[:]):
if len(numpy.ma.shape(wtopt)) == 1:
#
# Coerce the MV2 to numpy type..... only if the wtopt is 1-d!!
#
if __DEBUG__:
print('Returning a numeric array from MV2!!')
wtopt = numpy.ma.filled(wtopt)
# end of if len(numpy.ma.shape(wtopt)) == 1:
elif numpy.ma.isMA(wtopt):
#
# wtopt is an numpy.ma
#
if __DEBUG__:
print('I have a Masked Array of rank', wtopt.ndim)
#
if wtopt.ndim > 1:
raise AveragerError(
'Error: The Masked Array of more than 1 dimension lacks sufficient information')
# end of if numpy.ma.rank(wtopt) > 1:
if numpy.ma.shape(wtopt)[0] != len(x.getAxis(index)[:]):
raise AveragerError('Error: Axis is of length %d, weights passed of length %d.' %
(len(x.getAxis(index)[:]), numpy.ma.shape(wtopt)[0]))
# end of if numpy.ma.shape(wtopt)[0] != len(x.getAxis(index)[:]):
#
# Coerce the numpy.ma to numpy type.....
#
if __DEBUG__:
print('Returning a numeric array from numpy.ma!!')
wtopt = wtopt.filled()
elif isinstance(wtopt, numpy.ndarray):
#
# wtopt is a numpy Array
#
if __DEBUG__:
print('I have a numpy Array of rank', len(numpy.shape(wtopt)))
#
if len(numpy.shape(wtopt)) > 1:
raise AveragerError(
'Error: The numpy Array of more than 1 dimension lacks sufficient information')
if numpy.shape(wtopt)[0] != len(x.getAxis(index)[:]):
raise AveragerError('Error: Axis is of length %d, weights passed of length %d' %
(len(x.getAxis(index)[:]), numpy.shape(wtopt)[0]))
elif isinstance(wtopt, basestring):
#
# wtopt is a string
#
if __DEBUG__:
print('I have a string =', wtopt)
#
if wtopt.lower() in ['equal', 'unweighted']:
if __DEBUG__:
print('Equal weights specified')
wtopt = 'unweighted'
elif wtopt.lower() in ['generate', 'weighted']:
# NOTE: THIS FUNCTION CAN BE CHANGED WHEN BOB PUTS THE FUNCTION
# getAxisWeights() INTO cdms2
if __DEBUG__:
print('GENERATE weights specified')
wtopt = __myGetAxisWeights(x, index)
if __DEBUG__:
print(wtopt)
else:
raise AveragerError('Error: Unrecognised string option specified')
# end of if MV2.isMaskedVariable(wtopt):
return wtopt
def __check_weightoptions(x, axisoptions, weightoptions):
"""
Checks the weights=options to make sure that it is valid.
Default: 'weighted'
:param weightoptions: One of 'weighted', 'unweighted', an array of weights for each dimension or a MaskedVariable
of the same shape as the data x.
- 'weighted' means use the grid information to generate weights for that
dimension or if multiple axes are passed, generate goes ahead and
generates the full masked area weights.
- 'unweighted' means use equal weights for all the grid points in that axis.
- Also an array of weights (of the same shape as the dimension being
averaged over or same shape as V) can be passed.
"""
#
# Since the _check_axisoptions was passed, the variable x has already been reordered
# to the required order..... check it anyway.
#
#
__DEBUG__ = 0
#
if __DEBUG__:
print('Axis options entering __check_weightoptions = ', axisoptions)
#
axisindex = cdms2.order2index(x.getAxisList(), axisoptions)
if __DEBUG__:
print('This should be 0,1,2... etc. is it? ', axisindex)
#
axislist = cdms2.orderparse(axisoptions)
if __DEBUG__:
print('axislist = ', axislist)
#
if not isinstance(weightoptions, (list, tuple)):
#
# We have either 1 axis only or multiple axes and one MV2 of weights
#
if MV2.isMaskedVariable(weightoptions):
#
# Weight passed is an MV2. Probably OK
#
try:
# We had required that the weights be of the same rank as the
# variable to be averaged.
weightoptions = weightoptions(order=axisoptions)
#
# KRISHNA : check this for combinewts!!
#
if __DEBUG__:
print('... definitely OK')
except BaseException:
raise AveragerError(
'Error: Did not find the axes requested in the Masked variable.')
elif len(axislist) == 1:
#
# Only one axis to reduce over....'
# figure out if it is an array (numpy or numpy.ma) or 'equal' or 'generate' or something else
#
if __DEBUG__:
print('I have only 1 axis and 1 option')
weightoptions = __check_each_weight_option(
x, axislist[0], axisindex[0], weightoptions)
else:
#
# More than 1 axis to reduce over, and not an MV2 of the same dimensionality as x!
#
if weightoptions in ['generate', 'weighted']:
weightoptions = area_weights(x, axisoptions)
else:
# Cannot do this because 'generate' was not passed with
# multiple axes.
raise AveragerError(
'Error: Multiple axes passed without weights to match')
# end of if weightoptions == 'generate':
else:
#
# I have a list of weightoptions i.e more than 1 axis in axisoption
#
#
# We have multiple axes to deal with each with a weight....
#
# Ensure we have a mutable list, handles tuple (https://github.com/CDAT/genutil/issues/32
if not isinstance(weightoptions, list):
weightoptions = list(weightoptions)
for i in range(len(axislist)):
weightoptions[i] = __check_each_weight_option(
x, axislist[i], axisindex[i], weightoptions[i])
# end of for i in range(len(axislist)):
#
if len(axislist) < len(weightoptions):
for j in range(len(axislist), len(weightoptions), 1):
weightoptions[j] = __check_each_weight_option(
x, None, j, weightoptions[j])
# end of if len(axislist) < len(weightoptions):
# end of if not isinstance(weightoptions, types.ListType):
#
if __DEBUG__:
print('Successful with __check_weightoptions')
#
return weightoptions
def _check_MA_weight_options(weightoptions, shx, N_axisopt):
"""
Check the weight options for the case of an MA passed to averager.
Inputs:
weightoptions : The user specified options in weights =
shx : Is the shape of the reordered numpy.ma
"""
#
__DEBUG__ = 0
#
if __DEBUG__:
print('Entered _check_MA_weight_options:', weightoptions)
#
if weightoptions is None:
weightoptions = [None] * N_axisopt
#
if not isinstance(weightoptions, list):
weightoptions = [weightoptions]
# end of if not isinstance(weightoptions, types.ListType):
#
for i in range(len(weightoptions)):
#
wt = weightoptions[i]
#
if isinstance(wt, basestring):
if __DEBUG__:
print('string weights')
if wt in ['weighted', 'generate']:
raise AveragerError(
'Cannot generate weights for an numpy.ma. %s is not a valid option when you do not pass an MV2. ' %
wt)
elif (wt in ['equal', 'unweighted']):
weightoptions[i] = numpy.ones(tuple([shx[i]]), numpy.float)
# end of if wt in ['weighted', 'generate']:
elif isinstance(wt, numpy.ndarray):
if __DEBUG__:
print('numpy Array weights')
if (wt.shape != shx) and (wt.ndim == 1 and len(wt) != shx[i]):
raise AveragerError(
'The passed weight is not of the appropriate shape')
# end of if (wt.shape != shx) or (numpy.ma.rank(wt) == 1 and
# len(wt) != shx[i]):
elif numpy.ma.isMA(wt):
if __DEBUG__:
print('numpy.ma Array weights')
if __DEBUG__:
print('wt.shape = ', wt.shape)
if __DEBUG__:
print('numpy.ma.rank(wt) = ', wt.ndim)
if __DEBUG__:
print('len(wt) = ', len(wt))
if __DEBUG__:
print('shx[i] = ', shx[i])
if (wt.shape != shx) and (wt.ndim == 1 and len(wt) != shx[i]):
if __DEBUG__:
print('The passed weight is not of the appropriate shape')
raise AveragerError(
'The passed weight is not of the appropriate shape')
# end of if (wt.shape != shx) or (numpy.ma.rank(wt) == 1 and len(wt) != shx[i]):
# end of if isinstance(wt, types.StringType):
# end of for i in range(len(weightoptions)):
#
if __DEBUG__:
print('weightoptions after _check_MA_weight_options', weightoptions)
return weightoptions
def _combine_weights(x, weightoptions):
"""
This takes in the shape of the reordered array, the passed weight options
and combines the weights to form a weight array of the same shape as x.
Inputs:
x : The input array reordered to be in the order of operations.
weightoptions : The weight options for the subset of axes of x - in the order of x
Returned:
weight_array : In the same shape as x but assuming that the remaining weights are equal.
"""
#
__DEBUG__ = 0
#
xsh = x.shape
if __DEBUG__:
print('Shape of incoming data x ', xsh)
if __DEBUG__:
print('Type of x ', x.__class__)
#
if isinstance(weightoptions, list):
if __DEBUG__:
print('weightoptions is a list')
#
# Note the weight options have already gone through checks against the
# reordered data. So nofurther checks are necessary!
#
n_dimstoadd = len(x.shape) - len(weightoptions)
if __DEBUG__:
print('Dimensions to add = ', n_dimstoadd)
if n_dimstoadd < 0:
raise AveragerError(
'Error in weights list - too many weights passed!')
elif n_dimstoadd > 0:
init_shape = x.shape[-n_dimstoadd:]
if __DEBUG__:
print('Initialized shape = ', init_shape)
#
wt_init = numpy.ones(init_shape, numpy.float)
#
dim = len(init_shape) + 1
else:
wt_init = None
dim = 1
# end of if n_dimstoadd < 0 :
#
wgt = weightoptions[-1]
if wgt in ['equal', 'unweighted']:
wgt = numpy.ones(xsh[-dim], numpy.float)
else:
if __DEBUG__:
print(wgt)
# end of if wgt in ['equal', 'unweighted']:
#
if __DEBUG__:
print('wgt.shape = ', wgt.shape)
#
if wt_init is None:
wt_init = wgt
if not isinstance(wt_init, numpy.ndarray):
raise AveragerError('Wrong Weight!!!')
else:
if __DEBUG__:
print('list(init_shape) = ', list(init_shape))
newshape = list(init_shape)
newshape.insert(0, wgt.shape[0])
if __DEBUG__:
print('Pre-loop newshape ', newshape)
wt_init = numpy.resize(wt_init, tuple(newshape))
if __DEBUG__:
print('Pre-loop wt_init.shape ', wt_init.shape)
wgtsh = list(wgt.shape)
for nn in range(1, len(wt_init.shape), 1):
wgtsh.append(1)
if __DEBUG__:
print('wgt resized to ', tuple(wgtsh))
wgt = numpy.resize(wgt, tuple(wgtsh))
wt_init = wt_init * wgt
# end of if not wt_init:
#
if __DEBUG__:
print('Pre-loop wt_init.shape ', wt_init.shape)
#
for i in range(len(weightoptions) - 2, -1, -1):
dim_wt = weightoptions[i]
if dim_wt in ['equal', 'unweighted']:
dim_wt = numpy.ones(xsh[i], numpy.float)
# end of if dim_wt in ['equal', 'weighted']:
if __DEBUG__:
print('At step ', i, dim_wt)
newshape = list(wt_init.shape)
newshape.insert(0, dim_wt.shape[0])
wt_init = numpy.resize(wt_init, tuple(newshape))
if __DEBUG__:
print('Shape of wt_init = ', wt_init.shape)
dim_wtsh = list(dim_wt.shape)
for nn in range(1, len(wt_init.shape), 1):
dim_wtsh.append(1)
if __DEBUG__:
print('dim_wt resized to ', tuple(dim_wtsh))
dim_wt = numpy.resize(dim_wt, tuple(dim_wtsh))
wt_init = wt_init * dim_wt
# end of for i in range(len(weightoptions)-1, -1, -1):
#
if __DEBUG__:
print('wt_init after all dimensions adeed has shape ', wt_init.shape)
if wt_init.shape != xsh:
raise AveragerError('SOMETHING SCREWY HAPPENED!!')
#
if MV2.isMaskedVariable(x):
wt_init = MV2.array(wt_init, axes=x.getAxisList())
weightoptions = [wt_init]
#
if __DEBUG__:
print(
'Are my weight and area_weights the same?',
numpy.ma.allclose(
weightoptions[0],
area_weights(x)))
# end of if isinstance(weightoptions, types.ListType):
#
return weightoptions
def _check_MA_axisoptions(axisoption, N_dim):
"""
This checks the axis options for the case of an MA passed to the averager.
Inputs:
axisoption : The user specified options in axis=
N_dim : rank of the MA that is being averaged
Returned:
axisoption : This one is always a list of integers pertaining to axes
"""
#
__DEBUG__ = 0
#
if __DEBUG__:
print('Inside _check_MA_axisoptions:', axisoption)
#
if not isinstance(axisoption, list):
axisoption = [axisoption]
# end of if not isinstance(axis, types.ListType):
#
for i in range(len(axisoption)):
axis = axisoption[i]
if not axis:
axisoption[i] = 0
elif isinstance(axis, int):
if axis not in list(range(N_dim)):
raise AveragerError(
'Specified dimension \'%d\' not valid in array of rank %d' %
(axis, N_dim))
# end of if axis >= len(N_dim):
elif isinstance(axis, basestring):
try:
axisoption[i] = int(axis)
except BaseException:
raise AveragerError(
'%s is not a valid axis for an MA. You must pass an MV2' %
axis)
# end of try:
# end of if axis is None:
# end of for axis in axisoption:
#
if __DEBUG__:
print(
'axisoption after _check_MA_axisoptions = ',
axisoption,
len(axisoption))
#
return axisoption
def sum_engine(x, wts):
"""
The work horse that does the summing ! This is specific to summing.
We will always be dealing with the first dimension, and x is already in
the order we will sum.
1-d wts are always numpy arrays or 'equal' Multi-dimensional arrays are
always MV2's
:param x: the input array (can be MV2 or MA)
:type: MV2 or MA
:param wts: the input weight array
:type wts: numpy array or MV2 or 'equal'
:returns y: The weighted sum (summed over the first dimension)
:returns return_wts: The sum of weights (summed over the first dimension)
"""
#
__DEBUG__ = 0
#
if x is None:
return None
if wts is None:
return None
#
shx = numpy.ma.shape(x)
#
if __DEBUG__:
print('\tInside sum_engine.')
if __DEBUG__:
print('\tIncoming data of shape ', shx)
#
if MV2.isMaskedVariable(wts) or isinstance(wts, numpy.ndarray):
#
# wts is an MV2 or numpy array
#
if __DEBUG__:
print('\t********** Weight is an MV2 or numpy array! **********')
#
xavg, return_wts = MV2.average(x, weights=wts, returned=1, axis=0)
y = xavg * return_wts
return y, return_wts
elif wts in ['equal', 'unweighted']:
#
# Equal weights
#
if __DEBUG__:
print('\t********** Weight is Equal! **********')
xavg, return_wts = MV2.average(x, returned=1, axis=0)
y = xavg * return_wts
return y, return_wts
# end of if action == 'sum':
else:
raise AveragerError('wts is an unknown type in sum_engine')
return None
# end of if MV2.isMaskedVariable(wts) or isinstance(wts, numpy.ndarray):
def average_engine(x, wts):
"""
The work horse that does the averaging! This is specific to averaging.
We will always be dealing with the first dimension, and x is already in
the order we will average.
1-d wts are always numpy arrays or 'equal' Multi-dimensional arrays are
always MV2's
:param x: the input array (can be MV2 or MA)
:type: MV2 or MA
:param wts: the input weight array
:type wts: numpy array or MV2 or 'equal'
:returns y: The weighted average (averaged over the first dimension)
:returns return_wts: The average of weights (averaged over the first dimension)
"""
#
__DEBUG__ = 0
#
if x is None:
return None
if wts is None:
return None
#
shx = numpy.ma.shape(x)
if __DEBUG__:
print('\tInside average_engine.')
if __DEBUG__:
print('\tIncoming data of shape ', shx)
#
if MV2.isMaskedVariable(wts) or isinstance(wts, numpy.ndarray):
y, return_wts = MV2.average(x, weights=wts, returned=1, axis=0)
return y, return_wts
elif wts in ['equal', 'unweighted']:
y, return_wts = MV2.average(x, returned=1, axis=0)
return y, return_wts
else:
raise AveragerError('wts is an unknown type in average_engine')
# end of if MV2.isMaskedVariable(wts) or isinstance(wts, numpy.ndarray):
def averager(V, axis=None, weights=None, action='average',
returned=0, weight=None, combinewts=None):
"""
The averager() function provides a convenient way of averaging your data giving
you control over the order of operations (i.e which dimensions are averaged
over first) and also the weighting for the different axes. You can pass your
own array of weights for each dimension or use the default (grid) weights or
specify equal weighting.
Author: Krishna AchutaRao : achutarao1@llnl.gov
:returns: The average over the specified dimensions.
:Usage:
.. code-block:: python
>>> import numpy as np
>>> V=np.array([1,2,3,4,5])
>>> averager(V, returned=1)
3
:param V: an array of numpy, numpy.ma or MV2 type
:type V: numpy.array or numpy.ma or MV2
:param axis: String specifying axisoptions.
Default: first dimension in the data you pass to the function.
You can pass axis='tyx', or '123', or 'x (plev)' etc. the same way as
in order= options for variable operations EXCEPT that
'...'(i.e Ellipses) are not allowed. In the case that V is a numpy or
numpy.ma array, axis names have no meaning and only axis indexes are valid.
:type axis: string
:param weights: String specifying weight options
Default:
'weighted' for Transient Variables (MV2s)
'unweighted' for numpy.ma or numpy arrays.
.. note::
Depending on the array being operated on by averager, the
default weights change!
Weight options are one of 'weighted', 'unweighted', an array of weights for
each dimension or a MaskedVariable of the same shape as the data x.
- 'weighted' means use the grid information to generate weights for
that dimension.
- 'unweighted' means use equal weights for all the grid points in that axis.
- Also an array of weights (of the same shape as the dimension being
averaged over or same shape as V) can be passed.
.. note::
The weights are generated using the bounds for the specified axis.
For latitude and Longitude, the weights are calculated using the area (see the cdms2 manual
grid.getWeights() for more details) whereas for the other axes weights are the difference
between the bounds (when the bounds are available).
If the bounds are stored in the file being read in, then
those values are used. Otherwise, bounds are generated as long as
cdms2.setAutoBounds('on') is set.
If cdms2.setAutoBounds() is set to 'off', then an Error is raised.
:type weights: str
:param action: One of 'average' or 'sum'. Specifies whether to return the weighted average or weighted sum of data.
Default: 'average'
:type action: str
:param returned: Integer flag indicating whether or not the weighted average should be returned.
*0:* implies sum of weights are not returned after averaging operation.
*1:* implies the sum of weights after the average operation is returned.
:type returned: int
:param combinewts: Integer flag indicating whether or not weights passed in for axes should be combined.
*0:* implies weights passed for individual axes are not combined into one
weight array for the full variable V before performing operation.
*1:* implies weights passed for individual axes are combined into one
weight array for the full variable before performing average or sum
operations. One-dimensional weight arrays or key words of 'weighted' or
'unweighted' must be passed for the axes over which the operation is
to be performed. Additionally, weights for axes that are not being
averaged or summed may also bepassed in the order in which they appear.
If the weights for the other axes are not passed, they are assumed to
be equally weighted.
:Examples:
.. code-block:: python
>>> f = cdms2.open('data_file_name')
>>> averager(f('variable_name'), axis='1')
# extracts the variable 'variable_name' from f and averages over the
# dimension whose position is 1. Since no other options are specified,
# defaults kick in i.e weight='weighted' and returned=0
>>> averager(V, axis='xy', weights=['weighted','unweighted'])
>>> averager(V, axis='t', weights='unweighted')
>>> averager(V, axis='x') # Default weights option of 'weighted' is implemented
>>> averager(V, axis='x', weights=mywts) # where mywts is an array of shape (len(xaxis)) or shape(V)
>>> averager(V, axis='(lon)y', weights=[xwts, ywts]) # xwts of shape len(xaxis), ywts of shape len(yaxis)
>>> averager(V, axis='xy', weights=V_wts) # where V_wts is a Masked Variable of shape V
>>> averager(V, axis='x', weights='unweighted', action='sum') # equally weighted sum over the x dimension
>>> ywt = area_weights(y) # These 2 lines compute the area fraction that the data y that is non-missing
>>> fractional_area = averager(ywt, axis='xy', weights=['unweighted', 'unweighted'], action='sum')
.. note::
When averaging data with missing values, extra care needs to be taken.
It is recommended that you use the default weights='weighted' option.
This uses cdutil.area_weights(V) to get the correct weights to
pass to the averager.
>>> averager(V, axis='xy', weights='weighted')`
The above is equivalent to:
>>> V_wts = cdutil.area_weights(V)
>>> result = averager(V, axis='xy', weights=V_wts)
>>> result = averager(V, axis='xy', weights=cdutil.area_weights(V))
However, the area_weights function requires that the axis bounds are
stored or can be calculated (see documentation of area_weights for more
details). In the case that such weights are not stored with the axis
specifications (or the user desires to specify weights from another
source), the use of combinewts option can produce the same results.
In short, the following two are equivalent:
>>> xavg_1 = averager(X, axis = 'xy', weights = area_weights(X))
>>> xavg_2 = averager(X, axis = 'xy', weights = ['weighted', 'weighted', 'weighted'], combinewts=1)
Where X is a function of x, y and a third dimension such as time or level.
In general, the above can be substituted with arrays of weights where
the 'weighted' keyword appears.
"""
__DEBUG__ = 0
#
# Check the weight = option. This is done for backward compatibility since
# weights= is the current default syntax.
#
if weight is not None:
if weights is not None:
raise AveragerError(
'Error: You cannot set both weight and weights!. weight is obsolete please use weights only !!!')