Beispiel #1
0
def convert_static_network(N, edge_list, tmax=1.0):
    """Get a single frame which consists of the static network.

    Parameters
    ----------
    N : int
        Number of nodes.
    edge_list : :obj:`list` of :obj:`tuple` of int
        The edges of the static graph
    tmax : double, default : 1.0
        The maximum time until the network is looped.
        
    Returns 
    -------
    :class:`_tacoma.edge_lists`
        An instance of `tacoma.edge_lists` with t = [0.0], tmax = ``tmax``.
    """

    new_edge_list = []

    for e in edge_list:
        if e[0] > e[1]:
            new_edge_list.append((e[1], e[0]))
        elif e[1] > e[0]:
            new_edge_list.append((e[0], e[1]))

    this = tc.edge_lists()
    this.t = [0.]
    this.tmax = tmax
    this.edges = [new_edge_list]
    this.N = N

    return this
Beispiel #2
0
def load_json_taco(fp):
    """
    Loads a temporal network from a .taco-file (which is actually in json format).

    Parameters
    ----------
    fp : file-like or :obj:`str`
        read from this file

    Returns
    -------
    temporal network
        type as given in the .taco-file
    """

    file_is_string = isinstance(fp, str)

    if file_is_string:
        fp = os.path.abspath(os.path.expanduser(fp))
        with open(fp, 'r') as f:
            this_data = json.load(f)

    else:
        this_data = json.load(fp)

    if this_data['type'] == 'edge_changes':
        temporal_network = tc.edge_changes()
        temporal_network.t = this_data['t']
        temporal_network.t0 = this_data['t0']
        temporal_network.tmax = this_data['tmax']
        temporal_network.N = this_data['N']
        temporal_network.edges_initial = this_data['edges_initial']
        temporal_network.edges_in = this_data['edges_in']
        temporal_network.edges_out = this_data['edges_out']
        temporal_network.int_to_node = {
            int(i): s
            for i, s in this_data['int_to_node'].items()
        }
        temporal_network.notes = this_data['notes']
        temporal_network.time_unit = this_data['time_unit']

    elif this_data['type'] == 'edge_lists':
        temporal_network = tc.edge_lists()
        temporal_network.t = this_data['t']
        temporal_network.tmax = this_data['tmax']
        temporal_network.N = this_data['N']
        temporal_network.edges = this_data['edges']
        temporal_network.int_to_node = {
            int(i): s
            for i, s in this_data['int_to_node'].items()
        }
        temporal_network.notes = this_data['notes']
        temporal_network.time_unit = this_data['time_unit']

    else:
        raise ValueError(
            'file is corrupted, unknown temporal network format: ' +
            this_data['type'])

    return temporal_network
Beispiel #3
0
def complete_graph(N, tmax=1.0):
    """Get a single frame which consists of a complete network.

    Parameters
    ----------
    N : int
        Number of nodes.
    tmax : float, default : 1.0
        Maximum time of the static network.
        
    Returns 
    -------
    :class:`_tacoma.edge_lists`
        An instance of `tacoma.edge_lists` with t = [0.0], tmax = ``tmax``.
    """

    edge_list = []
    for i in range(N - 1):
        for j in range(i + 1, N):
            edge_list.append((i, j))

    this = tc.edge_lists()
    this.t = [0.]
    this.tmax = tmax
    this.edges = [edge_list]
    this.N = N

    return this
