Exemple #1
0
 def test_num_per_timestep_release_elements(self):
     'release elements in the context of a spill container'
     # todo: need a test for a line release where rate is given - to check
     # positions are being initialized correctly
     end_time = self.rel_time + timedelta(hours=1)
     release = ContinuousRelease(self.rel_time,
                                 self.pos,
                                 num_per_timestep=100,
                                 initial_elements=1000,
                                 end_release_time=end_time)
     s = Spill(release)
     sc = SpillContainer()
     sc.spills += s
     sc.prepare_for_model_run()
     for ix in range(5):
         time = self.rel_time + timedelta(seconds=900 * ix)
         num_les = sc.release_elements(900, time)
         if time <= s.get('end_release_time'):
             if ix == 0:
                 assert num_les == 1100
             else:
                 assert num_les == 100
             assert sc.num_released == 100 + ix * 100 + 1000
         else:
             assert num_les == 0
Exemple #2
0
    def test_spills_with_and_notwith_substance(self):
        '''
        datastructure only adds substance/spills if substance is not None
        deleting spill resets datastructure.

        - the spills in _substances_spills 'is' the same as the spills
          in sc.spills - same object
        '''
        sc = SpillContainer()
        sc.spills += [
            Spill(Release(datetime.now(), 10),
                  element_type=floating(substance=None),
                  name='spill0'),
            Spill(Release(datetime.now(), 10),
                  element_type=floating(substance=test_oil),
                  name='spill1')
        ]

        assert len(sc.get_substances()) == 2
        sc.prepare_for_model_run()
        all_spills = list(chain.from_iterable(sc._substances_spills.spills))
        assert len(all_spills) == len(sc.spills)
        for spill in all_spills:
            assert sc.spills[spill.id] is spill

        del sc.spills[-1]
        assert len(sc.get_substances()) == 1
        assert len(sc.iterspillsbysubstance()) == 1
Exemple #3
0
def test_initailize_InitMassFromVolume():
    data_arrays = mock_append_data_arrays(mass_array, num_elems)
    fcn = InitMassFromVolume()
    spill = Spill()
    spill.volume = num_elems / (spill.oil_props.get_density('kg/m^3') * 1000)
    fcn.initialize(num_elems, spill, data_arrays)

    assert_dataarray_shape_size(mass_array, data_arrays, num_elems)
    assert np.all(1. == data_arrays['mass'])
Exemple #4
0
 def test_serialization_deserialization(self):
     """
     tests serializatin/deserialization of the Spill object
     """
     spill = point_line_release_spill(num_elements=self.num_elements,
             start_position=self.start_position,
             release_time=self.release_time)
     serial = spill.serialize('create')
     new_dict = Spill.deserialize(serial)    # classmethod
     new_spill = Spill.new_from_dict(new_dict)   # classmethod
     assert spill == new_spill
Exemple #5
0
def test_init_exceptions():

    with raises(TypeError):
        Spill(Release(datetime.now()), amount=10)

    with raises(ValueError):
        Spill(Release(release_time=datetime.now()),
              element_type=floating(windage_range=(-1, 0)))

    with raises(ValueError):
        Spill(Release(release_time=datetime.now()),
              element_type=floating(windage_persist=0))
Exemple #6
0
def test_initailize_InitMassFromVolume():
    data_arrays = mock_append_data_arrays(mass_array, num_elems)
    substance = OilProps('oil_conservative')

    spill = Spill(Release(10))
    spill.volume = num_elems / (substance.get_density('kg/m^3') * 1000)

    fcn = InitMassFromVolume()
    fcn.initialize(num_elems, spill, data_arrays, substance)

    assert_dataarray_shape_size(mass_array, data_arrays, num_elems)
    assert np.all(1. == data_arrays['mass'])
Exemple #7
0
def test_initailize_InitMassFromTotalMass():
    data_arrays = mock_append_data_arrays(mass_array, num_elems)
    substance = OilProps('oil_conservative')

    spill = Spill(Release())
    spill.release.num_elements = 10
    spill.mass = num_elems

    fcn = InitMassFromTotalMass()
    fcn.initialize(num_elems, spill, data_arrays, substance)

    assert_dataarray_shape_size(mass_array, data_arrays, num_elems)
    assert np.all(1. == data_arrays['mass'])
