def test_count_layer_degree(create_pop):
    sp.logger.info(
        "Testing degree_df and quantile stats calculating method for degree distribution by age."
    )
    pop = create_pop

    layer = 'S'
    ages = None
    uids = None
    degree_df = sp.count_layer_degree(pop, layer, ages, uids)
    assert list(
        degree_df.columns.values) == ['uid', 'age', 'degree',
                                      'contact_ages'], 'Check failed.'
    print('Check passed.')

    desc = sp.compute_layer_degree_description(pop, degree_df=degree_df)
    cols = list(desc.columns.values)
    expected_cols = [
        'count', 'mean', 'std', 'min', '5%', '25%', '50%', '75%', '95%', 'max'
    ]
    for exc in expected_cols:
        assert exc in cols, f'Check failed. {exc} not found in description columns.'
    print('Check passed. Found all expected columns.')

    return pop
def test_count_layer_degree_by_age(create_pop):
    pop = create_pop
    layer = 'W'
    brackets = pop.age_brackets
    ageindex = pop.age_by_brackets
    total = np.zeros(len(brackets))
    contacts = np.zeros(len(brackets))
    # brute force check for contact count
    for p in pop.popdict.values():
        total[ageindex[p["age"]]] += 1
        contacts[ageindex[p["age"]]] += len(p["contacts"][layer])
    for b in brackets:
        degree_df = sp.count_layer_degree(pop, layer, brackets[b])
        expected = contacts[b]
        actual = degree_df.sum(axis=0)['degree'] if len(degree_df) > 0 else 0
        print(f"expected contacts for {brackets[b]} is {expected}")
        assert expected == actual, f"expecred: {expected} actual:{actual}"
Beispiel #3
0
def get_pop_average_contacts_by_brackets(pop, layer, decimal=3):
    """
    get population contact counts by age brackets and save the results as json files and plots
    Args:
        pop (pop object)   : population, either synthpops.pop.Pop, covasim.people.People, or dict
        layer (str)        : name of the physical contact layer: H for households, S for schools, W for workplaces, C for community or other
        decimal (int)      : rounding precision for average contact calculation
    Returns:
    dict: a dictionary where index is the age bracket and value is the percentage of contact
    """
    # want default age brackets and to see that they line up with the average contacts by age bracket created
    age_brackets = spdd.get_census_age_brackets(**pop.loc_pars)
    average_contacts = []
    for k in age_brackets:
        degree_df = sp.count_layer_degree(pop, layer=layer, ages=age_brackets[k])
        people_in_ages = sp.filter_people(pop, ages=age_brackets[k])
        average_contacts.append(
            0 if len(degree_df) == 0 else np.round(degree_df.sum(axis=0)['degree'] / len(people_in_ages),
                                                   decimals=decimal))
    return dict(enumerate(average_contacts))
def test_plot_degree_by_age_methods(create_pop,
                                    layer='S',
                                    do_show=False,
                                    do_save=False):
    sp.logger.info(
        "Testing the different plotting methods to show the degree distribution by age for a single population."
    )
    # age on x axis, degree distribution on y axis
    pop = create_pop
    kwargs = sc.objdict(do_show=do_show, do_save=do_save)

    ages = None
    uids = None

    uids_included = None

    degree_df = sp.count_layer_degree(pop,
                                      layer=layer,
                                      ages=ages,
                                      uids=uids,
                                      uids_included=uids_included)

    if kwargs.do_show:
        plt.switch_backend(mplt_org_backend)

    # kde seaborn jointplot
    gkde = sp.plotting.plot_degree_by_age(pop,
                                          layer=layer,
                                          ages=ages,
                                          uids=uids,
                                          uids_included=uids_included,
                                          degree_df=degree_df,
                                          kind='kde',
                                          **kwargs)

    # hist seaborn jointplot
    ghist = sp.plotting.plot_degree_by_age(pop,
                                           layer=layer,
                                           ages=ages,
                                           uids=uids,
                                           uids_included=uids_included,
                                           degree_df=degree_df,
                                           kind='hist',
                                           **kwargs)

    # reg seaborn joint
    greg = sp.plotting.plot_degree_by_age(pop,
                                          layer=layer,
                                          ages=ages,
                                          uids=uids,
                                          uids_included=uids_included,
                                          degree_df=degree_df,
                                          kind='reg',
                                          **kwargs)

    # hex seaborn joint
    # extra features: can limit the ages or uids, then just don't include the degree_df and it will calculate a new one with those filters applied
    ages = np.arange(3, 76)
    kwargs.xlim = [3, 76]
    ghex = sp.plotting.plot_degree_by_age(pop,
                                          layer=layer,
                                          ages=ages,
                                          uids=uids,
                                          uids_included=uids_included,
                                          kind='hex',
                                          **kwargs)

    ages = np.arange(15, 76)
    fig, axboxplot = sp.plotting.plot_degree_by_age_boxplot(pop,
                                                            layer='W',
                                                            ages=ages,
                                                            **kwargs)

    return gkde, ghist, greg, ghex, axboxplot