コード例 #1
0
    def sample_sc_intrinsic(self, num_elements, rel_time, add_at=None):
        '''
        initialize Sample SC and WeatheringData object
        objects are constructed and prepare_for_model_run() is invoked on all
        '''
        wd = WeatheringData(Water())
        end_time = rel_time + timedelta(hours=1)
        spills = [
            point_line_release_spill(num_elements, (0, 0, 0),
                                     rel_time,
                                     end_release_time=end_time,
                                     amount=100,
                                     units='kg',
                                     substance=test_oil)
        ]
        sc = SpillContainer()
        sc.spills += spills
        at = wd.array_types
        if add_at is not None:
            at.update(add_at)
        sc.prepare_for_model_run(at)

        # test initialization as well
        wd.prepare_for_model_run(sc)
        for val in sc.mass_balance.values():
            assert val == 0.0

        # test initialization as well
        return (sc, wd)
コード例 #2
0
def test_ne_spill_container():
    """ test two spill containers are not equal """

    (sp1, sp2) = get_eq_spills()

    # just move one data array a bit

    sp2.release.start_position = sp2.release.start_position + (1e-8, 1e-8, 0)

    sc1 = SpillContainer()
    sc2 = SpillContainer()

    sc1.spills.add(sp1)
    sc2.spills.add(sp2)

    sc1.prepare_for_model_run(windage_at)
    sc1.release_elements(360, sp1.release.release_time)

    sc2.prepare_for_model_run(windage_at)
    sc2.release_elements(360, sp2.release.release_time)

    assert sc1 != sc2
    assert sc2 != sc1
    assert not (sc1 == sc2)
    assert not (sc2 == sc1)
コード例 #3
0
ファイル: test_release.py プロジェクト: nilodna/PyGnome
 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.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
コード例 #4
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.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
コード例 #5
0
    def sample_sc_intrinsic(self, num_elements, rel_time, add_at=None):
        '''
        initialize Sample SC and WeatheringData object
        objects are constructed and prepare_for_model_run() is invoked on all
        '''
        wd = WeatheringData(Water())
        end_time = rel_time + timedelta(hours=1)
        spills = [point_line_release_spill(num_elements,
                                           (0, 0, 0),
                                           rel_time,
                                           end_release_time=end_time,
                                           amount=100,
                                           units='kg',
                                           substance=test_oil)]
        sc = SpillContainer()
        sc.spills += spills
        at = wd.array_types
        if add_at is not None:
            at.update(add_at)
        sc.prepare_for_model_run(at)

        # test initialization as well
        wd.prepare_for_model_run(sc)
        for val in sc.mass_balance.values():
            assert val == 0.0

        # test initialization as well
        return (sc, wd)
コード例 #6
0
ファイル: conftest.py プロジェクト: NOAA-ORR-ERD/PyGnome
def sample_sc_release(num_elements=10,
                      start_pos=(0.0, 0.0, 0.0),
                      release_time=datetime(2000, 1, 1, 1),
                      uncertain=False,
                      time_step=360,
                      spill=None,
                      element_type=None,
                      current_time=None,
                      arr_types=None,
                      windage_range=None,
                      units='g',
                      amount_per_element=1.0):
    """
    Initialize a Spill of type 'spill', add it to a SpillContainer.
    Invoke release_elements on SpillContainer, then return the spill container
    object

    If 'spill' is None, define a Spill object with a PointLineRelease type
    of release
    """
    if current_time is None:
        current_time = release_time

    if spill is None:
        spill = gnome.spill.point_line_release_spill(num_elements,
                                                     start_pos,
                                                     release_time)
    spill.units = units
    spill.amount = amount_per_element * num_elements

    if element_type is not None:
        spill.element_type = element_type

    if current_time is None:
        current_time = spill.release_time

    # fixme -- maybe this is not the place for the default arrays?
    always = {'windages', 'windage_range', 'windage_persist'}
    if arr_types is None:
        # default always has standard windage parameters required by wind_mover
        arr_types = always
    else:
        arr_types.update(always)

    if windage_range is not None:
        spill.windage_range = windage_range

    sc = SpillContainer(uncertain)
    sc.spills.add(spill)

    # used for testing so just assume there is a Windage array
    sc.prepare_for_model_run(arr_types)
    sc.release_elements(time_step, current_time)

    return sc
コード例 #7
0
def test_rewind():
    """
    Test rewinding spill containter rewinds the spills.
    - SpillContainer should reset its the data_arrays to empty and num_released
      to 0
    - it should reset num_released = 0 for all spills and reset
      start_time_invalid flag to True. Basically all spills are rewound
    """
    num_elements = 100
    release_time = datetime(2012, 1, 1, 12)
    release_time2 = release_time + timedelta(hours=24)
    start_position = (23.0, -78.5, 0.0)
    sc = SpillContainer()

    spills = [
        point_line_release_spill(num_elements, start_position, release_time),
        point_line_release_spill(num_elements, start_position, release_time2)
    ]
    sc.spills.add(spills)

    sc.prepare_for_model_run(windage_at)

    for time in [release_time, release_time2]:
        sc.release_elements(3600, time)

    assert sc.num_released == num_elements * len(spills)
    for spill in spills:
        assert spill.get('num_released') == spill.release.num_elements

    sc.rewind()
    assert sc.num_released == 0
    assert_dataarray_shape_size(sc)
    for spill in spills:
        assert spill.get('num_released') == 0
        assert spill.release.start_time_invalid is None