def test_initailize_InitMassFromTotalMass():
    data_arrays = mock_append_data_arrays(mass_array, num_elems)
    substance = OilProps("oil_conservative")

    spill = Spill(Release(datetime.now()))
    spill.release.num_elements = 10
    spill.set_mass(num_elems, units="g")

    fcn = InitMassFromTotalMass()
    fcn.initialize(num_elems, spill, data_arrays, substance)

    assert_dataarray_shape_size(mass_array, data_arrays, num_elems)
    assert np.all(1.0 == data_arrays["mass"])
Exemple #9
0
def test_total_mass():
    '''
    test total_mass attribute
    '''
    sc = SpillContainer()
    sc.spills += [
        Spill(Release(datetime.now(), 10), amount=100, units='kg'),
        Spill(Release(datetime.now(), 1000), amount=1234, units='kg'),
        Spill(Release(datetime.now(), 100))
    ]
    assert sc.total_mass == 100 + 1234

    sc.spills.clear()
    sc.spills += [Spill(Release(datetime.now(), 10))]
    assert sc.total_mass is None
Exemple #10
0
def model(sample_model, output_dir):
    model = sample_model['model']
    rel_start_pos = sample_model['release_start_pos']
    rel_end_pos = sample_model['release_end_pos']

    model.cache_enabled = True
    model.uncertain = True

    N = 10  # a line of ten points
    line_pos = np.zeros((N, 3), dtype=np.float64)
    line_pos[:, 0] = np.linspace(rel_start_pos[0], rel_end_pos[0], N)
    line_pos[:, 1] = np.linspace(rel_start_pos[1], rel_end_pos[1], N)

    # print start_points
    model.environment += td

    model.spills += point_line_release_spill(1,
                                             start_position=rel_start_pos,
                                             release_time=model.start_time,
                                             end_position=rel_end_pos)

    release = SpatialRelease(start_position=line_pos,
                             release_time=model.start_time)

    model.spills += Spill(release)

    model.movers += c_cats

    model.outputters += CurrentJsonOutput([c_cats])

    model.rewind()

    return model
def model(sample_model, output_dir):
    model = sample_model['model']
    rel_start_pos = sample_model['release_start_pos']
    rel_end_pos = sample_model['release_end_pos']

    model.start_time = datetime(2015, 5, 14, 0)
    model.cache_enabled = True
    model.uncertain = True

    N = 10  # a line of ten points
    line_pos = np.zeros((N, 3), dtype=np.float64)
    line_pos[:, 0] = np.linspace(rel_start_pos[0], rel_end_pos[0], N)
    line_pos[:, 1] = np.linspace(rel_start_pos[1], rel_end_pos[1], N)

    start_pos = (-164.01696, 72.921024, 0)
    model.spills += point_line_release_spill(1,
                                             start_position=start_pos,
                                             release_time=model.start_time,
                                             end_position=start_pos)

    release = SpatialRelease(start_position=line_pos,
                             release_time=model.start_time)

    model.spills += Spill(release)

    model.movers += c_ice_mover

    model.outputters += IceGeoJsonOutput([c_ice_mover])

    model.rewind()

    return model
Exemple #12
0
    def test_validate_model_spills_time_mismatch_warning(self):
        '''
        test warning messages output for no spills and model start time
        mismatch with release time
        '''
        model = Model(start_time=self.start_time)
        (msgs, isvalid) = model.check_inputs()

        print model.environment
        print msgs, isvalid
        assert len(msgs) == 1 and isvalid
        assert ('{0} contains no spills'.format(model.name) in msgs[0])

        model.spills += Spill(Release(self.start_time + timedelta(hours=1), 1))
        (msgs, isvalid) = model.check_inputs()

        assert len(msgs) == 1 and isvalid
        assert ('{} has release time after model start time'.format(
            model.spills[0].name) in msgs[0])

        model.spills[0].release_time = self.start_time - timedelta(hours=1)
        (msgs, isvalid) = model.check_inputs()

        assert len(msgs) == 1 and not isvalid
        assert ('{} has release time before model start time'.format(
            model.spills[0].name) in msgs[0])
