Ejemplo n.º 1
0
def test_population_size():
    population = Population()
    population.add(Household('1'))
    population['1'].add(Person('0', freq=1))
    population['1'].add(Person('1', freq=3))
    population.add(Household('2'))
    assert population.size == 4
Ejemplo n.º 2
0
def population():

    population = Population()
    for hid in range(1, 11):
        household = HouseHold(hid)
        for pid in range(2):
            pid = f"{hid}-{pid}"
            person = Person(pid)

            person.add(Activity(1, 'home', 'a'))
            person.add(Leg(1, 'car', 'a', 'b'))
            person.add(Activity(2, 'work', 'b'))
            person.add(Leg(2, 'car', 'b', 'a'))
            person.add(Activity(3, 'home', 'a'))

            household.add(person)
        population.add(household)

    for hid in range(10, 21):
        household = HouseHold(hid)
        for pid in range(2):
            pid = f"{hid}-{pid}"
            person = Person(pid)

            person.add(Activity(1, 'home', 'a'))
            person.add(Leg(1, 'bus', 'a', 'b'))
            person.add(Activity(2, 'education', 'b'))
            person.add(Leg(2, 'bus', 'b', 'a'))
            person.add(Activity(3, 'home', 'a'))

            household.add(person)
        population.add(household)
    return population
Ejemplo n.º 3
0
def test_extract_population_mode_classes():
    population = Population()
    for hid, (_act, _mode) in enumerate(zip(['work', 'shop'], ['pt', 'walk'])):
        household = Household(hid=str(hid))
        population.add(household)
        for i, (act, mode) in enumerate(zip(['work', _act], ['car', _mode])):
            person = Person(pid=str(i))
            person.add(
                Activity(seq=1,
                         act='home',
                         area='A',
                         start_time=mtdt(0),
                         end_time=mtdt(600)))
            person.add(
                Leg(seq=2,
                    mode=mode,
                    start_area='A',
                    end_area='B',
                    start_time=mtdt(600),
                    end_time=mtdt(620)))
            person.add(
                Activity(seq=3,
                         act=act,
                         area='B',
                         start_time=mtdt(620),
                         end_time=mtdt(1200)))
            household.add(person)

    assert population.mode_classes == set(['car', 'pt', 'walk'])
Ejemplo n.º 4
0
def test_population_print(capfd, person_heh):
    population = Population()
    population.add(Household('1'))
    population['1'].add(person_heh)
    population.print()
    out, _ = capfd.readouterr()
    assert (out)
Ejemplo n.º 5
0
def test_population_num_households():
    population = Population()
    population.add(Household('1'))
    population['1'].add(Person('0', freq=1))
    population['1'].add(Person('1', freq=3))
    population.add(Household('2'))
    assert population.num_households == 2
Ejemplo n.º 6
0
def test_population_stats():
    population = Population()
    population.add(Household('1'))
    population['1'].add(Person('0', freq=1))
    population['1'].add(Person('1', freq=3))
    population.add(Household('2'))
    population['2'].add(Person('2', freq=3))
    assert isinstance(population.stats, dict)
Ejemplo n.º 7
0
def test_pickle_population(person_crop_last_act, tmpdir):
    population = Population()
    hh = Household('1')
    hh.add(person_crop_last_act)
    population.add(hh)
    path = os.path.join(tmpdir, 'test.pkl')
    population.pickle(path)
    assert os.path.exists(path)
Ejemplo n.º 8
0
def test_count_population():
    population = Population()
    for i in range(1, 5):
        hh = Household(str(i))
        for ii in range(i):
            hh.add(Person(f"{i}_{ii}"))
        population.add(hh)
    assert population.population == 10
Ejemplo n.º 9
0
def test_populations_equal_given_same_population():
    pop1 = Population()
    hh1 = Household('1', attributes={1: 1})
    p1 = Person('1', attributes={1: 1})
    hh1.add(p1)
    pop1.add(hh1)

    assert pop1 == pop1
Ejemplo n.º 10
0
def test_plot_act_time_bins(Steve, Hilda):
    population = Population()
    for i, person in enumerate([Steve, Hilda]):
        hh = Household(i)
        hh.add(person)
        population.add(hh)
    fig = plot_activity_times(population)
    assert isinstance(fig, Figure)
Ejemplo n.º 11
0
def test_populations_not_equal_given_diff_type():
    pop1 = Population()
    hh1 = Household('1', attributes={1: 1})
    p1 = Person('1', attributes={1: 1})
    hh1.add(p1)
    pop1.add(hh1)

    assert not pop1 == None
Ejemplo n.º 12
0
def test_reindex_population_duplicate_key():
    pop = Population()
    for i in ['1', 'test_1']:
        hh = Household(i)
        pop.add(hh)
        for j in ['1', 'test_1']:
            hh.add(Person(j))
    with pytest.raises(KeyError):
        pop.reindex("test_")
