Esempio n. 1
0
def test_mover_api():
    '''
    Test the API methods for adding and removing movers to the model.
    '''
    start_time = datetime(2012, 1, 1, 0, 0)

    model = Model()
    model.duration = timedelta(hours=12)
    model.time_step = timedelta(hours=1)
    model.start_time = start_time

    mover_1 = SimpleMover(velocity=(1., -1., 0.))
    mover_2 = SimpleMover(velocity=(1., -1., 0.))
    mover_3 = SimpleMover(velocity=(1., -1., 0.))
    mover_4 = SimpleMover(velocity=(1., -1., 0.))

    # test our add object methods

    model.movers += mover_1
    model.movers += mover_2

    # test our get object methods

    assert model.movers[mover_1.id] == mover_1
    assert model.movers[mover_2.id] == mover_2
    with raises(KeyError):
        temp = model.movers['Invalid']
        print temp

    # test our iter and len object methods
    assert len(model.movers) == 2
    assert len([m for m in model.movers]) == 2
    for (m1, m2) in zip(model.movers, [mover_1, mover_2]):
        assert m1 == m2

    # test our add objectlist methods
    model.movers += [mover_3, mover_4]
    assert [m for m in model.movers] == [mover_1, mover_2, mover_3, mover_4]

    # test our remove object methods
    del model.movers[mover_3.id]
    assert [m for m in model.movers] == [mover_1, mover_2, mover_4]

    with raises(KeyError):
        # our key should also be gone after the delete
        temp = model.movers[mover_3.id]
        print temp

    # test our replace method
    model.movers[mover_2.id] = mover_3
    assert [m for m in model.movers] == [mover_1, mover_3, mover_4]
    assert model.movers[mover_3.id] == mover_3

    with raises(KeyError):
        # our key should also be gone after the delete
        temp = model.movers[mover_2.id]
        print temp
Esempio n. 2
0
def test_mover_api():
    '''
    Test the API methods for adding and removing movers to the model.
    '''
    start_time = datetime(2012, 1, 1, 0, 0)

    model = Model()
    model.duration = timedelta(hours=12)
    model.time_step = timedelta(hours=1)
    model.start_time = start_time

    mover_1 = SimpleMover(velocity=(1., -1., 0.))
    mover_2 = SimpleMover(velocity=(1., -1., 0.))
    mover_3 = SimpleMover(velocity=(1., -1., 0.))
    mover_4 = SimpleMover(velocity=(1., -1., 0.))

    # test our add object methods

    model.movers += mover_1
    model.movers += mover_2

    # test our get object methods

    assert model.movers[mover_1.id] == mover_1
    assert model.movers[mover_2.id] == mover_2
    with raises(KeyError):
        temp = model.movers['Invalid']
        print temp

    # test our iter and len object methods
    assert len(model.movers) == 2
    assert len([m for m in model.movers]) == 2
    for (m1, m2) in zip(model.movers, [mover_1, mover_2]):
        assert m1 == m2

    # test our add objectlist methods
    model.movers += [mover_3, mover_4]
    assert [m for m in model.movers] == [mover_1, mover_2, mover_3, mover_4]

    # test our remove object methods
    del model.movers[mover_3.id]
    assert [m for m in model.movers] == [mover_1, mover_2, mover_4]

    with raises(KeyError):
        # our key should also be gone after the delete
        temp = model.movers[mover_3.id]
        print temp

    # test our replace method
    model.movers[mover_2.id] = mover_3
    assert [m for m in model.movers] == [mover_1, mover_3, mover_4]
    assert model.movers[mover_3.id] == mover_3

    with raises(KeyError):
        # our key should also be gone after the delete
        temp = model.movers[mover_2.id]
        print temp
Esempio n. 3
0
def test_timestep():
    model = Model()

    ts = timedelta(hours=1)
    model.time_step = ts
    assert model.time_step == ts.total_seconds()

    dur = timedelta(days=3)
    model.duration = dur
    assert model._duration == dur
Esempio n. 4
0
def test_timestep():
    model = Model()

    ts = timedelta(hours=1)
    model.time_step = ts
    assert model.time_step == ts.total_seconds()

    dur = timedelta(days=3)
    model.duration = dur
    assert model._duration == dur