Exemple #13
0
def test_simple_run_with_image_output_uncertainty(tmpdir):
    '''
    Pretty much all this tests is that the model will run and output images
    '''
    images_dir = tmpdir.mkdir('Test_images2').strpath

    if os.path.isdir(images_dir):
        shutil.rmtree(images_dir)
    os.mkdir(images_dir)

    start_time = datetime(2012, 9, 15, 12, 0)

    # the land-water map
    gmap = gnome.map.MapFromBNA(testdata['MapFromBNA']['testmap'],
                                refloat_halflife=6)  # hours
    renderer = gnome.outputters.Renderer(testdata['MapFromBNA']['testmap'],
                                         images_dir, size=(400, 300))

    model = Model(start_time=start_time,
                  time_step=timedelta(minutes=15), duration=timedelta(hours=1),
                  map=gmap,
                  uncertain=True, cache_enabled=False,
                  )

    model.outputters += renderer
    a_mover = SimpleMover(velocity=(1., -1., 0.))
    model.movers += a_mover

    N = 10  # a line of ten points
    start_points = np.zeros((N, 3), dtype=np.float64)
    start_points[:, 0] = np.linspace(-127.1, -126.5, N)
    start_points[:, 1] = np.linspace(47.93, 48.1, N)
    # print start_points

    release = SpatialRelease(start_position=start_points,
                             release_time=start_time)

    model.spills += Spill(release)

    # model.add_spill(spill)

    model.start_time = release.release_time

    # image_info = model.next_image()

    model.uncertain = True
    num_steps_output = 0
    while True:
        try:
            image_info = model.step()
            num_steps_output += 1
            print image_info
        except StopIteration:
            print 'Done with the model run'
            break

    # there is the zeroth step, too.
    calculated_steps = (model.duration.total_seconds() / model.time_step) + 1
    assert num_steps_output == calculated_steps
Exemple #14
0
 def test_spills_same_substance_init(self):
     sc = SpillContainer()
     et = floating(substance=test_oil)
     sp_add = [
         point_line_release_spill(3, (1, 1, 1),
                                  datetime.now(),
                                  element_type=et),
         Spill(Release(datetime.now(), 10),
               amount=100,
               units='kg',
               element_type=floating(substance=test_oil)),
         Spill(Release(datetime.now(), 10),
               element_type=floating(substance=et.substance))
     ]
     sc.spills += sp_add
     assert len(sc.get_substances()) == 1
     sc.prepare_for_model_run()
     assert all([sp_add == spills for spills in sc.iterspillsbysubstance()])
 def test_serialization_deserialization(self, json_):
     """
     tests serializatin/deserialization of the Spill object
     """
     spill = point_line_release_spill(num_elements=self.num_elements,
                                      start_position=self.start_position,
                                      release_time=self.release_time)
     dict_ = Spill.deserialize(spill.serialize(json_))
     if json_ == 'save':
         new_spill = Spill.new_from_dict(dict_)
         assert spill == new_spill
     else:
         # for webapi, make new objects from nested objects before creating
         # new element_type
         dict_['element_type'] = spill.element_type
         dict_['release'] = spill.release
         new_spill = Spill.new_from_dict(dict_)
         assert True