コード例 #8
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
コード例 #9
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
コード例 #10
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()])
コード例 #11
0
def test_multiple_spills(uncertain):
    """
    SpillContainer initializes correct number of elements in data_arrays.
    Use Multiple spills with different release times.
    Also, deleting a spill shouldn't change data_arrays for particles
    already released.
    """
    sc = SpillContainer(uncertain)
    spills = [point_line_release_spill(num_elements, start_position, release_time),
              point_line_release_spill(num_elements,
                                       start_position,
                                       release_time + timedelta(hours=1),
                                       end_position,
                                       end_release_time)
              ]

    sc.spills.add(spills)

    assert len(sc.spills) == 2

    for spill in spills:
        assert sc.spills[spill.id] == spill

    assert sc.uncertain == uncertain

    time_step = 3600
    num_steps = ((spills[-1].release.end_release_time -
                  spills[-1].release.release_time).seconds / time_step + 1)

    sc.prepare_for_model_run(windage_at)

    for step in range(num_steps):
        current_time = release_time + timedelta(seconds=time_step * step)
        sc.release_elements(time_step, current_time)

    total_elements = sum(s.num_elements for s in spills)
    assert sc.num_released == total_elements
    assert_dataarray_shape_size(sc)

    sc.spills.remove(spills[0].id)

    with raises(KeyError):
        # it shouldn't be there anymore.
        assert sc.spills[spills[0].id] is None

    # however, the data arrays of released particles should be unchanged
    assert sc.num_released == spill.release.num_elements * len(spills)
    assert_dataarray_shape_size(sc)
コード例 #12
0
def sample_sc_no_uncertainty():
    """
    Sample spill container with 2 point_line_release_spill spills:

    - release_time for 2nd spill is 1 hour delayed
    - 2nd spill takes 4 hours to release and end_position is different so it
      is a time varying, line release
    - both have a volume of 10 and default element_type

    Nothing is released. This module simply defines a SpillContainer, adds
    the two spills and returns it. It is used in test_spill_container.py
    and test_elements.py so defined as a fixture.
    """
    sc = SpillContainer()
    # Sample data for creating spill
    num_elements = 100
    start_position = (23.0, -78.5, 0.0)
    release_time = datetime(2012, 1, 1, 12)
    end_position = (24.0, -79.5, 1.0)
    end_release_time = datetime(2012, 1, 1, 12) + timedelta(hours=4)

    spills = [gnome.spill.point_line_release_spill(num_elements,
                                                   start_position,
                                                   release_time,
                                                   amount=10, units='l'),
              gnome.spill.point_line_release_spill(num_elements,
                                                   start_position,
                                                   release_time + timedelta(hours=1),
                                                   end_position,
                                                   end_release_time),
              ]
    sc.spills.add(spills)
    return sc
コード例 #13
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)
コード例 #14
0
ファイル: test_cleanup.py プロジェクト: shhw2019/noaa_pyGnome
    def mk_test_objs(cls, water=None):
        '''
        create SpillContainer and test WeatheringData object test objects so
        we can run Skimmer, Burn like a model without using a full on Model

        NOTE: Use this function to define class level objects. Other methods
            in this class expect sc, and weatherers to be class level objects
        '''
        # spreading does not need to be initialized correctly for these tests,
        # but since we are mocking the model, let's do it correctly
        if water is None:
            water = Water()

        # keep this order
        weatherers = [WeatheringData(water), FayGravityViscous(water)]
        weatherers.sort(key=weatherer_sort)
        sc = SpillContainer()
        print "******************"
        print "Adding a spill to spill container"
        sc.spills += point_line_release_spill(10, (0, 0, 0),
                                              rel_time,
                                              substance=test_oil,
                                              amount=amount,
                                              units='kg',
                                              water=water)
        return (sc, weatherers)
コード例 #15
0
def test_eq_spill_container():
    """ test if two spill containers are equal """

    (sp1, sp2) = get_eq_spills()
    sc1 = SpillContainer()
    sc2 = SpillContainer()

    sc1.spills.add(sp1)
    sc2.spills.add(sp2)

    sc1.prepare_for_model_run(windage_at)
    sc1.release_elements(360, sp1.release_time)

    sc2.prepare_for_model_run(windage_at)
    sc2.release_elements(360, sp2.release_time)

    assert sc1 == sc2
コード例 #16
0
def test_one_simple_spill(spill):
    """ checks data_arrays correctly populated for a single spill in
    SpillContainer """
    sc = SpillContainer()
    sc.spills.add(spill)
    time_step = 3600

    sc.prepare_for_model_run(windage_at)
    num_steps = ((spill.end_release_time -
                  spill.release_time).seconds / time_step + 1)
    for step in range(num_steps):
        current_time = spill.release_time + timedelta(seconds=time_step * step)
        sc.release_elements(time_step, current_time)

    assert sc.num_released == spill.num_elements

    assert_sc_single_spill(sc)
コード例 #17
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
コード例 #18
0
def test_rewind():
    """
    Test rewinding spill containter rewinds the spills.
    - SpillContainer should reset its the data_arrays to empty and num_released
      to 0
    - it should reset num_released = 0 for all spills and reset
      start_time_invalid flag to True. Basically all spills are rewound
    """
    num_elements = 100
    release_time = datetime(2012, 1, 1, 12)
    release_time2 = release_time + timedelta(hours=24)
    start_position = (23.0, -78.5, 0.0)
    sc = SpillContainer()

    spills = [point_line_release_spill(num_elements, start_position,
                                       release_time),
              point_line_release_spill(num_elements, start_position,
                                       release_time2)]
    sc.spills.add(spills)

    sc.prepare_for_model_run(windage_at)

    for time in [release_time, release_time2]:
        sc.release_elements(3600, time)

    assert sc.num_released == num_elements * len(spills)
    for spill in spills:
        assert spill.num_released == spill.release.num_elements

    sc.rewind()
    assert sc.num_released == 0
    assert_dataarray_shape_size(sc)
    for spill in spills:
        assert spill.num_released == 0
        assert spill.release.start_time_invalid is None
