Пример #1
1
def test_serialize_deseriailize():
    'test serialize/deserialize for webapi'
    wind = constant_wind(1., 0)
    water = Water()
    w = Waves(wind, water)

    json_ = w.serialize()

    # deserialize and ensure the dict's are correct
    w2 = Waves.deserialize(json_)
    assert w2.wind == Wind.deserialize(json_['wind'])
    assert w2.water == Water.deserialize(json_['water'])
    assert w == w2
Пример #2
0
def test_units():
    """
    just make sure there are no errors
    """
    wm = Wind(filename=wind_file)
    new_units = 'meter per second'
    assert wm.units != new_units
    wm.units = new_units
    assert wm.units == new_units
Пример #3
0
def test_set_timeseries():
    '''
    following operation requires a numpy array. Slicing numy array
    automatically makes it a 0-D array, make sure it gets converted to a 1-D
    array correctly
    '''
    wm = Wind(filename=wind_file)
    x = wm.timeseries[0]
    wm.timeseries = x
    assert wm.timeseries == x

    x = (datetime.now().replace(microsecond=0, second=0), (4, 5))
    wm.timeseries = x
    assert wm.timeseries['time'] == x[0]
    assert np.allclose(wm.timeseries['value'], x[1], atol=1e-6)
Пример #4
0
def test_new_from_dict_filename():
    """
    test to_dict function for Wind object
    create a new wind object and make sure it has same properties
    """

    wm = Wind(filename=wind_file)
    wm_state = wm.to_dict('create')
    print wm_state

    # this does not catch two objects with same ID

    wm2 = Wind.new_from_dict(wm_state)

    assert wm == wm2
Пример #5
0
def test_update_from_dict_with_dst_spring_transition():
    """
    checking a time series crossing over a DST transition.

    NOTE: the ofset is ignored! so there is no way to do this "right"
    """
    timeseries = gen_timeseries_for_dst('spring')
    wind_json = {'obj_type': 'gnome.environment.Wind',
                 'description': 'dst transition test',
                 'latitude': 90,
                 'longitude': 90,
                 'updated_at': '2016-03-12T12:52:45.385126',
                 'source_type': u'manual',
                 'source_id': u'unknown',
                 'timeseries': timeseries,
                 'units': 'knots',
                 'json_': u'webapi'
                 }

    wind = Wind.deserialize(wind_json)

    assert wind.description == 'dst transition test'
    assert wind.units == 'knots'

    ts = wind.get_timeseries()

    # this should raise if there is a problem
    wind._check_timeseries(ts)

    assert True  # if we got here, the test passed.
Пример #6
0
def test_serialize_deserialize(wind_circ, do):
    '''
    wind_circ is a fixture
    create - it creates new object after serializing original object
        and tests equality of the two

    update - tests serialize/deserialize and from_dict methods don't fail.
        It doesn't update any properties.
    '''
    json_ = wind_circ['wind'].serialize(do)
    dict_ = Wind.deserialize(json_)
    if do == 'create':
        new_w = Wind.new_from_dict(dict_)
        assert new_w == wind_circ['wind']
    else:
        wind_circ['wind'].from_dict(dict_)
        assert True
Пример #7
0
def test_eq():
    """
    tests the filename is not used for testing equality
    even if filename changes but other attributes are the same, the objects
    are equal
    """
    w = Wind(filename=wind_file)
    w1 = Wind(filename=wind_file)
    assert w == w1

    p, f = os.path.split(wind_file)
    f, e = os.path.splitext(f)
    w_copy = os.path.join(p, '{0}_copy{1}'.format(f, e))
    shutil.copy(wind_file, w_copy)
    w2 = Wind(filename=w_copy)
    w2.updated_at = w.updated_at    # match these before testing
    assert w == w2
Пример #8
0
def test_from_dict():
    """
    test update_from_dict function for Wind object
    update existing wind object update_from_dict
    """
    wm = Wind(filename=wind_file)
    wm_dict = wm.to_dict()

    # let's update timeseries
    update_value = np.array((10., 180.))
    (wm_dict['timeseries'][0]['value'])[:] = update_value
    wm.update_from_dict(wm_dict)

    updatable_attr = wm._state.get_field_by_attribute('update')
    for key in wm_dict.keys():
        if key in updatable_attr and key != 'timeseries':
            assert getattr(wm, key) == wm_dict[key]

    assert np.all(wm.timeseries['value'][0] == update_value)
Пример #9
0
def test_from_dict():
    """
    test from_dict function for Wind object
    update existing wind object from_dict
    """

    wm = Wind(filename=wind_file)
    wm_dict = wm.to_dict()

    # let's update timeseries

    update_value = np.array((10., 180.))
    (wm_dict['timeseries'][0]['value'])[:] = update_value
    wm.from_dict(wm_dict)

    for key in wm_dict.keys():
        if key != 'timeseries':
            assert wm.__getattribute__(key) == wm_dict.__getitem__(key)

    assert np.all(wm.timeseries['value'][0] == update_value)
Пример #10
0
def test_save_load(save_ref, saveloc_):
    """
    tests and illustrates the functionality of save/load for
    WindMover
    """
    wind = Wind(filename=file_)
    wm = WindMover(wind)
    wm_fname = 'WindMover_save_test.json'
    refs = None
    if save_ref:
        w_fname = 'Wind.json'
        refs = References()
        refs.reference(wind, w_fname)
        wind.save(saveloc_, refs, w_fname)

    wm.save(saveloc_, references=refs, name=wm_fname)

    l_refs = References()
    obj = load(os.path.join(saveloc_, wm_fname), l_refs)
    assert (obj == wm and obj is not wm)
    assert (obj.wind == wind and obj.wind is not wind)
    shutil.rmtree(saveloc_)  # clean-up
Пример #11
0
def test_save_load(save_ref, saveloc_):
    """
    tests and illustrates the functionality of save/load for
    WindMover
    """
    wind = Wind(filename=file_)
    wm = WindMover(wind)
    wm_fname = 'WindMover_save_test.json'
    refs = None
    if save_ref:
        w_fname = 'Wind.json'
        refs = References()
        refs.reference(wind, w_fname)
        wind.save(saveloc_, refs, w_fname)

    wm.save(saveloc_, references=refs, name=wm_fname)

    l_refs = References()
    obj = load(os.path.join(saveloc_, wm_fname), l_refs)
    assert (obj == wm and obj is not wm)
    assert (obj.wind == wind and obj.wind is not wind)
    shutil.rmtree(saveloc_)  # clean-up
Пример #12
0
def test_serialize_deserialize():
    'test serialize/deserialize for webapi'
    wind = constant_wind(1., 0)
    av = RunningAverage(wind)
    json_ = av.serialize()
    json_['wind'] = wind.serialize()

    # deserialize and ensure the dict's are correct
    d_av = RunningAverage.deserialize(json_)
    assert d_av['wind'] == Wind.deserialize(json_['wind'])
    d_av['wind'] = wind
    av.update_from_dict(d_av)
    assert av.wind is wind
Пример #13
0
def test_serialize_deseriailize():
    'test serialize/deserialize for webapi'
    wind = constant_wind(1., 0)
    water = Water()
    w = Waves(wind, water)

    json_ = w.serialize()

    # deserialize and ensure the dict's are correct
    w2 = Waves.deserialize(json_)
    assert w2.wind == Wind.deserialize(json_['wind'])
    assert w2.water == Water.deserialize(json_['water'])
    assert w == w2
Пример #14
0
def test_peak_wave_period(wind_speed, expected):
    "fully developed seas"
    series = np.array((start_time, (wind_speed, 45)),
                      dtype=datetime_value_2d).reshape((1, ))
    test_wind = Wind(timeseries=series, units='meter per second')

    w = Waves(test_wind, default_water)

    print 'Wind speed:', w.wind.get_value(start_time)

    T_w = w.peak_wave_period(None, start_time)

    assert np.isclose(T_w, expected)
