gnome.tamoc¶
code for interfacing with TAMOC:
https://github.com/socolofs/tamoc
For now, this imports everythign from tamoc.py in this package
Submodules¶
Classes¶
base class for Release classes. |
|
Models a spill by combining Release and Substance objects |
|
A class for assigning a unique ID for an object |
|
Class to create an oil for use in Gnome |
|
A class for assigning a unique ID for an object |
|
Models a TAMOC spill by combining the near-field model with Release |
Functions¶
|
makes sure the input is a datetime.datetime object |
Package Contents¶
- class gnome.tamoc.Release(release_time=None, num_elements=None, num_per_timestep=None, end_release_time=None, custom_positions=None, release_mass=0, retain_initial_positions=False, **kwargs)¶
Bases:
gnome.gnomeobject.GnomeId
base class for Release classes.
It contains interface for Release objects
Required Arguments:
- Parameters:
release_time (datetime.datetime or iso string.) – time the LEs are released
custom_positions (iterable of (lon, lat, z)) – initial location(s) the elements are released
Optional arguments:
Note
Either num_elements or num_per_timestep must be given. If both are None, then it defaults to num_elements=1000. If both are given a TypeError is raised because user can only specify one or the other, not both.
- Parameters:
num_elements (integer) – total number of elements to be released
num_per_timestep – fixed number of LEs released at each timestep
end_release_time=None – optional – for a time varying release, the end release time. If None, then release is instantaneous
release_mass=0 – optional. This is the mass released in kilograms.
retain_initial_positions (boolean) – Optional. If True, each LE will retain information about its originally released position
- property num_elements¶
- release_time = None¶
- property end_release_time¶
- property release_mass¶
- custom_positions = None¶
- retain_initial_positions = False¶
- cumulative_time_scale¶
- rewind()¶
- property centroid¶
- property num_per_timestep¶
- property release_duration¶
duration over which particles are released in seconds
- LE_timestep_ratio(ts)¶
Returns the ratio
- maximum_mass_error(ts)¶
This function returns the maximum error in mass present in the model at any given time. In theory, this should be the mass of 1 LE
- get_num_release_time_steps(ts)¶
calculates how many time steps it takes to complete the release duration
- generate_release_timeseries(num_ts, max_release, ts)¶
Release timeseries describe release behavior as a function of time. _release_ts describes the number of LEs that should exist at time T PolygonRelease does not have a _pos_ts because it uses start_positions only All use TimeseriesData objects.
- num_elements_after_time(current_time)¶
Returns the number of elements expected to exist at current_time. Returns 0 if prepare_for_model_run has not been called. :param current_time: time of release :type current_time: datetime
- prepare_for_model_run(ts)¶
- Parameters:
ts – timestep as integer seconds
- initialize_LEs(to_rel, sc, start_time, end_time)¶
set positions for new elements added by the SpillContainer
Note
this releases all the elements at their initial positions at the end_time
- initialize_LEs_post_substance(to_rel, sc, start_time, end_time, environment)¶
- class gnome.tamoc.Spill(on=True, num_elements=1000, amount=0, units='kg', substance=None, release=None, water=None, amount_uncertainty_scale=0.0, **kwargs)¶
Bases:
BaseSpill
Models a spill by combining Release and Substance objects
Spills used by the gnome model. It contains a release object, which releases elements. It also contains a Substance which contains the type of substance spilled and it initializes data arrays to non-default values (non-zero).
- Parameters:
release (derived from
Release
) – an object defining how elements are to be releasedsubstance (derived from
Substance
) – an object defining the substance of this spill. Defaults toNonWeatheringSubstance
Optional parameters (kwargs):
- Parameters:
name (str) – Human-usable Name of this spill
on=True – Toggles the spill on/off.
amount=None – mass or volume of oil spilled.
units=None – must provide units for amount spilled.
amount_uncertainty_scale=0.0 – scale value in range 0-1 that adds uncertainty to the spill amount. Maximum uncertainty scale is (2/3) * spill_amount.
Note
Define either volume or mass in ‘amount’ attribute and provide appropriate ‘units’.
- valid_vol_units¶
- valid_mass_units¶
- on = True¶
- property substance¶
- property num_elements¶
- property units¶
Default units in which amount of oil spilled was entered by user. The ‘amount’ property is returned in these ‘units’
- property amount¶
- water = None¶
- amount_uncertainty_scale = 0.0¶
- frac_coverage = 1.0¶
- property all_array_types¶
Need to add array types from Release and Substance
- property release_time¶
- property end_release_time¶
- property release_duration¶
- property start_position¶
- property end_position¶
- get_mass()¶
Return the total mass released during the spill.
- uncertain_copy()¶
Returns a deepcopy of this spill for the uncertainty runs
The copy has everything the same, including the spill_num, but it is a new object with a new id.
Not much to this method, but it could be overridden to do something fancier in the future or a subclass.
There are a number of python objects that cannot be deepcopied. - Logger objects
So we copy them temporarily to local variables before we deepcopy our Spill object.
- set_amount_uncertainty(up_or_down=None)¶
This function shifts the spill amount based on a scale value in the range [0.0 … 1.0]. The maximum uncertainty scale value is (2/3) * spill_amount. We determine either an upper uncertainty or a lower uncertainty multiplier. Then we shift our spill amount value based on it.
Since we are irreversibly changing the spill amount value, we should probably do this only once.
- rewind()¶
rewinds the release to original status (before anything has been released).
- prepare_for_model_run(timestep)¶
array_types comes from all the other objects above in the model such as movers, weatherers, etc. The ones from the substance still need to be added
- release_elements(sc, start_time, end_time, environment=None)¶
Releases and partially initializes new LEs Note: this will have to be updated if we allow backwards runs for continuous spills
- num_elements_to_release(current_time, time_step)¶
Determines the number of elements to be released during: current_time + time_step
It invokes the num_elements_to_release method for the the underlying release object: self.release.num_elements_to_release()
- Parameters:
current_time (datetime.datetime) – current time
time_step (int) – the time step, sometimes used to decide how many should get released.
- Returns:
the number of elements that will be released. This is taken by SpillContainer to initialize all data_arrays.
- class gnome.tamoc.Substance(windage_range=None, windage_persist=None, standard_density=1000.0, *args, **kwargs)¶
Bases:
gnome.gnomeobject.GnomeId
A class for assigning a unique ID for an object
- Parameters:
windage_range (tuple of values between 0 and 1) – Range of windages for the substance (leeway). Default: (.01, .04)
windage_persist=900 – persistence of windage settings in seconds. -1 or Inf means infinite.
standard_density=1000.0 – The density of the substance, used to convert mass to/from volume
- property windage_range¶
- property windage_persist¶
- initializers¶
- property all_array_types¶
- Fixme: should the initializers be what holds the array types?
don’t we know that this should have already?
- property is_weatherable¶
- get_initializer_by_name(name)¶
get first initializer in list whose name matches ‘name’
- has_initializer(name)¶
Returns True if an initializer is present in the list which sets the data_array corresponding with ‘name’, otherwise returns False
- initialize_LEs(to_rel, arrs, environment=None)¶
:param to_rel - number of new LEs to initialize :param arrs - dict-like of data arrays representing LEs
- density_at_temp(temp=273.15)¶
For non-weathering substance, we just return the standard density.
- class gnome.tamoc.GnomeOil(oil_name=None, filename=None, water=None, **kwargs)¶
Bases:
gnome.spills.substance.Substance
Class to create an oil for use in Gnome
Initialize a GnomeOil:
- Parameters:
oil_name=None – Name of one of the sample oils provided by:
gnome.spills.sample_oils
filename=None – filename (Path) of JSON file in the Adios Oil Database format.
water=None – Water object with environmental conditions – Deprecated.
Additional keyword arguments will be passed to Substance: e.g.:
windage_range
,windage_persist=None
,A GnomeOil can be initialized in three ways:
From a sample oil name :
GnomeOil(oil_name="sample_oil_name")
the oils are available in gnome.spills.sample_oilsFrom a JSON file in the ADIOS Oil Database format:
GnomeOil(filename="adios_oil.json")
usually records from the ADIOS Oil Database (https://adios.orr.noaa.gov)From the json :
GnomeOil.new_from_dict(**json_)
for loading save files, etc. (this is usually done under the hood)
GnomeOil(“sample_oil_name”) —works for test oils from sample_oils only
GnomeOil(oil_name=”sample_oil_name”)
GnomeOil(filename=”oil.json”) —load from file using adios_db
GnomeOil.new_from_dict(**json_) —webgnomeclient, savefiles, etc.
GnomeOil(“invalid_name”) —ValueError (not in sample oils)
- filename = None¶
- oil_name = None¶
- water = None¶
- from_adiosdb_file(filename, kwargs)¶
- classmethod get_GnomeOil(oil_info, max_cuts=None)¶
#fixme: what is oil_info ???
Use this instead of get_oil_props
- to_dict(json_=None)¶
Returns a dictionary representation of this object. Uses the schema to determine which attributes are put into the dictionary. No extra processing is done to each attribute. They are presented as is.
The
json_
parameter is ignored in this base class. ‘save’ is passed in when the schema is saving the object. This allows an override of this function to do any custom stuff necessary to prepare for saving.
- initialize_LEs(to_rel, arrs, environment=None)¶
:param to_rel - number of new LEs to initialize :param arrs - dict-like of data arrays representing LEs
- fixme:
this shouldn’t use water temp – it should use standard density and STP temp – and let weathering_data set it correctly
Note
weathering data is currently broken for initial setting
- vapor_pressure(temp, atmos_pressure=101325.0)¶
the vapor pressure on the PCs at a given temperature water_temp and boiling point units are Kelvin
- Parameters:
temp – temperature in K
- Returns:
vapor_pressure array in SI units (Pascals)
## Fixme: shouldn’t this be in the Evaporation code?
- classmethod bounding_temperatures(obj_list, temperature)¶
General Utility Function
From a list of objects containing a ref_temp_k attribute, return the object(s) that are closest to the specified temperature(s)
Specifically:
We want the ones that immediately bound our temperature.
If our temperature is high and out of bounds of the temperatures in our obj_list, then we return a range containing only the highest temperature.
If our temperature is low and out of bounds of the temperatures in our obj_list, then we return a range containing only the lowest temperature.
We accept only a scalar temperature or a sequence of temperatures
- get_densities()¶
return a list of densities for the oil at a specified state of weathering.
#fixme: this should not happen here!
We include the API as a density if:
the specified weathering is 0
the culled list of densities does not contain a measurement at 15C
- density_at_temp(temperature=288.15)¶
Get the oil density at a temperature or temperatures.
Note
This is all kruft left over from the estimating code. At this point, a GnomeOil should already have what it needs.
Note
There is a catch-22 which prevents us from getting the min_temp in some cases:
To estimate pour point, we need viscosities
If we need to convert dynamic viscosities to kinematic, we need density at 15C
To estimate density at temp, we need to estimate pour point
…and then we recurse
For this case we need to make an exception.
Note
If we have a pour point that is higher than one or more of our reference temperatures, then the lowest reference temperature will become our minimum temperature.
- TODO:
We are getting rid of the argument that specifies a weathering amount because it is currently implemented in an unusably precise manner. Robert would like us to implement a means of interpolating density using a combination of (temperature, weathering). But the algorithm for this is not defined at the moment.
- property standard_density¶
Standard density is simply the density at 15C, which is the default temperature for density_at_temp()
- classmethod closest_to_temperature(obj_list, temperature, num=1)¶
General Utility Function
From a list of objects containing a ref_temp_k attribute, return the object(s) that are closest to the specified temperature(s)
We accept only a scalar temperature or a sequence of temperatures
- kvis_at_temp(temp_k=288.15, weathering=0.0)¶
Compute the kinematic viscosity of the oil as a function of temperature
- Parameters:
temp_k – temperatures to compute at: can be scalar or array of values. should be in Kelvin
weathering – fraction weathered – currently not implemented
viscosity as a function of temp is given by: v = A exp(k_v2 / T)
with constants determined from measured data
- determine_visc_constants()¶
viscosity as a function of temp is given by:
v = A exp(k_v2 / T)
The constants, A and k_v2 are determined from the viscosity data:
If only one data point, a default value for k_vs is used:
2100 K, based on analysis of data in the ADIOS database as of 2018
If two data points, the two constants are directly computed
If three or more, the constants are computed by a least squares fit.
- get(prop)¶
get oil props
- gnome.tamoc.asdatetime(dt)¶
makes sure the input is a datetime.datetime object
if it already is, it will be passed through.
If not it will attempt to parse a string to make a datetime object.
None will also be passed through silently
- class gnome.tamoc.GnomeId(name=None, _appearance=None, *args, **kwargs)¶
Bases:
AddLogger
A class for assigning a unique ID for an object
- make_default_refs = True¶
- RTOL = 1e-05¶
- ATOL = 1e-38¶
- array_types¶
- property all_array_types¶
Returns all the array types required by this object
If this object contains or is composed of other gnome objects (Spill->Substance->Initializers for example) then override this function to ensure all array types get presented at the top level. See
Spill
for an example
- property id¶
Override this method for more exotic forms of identification.
- Returns:
a unique ID assigned during construction
- property obj_type¶
- property name¶
define as property in base class so all objects will have a name by default
- gather_ref_as(src, refs)¶
Gathers refs from single or collection of GnomeId objects. :param src: GnomeId object or collection of GnomeId :param refs: dictionary of str->list of GnomeId :returns {‘ref1’: [list of GnomeId], ‘ref2 : [list of GnomeId], …}
- validate_refs(refs=['wind', 'water', 'waves'])¶
level is the logging level to use for messages. Default is ‘warning’ but if called from prepare_for_model_run, we want to use error and raise exception.
- validate()¶
All pygnome objects should be able to validate themselves. Many py_gnome objects reference other objects like wind, water, waves. These may not be defined when object is created so they can be None at construction time; however, they should reference valid objects when running in the model. If make_default_refs is True, then object is valid because the model will set these up at runtime. To raise an exception for missing references at runtime, directly call validate_refs(level=’error’)
‘wind’, ‘water’, ‘waves’ attributes also have special meaning. An object containing this attribute references the corresponding object.
Logs warnings:
- Returns:
a tuple of length two containing: (a list of messages that were logged, isvalid bool) If any references are missing and make_default_refs is False, object is not valid
- classmethod new_from_dict(dict_)¶
creates a new object from dictionary
This is base implementation and can be over-ridden by classes using this mixin
- to_dict(json_=None)¶
Returns a dictionary representation of this object. Uses the schema to determine which attributes are put into the dictionary. No extra processing is done to each attribute. They are presented as is.
The
json_
parameter is ignored in this base class. ‘save’ is passed in when the schema is saving the object. This allows an override of this function to do any custom stuff necessary to prepare for saving.
- update_from_dict(dict_, refs=None)¶
- update(*args, **kwargs)¶
- serialize(options={})¶
Returns a json serialization of this object (“webapi” mode only)
- classmethod deserialize(json_, refs=None)¶
classmethod takes json structure as input, deserializes it using a colander schema then invokes the new_from_dict method to create an instance of the object described by the json schema.
We also need to accept sparse json objects, in which case we will not treat them, but just send them back.
- save(saveloc='.', refs=None, overwrite=True)¶
Save object state as json to user specified saveloc
- Parameters:
saveloc –
A directory, file path, open zipfile.ZipFile, or None. If a directory, it will place the zip file there, overwriting if specified.
If a file path, it will write the file there as follows:
If the file does not exist, it will create the zip archive there. If the saveloc is a zip file or
zipfile.Zipfile
object and overwrite is False, it will append there. Otherwise, it will overwrite the file if allowed.If set to None, this function will instead return an open
zipfile.Zipfile
object linked to a temporary file. The zip file will be named [object.name].zip if a directory is specifiedrefs – dictionary of references to objects
overwrite – If True, overwrites the file at the saveloc
- Returns (obj_json, saveloc, refs):
obj_json
is the json that is written to this object’s file in the zipfile. For example if saving a Model named Model1, obj_json will contain the contents of the Model1.json in the save file.saveloc
will be the string path passed in EXCEPT if None was passed in. In this case, it will be an openzipfile.ZipFile
based on a temporary file.refs
will be a dict containing all the objects that were saved in the save file, keyed by object id. It will also contain the reference to the object that called.save
itself.
- classmethod load(saveloc='.', filename=None, refs=None)¶
Load an instance of this class from an archive or folder
- Parameters:
saveloc – Can be an open zipfile.ZipFile archive, a folder, or a filename. If it is an open zipfile or folder, it must contain a .json file that describes an instance of this object type. If ‘filename’ is not specified, it will load the first instance of this object discovered. If a filename, it must be a zip archive or a json file describing an object of this type.
filename – If saveloc is an open zipfile or folder, this indicates the name of the file to be loaded. If saveloc is a filename, this parameter is ignored.
refs – A dictionary of id -> object instances that will be used to complete references, if available.
- class gnome.tamoc.TamocSpill(num_elements=1000, num_per_timestep=None, start_position=(0.0, 0.0, 1000.0), release_time=datetime.now(), release_rate=0.0, release_duration=timedelta(hours=1), units='bbl/day', substance=None, release=None, water=None, gor=None, d0=0.0, phi_0=-np.pi / 2.0, theta_0=0.0, windage_range=(0.01, 0.04), windage_persist=900, on=True, name=None, **kwargs)¶
Bases:
gnome.spills.spill.Spill
Models a TAMOC spill by combining the near-field model with Release and Substance objects
# This really should be based in a BaseSpill Class!
Spills used by the gnome model. It contains a release object, which releases elements. It also contains a Substance which contains the type of substance spilled and it initializes data arrays to non-default values (non-zero).
- Parameters:
release (derived from
Release
) – an object defining how elements are to be releasedsubstance (derived from
Substance
) – an object defining the substance of this spill. Defaults toNonWeatheringSubstance
Optional parameters (kwargs):
- Parameters:
name (str) – Human-usable Name of this spill
on=True – Toggles the spill on/off.
amount=None – mass or volume of oil spilled.
units=None – must provide units for amount spilled.
amount_uncertainty_scale=0.0 – scale value in range 0-1 that adds uncertainty to the spill amount. Maximum uncertainty scale is (2/3) * spill_amount.
Note
Define either volume or mass in ‘amount’ attribute and provide appropriate ‘units’.
- release_time = None¶
- end_release_time = None¶
- start_position = None¶
- num_elements = None¶
- property substance¶
- release_mass¶
- release = None¶
- frac_coverage = 1.0¶
- rewind()¶
rewinds the release to original status (before anything has been released).