Beispiel #4
0
def continuous_time_simulation(n_nodes,
                               t0,
                               t_max,
                               shape,
                               scale,
                               edge_contact_time,
                               alpha,
                               beta,
                               gamma,
                               delta_in,
                               delta_out,
                               mean_degree=1.5):
    # # static structure parameters
    # p = mean_degree / (n_nodes - 1.0)

    # temporal parameters
    edge_lists = []
    t = []
    this_time = t0

    edge_lists, t = scale_free_graph(n_nodes,
                                     t0=t0,
                                     t_max=t_max,
                                     shape=shape,
                                     scale=scale,
                                     edge_contact_time=edge_contact_time,
                                     alpha=alpha,
                                     beta=beta,
                                     gamma=gamma,
                                     delta_in=delta_in,
                                     delta_out=delta_out)
    # while this_time < tmax:
    #     G = nx.fast_gnp_random_graph(n_nodes, p)  # Generate a new random network
    #     # G = nx.gnm_random_graph(N, M)  # Generate a Erdos Renyi network
    #     # G = nx.barabasi_albert_graph(N, M) # Generate a Erdos Renyi network
    #     these_edges = list(G.edges())
    #     t.append(this_time)
    #     edge_lists.append(these_edges)
    #     this_time += np.random.exponential(scale=scale)

    # save to _tacoma-object
    el = tc.edge_lists()
    el.N = n_nodes
    el.t = t
    el.edges = edge_lists
    el.tmax = t_max
    res_sim = []
    for k in range(len(el.t)):
        t = el.t[k]
        # print('el.t[k]', el.t[k])
        # print('el.edges[k]', el.edges[k])
        for i, j in el.edges[k]:
            res_sim.append([i, j, t])
    return res_sim, el
Beispiel #5
0
import tacoma as tc
import numpy as np

print "===== edge_lists => edge_lists ====="

L = tc.edge_lists()

L.N = 3
L.t = [0.0,1.0,2.0]
L.tmax = 3.0
L.edges = [ 
            [
              (0,1)
            ],
            [
              (1,2), (0,2)
            ],
            [
              (0,1)
            ],
           ]

result = tc.measure_group_sizes_and_durations_for_edge_lists(L)

print "N_m =", result.aggregated_size_histogram
print "sum(m*N_m) =", np.dot(np.arange(0,L.N+1),result.aggregated_size_histogram), "should be N =", L.N


print "===== edge_changes => edge_lists ====="

C = tc.edge_changes()
import tacoma as tc

temporal_network = tc.edge_lists()

temporal_network.N = 8
temporal_network.t = [0., 1., 1.5, 3., 4., 7., 7.31]
temporal_network.tmax = 8.1
temporal_network.edges = [[(0, 1), (1, 7)], [(0, 1)], [(0, 1), (1, 7)],
                          [(2, 5), (1, 7)], [(2, 5)], [(0, 1), (2, 5)],
                          [(0, 1)]]
temporal_network.time_unit = 's'
temporal_network.notes = 'This experiment was conducted as a test.'
temporal_network.int_to_node = {
    0: 'Alice',
    1: 'Bob',
    2: 'Clara',
    4: 'Darren',
    5: 'Elle',
    5: 'Felicitas',
    6: 'George',
    7: 'Harriett',
}

C = tc.convert(temporal_network)

traj = tc.convert_to_edge_trajectories(C)
C2 = tc.convert_edge_trajectories(traj)

import pprint
pp = pprint.PrettyPrinter(indent=4)
from __future__ import print_function
import tacoma as tc

dyn_RGG = tc.dynamic_RGG(N=3, t_run_total=10, mean_link_duration=2.0)
test_list = tc.edge_lists(dyn_RGG)
#test_list.copy_from(dyn_RGG)

print(test_list.t, dyn_RGG.t)
print(test_list.tmax, dyn_RGG.tmax)
print(test_list.edges)
print(dyn_RGG.edges)
print(test_list.N, dyn_RGG.N)

zsbb = tc.ZSBB_model([], 3, 0.6, 0.6, 0.6, t_run_total=100)

test_list = tc.edge_changes(zsbb)

print(test_list.t, zsbb.t)
print(test_list.t0, zsbb.t0)
print(test_list.tmax, zsbb.tmax)
print(test_list.edges_in)
print(zsbb.edges_in)
print(test_list.edges_out)
print(zsbb.edges_out)
print(test_list.N, zsbb.N)
Beispiel #8
0
import matplotlib.pyplot as pl

N = 10
t_run = 10000

result = tc.dynamic_RGG(
    N=N,
    t_run_total=t_run,
    mean_link_duration=10.,
    periodic_boundary_conditions_for_link_building=False,
    record_sizes_and_durations=True,
    critical_density=1.0,
    #verbose = True)
    seed=2335)

this = tc.edge_lists(result)

second_result = tc.measure_group_sizes_and_durations_for_edge_lists(
    this,
    #verbose=True,
)