def test_SpillContainer_add_array_types():
    '''
    Test an array_type is dynamically added/subtracted from SpillContainer if
    it is contained in Initailizer's array_types property.

    For example:

        Add 'rise_vel' initializer, InitRiseVelFromDropletSizeFromDist()) is
        added to Spill's element_type object. Now, the array_types for this
        initailizer are 'rise_vel' and 'droplet_diameter'. Only if a
        RiseVelocityMover is added to the model in which case the Model
        provides 'rise_vel' as an array_type to the SpillContainer to append
        it to its own list, then the SpillContainer will also add the
        'droplet_diameter' array_type that is additionally set by the
        Initializer but is not explicitly required by the Mover.
    '''
    sc = SpillContainer()
    s = Spill(Release(datetime(2014, 1, 1, 12, 0), 0))
    s.set_initializer(
        InitRiseVelFromDropletSizeFromDist(distribution=UniformDistribution()))
    sc.spills += s
    assert 'rise_vel' not in sc.array_types
    assert 'droplet_diameter' not in sc.array_types

    # Now say you added RiseVelocityMover and the Model collects ArrayTypes
    # from all movers and passes it into SpillContainer's prepare_for_model_run
    #
    sc.prepare_for_model_run(array_types={'rise_vel'})
    assert 'rise_vel' in sc.array_types
    assert 'droplet_diameter' in sc.array_types

    # calling prepare_for_model_run without different array_types keeps the
    # previously added 'rise_vel' array_types - always rewind if you want to
    # clear out the state and reset array_types to original data
    sc.prepare_for_model_run()
    assert 'rise_vel' in sc.array_types
    assert 'droplet_diameter' in sc.array_types

    # Now let's rewind array_types and these extra properties should disappear
    # they are only added after the prepare_for_model_run step
    sc.rewind()
    sc.prepare_for_model_run()
    assert 'rise_vel' not in sc.array_types
    assert 'droplet_diameter' not in sc.array_types
Exemple #17
0
    def test_spills_different_substance_init(self):
        sc = SpillContainer()
        splls0 = [
            point_line_release_spill(
                3, (1, 1, 1),
                datetime.now(),
                element_type=floating(substance=test_oil)),
            Spill(Release(datetime.now(), 10),
                  element_type=floating(substance=test_oil)),
        ]
        sc.spills += splls0
        splls1 = [
            Spill(Release(datetime.now(), 10),
                  element_type=floating(substance='oil_crude'))
        ]
        sc.spills += splls1

        assert (len(sc.get_substances()) == 2
                and len(sc.iterspillsbysubstance()) == 2)
    def test_set_newparticle_positions(self):
        'define two spatial releases and check positions are set correctly'
        sp2 = Spill(SpatialRelease(self.sp.release.release_time,
                                  ((0, 0, 0), (0, 0, 0))))
        (data_arrays, num) = release_elements(self.sp,
                                            self.sp.release.release_time, 600)
        assert (self.sp.get('num_released') == self.sp.release.num_elements and
                self.sp.release.num_elements == num)

        (data_arrays, num2) = release_elements(sp2,
                                              sp2.release.release_time,
                                              600,
                                              data_arrays)
        assert (sp2.get('num_released') == sp2.release.num_elements and
                len(data_arrays['positions']) == num2 + num)
        assert (np.all(data_arrays['positions'][:num, :] ==
                self.sp.get('start_position')))
        assert (np.all(data_arrays['positions'][num:, :] ==
                sp2.get('start_position')))
def test_SpillContainer_add_array_types():
    '''
    Test an array_type is dynamically added/subtracted from SpillContainer if
    it is contained in Initailizer's array_types property.

    For example:

        Add 'rise_vel' initializer, InitRiseVelFromDropletSizeFromDist()) is
        added to Spill's element_type object. Now, the array_types for this
        initailizer are 'rise_vel' and 'droplet_diameter'. Only if a
        RiseVelocityMover is added to the model in which case the Model
        provides 'rise_vel' as an array_type to the SpillContainer to append
        it to its own list, then the SpillContainer will also add the
        'droplet_diameter' array_type that is additionally set by the
        Initializer but is not explicitly required by the Mover.
    '''
    sc = SpillContainer()
    s = Spill(Release(datetime(2014, 1, 1, 12, 0), 0))
    s.set_initializer(InitRiseVelFromDropletSizeFromDist(distribution = UniformDistribution()))
    sc.spills += s
    assert 'rise_vel' not in sc.array_types
    assert 'droplet_diameter' not in sc.array_types

    # Now say you added RiseVelocityMover and the Model collects ArrayTypes
    # from all movers and passes it into SpillContainer's prepare_for_model_run
    #
    sc.prepare_for_model_run(array_types={'rise_vel'})
    assert 'rise_vel' in sc.array_types
    assert 'droplet_diameter' in sc.array_types

    # calling prepare_for_model_run without different array_types keeps the
    # previously added 'rise_vel' array_types - always rewind if you want to
    # clear out the state and reset array_types to original data
    sc.prepare_for_model_run()
    assert 'rise_vel' in sc.array_types
    assert 'droplet_diameter' in sc.array_types

    # Now let's rewind array_types and these extra properties should disappear
    # they are only added after the prepare_for_model_run step
    sc.rewind()
    sc.prepare_for_model_run()
    assert 'rise_vel' not in sc.array_types
    assert 'droplet_diameter' not in sc.array_types
