multisplit
[iramuteq] / graph_to_json.py
1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2008-2020 Pierre Ratinaud
4 #modification pour python 3 : Laurent Mérat, 6x7 - mai 2020
5 #License: GNU/GPL
6
7 #------------------------------------
8 # import des modules python
9 #------------------------------------
10 import codecs
11 import os
12 import json
13 from random import randint
14
15
16 class GraphToJson :
17     def __init__(self, nodesfile, edgesfile, jsonout, parametres = {}):
18
19         with codecs.open(edgesfile, 'r', 'utf8') as f :
20             content = f.read()
21         content = content.replace('"', '')
22         content = content.splitlines()
23         try :
24             titles_edges = content.pop(0)
25             titles_edges = titles_edges.split('\t')
26             edges = [line.split('\t') for line in content]
27         except :
28             edges = None
29             
30         with codecs.open(nodesfile, 'r', 'utf8') as f :
31             content = f.read()
32         content = content.replace('"','')
33         content = content.splitlines()
34         titles = content.pop(0)
35         titles = titles.split('\t')
36         #titles.insert(0,'')
37
38         xr = titles.index('x')
39         yr = titles.index('y')
40         try :
41             zr = titles.index('z')
42         except :
43             zr = None
44         wr = titles.index('weight')
45         try :
46             r = titles.index('r')
47             g = titles.index('g')
48             b = titles.index('b')
49         except :
50             r = None
51         ni = titles.index('name')
52
53         nodes = [line.split('\t') for line in content]
54
55         graph = {'edges': [], 'nodes' : {}}
56         
57         we = titles_edges.index('weight')
58         if edges is not None :
59             for edge in edges :
60                 graph['edges'].append({'source' : edge[0], 'target' : edge[1], 'weight' : edge[we]})
61         
62         
63         coefcoord = parametres.get('coefcoord', 1)
64         coefweight = parametres.get('coefweight', 1)
65         
66         
67         for node in nodes :
68             if zr is not None :
69                 graph['nodes'][node[ni]] = {"location" : [float(node[xr])*coefcoord, float(node[yr])*coefcoord, float(node[zr])*coefcoord], 'weight' : float(node[wr])/coefweight, 'color': (int(node[r]),int(node[g]),int(node[b]))}
70             else :
71                 x = parametres.get('randomx', 0)
72                 if x :
73                     x = randint(-150,150)
74                 graph['nodes'][node[ni]] = {"location" : [ x, float(node[xr]), float(node[yr])], 'weight' : float(node[wr]), 'color': (int(node[r]),int(node[g]),int(node[b]))}
75
76         with open(jsonout, 'w') as f :
77             json.dump(graph, f)