#print result.durations
#print second_result.contact_durations
#print result.size_histograms
#print second_result.size_histograms

print(("all size histograms are the same:",
       all([
           hist1 == hist2 for hist1, hist2 in zip(
               result.size_histograms, second_result.size_histograms)
Beispiel #9
0
import tacoma as tc

print("===== edge_lists => edge_lists =====")

L = tc.edge_lists()

L.N = 4
L.t = [0.0, 1.0, 2.0]
L.tmax = 3.0
L.edges = [
    [(0, 1)],
    [(1, 2), (0, 2)],
    [(0, 1)],
]

L2 = tc.edge_lists()

L2.N = 4
L2.t = [0.0, 1.0, 2.0]
L2.tmax = 3.0
L2.edges = [
    [(3, 1)],
    [(3, 2), (0, 2)],
]

new = tc.concatenate([L, L2, L])

print(new.N)
print(new.t)
print(new.tmax)
print(new.edges)
Beispiel #10
0
def download_and_convert_sociopatterns_high_school_2013(
    url="http://www.sociopatterns.org/wp-content/uploads/2015/07/High-School_data_2013.csv.gz",
    filename="~/.tacoma/hs13.taco",
):
    """Download the SocioPatterns 'High school 2013 dynamic contact network' data,
    extract it and save it as taco. This data is actually binned in intervals
    of `[t-20s, t]`.

    Parameters
    ----------
    url : :obj:`str`, optional
        The url from which the tsv-data should be retrieved
    filename : :obj:`str`, optional
        this is the path where the taco will be saved to. default : "~/.tacoma/hs13.taco"

    Returns
    -------
    edge_lists : :mod:`edge_lists`
        The temporal network of the 'High school 2013 dynamic contact network'.

    Notes
    -----

    If you use this data, please cite

    :: [HS13]
        R. Mastrandrea, J. Fournet, A. Barrat,
        Contact patterns in a high school: a comparison between data collected
        using wearable sensors, contact diaries and friendship surveys.
        PLoS ONE 10(9): e0136497 (2015)
    """

    # get directory name for download

    directory, _ = os.path.split(os.path.abspath(os.path.expanduser(filename)))
    mkdirp_customdir(directory)

    # download
    wget.download(url, out=directory)

    # open gzipped file
    gzip_file = os.path.join(directory, 'High-School_data_2013.csv.gz')
    with gzip.open(gzip_file, mode='rt') as f:
        reader = csv.reader(f, delimiter=' ')

        # mappings of nodes to integers
        node_to_int = {}
        int_to_node = {}

        # get an initial t_old
        # (this is done to detect changes in the tsv
        t_old = None

        # list of edge lists
        edges = []

        # time points
        time = []

        count = 0
        for row in reader:

            if count == 0:
                t0 = int(row[0]) - 20

            # this is to account for the interval choice [t-20s, t]
            t = float(int(row[0]) - 20 - t0)

            # if the time changed, we save the new time and
            # prepare to save new edges
            if t_old != t:
                if (t_old is not None) and (t - t_old > 20):
                    edges.append([])
                    time.append(t_old + 20)

                edges.append([])
                time.append(t)

            # get the edge
            i = int(row[1])
            j = int(row[2])

            # map the edge to integers
            if i not in node_to_int:
                this_int = len(node_to_int)
                node_to_int[i] = len(node_to_int)
                int_to_node[this_int] = str(i)

            if j not in node_to_int:
                this_int = len(node_to_int)
                node_to_int[j] = len(node_to_int)
                int_to_node[this_int] = str(j)

            # save the edge
            edges[-1].append(tuple(sorted([node_to_int[i], node_to_int[j]])))
            t_old = t

            count += 1

        N = len(node_to_int)
        tmax = time[-1] + 20.0

    # get a new `edge_lists` instance
    el = tc.edge_lists()

    el.N = N
    el.tmax = tmax
    el.edges = edges
    el.t = time
    el.time_unit = 's'
    el.notes = """
        This data is binned.

        In this data, t0 = 0.0 corresponds to UNIX time """ + str(t0) + """.

        For more info, please visit 
        http://www.sociopatterns.org/datasets/high-school-contact-and-friendship-networks/ .

        If you use this data, please cite

        R. Mastrandrea, J. Fournet, A. Barrat,
        Contact patterns in a high school: a comparison between data collected
        using wearable sensors, contact diaries and friendship surveys.
        PLoS ONE 10(9): e0136497 (2015)
        """
    el.int_to_node = int_to_node

    # verifying that this is a valid temporal network
    tc.verify(el)

    # save this edge_lists instance
    with open(os.path.abspath(os.path.expanduser(filename)), 'w') as f:
        write_json_taco(el, f)

    # remove the downloaded gzipped file
    os.remove(gzip_file)

    return el
Beispiel #11
0
def download_and_convert_sociopatterns_hypertext_2009(
    url="http://www.sociopatterns.org/files/datasets/003/ht09_contact_list.dat.gz",
    filename="~/.tacoma/ht09.taco",
):
    """Download the SocioPatterns 'Hypertext 2009 dynamic contact network' data,
    extract it and save it as taco. This data is actually binned in intervals
    of `[t-20s, t]`.

    Parameters
    ----------
    url : :obj:`str`, optional
        The url from which the tsv-data should be retrieved
    filename : :obj:`str`, optional
        this is the path where the taco will be saved to. default : "~/.tacoma/ht09.taco"

    Returns
    -------
    edge_lists : :mod:`edge_lists`
        The temporal network of the 'Hypertext 2009 dynamic contact network'.

    Notes
    -----

    If you use this data, please cite

    ::
        L. Isella et al.,  What's in a crowd? Analysis of face-to-face behavioral networks, 
        Journal of Theoretical Biology 271, 166 (2011).
    """

    # get directory name for download
    directory, _ = os.path.split(os.path.abspath(os.path.expanduser(filename)))
    mkdirp_customdir(directory)

    # download
    wget.download(url, out=directory)

    # open gzipped file
    gzip_file = os.path.join(directory, 'ht09_contact_list.dat.gz')
    with gzip.open(gzip_file, mode='rt') as f:
        reader = csv.reader(f, delimiter='\t')

        # mappings of nodes to integers
        node_to_int = {}
        int_to_node = {}

        # get an initial t_old
        # (this is done to detect changes in the tsv
        t_old = None

        # list of edge lists
        edges = []

        # time points
        time = []
        for row in reader:
            # this is to account for the interval choice [t-20s, t]
            t = float(int(row[0]) - 20)

            # if the time changed, we save the new time and
            # prepare to save new edges
            if t_old != t:
                if (t_old is not None) and (t - t_old > 20):
                    edges.append([])
                    time.append(t_old + 20)

                edges.append([])
                time.append(t)

            # get the edge
            i = int(row[1])
            j = int(row[2])

            # map the edge to integers
            if i not in node_to_int:
                this_int = len(node_to_int)
                node_to_int[i] = len(node_to_int)
                int_to_node[this_int] = str(i)

            if j not in node_to_int:
                this_int = len(node_to_int)
                node_to_int[j] = len(node_to_int)
                int_to_node[this_int] = str(j)

            # save the edge
            edges[-1].append(tuple(sorted([node_to_int[i], node_to_int[j]])))
            t_old = t

        N = len(node_to_int)
        tmax = time[-1] + 20.0

    # get a new `edge_lists` instance
    el = tc.edge_lists()

    el.N = N
    el.tmax = tmax
    el.edges = edges
    el.t = time
    el.time_unit = 's'
    el.notes = """
        This data is binned.

        In this data, t0 = 0.0 corresponds to 8am on Jun 29th 2009 (UNIX time 1246255200).

        For more info, please visit http://www.sociopatterns.org/datasets/hypertext-2009-dynamic-contact-network/ .

        If you use this data, please cite

        L. Isella et al.,  What's in a crowd? Analysis of face-to-face behavioral networks, 
        Journal of Theoretical Biology 271, 166 (2011).
        """
    el.int_to_node = int_to_node

    # verifying that this is a valid temporal network
    tc.verify(el)

    # save this edge_lists instance
    with open(os.path.abspath(os.path.expanduser(filename)), 'w') as f:
        write_json_taco(el, f)

    # remove the downloaded gzipped file
    os.remove(gzip_file)

    return el