Exemplo n.º 1
0
def test_agent_pid_13_not_start_and_return_home_night_worker_complex_chain_type2_intra_trip(
        simple_plans, simple_attributes
):
    population = Population()
    population.load(simple_plans, simple_attributes)
    acts = [a.act for a in population.households[10].people[13].activities]
    assert acts == ['work', 'shop', 'home', 'work']
Exemplo n.º 2
0
def test_agent_pid_11_not_start_from_home_impossible_chain_type2(
        simple_plans, simple_attributes
):
    population = Population()
    population.load(simple_plans, simple_attributes)
    acts = [a.act for a in population.households[8].people[11].activities]
    assert acts == ['work', 'shop', 'home']
Exemplo 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'])
Exemplo n.º 4
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
Exemplo n.º 5
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
Exemplo n.º 6
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)
Exemplo n.º 7
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
Exemplo n.º 8
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']
Exemplo n.º 9
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
Exemplo n.º 10
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
Exemplo n.º 11
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)
Exemplo n.º 12
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)
Exemplo n.º 13
0
def test_population_combine_population_duplicate_key():
    pop1 = Population()
    hh1 = Household('1')
    p1 = Person('1')
    hh1.add(p1)
    pop1.add(hh1)

    pop2 = Population()
    hh2 = Household('1')
    p2 = Person('1')
    hh2.add(p2)
    pop2.add(hh2)

    with pytest.raises(KeyError):
        pop1.combine(pop2, '')
Exemplo n.º 14
0
def add_persons_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 persons from persons_attributes")
    for hid, hh_data in persons_attributes.groupby('hid'):
        household = population.get(hid)
        if household is None:
            logger.warning(
                f"Failed to find household {hid} in population - unable to add person."
            )
            continue
        for pid in hh_data.index:
            if pid in household.people:
                continue
            person_attributes = persons_attributes.loc[pid].to_dict()
            person = core.Person(pid,
                                 attributes=person_attributes,
                                 home_area=person_attributes.pop(
                                     'hzone', None),
                                 freq=person_attributes.pop('freq', None))
            household.add(person)
Exemplo n.º 15
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)
Exemplo n.º 16
0
def population_heh():
    home_loc = Point(0, 0)
    education_loc = Point(110, 110)
    attributes = {'hid': 0, 'hh_size': 3, 'inc': "high"}
    person = Person('1', attributes=attributes)
    person.add(
        Activity(seq=1,
                 act='home',
                 area='a',
                 loc=home_loc,
                 start_time=mtdt(0),
                 end_time=mtdt(60)))
    person.add(
        Leg(seq=1,
            mode='car',
            start_area='a',
            end_area='b',
            start_time=mtdt(60),
            end_time=mtdt(90)))
    person.add(
        Activity(seq=2,
                 act='education',
                 area='b',
                 loc=education_loc,
                 start_time=mtdt(90),
                 end_time=mtdt(120)))
    person.add(
        Leg(seq=2,
            mode='car',
            start_area='b',
            end_area='a',
            start_time=mtdt(120),
            end_time=mtdt(180)))
    person.add(
        Activity(seq=3,
                 act='home',
                 area='a',
                 loc=home_loc,
                 start_time=mtdt(180),
                 end_time=END_OF_DAY))
    person.plan.autocomplete_matsim()
    household = Household('0')
    household.add(person)
    population = Population()
    population.add(household)
    return population
Exemplo n.º 17
0
def test_population_combine_population():
    pop1 = Population()
    hh1 = Household('1')
    p1 = Person('1')
    hh1.add(p1)
    pop1.add(hh1)

    pop2 = Population()
    hh2 = Household('1')
    p2 = Person('1')
    hh2.add(p2)
    pop2.add(hh2)

    pop1.combine(pop2, '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)
Exemplo n.º 18
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
Exemplo n.º 19
0
def test_writes_od_matrix_to_expected_file(tmpdir):
    population = Population()
    for hid in range(1, 11):
        household = Household(hid)
        population.add(household)

        for pid in range (2):
            person = Person(pid)
            person.add(Activity(1,'home', 'Barnet'))
            person.add(Leg(1,'car', start_area='Barnet', end_area='Southwark'))
            person.add(Activity(2,'work', 'Southwark'))
            person.add(Leg(2,'car', start_area='Southwark', end_area='Barnet'))
            person.add(Activity(3,'work', 'Barnet'))
            household.add(person)

    od_matrix_file = os.path.join(tmpdir, "od_matrix_test.csv")

    extract_od(population, od_matrix_file)

    od_matrix_csv_string = open(od_matrix_file).read()
    assert od_matrix_csv_string == 'ozone,Barnet,Southwark\nBarnet,0,20\nSouthwark,20,0\n'
Exemplo n.º 20
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
Exemplo n.º 21
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
Exemplo n.º 22
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
Exemplo n.º 23
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
Exemplo n.º 24
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)
Exemplo n.º 25
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
Exemplo n.º 26
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
Exemplo n.º 27
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)
Exemplo n.º 28
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)
Exemplo n.º 29
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_")
Exemplo n.º 30
0
def test_plot_population_comparisons(Steve, Hilda):
    population_1 = Population()
    for i, person in enumerate([Steve, Hilda]):
        hh = Household(i)
        hh.add(person)
        population_1.add(hh)
    population_1.name = 'base'
    population_2 = deepcopy(population_1)
    population_2.name = 'work_removed'

    policy_remove_work = policies.RemovePersonActivities(activities=['work'],
                                                         probability=1)
    policies.apply_policies(population_2, [policy_remove_work])

    list_of_populations = [population_1, population_2]
    outputs = plot_population_comparisons(list_of_populations, 'home')
    legs = outputs[2]
    activities = outputs[3]
    check = calculate_leg_duration_by_mode(population_2)
    assert isinstance(outputs[0], Figure)
    assert isinstance(outputs[1], Figure)
    assert legs.loc['work_removed',
                    'walk'] == check.loc[check['leg mode'] == 'walk',
                                         'duration_hours'].iloc[0]