Ejemplo n.º 13
0
def test_build_leg_log(person_heh):
    population = Population()
    for i in range(5):
        hh = Household(i)
        hh.add(person_heh)
        population.add(hh)
    log = extract_leg_log(population)
    assert len(log) == 10
    assert list(log.columns) == ['mode', 'start', 'end', 'duration']
Ejemplo n.º 14
0
def population():
    population = Population()
    hh = Household('A', attributes={1: 1})
    pa = Person('person_A', attributes={1: 1})
    hh.add(pa)
    pb = Person('Person_B', attributes={1: 3})
    hh.add(pb)
    population.add(hh)
    population.add(Household('B'))
    return population
Ejemplo n.º 15
0
def test_load_pickle_population(person_crop_last_act, tmpdir):
    population = Population()
    hh = Household('1')
    hh.add(person_crop_last_act)
    population.add(hh)
    path = os.path.join(tmpdir, 'test.pkl')
    population.pickle(path)
    loaded = load_pickle(path)
    assert loaded.households
    assert list(loaded.households['1'].people) == list(
        population.households['1'].people)
Ejemplo n.º 16
0
def test_population_combine_person_duplicate_key():
    pop1 = Population()
    hh1 = Household('1')
    p1 = Person('1')
    hh1.add(p1)
    pop1.add(hh1)

    p2 = Person('1')

    with pytest.raises(KeyError):
        pop1.combine(p2, '')
Ejemplo n.º 17
0
def test_time_binner(person_heh):
    population = Population()
    for i in range(5):
        hh = Household(i)
        hh.add(person_heh)
        population.add(hh)
    log = extract_activity_log(population)
    binned = time_binner(log)
    assert len(binned) == 96
    for h in ['start', 'end', 'duration']:
        assert binned[h].sum() == 3
Ejemplo n.º 18
0
def test_population_sample_locs(person_heh):
    population = Population()
    population.add(Household('1'))
    population['1'].add(person_heh)

    class DummySampler:
        def sample(self, loc, act):
            return None

    population.sample_locs(DummySampler())
    assert population['1']['1'].plan[2].location.loc is None
Ejemplo n.º 19
0
def test_assign_same_locs_to_household_activity_in_same_area(SmithHousehold):
    population = Population()
    population.add(SmithHousehold)

    class FakeSampler:
        def sample(self, location_idx, activity):
            return random()

    population.sample_locs(FakeSampler())
    SmithHousehold['3'].plan[2].location == SmithHousehold['4'].plan[
        2].location
Ejemplo n.º 20
0
def test_populations_not_equal_given_missing_person():
    pop1 = Population()
    hh1 = Household('1', attributes={1: 1})
    p1 = Person('1', attributes={1: 1})
    hh1.add(p1)
    pop1.add(hh1)

    pop4 = Population()
    hh4 = Household('2', attributes={1: 2})
    pop4.add(hh4)

    assert not pop1 == pop4
Ejemplo n.º 21
0
def test_write_plans_xml_v12_assert_contents(tmp_path):
    population = Population()
    hh = Household('a')
    p = Person('a', attributes={'1':'1'})
    p.add(Activity(
        act="home",
        loc=Point((0,0)),
        start_time=datetime(1900,1,1,0,0,0),
        end_time=datetime(1900,1,1,8,0,0)
        ))
    p.add(Leg(
        mode='car',
        start_loc=Point((0,0)),
        end_loc=Point((0,1000)),
        start_time=datetime(1900,1,1,8,0,0),
        end_time=datetime(1900,1,1,9,0,0)
    ))
    p.add(Activity(
        act="work",
        loc=Point((0,1000)),
        start_time=datetime(1900,1,1,9,0,0),
        end_time=datetime(1900,1,1,18,0,0)
        ))
    p.add(Leg(
        mode='car',
        start_loc=Point((0,1000)),
        end_loc=Point((0,0)),
        start_time=datetime(1900,1,1,18,0,0),
        end_time=datetime(1900,1,1,19,0,0)
    ))
    p.add(Activity(
        act="home",
        loc=Point((0,0)),
        start_time=datetime(1900,1,1,19,0,0),
        end_time=END_OF_DAY
        ))
    hh.add(p)
    population.add(hh)
    plans_location = str(tmp_path / "test_plans.xml")
    write_matsim(
        population,
        plans_path=plans_location,
        comment="test",
        version=12,
        household_key=None
        )
    new = read_matsim(
        plans_location,
        version=12
        )
    assert new == population
    assert new['a']['a'].attributes == {'1':'1'}
    assert new['a']['a'].plan.day[1].distance == 1000