Esempio n. 5
0
def test_callback_add_mover():
    'Test callback after add mover'
    units = 'meter per second'

    model = Model()
    model.start_time = datetime(2012, 1, 1, 0, 0)
    model.duration = timedelta(hours=10)
    model.time_step = timedelta(hours=1)

    # start_loc = (1.0, 2.0, 0.0)  # random non-zero starting points

    # add Movers
    model.movers += SimpleMover(velocity=(1., -1., 0.))
    series = np.array((model.start_time, (10, 45)),
                      dtype=datetime_value_2d).reshape((1, ))
    model.movers += WindMover(Wind(timeseries=series, units=units))

    # this should create a Wind object
    new_wind = Wind(timeseries=series, units=units)
    model.environment += new_wind
    assert new_wind in model.environment
    assert len(model.environment) == 2

    tide_file = get_datafile(os.path.join(tides_dir, 'CLISShio.txt'))
    tide_ = Tide(filename=tide_file)

    d_file = get_datafile(os.path.join(lis_dir, 'tidesWAC.CUR'))
    model.movers += CatsMover(d_file, tide=tide_)

    model.movers += CatsMover(d_file)

    for mover in model.movers:
        assert mover.active_start == inf_datetime.InfDateTime('-inf')
        assert mover.active_stop == inf_datetime.InfDateTime('inf')

        if hasattr(mover, 'wind'):
            assert mover.wind in model.environment

        if hasattr(mover, 'tide'):
            if mover.tide is not None:
                assert mover.tide in model.environment

    # Add a mover with user defined active_start / active_stop values
    # - these should not be updated

    active_on = model.start_time + timedelta(hours=1)
    active_off = model.start_time + timedelta(hours=4)
    custom_mover = SimpleMover(velocity=(1., -1., 0.),
                               active_start=active_on,
                               active_stop=active_off)
    model.movers += custom_mover

    assert model.movers[custom_mover.id].active_start == active_on
    assert model.movers[custom_mover.id].active_stop == active_off
Esempio n. 6
0
def test_callback_add_mover():
    'Test callback after add mover'
    units = 'meter per second'

    model = Model()
    model.start_time = datetime(2012, 1, 1, 0, 0)
    model.duration = timedelta(hours=10)
    model.time_step = timedelta(hours=1)

    # start_loc = (1.0, 2.0, 0.0)  # random non-zero starting points

    # add Movers
    model.movers += SimpleMover(velocity=(1., -1., 0.))
    series = np.array((model.start_time, (10, 45)),
                      dtype=datetime_value_2d).reshape((1, ))
    model.movers += WindMover(Wind(timeseries=series, units=units))

    # this should create a Wind object
    new_wind = Wind(timeseries=series, units=units)
    model.environment += new_wind
    assert new_wind in model.environment
    assert len(model.environment) == 2

    tide_ = Tide(filename=testdata['CatsMover']['tide'])

    d_file = testdata['CatsMover']['curr']
    model.movers += CatsMover(d_file, tide=tide_)

    model.movers += CatsMover(d_file)

    for mover in model.movers:
        assert mover.active_start == inf_datetime.InfDateTime('-inf')
        assert mover.active_stop == inf_datetime.InfDateTime('inf')

        if hasattr(mover, 'wind'):
            assert mover.wind in model.environment

        if hasattr(mover, 'tide'):
            if mover.tide is not None:
                assert mover.tide in model.environment

    # Add a mover with user defined active_start / active_stop values
    # - these should not be updated

    active_on = model.start_time + timedelta(hours=1)
    active_off = model.start_time + timedelta(hours=4)
    custom_mover = SimpleMover(velocity=(1., -1., 0.),
                               active_start=active_on,
                               active_stop=active_off)
    model.movers += custom_mover

    assert model.movers[custom_mover.id].active_start == active_on
    assert model.movers[custom_mover.id].active_stop == active_off