コード例 #19
0
def test_ordered_collection_api():
    release_time = datetime(2012, 1, 1, 12)
    start_position = (23.0, -78.5, 0.0)
    num_elements = 100

    sc = SpillContainer()
    sc.spills += point_line_release_spill(num_elements, start_position,
                                          release_time)
    assert len(sc.spills) == 1
コード例 #20
0
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
コード例 #21
0
ファイル: conftest.py プロジェクト: kthyng/GNOME2
def sample_sc_release(
    num_elements=10,
    start_pos=(0.0, 0.0, 0.0),
    release_time=datetime(2000, 1, 1, 1),
    uncertain=False,
    time_step=360,
    spill=None,
    element_type=None,
    current_time=None,
    arr_types=None,
):
    """
    Initialize a Spill of type 'spill', add it to a SpillContainer.
    Invoke release_elements on SpillContainer, then return the spill container
    object

    If 'spill' is None, define a Spill object with a PointLineRelease type
    of release
    """
    if current_time is None:
        current_time = release_time

    if spill is None:
        spill = gnome.spill.point_line_release_spill(num_elements, start_pos, release_time)
    spill.mass = num_elements

    if element_type is not None:
        spill.element_type = element_type

    if current_time is None:
        current_time = spill.release_time

    if arr_types is None:
        # default always has standard windage parameters required by wind_mover
        arr_types = {"windages": windages, "windage_range": windage_range, "windage_persist": windage_persist}

    sc = SpillContainer(uncertain)
    sc.spills.add(spill)

    # used for testing so just assume there is a Windage array
    sc.prepare_for_model_run(arr_types)
    sc.release_elements(time_step, current_time)
    return sc
コード例 #22
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)
コード例 #23
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
        assert len(sc.get_substances(complete=False)) == 0

        # iterspillsbysubstance() iterates through all the spills associated
        # with each substance including the spills where substance is None
        assert len(sc.iterspillsbysubstance()) == 2
コード例 #24
0
def test_array_types_reset():
    """
    check the array_types are reset on rewind() only
    """
    sc = SpillContainer()
    sc.prepare_for_model_run(array_types=windage_at)

    assert 'windages' in sc.array_types

    sc.rewind()
    assert 'windages' not in sc.array_types
    assert sc.array_types == sc_default_array_types

    sc.prepare_for_model_run(array_types=windage_at)
    assert 'windages' in sc.array_types

    # now if we invoke prepare_for_model_run without giving it any array_types
    # it should not reset the dict to default
    sc.prepare_for_model_run()  # set to any datetime
    assert 'windages' in sc.array_types
コード例 #25
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
コード例 #26
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
コード例 #27
0
 def test_num_per_timestep_release_elements(self):
     """release elements in the context of a Spill object"""
     # fixme: A "proper" unit test shouldn't need to put it in a spill
     # 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.end_release_time:
             assert num_les == 100
             assert sc.num_released == 100 + ix * 100
         else:
             assert num_les == 0
コード例 #28
0
def test_model_step_is_done():
    """
    tests that correct elements are released when their status_codes is toggled
    to basic_types.oil_status.to_be_removed
    """
    release_time = datetime(2012, 1, 1, 12)
    start_time2 = datetime(2012, 1, 2, 12)
    start_position = (23.0, -78.5, 0.0)
    num_elements = 10
    sc = SpillContainer()
    sp1 = point_line_release_spill(num_elements, start_position, release_time)

    sp2 = point_line_release_spill(num_elements, start_position, start_time2)

    sc.spills += [sp1, sp2]

    sc.prepare_for_model_run(windage_at)

    sc.release_elements(100, release_time)
    sc.release_elements(100, start_time2)

    (sc['status_codes'])[5:8] = oil_status.to_be_removed
    (sc['status_codes'])[14:17] = oil_status.to_be_removed
    sc['status_codes'][19] = oil_status.to_be_removed

    # also make corresponding positions 0 as a way to test

    sc['positions'][5:8, :] = (0, 0, 0)
    sc['positions'][14:17, :] = (0, 0, 0)
    sc['positions'][19, :] = (0, 0, 0)
    sc.model_step_is_done()

    assert sc.num_released == 2 * num_elements - 7

    assert np.all(sc['status_codes'] != oil_status.to_be_removed)
    assert np.all(sc['positions'] == start_position)

    assert np.count_nonzero(sc['spill_num'] == 0) == num_elements - 3
    assert np.count_nonzero(sc['spill_num'] == 1) == num_elements - 4
コード例 #29
0
ファイル: test_release.py プロジェクト: nilodna/PyGnome
 def test_num_per_timestep_release_elements(self):
     """release elements in the context of a Spill object"""
     # fixme: A "proper" unit test shouldn't need to put it in a spill
     # 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.end_release_time:
             assert num_les == 100
             assert sc.num_released == 100 + ix * 100
         else:
             assert num_les == 0
コード例 #30
0
ファイル: test_spill.py プロジェクト: shhw2019/noaa_pyGnome
 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_elements=1000,
                                end_release_time=end_time)
     sp = Spill(release=release)
     sc = SpillContainer()
     sc.spills += sp
     sc.prepare_for_model_run(array_types=sp.array_types)
     sp.prepare_for_model_run(900)
     for ix in range(5):
         model_time = self.rel_time + timedelta(seconds=900 * ix)
         to_rel = sp.release_elements(sc, model_time, 900)
         if model_time < sp.end_release_time:
             assert to_rel == 250
             assert len(sc['spill_num']) == min((ix + 1) * 250, 1000)
         else:
             assert to_rel == 0