Пример #15
0
def test_read_file_init():
    """
    initialize from a long wind file
    """

    wind = Wind(filename=file_)
    wm = WindMover(wind)
    wind_ts = wind.get_wind_data(coord_sys='uv', units='meter per second')
    _defaults(wm)  # check defaults set correctly
    assert not wm.make_default_refs
    cpp_timeseries = _get_timeseries_from_cpp(wm)
    _assert_timeseries_equivalence(cpp_timeseries, wind_ts)

    # make sure default units is correct and correctly called
    # NOTE: Following functionality is already tested in test_wind.py,
    #       but what the heck - do it here too.

    wind_ts = wind.get_wind_data(coord_sys=ts_format.uv)
    cpp_timeseries['value'] = uc.convert('Velocity',
                                         'meter per second', wind.units,
                                         cpp_timeseries['value'])

    _assert_timeseries_equivalence(cpp_timeseries, wind_ts)
Пример #16
0
def test_new_from_dict_with_dst_fall_transition():
    """
    checking a time series crossing over fall DST transition.

    This creates duplicate times, which we can't deal with.
    """
    wind_json = {'obj_type': 'gnome.environment.Wind',
                 'description': 'fall dst transition test',
                 'latitude': 90,
                 'longitude': 90,
                 'updated_at': '2016-03-12T12:52:45.385126',
                 'source_type': u'manual',
                 'source_id': u'unknown',
                 'timeseries': gen_timeseries_for_dst('fall'),
                 'units': 'knots',
                 'json_': u'webapi'
                 }

    wind_dict = Wind.deserialize(wind_json)
    wind = Wind.new_from_dict(wind_dict)

    assert wind.description == 'fall dst transition test'
    assert wind.units == 'knots'
Пример #17
0
def test_serialize_deserialize_update_webapi(wind_circ):
    '''
    wind_circ is a fixture
    create - it creates new object after serializing original object
        and tests equality of the two

    update - tests serialize/deserialize and update_from_dict methods don't
        fail. It doesn't update any properties.
    '''
    wind = wind_circ['wind']
    serial = wind.serialize('webapi')
    dict_ = Wind.deserialize(serial)
    wind.update_from_dict(dict_)
    assert True
Пример #18
0
def test_read_file_init():
    """
    initialize from a long wind file
    """

    wind = Wind(filename=file_)
    wm = WindMover(wind)
    wind_ts = wind.get_timeseries(format='uv', units='meter per second')
    _defaults(wm)  # check defaults set correctly
    cpp_timeseries = _get_timeseries_from_cpp(wm)
    _assert_timeseries_equivalence(cpp_timeseries, wind_ts)

    # make sure default units is correct and correctly called
    # NOTE: Following functionality is already tested in test_wind.py,
    #       but what the heck - do it here too.

    wind_ts = wind.get_timeseries(format=ts_format.uv)
    cpp_timeseries['value'] = unit_conversion.convert('Velocity',
                                                      'meter per second',
                                                      wind.units,
                                                      cpp_timeseries['value'])

    _assert_timeseries_equivalence(cpp_timeseries, wind_ts)
Пример #19
0
def test_roundtrip_dst_spring_transition():
    """
    checking the round trip trhough serializing for time series
    crossing over the spring DST transition.
    """
    timeseries = gen_timeseries_for_dst('spring')
    wind_json = {'obj_type': 'gnome.environment.wind.Wind',
                 'description': 'dst transition test',
                 'latitude': 90,
                 'longitude': 90,
                 'updated_at': '2016-03-12T12:52:45.385126',
                 'source_type': u'manual',
                 'source_id': u'unknown',
                 'timeseries': timeseries,
                 'units': 'knots',
                 'json_': u'webapi'
                 }

    wind = Wind.deserialize(wind_json)

    # now make one from the new dict...
    wind2 = Wind.deserialize(wind_json)

    assert wind2 == wind
Пример #20
0
def test_new_from_dict_timeseries():
    """
    test to_dict function for Wind object
    create a new wind object and make sure it has same properties
    """

    wm = ConstantWind(10, 45, 'knots')
    wm_state = wm.to_dict('create')
    print wm_state

    # this does not catch two objects with same ID

    wm2 = Wind.new_from_dict(wm_state)

    assert wm == wm2
Пример #21
0
def test_serialize_deserialize(wind_circ):
    """
    tests and illustrate the funcitonality of serialize/deserialize for
    WindMover.
    """
    wind = Wind(filename=file_)
    wm = WindMover(wind)
    serial = wm.serialize('webapi')
    assert 'wind' in serial

    dict_ = wm.deserialize(serial)
    dict_['wind'] = wind_circ['wind']
    wm.update_from_dict(dict_)

    assert wm.wind == wind_circ['wind']
Пример #22
0
def make_model(images_dir=os.path.join(base_dir,"images")):
    print "initializing the model"

    start_time = datetime(2013, 7, 23, 0)
    model = Model(start_time = start_time,
                              duration = timedelta(hours=47),	# n+1 of data in file
                              time_step = 900, # 4 hr in seconds
                              uncertain = False,
                              )
    
    mapfile = os.path.join(base_dir, './coast.bna')
    print "adding the map"
    gnome_map = MapFromBNA(mapfile, refloat_halflife=6)  # hours
    
    print "adding renderer" 
    model.outputters += Renderer(mapfile, images_dir, size=(1800, 1600))

    print "adding a wind mover from a time-series"
    ## this is wind
    wind_file=get_datafile(os.path.join(base_dir, 'wind.WND'))
    wind = Wind(filename=wind_file)
    w_mover = WindMover(wind)
    model.movers += w_mover
    
    print "adding a current mover:"
    ## this is currents
    curr_file = get_datafile(os.path.join(base_dir, 'current.txt'))
    model.movers += GridCurrentMover(curr_file)

    ##
    ## Add some spills (sources of elements)
    ##
    print "adding 13 points in a cluster that has some small initial separation as the source of spill"
    
    for i in range(len(coor)):
        
        aaa=utmToLatLng(14,coor[i][0],coor[i][1],northernHemisphere=True)
        model.spills += point_line_release_spill(num_elements=1,
                                                start_position = (aaa[1],aaa[0], 0.0),
                                                release_time = start_time,
                                                )

    print "adding netcdf output"
    netcdf_output_file = os.path.join(base_dir,'GNOME_output.nc')
    scripting.remove_netcdf(netcdf_output_file)
    model.outputters += NetCDFOutput(netcdf_output_file, which_data='all')

    return model
Пример #23
0
def test_full_run_extended():
    '''
    test algorithm resets two day running average with a new time
    '''
    ts = np.zeros((20, ), dtype=datetime_value_2d)
    ts[:] = [(datetime(2015, 1, 1, 1, 0), (10, 0)),
             (datetime(2015, 1, 1, 2, 0), (20, 0)),
             (datetime(2015, 1, 1, 3, 0), (10, 0)),
             (datetime(2015, 1, 1, 4, 0), (20, 0)),
             (datetime(2015, 1, 1, 5, 0), (10, 0)),
             (datetime(2015, 1, 1, 6, 0), (20, 0)),
             (datetime(2015, 1, 1, 7, 0), (10, 0)),
             (datetime(2015, 1, 1, 8, 0), (20, 0)),
             (datetime(2015, 1, 1, 9, 0), (10, 0)),
             (datetime(2015, 1, 1, 10, 0), (20, 0)),
             (datetime(2015, 1, 5, 1, 0), (10, 0)),
             (datetime(2015, 1, 5, 2, 0), (20, 0)),
             (datetime(2015, 1, 5, 3, 0), (10, 0)),
             (datetime(2015, 1, 5, 4, 0), (20, 0)),
             (datetime(2015, 1, 5, 5, 0), (10, 0)),
             (datetime(2015, 1, 5, 6, 0), (20, 0)),
             (datetime(2015, 1, 5, 7, 0), (10, 0)),
             (datetime(2015, 1, 5, 8, 0), (20, 0)),
             (datetime(2015, 1, 5, 9, 0), (10, 0)),
             (datetime(2015, 1, 5, 10, 0), (20, 0))]

    wm = Wind(filename=wind_file, units='mps')

    start_time = datetime(2015, 1, 1, 1)
    model_time = start_time

    running_av = RunningAverage(wind=wm)
    # running_av = RunningAverage(timeseries=ts)
    running_av.prepare_for_model_run(model_time)
    running_av.prepare_for_model_step(model_time)

    print "running_av"
    print running_av.ossm.timeseries[:]

    model_time = datetime(2015, 1, 5, 4, 0)
    running_av.prepare_for_model_run(model_time)
    running_av.prepare_for_model_step(model_time)

    print "running_av2"
    print running_av.ossm.timeseries[:]

    assert np.all(running_av.ossm.timeseries['value']['u'][:] == 15)