Esempio n. 7
0
def test_callback_add_mover():
    """ Test callback after add mover """

    units = 'meter per second'

    model = Model()
    model.time_step = timedelta(hours=1)
    model.duration = timedelta(hours=10)
    model.start_time = datetime(2012, 1, 1, 0, 0)

    # start_loc = (1.0, 2.0, 0.0)  # random non-zero starting points

    # add Movers

    model.movers += SimpleMover(velocity=(1., -1., 0.))
    series = np.array((model.start_time, (10, 45)),
                      dtype=datetime_value_2d).reshape((1, ))
    model.movers += WindMover(Wind(timeseries=series, units=units))

    tide_file = get_datafile(os.path.join(os.path.dirname(__file__),
                             r"sample_data", 'tides', 'CLISShio.txt'))
    tide_ = Tide(filename=tide_file)

    d_file = get_datafile(os.path.join(datadir,
                          r"long_island_sound/tidesWAC.CUR"))
    model.movers += CatsMover(d_file, tide=tide_)

    model.movers += CatsMover(d_file)

    for mover in model.movers:
        assert mover.active_start == inf_datetime.InfDateTime('-inf')
        assert mover.active_stop == inf_datetime.InfDateTime('inf')

        if isinstance(mover, WindMover):
            assert mover.wind.id in model.environment

        if isinstance(mover, CatsMover):
            if mover.tide is not None:
                assert mover.tide.id in model.environment

    # Add a mover with user defined active_start / active_stop values
    # - these should not be updated

    active_on = model.start_time + timedelta(hours=1)
    active_off = model.start_time + timedelta(hours=4)
    custom_mover = SimpleMover(velocity=(1., -1., 0.),
                               active_start=active_on,
                               active_stop=active_off)
    model.movers += custom_mover

    assert model.movers[custom_mover.id].active_start == active_on
    assert model.movers[custom_mover.id].active_stop == active_off
Esempio n. 8
0
def test_callback_add_mover_midrun():
    'Test callback after add mover called midway through the run'
    model = Model()
    model.start_time = datetime(2012, 1, 1, 0, 0)
    model.duration = timedelta(hours=10)
    model.time_step = timedelta(hours=1)

    # start_loc = (1.0, 2.0, 0.0)  # random non-zero starting points

    # model = setup_simple_model()

    for i in range(2):
        model.step()

    assert model.current_time_step > -1

    # now add another mover and make sure model rewinds
    model.movers += SimpleMover(velocity=(2., -2., 0.))
    assert model.current_time_step == -1
Esempio n. 9
0
def test_callback_add_mover_midrun():
    'Test callback after add mover called midway through the run'
    model = Model()
    model.start_time = datetime(2012, 1, 1, 0, 0)
    model.duration = timedelta(hours=10)
    model.time_step = timedelta(hours=1)

    # start_loc = (1.0, 2.0, 0.0)  # random non-zero starting points

    # model = setup_simple_model()

    for i in range(2):
        model.step()

    assert model.current_time_step > -1

    # now add another mover and make sure model rewinds
    model.movers += SimpleMover(velocity=(2., -2., 0.))
    assert model.current_time_step == -1
Esempio n. 10
0
def test_linearity_of_wind_movers(wind_persist):
    '''
    WindMover is defined as a linear operation - defining a model
    with a single WindMover with 15 knot wind is equivalent to defining
    a model with three WindMovers each with 5 knot wind. Or any number of
    WindMover's such that the sum of their magnitude is 15knots and the
    direction of wind is the same for both cases.

    Below is an example which defines two models and runs them.
    In model2, there are multiple winds defined so the windage parameter
    is reset 3 times for one timestep.
    Since windage range and persistence do not change, this only has the effect
    of doing the same computation 3 times. However, the results are the same.

    The mean and variance of the positions for both models are close.
    As windage_persist is decreased, the values become closer.
    Setting windage_persist=0 gives the large difference between them.
    '''
    units = 'meter per second'
    start_time = datetime(2012, 1, 1, 0, 0)
    series1 = np.array((start_time, (15, 45)),
                       dtype=datetime_value_2d).reshape((1, ))
    series2 = np.array((start_time, (6, 45)),
                       dtype=datetime_value_2d).reshape((1, ))
    series3 = np.array((start_time, (3, 45)),
                       dtype=datetime_value_2d).reshape((1, ))

    num_LEs = 1000
    element_type = floating(windage_persist=wind_persist)

    model1 = Model(name='model1')
    model1.duration = timedelta(hours=1)
    model1.time_step = timedelta(hours=1)
    model1.start_time = start_time
    model1.spills += point_line_release_spill(num_elements=num_LEs,
                                              start_position=(1., 2., 0.),
                                              release_time=start_time,
                                              element_type=element_type)

    model1.movers += WindMover(Wind(timeseries=series1, units=units),
                               make_default_refs=False)

    model2 = Model(name='model2')
    model2.duration = timedelta(hours=10)
    model2.time_step = timedelta(hours=1)
    model2.start_time = start_time
    model2.spills += point_line_release_spill(num_elements=num_LEs,
                                              start_position=(1., 2., 0.),
                                              release_time=start_time,
                                              element_type=element_type)

    # todo: CHECK RANDOM SEED
    # model2.movers += WindMover(Wind(timeseries=series1, units=units))

    model2.movers += WindMover(Wind(timeseries=series2, units=units))
    model2.movers += WindMover(Wind(timeseries=series2, units=units))
    model2.movers += WindMover(Wind(timeseries=series3, units=units))
    model2.set_make_default_refs(False)

    while True:
        try:
            model1.next()
        except StopIteration as ex:
            # print message
            print ex.message
            break

    while True:
        try:
            model2.next()
        except StopIteration as ex:
            # print message
            print ex.message
            break

    # mean and variance at the end should be fairly close
    # look at the mean of the position vector. Assume m1 is truth
    # and m2 is approximation - look at the absolute error between
    # mean position of m2 in the 2 norm.
    # rel_mean_error =(np.linalg.norm(np.mean(model2.spills.LE('positions'), 0)
    #                  - np.mean(model1.spills.LE('positions'), 0)))
    # assert rel_mean_error <= 0.5

    # Similarly look at absolute error in variance of position of m2
    # in the 2 norm.

    rel_var_error = np.linalg.norm(np.var(model2.spills.LE('positions'), 0) -
                                   np.var(model1.spills.LE('positions'), 0))
    assert rel_var_error <= 0.0015
