-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjules.py
More file actions
1757 lines (1351 loc) · 75.7 KB
/
Copy pathjules.py
File metadata and controls
1757 lines (1351 loc) · 75.7 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
# -*- coding: iso-8859-1 -*-
'''
A collection of functions to facilitate the use of IRIS with JULES-related NETCDF files.
Although some testing has been carried out, use at your own risk!
Crown Copyright 2014, Met Office and licensed under LGPL v3.0 or later:
https://www.gnu.org/licenses/lgpl.html
The unittest suite for these functions is only available internally in the
Met Office (contact karina.williams@metoffice.gov.uk for more information).
Richard Gilham and Karina Williams, Met Office
'''
from __future__ import absolute_import, division, print_function
import os
import subprocess
import tempfile
import datetime
import copy
import iris
if int(iris.__version__[0]) == 1: # made default in Iris 2.0.0
iris.FUTURE.netcdf_promote = True
import numpy as np
import numpy.ma as ma
# version number refers to revision number on the internal Met Office repository,
# not the mirror on the external rep.
__version__ = "last known fcm revision: " + ''.join(filter(str.isdigit, "$Rev: 31131 $"))
# 9.8.2021: updated to JULES6.1
JULES_DIM_NAMES_DEFAULT = {
'land_dim_name':'land',
'pft_dim_name':'pft',
'cpft_dim_name':'cpft',
'nvg_dim_name':'nvg',
'type_dim_name':'type',
'tile_dim_name':'tile',
'soil_dim_name':'soil',
'snow_dim_name':'snow',
'scpool_dim_name':'scpool',
'scalar_dim_name':"scalar",
'sclayer_dim_name':"sclayer",
'nolevs_dim_name':"olevs",
'nfarray_dim_name':'nfarray',
'seed_dim_name':'seed',
'bedrock_dim_name':'bedrock',
'p_rivers_dim_name':'p_rivers',
'bl_level_dim_name':'bllevel',
'soilt_dim_name':'soilt',
'soil_n_pool_dim_name':'snpool',
'tracer_dim_name':'tracer',
'ch4layer_dim_name':'ch4layer',
'ch4subgrid_dim_name':'ch4subgrid',
}
# 9.8.2021: updated to JULES6.1
VAR_NO_LATLON_DIMS = (
'co2_ppmv', 'co2_change_ppmv', 'dtemp_o', 'fa_ocean', 'seed_rain',
'frac_irr_all_tiles', 'irrtiles', 'nirrtile', 'co2_mmr',
'ch4_ppbv',
#'rivers_lat_rp', 'rivers_lon_rp', 'rivers_sto_rp',
'rfm_surfstore_rp',
'rfm_substore_rp', 'rfm_flowin_rp', 'rfm_bflowin_rp'
'set_irrfrac_on_irrtiles'
)
SOME_POSSIBLE_FRAC_NAMES = ("frac", "fractions", "field1391")
STANDARD_TILE_LIST = ['bleaftree', 'nleaftree', 'c3grass', 'c4grass', 'shrub', 'urban', 'lake', 'soil', 'ice']
# if two lats or lons are within this amount of each other, they are considered to be the same
# This needs to be quite large to allow for rotated pole use cases where there seems to be
#quite large rounding errors.
TOLERANCE_LATLON = 0.5E-2 # in degrees
TOLERANCE_LATLONIND = 1.0E-2
def load(filename, constraint=None, cubename=None, conv_to_grid=True, latlon_str=None,
gridfile=None, missingdata=np.nan, nsmax=None, ntiles=None,
jules_dim_names=None, latlon_flatten_function=None, coord_system=None,
**kwargs):
"""
Loads an iris compatible file using iris.load and returns a cubelist instance.
By default assumes a JULES land point format and converts to grid format. This conversion needs
a regular grid.
Args:
* filename:
filenames or list of filenames to read from. Can contain wildcards.
Kwargs:
* constraint:
iris.Constraint object
* cubename:
load only cubes with this name i.e. same as giving constraint=iris.Constraint(name=cubename)
* conv_to_grid:
conv_to_grid = True (note this is the default) assumes that the file being read in is
land points only and puts it on a grid.
* latlon_str:
A tuple of strings (lat_str,lon_str) containing additional names for longitude and latitude
(if latlon_str=None, the standard names e.g 'longitude', 'lon' are searched for).
* gridfile:
The file to read longitudes and latitudes from. Ususally only useful if the input file
does not contain longitudes and latitudes for some reason.
* missingdata:
what the sea points should be set to, if points-only data is converted to a grid.
e.g. 0.0, np.nan, ma.masked. (If missingdata=ma.masked, then the data in the resulting
cube is a np.MaskedArray, otherwise it is a np.ndarray)
* jules_dim_names:
a dictionary containing dimension names e.g. jules_dim_names = {'pft_dim_name':'my_pft'}.
The default names in the JULES User Guide are used for any dimensions not specified here.
* latlon_flatten_function:
function that can be applied to flatten 2D arrays of latitudes and longitudes.
e.g. latlon_flatten_function=np.hstack
* coord_system:
an iris.coord_system object to facilitate pole rotation. Used when the longitudes and latitudes in the cube are
unrotated and the cube needs to be rotated to a regular grid.
Any kwarg not described above is passed straight to iris.load.
"""
if nsmax is not None:
print('Warning: nsmax is an obsolete option')
if ntiles is not None:
print('Warning: ntiles is an obsolete option')
comb_constraint = _combine_constraints(cubename, constraint)
kwargs['callback'] = _combine_callbacks(kwargs, jules_dim_names=jules_dim_names)
cubelist = iris.load(filename, comb_constraint, **kwargs)
cubelist = _tidy_cubelist_after_loading(
cubelist,
filename=filename,
conv_to_grid=conv_to_grid,
latlon_str=latlon_str,
gridfile=gridfile,
missingdata=missingdata,
jules_dim_names=jules_dim_names,
latlon_flatten_function=latlon_flatten_function,
coord_system=coord_system)
return cubelist
def load_cube(filename, constraint=None, cubename=None, conv_to_grid=True, latlon_str=None,
gridfile=None, missingdata=np.nan, nsmax=None, ntiles=None,
jules_dim_names=None, latlon_flatten_function=None, coord_system=None,
**kwargs):
"""
Loads an iris compatible file using iris.load_cube and returns a cube instance.
By default assumes a JULES land point format and converts to grid format. This conversion needs
a regular grid.
Args:
* filename:
filenames or list of filenames to read from. Can contain wildcards.
Kwargs:
* constraint:
iris.Constraint object
* cubename:
load only cubes with this name i.e. same as giving constraint=iris.Constraint(name=cubename)
* conv_to_grid:
conv_to_grid = True (note this is the default) assumes that the file being read in is
land points only and puts it on a grid.
* latlon_str:
A tuple of strings (lat_str,lon_str) containing additional names for longitude and latitude
(if latlon_str=None, the standard names e.g 'longitude', 'lon' are searched for).
* gridfile:
The file to read longitudes and latitudes from. Ususally only useful if the input file
does not contain longitudes and latitudes for some reason.
* missingdata:
what the sea points should be set to, if points-only data is converted to a grid.
e.g. 0.0, np.nan, ma.masked. (If missingdata=ma.masked, then the data in the resulting
cube is a np.MaskedArray, otherwise it is a np.ndarray)
* jules_dim_names:
a dictionary containing dimension names e.g. jules_dim_names = {'pft_dim_name':'my_pft'}.
The default names in the JULES User Guide are used for any dimensions not specified here.
* latlon_flatten_function:
function that can be applied to flatten 2D arrays of latitudes and longitudes.
e.g. latlon_flatten_function=np.hstack
* coord_system:
an iris.coord_system object to facilitate pole rotation. Used when the longitudes and latitudes in the cube are
unrotated and the cube needs to be rotated to a regular grid.
Any kwarg not described above is passed straight to iris.load_cube.
"""
if nsmax is not None:
print('Warning: nsmax is an obsolete option')
if ntiles is not None:
print('Warning: ntiles is an obsolete option')
comb_constraint = _combine_constraints(cubename, constraint)
kwargs['callback'] = _combine_callbacks(kwargs, jules_dim_names=jules_dim_names)
cube = iris.load_cube(filename, comb_constraint, **kwargs)
cubelist = _tidy_cubelist_after_loading(
iris.cube.CubeList([cube]),
filename=filename,
conv_to_grid=conv_to_grid,
latlon_str=latlon_str,
gridfile=gridfile,
missingdata=missingdata,
jules_dim_names=jules_dim_names,
latlon_flatten_function=latlon_flatten_function,
coord_system=coord_system)
if len(cubelist) != 1:
raise UserWarning('expecting a cubelist of length 1, not length '+str(len(cubelist)))
return cubelist[0]
def _tidy_cubelist_after_loading(cubelist, filename=None,
conv_to_grid=True, latlon_str=None,
gridfile=None, missingdata=np.nan,
jules_dim_names=None, latlon_flatten_function=None, coord_system=None):
"""
Takes the cubelist as read in by Iris and tidies it up e.g. by converting from list of points to grid.
Args:
* cubelist:
cubelist to tidy.
Kwargs:
* filename:
filenames or list of filenames to read from. Can contain wildcards.
* constraint:
iris.Constraint object
* cubename:
load only cubes with this name i.e. same as giving constraint=iris.Constraint(name=cubename)
* conv_to_grid:
conv_to_grid = True (note this is the default) assumes that the file being read in is
land points only and puts it on a grid.
* latlon_str:
A tuple of strings (lat_str,lon_str) containing additional names for longitude and latitude
(if latlon_str=None, the standard names e.g 'longitude', 'lon' are searched for).
* gridfile:
The file to read longitudes and latitudes from. Ususally only useful if the input file
does not contain longitudes and latitudes for some reason.
* missingdata:
what the sea points should be set to, if points-only data is converted to a grid.
e.g. 0.0, np.nan, ma.masked. (If missingdata=ma.masked, then the data in the resulting
cube is a np.MaskedArray, otherwise it is a np.ndarray)
* jules_dim_names:
a dictionary containing dimension names e.g. jules_dim_names = {'pft_dim_name':'my_pft'}.
The default names in the JULES User Guide are used for any dimensions not specified here.
* latlon_flatten_function:
function that can be applied to flatten 2D arrays of latitudes and longitudes.
e.g. latlon_flatten_function=np.hstack
* coord_system:
an iris.coord_system object to facilitate pole rotation. Used when the longitudes and latitudes in the cube are
unrotated and the cube needs to be rotated to a regular grid.
"""
if not cubelist:
raise UserWarning('cubelist has no cubes')
if conv_to_grid:
# have a list of points to be converted to a grid
gridcubelist = iris.cube.CubeList()
while cubelist:
temp_cube = cubelist.pop()
if temp_cube.core_data().dtype.kind in ['S', 'a'] or temp_cube.var_name in VAR_NO_LATLON_DIMS:
gridcubelist.append(temp_cube)
else:
try:
gridcubelist.append(
points_to_grid(temp_cube, latlon_str=latlon_str, gridfile=gridfile,
missingdata=missingdata, jules_dim_names=jules_dim_names,
latlon_flatten_function=latlon_flatten_function, coord_system=coord_system))
except _LonlatException:
gridfile = filename
gridcubelist.append(
points_to_grid(temp_cube, latlon_str=latlon_str, gridfile=gridfile,
missingdata=missingdata, jules_dim_names=jules_dim_names,
latlon_flatten_function=latlon_flatten_function, coord_system=coord_system))
return gridcubelist
else:
# no points-to-grid conversion necessary, either because want to keep as points (e.g.
# to save computer memory) or because data is already on a lat,lon grid
for cube in cubelist:
try:
# check whether there are lat, lon coords in cube
all_coord_names = [ coord.name() for coord in cube.coords() ]
(_lat_str, _lon_str) = _get_latlon_str(all_coord_names, latlon_str=latlon_str)
dim_coord_names = [ coord.name() for coord in cube.coords(dim_coords=True) ]
if ( len(cube.coord(_lat_str).points) > 1 and
len(cube.coord(_lon_str).points) > 1 and
not ( _lat_str in dim_coord_names ) and
not ( _lon_str in dim_coord_names )
):
# this special case is needed for e.g. JULES 3.4.1 output files with
# land_only=F, where the lat and lon is in the files, but given
# as a 2D array. Iris reads both the lat and lon as a 2-dim aux coords,
# so want to reduce these to 1-dim and add as dimcoords.
try:
(latcoord, loncoord, latpts, lonpts) = _parse_grid_file(
latlon_str=latlon_str, gridfile=filename, latlon_flatten_function=np.hstack,
coord_system=coord_system)
# don't want to get rid of the auxcoord lat and lon
# until we know whether the new dimcoords are ok
# so give the new dimcoords a temporary name
latcoord.rename('temporary_latitude')
loncoord.rename('temporary_longitude')
cube.add_dim_coord(latcoord, cube.ndim-2) # note this assumes the position of lat and lon
cube.add_dim_coord(loncoord, cube.ndim-1)
cube.remove_coord(_lat_str)
cube.remove_coord(_lon_str)
cube.coord('temporary_latitude').rename('latitude')
cube.coord('temporary_longitude').rename('longitude')
except (ValueError, IndexError):
pass
except _LonlatException:
try:
# this one is handy for old-style JULES land_only=F files, because they're
# not set up so that lat and lon are recognised as coords and instead are
# treated as separate variables
(latcoord, loncoord, latpts, lonpts) = _parse_grid_file(
latlon_str=latlon_str, gridfile=filename, latlon_flatten_function=np.hstack,
coord_system=coord_system)
cube.add_dim_coord(latcoord, cube.ndim-2) # note this assumes the position of lat and lon
cube.add_dim_coord(loncoord, cube.ndim-1)
except (ValueError, IndexError, UserWarning) :
pass
return cubelist
def load_dump(*args, **kwargs):
"""Loads a JULES dump file with jules.load and returns an iris cubelist instance, by calling jules.load
and then setting the long_name of each variable to be the same as it's var_name.
Takes same arguments as jules.load.
Args:
* filename:
filenames or list of filenames to read from. Can contain wildcards.
Kwargs:
* constraint:
iris.Constraint object
* cubename:
load only cubes with this name i.e. same as giving constraint=iris.Constraint(name=cubename)
* conv_to_grid:
conv_to_grid = True (note this is the default) assumes that the file being read in is
land points only and puts it on a grid.
* latlon_str:
A tuple of strings (lat_str,lon_str) containing additional names for longitude and latitude
(if latlon_str=None, the standard names e.g 'longitude', 'lon' are searched for).
* gridfile:
The file to read longitudes and latitudes from. Usually only useful if the input file
does not contain longitudes and latitudes for some reason.
* missingdata:
what the sea points should be set to, if points-only data is converted to a grid.
e.g. 0.0, np.nan, ma.masked. (If missingdata=ma.masked, then the data in the resulting
cube is a np.MaskedArray, otherwise it is a np.ndarray)
* jules_dim_names:
a dictionary containing dimension names e.g. jules_dim_names = {'pft_dim_name':'my_pft'}.
The default names in the JULES User Guide are used for any dimensions not specified here.
* latlon_flatten_function:
function that can be applied to flatten 2D arrays of latitudes and longitudes.
e.g. latlon_flatten_function=np.hstack
* coord_system:
an iris.coord_system object to facilitate pole rotation. Used when the longitudes and latitudes in the cube are
unrotated and the cube needs to be rotated to a regular grid.
Any kwarg not described above is passed straight to iris.load.
"""
cubelist = load(*args, **kwargs)
for cube in cubelist:
cube.long_name = getattr(cube, 'var_name', None)
return cubelist
def _combine_constraints(cubename, constraint):
"""combines the cubename constraint and any other specified constraint"""
if cubename is None:
combined_constraint = constraint
elif constraint is None:
combined_constraint = cubename
else:
combined_constraint = iris.Constraint(name=cubename) & constraint
return combined_constraint
def _combine_callbacks(load_kwargs, jules_dim_names=None):
"""combines the callback that adds recognised dim coords and any other specified callback"""
jules_recognised_dim_names = {'Psuedo':'tile'} # this is needed for some of the older files. Note spelling.
for key,val in JULES_DIM_NAMES_DEFAULT.items():
jules_recognised_dim_names[val] = val
if jules_dim_names is not None:
if key in jules_dim_names:
jules_recognised_dim_names[val] = jules_dim_names[key]
jules_recognised_dim_names[jules_dim_names[key]] = jules_dim_names[key]
if jules_dim_names is not None:
for key,val in jules_dim_names.items():
if key not in jules_recognised_dim_names:
jules_recognised_dim_names[val] = val
def _add_recognised_dim_coords(cube, field, filename):
'''
Adds a dim coord to each anonymous dimension with a recognised name in the netCDF file.
Values of the dim coord are integers starting from 0.
'''
for i,dim_length in enumerate(cube.shape):
if not cube.coords(dim_coords=True, contains_dimension=i):
if field.dimensions[i] in jules_recognised_dim_names:
new_dim_coord = iris.coords.DimCoord(list(range(dim_length)), long_name=jules_recognised_dim_names[field.dimensions[i]])
cube.add_dim_coord(new_dim_coord, (i,))
if 'callback' in load_kwargs.keys():
user_callback = load_kwargs['callback']
else:
user_callback = None
def comb_callback(cube, field, filename):
_callback_discard_empty(cube, field, filename)
_add_recognised_dim_coords(cube, field, filename)
if user_callback is not None:
user_callback(cube, field, filename)
return comb_callback
def _callback_discard_empty(cube, field, filename):
'''
Callback to discard any empty cubes i.e. cubes where one or more dimensions have zero length
'''
if 0 in cube.shape:
raise iris.exceptions.IgnoreCubeException
def load_pftfrac_cube(*args, **kwargs):
"""Deprecated. Please use load_frac_cube instead."""
raise UserWarning("Deprecated function. Please use load_frac_cube instead.")
#load_frac_cube(*args, **kwargs)
def load_frac_cube(filename, frac_names=None, tilelist=None,
**kwargs):
"""Loads a JULES tile fractions mask file with jules.load_cube and returns it as an iris cube.
Take same arguments as jules.load_cube except gridfile is required, not optional)
and also there are two additional optional arguments: frac_names and tilelist.
Args:
* filename:
filenames or list of filenames to read from. Can contain wildcards.
Kwargs:
* frac_names:
list of possible variable names for the variable storing the tile fractions
within the netcdf file
* tilelist:
list of tile names to be added to the cube as an aux coord.
* constraint:
iris.Constraint object
* cubename:
load only cubes with this name i.e. same as giving constraint=iris.Constraint(name=cubename)
* conv_to_grid:
conv_to_grid = True (note this is the default) assumes that the file being read in is
land points only and puts it on a grid.
* latlon_str:
A tuple of strings (lat_str,lon_str) containing additional names for longitude and latitude
(if latlon_str=None, the standard names e.g 'longitude', 'lon' are searched for).
* gridfile:
The file to read longitudes and latitudes from. Ususally only useful if the input file
does not contain longitudes and latitudes for some reason.
* missingdata:
what the sea points should be set to, if points-only data is converted to a grid.
e.g. 0.0, np.nan, ma.masked. (If missingdata=ma.masked, then the data in the resulting
cube is a np.MaskedArray, otherwise it is a np.ndarray)
* jules_dim_names:
a dictionary containing dimension names e.g. jules_dim_names = {'pft_dim_name':'my_pft'}.
The default names in the JULES User Guide are used for any dimensions not specified here.
* latlon_flatten_function:
function that can be applied to flatten 2D arrays of latitudes and longitudes.
e.g. latlon_flatten_function=np.hstack
* coord_system:
an iris.coord_system object to facilitate pole rotation. Used when the longitudes and latitudes in the cube are
unrotated and the cube needs to be rotated to a regular grid.
Any kwarg not described above is passed straight to iris.load_cube.
"""
if not "gridfile" in kwargs:
raise UserWarning('Error: Grid file needed to load a frac file.')
if frac_names is None:
frac_names = SOME_POSSIBLE_FRAC_NAMES
# put the possible names for the variable containing the fraction into lowercase
# don't need _nice_lower here because none of x should be None anyway
frac_names = [x.lower() for x in frac_names]
##ensure that only the variable containing the tile fractions are read in to the cube.
frac_var = iris.Constraint(cube_func=lambda cube: _nice_lower(cube.var_name) in frac_names)
cube = load_cube(filename, constraint=frac_var, **kwargs)
if tilelist is not None:
tilecoord = iris.coords.AuxCoord(tilelist, long_name="frac_name")
cube.add_aux_coord(tilecoord, 0)
return cube
def apply_pft_mask(*args, **kwargs):
"""Deprecated. Please use apply_frac_mask instead"""
raise UserWarning("Deprecated function. Please use apply_frac_mask instead.")
#apply_frac_mask(*args, **kwargs)
def apply_frac_mask(cube, fraccube, targetfrac, threshold, missingdata=np.nan, pos_mask=True):
"""Returns a modified IRIS cube where some data is multiplied by a 'missingdata' value,
according to whether the corresponding element in a tile fraction cube is above or below a threshold
value.
Args:
* cube:
Cube of data to be masked
* fraccube:
Cube of tile fractions. The fraction dimension should have the name 'frac_name'.
* targetfrac:
The name of the fraction to use for masking.
* threshold:
threshold value
Kwargs:
* missingdata:
what to multiply the unwanted data values by. Recommended values are np.nan (default) or 0.0.
* pos_mask:
If pos_mask=True, data less than the threshold is multiplied by the 'missingdata' value. The rest is multiplied by 1.
If pos_mask=False, data greater than the threshold is multiplied by the 'missingdata' value. The rest is multiplied by 1.
"""
maskcube = fraccube.extract(iris.Constraint(frac_name=targetfrac))
if pos_mask:
maskcube.data[maskcube.data < threshold] = missingdata
maskcube.data[maskcube.data >= threshold] = 1.0
else:
maskcube.data[maskcube.data > threshold] = missingdata
maskcube.data[maskcube.data <= threshold] = 1.0
#Deal with the possibility of gridded and point cubes being masked
if len(maskcube.data.shape) == 2:
cube.data[..., :, :] *= maskcube.data[:, :]
elif len(maskcube.data.shape) == 1:
cube.data[..., :] *= maskcube.data[:]
else:
raise ValueError("Unexpected maskcube dimensionality")
return cube
def points_to_grid(pcube, gridfile=None, missingdata=np.nan, latlon_str=None, latlon_flatten_function=None, coord_system=None, **kwargs):
"""
Takes an IRIS cube with land points only data and returns the data as a gridded cube.
Designed to work with JULES output. The output grid should be a regular grid.
Some functionality for rotated poles has been added.
Args:
* pcube:
Iris cube before being put on a grid i.e. containing a list of land point data.
Kwargs:
* constraint:
iris.Constraint object
* cubename:
load only cubes with this name i.e. same as giving constraint=iris.Constraint(name=cubename)
* conv_to_grid:
conv_to_grid = True (note this is the default) assumes that the file being read in is
land points only and puts it on a grid.
* latlon_str:
A tuple of strings (lat_str,lon_str) containing additional names for longitude and latitude
(if latlon_str=None, the standard names e.g 'longitude', 'lon' are searched for).
* gridfile:
The file to read longitudes and latitudes from. Ususally only useful if the input file
does not contain longitudes and latitudes for some reason.
* missingdata:
what the sea points should be set to, if points-only data is converted to a grid.
e.g. 0.0, np.nan, ma.masked. (If missingdata=ma.masked, then the data in the resulting
cube is a np.MaskedArray, otherwise it is a np.ndarray)
* jules_dim_names:
a dictionary containing dimension names e.g. jules_dim_names = {'pft_dim_name':'my_pft'}.
The default names in the JULES User Guide are used for any dimensions not specified here.
* latlon_flatten_function:
function that can be applied to flatten 2D arrays of latitudes and longitudes.
e.g. latlon_flatten_function=np.hstack
* coord_system:
an iris.coord_system object to facilitate pole rotation. Used when the longitudes and latitudes in the cube are
unrotated and the cube needs to be rotated to a regular grid.
"""
if 'nsmax' in kwargs:
print('Warning: nsmax is an obsolete option')
if 'ntiles' in kwargs:
print('Warning: ntiles is an obsolete option')
# assume last element is the land-points dimension
# start list of pcube.data dimensions that should not be copied straight to new cube
not_to_be_copied_over = [len(pcube.core_data().shape)-1]
# list of locations of dim coords which have names (i.e. are not anonymous) in pcube.data
named_coord_loc = []
for coord in pcube.coords(dim_coords=True):
named_coord_loc.extend(pcube.coord_dims(coord))
# list of locations of anonymous dim coords in pcube.data
unnamed_coord_loc = []
for i in range(len(pcube.data.shape)):
if not i in named_coord_loc:
unnamed_coord_loc.append(i)
# list of the names of all named coord (both dim and aux)
all_coord_names = [ coord.name() for coord in pcube.coords() ]
# in a special case, want to get rid of one of the anonymous dimensions right away:
if (
( len(pcube.core_data().shape) >= 2) and
( pcube.core_data().shape[-2] == 1 ) and
( len(pcube.core_data().shape)-2 in unnamed_coord_loc ) and
( 'latitude' in [coord.name() for coord in pcube.aux_coords]) and
( len(pcube.core_data().shape)-2 in pcube.coord_dims(pcube.coords('latitude')[0]) )
):
data = np.mean(pcube.core_data(), axis=-2)
not_to_be_copied_over.append(len(pcube.core_data().shape)-2)
elif ( # as above, except dimension we want to get rid of is a dim_coord called 'y'
( len(pcube.core_data().shape) >= 2) and
( pcube.core_data().shape[-2] == 1 ) and
( 'y' in [coord.name() for coord in pcube.coords(dim_coords=True)] ) and
( pcube.coord_dims(pcube.coord('y')) == (len(pcube.core_data().shape)-2 ,) ) and
( 'latitude' in [coord.name() for coord in pcube.aux_coords]) and
( len(pcube.core_data().shape)-2 in pcube.coord_dims(pcube.coords('latitude')[0]) )
):
data = np.mean(pcube.core_data(), axis=-2)
not_to_be_copied_over.append(len(pcube.core_data().shape)-2)
else:
data = pcube.core_data().copy()
# list of dim coords that are named
reduced_dim_coords = [ coord for coord in pcube.coords(dim_coords=True)
if not set(pcube.coord_dims(coord)).intersection(set(not_to_be_copied_over)) ]
#Set up an empty list to hold iris.coord instances for each named dim coord and its location in pcube.data
cubedimlist = []
#Set up each named 'dim coord and dim' instance we want to copy over and append it onto cubedimlist
for coord in reduced_dim_coords:
cubedimlist.append((coord, pcube.coord_dims(coord)[0]))
# append the unnamed ones we want too, and give them names
idim = 1
n_unknown_dim = len([i for i in unnamed_coord_loc if not i in not_to_be_copied_over])
for i in unnamed_coord_loc:
if not i in not_to_be_copied_over:
ntiles = pcube.core_data().shape[i]
long_name = 'tiles_or_layers_dim_'+ str(idim)
tilecoord = iris.coords.DimCoord(list(range(ntiles)), long_name=long_name) # units='no_unit' is for strings only
cubedimlist.append((tilecoord, i))
idim += 1
# now make the new longitude and latitude coords
if gridfile is None:
(_lat_str, _lon_str) = _get_latlon_str(all_coord_names, latlon_str=latlon_str)
for coord_str in [_lat_str, _lon_str]:
if np.ma.is_masked(pcube.coord(coord_str).points):
print(pcube.coord(coord_str))
raise UserWarning('This function does not work when coordinate is masked. Unmask beforehand.')
#flatten for the point case (treated as 1x1)
latpts = pcube.coord(_lat_str).points.flatten()
lonpts = pcube.coord(_lon_str).points.flatten()
#Determine whether lat and lon points need modifiying, eg for a rotated pole
if isinstance(type(coord_system), type(iris.coord_systems.RotatedGeogCS)):
lonpts, latpts = iris.analysis.cartography.rotate_pole(lonpts, latpts,
coord_system.grid_north_pole_longitude,
coord_system.grid_north_pole_latitude)
# case where lat,lon coords are 2D and neither dim is 1
if ( ( len(pcube.coord(_lat_str).points.shape) == 2 ) & ( not 1 in pcube.coord(_lat_str).points.shape )
& ( len(pcube.coord(_lon_str).points.shape) == 2 ) & ( not 1 in pcube.coord(_lon_str).points.shape ) ):
# check first whether data looks already gridded
test_latcoord = _make_spatial_coord(latpts, 'latitude', coord_system=coord_system)
test_loncoord = _make_spatial_coord(lonpts, 'longitude', coord_system=coord_system)
if test_latcoord.points.shape == np.unique(latpts).shape:
if test_loncoord.points.shape == np.unique(lonpts).shape:
if np.allclose(test_latcoord.points, np.unique(latpts)):
if np.allclose(test_loncoord.points, np.unique(lonpts)):
raise _MaybeAlreadyGriddedException
#Flatten to a point pseudocube
raise UserWarning("UNTESTED CODE- Multipoint pseudo-gridded data- attempting to flattening and regridding.")
pcube = _flatten_pseudogrid(pcube)
latpts = pcube.coord(_lat_str).points.flatten()
lonpts = pcube.coord(_lon_str).points.flatten()
latcoord = _make_spatial_coord(latpts, 'latitude', coord_system=coord_system)
loncoord = _make_spatial_coord(lonpts, 'longitude', coord_system=coord_system)
else:
(latcoord, loncoord, latpts, lonpts) = _parse_grid_file(
latlon_str=latlon_str, gridfile=gridfile, latlon_flatten_function=latlon_flatten_function,
coord_system=coord_system)
#Get the lat/lon value for each index.
#This is where we need to work in rotated pole world.
if len(latcoord.points) == 1:
latind_int = np.zeros(len(latpts), dtype=int)
else:
latind_float = (latpts - latcoord.points[0]) / (latcoord.points[1] - latcoord.points[0])
latind_int = np.rint(latind_float).astype(int)
if not np.allclose( latind_int.astype('float'), latind_float, atol=TOLERANCE_LATLONIND ):
raise UserWarning('lats not interpreted correctly')
if len(loncoord.points) == 1:
lonind_int = np.zeros(len(lonpts), dtype=int)
else:
lonind_float = (lonpts - loncoord.points[0]) / (loncoord.points[1] - loncoord.points[0])
lonind_int = np.rint(lonind_float).astype(int)
if not np.allclose( lonind_int.astype('float'), lonind_float, atol=TOLERANCE_LATLONIND ):
raise UserWarning('lons not interpreted correctly')
cubedimlist.append((latcoord, len(cubedimlist)))
cubedimlist.append((loncoord, len(cubedimlist)))
griddata_shape = [dim[0].shape[0] for dim in cubedimlist]
if missingdata is ma.masked: # n.b. need the 'is' here rather than ==
griddata = ma.masked_all(griddata_shape)
data_for_copying = data
else:
griddata = np.zeros(griddata_shape)
griddata[:] = missingdata
if np.ma.is_masked(data):
data_for_copying = data.filled(missingdata)
else:
data_for_copying = data
if griddata.shape[:-2] != data.shape[:-1]:
print(cubedimlist)
print(griddata.shape)
print(data.shape)
raise UserWarning("either griddata or data has an unexpected shape")
if data.shape[-1] - 1 > len(latind_int):
raise _MaybeAlreadyGriddedException('Latitudes are not consistent with the data.')
for gridpt in range(data.shape[-1]):
griddata[..., latind_int[gridpt], lonind_int[gridpt]] = data_for_copying[..., gridpt]
# now to copy over any aux coords we want
# n.b. do not want to copy over any aux coords which depend on one we're getting rid of
aux_coords_and_dims = []
for coord in pcube.aux_coords:
dim_tuple = pcube.coord_dims(coord)
if set(dim_tuple).intersection(set(not_to_be_copied_over)) == set([]):
aux_coords_and_dims.append((coord, dim_tuple))
#Make the cube and go home
cube = iris.cube.Cube(griddata,
dim_coords_and_dims = cubedimlist,
aux_coords_and_dims = aux_coords_and_dims,
standard_name = pcube.standard_name,
long_name = pcube.long_name,
var_name = pcube.var_name,
units = pcube.units,
cell_methods = pcube.cell_methods,
attributes = pcube.attributes
)
#aux_factories = pcube.aux_factories, # need to deal with this in a better way
for name in ['latitude', 'longitude']:
if [coord.standard_name for coord in cube.coords(dim_coords=True)].count(name) > 1:
raise _MaybeAlreadyGriddedException('a cube has ended up with more than one dim coord with '
'the standard_name "' + name + '"')
return cube
def _parse_grid_file(latlon_str=None, gridfile='dummy', latlon_flatten_function=None, coord_system=None):
"""Loads a JULES land point-only grid definition file and returns a tuple of iris coordinates for lat and lon"""
cubelist = iris.load(gridfile)
try:
var_name_list = [cube.var_name for cube in cubelist]
(_lat_str, _lon_str) = _get_latlon_str(var_name_list, latlon_str=latlon_str)
latdim = var_name_list.index(_lat_str)
londim = var_name_list.index(_lon_str)
if len(cubelist[latdim].data.shape) == 1 :
latdata = cubelist[latdim].data
elif latlon_flatten_function != None:
try:
latdata = latlon_flatten_function(cubelist[latdim].data)
except (ValueError, IndexError):
print('this latlon_flatten_function did not work')
raise _LonlatException
else:
print('warning: latitude coord found but not list of points. Maybe think about setting a latlon_flatten_function?')
raise _LonlatException
if len(cubelist[londim].data.shape) == 1 :
londata = cubelist[londim].data
elif latlon_flatten_function != None:
try:
londata = latlon_flatten_function(cubelist[londim].data)
except (ValueError, IndexError):
print('this latlon_flatten_function did not work')
raise _LonlatException
else:
print('warning: longitude coord found but not list of points. Maybe think about setting a latlon_flatten_function?')
raise _LonlatException
latpts = latdata
lonpts = londata
except _LonlatException:
cube0 = cubelist[0] #fixme: generalise so that it checks each cube in cubelist
coord_name_list = [ coord.name() for coord in cube0.coords() ]
(_lat_str, _lon_str) = _get_latlon_str(coord_name_list, latlon_str=latlon_str)
# flatten() is needed because might have a (1,npoints) array or lat, lon as auxcoords
# that are in the process of being reduced to dim coords
latpts = cube0.coord(_lat_str).points.flatten()
lonpts = cube0.coord(_lon_str).points.flatten()
#Determine whether lat and lon points need modifiying, eg for a rotated pole
if isinstance(type(coord_system), type(iris.coord_systems.RotatedGeogCS)):
lonpts, latpts = iris.analysis.cartography.rotate_pole(lonpts, latpts,
coord_system.grid_north_pole_longitude,
coord_system.grid_north_pole_latitude)
latcoord = _make_spatial_coord(latpts, 'latitude', coord_system=coord_system)
loncoord = _make_spatial_coord(lonpts, 'longitude', coord_system=coord_system)
return (latcoord, loncoord, latpts, lonpts)
def _make_spatial_coord(coord, name, units='degrees', tolerance = TOLERANCE_LATLON, coord_system=None):
"""Takes an unordered list of grid box lat/lons and generates an iris coords instance assuming a regular grid
and assuming that two points are next to each other in the grid
"""
coordset = np.sort(np.unique(coord))
if len(coordset) == 1:
step = 0.0
elif len(coordset) == 2:
step = abs(coordset[1] - coordset[0])
else:
steparr = np.diff( coordset )
steparr = steparr[np.nonzero( steparr > tolerance )]
stepmin = np.min( steparr )
step = np.mean( steparr[np.nonzero( steparr < stepmin + tolerance )] )
normalised_step = steparr / step
if not np.allclose( np.rint(normalised_step).astype('float'), normalised_step, atol=tolerance):
raise Exception('problem converting this coord - check grid is regular and that two points are next to each other')
if step < tolerance:
coordlist = coordset[0]
else:
# old method using arange:
#coordlist = np.arange(min(coordset), max(coordset) + step, step)
# new method using linspace:
coordlist = np.linspace(min(coordset), max(coordset), np.rint((max(coordset) - min(coordset)) / step).astype(int) + 1)
iriscoord = iris.coords.DimCoord(coordlist, standard_name=name, units=units, coord_system=coord_system)
return iriscoord
def save(source, target, lsmask=None, missingdata=np.nan, lsmask_missingdata_str='nan',
landpointsonly=True, latlon_str=None, data2D = False, user_def_start_corner=None, **kwargs):
"""
Saves an iris cube/cubelist/cube sequence. Requires CDO. Has the option of just outputting
landpoints, in a format suitable for JULES i.e. data stored in a 1 x npoints array where npoints
is the number of land points.
Args:
* source:
A iris cube/cubelist/cube sequence
* target:
Output filename.
Kwargs:
* lsmask:
The land-sea mask as a cube
* landpointsonly:
landpointsonly = True means gridded data will be converted to a list of land points before outputting.
* missingdata:
What the missing data in the output array will be set to.
* lsmask_missingdata_str:
Specifies how sea points are labelled in lsmask. Can be either 'nan' or 'zeros'. For an array
of Trues and Falses, where False labels sea points, pick 'zeros'.
* latlon_str:
A tuple (lat_str,lon_str) containing the variable names for longitude and latitude in lsmask.
* data2D:
If data2D=True, there will be two spatial dimensions with sizes (1,npoints), rather than just one with size (npoints).
This is a similar format to the JULES output files.
* user_def_start_corner:
When converting to a list of points, a particular order of points is chosen as default. This keyword allows
this choice to be overridden. See grid_to_points for more information.
"""
print('jules.save: just entering function at '+str(datetime.datetime.now()))
# force netcdf output
saver = iris.fileformats.netcdf.save