-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbuild_chord.py
161 lines (136 loc) · 6.16 KB
/
build_chord.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 30 09:20:49 2018
@author: gjacopo
"""
#%%
from __future__ import print_function
import os, re#analysis:ignore
import warnings
from operator import itemgetter
try:
import numpy as np#analysis:ignore
except ImportError:
raise IOError("Package numpy not imported - Requested")
try:
import pandas as pd
PDVERS = int(pd.__version__.split('.')[1])
except ImportError:
PDVERS = 0 # unknown
raise IOError("Package pandas not imported - Requested")
try:
import networkx as nx
except ImportError:
raise IOError("Package networkx not imported - Requested")
try:
import json
except:
try:
import simplejson as json#analysis:ignore
except:
warnings.warn("Package simplejson/json not imported")
import metadata
#%%
#==============================================================================
# CHORD FUNCTIONS
#==============================================================================
def __filedirexists(file):
return os.path.exists(os.path.abspath(os.path.dirname(file)))
def data2adjacency(df):
df_unique = df.drop_duplicates([metadata.INDICATOR, metadata.DIMENSION])
# df_test = df_unique.pivot(index='indicator', columns='dimension', values='label')
df_unique.drop(columns=metadata.LABEL)
df_cross = pd.crosstab(df_unique[metadata.INDICATOR], df_unique[metadata.DIMENSION])
df_cross['dumb'] = 0
df_cross = df_cross.T
df_cross['dumber'] = 0
df_cross.loc['dumb','dumber'] = -1
df_crossT = df_cross
df_cross = df_crossT.T
# note that at this stage, indicators and dimensions are reordered
#a dimensions, indicators = df_cross.index.tolist(), df_cross.columns.tolist()
indicators, dimensions = df_cross.index.tolist(), df_cross.columns.tolist()
# df_crossT = df_cross.T
#idx = indicators + dimensions
idx = dimensions + indicators
df_cross = df_cross.reindex(index = idx, columns = idx, fill_value=0)
df_crossT = df_crossT.reindex(index = idx, columns = idx, fill_value=0)
return [dimensions, indicators, pd.DataFrame(df_cross.values | df_crossT.values, index = idx, columns = idx)]
# note: df_cross | df_crossT generates a NotImplementedError error type
def meta2cross(df, cross=None):
idx = {0: [], 1: []}
if not cross in ([],None):
if not isinstance(cross, (list,tuple)) or len(cross)!=2:
cross = [cross,]
for i in [0,1]:
if cross[i] in ([],None): break
regexp = '|'.join(cross[i])
_idx = df.loc[df[metadata.INDICATOR].str.contains(regexp, regex=True)].index.tolist()
idx[i] = idx[i] + _idx
if not all([_idx in ([],None) for _idx in idx.values()]):
index = idx[0] + idx[1]
else:
idx[0] = idx[1] = df.index
index = df.index
## two rounds of drop_duplicates to keep only non-unique (DIMENSION,LABEL) pairs
#df1 = df.drop_duplicates(subset=[metabase.DIMENSION, metabase.LABEL])
#df2 = df.loc[(df.index).difference(df1.index)]
#uni_index = df2.drop_duplicates(subset=[metabase.DIMENSION, metabase.LABEL]).index
## note also:
#df_group = df.groupby(by=[metabase.DIMENSION, metabase.LABEL])
#df_dimlab = df_group.count()
## keep only non-unique (DIMENSION,LABEL) pairs
#df_dimlab = df_dimlab[df_dimlab[metabase.INDICATOR] > 1]
df_cross = pd.pivot_table(df, index=[metadata.DIMENSION, metadata.LABEL], columns=[metadata.INDICATOR], aggfunc=len, fill_value=0)
df_cross = df_cross.T.dot(df_cross)
# # alternative solution
# df['value'] = 1
# df1 = pd.pivot_table(df, index=[metabase.DIMENSION, metabase.LABEL], values='value', columns=metabase.INDICATOR, fill_value=0)
np.fill_diagonal(df_cross.values, 0)
#s = df_cross.sum(axis=0)
#index = s[s != 0].index.tolist()
df_cross.reindex(index = index, columns = index, fill_value=0)
return [df.ix[pd.Index(idx[0]),metadata.INDICATOR].unique().tolist(),
df.ix[pd.Index(idx[1]),metadata.INDICATOR].unique().tolist(),
df_cross]
def adjacency2edges(df, ind0, ind1):
#g = nx.from_pandas_adjacency(df.loc[ind0].T.loc[ind1].T)
# adjacency matrix needs to be square
df_adj = df.copy()
df_adj.loc[ind0] = 0
df_adj = df_adj.T
df_adj.loc[pd.Index(ind1)] = 0
df_adj = df_adj.T
g = nx.from_pandas_adjacency(df_adj)
edges = sorted([(s, t, w['weight']) for (s, t, w) in g.edges(data=True)], key=itemgetter(2), reverse=True)
df_edges = pd.DataFrame(edges, columns=("source","target","value"))
return df_edges
def adjacency2json(df_adjacency, **kwargs):
dimensions, indicators = kwargs.pop('dim',[]), kwargs.pop('ind',[])
odir, ofmt = kwargs.pop('odir','.'), kwargs.pop('ofmt','json')
oifn, odfn = kwargs.pop('oifn', metadata.INDICATOR), kwargs.pop('odfn', metadata.DIMENSION)
oixdfn = kwargs.pop('oixdfn','%sx%s' % (metadata.INDICATOR, metadata.DIMENSION))
ofn = '%s/%s.%s' % (odir, oixdfn, ofmt)
if __filedirexists(ofn):
with open(ofn, 'w') as f:
#s = str(df_adjacency.values.tolist())
#f.write('var matrix = %s;' % s.replace('-1','emptyStroke'))
f.write('var matrix = %s;' % df_adjacency.values.tolist())
#df_adjacency.to_json('%s/%s.%s' % (odir, oixdfn, ofmt), orient='split')
#with open('%s/%s.%s' % (odir, oixdfn, ofmt), 'w') as f:
# json.dump(df_adjacency.values.tolist())
ofn = '%s/%s.%s' % (odir, odfn, ofmt)
if __filedirexists(ofn) and dimensions is not None:
with open(ofn, 'w') as f:
# json.dump('var %s = %s;' % (DIMENSION,dimensions), f)
s = str(dimensions)
#a: f.write('var Dimension = %s;' % s.replace('dumber',''))
f.write('var Dimension = %s;' % s.replace('dumb',''))
ofn = '%s/%s.%s' % (odir, oifn, ofmt)
if __filedirexists(ofn) and indicators is not None:
with open(ofn, 'w') as f:
# json.dump({INDICATOR:indicators}, f)
s = str(indicators)
# a: f.write('var Indicator = %s;' % s.replace('dumb',''))
f.write('var Indicator = %s;' % s.replace('dumber',''))