Пример #24
0
def test_serialize_deseriailize():
    'test serialize/deserialize for webapi'
    e = Evaporation()
    wind = constant_wind(1., 0)
    water = Water()
    json_ = e.serialize()
    json_['wind'] = wind.serialize()
    json_['water'] = water.serialize()

    # deserialize and ensure the dict's are correct
    d_ = Evaporation.deserialize(json_)
    assert d_['wind'] == Wind.deserialize(json_['wind'])
    assert d_['water'] == Water.deserialize(json_['water'])
    d_['wind'] = wind
    d_['water'] = water
    e.update_from_dict(d_)
    assert e.wind is wind
    assert e.water is water
Пример #25
0
    def __init__(self):
        wind_file = testdata['ComponentMover']['wind']
        #self.ossm = cy_ossm_time.CyOSSMTime(wind_file,file_contains=basic_types.ts_format.magnitude_direction)
        wm = Wind(filename=wind_file)

        cats1_file = testdata['ComponentMover']['curr']
        cats2_file = testdata['ComponentMover']['curr2']
        self.component = cy_component_mover.CyComponentMover()
        self.component.set_ossm(wm.ossm)
        #self.component.set_ossm(self.ossm)
        self.component.text_read(cats1_file, cats2_file)
        self.component.ref_point = (-75.262319, 39.142987, 0)

        super(ComponentMove, self).__init__()
        self.ref[:] = (-75.262319, 39.142987, 0)
        self.component.prepare_for_model_run()
        self.component.prepare_for_model_step(self.model_time, self.time_step,
                                              1, self.spill_size)
Пример #26
0
def test_serialize_deseriailize():
    'test serialize/deserialize for webapi'
    e = Evaporation()
    wind = constant_wind(1., 0)
    water = Water()
    json_ = e.serialize()
    json_['wind'] = wind.serialize()
    json_['water'] = water.serialize()

    # deserialize and ensure the dict's are correct
    d_ = Evaporation.deserialize(json_)
    assert d_['wind'] == Wind.deserialize(json_['wind'])
    assert d_['water'] == Water.deserialize(json_['water'])
    d_['wind'] = wind
    d_['water'] = water
    e.update_from_dict(d_)
    assert e.wind is wind
    assert e.water is water
Пример #27
0
def test_timespan():
    """
    Ensure the active flag is being set correctly and checked,
    such that if active=False, the delta produced by get_move = 0
    """
    time_step = 15 * 60  # seconds

    start_pos = (3., 6., 0.)
    rel_time = datetime(2012, 8, 20, 13)  # yyyy/month/day/hr/min/sec

    sc = sample_sc_release(5, start_pos, rel_time)

    # value is given as (r,theta)
    model_time = rel_time
    time_val = np.zeros((1, ), dtype=datetime_value_2d)
    time_val['time'] = rel_time
    time_val['value'] = (2., 25.)

    wm = WindMover(Wind(timeseries=time_val,
                        units='meter per second'),
                   active_range=(model_time + timedelta(seconds=time_step),
                                 InfDateTime('inf')))

    wm.prepare_for_model_run()
    wm.prepare_for_model_step(sc, time_step, model_time)

    delta = wm.get_move(sc, time_step, model_time)
    wm.model_step_is_done()

    assert wm.active is False
    assert np.all(delta == 0)  # model_time + time_step = active_start

    wm.active_range = (model_time - timedelta(seconds=time_step / 2),
                       InfDateTime('inf'))
    wm.prepare_for_model_step(sc, time_step, model_time)

    delta = wm.get_move(sc, time_step, model_time)
    wm.model_step_is_done()

    assert wm.active is True
    print '''\ntest_timespan delta \n{0}'''.format(delta)
    assert np.all(delta[:, :2] != 0)  # model_time + time_step > active_start
Пример #28
0
def test_serialize_deseriailize():
    "test serialize/deserialize for webapi"
    wind = constant_wind(1.0, 0)
    water = Water()
    w = Waves(wind, water)
    json_ = w.serialize()
    json_["wind"] = wind.serialize()
    json_["water"] = water.serialize()

    # deserialize and ensure the dict's are correct
    d_ = Waves.deserialize(json_)
    print "d_"
    print d_
    assert d_["wind"] == Wind.deserialize(json_["wind"])
    assert d_["water"] == Water.deserialize(json_["water"])
    d_["wind"] = wind
    d_["water"] = water
    w.update_from_dict(d_)
    assert w.wind is wind
    assert w.water is water
Пример #29
0
def test_serialize_deseriailize():
    'test serialize/deserialize for webapi'
    wind = constant_wind(1., 0)
    water = Water()
    w = Waves(wind, water)
    json_ = w.serialize()
    json_['wind'] = wind.serialize()
    json_['water'] = water.serialize()

    # deserialize and ensure the dict's are correct
    d_ = Waves.deserialize(json_)
    print 'd_'
    print d_
    assert d_['wind'] == Wind.deserialize(json_['wind'])
    assert d_['water'] == Water.deserialize(json_['water'])
    d_['wind'] = wind
    d_['water'] = water
    w.update_from_dict(d_)
    assert w.wind is wind
    assert w.water is water
Пример #30
0
def make_model(images_dir):
    print 'initializing the model'

    timestep = timedelta(minutes=15)  # this is already default
    start_time = datetime(2012, 9, 15, 12, 0)
    model = Model(timestep, start_time)

    # timeseries for wind data. The value is interpolated if time is between
    # the given datapoints
    series = np.zeros((4, ), dtype=datetime_value_2d)
    series[:] = [(start_time, (5, 180)),
                 (start_time + timedelta(hours=6), (10, 180)),
                 (start_time + timedelta(hours=12), (12, 180)),
                 (start_time + timedelta(hours=18), (8, 180))]
    wind = Wind(timeseries=series, units='m/s')
    model.environment += wind

    # include a wind mover and random diffusion
    print 'adding movers'
    model.movers += [WindMover(wind), RandomMover()]

    # add particles
    print 'adding particles'
    release = release_from_splot_data(start_time,
                                      'GL.2013267._LE_WHOLELAKE.txt')
    model.spills += Spill(release)

    # output data as png images and in netcdf format
    print 'adding outputters'
    netcdf_file = os.path.join(base_dir, 'script_example.nc')

    # ignore renderer for now
    model.outputters += [
        Renderer(images_dir=images_dir,
                 size=(800, 800),
                 projection_class=GeoProjection),
        NetCDFOutput(netcdf_file)
    ]

    print 'model complete'
    return model
Пример #31
0
    def __init__(self, wind=None, timeseries=None, past_hours_to_average=3,
                 **kwargs):
        """
        Initializes a running average object from a wind and past hours
        to average

        If no wind is given, timeseries gets initialized as:

            timeseries = np.zeros((1,), dtype=basic_types.datetime_value_2d)
            units = 'mps'
        (note: probably should be an error)

        All other keywords are optional. Optional parameters (kwargs):

        :param past_hours_to_average: default is 3

        """
        self.units = 'mps'
        self.format = 'uv'
        self._past_hours_to_average = past_hours_to_average
        self.wind = wind

        if (wind is None and timeseries is None):
            mvg_timeseries = np.array([(sec_to_date(zero_time()), [0.0, 0.0])],
                                      dtype=basic_types.datetime_value_2d)
            moving_timeseries = self._convert_to_time_value_pair(mvg_timeseries)

        else:
            if wind is not None:
                moving_timeseries = wind.ossm.create_running_average(self._past_hours_to_average)
            else:
                self.wind = Wind(timeseries, units='mps', format='uv')
                moving_timeseries = self.wind.ossm.create_running_average(self._past_hours_to_average)

        # print "moving_timeseries"
        # print moving_timeseries

        self.ossm = CyTimeseries(timeseries=moving_timeseries)

        super(RunningAverage, self).__init__(**kwargs)