Exemple #20
0
 def test_serialization_deserialization(self, json_, amount, units):
     """
     tests serializatin/deserialization of the Spill object
     """
     spill = point_line_release_spill(num_elements=self.num_elements,
                                      start_position=self.start_position,
                                      release_time=self.release_time,
                                      amount=amount,
                                      units=units)
     new_spill = Spill.deserialize(spill.serialize())
     assert new_spill == spill
Exemple #21
0
def test_amount_mass_vol(amount, units):
    '''
    ensure mass is being returned correctly when 'amount' is initialized wtih
    'mass' or 'volume'
    '''
    spill = Spill(Release(datetime.now()),
                  amount=amount,
                  units=units,
                  substance=test_oil)
    assert spill.amount == amount
    assert spill.units == units

    if units in Spill.valid_vol_units:
        exp_mass = (spill.get('substance').get_density() *
                    uc.convert('Volume', units, 'm^3', spill.amount))
    else:
        exp_mass = uc.convert('Mass', units, 'kg', spill.amount)
    assert spill.get_mass() == exp_mass
    exp_mass_g = exp_mass * 1000
    assert spill.get_mass('g') == exp_mass_g
Exemple #22
0
    def test_set_newparticle_positions(self):
        'define two spatial releases and check positions are set correctly'
        sp2 = Spill(
            SpatialRelease(self.sp.release.release_time,
                           ((0, 0, 0), (0, 0, 0))))
        (data_arrays, num) = release_elements(self.sp,
                                              self.sp.release.release_time,
                                              600)
        assert (self.sp.get('num_released') == self.sp.release.num_elements
                and self.sp.release.num_elements == num)

        (data_arrays, num2) = release_elements(sp2, sp2.release.release_time,
                                               600, data_arrays)
        assert (sp2.get('num_released') == sp2.release.num_elements
                and len(data_arrays['positions']) == num2 + num)
        assert (np.all(
            data_arrays['positions'][:num, :] == self.sp.get('start_position'))
                )
        assert (np.all(
            data_arrays['positions'][num:, :] == sp2.get('start_position')))
Exemple #23
0
 def test_serialization_deserialization(self, json_, amount, units):
     """
     tests serializatin/deserialization of the Spill object
     """
     spill = point_line_release_spill(num_elements=self.num_elements,
                                      start_position=self.start_position,
                                      release_time=self.release_time,
                                      amount=amount,
                                      units=units)
     dict_ = Spill.deserialize(spill.serialize(json_))
     if json_ == 'save':
         new_spill = Spill.new_from_dict(dict_)
         assert spill == new_spill
     else:
         # for webapi, make new objects from nested objects before creating
         # new element_type
         dict_['element_type'] = spill.element_type
         dict_['release'] = spill.release
         new_spill = Spill.new_from_dict(dict_)
         assert True
Exemple #24
0
 def test_serialization_deserialization(self, json_, amount, units):
     """
     tests serializatin/deserialization of the Spill object
     """
     spill = point_line_release_spill(num_elements=self.num_elements,
                                      start_position=self.start_position,
                                      release_time=self.release_time,
                                      amount=amount,
                                      units=units)
     new_spill = Spill.deserialize(spill.serialize())
     assert new_spill == spill
