/
fieldset.py
1156 lines (1017 loc) · 70.5 KB
/
fieldset.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
from copy import deepcopy
from glob import glob
from os import path
import dask.array as da
import numpy as np
import warnings
from parcels.field import Field, DeferredArray
from parcels.field import NestedField
from parcels.field import SummedField
from parcels.field import VectorField
from parcels.grid import Grid
from parcels.gridset import GridSet
from parcels.tools.converters import TimeConverter, convert_xarray_time_units
from parcels.tools.statuscodes import TimeExtrapolationError
from parcels.tools.loggers import logger
try:
from mpi4py import MPI
except:
MPI = None
__all__ = ['FieldSet']
class FieldSet(object):
"""FieldSet class that holds hydrodynamic data needed to execute particles
:param U: :class:`parcels.field.Field` object for zonal velocity component
:param V: :class:`parcels.field.Field` object for meridional velocity component
:param fields: Dictionary of additional :class:`parcels.field.Field` objects
"""
def __init__(self, U, V, fields=None):
self.gridset = GridSet()
self.completed = False
if U:
self.add_field(U, 'U')
self.time_origin = self.U.grid.time_origin if isinstance(self.U, Field) else self.U[0].grid.time_origin
if V:
self.add_field(V, 'V')
# Add additional fields as attributes
if fields:
for name, field in fields.items():
self.add_field(field, name)
self.compute_on_defer = None
self.add_UVfield()
@staticmethod
def checkvaliddimensionsdict(dims):
for d in dims:
if d not in ['lon', 'lat', 'depth', 'time']:
raise NameError('%s is not a valid key in the dimensions dictionary' % d)
@classmethod
def from_data(cls, data, dimensions, transpose=False, mesh='spherical',
allow_time_extrapolation=None, time_periodic=False, **kwargs):
"""Initialise FieldSet object from raw data
:param data: Dictionary mapping field names to numpy arrays.
Note that at least a 'U' and 'V' numpy array need to be given, and that
the built-in Advection kernels assume that U and V are in m/s
1. If data shape is [xdim, ydim], [xdim, ydim, zdim], [xdim, ydim, tdim] or [xdim, ydim, zdim, tdim],
whichever is relevant for the dataset, use the flag transpose=True
2. If data shape is [ydim, xdim], [zdim, ydim, xdim], [tdim, ydim, xdim] or [tdim, zdim, ydim, xdim],
use the flag transpose=False (default value)
3. If data has any other shape, you first need to reorder it
:param dimensions: Dictionary mapping field dimensions (lon,
lat, depth, time) to numpy arrays.
Note that dimensions can also be a dictionary of dictionaries if
dimension names are different for each variable
(e.g. dimensions['U'], dimensions['V'], etc).
:param transpose: Boolean whether to transpose data on read-in
:param mesh: String indicating the type of mesh coordinates and
units used during velocity interpolation, see also `this tutorial <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_unitconverters.ipynb>`_:
1. spherical (default): Lat and lon in degree, with a
correction for zonal velocity U near the poles.
2. flat: No conversion, lat/lon are assumed to be in m.
:param allow_time_extrapolation: boolean whether to allow for extrapolation
(i.e. beyond the last available time snapshot)
Default is False if dimensions includes time, else True
:param time_periodic: To loop periodically over the time component of the Field. It is set to either False or the length of the period (either float in seconds or datetime.timedelta object). (Default: False)
This flag overrides the allow_time_interpolation and sets it to False
Usage examples
==============
* `Analytical advection <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_analyticaladvection.ipynb>`_
* `Diffusion <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_diffusion.ipynb>`_
* `Interpolation <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_interpolation.ipynb>`_
* `Unit converters <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_unitconverters.ipynb>`_
"""
fields = {}
for name, datafld in data.items():
# Use dimensions[name] if dimensions is a dict of dicts
dims = dimensions[name] if name in dimensions else dimensions
cls.checkvaliddimensionsdict(dims)
if allow_time_extrapolation is None:
allow_time_extrapolation = False if 'time' in dims else True
lon = dims['lon']
lat = dims['lat']
depth = np.zeros(1, dtype=np.float32) if 'depth' not in dims else dims['depth']
time = np.zeros(1, dtype=np.float64) if 'time' not in dims else dims['time']
time = np.array(time) if not isinstance(time, np.ndarray) else time
if isinstance(time[0], np.datetime64):
time_origin = TimeConverter(time[0])
time = np.array([time_origin.reltime(t) for t in time])
else:
time_origin = TimeConverter(0)
grid = Grid.create_grid(lon, lat, depth, time, time_origin=time_origin, mesh=mesh)
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_data'
fields[name] = Field(name, datafld, grid=grid, transpose=transpose,
allow_time_extrapolation=allow_time_extrapolation, time_periodic=time_periodic, **kwargs)
u = fields.pop('U', None)
v = fields.pop('V', None)
return cls(u, v, fields=fields)
def add_field(self, field, name=None):
"""Add a :class:`parcels.field.Field` object to the FieldSet
:param field: :class:`parcels.field.Field` object to be added
:param name: Name of the :class:`parcels.field.Field` object to be added
For usage examples see the following tutorials:
* `Nested Fields <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_NestedFields.ipynb>`_
* `Unit converters <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_unitconverters.ipynb>`_
"""
if self.completed:
raise RuntimeError("FieldSet has already been completed. Are you trying to add a Field after you've created the ParticleSet?")
name = field.name if name is None else name
if hasattr(self, name): # check if Field with same name already exists when adding new Field
raise RuntimeError("FieldSet already has a Field with name '%s'" % name)
if isinstance(field, SummedField):
setattr(self, name, field)
field.name = name
for fld in field:
self.gridset.add_grid(fld)
fld.fieldset = self
elif isinstance(field, NestedField):
setattr(self, name, field)
for fld in field:
self.gridset.add_grid(fld)
fld.fieldset = self
elif isinstance(field, list):
raise NotImplementedError('FieldLists have been replaced by SummedFields. Use the + operator instead of []')
else:
setattr(self, name, field)
self.gridset.add_grid(field)
field.fieldset = self
def add_constant_field(self, name, value, mesh='flat'):
"""Wrapper function to add a Field that is constant in space,
useful e.g. when using constant horizontal diffusivity
:param name: Name of the :class:`parcels.field.Field` object to be added
:param value: Value of the constant field (stored as 32-bit float)
:param units: Optional UnitConverter object, to convert units
(e.g. for Horizontal diffusivity from m2/s to degree2/s)
"""
self.add_field(Field(name, value, lon=0, lat=0, mesh=mesh))
def add_vector_field(self, vfield):
"""Add a :class:`parcels.field.VectorField` object to the FieldSet
:param vfield: :class:`parcels.field.VectorField` object to be added
"""
setattr(self, vfield.name, vfield)
for v in vfield.__dict__.values():
if isinstance(v, Field) and (v not in self.get_fields()):
self.add_field(v)
vfield.fieldset = self
if isinstance(vfield, NestedField):
for f in vfield:
f.fieldset = self
def add_UVfield(self):
if not hasattr(self, 'UV') and hasattr(self, 'U') and hasattr(self, 'V'):
if isinstance(self.U, SummedField):
self.add_vector_field(SummedField('UV', self.U, self.V))
elif isinstance(self.U, NestedField):
self.add_vector_field(NestedField('UV', self.U, self.V))
else:
self.add_vector_field(VectorField('UV', self.U, self.V))
if not hasattr(self, 'UVW') and hasattr(self, 'W'):
if isinstance(self.U, SummedField):
self.add_vector_field(SummedField('UVW', self.U, self.V, self.W))
elif isinstance(self.U, NestedField):
self.add_vector_field(NestedField('UVW', self.U, self.V, self.W))
else:
self.add_vector_field(VectorField('UVW', self.U, self.V, self.W))
def check_complete(self):
assert self.U, 'FieldSet does not have a Field named "U"'
assert self.V, 'FieldSet does not have a Field named "V"'
for attr, value in vars(self).items():
if type(value) is Field:
assert value.name == attr, 'Field %s.name (%s) is not consistent' % (value.name, attr)
def check_velocityfields(U, V, W):
if (U.interp_method == 'cgrid_velocity' and V.interp_method != 'cgrid_velocity') or \
(U.interp_method != 'cgrid_velocity' and V.interp_method == 'cgrid_velocity'):
raise ValueError("If one of U,V.interp_method='cgrid_velocity', the other should be too")
if 'linear_invdist_land_tracer' in [U.interp_method, V.interp_method]:
raise NotImplementedError("interp_method='linear_invdist_land_tracer' is not implemented for U and V Fields")
if U.interp_method == 'cgrid_velocity':
if U.grid.xdim == 1 or U.grid.ydim == 1 or V.grid.xdim == 1 or V.grid.ydim == 1:
raise NotImplementedError('C-grid velocities require longitude and latitude dimensions at least length 2')
if U.gridindexingtype not in ['nemo', 'mitgcm', 'mom5', 'pop']:
raise ValueError("Field.gridindexing has to be one of 'nemo', 'mitgcm', 'mom5' or 'pop'")
if V.gridindexingtype != U.gridindexingtype or (W and W.gridindexingtype != U.gridindexingtype):
raise ValueError('Not all velocity Fields have the same gridindexingtype')
if U.cast_data_dtype != V.cast_data_dtype or (W and W.cast_data_dtype != U.cast_data_dtype):
raise ValueError('Not all velocity Fields have the same dtype')
if isinstance(self.U, (SummedField, NestedField)):
w = self.W if hasattr(self, 'W') else [None]*len(self.U)
for U, V, W in zip(self.U, self.V, w):
check_velocityfields(U, V, W)
else:
W = self.W if hasattr(self, 'W') else None
check_velocityfields(self.U, self.V, W)
for fld in [self.U, self.V]:
if isinstance(fld, SummedField) and fld[0].interp_method in ['partialslip', 'freeslip'] and np.any([fld[0].grid is not f.grid for f in fld]):
warnings.warn('Slip boundary conditions may not work well with SummedFields. Be careful', UserWarning)
for g in self.gridset.grids:
g.check_zonal_periodic()
if len(g.time) == 1:
continue
assert isinstance(g.time_origin.time_origin, type(self.time_origin.time_origin)), 'time origins of different grids must be have the same type'
g.time = g.time + self.time_origin.reltime(g.time_origin)
if g.defer_load:
g.time_full = g.time_full + self.time_origin.reltime(g.time_origin)
g.time_origin = self.time_origin
self.add_UVfield()
ccode_fieldnames = []
counter = 1
for fld in self.get_fields():
if fld.name not in ccode_fieldnames:
fld.ccode_name = fld.name
else:
fld.ccode_name = fld.name + str(counter)
counter += 1
ccode_fieldnames.append(fld.ccode_name)
for f in self.get_fields():
if type(f) in [VectorField, NestedField, SummedField] or f.dataFiles is None:
continue
if f.grid.depth_field is not None:
if f.grid.depth_field == 'not_yet_set':
raise ValueError("If depth dimension is set at 'not_yet_set', it must be added later using Field.set_depth_from_field(field)")
if not f.grid.defer_load:
depth_data = f.grid.depth_field.data
f.grid.depth = depth_data if isinstance(depth_data, np.ndarray) else np.array(depth_data)
self.completed = True
@classmethod
def parse_wildcards(cls, paths, filenames, var):
if not isinstance(paths, list):
paths = sorted(glob(str(paths)))
if len(paths) == 0:
notfound_paths = filenames[var] if isinstance(filenames, dict) and var in filenames else filenames
raise IOError("FieldSet files not found for variable %s: %s" % (var, str(notfound_paths)))
for fp in paths:
if not path.exists(fp):
raise IOError("FieldSet file not found: %s" % str(fp))
return paths
@classmethod
def from_netcdf(cls, filenames, variables, dimensions, indices=None, fieldtype=None,
mesh='spherical', timestamps=None, allow_time_extrapolation=None, time_periodic=False,
deferred_load=True, chunksize=None, **kwargs):
"""Initialises FieldSet object from NetCDF files
:param filenames: Dictionary mapping variables to file(s). The
filepath may contain wildcards to indicate multiple files
or be a list of file.
filenames can be a list [files], a dictionary {var:[files]},
a dictionary {dim:[files]} (if lon, lat, depth and/or data not stored in same files as data),
or a dictionary of dictionaries {var:{dim:[files]}}.
time values are in filenames[data]
:param variables: Dictionary mapping variables to variable names in the netCDF file(s).
Note that the built-in Advection kernels assume that U and V are in m/s
:param dimensions: Dictionary mapping data dimensions (lon,
lat, depth, time, data) to dimensions in the netCF file(s).
Note that dimensions can also be a dictionary of dictionaries if
dimension names are different for each variable
(e.g. dimensions['U'], dimensions['V'], etc).
:param indices: Optional dictionary of indices for each dimension
to read from file(s), to allow for reading of subset of data.
Default is to read the full extent of each dimension.
Note that negative indices are not allowed.
:param fieldtype: Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
:param mesh: String indicating the type of mesh coordinates and
units used during velocity interpolation, see also `this tuturial <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_unitconverters.ipynb>`_:
1. spherical (default): Lat and lon in degree, with a
correction for zonal velocity U near the poles.
2. flat: No conversion, lat/lon are assumed to be in m.
:param timestamps: list of lists or array of arrays containing the timestamps for
each of the files in filenames. Outer list/array corresponds to files, inner
array corresponds to indices within files.
Default is None if dimensions includes time.
:param allow_time_extrapolation: boolean whether to allow for extrapolation
(i.e. beyond the last available time snapshot)
Default is False if dimensions includes time, else True
:param time_periodic: To loop periodically over the time component of the Field. It is set to either False or the length of the period (either float in seconds or datetime.timedelta object). (Default: False)
This flag overrides the allow_time_interpolation and sets it to False
:param deferred_load: boolean whether to only pre-load data (in deferred mode) or
fully load them (default: True). It is advised to deferred load the data, since in
that case Parcels deals with a better memory management during particle set execution.
deferred_load=False is however sometimes necessary for plotting the fields.
:param interp_method: Method for interpolation. Options are 'linear' (default), 'nearest',
'linear_invdist_land_tracer', 'cgrid_velocity', 'cgrid_tracer' and 'bgrid_velocity'
:param gridindexingtype: The type of gridindexing. Either 'nemo' (default) or 'mitgcm' are supported.
See also the Grid indexing documentation on oceanparcels.org
:param chunksize: size of the chunks in dask loading. Default is None (no chunking). Can be None or False (no chunking),
'auto' (chunking is done in the background, but results in one grid per field individually), or a dict in the format
'{parcels_varname: {netcdf_dimname : (parcels_dimname, chunksize_as_int)}, ...}', where 'parcels_dimname' is one of ('time', 'depth', 'lat', 'lon')
:param netcdf_engine: engine to use for netcdf reading in xarray. Default is 'netcdf',
but in cases where this doesn't work, setting netcdf_engine='scipy' could help
For usage examples see the following tutorials:
* `Basic Parcels setup <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/parcels_tutorial.ipynb>`_
* `Argo floats <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_Argofloats.ipynb>`_
* `Timestamps <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_timestamps.ipynb>`_
* `Time-evolving depth dimensions <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_timevaryingdepthdimensions.ipynb>`_
"""
# Ensure that times are not provided both in netcdf file and in 'timestamps'.
if timestamps is not None and 'time' in dimensions:
logger.warning_once("Time already provided, defaulting to dimensions['time'] over timestamps.")
timestamps = None
fields = {}
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_netcdf'
for var, name in variables.items():
# Resolve all matching paths for the current variable
paths = filenames[var] if type(filenames) is dict and var in filenames else filenames
if type(paths) is not dict:
paths = cls.parse_wildcards(paths, filenames, var)
else:
for dim, p in paths.items():
paths[dim] = cls.parse_wildcards(p, filenames, var)
# Use dimensions[var] and indices[var] if either of them is a dict of dicts
dims = dimensions[var] if var in dimensions else dimensions
cls.checkvaliddimensionsdict(dims)
inds = indices[var] if (indices and var in indices) else indices
fieldtype = fieldtype[var] if (fieldtype and var in fieldtype) else fieldtype
varchunksize = chunksize[var] if (chunksize and var in chunksize) else chunksize # <varname> -> {<netcdf_dimname>: (<parcels_dimname>, <chunksize_as_int_numeral>) }
grid = None
dFiles = None
# check if grid has already been processed (i.e. if other fields have same filenames, dimensions and indices)
for procvar, _ in fields.items():
procdims = dimensions[procvar] if procvar in dimensions else dimensions
procinds = indices[procvar] if (indices and procvar in indices) else indices
procpaths = filenames[procvar] if isinstance(filenames, dict) and procvar in filenames else filenames
procchunk = chunksize[procvar] if (chunksize and procvar in chunksize) else chunksize
nowpaths = filenames[var] if isinstance(filenames, dict) and var in filenames else filenames
if procdims == dims and procinds == inds:
possibly_samegrid = True
if procchunk != varchunksize:
for dim in varchunksize:
if varchunksize[dim][1] != procchunk[dim][1]:
possibly_samegrid &= False
if not possibly_samegrid:
break
if varchunksize == 'auto':
break
if 'depth' in dims and dims['depth'] == 'not_yet_set':
break
processedGrid = False
if ((not isinstance(filenames, dict)) or filenames[procvar] == filenames[var]):
processedGrid = True
elif isinstance(filenames[procvar], dict):
processedGrid = True
for dim in ['lon', 'lat', 'depth']:
if dim in dimensions:
processedGrid *= filenames[procvar][dim] == filenames[var][dim]
if processedGrid:
grid = fields[procvar].grid
if procpaths == nowpaths:
dFiles = fields[procvar].dataFiles
break
fields[var] = Field.from_netcdf(paths, (var, name), dims, inds, grid=grid, mesh=mesh, timestamps=timestamps,
allow_time_extrapolation=allow_time_extrapolation,
time_periodic=time_periodic, deferred_load=deferred_load,
fieldtype=fieldtype, chunksize=varchunksize, dataFiles=dFiles, **kwargs)
u = fields.pop('U', None)
v = fields.pop('V', None)
return cls(u, v, fields=fields)
@classmethod
def from_nemo(cls, filenames, variables, dimensions, indices=None, mesh='spherical',
allow_time_extrapolation=None, time_periodic=False,
tracer_interp_method='cgrid_tracer', chunksize=None, **kwargs):
"""Initialises FieldSet object from NetCDF files of Curvilinear NEMO fields.
See `here <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_nemo_curvilinear.ipynb>`_
for a detailed tutorial on the setup for 2D NEMO fields and `here <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_nemo_3D.ipynb>`_
for the tutorial on the setup for 3D NEMO fields.
See `here <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/documentation_indexing.ipynb>`_
for a more detailed explanation of the different methods that can be used for c-grid datasets.
:param filenames: Dictionary mapping variables to file(s). The
filepath may contain wildcards to indicate multiple files,
or be a list of file.
filenames can be a list [files], a dictionary {var:[files]},
a dictionary {dim:[files]} (if lon, lat, depth and/or data not stored in same files as data),
or a dictionary of dictionaries {var:{dim:[files]}}
time values are in filenames[data]
:param variables: Dictionary mapping variables to variable names in the netCDF file(s).
Note that the built-in Advection kernels assume that U and V are in m/s
:param dimensions: Dictionary mapping data dimensions (lon,
lat, depth, time, data) to dimensions in the netCF file(s).
Note that dimensions can also be a dictionary of dictionaries if
dimension names are different for each variable.
Watch out: NEMO is discretised on a C-grid:
U and V velocities are not located on the same nodes (see https://www.nemo-ocean.eu/doc/node19.html ).
+-----------------------------+-----------------------------+-----------------------------+
| | V[k,j+1,i+1] | |
+-----------------------------+-----------------------------+-----------------------------+
|U[k,j+1,i] |W[k:k+2,j+1,i+1],T[k,j+1,i+1]|U[k,j+1,i+1] |
+-----------------------------+-----------------------------+-----------------------------+
| | V[k,j,i+1] + |
+-----------------------------+-----------------------------+-----------------------------+
To interpolate U, V velocities on the C-grid, Parcels needs to read the f-nodes,
which are located on the corners of the cells.
(for indexing details: https://www.nemo-ocean.eu/doc/img360.png )
In 3D, the depth is the one corresponding to W nodes
The gridindexingtype is set to 'nemo'. See also the Grid indexing documentation on oceanparcels.org
:param indices: Optional dictionary of indices for each dimension
to read from file(s), to allow for reading of subset of data.
Default is to read the full extent of each dimension.
Note that negative indices are not allowed.
:param fieldtype: Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
:param mesh: String indicating the type of mesh coordinates and
units used during velocity interpolation, see also `this tutorial <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_unitconverters.ipynb>`_:
1. spherical (default): Lat and lon in degree, with a
correction for zonal velocity U near the poles.
2. flat: No conversion, lat/lon are assumed to be in m.
:param allow_time_extrapolation: boolean whether to allow for extrapolation
(i.e. beyond the last available time snapshot)
Default is False if dimensions includes time, else True
:param time_periodic: To loop periodically over the time component of the Field. It is set to either False or the length of the period (either float in seconds or datetime.timedelta object). (Default: False)
This flag overrides the allow_time_interpolation and sets it to False
:param tracer_interp_method: Method for interpolation of tracer fields. It is recommended to use 'cgrid_tracer' (default)
Note that in the case of from_nemo() and from_cgrid(), the velocity fields are default to 'cgrid_velocity'
:param chunksize: size of the chunks in dask loading. Default is None (no chunking)
"""
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_nemo'
if kwargs.pop('gridindexingtype', 'nemo') != 'nemo':
raise ValueError("gridindexingtype must be 'nemo' in FieldSet.from_nemo(). Use FieldSet.from_c_grid_dataset otherwise")
fieldset = cls.from_c_grid_dataset(filenames, variables, dimensions, mesh=mesh, indices=indices, time_periodic=time_periodic,
allow_time_extrapolation=allow_time_extrapolation, tracer_interp_method=tracer_interp_method,
chunksize=chunksize, gridindexingtype='nemo', **kwargs)
if hasattr(fieldset, 'W'):
fieldset.W.set_scaling_factor(-1.)
return fieldset
@classmethod
def from_mitgcm(cls, filenames, variables, dimensions, indices=None, mesh='spherical',
allow_time_extrapolation=None, time_periodic=False,
tracer_interp_method='cgrid_tracer', chunksize=None, **kwargs):
"""Initialises FieldSet object from NetCDF files of MITgcm fields.
All parameters and keywords are exactly the same as for FieldSet.from_nemo(), except that
gridindexing is set to 'mitgcm' for grids that have the shape
+-----------------------------+-----------------------------+-----------------------------+
| | V[k,j+1,i] | |
+-----------------------------+-----------------------------+-----------------------------+
|U[k,j,i] | W[k-1:k,j,i], T[k,j,i] |U[k,j,i+1] |
+-----------------------------+-----------------------------+-----------------------------+
| | V[k,j,i] + |
+-----------------------------+-----------------------------+-----------------------------+
For indexing details: https://mitgcm.readthedocs.io/en/latest/algorithm/algorithm.html#spatial-discretization-of-the-dynamical-equations
Note that vertical velocity (W) is assumed postive in the positive z direction (which is upward in MITgcm)
"""
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_mitgcm'
if kwargs.pop('gridindexingtype', 'mitgcm') != 'mitgcm':
raise ValueError("gridindexingtype must be 'mitgcm' in FieldSet.from_mitgcm(). Use FieldSet.from_c_grid_dataset otherwise")
fieldset = cls.from_c_grid_dataset(filenames, variables, dimensions, mesh=mesh, indices=indices, time_periodic=time_periodic,
allow_time_extrapolation=allow_time_extrapolation, tracer_interp_method=tracer_interp_method,
chunksize=chunksize, gridindexingtype='mitgcm', **kwargs)
return fieldset
@classmethod
def from_c_grid_dataset(cls, filenames, variables, dimensions, indices=None, mesh='spherical',
allow_time_extrapolation=None, time_periodic=False,
tracer_interp_method='cgrid_tracer', gridindexingtype='nemo', chunksize=None, **kwargs):
"""Initialises FieldSet object from NetCDF files of Curvilinear NEMO fields.
See `here <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/documentation_indexing.ipynb>`_
for a more detailed explanation of the different methods that can be used for c-grid datasets.
:param filenames: Dictionary mapping variables to file(s). The
filepath may contain wildcards to indicate multiple files,
or be a list of file.
filenames can be a list [files], a dictionary {var:[files]},
a dictionary {dim:[files]} (if lon, lat, depth and/or data not stored in same files as data),
or a dictionary of dictionaries {var:{dim:[files]}}
time values are in filenames[data]
:param variables: Dictionary mapping variables to variable
names in the netCDF file(s).
:param dimensions: Dictionary mapping data dimensions (lon,
lat, depth, time, data) to dimensions in the netCF file(s).
Note that dimensions can also be a dictionary of dictionaries if
dimension names are different for each variable.
Watch out: NEMO is discretised on a C-grid:
U and V velocities are not located on the same nodes (see https://www.nemo-ocean.eu/doc/node19.html ).
+-----------------------------+-----------------------------+-----------------------------+
| | V[k,j+1,i+1] | |
+-----------------------------+-----------------------------+-----------------------------+
|U[k,j+1,i] |W[k:k+2,j+1,i+1],T[k,j+1,i+1]|U[k,j+1,i+1] |
+-----------------------------+-----------------------------+-----------------------------+
| | V[k,j,i+1] + |
+-----------------------------+-----------------------------+-----------------------------+
To interpolate U, V velocities on the C-grid, Parcels needs to read the f-nodes,
which are located on the corners of the cells.
(for indexing details: https://www.nemo-ocean.eu/doc/img360.png )
In 3D, the depth is the one corresponding to W nodes.
:param indices: Optional dictionary of indices for each dimension
to read from file(s), to allow for reading of subset of data.
Default is to read the full extent of each dimension.
Note that negative indices are not allowed.
:param fieldtype: Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
:param mesh: String indicating the type of mesh coordinates and
units used during velocity interpolation:
1. spherical (default): Lat and lon in degree, with a
correction for zonal velocity U near the poles.
2. flat: No conversion, lat/lon are assumed to be in m.
:param allow_time_extrapolation: boolean whether to allow for extrapolation
(i.e. beyond the last available time snapshot)
Default is False if dimensions includes time, else True
:param time_periodic: To loop periodically over the time component of the Field. It is set to either False or the length of the period (either float in seconds or datetime.timedelta object). (Default: False)
This flag overrides the allow_time_interpolation and sets it to False
:param tracer_interp_method: Method for interpolation of tracer fields. It is recommended to use 'cgrid_tracer' (default)
Note that in the case of from_nemo() and from_cgrid(), the velocity fields are default to 'cgrid_velocity'
:param gridindexingtype: The type of gridindexing. Set to 'nemo' in FieldSet.from_nemo()
See also the Grid indexing documentation on oceanparcels.org
:param chunksize: size of the chunks in dask loading
"""
if 'U' in dimensions and 'V' in dimensions and dimensions['U'] != dimensions['V']:
raise ValueError("On a C-grid, the dimensions of velocities should be the corners (f-points) of the cells, so the same for U and V. "
"See also https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/documentation_indexing.ipynb")
if 'U' in dimensions and 'W' in dimensions and dimensions['U'] != dimensions['W']:
raise ValueError("On a C-grid, the dimensions of velocities should be the corners (f-points) of the cells, so the same for U, V and W. "
"See also https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/documentation_indexing.ipynb")
if 'interp_method' in kwargs.keys():
raise TypeError("On a C-grid, the interpolation method for velocities should not be overridden")
interp_method = {}
for v in variables:
if v in ['U', 'V', 'W']:
interp_method[v] = 'cgrid_velocity'
else:
interp_method[v] = tracer_interp_method
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_c_grid_dataset'
return cls.from_netcdf(filenames, variables, dimensions, mesh=mesh, indices=indices, time_periodic=time_periodic,
allow_time_extrapolation=allow_time_extrapolation, interp_method=interp_method,
chunksize=chunksize, gridindexingtype=gridindexingtype, **kwargs)
@classmethod
def from_pop(cls, filenames, variables, dimensions, indices=None, mesh='spherical',
allow_time_extrapolation=None, time_periodic=False,
tracer_interp_method='bgrid_tracer', chunksize=None, depth_units='m', **kwargs):
"""Initialises FieldSet object from NetCDF files of POP fields.
It is assumed that the velocities in the POP fields is in cm/s.
:param filenames: Dictionary mapping variables to file(s). The
filepath may contain wildcards to indicate multiple files,
or be a list of file.
filenames can be a list [files], a dictionary {var:[files]},
a dictionary {dim:[files]} (if lon, lat, depth and/or data not stored in same files as data),
or a dictionary of dictionaries {var:{dim:[files]}}
time values are in filenames[data]
:param variables: Dictionary mapping variables to variable names in the netCDF file(s).
Note that the built-in Advection kernels assume that U and V are in m/s
:param dimensions: Dictionary mapping data dimensions (lon,
lat, depth, time, data) to dimensions in the netCF file(s).
Note that dimensions can also be a dictionary of dictionaries if
dimension names are different for each variable.
Watch out: POP is discretised on a B-grid:
U and V velocity nodes are not located as W velocity and T tracer nodes (see http://www.cesm.ucar.edu/models/cesm1.0/pop2/doc/sci/POPRefManual.pdf ).
+-----------------------------+-----------------------------+-----------------------------+
|U[k,j+1,i],V[k,j+1,i] | |U[k,j+1,i+1],V[k,j+1,i+1] |
+-----------------------------+-----------------------------+-----------------------------+
| |W[k:k+2,j+1,i+1],T[k,j+1,i+1]| |
+-----------------------------+-----------------------------+-----------------------------+
|U[k,j,i],V[k,j,i] | +U[k,j,i+1],V[k,j,i+1] |
+-----------------------------+-----------------------------+-----------------------------+
In 2D: U and V nodes are on the cell vertices and interpolated bilinearly as a A-grid.
T node is at the cell centre and interpolated constant per cell as a C-grid.
In 3D: U and V nodes are at the middle of the cell vertical edges,
They are interpolated bilinearly (independently of z) in the cell.
W nodes are at the centre of the horizontal interfaces.
They are interpolated linearly (as a function of z) in the cell.
T node is at the cell centre, and constant per cell.
Note that Parcels assumes that the length of the depth dimension (at the W-points)
is one larger than the size of the velocity and tracer fields in the depth dimension.
:param indices: Optional dictionary of indices for each dimension
to read from file(s), to allow for reading of subset of data.
Default is to read the full extent of each dimension.
Note that negative indices are not allowed.
:param fieldtype: Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
:param mesh: String indicating the type of mesh coordinates and
units used during velocity interpolation, see also `this tutorial <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_unitconverters.ipynb>`_:
1. spherical (default): Lat and lon in degree, with a
correction for zonal velocity U near the poles.
2. flat: No conversion, lat/lon are assumed to be in m.
:param allow_time_extrapolation: boolean whether to allow for extrapolation
(i.e. beyond the last available time snapshot)
Default is False if dimensions includes time, else True
:param time_periodic: To loop periodically over the time component of the Field. It is set to either False or the length of the period (either float in seconds or datetime.timedelta object). (Default: False)
This flag overrides the allow_time_interpolation and sets it to False
:param tracer_interp_method: Method for interpolation of tracer fields. It is recommended to use 'bgrid_tracer' (default)
Note that in the case of from_pop() and from_bgrid(), the velocity fields are default to 'bgrid_velocity'
:param chunksize: size of the chunks in dask loading
:param depth_units: The units of the vertical dimension. Default in Parcels is 'm',
but many POP outputs are in 'cm'
"""
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_pop'
fieldset = cls.from_b_grid_dataset(filenames, variables, dimensions, mesh=mesh, indices=indices, time_periodic=time_periodic,
allow_time_extrapolation=allow_time_extrapolation, tracer_interp_method=tracer_interp_method,
chunksize=chunksize, gridindexingtype='pop', **kwargs)
if hasattr(fieldset, 'U'):
fieldset.U.set_scaling_factor(0.01) # cm/s to m/s
if hasattr(fieldset, 'V'):
fieldset.V.set_scaling_factor(0.01) # cm/s to m/s
if hasattr(fieldset, 'W'):
if depth_units == 'm':
fieldset.W.set_scaling_factor(-0.01) # cm/s to m/s and change the W direction
logger.warning_once("Parcels assumes depth in POP output to be in 'm'. Use depth_units='cm' if the output depth is in 'cm'.")
elif depth_units == 'cm':
fieldset.W.set_scaling_factor(-1.) # change the W direction but keep W in cm/s because depth is in cm
else:
raise SyntaxError("'depth_units' has to be 'm' or 'cm'")
return fieldset
@classmethod
def from_mom5(cls, filenames, variables, dimensions, indices=None, mesh='spherical',
allow_time_extrapolation=None, time_periodic=False,
tracer_interp_method='bgrid_tracer', chunksize=None, **kwargs):
"""Initialises FieldSet object from NetCDF files of MOM5 fields.
:param filenames: Dictionary mapping variables to file(s). The
filepath may contain wildcards to indicate multiple files,
or be a list of file.
filenames can be a list [files], a dictionary {var:[files]},
a dictionary {dim:[files]} (if lon, lat, depth and/or data not stored in same files as data),
or a dictionary of dictionaries {var:{dim:[files]}}
time values are in filenames[data]
:param variables: Dictionary mapping variables to variable names in the netCDF file(s).
Note that the built-in Advection kernels assume that U and V are in m/s
:param dimensions: Dictionary mapping data dimensions (lon,
lat, depth, time, data) to dimensions in the netCF file(s).
Note that dimensions can also be a dictionary of dictionaries if
dimension names are different for each variable.
+-------------------------------+-------------------------------+-------------------------------+
|U[k,j+1,i],V[k,j+1,i] | |U[k,j+1,i+1],V[k,j+1,i+1] |
+-------------------------------+-------------------------------+-------------------------------+
| |W[k-1:k+1,j+1,i+1],T[k,j+1,i+1]| |
+-------------------------------+-------------------------------+-------------------------------+
|U[k,j,i],V[k,j,i] | +U[k,j,i+1],V[k,j,i+1] |
+-------------------------------+-------------------------------+-------------------------------+
In 2D: U and V nodes are on the cell vertices and interpolated bilinearly as a A-grid.
T node is at the cell centre and interpolated constant per cell as a C-grid.
In 3D: U and V nodes are at the midlle of the cell vertical edges,
They are interpolated bilinearly (independently of z) in the cell.
W nodes are at the centre of the horizontal interfaces, but below the U and V.
They are interpolated linearly (as a function of z) in the cell.
Note that W is normally directed upward in MOM5, but Parcels requires W
in the positive z-direction (downward) so W is multiplied by -1.
T node is at the cell centre, and constant per cell.
:param indices: Optional dictionary of indices for each dimension
to read from file(s), to allow for reading of subset of data.
Default is to read the full extent of each dimension.
Note that negative indices are not allowed.
:param fieldtype: Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
:param mesh: String indicating the type of mesh coordinates and
units used during velocity interpolation, see also https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_unitconverters.ipynb:
1. spherical (default): Lat and lon in degree, with a
correction for zonal velocity U near the poles.
2. flat: No conversion, lat/lon are assumed to be in m.
:param allow_time_extrapolation: boolean whether to allow for extrapolation
(i.e. beyond the last available time snapshot)
Default is False if dimensions includes time, else True
:param time_periodic: To loop periodically over the time component of the Field. It is set to either False or the length of the period (either float in seconds or datetime.timedelta object). (Default: False)
This flag overrides the allow_time_interpolation and sets it to False
:param tracer_interp_method: Method for interpolation of tracer fields. It is recommended to use 'bgrid_tracer' (default)
Note that in the case of from_mom5() and from_bgrid(), the velocity fields are default to 'bgrid_velocity'
:param chunksize: size of the chunks in dask loading
"""
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_mom5'
fieldset = cls.from_b_grid_dataset(filenames, variables, dimensions, mesh=mesh, indices=indices, time_periodic=time_periodic,
allow_time_extrapolation=allow_time_extrapolation, tracer_interp_method=tracer_interp_method,
chunksize=chunksize, gridindexingtype='mom5', **kwargs)
if hasattr(fieldset, 'W'):
fieldset.W.set_scaling_factor(-1)
return fieldset
@classmethod
def from_b_grid_dataset(cls, filenames, variables, dimensions, indices=None, mesh='spherical',
allow_time_extrapolation=None, time_periodic=False,
tracer_interp_method='bgrid_tracer', chunksize=None, **kwargs):
"""Initialises FieldSet object from NetCDF files of Bgrid fields.
:param filenames: Dictionary mapping variables to file(s). The
filepath may contain wildcards to indicate multiple files,
or be a list of file.
filenames can be a list [files], a dictionary {var:[files]},
a dictionary {dim:[files]} (if lon, lat, depth and/or data not stored in same files as data),
or a dictionary of dictionaries {var:{dim:[files]}}
time values are in filenames[data]
:param variables: Dictionary mapping variables to variable
names in the netCDF file(s).
:param dimensions: Dictionary mapping data dimensions (lon,
lat, depth, time, data) to dimensions in the netCF file(s).
Note that dimensions can also be a dictionary of dictionaries if
dimension names are different for each variable.
U and V velocity nodes are not located as W velocity and T tracer nodes (see http://www.cesm.ucar.edu/models/cesm1.0/pop2/doc/sci/POPRefManual.pdf ).
+-----------------------------+-----------------------------+-----------------------------+
|U[k,j+1,i],V[k,j+1,i] | |U[k,j+1,i+1],V[k,j+1,i+1] |
+-----------------------------+-----------------------------+-----------------------------+
| |W[k:k+2,j+1,i+1],T[k,j+1,i+1]| |
+-----------------------------+-----------------------------+-----------------------------+
|U[k,j,i],V[k,j,i] | +U[k,j,i+1],V[k,j,i+1] |
+-----------------------------+-----------------------------+-----------------------------+
In 2D: U and V nodes are on the cell vertices and interpolated bilinearly as a A-grid.
T node is at the cell centre and interpolated constant per cell as a C-grid.
In 3D: U and V nodes are at the midlle of the cell vertical edges,
They are interpolated bilinearly (independently of z) in the cell.
W nodes are at the centre of the horizontal interfaces.
They are interpolated linearly (as a function of z) in the cell.
T node is at the cell centre, and constant per cell.
:param indices: Optional dictionary of indices for each dimension
to read from file(s), to allow for reading of subset of data.
Default is to read the full extent of each dimension.
Note that negative indices are not allowed.
:param fieldtype: Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
:param mesh: String indicating the type of mesh coordinates and
units used during velocity interpolation:
1. spherical (default): Lat and lon in degree, with a
correction for zonal velocity U near the poles.
2. flat: No conversion, lat/lon are assumed to be in m.
:param allow_time_extrapolation: boolean whether to allow for extrapolation
(i.e. beyond the last available time snapshot)
Default is False if dimensions includes time, else True
:param time_periodic: To loop periodically over the time component of the Field. It is set to either False or the length of the period (either float in seconds or datetime.timedelta object). (Default: False)
This flag overrides the allow_time_interpolation and sets it to False
:param tracer_interp_method: Method for interpolation of tracer fields. It is recommended to use 'bgrid_tracer' (default)
Note that in the case of from_pop() and from_bgrid(), the velocity fields are default to 'bgrid_velocity'
:param chunksize: size of the chunks in dask loading
"""
if 'U' in dimensions and 'V' in dimensions and dimensions['U'] != dimensions['V']:
raise ValueError("On a B-grid, the dimensions of velocities should be the (top) corners of the grid cells, so the same for U and V. "
"See also https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/documentation_indexing.ipynb")
if 'U' in dimensions and 'W' in dimensions and dimensions['U'] != dimensions['W']:
raise ValueError("On a B-grid, the dimensions of velocities should be the (top) corners of the grid cells, so the same for U, V and W. "
"See also https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/documentation_indexing.ipynb")
interp_method = {}
for v in variables:
if v in ['U', 'V']:
interp_method[v] = 'bgrid_velocity'
elif v in ['W']:
interp_method[v] = 'bgrid_w_velocity'
else:
interp_method[v] = tracer_interp_method
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_b_grid_dataset'
return cls.from_netcdf(filenames, variables, dimensions, mesh=mesh, indices=indices, time_periodic=time_periodic,
allow_time_extrapolation=allow_time_extrapolation, interp_method=interp_method,
chunksize=chunksize, **kwargs)
@classmethod
def from_parcels(cls, basename, uvar='vozocrtx', vvar='vomecrty', indices=None, extra_fields=None,
allow_time_extrapolation=None, time_periodic=False, deferred_load=True,
chunksize=None, **kwargs):
"""Initialises FieldSet data from NetCDF files using the Parcels FieldSet.write() conventions.
:param basename: Base name of the file(s); may contain
wildcards to indicate multiple files.
:param indices: Optional dictionary of indices for each dimension
to read from file(s), to allow for reading of subset of data.
Default is to read the full extent of each dimension.
Note that negative indices are not allowed.
:param fieldtype: Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
:param extra_fields: Extra fields to read beyond U and V
:param allow_time_extrapolation: boolean whether to allow for extrapolation
(i.e. beyond the last available time snapshot)
Default is False if dimensions includes time, else True
:param time_periodic: To loop periodically over the time component of the Field. It is set to either False or the length of the period (either float in seconds or datetime.timedelta object). (Default: False)
This flag overrides the allow_time_interpolation and sets it to False
:param deferred_load: boolean whether to only pre-load data (in deferred mode) or
fully load them (default: True). It is advised to deferred load the data, since in
that case Parcels deals with a better memory management during particle set execution.
deferred_load=False is however sometimes necessary for plotting the fields.
:param chunksize: size of the chunks in dask loading
"""
if extra_fields is None:
extra_fields = {}
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_parcels'
dimensions = {}
default_dims = {'lon': 'nav_lon', 'lat': 'nav_lat',
'depth': 'depth', 'time': 'time_counter'}
extra_fields.update({'U': uvar, 'V': vvar})
for vars in extra_fields:
dimensions[vars] = deepcopy(default_dims)
dimensions[vars]['depth'] = 'depth%s' % vars.lower()
filenames = dict([(v, str("%s%s.nc" % (basename, v)))
for v in extra_fields.keys()])
return cls.from_netcdf(filenames, indices=indices, variables=extra_fields,
dimensions=dimensions, allow_time_extrapolation=allow_time_extrapolation,
time_periodic=time_periodic, deferred_load=deferred_load,
chunksize=chunksize, **kwargs)
@classmethod
def from_xarray_dataset(cls, ds, variables, dimensions, mesh='spherical', allow_time_extrapolation=None,
time_periodic=False, **kwargs):
"""Initialises FieldSet data from xarray Datasets.
:param ds: xarray Dataset.
Note that the built-in Advection kernels assume that U and V are in m/s
:param variables: Dictionary mapping parcels variable names to data variables in the xarray Dataset.
:param dimensions: Dictionary mapping data dimensions (lon,
lat, depth, time, data) to dimensions in the xarray Dataset.
Note that dimensions can also be a dictionary of dictionaries if
dimension names are different for each variable
(e.g. dimensions['U'], dimensions['V'], etc).
:param fieldtype: Optional dictionary mapping fields to fieldtypes to be used for UnitConverter.
(either 'U', 'V', 'Kh_zonal', 'Kh_meridional' or None)
:param mesh: String indicating the type of mesh coordinates and
units used during velocity interpolation, see also `this tutorial <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_unitconverters.ipynb>`_:
1. spherical (default): Lat and lon in degree, with a
correction for zonal velocity U near the poles.
2. flat: No conversion, lat/lon are assumed to be in m.
:param allow_time_extrapolation: boolean whether to allow for extrapolation
(i.e. beyond the last available time snapshot)
Default is False if dimensions includes time, else True
:param time_periodic: To loop periodically over the time component of the Field. It is set to either False or the length of the period (either float in seconds or datetime.timedelta object). (Default: False)
This flag overrides the allow_time_interpolation and sets it to False
"""
fields = {}
if 'creation_log' not in kwargs.keys():
kwargs['creation_log'] = 'from_xarray_dataset'
if 'time' in dimensions:
if 'units' not in ds[dimensions['time']].attrs and 'Unit' in ds[dimensions['time']].attrs:
# Fix DataArrays that have time.Unit instead of expected time.units
convert_xarray_time_units(ds, dimensions['time'])
for var, name in variables.items():
dims = dimensions[var] if var in dimensions else dimensions
cls.checkvaliddimensionsdict(dims)
fields[var] = Field.from_xarray(ds[name], var, dims, mesh=mesh, allow_time_extrapolation=allow_time_extrapolation,
time_periodic=time_periodic, **kwargs)
u = fields.pop('U', None)
v = fields.pop('V', None)
return cls(u, v, fields=fields)
def get_fields(self):
"""Returns a list of all the :class:`parcels.field.Field` and :class:`parcels.field.VectorField`
objects associated with this FieldSet"""
fields = []
for v in self.__dict__.values():
if type(v) in [Field, VectorField]:
if v not in fields:
fields.append(v)
elif type(v) in [NestedField, SummedField]:
if v not in fields:
fields.append(v)
for v2 in v:
if v2 not in fields:
fields.append(v2)
return fields
def add_constant(self, name, value):
"""Add a constant to the FieldSet. Note that all constants are
stored as 32-bit floats. While constants can be updated during
execution in SciPy mode, they can not be updated in JIT mode.
Tutorials using fieldset.add_constant:
`Analytical advection <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_analyticaladvection.ipynb>`_
`Diffusion <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_diffusion.ipynb>`_
`Periodic boundaries <https://nbviewer.jupyter.org/github/OceanParcels/parcels/blob/master/parcels/examples/tutorial_periodic_boundaries.ipynb>`_
:param name: Name of the constant
:param value: Value of the constant (stored as 32-bit float)
"""
setattr(self, name, value)
def add_periodic_halo(self, zonal=False, meridional=False, halosize=5):
"""Add a 'halo' to all :class:`parcels.field.Field` objects in a FieldSet,
through extending the Field (and lon/lat) by copying a small portion
of the field on one side of the domain to the other.
:param zonal: Create a halo in zonal direction (boolean)
:param meridional: Create a halo in meridional direction (boolean)
:param halosize: size of the halo (in grid points). Default is 5 grid points
"""
for grid in self.gridset.grids:
grid.add_periodic_halo(zonal, meridional, halosize)
for attr, value in iter(self.__dict__.items()):
if isinstance(value, Field):
value.add_periodic_halo(zonal, meridional, halosize)
def write(self, filename):
"""Write FieldSet to NetCDF file using NEMO convention
:param filename: Basename of the output fileset"""
if MPI is None or MPI.COMM_WORLD.Get_rank() == 0:
logger.info("Generating FieldSet output with basename: %s" % filename)
if hasattr(self, 'U'):
self.U.write(filename, varname='vozocrtx')
if hasattr(self, 'V'):
self.V.write(filename, varname='vomecrty')