-
Notifications
You must be signed in to change notification settings - Fork 108
/
__init__.py
4694 lines (4181 loc) · 196 KB
/
__init__.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
# This file is part of OpenDrift.
#
# OpenDrift is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2
#
# OpenDrift is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OpenDrift. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright 2015, Knut-Frode Dagestad, MET Norway
# Copyright 2020, Gaute Hope, MET Norway
import sys
import os
import types
from typing import Union, List
import traceback
import inspect
import logging
import psutil
from opendrift.models.basemodel.environment import Environment
from opendrift.readers import reader_global_landmask
logging.captureWarnings(True)
logger = logging.getLogger(__name__)
from datetime import datetime, timedelta
from abc import ABCMeta, abstractmethod, abstractproperty
import geojson
import xarray as xr
import numpy as np
import scipy
import pyproj
import matplotlib
matplotlib.rcParams['legend.numpoints'] = 1
matplotlib.rcParams['legend.scatterpoints'] = 1
matplotlib.rcParams['figure.autolayout'] = True
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.patches import Polygon
from matplotlib.path import Path
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from enum import Enum
import functools
import opendrift
from opendrift.timer import Timeable
from opendrift.errors import WrongMode
from opendrift.models.physics_methods import PhysicsMethods
from opendrift.config import Configurable, CONFIG_LEVEL_BASIC, CONFIG_LEVEL_ADVANCED
Mode = Enum('Mode', ['Config', 'Ready', 'Run', 'Result'])
def require_mode(mode: Union[Mode, List[Mode]], post_next_mode=False, error=None):
if not isinstance(mode, list):
mode = [mode]
def _decorator(func):
@functools.wraps(func)
def inner(self, *args, **kwargs):
def next_mode():
# Change the mode
prev = self.mode
if self.mode is Mode.Config:
self.env.finalize()
self.mode = Mode.Ready
elif self.mode is Mode.Ready:
self.mode = Mode.Run
elif self.mode is Mode.Run:
self.mode = Mode.Result
elif self.mode is Mode.Result:
pass
else:
raise Exception("Unknown mode")
logger.debug(f"Changed mode from {prev} to {self.mode}")
if self.mode not in mode:
# Check if we can advance to the required mode
if mode[0] is Mode.Ready and self.mode is Mode.Config:
next_mode()
elif mode[0] is Mode.Run and self.mode is Mode.Ready:
next_mode()
elif mode[0] is Mode.Result and self.mode is Mode.Run:
next_mode()
else:
raise WrongMode(mode, self.mode, error)
r = func(self, *args, **kwargs)
if post_next_mode:
next_mode()
return r
return inner
return _decorator
class OpenDriftSimulation(PhysicsMethods, Timeable, Configurable):
"""Generic trajectory model class, to be extended (subclassed).
This as an Abstract Base Class, meaning that only subclasses can
be initiated and used.
Any specific subclass ('model') must contain its own (or shared)
specific type of particles (ElementType), whose properties are
updated at each time_step using method update() on basis of model
physics/chemistry/biology and 'required_variables' (environment)
which are provided by one or more Reader objects.
Attributes:
ElementType: the type (class) of particles to be used by this model
elements: object of the class ElementType, storing the specific
particle properties (ndarrays and scalars) of all active particles
as named attributes. Elements are added by seeding-functions
(presently only one implemented: seed_elements).
elements_deactivated: ElementType object containing particles which
have been deactivated (and removed from 'elements')
elements_scheduled: ElementType object containing particles which
have been scheduled, but not yet activated
required_variables: list of strings of CF standard_names which is
needed by this model (update function) to update properties of
particles ('elements') at each time_step. This core class has
no required_elements, this is implemented by subclasses/modules.
environment: recarray storing environment variables (wind, waves,
current etc) as named attributes. Attribute names follow
standard_name from CF-convention, allowing any OpenDriftSimulation
module/subclass using environment data from any readers which
can provide the requested variables. Used in method 'update'
to update properties of elements every time_step.
time_step: timedelta object, time interval at which element properties
are updated (including advection).
time_step_output: timedelta object, time interval at which element
properties are stored in memory and eventually written to file
readers: Dictionary where values are Reader objects, and names are
unique reference keywords used to access a given reader (typically
filename or URL)
priority_list: OrderedDict where names are variable names,
and values are lists of names (kewywords) of the reader, in the
order of priority (user defined) of which the readers shall be
called to retrieve environmental data.
"""
__metaclass__ = ABCMeta
mode = Mode.Config
status_categories = ['active'] # Particles are active by default
# Default plotting colors of trajectory endpoints
status_colors_default = {
'initial': 'green',
'active': 'blue',
'missing_data': 'gray'
}
plot_comparison_colors = [
'k', 'r', 'g', 'b', 'm', 'c', 'y', 'crimson', 'indigo', 'lightcoral',
'grey', 'sandybrown', 'palegreen', 'gold', 'yellowgreen', 'lime',
'steelblue', 'navy', 'darkviolet'
]
plot_comparison_colors = plot_comparison_colors + plot_comparison_colors
proj_latlon = pyproj.Proj('+proj=latlong')
"""
The environment holds all the readers and the forcing data for the simulation.
"""
env: Environment
@classmethod
def SRS(cls):
return cls.proj_latlon
def __init__(self,
seed=0,
iomodule='netcdf',
loglevel=logging.DEBUG,
logtime='%H:%M:%S',
logfile=None):
"""Initialise OpenDriftSimulation
Args:
seed: integer or None. A given integer will yield identical
random numbers drawn each simulation. Random numbers are
e.g. used to distribute particles spatially when seeding,
and may be used by modules (subclasses) for e.g. diffusion.
Specifying a fixed value (default: 0) is useful for sensitivity
tests. With seed = None, different random numbers will be drawn
for subsequent runs, even with identical configuration/input.
iomodule: name of module used to export data
default: netcdf, see :py:mod:`opendrift.io` for more alternatives.
`iomodule` is module/filename without preceeding `io_`
loglevel: set to 0 (default) to retrieve all debug information.
Provide a higher value (e.g. 20) to receive less output.
Use the string 'custom' to configure logging from outside.
logtime: if True, a time stamp is given for each logging line.
logtime can also be given as a python time specifier
(e.g. '%H:%M:%S')
"""
super().__init__()
self.profiles_depth = None
self.show_continuous_performance = False
self.origin_marker = None # Dictionary to store named seeding locations
self.minvals = {
} # Dicionaries to store minimum and maximum values of variables
self.maxvals = {}
# List to store GeoJSON dicts of seeding commands
self.seed_geojson = []
self.env = Environment(self.required_variables, self._config)
# Make copies of dictionaries so that they are private to each instance
self.status_categories = ['active'] # Particles are active by default
self.status_colors_default = self.status_colors_default.copy()
if hasattr(self, 'status_colors'):
# Append model specific colors to (and override) default colors
self.status_colors_default.update(self.status_colors)
self.status_colors = self.status_colors_default
else:
self.status_colors = self.status_colors_default
# Using a fixed seed will generate the same random numbers
# each run, useful for sensitivity tests
# Use seed = None to get different random numbers each time
np.random.seed(seed)
self.steps_calculation = 0 # Increase for each simulation step
self.steps_output = 0
self.elements_deactivated = self.ElementType() # Empty array
self.elements = self.ElementType() # Empty array
if loglevel != 'custom':
format = '%(levelname)-7s %(name)s:%(lineno)d: %(message)s'
datefmt = None
if logtime is not False:
format = '%(asctime)s ' + format
if logtime is not True:
datefmt = logtime
formatter = logging.Formatter(format, datefmt=datefmt)
if loglevel < 10: # 0 is NOTSET, giving no output
loglevel = 10
od_loggers = [
logging.getLogger('opendrift'),
]
if logfile is not None:
handler = logging.FileHandler(logfile, mode='w')
handler.setFormatter(formatter)
for l in od_loggers:
l.setLevel(loglevel)
l.handlers = []
l.addHandler(handler)
else:
import coloredlogs
fields = coloredlogs.DEFAULT_FIELD_STYLES
fields['levelname']['color'] = 'magenta'
# coloredlogs does not create duplicate handlers
for l in od_loggers:
coloredlogs.install(level=loglevel,
logger=l,
fmt=format,
datefmt=datefmt,
field_styles=fields)
# Prepare outfile
try:
io_module = __import__(
'opendrift.export.io_' + iomodule,
fromlist=['init', 'write_buffer', 'close', 'import_file'])
except ImportError:
logger.info('Could not import iomodule ' + iomodule)
self.io_init = types.MethodType(io_module.init, self)
self.io_write_buffer = types.MethodType(io_module.write_buffer, self)
self.io_close = types.MethodType(io_module.close, self)
self.io_import_file = types.MethodType(io_module.import_file, self)
self.io_import_file_xarray = types.MethodType(
io_module.import_file_xarray, self)
# Set configuration options
self._add_config({
# type, default, min, max, enum, important, value, units, description
'general:simulation_name': {'type': 'str', 'min_length': 0, 'max_length': 64,
'default': '', 'level': CONFIG_LEVEL_BASIC,
'description': 'Name of simulation'},
'general:coastline_action': {
'type':
'enum',
'enum': ['none', 'stranding', 'previous'],
'default':
'stranding',
'level':
CONFIG_LEVEL_BASIC,
'description':
'None means that objects may also move over land. '
'stranding means that objects are deactivated if they hit land. '
'previous means that objects will move back to the previous location '
'if they hit land'
},
'general:time_step_minutes': {
'type': 'float',
'min': .01,
'max': 1440,
'default': 60,
'units': 'minutes',
'level': CONFIG_LEVEL_BASIC,
'description': 'Calculation time step used for the simulation. The output time step may '
'be equal or larger than this.'
},
'general:time_step_output_minutes': {
'type': 'float',
'min': 1,
'max': 1440,
'default': None,
'units': 'minutes',
'level': CONFIG_LEVEL_BASIC,
'description': 'Output time step, i.e. the interval at which output is saved. '
'This must be larger than the calculation time step, and be an integer multiple of this.'
},
'seed:ocean_only': {
'type': 'bool',
'default': True,
'description': 'If True, elements seeded on land will be moved to the closest '
'position in ocean',
'level': CONFIG_LEVEL_ADVANCED
},
'seed:number': {
'type': 'int',
'default': 1,
'min': 1,
'max': 100000000,
'units': 1,
'description': 'The number of elements for the simulation.',
'level': CONFIG_LEVEL_BASIC
},
'drift:max_age_seconds': {
'type': 'float',
'default': None,
'min': 0,
'max': np.inf,
'units': 'seconds',
'description':
'Elements will be deactivated when this age is reached',
'level': CONFIG_LEVEL_ADVANCED
},
'drift:advection_scheme': {
'type': 'enum',
'enum': ['euler', 'runge-kutta', 'runge-kutta4'],
'default': 'euler',
'level': CONFIG_LEVEL_ADVANCED,
'description': 'Numerical advection scheme for ocean current advection'
},
'drift:horizontal_diffusivity': {
'type': 'float',
'default': 0,
'min': 0,
'max': 100000,
'units': 'm2/s',
'description': 'Add horizontal diffusivity (random walk)',
'level': CONFIG_LEVEL_BASIC
},
'drift:profiles_depth': {'type': 'float', 'default': 50, 'min': 0, 'max': None,
'level': CONFIG_LEVEL_ADVANCED, 'units': 'meters', 'description':
'Environment profiles will be retrieved from surface and down to this depth'},
'drift:wind_uncertainty': {
'type': 'float',
'default': 0,
'min': 0,
'max': 5,
'units': 'm/s',
'description':
'Add gaussian perturbation with this standard deviation to wind components at each time step.',
'level': CONFIG_LEVEL_ADVANCED
},
'drift:relative_wind': {
'type': 'bool',
'default': False,
'description':
'If True, wind drift is calculated for absolute wind (wind vector minus ocean surface current vector).',
'level': CONFIG_LEVEL_ADVANCED
},
'drift:deactivate_north_of': {
'type': 'float',
'default': None,
'min': -90,
'max': 90,
'units': 'degrees',
'description':
'Elements are deactivated if the move further north than this limit',
'level': CONFIG_LEVEL_ADVANCED
},
'drift:deactivate_south_of': {
'type': 'float',
'default': None,
'min': -90,
'max': 90,
'units': 'degrees',
'description':
'Elements are deactivated if the move further south than this limit',
'level': CONFIG_LEVEL_ADVANCED
},
'drift:deactivate_east_of': {
'type': 'float',
'default': None,
'min': -360,
'max': 360,
'units': 'degrees',
'description':
'Elements are deactivated if the move further east than this limit',
'level': CONFIG_LEVEL_ADVANCED
},
'drift:deactivate_west_of': {
'type': 'float',
'default': None,
'min': -360,
'max': 360,
'units': 'degrees',
'description':
'Elements are deactivated if the move further west than this limit',
'level': CONFIG_LEVEL_ADVANCED
},
'readers:max_number_of_fails': {
'type': 'int',
'default': 1,
'min': 0,
'max': 1e6,
'units': 'number',
'description':
'Readers are discarded if they fail (e.g. corrupted data, og hanging servers) move than this number of times',
'level': CONFIG_LEVEL_ADVANCED
},
})
# Add default element properties to config
c = {}
for p in self.ElementType.variables:
v = self.ElementType.variables[p]
if 'seed' in v and v['seed'] is False:
continue # Properties which may not be provided by user
minval = v['min'] if 'min' in v else None
maxval = v['max'] if 'max' in v else None
units = v['units'] if 'units' in v else None
c['seed:%s' % p] = {
'type': v['type'] if 'type' in v else 'float',
'min': v['min'] if 'min' in v else None,
'max': v['max'] if 'max' in v else None,
'units': v['units'] if 'units' in v else None,
'default': v['default'] if 'default' in v else None,
'description': v['description'] if 'description' in v \
else 'Seeding value of %s' % p, 'level': v['level'] if 'level' in v \
else CONFIG_LEVEL_ADVANCED
}
self._add_config(c)
self.history = None # Recarray to store trajectories and properties
# Find variables which require profiles
self.required_profiles = [
var for var in self.required_variables
if 'profiles' in self.required_variables[var]
and self.required_variables[var]['profiles'] is True
]
# Find variables which are desired, but not required
self.desired_variables = [
var for var in self.required_variables
if 'important' in self.required_variables[var]
and self.required_variables[var]['important'] is False
]
self.timer_start('total time')
self.timer_start('configuration')
self.add_metadata('opendrift_version', opendrift.__version__)
logger.info('OpenDriftSimulation initialised (version %s)' %
opendrift.version.version_or_git())
# Check if dependencies are outdated
import importlib
if importlib.util.find_spec("cmocean") is None:
logger.warning('#' * 82)
logger.warning(
'Dependencies are outdated, please update with: conda env update -f environment.yml'
)
logger.warning('#' * 82)
def clone(self):
c = self.__class__()
c._config.clear()
for k, v in self._config.items():
c._config[k] = v
c.add_reader([r for _, r in self.env.readers.items()])
return c
@require_mode(mode=Mode.Config,
error='Cannot set config after elements have been seeded')
@functools.wraps(Configurable.set_config)
def set_config(self, *args, **kwargs):
return Configurable.set_config(self, *args, **kwargs)
@require_mode(mode=[Mode.Config, Mode.Ready])
@functools.wraps(Configurable.set_config)
def __set_seed_config__(self, key: str, value):
"""
This method allows setting config values that are passed as seed arguments. The environment is already prepared before this, so make sure that nothing is changed that requires the environment to be re-initialized.
"""
if not key.startswith('seed'):
raise ValueError("This method is only allowed for setting seed arguments.")
# check that the oil_type is only set once
if key == 'seed:oil_type' and self.num_elements_scheduled() > 0:
if value != self.get_config('seed:oil_type'):
raise WrongMode(Mode.Config, self.mode, msg=f"Cannot change the oil type after elements have been seeded: {self.get_config('seed:oil_type')} -> {value}")
return Configurable.set_config(self, key, value)
def add_metadata(self, key, value):
"""Add item to metadata dictionary, for export as netCDF global attributes"""
if not hasattr(self, 'metadata_dict'):
from collections import OrderedDict
self.metadata_dict = OrderedDict()
self.metadata_dict[key] = value
@require_mode(mode=[Mode.Config, Mode.Result])
def add_reader(self, readers, variables=None, first=False):
self.env.add_reader(readers, variables, first)
@require_mode(mode=Mode.Config)
def add_readers_from_list(self, *args, **kwargs):
'''Make readers from a list of URLs or paths to netCDF datasets'''
self.env.add_readers_from_list(*args, **kwargs)
@require_mode(mode=Mode.Config)
def add_readers_from_file(self, *args, **kwargs):
'''Make readers from a file containing list of URLs or paths to netCDF datasets'''
self.env.add_readers_from_file(*args, **kwargs)
# To be overloaded by sublasses, but this parent method must be called
def prepare_run(self):
# Copy profile_depth from config
self.profiles_depth = self.get_config('drift:profiles_depth')
def store_present_positions(self, IDs=None, lons=None, lats=None):
"""Store present element positions, in case they shall be moved back"""
if self.get_config('general:coastline_action') == 'previous' or (
'general:seafloor_action' in self._config
and self.get_config('general:seafloor_action') == 'previous'):
if not hasattr(self, 'previous_lon'):
self.previous_lon = np.ma.masked_all(self.num_elements_total())
self.previous_lat = np.ma.masked_all(self.num_elements_total())
if IDs is None:
IDs = self.elements.ID
lons = self.elements.lon
lats = self.elements.lat
self.newly_seeded_IDs = None
else:
# to check if seeded on land
if len(IDs) > 0:
self.newly_seeded_IDs = np.copy(IDs)
else:
self.newly_seeded_IDs = None
self.previous_lon[IDs - 1] = np.copy(lons)
self.previous_lat[IDs - 1] = np.copy(lats)
def store_previous_variables(self):
"""Store some environment variables, for access at next time step"""
if not hasattr(self, 'store_previous'):
return
if not hasattr(self, 'variables_previous'):
# Create ndarray to store previous variables
dtype = [(var, np.float32) for var in self.store_previous]
self.variables_previous = np.array(np.full(
self.num_elements_total(), np.nan),
dtype=dtype)
# Copying variables_previous to environment_previous
self.environment_previous = self.variables_previous[self.elements.ID -
1]
# Use new values for new elements which have no previous value
for var in self.store_previous:
undefined = np.isnan(self.environment_previous[var])
self.environment_previous[var][undefined] = getattr(
self.environment, var)[undefined]
self.environment_previous = self.environment_previous.view(np.recarray)
for var in self.store_previous:
self.variables_previous[var][self.elements.ID - 1] = getattr(
self.environment, var)
def interact_with_coastline(self, final=False):
"""Coastline interaction according to configuration setting"""
if self.num_elements_active() == 0:
return
i = self.get_config('general:coastline_action')
if not hasattr(self, 'environment') or not hasattr(
self.environment, 'land_binary_mask'):
return
if i == 'none': # Do nothing
return
if final is True: # Get land_binary_mask for final location
en, en_prof, missing = \
self.env.get_environment(['land_binary_mask'],
self.time,
self.elements.lon,
self.elements.lat,
self.elements.z)
self.environment.land_binary_mask = en.land_binary_mask
if i == 'stranding': # Deactivate elements on land, but not in air
self.deactivate_elements((self.environment.land_binary_mask == 1) &
(self.elements.z <= 0),
reason='stranded')
elif i == 'previous': # Go back to previous position (in water)
if self.newly_seeded_IDs is not None:
self.deactivate_elements(
(self.environment.land_binary_mask == 1) &
(self.elements.age_seconds
== self.time_step.total_seconds()),
reason='seeded_on_land')
on_land = np.where(self.environment.land_binary_mask == 1)[0]
if len(on_land) == 0:
logger.debug('No elements hit coastline.')
else:
logger.debug('%s elements hit coastline, '
'moving back to water' % len(on_land))
on_land_ID = self.elements.ID[on_land]
self.elements.lon[on_land] = \
np.copy(self.previous_lon[on_land_ID - 1])
self.elements.lat[on_land] = \
np.copy(self.previous_lat[on_land_ID - 1])
self.environment.land_binary_mask[on_land] = 0
def interact_with_seafloor(self):
"""Seafloor interaction according to configuration setting"""
if self.num_elements_active() == 0:
return
if 'sea_floor_depth_below_sea_level' not in self.env.priority_list:
return
if not hasattr(self, 'environment'):
logger.warning('Seafloor check not being run because environment is missing. '
'This will happen the first time the function is run but if it happens '
'subsequently there is probably a problem.')
return
if not hasattr(self.environment, 'sea_surface_height'):
logger.warning('Seafloor check not being run because sea_surface_height is missing. ')
return
# the shape of these is different than the original arrays
# because it is for active drifters
sea_floor_depth = self.sea_floor_depth()
sea_surface_height = self.sea_surface_height()
# Check if any elements are below sea floor
# But remember that the water column is the sea floor depth + sea surface height
ibelow = self.elements.z < -(sea_floor_depth + sea_surface_height)
below = np.where(ibelow)[0]
if len(below) == 0:
logger.debug('No elements hit seafloor.')
return
i = self.get_config('general:seafloor_action')
if i == 'lift_to_seafloor':
logger.debug('Lifting %s elements to seafloor.' % len(below))
self.elements.z[below] = -sea_floor_depth[below]
elif i == 'deactivate':
self.deactivate_elements(ibelow, reason='seafloor')
self.elements.z[below] = -sea_floor_depth[below]
elif i == 'previous': # Go back to previous position (in water)
logger.warning('%s elements hit seafloor, '
'moving back ' % len(below))
below_ID = self.elements.ID[below]
self.elements.lon[below] = \
np.copy(self.previous_lon[below_ID - 1])
self.elements.lat[below] = \
np.copy(self.previous_lat[below_ID - 1])
@abstractmethod
def update(self):
"""Any trajectory model implementation must define an update method.
This method must/can use environment data (self.environment) to
update properties (including position) of its particles (self.elements)
"""
@abstractproperty
def ElementType(self):
"""Any trajectory model implementation must define an ElementType."""
@abstractproperty
def required_variables(self):
"""Any trajectory model implementation must list needed variables."""
def test_data_folder(self):
import opendrift
return os.path.abspath(
os.path.join(os.path.dirname(opendrift.__file__), '..', 'tests',
'test_data')) + os.path.sep
def performance(self):
'''Report the time spent on various tasks'''
outStr = '--------------------\n'
outStr += 'Reader performance:\n'
for r in self.env.readers:
reader = self.env.readers[r]
if reader.is_lazy:
continue
outStr += '--------------------\n'
outStr += r + '\n'
outStr += reader.performance()
outStr += '--------------------\n'
outStr += 'Performance:\n'
for category, time in self.timing.items():
timestr = str(time)[0:str(time).find('.') + 2]
for i, c in enumerate(timestr):
if c in '123456789.':
timestr = timestr[i:] # Strip leading 0 and :
if c == '.':
timestr = '0' + timestr
break
parts = category.split(':')
indent = ' ' * (len(parts) - 1)
category = parts[-1]
category = category.replace('<colon>', ':')
outStr += '%s%7s %s\n' % (indent, timestr, category)
outStr += '--------------------\n'
return outStr
def num_elements_active(self):
"""The number of active elements."""
if hasattr(self, 'elements'):
return len(self.elements)
else:
return 0
def num_elements_deactivated(self):
"""The number of deactivated elements."""
if hasattr(self, 'elements_deactivated'):
return len(self.elements_deactivated)
else:
return 0
def num_elements_scheduled(self):
if hasattr(self, 'elements_scheduled'):
return len(self.elements_scheduled)
else:
return 0
def num_elements_total(self):
"""The total number of scheduled, active and deactivated elements."""
return self.num_elements_activated() + self.num_elements_scheduled()
def num_elements_activated(self):
"""The total number of active and deactivated elements."""
return self.num_elements_active() + self.num_elements_deactivated()
@require_mode(mode=Mode.Ready)
def schedule_elements(self, elements, time):
"""Schedule elements to be seeded during runtime.
Also assigns a unique ID to each particle, monotonically increasing."""
# prepare time
if isinstance(time, np.ndarray):
time = list(time)
if not isinstance(time, list):
time = [time]
if len(time) == 1 and len(elements) > 1:
time = time * len(elements)
if not hasattr(self, 'elements_scheduled'):
self.elements_scheduled = elements
self.elements_scheduled_time = np.array(time)
# We start simulation at time of release of first element:
self.start_time = time[0]
self.elements_scheduled.ID = np.arange(1, len(elements) + 1)
else:
elements.ID = np.arange(self.num_elements_scheduled() + 1,
self.num_elements_scheduled() + 1 +
len(elements)) # Increase ID successively
self.elements_scheduled.extend(elements)
self.elements_scheduled_time = np.append(
self.elements_scheduled_time, np.array(time))
min_time = np.min(time)
if hasattr(self, 'start_time'):
if min_time < self.start_time:
self.start_time = min_time
logger.debug('Setting simulation start time to %s' %
str(min_time))
else:
self.start_time = min_time
logger.debug('Setting simulation start time to %s' % str(min_time))
def release_elements(self):
"""Activate elements which are scheduled within following timestep."""
logger.debug(
'to be seeded: %s, already seeded %s' %
(len(self.elements_scheduled), self.num_elements_activated()))
if len(self.elements_scheduled) == 0:
return
if self.time_step.days >= 0:
indices = (self.elements_scheduled_time >= self.time) & \
(self.elements_scheduled_time <
self.time + self.time_step)
else:
indices = (self.elements_scheduled_time <= self.time) & \
(self.elements_scheduled_time >
self.time + self.time_step)
self.store_present_positions(self.elements_scheduled.ID[indices],
self.elements_scheduled.lon[indices],
self.elements_scheduled.lat[indices])
self.elements_scheduled.move_elements(self.elements, indices)
self.elements_scheduled_time = self.elements_scheduled_time[~indices]
logger.debug('Released %i new elements.' % np.sum(indices))
def closest_ocean_points(self, lon, lat):
"""Return the closest ocean points for given lon, lat"""
deltalon = 0.01 # grid
deltalat = 0.01
numbuffer = 10
lonmin = lon.min() - deltalon * numbuffer
lonmax = lon.max() + deltalon * numbuffer
latmin = lat.min() - deltalat * numbuffer
latmax = lat.max() + deltalat * numbuffer
if not 'land_binary_mask' in self.env.priority_list:
logger.info('No land reader added, '
'making a temporary landmask reader')
from opendrift.models.oceandrift import OceanDrift
reader_landmask = reader_global_landmask.Reader()
seed_state = np.random.get_state(
) # Do not alter current random number generator
o = OceanDrift(loglevel='custom')
np.random.set_state(seed_state)
if hasattr(self, 'simulation_extent'):
o.simulation_extent = self.simulation_extent
o.env.add_reader(reader_landmask)
o.env.finalize() # This is not env of the main simulation
land_reader = reader_landmask
else:
logger.info('Using existing reader for land_binary_mask')
land_reader_name = self.env.priority_list['land_binary_mask'][0]
land_reader = self.env.readers[land_reader_name]
o = self
land = o.env.get_environment(['land_binary_mask'],
lon=lon,
lat=lat,
z=0 * lon,
time=land_reader.start_time)[0]['land_binary_mask']
if land.max() == 0:
logger.info('All points are in ocean')
return lon, lat
logger.info('Moving %i out of %i points from land to water' %
(np.sum(land != 0), len(lon)))
landlons = lon[land != 0]
landlats = lat[land != 0]
longrid = np.arange(lonmin, lonmax, deltalon)
latgrid = np.arange(latmin, latmax, deltalat)
longrid, latgrid = np.meshgrid(longrid, latgrid)
longrid = longrid.ravel()
latgrid = latgrid.ravel()
# Remove grid-points not covered by this reader
latgrid_covered = land_reader.covers_positions(longrid, latgrid)[0]
longrid = longrid[latgrid_covered]
latgrid = latgrid[latgrid_covered]
landgrid = o.env.get_environment(['land_binary_mask'],
lon=longrid,
lat=latgrid,
z=0 * longrid,
time=land_reader.start_time)[0]['land_binary_mask']
if landgrid.min() == 1 or np.isnan(landgrid.min()):
logger.warning('No ocean pixels nearby, cannot move elements.')
return lon, lat
oceangridlons = longrid[landgrid == 0]
oceangridlats = latgrid[landgrid == 0]
tree = scipy.spatial.cKDTree(
np.dstack([oceangridlons, oceangridlats])[0])
landpoints = np.dstack([landlons, landlats])
_dist, indices = tree.query(landpoints)
indices = indices.ravel()
lon[land != 0] = oceangridlons[indices]
lat[land != 0] = oceangridlats[indices]
return lon, lat
@require_mode(mode=Mode.Ready)
def seed_elements(self,
lon,
lat,
time,
radius=0,
number=None,
radius_type='gaussian',
**kwargs):
"""Seed elements with given position(s), time and properties.
Arguments:
lon: scalar or array
central longitude(s).
lat: scalar or array
central latitude(s).
radius: scalar or array
radius in meters around each lon-lat pair,
within which particles will be randomly seeded.
number: integer, total number of particles to be seeded
If number is None, the number of elements is the
length of lon/lat or time if these are arrays. Otherwise
the number of elements are obtained from the config-default.
time: datenum or list
The time at which particles are seeded/released.
If time is a list with two elements, elements are seeded
continously from start/first to end/last time.
If time is a list with more than two elements, the number of elements
is equal to len(time) and are seeded as a time series.
radius_type: string
If 'gaussian' (default), the radius is the standard deviation in
x-y-directions. If 'uniform', elements are spread evenly and
always inside a circle with the given radius.
kwargs:
keyword arguments containing properties/attributes and
values corresponding to the actual particle type (ElementType).
These are forwarded to the ElementType class. All properties
for which there are no default value must be specified.
"""
if 'cone' in kwargs:
raise ValueError(
'Keyword *cone* for seed_elements is deprecated, use seed_cone() instead.'
)
if self.origin_marker is None:
self.origin_marker = {}
if 'origin_marker' in kwargs:
origin_marker = kwargs['origin_marker']
else:
origin_marker = len(self.origin_marker)
if 'origin_marker_name' in kwargs:
origin_marker_name = kwargs['origin_marker_name']
del kwargs['origin_marker_name']
else:
origin_marker_name = 'Seed %d' % len(self.origin_marker)
if not 'origin_marker' in kwargs:
kwargs['origin_marker'] = origin_marker
if '_' in origin_marker_name:
raise ValueError(
'Underscore (_) not allowed in origin_marker_name')
self.origin_marker[str(origin_marker)] = origin_marker_name.replace(
' ', '_')
lon = np.atleast_1d(lon).ravel()
lat = np.atleast_1d(lat).ravel()
radius = np.atleast_1d(radius).ravel()
time = np.atleast_1d(time)