def test_get_oil_props(search, isNone): if isNone: with raises(NoResultFound): op = get_oil_props(search) else: op = get_oil_props(search) assert op is not None
def plume(distribution_type='droplet_size', distribution='weibull', windage_range=(.01, .04), windage_persist=900, substance_name=None, density=None, density_units='kg/m^3', **kwargs): """ Helper function returns an ElementType object containing 'rise_vel' and 'windages' initializer with user specified parameters for distribution. See below docs for details on the parameters. :param str distribution_type: default 'droplet_size' available options: 1. 'droplet_size': Droplet size is samples from the specified distribution. Rise velocity is calculated. 2.'rise_velocity': rise velocity is directly sampled from the specified distribution. No droplet size is computed. :param distribution='weibull': :param windage_range=(.01, .04): :param windage_persist=900: :param substance_name='oil_conservative': :param float density = None: :param str density_units='kg/m^3': """ if density is not None: # Assume density is at 15 K - convert density to api api = uc.convert('density', density_units, 'API', density) substance = get_oil_props({'name': substance_name, 'api': api}, 2) else: # model 2 cuts if fake oil substance = get_oil_props(substance_name, 2) if distribution_type == 'droplet_size': return ElementType([InitRiseVelFromDropletSizeFromDist( distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist)], substance) elif distribution_type == 'rise_velocity': return ElementType([InitRiseVelFromDist(distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist)], substance)
def test_correct_particles_set_by_initializers(fcn, arr_types, spill): ''' Tests that the correct elements (ones that were released last) are initialized ''' # let's only set the values for the last 10 elements # this is not how it would be used, but this is just to make sure # the values for the correct elements are set data_arrays = mock_append_data_arrays(arr_types, num_elems) data_arrays = mock_append_data_arrays(arr_types, num_elems, data_arrays) substance = get_oil_props(oil) if spill is not None: spill.release.num_elements = 10 fcn.initialize(num_elems, spill, data_arrays, substance) assert_dataarray_shape_size(arr_types, data_arrays, num_elems * 2) # contrived example since particles will be initialized for every timestep # when they are released. But just to make sure that only values for the # latest released elements are set for key in data_arrays: assert np.all(0 == data_arrays[key][:num_elems]) # values for these particles should be initialized to non-zero assert np.any(0 != data_arrays[key][-num_elems:])
def __init__(self, name=None, water=None, **kwargs): oil_info = name if name in _sample_oils: oil_info = _sample_oils[name] elif isinstance(name, six.string_types): # check if it's json from save file or from client if kwargs.get('component_density', False): oil_info = kwargs else: from oil_library import get_oil_props if kwargs.get('adios_oil_id', False): # init the oilprops from dictionary, old form oil_obj = get_oil_props(kwargs) else: # use name to get oil from oil library oil_obj = get_oil_props(name) oil_info = oil_obj.get_gnome_oil() kwargs['name'] = name #this is important; it passes name up to GnomeId to be handled there! else: raise ValueError('Must provide an oil name or OilLibrary.Oil ' 'to GnomeOil init') Oil.__init__(self, **oil_info) # because passing oilLibrary kwargs makes problem up the tree, # only pass up the kwargs specified in the schema keys = self._schema().get_nodes_by_attr('all') if 'windage_range' in kwargs: keys.append('windage_range') if 'windage_persist' in kwargs: keys.append('windage_persist') k2 = dict([(key, kwargs.get(key)) for key in keys]) read_only_attrs = GnomeOil._schema().get_nodes_by_attr('read_only') for n in read_only_attrs: k2.pop(n, None) k2.pop('water') Substance.__init__(self, **k2) self.water = water # add the array types that this substance DIRECTLY initializes self.array_types.update({'density': gat('density'), 'viscosity': gat('viscosity'), 'mass_components': gat('mass_components')}) self.array_types['mass_components'].shape = (self.num_components,) self.array_types['mass_components'].initial_value = (self.mass_fraction,)
def test_OilProps_sample_oil(oil, density, units): """ compare expected values with values stored in OilProps - make sure data entered correctly and unit conversion is correct """ o = get_oil_props(oil) d = uc.convert('density', units, 'kg/m^3', density) assert o.name == oil assert np.isclose(o.density_at_temp(273.15 + 15), d)
def test_OilProps_sample_oil(oil, density, units): """ compare expected values with values stored in OilProps - make sure data entered correctly and unit conversion is correct """ o = get_oil_props(oil) d = uc.convert('density', units, 'kg/m^3', density) assert o.name == oil assert np.isclose(get_density(o, 273.15 + 15), d)
def set_oiltype(self, oiltype): self.oil_name = oiltype self.set_config('seed:oil_type', oiltype) if self.oil_weathering_model == 'noaa': try: from oil_library import get_oil_props, _get_db_session from oil_library.models import Oil as ADIOS_Oil from oil_library.oil_props import OilProps session = _get_db_session() oils = session.query(ADIOS_Oil).filter( ADIOS_Oil.name == oiltype) ADIOS_ids = [oil.adios_oil_id for oil in oils] if len(ADIOS_ids) == 0: raise ValueError( 'Oil type "%s" not found in NOAA database' % oiltype) elif len(ADIOS_ids) == 1: self.oiltype = get_oil_props(oiltype) else: logging.warning( 'Two oils found with name %s (ADIOS IDs %s and %s). Using the first.' % (oiltype, ADIOS_ids[0], ADIOS_ids[1])) self.oiltype = OilProps(oils[0]) except Exception as e: logging.warning(e) return if oiltype not in self.oiltypes: raise ValueError( 'Oiltype %s is unknown. The following oiltypes are available: %s' % (oiltype, str(self.oiltypes))) indx = self.oiltypes.index(oiltype) linenumber = self.oiltypes_linenumbers[indx] oilfile = open(self.oiltype_file, 'r') for i in range(linenumber + 1): oilfile.readline() ref = oilfile.readline().split() self.oil_data = {} self.oil_data['reference_thickness'] = np.float(ref[0]) self.oil_data['reference_wind'] = np.float(ref[1]) tref = [] fref = [] wmax = [] while True: line = oilfile.readline() if not line[0].isdigit(): break line = line.split() tref.append(line[0]) fref.append(line[1]) wmax.append(line[3]) oilfile.close() self.oil_data['tref'] = np.array(tref, dtype='float') * 3600. self.oil_data['fref'] = np.array(fref, dtype='float') * .01 self.oil_data['wmax'] = np.array(wmax, dtype='float') self.oil_data['oiltype'] = oiltype # Store name of oil type
def test_hash(): """ make sure OilProps is hashable """ op = get_oil_props('ALASKA NORTH SLOPE (MIDDLE PIPELINE, 1997)') print(dir(op)) print(op.__hash__) print(f"Hash is: {op.__hash__()}") # this may change, but fpr now assert hash(op) == id(op)
def __init__(self): op = get_oil_props(u'ALASKA NORTH SLOPE (MIDDLE PIPELINE, 1997)') s_comp = sorted(op.record.sara_fractions, key=lambda s: s.ref_temp_k) s_dens = sorted(op.record.sara_densities, key=lambda s: s.ref_temp_k) # only keep density records + sara_fractions which fraction > 0. # OilProps prunes SARA to keep data for fractions > 0. s_dens = [ d_comp for ix, d_comp in enumerate(s_dens) if s_comp[ix].fraction > 0. ] s_comp = [comp for comp in s_comp if comp.fraction > 0.]
def substance(self, val): ''' first try to use get_oil_props using 'val'. If this fails, then assume user has provided a valid OilProps object and use it as is ''' try: self._substance = get_oil_props(val) except: if isinstance(val, basestring): raise self.logger.info('Failed to get_oil_props for {0}. Use as is ' 'assuming has OilProps interface'.format(val)) self._substance = val
def test_copy(self): ''' do a shallow copy and test that it is a shallow copy ''' op = get_oil_props('ARABIAN MEDIUM, PHILLIPS') cop = copy.copy(op) assert op == cop assert op is not cop assert op._r_oil is cop._r_oil for item in op.__dict__: try: assert getattr(op, item) == getattr(cop, item) except ValueError: assert np.all(getattr(op, item) == getattr(cop, item)) assert getattr(op, item) is getattr(cop, item)
def test_copy(self): ''' do a shallow copy and test that it is a shallow copy ''' op = get_oil_props('ARABIAN MEDIUM, PHILLIPS') cop = copy.copy(op) assert op == cop assert op is not cop assert op.record is cop.record for item in op.__dict__: try: assert getattr(op, item) == getattr(cop, item) except ValueError: assert np.all(getattr(op, item) == getattr(cop, item)) assert getattr(op, item) is getattr(cop, item)
def test_initialize_InitRiseVelFromDropletDist_weibull(): 'Test initialize data_arrays with Weibull dist' num_elems = 10 data_arrays = mock_append_data_arrays(rise_vel_diameter_array, num_elems) substance = get_oil_props(oil) spill = Spill(Release(datetime.now())) # (.001*.2) / (.693 ** (1 / 1.8)) - smaller droplet test case, in mm # so multiply by .001 dist = WeibullDistribution(alpha=1.8, lambda_=.000248) fcn = InitRiseVelFromDropletSizeFromDist(dist) fcn.initialize(num_elems, spill, data_arrays, substance) assert_dataarray_shape_size(rise_vel_array, data_arrays, num_elems) assert np.all(0 != data_arrays['rise_vel']) assert np.all(0 != data_arrays['droplet_diameter'])
def test_initialize_InitRiseVelFromDropletDist_weibull(): 'Test initialize data_arrays with Weibull dist' num_elems = 10 data_arrays = mock_append_data_arrays(rise_vel_diameter_array, num_elems) substance = get_oil_props(oil) spill = Spill(Release(datetime.now()), water=Water()) # (.001*.2) / (.693 ** (1 / 1.8)) - smaller droplet test case, in mm # so multiply by .001 dist = WeibullDistribution(alpha=1.8, lambda_=.000248) fcn = InitRiseVelFromDropletSizeFromDist(dist) fcn.initialize(num_elems, spill, data_arrays, substance) assert_dataarray_shape_size(rise_vel_array, data_arrays, num_elems) assert np.all(0 != data_arrays['rise_vel']) assert np.all(0 != data_arrays['droplet_diameter'])
def test_initialize_InitRiseVelFromDropletDist_weibull_with_min_max(): 'Test initialize data_arrays with Weibull dist' num_elems = 1000 data_arrays = mock_append_data_arrays(rise_vel_diameter_array, num_elems) substance = get_oil_props(oil) spill = Spill(Release(datetime.now()), water=Water()) # (.001*3.8) / (.693 ** (1 / 1.8)) - larger droplet test case, in mm # so multiply by .001 dist = WeibullDistribution(min_=0.002, max_=0.004, alpha=1.8, lambda_=.00456) fcn = InitRiseVelFromDropletSizeFromDist(dist) fcn.initialize(num_elems, spill, data_arrays, substance) # test for the larger droplet case above assert np.all(data_arrays['droplet_diameter'] >= .002) # test for the larger droplet case above assert np.all(data_arrays['droplet_diameter'] <= .004)
def test_initialize_InitRiseVelFromDropletDist_weibull_with_min_max(): 'Test initialize data_arrays with Weibull dist' num_elems = 1000 data_arrays = mock_append_data_arrays(rise_vel_diameter_array, num_elems) substance = get_oil_props(oil) spill = Spill(Release(datetime.now())) # (.001*3.8) / (.693 ** (1 / 1.8)) - larger droplet test case, in mm # so multiply by .001 dist = WeibullDistribution(min_=0.002, max_=0.004, alpha=1.8, lambda_=.00456) fcn = InitRiseVelFromDropletSizeFromDist(dist) fcn.initialize(num_elems, spill, data_arrays, substance) # test for the larger droplet case above assert np.all(data_arrays['droplet_diameter'] >= .002) # test for the larger droplet case above assert np.all(data_arrays['droplet_diameter'] <= .004)
def test_deepcopy(self): ''' do a shallow copy and test that it is a shallow copy ''' op = get_oil_props('ARABIAN MEDIUM, PHILLIPS') dcop = copy.deepcopy(op) assert op == dcop assert op is not dcop for item in op.__dict__: try: assert getattr(op, item) == getattr(dcop, item) except ValueError: assert np.all(getattr(op, item) == getattr(dcop, item)) if item == 'record' or getattr(op, item) is None: assert getattr(op, item) is getattr(dcop, item) else: assert getattr(op, item) is not getattr(dcop, item)
class TestProperties(object): op = get_oil_props(u'ALASKA NORTH SLOPE (MIDDLE PIPELINE, 1997)') s_comp = sorted(op.record.sara_fractions, key=lambda s: s.ref_temp_k) s_dens = sorted(op.record.sara_densities, key=lambda s: s.ref_temp_k) # only keep density records + sara_fractions which fraction > 0. # OilProps prunes SARA to keep data for fractions > 0. s_dens = [ d_comp for d_comp, s_c in zip(s_dens, s_comp) if s_c.fraction > 0.0 ] s_comp = [comp for comp in s_comp if comp.fraction > 0.] def test_num_components(self): assert self.op.num_components == len(self.s_comp) def test_sara(self): # boiling points assert np.all( self.op.boiling_point == [comp.ref_temp_k for comp in self.s_comp]) # mass fraction assert np.all( self.op.mass_fraction == [comp.fraction for comp in self.s_comp]) # sara type assert np.all( self.op._sara['type'] == [comp.sara_type for comp in self.s_comp]) # density assert np.all( self.op.boiling_point == [comp.ref_temp_k for comp in self.s_dens]) assert np.all(self.op.component_density == dens for dens in self.s_dens) assert np.allclose(self.op.mass_fraction.sum(), 1.0) def test_vapor_pressure(self): vp = self.op.vapor_pressure(273.)
def test_vapor_pressure(): # making sure the lru_cache works op = get_oil_props('ALASKA NORTH SLOPE (MIDDLE PIPELINE, 1997)') vp = op.vapor_pressure(303) print(f"{vp=}") # I have no idea if these values are correct assert np.allclose(vp, np.array([4.25112967e+04, 4.25112967e+04, 4.33030879e+03, 4.33030879e+03, 3.44544154e+02, 3.44544154e+02, 2.11131481e+01, 2.11131481e+01, 1.03347266e+00, 1.03347266e+00, 4.67207773e-02, 4.67207773e-02, 2.25663515e-03, 2.25663515e-03, 1.34558585e-04, 1.34558585e-04, 2.73632461e-05, 2.73632461e-05, 1.91947361e-05, 1.91947361e-05, 4.83593789e-19, 4.83593789e-19]))
def set_oiltype(self, oiltype): self.oil_name = oiltype self.set_config('input:spill:oil_type', oiltype) if self.oil_weathering_model == 'noaa': try: from oil_library import get_oil_props self.oiltype = get_oil_props(oiltype) except Exception as e: print e raise ValueError('Oil type "%s" not found in NOAA database' % oiltype) return if oiltype not in self.oiltypes: raise ValueError('The following oiltypes are available: %s' % str(self.oiltypes)) indx = self.oiltypes.index(oiltype) linenumber = self.oiltypes_linenumbers[indx] oilfile = open(self.oiltype_file, 'r') for i in range(linenumber + 1): oilfile.readline() ref = oilfile.readline().split() self.model.reference_thickness = np.float(ref[0]) self.model.reference_wind = np.float(ref[1]) tref = [] fref = [] wmax = [] while True: line = oilfile.readline() if not line[0].isdigit(): break line = line.split() tref.append(line[0]) fref.append(line[1]) wmax.append(line[3]) self.model.tref = np.array(tref, dtype='float')*3600. self.model.fref = np.array(fref, dtype='float')*.01 self.model.wmax = np.array(wmax, dtype='float') self.model.oiltype = oiltype # Store name of oil type
def set_oiltype(self, oiltype): self.oil_name = oiltype self.set_config('input:spill:oil_type', oiltype) if self.oil_weathering_model == 'noaa': try: from oil_library import get_oil_props self.oiltype = get_oil_props(oiltype) except Exception as e: print e raise ValueError('Oil type "%s" not found in NOAA database' % oiltype) return if oiltype not in self.oiltypes: raise ValueError('The following oiltypes are available: %s' % str(self.oiltypes)) indx = self.oiltypes.index(oiltype) linenumber = self.oiltypes_linenumbers[indx] oilfile = open(self.oiltype_file, 'r') for i in range(linenumber + 1): oilfile.readline() ref = oilfile.readline().split() self.model.reference_thickness = np.float(ref[0]) self.model.reference_wind = np.float(ref[1]) tref = [] fref = [] wmax = [] while True: line = oilfile.readline() if not line[0].isdigit(): break line = line.split() tref.append(line[0]) fref.append(line[1]) wmax.append(line[3]) self.model.tref = np.array(tref, dtype='float') * 3600. self.model.fref = np.array(fref, dtype='float') * .01 self.model.wmax = np.array(wmax, dtype='float') self.model.oiltype = oiltype # Store name of oil type
def test_ne(): assert (get_oil_props('ARABIAN MEDIUM, PHILLIPS') != get_oil_props('ARABIAN MEDIUM, EXXON'))
def plume(distribution_type='droplet_size', distribution='weibull', windage_range=(.01, .04), windage_persist=900, substance_name=None, density=None, density_units='kg/m^3', **kwargs): """ Helper function returns an ElementType object containing 'rise_vel' and 'windages' initializer with user specified parameters for distribution. See below docs for details on the parameters. NOTE: substance_name or density must be provided :param str distribution_type: default 'droplet_size' available options: 1. 'droplet_size': Droplet size is samples from the specified distribution. Rise velocity is calculated. 2.'rise_velocity': rise velocity is directly sampled from the specified distribution. No droplet size is computed. :param distribution='weibull': :param windage_range=(.01, .04): :param windage_persist=900: :param substance_name='oil_conservative': :param float density = None: :param str density_units='kg/m^3': """ if density is not None: # Assume density is at 15 K - convert density to api api = uc.convert('density', density_units, 'API', density) if substance_name is not None: substance = build_oil_props({ 'name': substance_name, 'api': api }, 2) else: substance = build_oil_props({'api': api}, 2) elif substance_name is not None: # model 2 cuts if fake oil substance = get_oil_props(substance_name, 2) else: ex = ValueError() ex.message = ("plume substance density and/or name must be provided") raise ex if distribution_type == 'droplet_size': return ElementType([ InitRiseVelFromDropletSizeFromDist(distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist) ], substance) elif distribution_type == 'rise_velocity': return ElementType([ InitRiseVelFromDist(distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist) ], substance)
def test_OilProps_DBquery(oil, api): """ test dbquery worked for an example like FUEL OIL NO.6 """ o = get_oil_props(oil) assert np.isclose(o.api, api, atol=0.01)
def test_eq(): op = get_oil_props('ARABIAN MEDIUM, PHILLIPS') op1 = get_oil_props('ARABIAN MEDIUM, PHILLIPS') assert op == op1
def plume(distribution_type='droplet_size', distribution=None, windage_range=(.01, .04), windage_persist=900, substance_name=None, density=None, density_units='kg/m^3', **kwargs): """ Helper function returns an ElementType object containing 'rise_vel' and 'windages' initialized with user specified parameters for distribution. :param str distribution_type: default is 'droplet_size' available options: * 'droplet_size': Droplet size is samples from the specified distribution. Rise velocity is calculated. * 'rise_velocity': rise velocity is directly sampled from the specified distribution. No droplet size is computed. :param distribution=None: An object capable of generating a probability distribution. :type gnome.utilities.distributions: Right now, we have: * UniformDistribution * NormalDistribution * LogNormalDistribution * WeibullDistribution New distribution classes could be made. The only requirement is they need to have a set_values() method which accepts a NumPy array. (presumably, this function will also modify the array in some way) :param windage_range=(.01, .04): :param windage_persist=900: # :param substance_name='oil_conservative': :param substance_name=None: :param float density = None: :param str density_units='kg/m^3': .. note:: substance_name or density must be provided """ # Add docstring from called classes # Note: following gives sphinx warnings on build, ignore for now. plume.__doc__ += ("\nDocumentation of InitRiseVelFromDropletSizeFromDist:\n" + InitRiseVelFromDropletSizeFromDist.__init__.__doc__ + "\nDocumentation of InitRiseVelFromDist:\n" + InitRiseVelFromDist.__init__.__doc__ + "\nDocumentation of InitWindages:\n" + InitWindages.__init__.__doc__ ) if density is not None: # Assume density is at 15 K - convert density to api api = uc.convert('density', density_units, 'API', density) if substance_name is not None: substance = build_oil_props({'name':substance_name, 'api': api}, 2) else: substance = build_oil_props({'api': api}, 2) elif substance_name is not None: # model 2 cuts if fake oil substance = get_oil_props(substance_name, 2) else: raise ValueError("plume substance density and/or name must be provided") if distribution_type == 'droplet_size': return ElementType([InitRiseVelFromDropletSizeFromDist( distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist)], substance) elif distribution_type == 'rise_velocity': return ElementType([InitRiseVelFromDist(distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist)], substance) else: raise TypeError('distribution_type must be either droplet_size or rise_velocity')
from datetime import datetime import numpy as np from gnome.utilities.inf_datetime import InfDateTime from gnome.spill.elements import floating from gnome.environment import Water from oil_library import get_oil_props from conftest import weathering_data_arrays, test_oil from gnome.weatherers import (Weatherer, HalfLifeWeatherer, NaturalDispersion, Dissolution, weatherer_sort) subs = get_oil_props(test_oil) rel_time = datetime(2012, 8, 20, 13) # yyyy/month/day/hr/min/sec class TestWeatherer: def test_init(self): weatherer = Weatherer() print weatherer assert weatherer.on assert weatherer.active assert weatherer.active_range == (InfDateTime('-inf'), InfDateTime('inf')) assert weatherer.array_types == { 'mass_components', 'mass', 'init_mass' }
def plume(distribution_type='droplet_size', distribution=None, windage_range=(.01, .04), windage_persist=900, substance_name=None, density=None, density_units='kg/m^3', **kwargs): """ Helper function returns an ElementType object containing 'rise_vel' and 'windages' initialized with user specified parameters for distribution. :param str distribution_type='droplet_size': type of distribution :param gnome.utilities.distributions distribution=None: :param windage_range=(.01, .04): minimum and maximum windage :type windage_range: tuple-of-floats :param int windage_persist=900: persistance of windage in seconds :param str substance_name=None: :param float density = None: :param str density_units='kg/m^3': Distribution type Available options: * 'droplet_size': Droplet size is sampled from the specified distribution. No droplet size is computed. * 'rise_velocity': Rise velocity is directly sampled from the specified distribution. Rise velocity is calculated. Distributions - An object capable of generating a probability distribution. Right now, we have: * UniformDistribution * NormalDistribution * LogNormalDistribution * WeibullDistribution New distribution classes could be made. The only requirement is they need to have a ``set_values()`` method which accepts a NumPy array. (presumably, this function will also modify the array in some way) .. note:: substance_name or density must be provided """ from oil_library import get_oil_props # Add docstring from called classes # Note: following gives sphinx warnings on build, ignore for now. plume.__doc__ += ("\nInitRiseVelFromDropletSizeFromDist Documentation:\n" + InitRiseVelFromDropletSizeFromDist.__init__.__doc__ + "\nInitRiseVelFromDist Documentation:\n" + InitRiseVelFromDist.__init__.__doc__ + "\nInitWindages Documentation:\n" + InitWindages.__init__.__doc__) if density is not None: # Assume density is at 15 C substance = NonWeatheringSubstance(standard_density=density) elif substance_name is not None: # model 2 cuts if fake oil substance = get_oil_props(substance_name, 2) else: raise ValueError('plume substance density and/or name ' 'must be provided') if distribution_type == 'droplet_size': return ElementType([ InitRiseVelFromDropletSizeFromDist(distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist) ], substance) elif distribution_type == 'rise_velocity': return ElementType([ InitRiseVelFromDist(distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist) ], substance) else: raise TypeError('distribution_type must be either droplet_size or ' 'rise_velocity')
def test_get_oil_props(): op = get_oil_props(sample_oil) assert np.isclose(sum(op.mass_fraction), 1.0) assert np.all(op.mass_fraction >= 0) assert op.api == \ uc.convert('density', 'kg/m^3', 'API', op.get_density(273.15 + 15))
def plume(distribution_type='droplet_size', distribution=None, windage_range=(.01, .04), windage_persist=900, substance_name=None, density=None, density_units='kg/m^3', **kwargs): """ Helper function returns an ElementType object containing 'rise_vel' and 'windages' initialized with user specified parameters for distribution. :param str distribution_type='droplet_size': type of distribution :param gnome.utilities.distributions distribution=None: :param windage_range=(.01, .04): minimum and maximum windage :type windage_range: tuple-of-floats :param int windage_persist=900: persistance of windage in seconds :param str substance_name=None: :param float density = None: :param str density_units='kg/m^3': Distribution type Available options: * 'droplet_size': Droplet size is sampled from the specified distribution. No droplet size is computed. * 'rise_velocity': Rise velocity is directly sampled from the specified distribution. Rise velocity is calculated. Distributions - An object capable of generating a probability distribution. Right now, we have: * UniformDistribution * NormalDistribution * LogNormalDistribution * WeibullDistribution New distribution classes could be made. The only requirement is they need to have a ``set_values()`` method which accepts a NumPy array. (presumably, this function will also modify the array in some way) .. note:: substance_name or density must be provided """ from oil_library import get_oil_props # Add docstring from called classes # Note: following gives sphinx warnings on build, ignore for now. plume.__doc__ += ("\nInitRiseVelFromDropletSizeFromDist Documentation:\n" + InitRiseVelFromDropletSizeFromDist.__init__.__doc__ + "\nInitRiseVelFromDist Documentation:\n" + InitRiseVelFromDist.__init__.__doc__ + "\nInitWindages Documentation:\n" + InitWindages.__init__.__doc__ ) if density is not None: # Assume density is at 15 C substance = NonWeatheringSubstance(standard_density=density) elif substance_name is not None: # model 2 cuts if fake oil substance = get_oil_props(substance_name, 2) else: raise ValueError('plume substance density and/or name ' 'must be provided') if distribution_type == 'droplet_size': return ElementType([InitRiseVelFromDropletSizeFromDist( distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist)], substance) elif distribution_type == 'rise_velocity': return ElementType([InitRiseVelFromDist(distribution=distribution, **kwargs), InitWindages(windage_range, windage_persist)], substance) else: raise TypeError('distribution_type must be either droplet_size or ' 'rise_velocity')
''' test functions in utilities modules ''' import numpy as np import pytest from oil_library import get_oil_props op_obj = get_oil_props('LUCKENBACH FUEL OIL') oil_obj = op_obj.record # Test case - get ref temps from densities then append ref_temp for # density at 0th index for a few more values: # density_test = [d.ref_temp_k for d in oil_.densities] # density_test.append(oil_.densities[0].ref_temp_k) density_tests = [ oil_obj.densities[ix].ref_temp_k if ix < len(oil_obj.densities) else oil_obj.densities[0].ref_temp_k for ix in range(0, len(oil_obj.densities) + 3) ] density_exp = [ d.kg_m_3 for temp in density_tests for d in oil_obj.densities if abs(d.ref_temp_k - temp) == 0 ] ''' test get_density for - scalar - list, tuple - numpy arrays as row/column and with/without output arrays '''
@pytest.mark.parametrize(("test_obj"), test_l) def test_save_load(saveloc_, test_obj): ''' test save/load for initializers and for ElementType objects containing each initializer. Tests serialize/deserialize as well. These are stored as nested objects in the Spill but this should also work so test it here ''' json_, savefile, refs = test_obj.save(saveloc_) test_obj2 = test_obj.__class__.load(savefile) assert test_obj == test_obj2 @pytest.mark.parametrize("substance", [test_oil, get_oil_props(test_oil)]) def test_element_type_init(substance): et = ElementType(substance=substance) if isinstance(substance, basestring): try: assert et.substance.get('name') == substance except AssertionError: assert et.substance.get('name') == _sample_oils[substance].name elif isinstance(substance, int): assert et.substance.get('id') == substance else: assert et.substance.get('name') == substance.get('name') def test_exception(): with pytest.raises(Exception):
assert n_et == et @pytest.mark.parametrize(("test_obj"), test_l) def test_save_load(saveloc_, test_obj): ''' test save/load for initializers and for ElementType objects containing each initializer. Tests serialize/deserialize as well. These are stored as nested objects in the Spill but this should also work so test it here ''' refs = test_obj.save(saveloc_) test_obj2 = load(os.path.join(saveloc_, refs.reference(test_obj))) assert test_obj == test_obj2 @pytest.mark.parametrize("substance", [test_oil, get_oil_props(test_oil)]) def test_element_type_init(substance): et = ElementType(substance=substance) if isinstance(substance, basestring): assert et.substance.get('name') == substance elif isinstance(substance, int): assert et.substance.get('id') == substance else: assert et.substance.get('name') == substance.get('name') def test_exception(): with pytest.raises(Exception): ElementType(substance='junk')
def test_OilProps_exceptions(): with pytest.raises(NoResultFound): get_oil_props('test')
@pytest.mark.parametrize(("test_obj"), test_l) def test_save_load(saveloc_, test_obj): ''' test save/load for initializers and for ElementType objects containing each initializer. Tests serialize/deserialize as well. These are stored as nested objects in the Spill but this should also work so test it here ''' refs = test_obj.save(saveloc_) test_obj2 = load(os.path.join(saveloc_, refs.reference(test_obj))) assert test_obj == test_obj2 @pytest.mark.parametrize("substance", [test_oil, get_oil_props(test_oil)]) def test_element_type_init(substance): et = ElementType(substance=substance) if isinstance(substance, basestring): assert et.substance.get('name') == substance elif isinstance(substance, int): assert et.substance.get('id') == substance else: assert et.substance.get('name') == substance.get('name') def test_exception(): with pytest.raises(Exception): ElementType(substance='junk')
from gnome.utilities.inf_datetime import InfDateTime from gnome.spill.elements import floating from gnome.environment import Water from oil_library import get_oil_props from conftest import weathering_data_arrays, test_oil from gnome.weatherers import (Weatherer, HalfLifeWeatherer, NaturalDispersion, Dissolution, weatherer_sort) subs = get_oil_props(test_oil) rel_time = datetime(2012, 8, 20, 13) # yyyy/month/day/hr/min/sec class TestWeatherer: def test_init(self): weatherer = Weatherer() print weatherer assert weatherer.on assert weatherer.active assert weatherer.active_range == (InfDateTime('-inf'), InfDateTime('inf')) assert weatherer.array_types == {'mass_components', 'mass', 'init_mass'}