Пример #32
0
def test_new_from_dict_with_dst_fall_transition():
    """
    checking a time series crossing over fall DST transition.

    This creates duplicate times, which we can't deal with.
    """
    wind_json = {'obj_type': 'gnome.environment.Wind',
                 'description': 'fall dst transition test',
                 'latitude': 90,
                 'longitude': 90,
                 'updated_at': '2016-03-12T12:52:45.385126',
                 'source_type': u'manual',
                 'source_id': u'unknown',
                 'timeseries': gen_timeseries_for_dst('fall'),
                 'units': 'knots',
                 'json_': u'webapi'
                 }

    wind = Wind.deserialize(wind_json)

    assert wind.description == 'fall dst transition test'
    assert wind.units == 'knots'
Пример #33
0
    def test_set_wind_data(self, all_winds):
        """
        get_wind_data with default output format
        """
        # check get_time_value()

        wm = Wind(timeseries=all_winds['wind'].get_wind_data(),
                  format='r-theta',
                  units='meter per second')
        gtime_val = wm.get_wind_data()
        x = gtime_val[:2]
        x['value'] = [(1, 10), (2, 20)]

        # default format is 'r-theta'
        wm.set_wind_data(x, 'meter per second')

        # only matches to 10^-14
        assert np.allclose(wm.get_wind_data()['value'][:, 0], x['value'][:, 0],
                           atol, rtol)
        assert np.all(wm.get_wind_data()['time'] == x['time'])
Пример #34
0
def test_make_default_refs():
    '''
    ensure make_default_refs is a thread-safe operation
    once object is instantiated, object.make_default_refs is an attribute of
    instance
    '''
    model = Model()
    model1 = Model()
    wind = Wind(timeseries=[(t, (0, 1))], units='m/s')
    water = Water()

    waves = Waves(name='waves')
    waves1 = Waves(name='waves1', make_default_refs=False)
    model.environment += [wind, water, waves]
    model1.environment += waves1

    # waves should get auto hooked up/waves1 should not
    model.step()
    assert waves.wind is wind
    assert waves.water is water
    with pytest.raises(ReferencedObjectNotSet):
        model1.step()
Пример #35
0
    def test_variable_wind_after_model_time_with_extrapolation(self):
        '''
            test to make sure the wind mover is behaving properly with
            out-of-bounds winds.
            A variable wind can extrapolate if it is configured to do so,
            so prepare_for_model_step() should succeed in this case.

            We are testing that the wind extrapolates properly, so the
            windages should be updated in the same way as the in-bounds test
        '''
        wind_time = datetime(2012, 8, 21, 13)  # one day after model time

        time_series = (np.zeros((3, ), dtype=datetime_value_2d)
                       .view(dtype=np.recarray))
        time_series.time = [sec_to_date(date_to_sec(wind_time) +
                                        self.time_step * i)
                            for i in range(3)]
        time_series.value = np.array(((2., 25.), (2., 25.), (2., 25.)))

        wind = Wind(timeseries=time_series.reshape(3),
                    extrapolation_is_allowed=True,
                    units='meter per second')

        wm = WindMover(wind)
        wm.prepare_for_model_run()

        for ix in range(2):
            curr_time = sec_to_date(date_to_sec(self.model_time) +
                                    self.time_step * ix)

            old_windages = np.copy(self.sc['windages'])
            wm.prepare_for_model_step(self.sc, self.time_step, curr_time)

            mask = self.sc['windage_persist'] == -1
            assert np.all(self.sc['windages'][mask] == old_windages[mask])

            mask = self.sc['windage_persist'] > 0
            assert np.all(self.sc['windages'][mask] != old_windages[mask])
Пример #36
0
    def test_set_timeseries(self, all_winds):
        """
        get_timeseries with default output format
        """

        # check get_time_value()

        wm = Wind(timeseries=all_winds['wind'].get_timeseries(),
                  format='r-theta', units='meter per second')
        gtime_val = wm.get_timeseries()
        x = gtime_val[:2]
        x['value'] = [(1, 10), (2, 20)]

        wm.set_timeseries(x, 'meter per second')  # default format is 'r-theta'

        assert np.allclose(wm.get_timeseries()['value'][:, 0], x['value'
                           ][:, 0], atol, rtol)  # only matches to 10^-14
        assert np.all(wm.get_timeseries()['time'] == x['time'])
Пример #37
0
    def test_windages_updated(self):
        '''
            explicitly test to make sure:
            - windages are being updated for persistence != 0 and
            - windages are not being changed for persistance == -1
        '''
        wind = Wind(timeseries=np.array((self.model_time, (2., 25.)),
                                        dtype=datetime_value_2d).reshape(1),
                    units='meter per second')

        wm = WindMover(wind)
        wm.prepare_for_model_run()

        for ix in range(2):
            curr_time = sec_to_date(date_to_sec(self.model_time) +
                                    self.time_step * ix)
            old_windages = np.copy(self.sc['windages'])
            wm.prepare_for_model_step(self.sc, self.time_step, curr_time)

            mask = self.sc['windage_persist'] == -1
            assert np.all(self.sc['windages'][mask] == old_windages[mask])

            mask = self.sc['windage_persist'] > 0
            assert np.all(self.sc['windages'][mask] != old_windages[mask])
Пример #38
0
def test_model_release_after_start():
    '''
    This runs the model for a simple spill, that starts after the model starts
    '''
    units = 'meter per second'
    seconds_in_minute = 60
    start_time = datetime(2013, 2, 22, 0)

    model = Model(time_step=30 * seconds_in_minute,
                  start_time=start_time,
                  duration=timedelta(hours=3))

    # add a spill that starts after the run begins.
    release_time = start_time + timedelta(hours=1)
    model.spills += point_line_release_spill(num_elements=5,
                                             start_position=(0, 0, 0),
                                             release_time=release_time)

    # and another that starts later..

    model.spills += point_line_release_spill(num_elements=4,
                                             start_position=(0, 0, 0),
                                             release_time=(start_time +
                                                           timedelta(hours=2)))

    # Add a Wind mover:
    series = np.array((start_time, (10, 45)), dtype=datetime_value_2d).reshape(
        (1, ))
    model.movers += WindMover(Wind(timeseries=series, units=units))

    for step in model:
        print 'running a step'
        assert step['step_num'] == model.current_time_step

        for sc in model.spills.items():
            print 'num_LEs', len(sc['positions'])
Пример #39
0
            06,
            20,
            10 + i,
            30,
            ) for i in range(len(dtv_rq) - 1)]
        Wind(timeseries=dtv_rq, units='meter per second')

    # exception raised since no units given for timeseries during init

    with pytest.raises(TypeError):
        Wind(timeseries=dtv)

    # no units during set_timeseries

    with pytest.raises(TypeError):
        wind = Wind(timeseries=dtv, units='meter per second')
        wind.set_timeseries(dtv)

    # invalid units

    with pytest.raises(unit_conversion.InvalidUnitError):
        wind = Wind(timeseries=dtv, units='met per second')


def test_read_file_init():
    """
    initialize from a long wind file
    """

    wm = Wind(filename=wind_file)
    print