Exemple #25
0
def test_amount_mass_vol(amount, units):
    '''
    ensure mass is being returned correctly when 'amount' is initialized wtih
    'mass' or 'volume'
    '''
    spill = Spill(Release(datetime.now()),
                  amount=amount,
                  units=units,
                  substance=test_oil)
    assert spill.amount == amount
    assert spill.units == units

    if units in Spill.valid_vol_units:
        exp_mass = (spill.get('substance').get_density() *
                    uc.convert('Volume', units, 'm^3', spill.amount))
    else:
        exp_mass = uc.convert('Mass', units, 'kg', spill.amount)
    assert spill.get_mass() == exp_mass
    exp_mass_g = exp_mass * 1000
    assert spill.get_mass('g') == exp_mass_g
Exemple #26
0
 def test_num_per_timestep_release_elements(self):
     'release elements in the context of a spill container'
     # todo: need a test for a line release where rate is given - to check
     # positions are being initialized correctly
     end_time = self.rel_time + timedelta(hours=1)
     release = PointLineRelease(self.rel_time,
                                self.pos,
                                num_per_timestep=100,
                                end_release_time=end_time)
     s = Spill(release)
     sc = SpillContainer()
     sc.spills += s
     sc.prepare_for_model_run()
     for ix in range(5):
         time = self.rel_time + timedelta(seconds=900 * ix)
         num_les = sc.release_elements(900, time)
         if time <= s.get('end_release_time'):
             assert num_les == 100
             assert sc.num_released == 100 + ix * 100
         else:
             assert num_les == 0
Exemple #27
0
    def test_full_run(self):
        'just check that all data arrays work correctly'
        s = Spill(InitElemsFromFile(testdata['nc']['nc_output']))
        model = Model(start_time=s.get('release_time'),
                      time_step=self.time_step.total_seconds(),
                      duration=timedelta(days=2))
        model.spills += s
        model.movers += RandomMover()

        # setup model run
        for step in model:
            if step['step_num'] == 0:
                continue
            for sc in model.spills.items():
                for key in sc.data_arrays.keys():
                    # following keys will not change with run
                    if key in ('status_codes', 'mass', 'id', 'spill_num',
                               'last_water_positions'):  # all water map
                        assert np.all(sc[key] == s.release._init_data[key])
                    else:
                        assert np.any(sc[key] != s.release._init_data[key])
Exemple #28
0
    def make_model_incomplete_waves(self):
        '''
        create a model with waves objects with no referenced wind, water.
        Include Spill so we don't get warnings for it
        '''
        model = Model(start_time=self.start_time)
        model.spills += Spill(Release(self.start_time, 1))

        waves = Waves()
        model.environment += waves

        return (model, waves)
Exemple #29
0
def test_copy():
    """
    TODO: how should this work
    """
    sp1 = Spill(Release(release_time=datetime.now().replace(microsecond=0)))
    sp2 = copy.copy(sp1)
    assert sp1 is not sp2
    assert sp1.id != sp2.id

    # try deleting the copy, and see if any errors result
    del sp1
    del sp2
Exemple #30
0
    def test_no_substance(self):
        '''
        no substance means run trajectory without an OilProps object/without
        weathering is one reason to do this
        '''
        sc = SpillContainer()
        sc.spills += [
            Spill(Release(datetime.now(), 10),
                  element_type=floating(substance=None),
                  name='spill0'),
            Spill(Release(datetime.now(), 10),
                  element_type=floating(substance=None),
                  name='spill1')
        ]
        assert len(sc.itersubstancedata('mass')) == 0
        assert len(sc.get_substances()) == 1

        # iterspillsbysubstance() iterates through all the spills associated
        # with each substance including the spills where substance is None
        assert len(sc.iterspillsbysubstance()) == 1
        assert len(sc.iterspillsbysubstance()) == 1
Exemple #31
0
def test_deepcopy():
    """
    tests that a deepcopy results in a copy so objects are not the same
    todo: how should this work?
    """
    sp1 = Spill(Release(release_time=datetime.now().replace(microsecond=0)))
    sp2 = copy.deepcopy(sp1)
    assert sp1 is not sp2
    assert sp1.id != sp2.id

    # try deleting the copy, and see if any errors result
    del sp2
    del sp1