コード例 #31
0
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
コード例 #32
0
def test_model_step_is_done():
    """
    tests that correct elements are released when their status_codes is toggled
    to basic_types.oil_status.to_be_removed
    """

    release_time = datetime(2012, 1, 1, 12)
    start_time2 = datetime(2012, 1, 2, 12)
    start_position = (23.0, -78.5, 0.0)
    num_elements = 10
    sc = SpillContainer()
    spill = PointLineSource(num_elements, start_position,
            release_time)

    sp2 = PointLineSource(num_elements, start_position,
                                    start_time2)

    sc.spills += [spill, sp2]

    sc.prepare_for_model_run(windage_at)

    sc.release_elements(100, release_time)
    sc.release_elements(100, start_time2)

    (sc['status_codes'])[5:8] = oil_status.to_be_removed
    (sc['status_codes'])[14:17] = oil_status.to_be_removed
    sc['status_codes'][19] = oil_status.to_be_removed

    # also make corresponding positions 0 as a way to test

    sc['positions'][5:8, :] = (0, 0, 0)
    sc['positions'][14:17, :] = (0, 0, 0)
    sc['positions'][19, :] = (0, 0, 0)
    sc.model_step_is_done()

    assert sc.num_released == 2 * num_elements - 7

    assert np.all(sc['status_codes'] != oil_status.to_be_removed)
    assert np.all(sc['positions'] == start_position)

    assert np.count_nonzero(sc['spill_num'] == 0) == num_elements - 3
    assert np.count_nonzero(sc['spill_num'] == 1) == num_elements - 4
コード例 #33
0
def test_array_types_reset():
    """
    check the array_types are reset on rewind() only
    """
    sc = SpillContainer()
    sc.prepare_for_model_run(array_types=windage_at)

    assert 'windages' in sc.array_types

    sc.rewind()
    assert 'windages' not in sc.array_types
    assert sc.array_types == sc_default_array_types

    sc.prepare_for_model_run(array_types=windage_at)
    assert 'windages' in sc.array_types

    # now if we invoke prepare_for_model_run without giving it any array_types
    # it should not reset the dict to default
    sc.prepare_for_model_run()   # set to any datetime
    assert 'windages' in sc.array_types
コード例 #34
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
コード例 #35
0
ファイル: test_wind_mover.py プロジェクト: kthyng/GNOME2
def test_windage_index():
    """
    A very simple test to make sure windage is set for the correct sc
    if staggered release
    """

    sc = SpillContainer()
    rel_time = datetime(2013, 1, 1, 0, 0)
    timestep = 30
    for i in range(2):
        spill = point_line_release_spill(num_elements=5,
                                start_position=(0., 0., 0.),
                                release_time=rel_time + i * timedelta(hours=1),
                                element_type=floating(windage_range=(i * .01 +
                                                        .01, i * .01 + .01),
                                                      windage_persist=900)
                                )
        sc.spills.add(spill)

    windage = {'windages': array_types.windages,
               'windage_range': array_types.windage_range,
               'windage_persist': array_types.windage_persist}
    sc.prepare_for_model_run(array_types=windage)
    sc.release_elements(timestep, rel_time)
    wm = WindMover(environment.ConstantWind(5, 0))
    wm.prepare_for_model_step(sc, timestep, rel_time)
    wm.model_step_is_done()  # need this to toggle _windage_is_set_flag

    def _check_index(sc):
        '''
        internal function for doing the test after windage is set
        - called twice so made a function
        '''

        # only 1st sc is released

        for sp in sc.spills:
            mask = sc.get_spill_mask(sp)
            if np.any(mask):
                assert np.all(sc['windages'][mask] ==
                              (sp.element_type.initializers["windages"].
                              windage_range[0]))

    # only 1st spill is released
    _check_index(sc)  # 1st ASSERT

    sc.release_elements(timestep, rel_time + timedelta(hours=1))
    wm.prepare_for_model_step(sc, timestep, rel_time)
    _check_index(sc)  # 2nd ASSERT
コード例 #36
0
ファイル: test_wind_mover.py プロジェクト: MustiDarsh/PyGnome
def test_windage_index():
    """
    A very simple test to make sure windage is set for the correct sc
    if staggered release
    """
    sc = SpillContainer()
    rel_time = datetime(2013, 1, 1, 0, 0)
    timestep = 30
    for i in range(2):
        spill = point_line_release_spill(num_elements=5,
                                         start_position=(0., 0., 0.),
                                         release_time=rel_time + i * timedelta(hours=1),
                                         element_type=floating(windage_range=(i * .01 +
                                                               .01, i * .01 + .01),
                                                               windage_persist=900)
                                         )
        sc.spills.add(spill)

    windage = ['windages', 'windage_range', 'windage_persist']
    sc.prepare_for_model_run(array_types=windage)
    sc.release_elements(timestep, rel_time)

    wm = constant_wind_mover(5, 0)
    wm.prepare_for_model_step(sc, timestep, rel_time)
    wm.model_step_is_done()  # need this to toggle _windage_is_set_flag

    def _check_index(sc):
        '''
        internal function for doing the test after windage is set
        - called twice so made a function
        '''
        # only 1st sc is released
        for sp in sc.spills:
            mask = sc.get_spill_mask(sp)
            if np.any(mask):
                assert np.all(sc['windages'][mask] ==
                              sp.windage_range[0])

    # only 1st spill is released
    _check_index(sc)  # 1st ASSERT

    sc.release_elements(timestep, rel_time + timedelta(hours=1))
    wm.prepare_for_model_step(sc, timestep, rel_time)
    _check_index(sc)  # 2nd ASSERT