Esempio n. 11
0
def test_all_movers(start_time, release_delay, duration):
    '''
    Tests that all the movers at least can be run

    Add new ones as they come along!
    '''

    model = Model()
    model.time_step = timedelta(hours=1)
    model.duration = timedelta(seconds=model.time_step * duration)
    model.start_time = start_time
    start_loc = (1., 2., 0.)  # random non-zero starting points

    # a spill - release after 5 timesteps

    release_time = (start_time +
                    timedelta(seconds=model.time_step * release_delay))
    model.spills += point_line_release_spill(num_elements=10,
                                             start_position=start_loc,
                                             release_time=release_time)

    # the land-water map
    model.map = gnome.map.GnomeMap()  # the simplest of maps

    # simple mover
    model.movers += SimpleMover(velocity=(1., -1., 0.))
    assert len(model.movers) == 1

    # random mover
    model.movers += RandomMover(diffusion_coef=100000)
    assert len(model.movers) == 2

    # wind mover
    series = np.array((start_time, (10, 45)),
                      dtype=datetime_value_2d).reshape((1, ))
    model.movers += WindMover(Wind(timeseries=series,
                              units='meter per second'))
    assert len(model.movers) == 3

    # CATS mover
    model.movers += CatsMover(testdata['CatsMover']['curr'])
    assert len(model.movers) == 4

    # run the model all the way...
    num_steps_output = 0
    for step in model:
        num_steps_output += 1
        print 'running step:', step

    # test release happens correctly for all cases
    if release_delay < duration:
        # at least one get_move has been called after release
        assert np.all(model.spills.LE('positions')[:, :2] != start_loc[:2])
    elif release_delay == duration:
        # particles are released after last step so no motion,
        # only initial _state
        assert np.all(model.spills.LE('positions') == start_loc)
    else:
        # release_delay > duration so nothing released though model ran
        assert len(model.spills.LE('positions')) == 0

    # there is the zeroth step, too.
    calculated_steps = (model.duration.total_seconds() / model.time_step) + 1
    assert num_steps_output == calculated_steps