Exemple #32
0
def test_var_attr_spill_num(output_filename):
    '''
    call prepare_for_model_run and ensure the spill_num attributes are written
    correctly. Just a simple test that creates two models and adds a spill to
    each. It then runs both models and checks that the correct spill_name
    exists in 'spills_map' attribute for NetCDF output variable 'spill_num'
    '''
    def _make_run_model(spill, nc_name):
        'internal function'
        release_time = spill.release.release_time

        m = Model(start_time=release_time)
        m.outputters += NetCDFOutput(nc_name)
        m.spills += spill

        _run_model(m)
        return m

    def _del_nc_file(nc_name):
        try:
            os.remove(nc_name)
        except:
            pass

    here = os.path.dirname(__file__)
    spills = []
    model = []
    nc_name = []

    for ix in (0, 1):
        spills.append(
            Spill(Release(datetime.now()), name='m{0}_spill'.format(ix)))
        nc_name.append(os.path.join(here, 'temp_m{0}.nc'.format(ix)))

        _del_nc_file(nc_name[ix])
        _make_run_model(spills[ix], nc_name[ix])

    # open and check the correct spill_name exists in each netcdf file
    for ix, f_ in enumerate(nc_name):
        with nc.Dataset(f_) as data:
            assert (spills[ix].name in data.variables['spill_num'].spills_map)

            if ix == 0:
                assert (spills[1].name
                        not in data.variables['spill_num'].spills_map)

            if ix == 1:
                assert (spills[0].name
                        not in data.variables['spill_num'].spills_map)

            _del_nc_file(nc_name[ix])
Exemple #33
0
    def test_full_run(self):
        'just check that all data arrays work correctly'
        s = Spill(InitElemsFromFile(testdata['nc']['nc_output']))
        model = Model(start_time=s.get('release_time'),
                      time_step=self.time_step.total_seconds(),
                      duration=timedelta(days=2))
        model.spills += s
        model.movers += RandomMover()

        # setup model run
        for step in model:
            if step['step_num'] == 0:
                continue
            for sc in model.spills.items():
                for key in sc.data_arrays.keys():
                    # following keys will not change with run
                    if key in ('status_codes',
                               'mass',
                               'id',
                               'spill_num',
                               'last_water_positions'):  # all water map
                        assert np.all(sc[key] == s.release._init_data[key])
                    else:
                        assert np.any(sc[key] != s.release._init_data[key])
Exemple #34
0
def test_amount_mass_vol(amount, units):
    '''
    ensure mass is being returned correctly when 'amount' is initialized wtih
    'mass' or 'volume'
    '''
    water = Water()
    spill = Spill(Release(datetime.now()),
                  amount=amount,
                  units=units,
                  substance=test_oil,
                  water=water)
    assert spill.amount == amount
    assert spill.units == units

    if units in Spill.valid_vol_units:
        # use 15C (288.15K) for mass<=>volume conversion
        exp_mass = (spill.substance.density_at_temp(288.15) *
                    uc.convert('Volume', units, 'm^3', spill.amount))
    else:
        exp_mass = uc.convert('Mass', units, 'kg', spill.amount)
    assert spill.get_mass() == exp_mass

    exp_mass_g = exp_mass * 1000
    assert spill.get_mass('g') == exp_mass_g
Exemple #35
0
def test_amount_mass_vol(amount, units):
    '''
    ensure mass is being returned correctly when 'amount' is initialized wtih
    'mass' or 'volume'
    '''
    water = Water()
    spill = Spill(Release(datetime.now()),
                  amount=amount,
                  units=units,
                  substance=test_oil,
                  water=water)
    assert spill.amount == amount
    assert spill.units == units

    if units in Spill.valid_vol_units:
        # use 15C (288.15K) for mass<=>volume conversion
        exp_mass = (spill.substance.density_at_temp(288.15) *
                    uc.convert('Volume', units, 'm^3', spill.amount))
    else:
        exp_mass = uc.convert('Mass', units, 'kg', spill.amount)
    assert spill.get_mass() == exp_mass

    exp_mass_g = exp_mass * 1000
    assert spill.get_mass('g') == exp_mass_g