コード例 #37
0
def sample_sc_release(num_elements=10,
                      start_pos=(0.0, 0.0, 0.0),
                      release_time=datetime(2000, 1, 1, 1),
                      uncertain=False,
                      time_step=360,
                      spill=None,
                      element_type=None,
                      current_time=None,
                      arr_types=None,
                      windage_range=None,
                      units='g',
                      amount_per_element=1.0):
    """
    Initialize a Spill of type 'spill', add it to a SpillContainer.
    Invoke release_elements on SpillContainer, then return the spill container
    object

    If 'spill' is None, define a Spill object with a PointLineRelease type
    of release
    """
    if current_time is None:
        current_time = release_time

    if spill is None:
        spill = gnome.spill.point_line_release_spill(num_elements, start_pos,
                                                     release_time)
    spill.units = units
    spill.amount = amount_per_element * num_elements

    if element_type is not None:
        spill.element_type = element_type

    if current_time is None:
        current_time = spill.release_time

    # fixme -- maybe this is not the place for the default arrays?
    always = {'windages', 'windage_range', 'windage_persist'}
    if arr_types is None:
        # default always has standard windage parameters required by wind_mover
        arr_types = always
    else:
        arr_types.update(always)

    if windage_range is not None:
        spill.windage_range = windage_range

    sc = SpillContainer(uncertain)
    sc.spills.add(spill)

    # used for testing so just assume there is a Windage array
    sc.prepare_for_model_run(arr_types)
    sc.release_elements(time_step, current_time)

    return sc
コード例 #38
0
def sample_sc_release(num_elements=10,
                      start_pos=(0.0, 0.0, 0.0),
                      release_time=datetime(2000, 1, 1, 1),
                      uncertain=False,
                      time_step=360,
                      spill=None,
                      substance=None,
                      current_time=None,
                      arr_types=None,
                      windage_range=None,
                      units='g',
                      amount_per_element=1.0):
    """
    Initialize a Spill of type 'spill', add it to a SpillContainer.
    Invoke release_elements on SpillContainer, then return the spill container
    object

    If 'spill' is None, define a Spill object with a PointLineRelease type
    of release
    """
    if current_time is None:
        current_time = release_time

    if spill is None:
        spill = gnome.spill.point_line_release_spill(num_elements,
                                                     start_pos,
                                                     release_time,
                                                     amount=0)
    spill.units = units
    spill.amount = amount_per_element * num_elements

    if substance is None:
        substance = NonWeatheringSubstance()
    spill.substance = substance

    if current_time is None:
        current_time = spill.release_time

    if windage_range is not None:
        spill.substance.windage_range = windage_range

    if arr_types is None:
        arr_types = {}
    arr_types.update(spill.all_array_types)

    sc = SpillContainer(uncertain)
    sc.spills.add(spill)

    # used for testing so just assume there is a Windage array
    sc.prepare_for_model_run(arr_types)
    sc.release_elements(time_step, current_time)

    return sc
コード例 #39
0
    def test_spills_different_substance_release(self):
        '''
        Test data structure gets correctly set/updated after release_elements
        is invoked
        '''
        sc = SpillContainer()
        rel_time = datetime(2014, 1, 1, 12, 0, 0)
        end_time = rel_time + timedelta(hours=1)
        time_step = 900
        splls0 = [
            point_line_release_spill(100, (1, 1, 1),
                                     rel_time,
                                     end_release_time=end_time,
                                     element_type=floating(substance=test_oil),
                                     amount=100,
                                     units='kg'),
            point_line_release_spill(50, (2, 2, 2),
                                     rel_time + timedelta(seconds=900),
                                     element_type=floating(substance=test_oil),
                                     amount=150,
                                     units='kg'),
        ]
        sc.spills += splls0
        splls1 = point_line_release_spill(
            10, (0, 0, 0), rel_time, element_type=floating(substance=None))
        sc.spills += splls1

        at = {'density', 'mass_components'}
        sc.prepare_for_model_run(at)
        assert len(sc.get_substances()) == 2

        print '\nElements released:'
        for ix in range(-1, 8):
            time = rel_time + timedelta(seconds=time_step) * ix
            num_rel = sc.release_elements(time_step, time)
            print num_rel
            for substance, data in sc.itersubstancedata(at):
                assert substance.name == test_oil
                idx = sc._substances_spills.substances.index(substance)
                mask = sc['substance'] == idx
                for array in at:
                    assert array in data
                    assert np.all(data[array] == sc[array][mask])
コード例 #40
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()])
コード例 #41
0
def test_multiple_spills(uncertain):
    """
    SpillContainer initializes correct number of elements in data_arrays.
    Use Multiple spills with different release times.
    Also, deleting a spill shouldn't change data_arrays for particles
    already released.
    """
    sc = SpillContainer(uncertain)
    spills = [
        point_line_release_spill(num_elements, start_position, release_time),
        point_line_release_spill(num_elements, start_position,
                                 release_time + timedelta(hours=1),
                                 end_position, end_release_time)
    ]

    sc.spills.add(spills)

    for spill in spills:
        assert sc.spills[spill.id] == spill

    assert sc.uncertain == uncertain

    time_step = 3600
    num_steps = ((spills[-1].release.end_release_time -
                  spills[-1].release.release_time).seconds / time_step + 1)

    sc.prepare_for_model_run(windage_at)

    for step in range(num_steps):
        current_time = release_time + timedelta(seconds=time_step * step)
        sc.release_elements(time_step, current_time)

    assert sc.num_released == spills[0].release.num_elements * len(spills)
    assert_dataarray_shape_size(sc)

    sc.spills.remove(spills[0].id)

    with raises(KeyError):
        # it shouldn't be there anymore.
        assert sc.spills[spills[0].id] is None

    # however, the data arrays of released particles should be unchanged
    assert sc.num_released == spill.release.num_elements * len(spills)
    assert_dataarray_shape_size(sc)