Пример #40
0
def make_model(images_dir=os.path.join(base_dir, 'images')):

    # create the maps:
    print 'creating the maps'
    mapfile = get_datafile(os.path.join(base_dir, './MassBayMap.bna'))
    gnome_map = MapFromBNA(
        mapfile,
        refloat_halflife=1,  # hours
        raster_size=2048 * 2048  # about 4 MB
    )

    renderer = Renderer(
        mapfile,
        images_dir,
        image_size=(800, 800),
    )

    print 'initializing the model'
    start_time = datetime(2016, 3, 9, 15)

    # 1 hour in seconds
    # Default to now, rounded to the nearest hour
    model = Model(time_step=3600,
                  start_time=start_time,
                  duration=timedelta(days=6),
                  map=gnome_map,
                  uncertain=True)

    print 'adding outputters'
    model.outputters += renderer

    # netcdf_file = os.path.join(base_dir, 'script_boston.nc')
    # scripting.remove_netcdf(netcdf_file)
    # model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    # model.outputters += KMZOutput(os.path.join(base_dir, 'script_boston.kmz'))

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=100000)

    print 'adding a wind mover:'

    series = np.zeros((2, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 180))
    series[1] = (start_time + timedelta(hours=18), (5, 180))
    w = Wind(filename=os.path.join(base_dir, '22NM_WNW_PortAngelesWA.nws'))
    w_mover = WindMover(w)
    model.movers += w_mover
    model.environment += w_mover.wind

    # print 'adding a cats shio mover:'

    # curr_file = get_datafile(os.path.join(base_dir, r"./EbbTides.cur"))
    # tide_file = get_datafile(os.path.join(base_dir, r"./EbbTidesShio.txt"))

    # c_mover = CatsMover(curr_file, tide=Tide(tide_file))

    # # this is the value in the file (default)
    # c_mover.scale_refpoint = (-70.8875, 42.321333)
    # c_mover.scale = True
    # c_mover.scale_value = -1

    # model.movers += c_mover

    # # TODO: cannot add this till environment base class is created
    # model.environment += c_mover.tide

    print 'adding a spill'

    end_time = start_time + timedelta(hours=12)
    spill = point_line_release_spill(num_elements=100,
                                     start_position=(-70.911432, 42.369142,
                                                     0.0),
                                     release_time=start_time,
                                     end_release_time=end_time)

    model.spills += spill

    return model
Пример #41
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2004, 12, 31, 13, 0)

    # 1 day of data in file
    # 1/2 hr in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(days=1),
                  time_step=30 * 60,
                  uncertain=True)

    mapfile = get_datafile(os.path.join(base_dir, 'ChesapeakeBay.bna'))

    print 'adding the map'
    model.map = MapFromBNA(mapfile, refloat_halflife=1)  # seconds

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(mapfile, images_dir, image_size=(800, 600),
                        output_timestep=timedelta(hours=2),
                        draw_ontop='forecast')
    # set the viewport to zoom in on the map:
    renderer.viewport = ((-76.5, 37.), (-75.8, 38.))
    # add the raster map, so we can see it...
    # note: this is really slow, so only use for diagnostics
    # renderer.raster_map = model.map

    print 'adding outputters'
    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'script_chesapeake_bay.nc')
    scripting.remove_netcdf(netcdf_file)
    model.outputters += NetCDFOutput(netcdf_file, which_data='all',
                                     output_timestep=timedelta(hours=2))

    print 'adding a spill'
    # for now subsurface spill stays on initial layer
    # - will need diffusion and rise velocity
    # - wind doesn't act
    # - start_position = (-76.126872, 37.680952, 5.0),
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-76.126872,
                                                     37.680952,
                                                     0.0),
                                     release_time=start_time)

    model.spills += spill

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=50000)

    print 'adding a wind mover:'

    series = np.zeros((2, ), dtype=datetime_value_2d)
    series[0] = (start_time, (30, 0))
    series[1] = (start_time + timedelta(hours=23), (30, 0))

    wind = Wind(timeseries=series, units='knot')

    # default is .4 radians
    w_mover = WindMover(wind, uncertain_angle_scale=0)
    wind.extrapolation_is_allowed=True
    model.movers += w_mover

    print 'adding a current mover:'
    curr_file = get_datafile(os.path.join(base_dir, 'ChesapeakeBay.nc'))
    topology_file = get_datafile(os.path.join(base_dir, 'ChesapeakeBay.dat'))

    # uncertain_time_delay in hours
    c_mover = GridCurrentMover(curr_file, topology_file,
                               uncertain_time_delay=3)
    c_mover.uncertain_along = 0  # default is .5
    # c_mover.uncertain_cross = 0  # default is .25

    model.movers += c_mover

    return model