Exemple #36
0
 def test_release_elements(self, at):
     'release elements in the context of a spill container'
     s = Spill(InitElemsFromFile(testdata['nc']['nc_output']))
     sc = SpillContainer()
     sc.spills += s
     sc.prepare_for_model_run(array_types=at)
     num_les = sc.release_elements(self.time_step, self.nc_start_time)
     assert sc.num_released == s.release.num_elements
     assert num_les == s.release.num_elements
     for array, val in s.release._init_data.iteritems():
         if array in sc:
             assert np.all(val == sc[array])
             assert val is not sc[array]
         else:
             assert array not in at
Exemple #37
0
def sample_vertical_plume_spill():
    '''
    creates an example VerticalPlumeSource object
    '''
    from gnome.spill import VerticalPlumeRelease, Spill
    from gnome.utilities.plume import get_plume_data

    release_time = datetime.now()
    vps = VerticalPlumeRelease(num_elements=200,
                               start_position=(28, -78, 0.),
                               release_time=release_time,
                               end_release_time=release_time + timedelta(hours=24),
                               plume_data=get_plume_data())

    vps.plume_gen.time_step_delta = timedelta(hours=1).total_seconds()
    return Spill(vps)
Exemple #38
0
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'])
Exemple #39
0
def test_init(element_type, amount):
    '''
    Test various initializations
    '''
    spill = Spill(Release(release_time=datetime.now()),
                  element_type=element_type,
                  amount=amount,
                  units='kg')

    if element_type is None:
        assert np.all(spill.windage_range == (0.01, 0.04))
        assert spill.windage_persist == 900
        # no need to test this in spill -- it shouldn't know about initializers
    #     assert len(spill.initializers) == 1  # add windages
    # else:
    #     assert len(spill.initializers) == 0

    assert spill.release_duration == 0
Exemple #40
0
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)
Exemple #41
0
def test_init(element_type, amount):
    '''
    Test various initializtions
    '''
    spill = Spill(Release(release_time=datetime.now()),
                  element_type=element_type,
                  amount=amount,
                  units='kg')

    if element_type is None:
        assert np.all(spill.get('windage_range') == (0.01, 0.04))
        assert (spill.get('windage_persist') == 900)
        assert len(spill.get('initializers')) == 1  # add windages
    else:
        assert len(spill.get('initializers')) == 0

    assert spill.name == 'Spill'
    assert spill.get('release_duration') == 0
Exemple #42
0
    def test_set_newparticle_positions(self):
        'define two spatial releases and check positions are set correctly'
        sp2 = Spill(
            SpatialRelease(self.sp.release.release_time,
                           ((0, 0, 0), (0, 0, 0))))
        (data_arrays, num) = release_elements(self.sp,
                                              self.sp.release.release_time,
                                              600)
        # fixme -- should we be checking for the release inside the Spill?
        assert (self.sp.num_released == self.sp.release.num_elements
                and self.sp.release.num_elements == num)

        (data_arrays, num2) = release_elements(sp2, sp2.release.release_time,
                                               600, data_arrays)
        assert (sp2.num_released == sp2.release.num_elements
                and len(data_arrays['positions']) == num2 + num)
        assert (np.all(
            data_arrays['positions'][:num, :] == self.sp.start_position))
        assert (np.all(
            data_arrays['positions'][num:, :] == sp2.start_position))
Exemple #43
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
Exemple #44
0
def test_init(element_type, amount):
    '''
    Test various initializtions
    '''
    spill = Spill(Release(release_time=datetime.now()),
                  element_type=element_type,
                  amount=amount,
                  units='kg'
                  )

    if element_type is None:
        assert np.all(spill.get('windage_range') == (0.01, 0.04))
        assert (spill.get('windage_persist') == 900)
        assert len(spill.get('initializers')) == 1  # add windages
    else:
        assert len(spill.get('initializers')) == 0

    assert spill.name == 'Spill'
    assert spill.get('release_duration') == 0