def test_define_tnet_weighted(): tnet = teneto.TemporalNetwork(nettype='wu', timetype='discrete') if not tnet.network.shape[1] == 4: raise AssertionError() tnet = teneto.TemporalNetwork(nettype='bu') if not tnet.network.shape[1] == 3: raise AssertionError() edgelist = [[0, 1, 2, 0.5], [0, 2, 1, 0.5]] tnet_edgelist = teneto.TemporalNetwork(from_edgelist=edgelist) if not tnet_edgelist.network.shape == (2, 4): raise AssertionError() G = np.zeros([3, 3, 3]) G[[0, 0], [1, 2], [2, 1]] = 0.5 tnet_array = teneto.TemporalNetwork(from_array=G) if not all(tnet_array.network == tnet_edgelist.network): raise AssertionError() C = teneto.utils.graphlet2contact(G) tnet_dict = teneto.TemporalNetwork(from_dict=C) if not all(tnet_dict.network == tnet_edgelist.network): raise AssertionError() tnet_edgelist.add_edge([[0, 3, 1, 0.8]]) if not all(tnet_edgelist.network.iloc[-1].values == [0, 3, 1, 0.8]): raise AssertionError() if not tnet_edgelist.network.shape == (3, 4): raise AssertionError() tnet_edgelist.drop_edge([[0, 3, 1]]) if not tnet_edgelist.network.shape == (2, 4): raise AssertionError()
def test_tnet_functions(): G = np.zeros([3, 3, 3]) G[[0, 0], [1, 2], [2, 1]] = 1 G = G + G.transpose([1, 0, 2]) tnet = teneto.TemporalNetwork(from_array=G) G = teneto.utils.set_diagonal(G, 0) D = tnet.calc_networkmeasure('temporal_degree_centrality') assert all(G.sum(axis=-1).sum(axis=-1) == D) G = np.zeros([3, 3, 3]) G[[0, 0], [1, 2], [2, 1]] = 0.5 G = G + G.transpose([1, 0, 2]) G = teneto.utils.set_diagonal(G, 0) tnet = teneto.TemporalNetwork(from_array=G) D = tnet.calc_networkmeasure('temporal_degree_centrality') assert all(G.sum(axis=-1).sum(axis=-1) == D)
def test_tnet_functions(): array = np.zeros([3, 3, 3]) array[[0, 0], [1, 2], [2, 1]] = 1 array = array + array.transpose([1, 0, 2]) tnet = teneto.TemporalNetwork(from_array=array) array = teneto.utils.set_diagonal(array, 0) degree = tnet.calc_networkmeasure('temporal_degree_centrality') if not all(array.sum(axis=-1).sum(axis=-1) == degree): raise AssertionError() array = np.zeros([3, 3, 3]) array[[0, 0], [1, 2], [2, 1]] = 0.5 array = array + array.transpose([1, 0, 2]) array = teneto.utils.set_diagonal(array, 0) tnet = teneto.TemporalNetwork(from_array=array) degree = tnet.calc_networkmeasure('temporal_degree_centrality') if not all(array.sum(axis=-1).sum(axis=-1) == degree): raise AssertionError()
def from_numpy_array(_class, array, node_ids_to_names=None): """Create a TemporalNetwork from an array representation of the network Parameters __________ array - a numpy.array with dimensions (nodes, nodes, time) node_ids_to_names - a dictionary whose keys (integers) are node IDs and values (of any type) are more descriptive names for nodes. """ teneto_network = teneto.TemporalNetwork(from_array=array) return _class(teneto_network, node_ids_to_names=node_ids_to_names)
def test_define_tnet_unweighted(): tnet = teneto.TemporalNetwork(nettype='wu', timetype='discrete') if not tnet.network.shape[1] == 4: raise AssertionError() tnet = teneto.TemporalNetwork(nettype='bu') if not tnet.network.shape[1] == 3: raise AssertionError() edgelist = [[0, 1, 2], [0, 2, 1]] tnet_edgelist = teneto.TemporalNetwork(from_edgelist=edgelist) if not tnet_edgelist.network.shape == (2, 3): raise AssertionError() array = np.zeros([3, 3, 3]) array[[0, 0], [1, 2], [2, 1]] = 1 tnet_array = teneto.TemporalNetwork(from_array=array) if not all(tnet_array.network == tnet_edgelist.network): raise AssertionError() tnet_df = teneto.TemporalNetwork(from_df=tnet_array.network) if not all(tnet_array.network == tnet_df.network): raise AssertionError() contact = teneto.utils.graphlet2contact(array) tnet_dict = teneto.TemporalNetwork(from_dict=contact) if not all(tnet_dict.network == tnet_edgelist.network): raise AssertionError() tnet_edgelist.add_edge([[0, 3, 1]]) if not all(tnet_edgelist.network.iloc[-1].values == [0, 3, 1]): raise AssertionError() if not tnet_edgelist.network.shape == (3, 3): raise AssertionError() tnet_edgelist.add_edge([0, 3, 1]) if not all(tnet_edgelist.network.iloc[-1].values == [0, 3, 1]): raise AssertionError() tnet_edgelist.drop_edge([0, 3, 1]) if not tnet_edgelist.network.shape == (2, 3): raise AssertionError()
def test_process_input(): tnet = teneto.TemporalNetwork() tnet.generatenetwork('rand_binomial', prob=[0.5, 0.2], size=[5, 12]) G = tnet.to_array() tnet2 = teneto.utils.process_input(G, 'G', 'TN') assert all(tnet2.network == tnet.network) C = teneto.utils.process_input(G, 'G', 'C') tnet3 = teneto.utils.process_input(C, 'C', 'TN') assert all(tnet2.network == tnet3.network) C2 = teneto.utils.process_input(tnet, 'TN', 'C') G2, _ = teneto.utils.process_input(tnet, 'TN', 'G') assert (C['contacts'] == C2['contacts']).all() assert (G == G2).all()
def test_hdf5(): df = pd.DataFrame({'i': [0, 0], 'j': [1, 2], 't': [0, 1]}) tnet = teneto.TemporalNetwork(from_df=df, hdf5=True) if not tnet.network == './teneto_temporalnetwork.h5': raise AssertionError() df2 = pd.read_hdf('./teneto_temporalnetwork.h5') if not (df == df2).all().all(): raise AssertionError() tnet.add_edge([0, 2, 2]) df3 = pd.read_hdf('./teneto_temporalnetwork.h5') if not (df3.iloc[2].values == [0, 2, 2]).all(): raise AssertionError() tnet.drop_edge([0, 2, 2]) df4 = pd.read_hdf('./teneto_temporalnetwork.h5') if not (df == df4).all().all(): raise AssertionError()
def test_metadata(): tnet = teneto.TemporalNetwork(nodelabels=['A', 'B', 'C'], timelabels=[0, 1, 2], desc='test meta data', starttime=0, timeunit='au') if not tnet.nodelabels == ['A', 'B', 'C']: raise AssertionError() if not tnet.timelabels == [0, 1, 2]: raise AssertionError() if not tnet.starttime == 0: raise AssertionError() if not tnet.desc == 'test meta data': raise AssertionError() if not tnet.timeunit == 'au': raise AssertionError()
def from_edge_list_dataframe(_class, edges, normalise=None, threshold=0, binary=False): """Create a TemporalNetwork from a DataFrame of edges over time Parameters __________ edges - a pandas.DataFrame with columns representing source node, target node, time and (optionally) weight normalise - a value determining what (if any) normalisation is applied. If 'normalise' is 'global', all weights will be divided through by the max weight across all edges. If 'normalise' is 'local', all weights corresponding to an edge (i,j) at some time will be divided through by the max weight of the edge (i,j) across all times. To skip normalisation, set to None. threshold - any edges with weight < 'threshold' (after normalising) will not be included in the temporal network binary - if True, all positive weights (after thresholding) will be set to 1. If False, does nothing. """ number_of_columns = edges.shape[1] if number_of_columns == 3: edges['weight'] = 1 elif number_of_columns != 4: raise ValueError('Edge list requires either 3 or 4 columns') edges.columns = ['i', 'j', 't', 'weight'] if normalise == 'global': min_weight = edges['weight'].min() difference = edges['weight'].max() - min_weight edges['weight'] = (edges['weight'] - min_weight) / difference if normalise == 'local': # Sort first two columns; we only care about *unordered* pairs (i,j), not ordered pairs. edges[['i', 'j']] = np.sort(edges[['i', 'j']], axis=1) grouped = edges.groupby(['i', 'j'])['weight'] maxes = grouped.transform('max') mins = grouped.transform('min') edges['weight'] = (edges['weight'] - mins) / (maxes - mins) # In cases where max = min we'll have a division by zero error. edges['weight'] = edges['weight'].fillna(0.5) edges = edges[edges['weight'] >= threshold] if binary: edges.loc[edges['weight'] > 0, 'weight'] = 1 edges, ids_to_names = replace_nodes_with_ids(edges) edges = edges.sort_values('t') start_time = edges['t'].iloc[0] if start_time != 0: # For compatibility with teneto, shift all times so that we start at time 0 edges['t'] -= start_time teneto_network = teneto.TemporalNetwork(from_df=edges) return _class(teneto_network, start_time, ids_to_names)
def test_hdf5_getnetwokwhen(): df = pd.DataFrame({'i': [0, 1], 'j': [1, 2], 't': [0, 1]}) tnet = teneto.TemporalNetwork(from_df=df, hdf5=True) dfcheck = tnet.get_network_when(i=0) if not (dfcheck.values == [0, 1, 0]).all(): raise AssertionError() dfcheck = tnet.get_network_when(i=0, j=1, t=0, logic='and') if not (dfcheck.values == [0, 1, 0]).all(): raise AssertionError() dfcheck = tnet.get_network_when(i=0, j=1, t=1, logic='or') if not (dfcheck.values == [[0, 1, 0], [1, 2, 1]]).all(): raise AssertionError() dfcheck = tnet.get_network_when(t=0) if not (dfcheck.values == [0, 1, 0]).all(): raise AssertionError() dfcheck = tnet.get_network_when(ij=1) if not (dfcheck.values == [[0, 1, 0], [1, 2, 1]]).all(): raise AssertionError()
def discrete_time_simulation(n_nodes, n_times, prob, simProcess, ncontacts, lam, nettype): tnet = teneto.TemporalNetwork(timetype='discrete') if simProcess == 'rand_binomial': tnet.generatenetwork(simProcess, size=(n_nodes, n_nodes, n_times), nettype=nettype, prob=prob, netrep='graphlet') elif simProcess == 'rand_poisson': tnet.generatenetwork(simProcess, nnodes=n_nodes, ncontacts=ncontacts, nettype=nettype, lam=lam, netrep='graphlet') else: raise Exception('simulation method do not supported!') return tnet
def test_process_input(): tnet = teneto.TemporalNetwork() tnet.generatenetwork('rand_binomial', prob=[0.5, 0.2], size=[5, 12]) G = tnet.network tnet2 = teneto.utils.process_input(G, 'G', 'TN') if not np.all(tnet2.network == tnet.network): raise AssertionError() C = teneto.utils.process_input(G, 'G', 'C') tnet3 = teneto.utils.process_input(C, 'C', 'TN') # Note TN>G>C>TN will fail if first time-point is all 0s. # This is because G>C changes starttime to 1. # Thus, must set start_at to zero in function below to not get error. if not np.all(tnet2.network == tnet3.df_to_array(start_at='zero')): raise AssertionError() C2 = teneto.utils.process_input(tnet, 'TN', 'C') G2, _ = teneto.utils.process_input(tnet, 'TN', 'G') if not (C['contacts'] == C2['contacts']).all(): raise AssertionError() if not (G == G2).all(): raise AssertionError()
def test_define_tnet_unweighted(): tnet = teneto.TemporalNetwork(nettype='wu', timetype='discrete') assert tnet.network.shape[1] == 4 tnet = teneto.TemporalNetwork(nettype='bu') assert tnet.network.shape[1] == 3 edgelist = [[0, 1, 2], [0, 2, 1]] tnet_edgelist = teneto.TemporalNetwork(from_edgelist=edgelist) assert tnet_edgelist.network.shape == (2, 3) G = np.zeros([3, 3, 3]) G[[0, 0], [1, 2], [2, 1]] = 1 tnet_array = teneto.TemporalNetwork(from_array=G) assert all(tnet_array.network == tnet_edgelist.network) tnet_df = teneto.TemporalNetwork(from_df=tnet_array.network) assert all(tnet_array.network == tnet_df.network) C = teneto.utils.graphlet2contact(G) tnet_dict = teneto.TemporalNetwork(from_dict=C) assert all(tnet_dict.network == tnet_edgelist.network) tnet_edgelist.add_edge([[0, 3, 1]]) assert all(tnet_edgelist.network.iloc[-1].values == [0, 3, 1]) assert tnet_edgelist.network.shape == (3, 3) tnet_edgelist.add_edge([0, 3, 1]) assert all(tnet_edgelist.network.iloc[-1].values == [0, 3, 1]) tnet_edgelist.drop_edge([0, 3, 1]) assert tnet_edgelist.network.shape == (2, 3)
def process_input(netin, allowedformats, outputformat='G', forcesparse=False): """ Takes input network and checks what the input is. Parameters ---------- netin : array, dict, or teneto.TemporalNetwork Network (graphlet, contact or object) allowedformats : list or str Which format of network objects that are allowed. Options: 'C', 'TN', 'G'. outputformat: str, default=G Target output format. Options: 'C' or 'G'. Returns ------- C : dict OR tnet : array Graphlet representation. netinfo : dict Metainformation about network. OR tnet : object object of teneto.TemporalNetwork class """ netinfo = {} if outputformat == 'DF': outputformat = 'TN' return_df = True forcesparse = True else: return_df = False inputtype = check_input(netin) if inputtype == 'DF': netin = teneto.TemporalNetwork(from_df=netin) inputtype = 'TN' # Convert TN to tnet representation if inputtype == 'TN' and 'TN' in allowedformats and outputformat != 'TN': if netin.sparse: tnet = netin.df_to_array() else: tnet = netin.network netinfo = { 'nettype': netin.nettype, 'netshape': [netin.netshape[0], netin.netshape[0], netin.netshape[1]] } elif inputtype == 'TN' and 'TN' in allowedformats and outputformat == 'TN': if not netin.sparse and forcesparse: tnet = teneto.TemporalNetwork(from_array=netin.network, forcesparse=True) else: tnet = netin elif inputtype == 'C' and 'C' in allowedformats and outputformat == 'G': tnet = contact2graphlet(netin) netinfo = dict(netin) netinfo.pop('contacts') elif inputtype == 'C' and 'C' in allowedformats and outputformat == 'TN': tnet = teneto.TemporalNetwork(from_dict=netin) elif inputtype == 'G' and 'G' in allowedformats and outputformat == 'TN': tnet = teneto.TemporalNetwork(from_array=netin, forcesparse=forcesparse) # Get network type if not set yet elif inputtype == 'G' and 'G' in allowedformats: netinfo = {} netinfo['netshape'] = netin.shape netinfo['nettype'] = gen_nettype(netin) tnet = netin elif inputtype == 'C' and outputformat == 'C': pass else: raise ValueError('Input invalid.') if outputformat == 'TN' and isinstance(tnet.network, pd.DataFrame): tnet.network['i'] = tnet.network['i'].astype(int) tnet.network['j'] = tnet.network['j'].astype(int) tnet.network['t'] = tnet.network['t'].astype(int) if outputformat == 'C' or outputformat == 'G': netinfo['inputtype'] = inputtype if inputtype != 'C' and outputformat == 'C': return graphlet2contact(tnet, netinfo) if outputformat == 'G': return tnet, netinfo elif outputformat == 'C': return netin elif outputformat == 'TN': if return_df: return tnet.network else: return tnet
def test_errors(): # Make sure that only 1 of three different input methods is specified with pytest.raises(ValueError): teneto.TemporalNetwork(from_dict={}, from_array=np.zeros([2, 2])) # Make sure error raised from_array if not a numpy array with pytest.raises(ValueError): teneto.TemporalNetwork(from_array=[1, 2, 3]) with pytest.raises(ValueError): teneto.TemporalNetwork(from_array=np.array([2])) # Make sure error raised from_dict if not a dictionary with pytest.raises(ValueError): teneto.TemporalNetwork(from_dict=[1, 2, 3]) with pytest.raises(ValueError): teneto.TemporalNetwork(from_dict={}) # Make sure error raised edge_list if not a list of lists with pytest.raises(ValueError): teneto.TemporalNetwork(from_edgelist='1,2,3') with pytest.raises(ValueError): teneto.TemporalNetwork(from_edgelist=[[0, 1], [0, 1, 2, 3]]) # Make sure error raised df is not pandas with pytest.raises(ValueError): teneto.TemporalNetwork(from_df={}) with pytest.raises(ValueError): df = pd.DataFrame({'i': [1, 2], 'j': [0, 1]}) teneto.TemporalNetwork(from_df=df) # Make sure error raised when nettype is wrong with pytest.raises(ValueError): teneto.TemporalNetwork(nettype='s') with pytest.raises(ValueError): teneto.TemporalNetwork(timetype='s') with pytest.raises(ValueError): teneto.TemporalNetwork(N='s') with pytest.raises(ValueError): teneto.TemporalNetwork(T='s') edgelist = [[0, 1, 2, 0.5], [0, 2, 1, 0.5]] tnet = teneto.TemporalNetwork(from_edgelist=edgelist) with pytest.raises(ValueError): tnet.calc_networkmeasure('skmdla') with pytest.raises(ValueError): tnet.generatenetwork('skmdla') with pytest.raises(ValueError): tnet.plot('skmdla') with pytest.raises(ValueError): tnet._check_input(datain=edgelist, datatype='skmdla')
def test_plot(): tnet = teneto.TemporalNetwork() tnet.generatenetwork('rand_binomial', size=(5, 10), prob=1) tnet.plot('graphlet_stack_plot')
def test_generatenetwork(): tnet = teneto.TemporalNetwork() tnet.generatenetwork('rand_binomial', size=(5, 10), prob=1) assert tnet.netshape == (5, 10)
def test_generatenetwork(): tnet = teneto.TemporalNetwork() tnet.generatenetwork('rand_binomial', size=(5, 10), prob=1) if not tnet.netshape == (5, 10): raise AssertionError()