Ejemplo n.º 22
0
def test_assign_same_locs_to_household(SmithHousehold):
    population = Population()
    population.add(SmithHousehold)

    class FakeSampler:
        def sample(self, location_idx, activity):
            return random()

    population.sample_locs(FakeSampler())

    home_location = population['1'].location

    for pid, person in SmithHousehold:
        assert person.home == home_location
Ejemplo n.º 23
0
def test_population_iadd_person():
    pop1 = Population()
    hh1 = Household('1')
    p1 = Person('1')
    hh1.add(p1)
    pop1.add(hh1)

    p2 = Person('2')

    pop1 += p2
    assert set(pop1.households) == {'1', '2'}
    assert set(pop1.households['2'].people) == {'2'}
    assert isinstance(pop1.households['2'], Household)
    assert isinstance(pop1.households['2'].people['2'], Person)
Ejemplo n.º 24
0
def test_population_combine_person():
    pop1 = Population()
    hh1 = Household('1')
    p1 = Person('1')
    hh1.add(p1)
    pop1.add(hh1)

    p2 = Person('1')

    pop1.combine(p2, 'test_')
    assert set(pop1.households) == {'1', 'test_1'}
    assert set(pop1.households['test_1'].people) == {'test_1'}
    assert isinstance(pop1.households['test_1'], Household)
    assert isinstance(pop1.households['test_1'].people['test_1'], Person)
Ejemplo n.º 25
0
def test_populations_equal_with_same_hh_and_person_attributes():
    pop1 = Population()
    hh1 = Household('1', attributes={1: 1})
    p1 = Person('1', attributes={1: 1})
    hh1.add(p1)
    pop1.add(hh1)

    pop2 = Population()
    hh2 = Household('1', attributes={1: 1})
    p2 = Person('1', attributes={1: 1})
    hh2.add(p2)
    pop2.add(hh2)

    assert pop1 == pop2
Ejemplo n.º 26
0
def test_populations_equal_given_same_hh_and_persons_with_diff_ids():
    pop1 = Population()
    hh1 = Household('1', attributes={1: 1})
    p1 = Person('1', attributes={1: 1})
    hh1.add(p1)
    pop1.add(hh1)

    pop3 = Population()
    hh3 = Household('2', attributes={1: 1})
    p3 = Person('2', attributes={1: 1})
    hh3.add(p3)
    pop3.add(hh3)

    assert pop1 == pop3
Ejemplo n.º 27
0
def test_populations_not_equal_given_wrong_person_attributes():
    pop1 = Population()
    hh1 = Household('1', attributes={1: 1})
    p1 = Person('1', attributes={1: 1})
    hh1.add(p1)
    pop1.add(hh1)

    pop5 = Population()
    hh5 = Household('2', attributes={1: 1})
    p5 = Person('1', attributes={1: 2})
    hh5.add(p5)
    pop5.add(hh5)

    assert not pop1 == pop5
Ejemplo n.º 28
0
def test_reindex_population():
    pop = Population()
    for i in ['1', '2']:
        hh = Household(i)
        pop.add(hh)
        for j in ['1', '2']:
            hh.add(Person(j))
    pop.reindex("test_")
    assert set(pop.households) == {'test_1', 'test_2'}
    assert {hh.hid for hh in pop.households.values()} == {'test_1', 'test_2'}
    assert set(pop.households['test_1'].people) == {'test_1', 'test_2'}
    assert {p.pid
            for p in pop.households['test_1'].people.values()
            } == {'test_1', 'test_2'}
Ejemplo n.º 29
0
def add_hhs_from_persons_attributes(
        population: core.Population,
        persons_attributes: Optional[pd.DataFrame] = None):
    logger = logging.getLogger(__name__)

    if persons_attributes is None or 'hid' not in persons_attributes.columns:
        return None

    logger.info("Adding hhs from persons_attributes")
    for hid, hh_data in persons_attributes.groupby('hid'):
        if hid not in population.households:
            hzone = hh_data.iloc[0].to_dict().get("hzone")
            household = core.Household(hid, area=hzone)
            population.add(household)
Ejemplo n.º 30
0
def add_hhs_from_hhs_attributes(population: core.Population,
                                hhs_attributes: Optional[pd.DataFrame] = None):
    logger = logging.getLogger(__name__)

    if hhs_attributes is None:
        return None

    logger.info("Adding hhs from hhs_attributes")
    for hid, hh in hhs_attributes.groupby('hid'):
        if hid not in population.households:
            hh_attributes = hhs_attributes.loc[hid].to_dict()
            household = core.Household(hid,
                                       attributes=hh_attributes,
                                       freq=hh_attributes.pop("freq", None),
                                       area=hh_attributes.pop("hzone", None))
            population.add(household)