コード例 #42
0
    def test_spills_different_substance_release(self):
        '''
        Test data structure gets correctly set/updated after release_elements
        is invoked
        '''
        sc = SpillContainer()
        rel_time = datetime(2014, 1, 1, 12, 0, 0)
        end_time = rel_time + timedelta(hours=1)
        time_step = 900
        splls0 = [point_line_release_spill(100, (1, 1, 1),
                                           rel_time,
                                           end_release_time=end_time,
                                           element_type=floating(substance=test_oil),
                                           amount=100,
                                           units='kg'),
                  point_line_release_spill(50, (2, 2, 2),
                                           rel_time + timedelta(seconds=900),
                                           element_type=floating(substance=test_oil),
                                           amount=150,
                                           units='kg'),
                  ]
        sc.spills += splls0
        splls1 = point_line_release_spill(10, (0, 0, 0),
                                          rel_time,
                                          element_type=floating(substance=None))
        sc.spills += splls1

        at = {'density', 'mass_components'}
        sc.prepare_for_model_run(at)
        assert len(sc.get_substances()) == 2

        print '\nElements released:'
        for ix in range(-1, 8):
            time = rel_time + timedelta(seconds=time_step) * ix
            num_rel = sc.release_elements(time_step, time)
            print num_rel
            for substance, data in sc.itersubstancedata(at):
                assert substance.name == test_oil
                idx = sc._substances_spills.substances.index(substance)
                mask = sc['substance'] == idx
                for array in at:
                    assert array in data
                    assert np.all(data[array] == sc[array][mask])
コード例 #43
0
def test_one_simple_spill(spill):
    """ checks data_arrays correctly populated for a single spill in
    SpillContainer """
    sc = SpillContainer()
    sc.spills.add(spill)
    time_step = 3600

    sc.prepare_for_model_run(windage_at)
    if spill.get('end_release_time') is None:
        num_steps = 0
    else:
        num_steps = ((spill.release.end_release_time -
                      spill.release.release_time).seconds / time_step + 1)

    for step in xrange(num_steps + 1):
        current_time = (spill.release.release_time +
                        timedelta(seconds=time_step * step))
        sc.release_elements(time_step, current_time)

    assert sc.num_released == spill.release.num_elements

    assert_sc_single_spill(sc)
コード例 #44
0
def test_uncertain_copy():
    """
    test whether creating an uncertain copy of a spill_container works
    """
    release_time = datetime(2012, 1, 1, 12)
    start_time2 = datetime(2012, 1, 2, 12)

    start_position = (23.0, -78.5, 0.0)
    start_position2 = (45.0, 75.0, 0.0)

    num_elements = 100

    sc = SpillContainer()
    spill = point_line_release_spill(num_elements, start_position,
                                     release_time)

    sp2 = point_line_release_spill(num_elements, start_position2,
                                   start_time2)

    sc.spills.add(spill)
    sc.spills.add(sp2)

    u_sc = sc.uncertain_copy()

    assert u_sc.uncertain
    assert len(sc.spills) == len(u_sc.spills)

    # make sure they aren't references to the same spills

    assert sc.spills[spill.id] not in u_sc.spills
    assert sc.spills[sp2.id] not in u_sc.spills

    # make sure they have unique ids:

    for id1 in [s.id for s in sc.spills]:
        for id2 in [s.id for s in u_sc.spills]:
            print id1, id2
            assert not id1 == id2

    # do the spills work?

    sc.prepare_for_model_run(windage_at)
    sc.release_elements(100, release_time)

    assert sc['positions'].shape == (num_elements, 3)
    assert sc['last_water_positions'].shape == (num_elements, 3)

    # now release second set:

    u_sc.prepare_for_model_run(windage_at)

    assert u_sc['positions'].shape[0] == 0  # nothing released yet.

    u_sc.release_elements(100, release_time)

    # elements should be there.

    assert u_sc['positions'].shape == (num_elements, 3)
    assert u_sc['last_water_positions'].shape == (num_elements, 3)

    # next release:

    sc.release_elements(100, release_time + timedelta(hours=24))

    assert sc['positions'].shape == (num_elements * 2, 3)
    assert sc['last_water_positions'].shape == (num_elements * 2, 3)

    # second set should not have changed

    assert u_sc['positions'].shape == (num_elements, 3)
    assert u_sc['last_water_positions'].shape == (num_elements, 3)

    # release second set

    u_sc.release_elements(100, release_time + timedelta(hours=24))
    assert u_sc['positions'].shape == (num_elements * 2, 3)
    assert u_sc['last_water_positions'].shape == (num_elements * 2, 3)
コード例 #45
0
def test_eq_allclose_spill_container():
    """
    test if two spill containers are equal within 1e-5 tolerance
    adjust the spill_container._array_allclose_atol = 1e-5
    and vary start_positions by 1e-8
    """

    (sp1, sp2) = get_eq_spills()

    # just move one data array a bit

    sp2.start_position = sp2.release.start_position + (1e-8, 1e-8, 0)

    sc1 = SpillContainer()
    sc2 = SpillContainer()

    sc1.spills.add(sp1)
    sc2.spills.add(sp2)

    sc1.prepare_for_model_run(windage_at)
    sc1.release_elements(360, sp1.release.release_time)

    sc2.prepare_for_model_run(windage_at)
    sc2.release_elements(360, sp2.release.release_time)

    # need to change both atol

    sc1._array_allclose_atol = 1e-5
    sc2._array_allclose_atol = 1e-5

    assert sc1 == sc2
    assert sc2 == sc1
    assert not (sc1 != sc2)
    assert not (sc2 != sc1)