Пример #42
0
    Test ValueError exception thrown if improper input arguments
    Test TypeError thrown if units are not given - so they are None
    """
    # valid timeseries for testing

    dtv = np.zeros((4, ), dtype=datetime_value_2d).view(dtype=np.recarray)
    dtv.time = [datetime(2012, 11, 06, 20, 10 + i, 30,) for i in range(4)]
    dtv.value = (1, 0)

    # exception raised since no units given for timeseries during init
    with raises(TypeError):
        Wind(timeseries=dtv)

    # no units during set_timeseries
    with raises(TypeError):
        wind = Wind(timeseries=dtv, units='meter per second')
        wind.set_wind_data(dtv)

    # invalid units
    with raises(unit_conversion.InvalidUnitError):
        Wind(timeseries=dtv, units='met per second')


def test_read_file_init():
    """
    initialize from a long wind file
    """
    wm = Wind(filename=wind_file)
    print
    print '----------------------------------'
    print 'Units: ' + str(wm.units)
Пример #43
0
    name = "name_{0}".format(uuid1())
    class_ = b_class[0]
    inputs = b_class[1]
    obj = class_(*inputs, name=name)
    assert obj.name == name

    obj.name = obj.__class__.__name__
    assert obj.name == obj.__class__.__name__


t = datetime(2015, 1, 1, 12, 0)


@pytest.mark.parametrize(
    ("obj", "make_default_refs", "objvalid"),
    [(Wind(timeseries=[(t, (0, 1)), (t + timedelta(10),
                                     (0, 2))], units='m/s'), False, True),
     (Evaporation(), False, False), (NaturalDispersion(), False, False),
     (Evaporation(), True, True)])
def test_base_validate(obj, make_default_refs, objvalid):
    '''
    base validate checks wind/water/waves objects are not None. Check these
    primarily for weatherers.
    '''
    obj.make_default_refs = make_default_refs
    (out, isvalid) = obj.validate()
    print out
    print isvalid
    assert isvalid is objvalid
    assert len(out) > 0

Пример #44
0
def make_model(images_dir=os.path.join(base_dir, 'images')):

    # create the maps:

    print 'creating the maps'
    mapfile = get_datafile(os.path.join(base_dir, 'DelawareRiverMap.bna'))
    gnome_map = MapFromBNA(mapfile, refloat_halflife=1)  # hours

    renderer = Renderer(mapfile, images_dir, image_size=(800, 800),
                        projection_class=GeoProjection)

    print 'initializing the model'
    start_time = datetime(2012, 8, 20, 13, 0)

    # 15 minutes in seconds
    # Default to now, rounded to the nearest hour
    model = Model(time_step=900, start_time=start_time,
                  duration=timedelta(days=1),
                  map=gnome_map, uncertain=False)

    print 'adding outputters'
    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'script_delaware_bay.nc')
    scripting.remove_netcdf(netcdf_file)
    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=100000)

    print 'adding a wind mover:'

    # wind_file = get_datafile(os.path.join(base_dir, 'ConstantWind.WND'))
    # wind = Wind(filename=wind_file)

    series = np.zeros((2, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 270))
    series[1] = (start_time + timedelta(hours=25), (5, 270))

    wind = Wind(timeseries=series, units='m/s')

    # w_mover = WindMover(Wind(timeseries=series, units='knots'))
    w_mover = WindMover(wind)
    model.movers += w_mover

    print 'adding a cats shio mover:'

    curr_file = get_datafile(os.path.join(base_dir, 'FloodTides.cur'))
    tide_file = get_datafile(os.path.join(base_dir, 'FloodTidesShio.txt'))

    c_mover = CatsMover(curr_file, tide=Tide(tide_file))

    # this is the value in the file (default)
    c_mover.scale_refpoint = (-75.081667, 38.7995)
    c_mover.scale = True
    c_mover.scale_value = 1

    model.movers += c_mover

    # TODO: cannot add this till environment base class is created
    model.environment += c_mover.tide

    print 'adding a cats mover:'

    curr_file = get_datafile(os.path.join(base_dir, 'Offshore.cur'))
    c_mover = CatsMover(curr_file)

    # but do need to scale (based on river stage)

    c_mover.scale = True
    c_mover.scale_refpoint = (-74.7483333, 38.898333)
    c_mover.scale_value = .03
    model.movers += c_mover
    #
    # these are from windows they don't match Mac values...
    # pat1Angle 315;
    # pat1Speed 30; pat1SpeedUnits knots;
    # pat1ScaleToValue 0.314426
    #
    # pat2Angle 225;
    # pat2Speed 30; pat2SpeedUnits knots;
    # pat2ScaleToValue 0.032882
    # scaleBy WindStress

    print 'adding a component mover:'

    # if only using one current pattern
    # comp_mover = ComponentMover(curr_file1, None, wind)
    #
    # todo: following is not working when model is saved out - fix
    # comp_mover = ComponentMover(curr_file1, curr_file2,
    #                             Wind(timeseries=series, units='m/s'))
    # comp_mover = ComponentMover(curr_file1, curr_file2,
    #                             wind=Wind(filename=wind_file))

    curr_file1 = get_datafile(os.path.join(base_dir, 'NW30ktwinds.cur'))
    curr_file2 = get_datafile(os.path.join(base_dir, 'SW30ktwinds.cur'))
    comp_mover = ComponentMover(curr_file1, curr_file2, wind)

    comp_mover.scale_refpoint = (-75.263166, 39.1428333)

    comp_mover.pat1_angle = 315
    comp_mover.pat1_speed = 30
    comp_mover.pat1_speed_units = 1
    # comp_mover.pat1ScaleToValue = .314426
    comp_mover.pat1_scale_to_value = .502035

    comp_mover.pat2_angle = 225
    comp_mover.pat2_speed = 30
    comp_mover.pat2_speed_units = 1
    # comp_mover.pat2ScaleToValue = .032882
    comp_mover.pat2_scale_to_value = .021869

    model.movers += comp_mover

    print 'adding a spill'

    end_time = start_time + timedelta(hours=12)
    spill = point_line_release_spill(num_elements=1000,
                                     release_time=start_time,
                                     # end_release_time=end_time,
                                     start_position=(-75.262319,
                                                     39.142987, 0.0),
                                     )

    model.spills += spill

    return model
Пример #45
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2012, 9, 15, 12, 0)
    mapfile = get_datafile(os.path.join(base_dir, 'LongIslandSoundMap.BNA'))

    gnome_map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    # # the image output renderer
    # global renderer

    # one hour timestep
    model = Model(start_time=start_time,
                  duration=timedelta(hours=48),
                  time_step=3600,
                  map=gnome_map,
                  uncertain=True,
                  cache_enabled=True)

    print 'adding outputters'
    model.outputters += Renderer(mapfile, images_dir, image_size=(800, 600))

    netcdf_file = os.path.join(base_dir, 'script_long_island.nc')
    scripting.remove_netcdf(netcdf_file)

    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'adding a spill'
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-72.419992, 41.202120,
                                                     0.0),
                                     release_time=start_time)
    model.spills += spill

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=500000, uncertain_factor=2)

    print 'adding a wind mover:'
    series = np.zeros((5, ), dtype=datetime_value_2d)
    series[0] = (start_time, (10, 45))
    series[1] = (start_time + timedelta(hours=18), (10, 90))
    series[2] = (start_time + timedelta(hours=30), (10, 135))
    series[3] = (start_time + timedelta(hours=42), (10, 180))
    series[4] = (start_time + timedelta(hours=54), (10, 225))

    wind = Wind(timeseries=series, units='m/s')
    model.movers += WindMover(wind)

    print 'adding a cats mover:'
    curr_file = get_datafile(os.path.join(base_dir, 'LI_tidesWAC.CUR'))
    tide_file = get_datafile(os.path.join(base_dir, 'CLISShio.txt'))

    c_mover = CatsMover(curr_file, tide=Tide(tide_file))

    model.movers += c_mover
    model.environment += c_mover.tide

    print 'viewport is:', [
        o.viewport for o in model.outputters if isinstance(o, Renderer)
    ]

    return model
Пример #46
0
import datetime
import os

import numpy as np
import pytest

from gnome.movers import ComponentMover
from gnome.environment import Wind
from gnome.utilities import time_utils

from ..conftest import sample_sc_release, testdata

curr1_file = testdata['ComponentMover']['curr']
curr2_file = testdata['ComponentMover']['curr2']
wnd = Wind(filename=testdata['ComponentMover']['wind'])


def test_exceptions():
    """
    Test correct exceptions are raised
    """
    with pytest.raises(ValueError):
        'bad file'
        ComponentMover(os.path.join('./', 'NW30ktwinds.CURX'))

    with pytest.raises(TypeError):
        ComponentMover(curr1_file, wind=10)


num_le = 3
Пример #47
0
class TestWindMover:
    """
    gnome.WindMover() test
    """
    time_step = 15 * 60  # seconds
    model_time = datetime(2012, 8, 20, 13)  # yyyy/month/day/hr/min/sec
    sc = sample_sc_release(5, (3., 6., 0.), model_time)

    time_val = np.array((model_time, (2., 25.)),
                        dtype=datetime_value_2d).reshape(1)
    wind = Wind(timeseries=time_val, units='meter per second')
    wm = WindMover(wind)

    wm.prepare_for_model_run()

    def test_string_repr_no_errors(self):
        print
        print '======================'
        print 'repr(WindMover): '
        print repr(self.wm)
        print
        print 'str(WindMover): '
        print str(self.wm)
        assert True

    def test_get_move(self):
        """
        Test the get_move(...) results in WindMover match the expected delta
        """
        for ix in range(2):
            curr_time = sec_to_date(date_to_sec(self.model_time) +
                                    self.time_step * ix)
            self.wm.prepare_for_model_step(self.sc, self.time_step, curr_time)

            delta = self.wm.get_move(self.sc, self.time_step, curr_time)
            actual = self._expected_move()

            # the results should be independent of model time
            tol = 1e-8

            msg = ('{0} is not within a tolerance of '
                   '{1}'.format('WindMover.get_move()', tol))
            np.testing.assert_allclose(delta, actual, tol, tol, msg, 0)

            assert self.wm.active

            ts = date_to_sec(curr_time) - date_to_sec(self.model_time)
            print ('Time step [sec]:\t{0}'
                   'C++ delta-move:\n{1}'
                   'Expected delta-move:\n{2}'
                   ''.format(ts, delta, actual))

        self.wm.model_step_is_done()

    def test_get_move_exceptions(self):
        curr_time = sec_to_date(date_to_sec(self.model_time) + self.time_step)
        tmp_windages = self.sc._data_arrays['windages']
        del self.sc._data_arrays['windages']

        with raises(KeyError):
            self.wm.get_move(self.sc, self.time_step, curr_time)

        self.sc._data_arrays['windages'] = tmp_windages

    def test_update_wind_vel(self):
        self.time_val['value'] = (1., 120.)  # now given as (r, theta)
        self.wind.set_wind_data(self.time_val, units='meter per second')
        self.test_get_move()
        self.test_get_move_exceptions()

    def _expected_move(self):
        """
        Put the expected move logic in separate (fixture) if it gets used
        multiple times
        """
        uv = r_theta_to_uv_wind(self.time_val['value'])
        exp = np.zeros((self.sc.num_released, 3))
        exp[:, 0] = self.sc['windages'] * uv[0, 0] * self.time_step
        exp[:, 1] = self.sc['windages'] * uv[0, 1] * self.time_step

        xform = FlatEarthProjection.meters_to_lonlat(exp, self.sc['positions'])
        return xform
Пример #48
0
def make_model(images_dir=os.path.join(base_dir, 'images')):

    # create the maps:

    print 'creating the maps'
    mapfile = get_datafile(os.path.join(base_dir, 'SanJuanMap.bna'))
    gnome_map = MapFromBNA(mapfile, refloat_halflife=1,
                           raster_size=1024 * 1024)

    renderer = Renderer(mapfile,
                        images_dir,
                        image_size=(800, 800),
                        projection_class=GeoProjection)

    renderer.viewport = ((-66.24, 18.39), (-66.1, 18.55))

    print 'initializing the model'
    start_time = datetime(2014, 9, 3, 13, 0)

    # 15 minutes in seconds
    # Default to now, rounded to the nearest hour
    model = Model(time_step=900, start_time=start_time,
                  duration=timedelta(days=1),
                  map=gnome_map, uncertain=False)

    print 'adding outputters'
    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'script_san_juan.nc')
    scripting.remove_netcdf(netcdf_file)
    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=100000)

    print 'adding a wind mover:'

    series = np.zeros((2, ), dtype=datetime_value_2d)
    series[0] = (start_time, (0, 270))
    series[1] = (start_time + timedelta(hours=18), (0, 270))

    wind = Wind(timeseries=series, units='m/s')
    w_mover = WindMover(wind)
    wind.extrapolation_is_allowed=True
    model.movers += w_mover

    print 'adding a cats shio mover:'

    # need to add the scale_factor for the tide heights file
    curr_file = get_datafile(os.path.join(base_dir, 'EbbTides.cur'))
    tide_file = get_datafile(os.path.join(base_dir, 'EbbTidesShioHt.txt'))

    c_mover = CatsMover(curr_file, tide=Tide(tide_file, scale_factor=.15))

    # this is the value in the file (default)
    c_mover.scale_refpoint = (-66.116667, 18.458333)
    c_mover.scale = True
    c_mover.scale_value = 1.0
    # c_mover.tide.scale_factor = 0.15

    model.movers += c_mover

    print 'adding a cats mover:'

    curr_file = get_datafile(os.path.join(base_dir, 'Offshore.cur'))

    c_mover = CatsMover(curr_file)

    # this is the value in the file (default)
    # c_mover.scale_refpoint = (-66.082836, 18.469334)
    c_mover.scale_refpoint = (-66.084333333, 18.46966667)
    c_mover.scale = True
    c_mover.scale_value = 0.1

    model.movers += c_mover

    print 'adding a spill'

    end_time = start_time + timedelta(hours=12)
    spill = point_line_release_spill(num_elements=1000,
                                     release_time=start_time,
                                     start_position=(-66.16374,
                                                     18.468054, 0.0),
                                     # start_position=(-66.129099,
                                     #                 18.465332, 0.0),
                                     # end_release_time=end_time,
                                     )

    model.spills += spill

    return model
Пример #49
0
def test_default_init():
    wind = Wind()

    assert wind.timeseries == np.array(
        [(sec_to_date(zero_time()), [0.0, 0.0])], dtype=datetime_value_2d)
    assert wind.units == 'mps'
Пример #50
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2012, 9, 15, 12, 0)
    mapfile = get_datafile(os.path.join(base_dir, './LongIslandSoundMap.BNA'))

    gnome_map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    # # the image output renderer
    # global renderer

    # one hour timestep
    model = Model(start_time=start_time,
                  duration=timedelta(hours=48), time_step=3600,
                  map=gnome_map, uncertain=False, cache_enabled=False)

    print 'adding a spill'
    et = floating_weathering(substance='FUEL OIL NO.6')
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-72.419992,
                                                     41.202120, 0.0),
                                     release_time=start_time,
                                     amount=1000,
                                     units='kg',
                                     element_type=et)
    spill.amount_uncertainty_scale = 1.0
    model.spills += spill

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=500000, uncertain_factor=2)

    print 'adding a wind mover:'
    series = np.zeros((5, ), dtype=datetime_value_2d)
    series[0] = (start_time, (10, 45))
    series[1] = (start_time + timedelta(hours=18), (10, 90))
    series[2] = (start_time + timedelta(hours=30), (10, 135))
    series[3] = (start_time + timedelta(hours=42), (10, 180))
    series[4] = (start_time + timedelta(hours=54), (10, 225))

    wind = Wind(timeseries=series, units='m/s',
                speed_uncertainty_scale=0.5)
    model.movers += WindMover(wind)

    print 'adding a cats mover:'
    curr_file = get_datafile(os.path.join(base_dir, r"./LI_tidesWAC.CUR"))
    tide_file = get_datafile(os.path.join(base_dir, r"./CLISShio.txt"))

    c_mover = CatsMover(curr_file, tide=Tide(tide_file))
    model.movers += c_mover

    model.environment += c_mover.tide

    print 'adding Weatherers'
    water_env = Water(311.15)
    model.environment += water_env
    model.weatherers += [Evaporation(water_env, wind),
                         Dispersion(),
                         Burn(),
                         Skimmer()]

    print 'adding outputters'
    model.outputters += WeatheringOutput()

    return model
Пример #51
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2014, 6, 9, 0, 0)
    mapfile = get_datafile(os.path.join(base_dir, 'PassamaquoddyMap.bna'))

    gnome_map = MapFromBNA(mapfile, refloat_halflife=1)  # hours

    # # the image output renderer
    # global renderer

    # one hour timestep
    model = Model(start_time=start_time,
                  duration=timedelta(hours=24), time_step=360,
                  map=gnome_map, uncertain=False, cache_enabled=True)

    print 'adding outputters'
    renderer = Renderer(mapfile, images_dir, size=(800, 600),
                        # output_timestep=timedelta(hours=1),
                        draw_ontop='uncertain')
    renderer.viewport = ((-67.15, 45.), (-66.9, 45.2))

    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'script_passamaquoddy.nc')
    scripting.remove_netcdf(netcdf_file)

    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'adding a spill'
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-66.991344, 45.059316,
                                                     0.0),
                                     release_time=start_time)
    model.spills += spill

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=30000, uncertain_factor=2)

    print 'adding a wind mover:'
    series = np.zeros((5, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 90))
    series[1] = (start_time + timedelta(hours=18), (5, 180))
    series[2] = (start_time + timedelta(hours=30), (5, 135))
    series[3] = (start_time + timedelta(hours=42), (5, 180))
    series[4] = (start_time + timedelta(hours=54), (5, 225))

    wind = Wind(timeseries=series, units='m/s')
    model.movers += WindMover(wind)

    print 'adding a current mover:'
    curr_file = get_datafile(os.path.join(base_dir, 'PQBayCur.nc4'))
    topology_file = get_datafile(os.path.join(base_dir, 'PassamaquoddyTOP.dat')
                                 )
    tide_file = get_datafile(os.path.join(base_dir, 'EstesHead.txt'))

    cc_mover = CurrentCycleMover(curr_file, topology_file,
                                 tide=Tide(tide_file))

    model.movers += cc_mover
    model.environment += cc_mover.tide

    print 'viewport is:', [o.viewport
                           for o in model.outputters
                           if isinstance(o, Renderer)]

    return model
Пример #52
0
def make_model(uncertain=False, mode='gnome'):
    '''
    Create a model from the data in sample_data/boston_data
    It contains:
      - the GeoProjection
      - wind mover
      - random mover
      - cats shio mover
      - cats ossm mover
      - plain cats mover
    '''
    start_time = datetime(2013, 2, 13, 9, 0)
    model = Model(start_time=start_time,
                  duration=timedelta(days=2),
                  time_step=timedelta(minutes=30).total_seconds(),
                  uncertain=uncertain,
                  map=MapFromBNA(testdata['boston_data']['map'],
                                 refloat_halflife=1),
                  mode=mode)

    print 'adding a spill'
    start_position = (144.664166, 13.441944, 0.0)
    end_release_time = start_time + timedelta(hours=6)
    spill_amount = 1000.0
    spill_units = 'kg'
    model.spills += point_line_release_spill(num_elements=1000,
                                             start_position=start_position,
                                             release_time=start_time,
                                             end_release_time=end_release_time,
                                             amount=spill_amount,
                                             units=spill_units,
                                             substance=test_oil)
    spill = model.spills[-1]
    spill_volume = spill.get_mass() / spill.substance.density_at_temp()
    # need a scenario for SimpleMover
    # model.movers += SimpleMover(velocity=(1.0, -1.0, 0.0))

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=100000)

    print 'adding a wind mover:'

    series = np.zeros((2, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 180))
    series[1] = (start_time + timedelta(hours=18), (5, 180))

    w_mover = WindMover(Wind(timeseries=series, units='m/s'))

    model.movers += w_mover
    model.environment += w_mover.wind

    print 'adding a cats shio mover:'

    c_mover = CatsMover(testdata['boston_data']['cats_curr2'],
                        tide=Tide(testdata['boston_data']['cats_shio']))

    # c_mover.scale_refpoint should automatically get set from tide object
    c_mover.scale = True  # default value
    c_mover.scale_value = -1

    # tide object automatically gets added by model
    model.movers += c_mover

    print 'adding a cats ossm mover:'

    c_mover = CatsMover(testdata['boston_data']['cats_curr2'],
                        tide=Tide(testdata['boston_data']['cats_ossm']))

    c_mover.scale = True  # but do need to scale (based on river stage)
    c_mover.scale_refpoint = (-70.65, 42.58333, 0.0)
    c_mover.scale_value = 1.

    print 'adding a cats mover:'

    c_mover = CatsMover(testdata['boston_data']['cats_curr3'])
    c_mover.scale = True  # but do need to scale (based on river stage)
    c_mover.scale_refpoint = (-70.78333, 42.39333, 0.0)

    # the scale factor is 0 if user inputs no sewage outfall effects
    c_mover.scale_value = .04
    model.movers += c_mover

    # TODO: seg faulting for component mover - comment test for now
    # print "adding a component mover:"
    # comp_mover = ComponentMover(testdata['boston_data']['component_curr1'],
    #                             testdata['boston_data']['component_curr2'],
    #                             w_mover.wind)
    # TODO: callback did not work correctly below - fix!
    # comp_mover = ComponentMover(component_file1,
    #                             component_file2,
    #                             Wind(timeseries=series, units='m/s'))

    # comp_mover.ref_point = (-70.855, 42.275)
    # comp_mover.pat1_angle = 315
    # comp_mover.pat1_speed = 19.44
    # comp_mover.pat1_speed_units = 1
    # comp_mover.pat1ScaleToValue = .138855
    # comp_mover.pat2_angle = 225
    # comp_mover.pat2_speed = 19.44
    # comp_mover.pat2_speed_units = 1
    # comp_mover.pat2ScaleToValue = .05121

    # model.movers += comp_mover

    print 'adding a Weatherer'
    model.environment += Water(311.15)
    skim_start = start_time + timedelta(hours=3)
    model.weatherers += [
        Evaporation(),
        Skimmer(spill_amount * .5,
                spill_units,
                efficiency=.3,
                active_range=(skim_start, skim_start + timedelta(hours=2))),
        Burn(0.2 * spill_volume,
             1.0, (skim_start, InfDateTime('inf')),
             efficiency=0.9)
    ]

    model.outputters += \
        CurrentJsonOutput(model.find_by_attr('_ref_as', 'current_movers',
                                             model.movers, allitems=True))

    return model
Пример #53
0
def make_model(images_dir=os.path.join(base_dir, 'images')):

    # create the maps:

    print 'creating the maps'
    mapfile = get_datafile(os.path.join(base_dir, './MassBayMap.bna'))
    gnome_map = MapFromBNA(mapfile, refloat_halflife=1)  # hours

    renderer = Renderer(mapfile,
                        images_dir,
                        size=(800, 800),
                        projection_class=GeoProjection)

    print 'initializing the model'
    start_time = datetime(2013, 3, 12, 10, 0)

    # 15 minutes in seconds
    # Default to now, rounded to the nearest hour
    model = Model(time_step=900,
                  start_time=start_time,
                  duration=timedelta(days=1),
                  map=gnome_map,
                  uncertain=False)

    print 'adding outputters'
    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'script_boston.nc')
    scripting.remove_netcdf(netcdf_file)
    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=100000)

    print 'adding a wind mover:'

    series = np.zeros((2, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 180))
    series[1] = (start_time + timedelta(hours=18), (5, 180))

    w_mover = WindMover(Wind(timeseries=series, units='m/s'))
    model.movers += w_mover
    model.environment += w_mover.wind

    print 'adding a cats shio mover:'

    curr_file = get_datafile(os.path.join(base_dir, r"./EbbTides.cur"))
    tide_file = get_datafile(os.path.join(base_dir, r"./EbbTidesShio.txt"))

    c_mover = CatsMover(curr_file, tide=Tide(tide_file))

    # this is the value in the file (default)
    c_mover.scale_refpoint = (-70.8875, 42.321333)
    c_mover.scale = True
    c_mover.scale_value = -1

    model.movers += c_mover

    # TODO: cannot add this till environment base class is created
    model.environment += c_mover.tide

    print 'adding a cats ossm mover:'

    # ossm_file = get_datafile(os.path.join(base_dir,
    #                          r"./MerrimackMassCoastOSSM.txt"))
    curr_file = get_datafile(
        os.path.join(base_dir, r"./MerrimackMassCoast.cur"))
    tide_file = get_datafile(
        os.path.join(base_dir, r"./MerrimackMassCoastOSSM.txt"))
    c_mover = CatsMover(curr_file, tide=Tide(tide_file))

    # but do need to scale (based on river stage)

    c_mover.scale = True
    c_mover.scale_refpoint = (-70.65, 42.58333)
    c_mover.scale_value = 1.
    model.movers += c_mover
    model.environment += c_mover.tide

    print 'adding a cats mover:'

    curr_file = get_datafile(os.path.join(base_dir, r"MassBaySewage.cur"))
    c_mover = CatsMover(curr_file)

    # but do need to scale (based on river stage)

    c_mover.scale = True
    c_mover.scale_refpoint = (-70.78333, 42.39333)

    # the scale factor is 0 if user inputs no sewage outfall effects
    c_mover.scale_value = .04

    model.movers += c_mover

    # pat1Angle 315;
    # pat1Speed 19.44; pat1SpeedUnits knots;
    # pat1ScaleToValue 0.138855
    #
    # pat2Angle 225;
    # pat2Speed 19.44; pat2SpeedUnits knots;
    # pat2ScaleToValue 0.05121
    #
    # scaleBy WindStress

    print "adding a component mover:"
    component_file1 = get_datafile(os.path.join(base_dir, r"./WAC10msNW.cur"))
    component_file2 = get_datafile(os.path.join(base_dir, r"./WAC10msSW.cur"))
    comp_mover = ComponentMover(component_file1, component_file2, w_mover.wind)

    # todo: callback did not work correctly below - fix!
    # comp_mover = ComponentMover(component_file1,
    #                             component_file2,
    #                             Wind(timeseries=series, units='m/s'))

    comp_mover.scale_refpoint = (-70.855, 42.275)
    comp_mover.pat1_angle = 315
    comp_mover.pat1_speed = 19.44
    comp_mover.pat1_speed_units = 1
    comp_mover.pat1ScaleToValue = .138855
    comp_mover.pat2_angle = 225
    comp_mover.pat2_speed = 19.44
    comp_mover.pat2_speed_units = 1
    comp_mover.pat2ScaleToValue = .05121

    model.movers += comp_mover

    print 'adding a spill'

    end_time = start_time + timedelta(hours=12)
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-70.911432, 42.369142,
                                                     0.0),
                                     release_time=start_time,
                                     end_release_time=end_time)

    model.spills += spill

    return model