Esempio n. 12
0
def test_linearity_of_wind_movers(wind_persist):
    '''
    WindMover is defined as a linear operation - defining a model
    with a single WindMover with 15 knot wind is equivalent to defining
    a model with three WindMovers each with 5 knot wind. Or any number of
    WindMover's such that the sum of their magnitude is 15knots and the
    direction of wind is the same for both cases.

    Below is an example which defines two models and runs them.
    In model2, there are multiple winds defined so the windage parameter
    is reset 3 times for one timestep.
    Since windage range and persistence do not change, this only has the effect
    of doing the same computation 3 times. However, the results are the same.

    The mean and variance of the positions for both models are close.
    As windage_persist is decreased, the values become closer.
    Setting windage_persist=0 gives the large difference between them.
    '''
    units = 'meter per second'
    start_time = datetime(2012, 1, 1, 0, 0)
    series1 = np.array((start_time, (15, 45)),
                       dtype=datetime_value_2d).reshape((1, ))
    series2 = np.array((start_time, (6, 45)), dtype=datetime_value_2d).reshape(
        (1, ))
    series3 = np.array((start_time, (3, 45)), dtype=datetime_value_2d).reshape(
        (1, ))

    num_LEs = 1000
    element_type = floating(windage_persist=wind_persist)

    model1 = Model(name='model1')
    model1.duration = timedelta(hours=1)
    model1.time_step = timedelta(hours=1)
    model1.start_time = start_time
    model1.spills += point_line_release_spill(num_elements=num_LEs,
                                              start_position=(1., 2., 0.),
                                              release_time=start_time,
                                              element_type=element_type)

    model1.movers += WindMover(Wind(timeseries=series1, units=units),
                               make_default_refs=False)

    model2 = Model(name='model2')
    model2.duration = timedelta(hours=10)
    model2.time_step = timedelta(hours=1)
    model2.start_time = start_time
    model2.spills += point_line_release_spill(num_elements=num_LEs,
                                              start_position=(1., 2., 0.),
                                              release_time=start_time,
                                              element_type=element_type)

    # todo: CHECK RANDOM SEED
    # model2.movers += WindMover(Wind(timeseries=series1, units=units))

    model2.movers += WindMover(Wind(timeseries=series2, units=units))
    model2.movers += WindMover(Wind(timeseries=series2, units=units))
    model2.movers += WindMover(Wind(timeseries=series3, units=units))
    model2.set_make_default_refs(False)

    while True:
        try:
            model1.next()
        except StopIteration as ex:
            # print message
            print ex.message
            break

    while True:
        try:
            model2.next()
        except StopIteration as ex:
            # print message
            print ex.message
            break

    # mean and variance at the end should be fairly close
    # look at the mean of the position vector. Assume m1 is truth
    # and m2 is approximation - look at the absolute error between
    # mean position of m2 in the 2 norm.
    # rel_mean_error =(np.linalg.norm(np.mean(model2.spills.LE('positions'), 0)
    #                  - np.mean(model1.spills.LE('positions'), 0)))
    # assert rel_mean_error <= 0.5

    # Similarly look at absolute error in variance of position of m2
    # in the 2 norm.

    rel_var_error = np.linalg.norm(
        np.var(model2.spills.LE('positions'), 0) -
        np.var(model1.spills.LE('positions'), 0))
    assert rel_var_error <= 0.0015
Esempio n. 13
0
def test_all_movers(start_time, release_delay, duration):
    '''
    Tests that all the movers at least can be run

    Add new ones as they come along!
    '''

    model = Model()
    model.time_step = timedelta(hours=1)
    model.duration = timedelta(seconds=model.time_step * duration)
    model.start_time = start_time
    start_loc = (1., 2., 0.)  # random non-zero starting points

    # a spill - release after 5 timesteps

    release_time = (start_time +
                    timedelta(seconds=model.time_step * release_delay))
    model.spills += point_line_release_spill(num_elements=10,
                                             start_position=start_loc,
                                             release_time=release_time)

    # the land-water map
    model.map = gnome.map.GnomeMap()  # the simplest of maps

    # simple mover
    model.movers += SimpleMover(velocity=(1., -1., 0.))
    assert len(model.movers) == 1

    # random mover
    model.movers += RandomMover(diffusion_coef=100000)
    assert len(model.movers) == 2

    # wind mover
    series = np.array((start_time, (10, 45)), dtype=datetime_value_2d).reshape(
        (1, ))
    model.movers += WindMover(Wind(timeseries=series,
                                   units='meter per second'))
    assert len(model.movers) == 3

    # CATS mover
    model.movers += CatsMover(testdata['CatsMover']['curr'])
    assert len(model.movers) == 4

    # run the model all the way...
    num_steps_output = 0
    for step in model:
        num_steps_output += 1
        print 'running step:', step

    # test release happens correctly for all cases
    if release_delay < duration:
        # at least one get_move has been called after release
        assert np.all(model.spills.LE('positions')[:, :2] != start_loc[:2])
    elif release_delay == duration:
        # particles are released after last step so no motion,
        # only initial _state
        assert np.all(model.spills.LE('positions') == start_loc)
    else:
        # release_delay > duration so nothing released though model ran
        assert len(model.spills.LE('positions')) == 0

    # there is the zeroth step, too.
    calculated_steps = (model.duration.total_seconds() / model.time_step) + 1
    assert num_steps_output == calculated_steps