コード例 #46
0
def test_split_element():
    '''
    test split_element() method
    '''
    sc = SpillContainer()
    o_sc = SpillContainer()
    reltime = datetime(2015, 1, 1, 12, 0, 0)
    num_les = 10
    sc.spills += point_line_release_spill(num_les, (1, 1, 1),
                                          reltime,
                                          amount=100,
                                          units='kg',
                                          substance=test_oil)
    o_sc.spills += copy.deepcopy(sc.spills[0])

    sc.prepare_for_model_run({'fate_status'})
    sc.release_elements(900, reltime)

    o_sc.prepare_for_model_run({'fate_status'})
    o_sc.release_elements(900, reltime)

    # now do a split at element - fate data is not being initialized; however
    # we want to make sure fate_data arrays are sync'd with sc data arrays so
    # test for fate=non_weather
    num = 2
    l_frac = (.65, .35)
    subs = sc.get_substances(complete=False)[0]
    data = sc.substancefatedata(subs,
                                {'fate_status'},
                                fate='non_weather')
    assert 'id' in data

    ix = data['id'][0]
    sc.split_element(ix, num, l_frac)
    for name in sc._data_arrays:
        split = sc[name]
        d_split = data[name]

        idx = np.where(sc['id'] == ix)[0][0]
        orig = o_sc[name]
        assert len(split) == num_les + num - 1
        assert len(d_split) == num_les + num - 1
        at = sc.array_types[name]
        if isinstance(at, array_types.ArrayTypeDivideOnSplit):
            assert np.allclose(split[idx:idx + num].sum(0), orig[idx])
            assert np.allclose(split[idx], l_frac[0] * orig[idx])
        else:
            assert np.all(split[idx:idx + num] == orig[idx])

        # fatedata copy of sc data is also updated
        assert np.allclose(d_split, split)
コード例 #47
0
def test_ne_spill_container():
    """ test two spill containers are not equal """

    (sp1, sp2) = get_eq_spills()

    # just move one data array a bit

    sp2.release.start_position = sp2.release.start_position + (1e-8, 1e-8, 0)

    sc1 = SpillContainer()
    sc2 = SpillContainer()

    sc1.spills.add(sp1)
    sc2.spills.add(sp2)

    sc1.prepare_for_model_run(windage_at)
    sc1.release_elements(360, sp1.release.release_time)

    sc2.prepare_for_model_run(windage_at)
    sc2.release_elements(360, sp2.release.release_time)

    assert sc1 != sc2
    assert sc2 != sc1
    assert not (sc1 == sc2)
    assert not (sc2 == sc1)
コード例 #48
0
def test_no_spills():
    """ if there are no spills, the substance should be None"""
    sc = SpillContainer()
    sc.prepare_for_model_run()
    assert sc.substance is None
コード例 #49
0
def test_eq_spill_container():
    """ test if two spill containers are equal """

    (sp1, sp2) = get_eq_spills()
    sc1 = SpillContainer()
    sc2 = SpillContainer()

    sc1.spills.add(sp1)
    sc2.spills.add(sp2)

    sc1.prepare_for_model_run(windage_at)
    sc1.release_elements(360, sp1.release.release_time)

    sc2.prepare_for_model_run(windage_at)
    sc2.release_elements(360, sp2.release.release_time)

    assert sc1 == sc2
    assert sc2 == sc1
    assert not (sc1 != sc2)
    assert not (sc2 != sc1)
コード例 #50
0
def test_eq_allclose_spill_container():
    """
    test if two spill containers are equal within 1e-5 tolerance
    adjust the spill_container._array_allclose_atol = 1e-5
    and vary start_positions by 1e-8
    """

    (sp1, sp2) = get_eq_spills()

    # just move one data array a bit

    sp2.start_position = sp2.release.start_position + (1e-8, 1e-8, 0)

    sc1 = SpillContainer()
    sc2 = SpillContainer()

    sc1.spills.add(sp1)
    sc2.spills.add(sp2)

    sc1.prepare_for_model_run(windage_at)
    sc1.release_elements(360, sp1.release.release_time)

    sc2.prepare_for_model_run(windage_at)
    sc2.release_elements(360, sp2.release.release_time)

    # need to change both atol

    sc1._array_allclose_atol = 1e-5
    sc2._array_allclose_atol = 1e-5

    assert sc1 == sc2
    assert sc2 == sc1
    assert not (sc1 != sc2)
    assert not (sc2 != sc1)
コード例 #51
0
def test_get_spill_mask():
    'Simple tests for get_spill_mask'

    start_time0 = datetime(2012, 1, 1, 12)
    start_time1 = datetime(2012, 1, 2, 12)
    start_time2 = start_time1 + timedelta(hours=1)
    start_position = (23.0, -78.5, 0.0)
    num_elements = 5
    sc = SpillContainer()
    sp0 = point_line_release_spill(num_elements, start_position, start_time0)

    sp1 = point_line_release_spill(
        num_elements,
        start_position,
        start_time1,
        end_position=(start_position[0] + 0.2, start_position[1] + 0.2, 0.0),
        end_release_time=start_time1 + timedelta(hours=3))

    sp2 = point_line_release_spill(num_elements, start_position, start_time2)

    sc.spills += [sp0, sp1, sp2]

    # as we move forward in time, the spills will release LEs in an
    # expected way

    sc.prepare_for_model_run(windage_at)
    sc.release_elements(100, start_time0)
    sc.release_elements(100, start_time0 + timedelta(hours=24))
    sc.release_elements(100, start_time1 + timedelta(hours=1))
    sc.release_elements(100, start_time1 + timedelta(hours=3))

    assert all(sc['spill_num'][sc.get_spill_mask(sp2)] == 2)
    assert all(sc['spill_num'][sc.get_spill_mask(sp0)] == 0)
    assert all(sc['spill_num'][sc.get_spill_mask(sp1)] == 1)
コード例 #52
0
def test_length_zero():
    sc = SpillContainer()
    assert len(sc) == 0
コード例 #53
0
 def test_no_spills(self):
     'test iterators work without any spills'
     sc = SpillContainer()
     assert len(sc.iterspillsbysubstance()) == 0
     assert len(sc.get_substances()) == 1
     assert len(sc.get_substances(complete=False)) == 0
コード例 #54
0
def test_get_spill_mask():
    'Simple tests for get_spill_mask'

    start_time0 = datetime(2012, 1, 1, 12)
    start_time1 = datetime(2012, 1, 2, 12)
    start_time2 = start_time1 + timedelta(hours=1)
    start_position = (23.0, -78.5, 0.0)
    num_elements = 5
    sc = SpillContainer()
    sp0 = point_line_release_spill(num_elements, start_position, start_time0)

    sp1 = point_line_release_spill(num_elements,
                                   start_position,
                                   start_time1,
                                   end_position=(start_position[0] + 0.2,
                                                 start_position[1] + 0.2,
                                                 0.0),
                                   end_release_time=start_time1 + timedelta(hours=3)
                                   )

    sp2 = point_line_release_spill(num_elements, start_position,
                                    start_time2)

    sc.spills += [sp0, sp1, sp2]

    # as we move forward in time, the spills will release LEs in an
    # expected way

    sc.prepare_for_model_run(windage_at)
    sc.release_elements(100, start_time0)
    sc.release_elements(100, start_time0 + timedelta(hours=24))
    sc.release_elements(100, start_time1 + timedelta(hours=1))
    sc.release_elements(100, start_time1 + timedelta(hours=3))

    assert all(sc['spill_num'][sc.get_spill_mask(sp2)] == 2)
    assert all(sc['spill_num'][sc.get_spill_mask(sp0)] == 0)
    assert all(sc['spill_num'][sc.get_spill_mask(sp1)] == 1)
コード例 #55
0
def test_uncertain_copy():
    """
    test whether creating an uncertain copy of a spill_container works
    """
    release_time = datetime(2012, 1, 1, 12)
    start_time2 = datetime(2012, 1, 2, 12)

    start_position = (23.0, -78.5, 0.0)
    start_position2 = (45.0, 75.0, 0.0)

    num_elements = 100

    sc = SpillContainer()
    spill = point_line_release_spill(num_elements, start_position,
                                     release_time)

    sp2 = point_line_release_spill(num_elements, start_position2, start_time2)

    sc.spills.add(spill)
    sc.spills.add(sp2)

    u_sc = sc.uncertain_copy()

    assert u_sc.uncertain
    assert len(sc.spills) == len(u_sc.spills)

    # make sure they aren't references to the same spills

    assert sc.spills[spill.id] not in u_sc.spills
    assert sc.spills[sp2.id] not in u_sc.spills

    # make sure they have unique ids:

    for id1 in [s.id for s in sc.spills]:
        for id2 in [s.id for s in u_sc.spills]:
            print id1, id2
            assert not id1 == id2

    # do the spills work?

    sc.prepare_for_model_run(windage_at)
    sc.release_elements(100, release_time)

    assert sc['positions'].shape == (num_elements, 3)
    assert sc['last_water_positions'].shape == (num_elements, 3)

    # now release second set:

    u_sc.prepare_for_model_run(windage_at)

    assert u_sc['positions'].shape[0] == 0  # nothing released yet.

    u_sc.release_elements(100, release_time)

    # elements should be there.

    assert u_sc['positions'].shape == (num_elements, 3)
    assert u_sc['last_water_positions'].shape == (num_elements, 3)

    # next release:

    sc.release_elements(100, release_time + timedelta(hours=24))

    assert sc['positions'].shape == (num_elements * 2, 3)
    assert sc['last_water_positions'].shape == (num_elements * 2, 3)

    # second set should not have changed

    assert u_sc['positions'].shape == (num_elements, 3)
    assert u_sc['last_water_positions'].shape == (num_elements, 3)

    # release second set

    u_sc.release_elements(100, release_time + timedelta(hours=24))
    assert u_sc['positions'].shape == (num_elements * 2, 3)
    assert u_sc['last_water_positions'].shape == (num_elements * 2, 3)
コード例 #56
0
    def test_update_intrinsic_props(self):
        '''
        test multiple spills with same substance
        '''
        weatherers = [WeatheringData(water), FayGravityViscous(water)]

        rel_time = datetime.now().replace(microsecond=0)
        end_time = rel_time + timedelta(hours=1)
        spills = [point_line_release_spill(10,
                                           (0, 0, 0),
                                           rel_time,
                                           end_release_time=end_time,
                                           amount=100,
                                           units='kg',
                                           substance=test_oil),
                  point_line_release_spill(5,
                                           (0, 0, 0),
                                           rel_time + timedelta(hours=.25),
                                           substance=test_oil,
                                           amount=100,
                                           units='kg')
                  ]
        sc = SpillContainer()
        sc.spills += spills
        at = set()
        for w in weatherers:
            at.update(w.array_types)

        sc.prepare_for_model_run(at)

        # test initialization as well
        for w in weatherers:
            w.prepare_for_model_run(sc)

        for val in sc.mass_balance.values():
            assert val == 0.0

        # test initialization as well

        ts = 900
        for i in range(-1, 5):
            curr_time = rel_time + timedelta(seconds=i * ts)
            num_released = sc.release_elements(ts, curr_time)

            if num_released > 0:
                for w in weatherers:
                    w.initialize_data(sc, num_released)

            for w in weatherers:
                self.step(w, sc, curr_time)

            for key, val in sc.mass_balance.iteritems():
                if len(sc) > 0 and key not in ('beached',
                                               'non_weathering',
                                               'off_maps'):
                    assert val > 0
                else:
                    # everything, including avg_density is 0 if nothing is
                    # released
                    assert val == 0.0

            if len(sc) > 0:
                # area arrays initialized correctly
                mask = sc['age'] == 0
                if np.any(~mask):
                    # sc['fay_area'][mask] is initial area of blob
                    # sc['fay_area'][~mask] is area of aged blob
                    assert (sc['fay_area'][mask].sum() !=
                            sc['fay_area'][~mask].sum())

                assert all(sc['fay_area'] > 0)
                assert all(sc['init_mass'] > 0)

                # wd props arrays initialized correctly
                assert all(sc['density'] > 0)
                assert all(sc['viscosity'] > 0)

            sc['age'] += ts     # model would do this operation
            print 'Completed step: ', i
コード例 #57
0
def test_simple_init():
    sc = SpillContainer()
    assert sc is not None