repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
houghnet
houghnet-master/src/lib/utils/ddd_utils.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import cv2 def compute_box_3d(dim, location, rotation_y): # dim: 3 # location: 3 # rotation_y: 1 # return: 8 x 3 c, s = np.cos(rotation_y), np.sin(rotation_y) R = np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]], dtype=np.float32) l, w, h = dim[2], dim[1], dim[0] x_corners = [l/2, l/2, -l/2, -l/2, l/2, l/2, -l/2, -l/2] y_corners = [0,0,0,0,-h,-h,-h,-h] z_corners = [w/2, -w/2, -w/2, w/2, w/2, -w/2, -w/2, w/2] corners = np.array([x_corners, y_corners, z_corners], dtype=np.float32) corners_3d = np.dot(R, corners) corners_3d = corners_3d + np.array(location, dtype=np.float32).reshape(3, 1) return corners_3d.transpose(1, 0) def project_to_image(pts_3d, P): # pts_3d: n x 3 # P: 3 x 4 # return: n x 2 pts_3d_homo = np.concatenate( [pts_3d, np.ones((pts_3d.shape[0], 1), dtype=np.float32)], axis=1) pts_2d = np.dot(P, pts_3d_homo.transpose(1, 0)).transpose(1, 0) pts_2d = pts_2d[:, :2] / pts_2d[:, 2:] # import pdb; pdb.set_trace() return pts_2d def compute_orientation_3d(dim, location, rotation_y): # dim: 3 # location: 3 # rotation_y: 1 # return: 2 x 3 c, s = np.cos(rotation_y), np.sin(rotation_y) R = np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]], dtype=np.float32) orientation_3d = np.array([[0, dim[2]], [0, 0], [0, 0]], dtype=np.float32) orientation_3d = np.dot(R, orientation_3d) orientation_3d = orientation_3d + \ np.array(location, dtype=np.float32).reshape(3, 1) return orientation_3d.transpose(1, 0) def draw_box_3d(image, corners, c=(0, 0, 255)): face_idx = [[0,1,5,4], [1,2,6, 5], [2,3,7,6], [3,0,4,7]] for ind_f in range(3, -1, -1): f = face_idx[ind_f] for j in range(4): cv2.line(image, (corners[f[j], 0], corners[f[j], 1]), (corners[f[(j+1)%4], 0], corners[f[(j+1)%4], 1]), c, 2, lineType=cv2.LINE_AA) if ind_f == 0: cv2.line(image, (corners[f[0], 0], corners[f[0], 1]), (corners[f[2], 0], corners[f[2], 1]), c, 1, lineType=cv2.LINE_AA) cv2.line(image, (corners[f[1], 0], corners[f[1], 1]), (corners[f[3], 0], corners[f[3], 1]), c, 1, lineType=cv2.LINE_AA) return image def unproject_2d_to_3d(pt_2d, depth, P): # pts_2d: 2 # depth: 1 # P: 3 x 4 # return: 3 z = depth - P[2, 3] x = (pt_2d[0] * depth - P[0, 3] - P[0, 2] * z) / P[0, 0] y = (pt_2d[1] * depth - P[1, 3] - P[1, 2] * z) / P[1, 1] pt_3d = np.array([x, y, z], dtype=np.float32) return pt_3d def alpha2rot_y(alpha, x, cx, fx): """ Get rotation_y by alpha + theta - 180 alpha : Observation angle of object, ranging [-pi..pi] x : Object center x to the camera center (x-W/2), in pixels rotation_y : Rotation ry around Y-axis in camera coordinates [-pi..pi] """ rot_y = alpha + np.arctan2(x - cx, fx) if rot_y > np.pi: rot_y -= 2 * np.pi if rot_y < -np.pi: rot_y += 2 * np.pi return rot_y def rot_y2alpha(rot_y, x, cx, fx): """ Get rotation_y by alpha + theta - 180 alpha : Observation angle of object, ranging [-pi..pi] x : Object center x to the camera center (x-W/2), in pixels rotation_y : Rotation ry around Y-axis in camera coordinates [-pi..pi] """ alpha = rot_y - np.arctan2(x - cx, fx) if alpha > np.pi: alpha -= 2 * np.pi if alpha < -np.pi: alpha += 2 * np.pi return alpha def ddd2locrot(center, alpha, dim, depth, calib): # single image locations = unproject_2d_to_3d(center, depth, calib) locations[1] += dim[0] / 2 rotation_y = alpha2rot_y(alpha, center[0], calib[0, 2], calib[0, 0]) return locations, rotation_y def project_3d_bbox(location, dim, rotation_y, calib): box_3d = compute_box_3d(dim, location, rotation_y) box_2d = project_to_image(box_3d, calib) return box_2d if __name__ == '__main__': calib = np.array( [[7.070493000000e+02, 0.000000000000e+00, 6.040814000000e+02, 4.575831000000e+01], [0.000000000000e+00, 7.070493000000e+02, 1.805066000000e+02, -3.454157000000e-01], [0.000000000000e+00, 0.000000000000e+00, 1.000000000000e+00, 4.981016000000e-03]], dtype=np.float32) alpha = -0.20 tl = np.array([712.40, 143.00], dtype=np.float32) br = np.array([810.73, 307.92], dtype=np.float32) ct = (tl + br) / 2 rotation_y = 0.01 print('alpha2rot_y', alpha2rot_y(alpha, ct[0], calib[0, 2], calib[0, 0])) print('rotation_y', rotation_y)
4,548
33.725191
92
py
mlgd
mlgd-master/layout_quality_measurement/neigh_pres_test.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import neighbors_preservation as np s_path = sys.argv[1] g_path = sys.argv[2] outputTxtFile = sys.argv[3] input_file_name = os.path.basename(s_path) graph_name = input_file_name.split(".")[0] S = nx_read_dot(s_path) G = nx_read_dot(g_path) G=sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[0] S_induced = nx.Graph(G.subgraph(S)) np_val_S = np.compute_neig_preservation(S) np_val_SG = np.compute_neig_preservation(S, G) np_val_SGI = np.compute_neig_preservation(S, S_induced) output_txt = "Metrics for " + graph_name + "\n" output_txt += "np_S:" + str(np_val_S) + "\n" output_txt += "np_SG:" + str(np_val_SG) + "\n" output_txt += "np_SGI:" + str(np_val_SGI) + "\n" print(output_txt) csv_head_line = "filename;np;np(induced);np(complete)\n" csv_line = graph_name+";"+ str(np_val_S) + ";" + str(np_val_SGI) + ";" + str(np_val_SG) + "\n" exists = os.path.isfile(outputTxtFile) if not exists: fh = open(outputTxtFile, 'w') fh.write(csv_head_line) fh = open(outputTxtFile, 'a') fh.write(csv_line)
1,265
20.827586
95
py
mlgd
mlgd-master/layout_quality_measurement/crossings.py
#Author #Felice De Luca #https://github.com/felicedeluca # import math import networkx as nx label_factor_magnifier = 72 # Given three colinear points p, q, r, the function checks if # point q lies on line segment 'pr' def onSegment(px, py, qx, qy, rx, ry): if (qx <= max(px, rx) and qx >= min(px, rx) and qy <= max(py, ry) and qy >= min(py, ry)): return True return False def strictlyOnSegment(px, py, qx, qy, rx, ry): if (qx < max(px, rx) and qx > min(px, rx) and qy < max(py, ry) and qy > min(py, ry)): intersection_point = (qx, qy) return (True, intersection_point) return (False, None) # To find orientation of ordered triplet (p, q, r). # The function returns following values # 0 --> p, q and r are colinear # 1 --> Clockwise # 2 --> Counterclockwise def orientation(px, py, qx, qy, rx, ry): # See http://www.geeksforgeeks.org/orientation-3-ordered-points/ # for details of below formula. val = (qy - py) * (rx - qx) - (qx - px) * (ry - qy) if (val == 0):return 0 # clock or counterclock wise if (val > 0): return 1 return 2 def yInt(x1, y1, x2, y2): if (y1 == y2):return y1 return y1 - slope(x1, y1, x2, y2) * x1 def slope(x1, y1, x2, y2): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)) if (x1 == x2):return False return (y1 - y2) / (x1 - x2) # The main function that returns true if line segment 'p1q1' # and 'p2q2' intersect. def doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): # Find the four orientations needed for general and # special cases o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y) o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y) o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y) o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y) #if(o1==0 or o2==0 or o3==0 or o4==0):return False # General case if (o1 != o2 and o3 != o4): intersection_point = compute_intersection_point(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) return (True, intersection_point) # Special Cases # p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 and onSegment(p1x, p1y, p2x, p2y, q1x, q1y)): intersection_point = (p2x, p2y) return (True, intersection_point) # p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 and onSegment(p1x, p1y, q2x, q2y, q1x, q1y)): intersection_point = (q2x, q2y) return (True, intersection_point) # p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 and onSegment(p2x, p2y, p1x, p1y, q2x, q2y)): intersection_point = (p1x, p1y) return (True, intersection_point) # p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 and onSegment(p2x, p2y, q1x, q1y, q2x, q2y)): intersection_point = (q1x, q1y) return (True, intersection_point) return (False, None) # Doesn't fall in any of the above cases def isSameCoord(x1, y1, x2, y2): if x1==x2 and y1==y2: return True return False # do p is an end point of edge (u,v) def isEndPoint(ux, uy, vx, vy, px, py): if isSameCoord(ux, uy, px, py) or isSameCoord(vx, vy, px, py): return True return False # is (p1,q1) is adjacent to (p2,q2)? def areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isEndPoint(p1x, p1y, q1x, q1y, p2x, p2y): return True elif isEndPoint(p1x, p1y, q1x, q1y, q2x, q2y): return True return False def isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): x1 = p1x-q1x y1 = p1y-q1y x2 = p2x-q2x y2 = p2y-q2y cross_prod_value = x1*y2 - x2*y1 if cross_prod_value==0: return True return False # here p1q1 is one segment, and p2q2 is another # this function checks first whether there is a shared vertex # then it checks whether they are colinear # finally it checks the segment intersection def doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): (intersection_exists, intersection_point) = strictlyOnSegment(p1x, p1y, p2x, p2y, q1x, q1y) if intersection_exists: return (intersection_exists, intersection_point) (intersection_exists, intersection_point) = strictlyOnSegment(p1x, p1y, q2x, q2y, q1x, q1y) if intersection_exists: return (intersection_exists, intersection_point) (intersection_exists, intersection_point) = strictlyOnSegment(p2x, p2y, p1x, p1y, q2x, q2y) if intersection_exists: return (intersection_exists, intersection_point) (intersection_exists, intersection_point) = strictlyOnSegment(p2x, p2y, q1x, q1y, q2x, q2y) if intersection_exists: return (intersection_exists, intersection_point) else: return (False, None) else: return (False, None) return doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) def getIntersection(x11, y11, x12, y12, x21, y21, x22, y22): slope1 = 0 slope2 = 0 yint1 = 0 yint2 = 0 intx = 0 inty = 0 if (x11 == x21 and y11 == y21):return [x11, y11] if (x12 == x22 and y12 == y22):return [x12, y22] # Check 1st point of edge 1 with 2nd point of edge 2 and viceversa slope1 = slope(x11, y11, x12, y12) slope2 = slope(x21, y21, x22, y22) #print('slope1:'+str(slope1)) #print('slope2:'+str(slope2)) if (slope1 == slope2):return False yint1 = yInt(x11, y11, x12, y12) yint2 = yInt(x21, y21, x22, y22) #print('yint1:'+str(yint1)) #print('yint2:'+str(yint2)) if (yint1 == yint2): if (yint1 == False):return False else:return [0, yint1] if(x11 == x12):return [x11, slope2*x11+yint2] if(x21 == x22):return [x21, slope1*x21+yint1] if(y11 == y12):return [(y11-yint2)/slope2,y11] if(y21 == y22):return [(y21-yint1)/slope1,y21] if (slope1 == False):return [y21, slope2 * y21 + yint2] if (slope2 == False):return [y11, slope1 * y11 + yint1] intx = (yint1 - yint2)/ (slope2-slope1) return [intx, slope1 * intx + yint1] def to_deg(rad): return rad*180/math.pi # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSegDegree(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) #return angle return to_deg(angle) # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSeg(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) return angle def compute_intersection_point(x_1, y_1, x_2, y_2, x_3, y_3, x_4, y_4): ''' Computes the intersection point Note that the intersection point is for the infinitely long lines defined by the points, and can produce an intersection point beyond the lengths of the line segments but here we know that there is an intersection, and it is unique. ''' den_intersection = (x_1 - x_2)*(y_3 - y_4) - (y_1 - y_2)*(x_3 - x_4) num_intersection_x = (x_1*y_2-y_1*x_2)*(x_3-x_4)-(x_1-x_2)*(x_3*y_4-y_3*x_4) num_intersection_y = (x_1*y_2-y_1*x_2)*(y_3-y_4)-(y_1-y_2)*(x_3*y_4-y_3*x_4) if(den_intersection == 0): return None intersection_x = num_intersection_x/den_intersection intersection_y = num_intersection_y/den_intersection intersection_point = (intersection_x, intersection_y) return intersection_point def get_rectangle(p1x, p1y, w_1, h_1): ''' Return the corner coordinates of the rectangle centered in p1x p1y and with width w_1 and h_1 ''' ax, ay = p1x-(w_1/2), p1y-(h_1/2) bx, by = p1x+(w_1/2), p1y+(h_1/2) cx, cy = p1x+(w_1/2), p1y-(h_1/2) dx, dy = p1x-(w_1/2), p1y-(h_1/2) return (ax, ay, bx, by, cx, cy, dx, dy, p1x, p1y) def remove_label_edge_crossings(G, crossings_edges): ''' Removes from the given list the crossings between edges and labels Instead of starting from the vertex position, the edges start from the boundary of the labels. ''' to_remove_crossings = [] edge_edge_crossings = [] all_pos = nx.get_node_attributes(G, "pos") all_width = nx.get_node_attributes(G, "width") all_heigth = nx.get_node_attributes(G, "height") for cr in crossings_edges: (e1, e2, intersection_point) = cr (v1, v2) = e1 (v3, v4) = e2 p1x, p1y = float(all_pos[v1].split(",")[0]), float(all_pos[v1].split(",")[1]) p2x, p2y = float(all_pos[v2].split(",")[0]), float(all_pos[v2].split(",")[1]) p3x, p3y = float(all_pos[v3].split(",")[0]), float(all_pos[v3].split(",")[1]) p4x, p4y = float(all_pos[v4].split(",")[0]), float(all_pos[v4].split(",")[1]) w_1, h_1 = float(all_width[v1]), float(all_heigth[v1]) w_2, h_2 = float(all_width[v2]), float(all_heigth[v2]) w_3, h_3 = float(all_width[v3]), float(all_heigth[v3]) w_4, h_4 = float(all_width[v4]), float(all_heigth[v4]) (ax, ay, bx, by, cx, cy, dx, dy, px, py) = get_rectangle(p1x, p1y, w_1*label_factor_magnifier, h_1*label_factor_magnifier) in_shape = check_point_in_rectangle(ax, ay, bx, by, cx, cy, dx, dy, px, py) if in_shape: to_remove_crossings.append(cr) continue (ax, ay, bx, by, cx, cy, dx, dy, px, py) = get_rectangle(p2x, p2y, w_2*label_factor_magnifier, h_2*label_factor_magnifier) in_shape = check_point_in_rectangle(ax, ay, bx, by, cx, cy, dx, dy, px, py) if in_shape: to_remove_crossings.append(cr) continue (ax, ay, bx, by, cx, cy, dx, dy, px, py) = get_rectangle(p3x, p3y, w_3*label_factor_magnifier, h_3*label_factor_magnifier) in_shape = check_point_in_rectangle(ax, ay, bx, by, cx, cy, dx, dy, px, py) if in_shape: to_remove_crossings.append(cr) continue (ax, ay, bx, by, cx, cy, dx, dy, px, py) = get_rectangle(p4x, p4y, w_4*label_factor_magnifier, h_4*label_factor_magnifier) in_shape = check_point_in_rectangle(ax, ay, bx, by, cx, cy, dx, dy, px, py) if in_shape: to_remove_crossings.append(cr) continue edge_edge_crossings.append(cr) print("removed crossings: " + str(len(to_remove_crossings))) return edge_edge_crossings def triangle_area(x1, y1, x2, y2, x3, y3): ''' A utility function to calculate area of triangle formed by (x1, y1), (x2, y2) and (x3, y3) ''' return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0) # A function to check whether point # P(x, y) lies inside the rectangle # formed by A(x1, y1), B(x2, y2), # C(x3, y3) and D(x4, y4) def check_point_in_rectangle(x1, y1, x2, y2, x3, y3, x4, y4, x, y): ''' A function to check whether point P(x, y) lies inside the rectangle formed by A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4) ''' # Calculate area of rectangle ABCD A = (triangle_area(x1, y1, x2, y2, x3, y3) + triangle_area(x1, y1, x4, y4, x3, y3)) # Calculate area of triangle PAB A1 = triangle_area(x, y, x1, y1, x2, y2) # Calculate area of triangle PBC A2 = triangle_area(x, y, x2, y2, x3, y3) # Calculate area of triangle PCD A3 = triangle_area(x, y, x3, y3, x4, y4) # Calculate area of triangle PAD A4 = triangle_area(x, y, x1, y1, x4, y4); # Check if sum of A1, A2, A3 # and A4 is same as A return (A == A1 + A2 + A3 + A4) def count_crossings(G, edges_to_compare=None, stop_when_found=False, ignore_label_edge_cr=False): ''' Counts the crossings of the given graph <tt>G<\tt>. The crossing count can be executed only on the given list of edges of <tt>G<\tt> passed as input in <tt>edges_to_compare<\tt>. Also the execution can stop as soon as a crossing is found if the boolean value <tt>stop_when_found<\tt> is set to True. If the vertices have labels with given height and width the crossings that occur below the labels can be ignored if the boolean value <tt>ignore_label_edge_cr<\tt> is set to True. Return a list of crossings where each element has the crossing edge and the intersection point. ''' count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") edge_list = list(nx.edges(G)) edge_set_1 = list(nx.edges(G)) if edges_to_compare is not None: edge_set_1 = list(edges_to_compare) for c1 in range(0, len(edge_set_1)): edge1 = edge_set_1[c1] (s1,t1) = edge1 ppos1 = all_pos[s1] qpos1 = all_pos[t1] p1x, p1y = float(ppos1.split(",")[0]), float(ppos1.split(",")[1]) q1x, q1y = float(qpos1.split(",")[0]), float(qpos1.split(",")[1]) j_start=c1+1 if edges_to_compare is not None: j_start=0 for c2 in range(j_start, len(edge_list)): edge2 = edge_list[c2] (s2,t2) = edge2 ppos2 = all_pos[s2] qpos2 = all_pos[t2] p2x, p2y = float(ppos2.split(",")[0]), float(ppos2.split(",")[1]) q2x, q2y = float(qpos2.split(",")[0]), float(qpos2.split(",")[1]) (intersection_exists, intersection_point) = doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) if(intersection_exists): crossings_edges.append((edge1, edge2, intersection_point)) count = count + 1 if stop_when_found: return crossings_edges if ignore_label_edge_cr: crossings_edges = remove_label_edge_crossings(G, crossings_edges) return crossings_edges
14,737
32.495455
130
py
mlgd
mlgd-master/layout_quality_measurement/stress_test.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import stress as st s_path = sys.argv[1] g_path = sys.argv[2] outputTxtFile = sys.argv[3] input_file_name = os.path.basename(s_path) graph_name = input_file_name.split(".")[0] S = nx_read_dot(s_path) G = nx_read_dot(g_path) G=sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[0] S_induced = nx.Graph(G.subgraph(S)) stress_val_S = st.stress(S) stress_val_SG = st.stress(S, G) stress_val_SGI = st.stress(S, S_induced) output_txt = "Metrics for " + graph_name + "\n" output_txt += "stress_S:" + str(stress_val_S) + "\n" output_txt += "stress_SG:" + str(stress_val_SG) + "\n" output_txt += "stress_SGI:" + str(stress_val_SGI) + "\n" print(output_txt) csv_head_line = "filename;stress;stress(induced);stress(complete)\n" csv_line = graph_name+";"+ str(stress_val_S) + ";" + str(stress_val_SGI) + ";" + str(stress_val_SG) + "\n" exists = os.path.isfile(outputTxtFile) if not exists: fh = open(outputTxtFile, 'w') fh.write(csv_head_line) fh = open(outputTxtFile, 'a') fh.write(csv_line)
1,252
20.603448
107
py
mlgd
mlgd-master/layout_quality_measurement/labelsmeas.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx import math import decimal global_labels_scaling_factor = 1 def boundingBox(G): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) max_x = float(coo_x[-1]) min_y = float(coo_y[0]) max_y = float(coo_y[-1]) width = abs(max_x - min_x) height = abs(max_y - min_y) return (width, height) def do_rectangles_overlap(x1, y1, w1, h1, x2, y2, w2, h2): '''Checks if two rectangles overlap and gives the value of overlapping area. Reactangles are centered in x1, y1, and x2, y2 and have as height and width h1 , w1 and h2,w2 respectively. ''' x_min_1=x1-(w1/2) y_min_1=y1-(h1/2) x_max_1=x1+(w1/2) y_max_1=y1+(h1/2) x_min_2=x2-(w2/2) y_min_2=y2-(h2/2) x_max_2=x2+(w2/2) y_max_2=y2+(h2/2) if(x_max_1 <= x_min_2 or x_max_2 <= x_min_1 or y_max_1 <= y_min_2 or y_max_2 <= y_min_1): # print("No Overlap") overlap = {'w': 0, 'h': 0, 'a':0, 'u':-1, 'v':-1} return overlap l1=(x_min_1, y_min_1) l2=(x_min_2, y_min_2) r1=(x_max_1, y_max_1) r2=(x_max_2, y_max_2) area_1=w1*h1 area_2=w2*h2 width_overlap = (min(x_max_1, x_max_2)-max(x_min_1, x_min_2)) height_overlap = (min(y_max_1, y_max_2)-max(y_min_1, y_min_2)) areaI = width_overlap*height_overlap total_area = area_1 + area_2 - areaI overlap = {"w": width_overlap, "h": height_overlap, "a":areaI} return overlap def totLabelsOverlappingArea(G, labelsscalingfactor=global_labels_scaling_factor): '''Computes the overlapping area of the labels of the graph G. It requires width and height for each vertex. The labels are supposed to be rectangular. Before computing the value, each label is scaled by <tt>labelsscalingfactor</tt> in order to reflect the printed size of the label. The default value of <tt>labelsscalingfactor</tt> is <tt>72</tt>''' overlapping_area = 0 widths=nx.get_node_attributes(G, "width") heights=nx.get_node_attributes(G, "height") all_pos = nx.get_node_attributes(G, "pos") nodes = list(nx.nodes(G)) for u_index in range(0, len(nodes)): u = nodes[u_index] u_width = float(widths[u])*labelsscalingfactor u_height = float(heights[u])*labelsscalingfactor u_x = float(all_pos[u].split(",")[0]) u_y = float(all_pos[u].split(",")[1]) for v_index in range(u_index+1, len(nodes)): v = nodes[v_index] v_width = float(widths[v])*labelsscalingfactor v_height = float(heights[v])*labelsscalingfactor v_x = float(all_pos[v].split(",")[0]) v_y = float(all_pos[v].split(",")[1]) curr_overlap = do_rectangles_overlap(u_x, u_y, u_width, u_height, v_x, v_y, v_width, v_height) overlapping_area += curr_overlap['a'] return overlapping_area def totLabelsArea(G, labelsscalingfactor=global_labels_scaling_factor): '''Computes the minimum area covered by non overlapping labels It requires width and height for each vertex. The labels are supposed to be rectangular. Before computing the value, each label is scaled by <tt>labelsscalingfactor</tt> in order to reflect the printed size of the label. The default value of <tt>labelsscalingfactor</tt> is <tt>72</tt>''' widths=nx.get_node_attributes(G, "width") heights=nx.get_node_attributes(G, "height") tot_area = 0 for v in widths.keys(): curr_area = (float(widths[v])*labelsscalingfactor)*(float(heights[v])*labelsscalingfactor) tot_area+=curr_area return tot_area def labelsBBRatio(G): ''' Computes the ratio between the minimum area occupied by non overlapping labels and the actual area of the drawings. Return ratio in scientific notation ''' bb = boundingBox(G) bb_area = bb[0]*bb[1] l_area = totLabelsArea(G) aspectRatio = bb_area/l_area aspectRatio = '%.2E' % decimal.Decimal(aspectRatio) return aspectRatio def diameter(G): return nx.diameter(G)
4,268
26.191083
106
py
mlgd
mlgd-master/layout_quality_measurement/crossings_old.py
#Author #Felice De Luca #https://github.com/felicedeluca import math import networkx as nx # Given three colinear points p, q, r, the function checks if # point q lies on line segment 'pr' def onSegment(px, py, qx, qy, rx, ry): if (qx <= max(px, rx) and qx >= min(px, rx) and qy <= max(py, ry) and qy >= min(py, ry)): return True return False def strictlyOnSegment(px, py, qx, qy, rx, ry): if (qx < max(px, rx) and qx > min(px, rx) and qy < max(py, ry) and qy > min(py, ry)): return True return False # To find orientation of ordered triplet (p, q, r). # The function returns following values # 0 --> p, q and r are colinear # 1 --> Clockwise # 2 --> Counterclockwise def orientation(px, py, qx, qy, rx, ry): # See http://www.geeksforgeeks.org/orientation-3-ordered-points/ # for details of below formula. val = (qy - py) * (rx - qx) - (qx - px) * (ry - qy) if (val == 0):return 0 # clock or counterclock wise if (val > 0): return 1 else: return 2 def yInt(x1, y1, x2, y2): if (y1 == y2):return y1 return y1 - slope(x1, y1, x2, y2) * x1 def slope(x1, y1, x2, y2): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)) if (x1 == x2):return False return (y1 - y2) / (x1 - x2) # The main function that returns true if line segment 'p1q1' # and 'p2q2' intersect. def doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): # Find the four orientations needed for general and # special cases o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y) o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y) o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y) o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y) #if(o1==0 or o2==0 or o3==0 or o4==0):return False # General case if (o1 != o2 and o3 != o4): return True # Special Cases # p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 and onSegment(p1x, p1y, p2x, p2y, q1x, q1y)):return True # p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 and onSegment(p1x, p1y, q2x, q2y, q1x, q1y)):return True # p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 and onSegment(p2x, p2y, p1x, p1y, q2x, q2y)):return True # p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 and onSegment(p2x, p2y, q1x, q1y, q2x, q2y)):return True return False # Doesn't fall in any of the above cases def isSameCoord(x1, y1, x2, y2): if x1==x2 and y1==y2: return True return False # do p is an end point of edge (u,v) def isEndPoint(ux, uy, vx, vy, px, py): if isSameCoord(ux, uy, px, py) or isSameCoord(vx, vy, px, py): return True return False # is (p1,q1) is adjacent to (p2,q2)? def areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isEndPoint(p1x, p1y, q1x, q1y, p2x, p2y): return True elif isEndPoint(p1x, p1y, q1x, q1y, q2x, q2y): return True return False def isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): x1 = p1x-q1x y1 = p1y-q1y x2 = p2x-q2x y2 = p2y-q2y cross_prod_value = x1*y2 - x2*y1 if cross_prod_value==0: return True return False # here p1q1 is one segment, and p2q2 is another # this function checks first whether there is a shared vertex # then it checks whether they are colinear # finally it checks the segment intersection def doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if strictlyOnSegment(p1x, p1y, p2x, p2y, q1x, q1y) or strictlyOnSegment(p1x, p1y, q2x, q2y, q1x, q1y) or strictlyOnSegment(p2x, p2y, p1x, p1y, q2x, q2y) or strictlyOnSegment(p2x, p2y, q1x, q1y, q2x, q2y): return True else: return False else: return False return doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) def getIntersection(x11, y11, x12, y12, x21, y21, x22, y22): slope1 = 0 slope2 = 0 yint1 = 0 yint2 = 0 intx = 0 inty = 0 #TODO: Please Check all four cases if (x11 == x21 and y11 == y21):return [x11, y11] if (x12 == x22 and y12 == y22):return [x12, y22] # Check 1st point of edge 1 with 2nd point of edge 2 and viceversa slope1 = slope(x11, y11, x12, y12) slope2 = slope(x21, y21, x22, y22) #print('slope1:'+str(slope1)) #print('slope2:'+str(slope2)) if (slope1 == slope2):return False yint1 = yInt(x11, y11, x12, y12) yint2 = yInt(x21, y21, x22, y22) #print('yint1:'+str(yint1)) #print('yint2:'+str(yint2)) if (yint1 == yint2): if (yint1 == False):return False else:return [0, yint1] if(x11 == x12):return [x11, slope2*x11+yint2] if(x21 == x22):return [x21, slope1*x21+yint1] if(y11 == y12):return [(y11-yint2)/slope2,y11] if(y21 == y22):return [(y21-yint1)/slope1,y21] if (slope1 == False):return [y21, slope2 * y21 + yint2] if (slope2 == False):return [y11, slope1 * y11 + yint1] intx = (yint1 - yint2)/ (slope2-slope1) return [intx, slope1 * intx + yint1] def to_deg(rad): return rad*180/math.pi # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSegDegree(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) #return angle return to_deg(angle) # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSeg(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) return angle def count_crossings(G, ignore_labels=False): """Counts the number of crossings of the given Graph""" count = 0 all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] for c1 in range(0, len(edge_list)): for c2 in range(c1+1, len(edge_list)): edge1 = edge_list[c1] edge2 = edge_list[c2] (s1,t1) = (edge1[0], edge1[1]) (s2,t2) = (edge2[0], edge2[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): count = count + 1 # if len(segment_pair)==2: # count = count + 1 # else: # count = count + comb(len(segment_pair), 2) return count
7,239
29.420168
207
py
mlgd
mlgd-master/layout_quality_measurement/neighbors_preservation.py
#Author #Felice De Luca #https://github.com/felicedeluca import pygraphviz as pgv import networkx as nx import math # import numpy as np # from numpy import random # from scipy.spatial import distance # import time # # def euclidean_closest_nodes(node, nodes, k_i): # ''' # Computes the distance matrix between point. # ''' # # node = np.array(node) # nodes = np.array(nodes) # # distances = distance.cdist(node, nodes) # indices = np.argpartition(distances, 3) # # return indices def euclidean_distance(source, target): x_source1 = float(source['pos'].split(",")[0]) x_target1 = float(target['pos'].split(",")[0]) y_source1 = float(source['pos'].split(",")[1]) y_target1 = float(target['pos'].split(",")[1]) geomDistance = math.sqrt((x_source1 - x_target1)**2 + (y_source1 - y_target1)**2) return geomDistance def find_graph_closest_nodes(G, r_g, sourceStr, all_sp): closest = [] # vertices = list(nx.nodes(G)) # source = G.node[sourceStr] # for i in range(0, len(vertices)): for target in nx.nodes(G): if(target == sourceStr): continue graph_theoretic_distance = len(all_sp[sourceStr][target])-1 if(graph_theoretic_distance <= r_g): closest.append(target) return closest def find_space_closest_nodes(Gnx, k_i, sourceStr): closest = [] vertices = list(nx.nodes(Gnx)) source = Gnx.node[sourceStr] closest_dict = dict() for i in range(0, len(vertices)): targetStr = vertices[i] target = Gnx.node[targetStr] if(target == source): continue space_distance = euclidean_distance(source, target) closest_dict[targetStr] = space_distance res = list(sorted(closest_dict, key=closest_dict.__getitem__, reverse=False)) closest = res[:k_i+1] return closest def compute_neig_preservation(G, weighted=True, all_sp=None): if all_sp is None: if(weighted): # converting weights in float all_weights_n = nx.get_node_attributes(G, "weight") for nk in all_weights_n.keys(): all_weights_n[nk] = float(all_weights_n[nk]) nx.set_node_attributes(G, all_weights_n, "weight") all_weights_e = nx.get_edge_attributes(G, "weight") for ek in all_weights_e.keys(): all_weights_e[ek] = float(all_weights_e[ek]) nx.set_edge_attributes(G, all_weights_e, "weight") all_sp = nx.shortest_path(G, weight="weight") else: all_sp = nx.shortest_path(G) r_g = 3 vertices = list(nx.nodes(G)) sum = 0 # all_pos = nx.get_node_attributes(G, "pos") # nodes_positions = {} # for v in all_pos.keys(): # x = float(all_pos[v].split(",")[0]) # y = float(all_pos[v].split(",")[1]) # nodes_positions[v] = (x, y) for i in range(0, len(vertices)): sourceStr = vertices[i] source = G.node[sourceStr] graph_neighbors = find_graph_closest_nodes(G, r_g, sourceStr, all_sp) k_i = len(graph_neighbors) # x = float(all_pos[sourceStr].split(",")[0]) # y = float(all_pos[sourceStr].split(",")[1]) # curr_node_pos = [(x, y)] # space_neigobors_new = euclidean_closest_nodes([curr_node_pos], list(nodes_positions.values()), k_i) space_neigobors = find_space_closest_nodes(G, k_i, sourceStr) vertices_intersection = set(graph_neighbors).intersection(set(space_neigobors)) vertices_union = set(graph_neighbors).union(set(space_neigobors)) sum += len(vertices_intersection)/len(vertices_union) pres = (1/len(vertices))*sum pres = round(pres, 3) return pres
3,765
24.972414
109
py
mlgd
mlgd-master/layout_quality_measurement/upwardflow.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import numpy as np # to compute inner product def compute_edges_vects(G): ''' Computes the vectors for each edge in G and resturns them in a list. ''' vects_list = [] pos_dict = nx.get_node_attributes(G, 'pos') for e in nx.edges(G): (source, target) = e x_source = float(pos_dict[source].split(",")[0]) x_target = float(pos_dict[target].split(",")[0]) y_source = float(pos_dict[source].split(",")[1]) y_target = float(pos_dict[target].split(",")[1]) # The following check is to force the upwardness # (if the edges vects) are inverted if y_target < y_source: x_temp = x_target x_target = x_source x_source = x_temp y_temp = y_target y_target = y_source y_source = y_temp len = [x_source - x_target, y_source - y_target] norm = math.sqrt(len[0] ** 2 + len[1] ** 2) dir = [len[0]/norm, len[1]/norm] vect = [dir[0], dir[1]] vects_list.append(vect) return vects_list def compute_upwardflow(G): ''' Computes the Upward flow of the given upward drawing of the graph G. This metric determines the proportion of edge segments of a drawing which have a consistent direction. Edge segments are used rather than edges, as edges with edge segments of alternating direction are generally considered undesirable. The desired direction is usually upwards or downwards with respect to a vertical axis, but the metric makes no assumptions about its orientation. It is assumed that G is a directed graph. The notation ei indicates the vector corresponding to the ith directed edge in the drawing:The inner product of two vectors is denoted <v1, v2> : The unit vector parallel with the desired direction is denoted 1 and is considered to point in the direction of desired flow. This metric is 0 for non directed graphs. <tt>https://pdfs.semanticscholar.org/be7e/4c447ea27e0891397ae36d8957d3cbcea613.pdf</tt> ''' e_vects = compute_edges_vects(G) prods_sum = 0 for e in e_vects: ones = [1, 1] inn_prod = np.inner(e, ones) if inn_prod > 0: prods_sum += 1 flow = prods_sum/len(e_vects) flow = round(flow, 3) return flow
2,556
26.494624
275
py
mlgd
mlgd-master/layout_quality_measurement/stress.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx import math def euclidean_distance(source, target): x_source1 = float(source['pos'].split(",")[0]) x_target1 = float(target['pos'].split(",")[0]) y_source1 = float(source['pos'].split(",")[1]) y_target1 = float(target['pos'].split(",")[1]) geomDistance = math.sqrt((x_source1 - x_target1)**2 + (y_source1 - y_target1)**2) return geomDistance def scale_graph(G, alpha): H = G.copy() for currVStr in nx.nodes(H): currV = H.node[currVStr] x = float(currV['pos'].split(",")[0]) y = float(currV['pos'].split(",")[1]) x = x * alpha y = y * alpha currV['pos'] = str(x)+","+str(y) return H def computeScalingFactor(S, all_sp): num = 0 den = 0 nodes = list(nx.nodes(S)) for i in range(0, len(nodes)): sourceStr = nodes[i] source = S.node[sourceStr] for j in range(i+1, len(nodes)): targetStr = nodes[j] if(sourceStr == targetStr): continue target = S.nodes[targetStr] graph_theoretic_distance = 0 graph_theoretic_distance = len(all_sp[sourceStr][targetStr])-1 geomDistance = euclidean_distance(source, target) if (graph_theoretic_distance <= 0): continue weight = 1/(graph_theoretic_distance**2) num = num + (graph_theoretic_distance * geomDistance * weight) den = den + (weight * (geomDistance**2)) scale = num/den return scale def stress(S, G=None, weighted=True, all_sp=None): '''Computes the strees of the layout <tt>S</tt> if the parameter <tt>G</tt> is passed it computes the stress of the layout <tt>S</tt> with respect the graph distances on <tt>G</tt>''' S_original = S.copy() alpha = 1 if all_sp is None: if(G is None): if(weighted): # converting weights in float all_weights_n = nx.get_node_attributes(S, "weight") for nk in all_weights_n.keys(): all_weights_n[nk] = float(all_weights_n[nk]) nx.set_node_attributes(S, all_weights_n, "weight") all_weights_e = nx.get_edge_attributes(S, "weight") for ek in all_weights_e.keys(): all_weights_e[ek] = float(all_weights_e[ek]) nx.set_edge_attributes(S, all_weights_e, "weight") all_sp = nx.shortest_path(S, weight="weight") else: all_sp = nx.shortest_path(S) else: if(weighted): # converting weights in float all_weights_n = nx.get_node_attributes(G, "weight") for nk in all_weights_n.keys(): all_weights_n[nk] = float(all_weights_n[nk]) nx.set_node_attributes(G, all_weights_n, "weight") all_weights_e = nx.get_edge_attributes(G, "weight") for ek in all_weights_e.keys(): all_weights_e[ek] = float(all_weights_e[ek]) nx.set_edge_attributes(G, all_weights_e, "weight") all_sp = nx.shortest_path(G, weight="weight") else: all_sp = nx.shortest_path(G) alpha = computeScalingFactor(S_original, all_sp) S = scale_graph(S_original, alpha) vertices = list(nx.nodes(S)) stress = 0 for i in range(0, len(vertices)): sourceStr = vertices[i] source = S.node[sourceStr] for j in range(i+1, len(vertices)): targetStr = vertices[j] target = S.nodes[targetStr] graph_theoretic_distance = len(all_sp[sourceStr][targetStr])-1 eu_dist = euclidean_distance(source, target) if (graph_theoretic_distance <= 0): continue delta_squared = (eu_dist - graph_theoretic_distance)**2 weight = 1/(graph_theoretic_distance**2) stress = stress + (weight * delta_squared) scale_graph(S, 1/alpha) stress = round(stress, 3) return stress
4,194
26.24026
85
py
mlgd
mlgd-master/layout_quality_measurement/other_measures.py
#Author #Felice De Luca #https://github.com/felicedeluca import pygraphviz as pgv import networkx as nx import math def vertex_degree(G): degree = sorted(dict(nx.degree(G)).values())[-1] return degree def boundingBox(G): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) max_x = float(coo_x[-1]) min_y = float(coo_y[0]) max_y = float(coo_y[-1]) width = abs(max_x - min_x) height = abs(max_y - min_y) return (width, height) def aspectRatio(G): bb = boundingBox(G) aspectRatio = bb[0]/bb[1] return aspectRatio def diameter(G): return nx.diameter(G)
774
15.145833
61
py
mlgd
mlgd-master/layout_quality_measurement/highwayness.py
import sys import networkx as nx import pygraphviz as pgv import math from networkx.readwrite import json_graph from networkx.readwrite.graphml import read_graphml if len(sys.argv)<2: print ("Enter dot file with positions ") quit() filepath=sys.argv[1] x=filepath.split(".") inputtype=x[len(x)-1] print ("filetype:", inputtype) #inputtype='dot' #inputtype='graphml' #'highwaynessExp/path1.graphml' if inputtype=='graphml': G=read_graphml(sys.argv[1]) G=G.to_undirected() else: G=nx.Graph(pgv.AGraph(filepath)) #G=nx.Graph(pgv.AGraph("Layer_7_drawing_improved.dot")) #G=nx.Graph(pgv.AGraph(sys.argv[1])) def calculateslope(G): #networkx v2 for x in G.edges(): s=slope(G, x[0], x[1]) nx.set_edge_attributes(G, {x:{'s':s}}) return G def calculateslopeX(G): for i in range(0,len(G.edges())): s=slope(G, G.edges()[i][0], G.edges()[i][1]) G[G.edges()[i][0]][G.edges()[i][1]]=s G[G.edges()[i][1]][G.edges()[i][0]]=s return G def slope(G,a,b): if inputtype=='graphml': x1,y1=G.node[a]['x'], G.node[a]['y'] x2,y2=G.node[b]['x'], G.node[b]['y'] else: x1,y1=G.node[a]['pos'].split(",") x2,y2=G.node[b]['pos'].split(",") if x1==x2: ang= math.pi/2 else: m=(float(y1)-float(y2))/(float(x1)-float(x2)) ang=math.atan(m) return ang**2 def sumofslope(G,p): ang=0 for i in range(0,len(p)-2): ang=ang+ abs( G[p[i]][p[i+1]]['s'] - G[p[i+1]][p[i+2]]['s']) return ang G=calculateslope(G) leaves=[] for x in G.nodes(): if G.degree(x)==1: leaves.append(x) totalhighwayness=0 for i in range(0, len(leaves)): for j in range(i+1, len(leaves)): p=nx.shortest_path(G,leaves[i],leaves[j]) totalhighwayness=totalhighwayness+ sumofslope(G,p) /((len(p)-1)*math.pi * math.pi ) print('score (low is better):',totalhighwayness) print('normalized score (low is better):',totalhighwayness/ ((len(leaves) * (len(leaves)-1))/2))
1,855
22.493671
96
py
mlgd
mlgd-master/layout_quality_measurement/uniformity_edge_length.py
#Author #Felice De Luca #https://github.com/felicedeluca ## # EU corresponds to the normalized standard deviation of the edge length. ## import networkx as nx import math def avg_edge_length(G): ''' Computes the average edge length of the given graph layout <tt>G</tt> ''' sum_edge_length = 0.0 pos_dict = nx.get_node_attributes(G, 'pos') for edge in nx.edges(G): (s,t) = edge x_source = float(pos_dict[s].split(",")[0]) x_target = float(pos_dict[t].split(",")[0]) y_source = float(pos_dict[s].split(",")[1]) y_target = float(pos_dict[t].split(",")[1]) curr_length = math.sqrt((x_source - x_target)**2 + (y_source - y_target)**2) sum_edge_length += curr_length edges_count = len(nx.edges(G)) avg_edge_len = sum_edge_length/edges_count return avg_edge_len def uniformity_edge_length(G): ''' The Edge length uniformity corresponds to the normalized standard deviation of the edge length. ''' edges = nx.edges(G) edge_count = len(edges) avgEdgeLength = avg_edge_length(G) tot_sum = 0.0 pos_dict = nx.get_node_attributes(G, 'pos') for edge in edges: (s,t) = edge x_source = float(pos_dict[s].split(",")[0]) x_target = float(pos_dict[t].split(",")[0]) y_source = float(pos_dict[s].split(",")[1]) y_target = float(pos_dict[t].split(",")[1]) curr_length = math.sqrt((x_source - x_target)**2 + (y_source - y_target)**2) num = (curr_length-avgEdgeLength)**2 den = edge_count*(avgEdgeLength**2) currValue = num/den tot_sum += currValue uniformity_e_len = math.sqrt(tot_sum) result = round(uniformity_e_len, 3) return result
1,764
21.341772
99
py
mlgd
mlgd-master/layout_quality_measurement/metricscomputer.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import stress import neighbors_preservation as neigpres import crossings import uniformity_edge_length as uniedgelen import other_measures as othermeas import labelsmeas import upwardflow graphpath = sys.argv[1] outputTxtFile = sys.argv[2] input_file_name = os.path.basename(graphpath) graph_name = input_file_name.split(".")[0] G = nx_read_dot(graphpath) G = nx.Graph(G) cmds=[] all = False if len(sys.argv) > 3 : cmds = sys.argv[3].split(",") else: # Compute all measures all = True cr = ('cr' in cmds) # crossings ue = ('ue' in cmds) # edge length uniformity st = ('st' in cmds) # stress np = ('np' in cmds) # neighbors_preservation lblbb = ('lblbb' in cmds) #label to boundingBox ratio lblarea = ('lblarea' in cmds) #labels total area bb = ('bb' in cmds) #bounding box upflow = ('upflow' in cmds) #upward flow lblo = ('lblo' in cmds) #labels overlaping area weighted = False #Weighted version of measures output_txt = "Metrics for " + graph_name + "\n" output_txt = nx.info(G) + "\n" print(output_txt) csv_head_line = "filename&" csv_line = graph_name+"&" all_pairs_sp = None if cr or np: if(weighted): # converting weights in float all_weights_n = nx.get_node_attributes(G, "weight") for nk in all_weights_n.keys(): all_weights_n[nk] = float(all_weights_n[nk]) nx.set_node_attributes(G, all_weights_n, "weight") all_weights_e = nx.get_edge_attributes(G, "weight") for ek in all_weights_e.keys(): all_weights_e[ek] = float(all_weights_e[ek]) nx.set_edge_attributes(G, all_weights_e, "weight") all_pairs_sp = nx.shortest_path(G, weight="weight") else: all_pairs_sp = nx.shortest_path(G) if cr or all: crss = crossings.count_crossings(G, ignore_label_edge_cr=True) crossings_val = len(crss) output_line = "CR: " + str(crossings_val) output_txt += output_line + "\n" print(output_line) csv_head_line += "crossings&" csv_line += str(crossings_val) + "&" if ue or all: uniedgelen_val = uniedgelen.uniformity_edge_length(G) output_line = "UE: " + str(uniedgelen_val) output_txt += output_line + "\n" print(output_line) csv_head_line += "uniformity\_edge\_length&" csv_line += str(uniedgelen_val) + "&" if st or all: stress_val = stress.stress(G, weighted=weighted, all_sp=all_pairs_sp) output_line = "ST: " + str(stress_val) output_txt += output_line + "\n" print(output_line) csv_head_line += "stress&" csv_line += str(stress_val) + "&" if np or all: neigpres_val = neigpres.compute_neig_preservation(G, weighted=weighted, all_sp=all_pairs_sp) output_line = "NP: " + str(neigpres_val) output_txt += output_line + "\n" print(output_line) csv_head_line += "neighbors\_preservation&" csv_line += str(neigpres_val) + "&" if lblbb or all: labelsBBRatio_val = labelsmeas.labelsBBRatio(G) output_line = "lblbb: " + str(labelsBBRatio_val) output_txt += output_line + "\n" print(output_line) csv_head_line += "boundingbox\_ratio\_to\_labels&" csv_line += str(labelsBBRatio_val) + "&" if lblarea or all: totLabelsArea_val = labelsmeas.totLabelsArea(G) output_line = "lblarea: " + str(totLabelsArea_val) output_txt += output_line + "\n" print(output_line) csv_head_line += "labels\_total\_area&" csv_line += str(totLabelsArea_val) + "&" if bb or all: bbox_val = othermeas.boundingBox(G) output_line = "BB: " + str(bbox_val) output_txt += output_line + "\n" print(output_line) csv_head_line += "bounding\_box" csv_line += str(bbox_val) + "&" if lblo or all: value = labelsmeas.totLabelsOverlappingArea(G) output_line = "lblo: " + str(value) + "\n" output_txt += output_line csv_head_line += "lblo;" csv_line += str(value) + "&" print(output_line) if upflow: upflow_val = upwardflow.compute_upwardflow(G) output_txt += "upflow: " + str(upflow_val) + "\n" output_txt += output_line + "\n" print(output_line) csv_head_line += "upflow&" csv_line += str(upflow_val) + "&" csv_head_line += "\\\\ \\hline \n" csv_line += "\\\\ \\hline \n" # print(output_txt) exists = os.path.isfile(outputTxtFile) if not exists: fh = open(outputTxtFile, 'w') fh.write(csv_head_line) fh = open(outputTxtFile, 'a') fh.write(csv_line)
4,608
26.434524
96
py
mlgd
mlgd-master/layout_quality_measurement/graphconverter/dot2txt.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx from networkx.drawing.nx_agraph import read_dot as nx_read_dot import vertexmanager def dot_to_txt(input_file, output_file): G = nx_read_dot(input_file) print(nx.info(G)) f = open(output_file, 'w') f.write(str(len(G.nodes()))+'\n') id_to_name = dict() name_to_id = dict() count = 0 for node_id in G.nodes(): node = G.node[node_id] name_to_id[node_id] = count count += 1 x, y = vertexmanager.getCoordinate(node) f.write(str(x) + ' ' + str(y) + '\n') print(name_to_id) for edg in G.edges(): f.write(str(name_to_id[edg[0]]) + " " + str(name_to_id[edg[1]]) + "\n") f.close() # Main Flow input_path = sys.argv[1] output_path = sys.argv[2] dot_to_txt(input_path, output_path)
848
22.583333
79
py
mlgd
mlgd-master/layout_quality_measurement/graphconverter/gml2dot.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot def set_graph_properties(G): ''' Extracts the attributes of the vertices and edges from the gml data structure <tt>return</tt> the graph with the standard dot attributes''' graphics = nx.get_node_attributes(G, "graphics") # print(graphics) for k in nx.nodes(G): pos = str(graphics[k]['x']) +"," + str(graphics[k]['y']) nx.set_node_attributes(G, {k:pos}, 'pos') nx.set_node_attributes(G, {k:""}, "graphics") nx.set_node_attributes(G, {k:k}, "label") if('w' in graphics[k].keys() and 'h' in graphics[k].keys()): # HERE W and H seem to be inverted width = float(graphics[k]['w']) height = float(graphics[k]['h']) nx.set_node_attributes(G, {k:max(width, height)}, "width") nx.set_node_attributes(G, {k:min(width, height)}, "height") G = nx.Graph(G) return G g_path = sys.argv[1] outputpath = sys.argv[2] g_name = os.path.basename(g_path).split(".")[0] # Reading graph and subgraph G = nx.read_gml(g_path) G = nx.Graph(G) print(nx.info(G)) G = set_graph_properties(G) print(nx.info(G)) write_dot(G, outputpath) print(nx.info(G))
1,408
25.092593
71
py
mlgd
mlgd-master/layout_quality_measurement/betametrics/smoothness.py
#zigzagness import networkx as nx import math import numpy as np def extract_leaves(G): """Extracts from <tt>G</tt> the vertices with degree 1, i.e. the leaves.""" leaves=[] for n in nx.nodes(G): if len(list(G.neighbors(n)))<=1: leaves.append(n) return leaves def compute_euclidean_distance(s, t): """Computes the distance between the two points <tt>s</tt> and <tt>t</tt>. <strong>return</strong> distance between the given vertices """ s_pos = s["pos"] t_pos = t["pos"] x_s = float(s_pos.split(",")[0]) x_t = float(t_pos.split(",")[0]) y_s = float(s_pos.split(",")[1]) y_t = float(t_pos.split(",")[1]) curr_distance = math.sqrt((x_s - x_t)**2 + (y_s - y_t)**2) return curr_distance def compute_distance_on_graph(G, s_id, t_id): """ Computes the sum of the length in the shortest path between <tt>s</tt> and <tt>t</tt>. If the shortest path are more than one the shorter in edge lengths is considered <tt>return</tt> a double value of the length of the shortestpath between <tt>s</tt> and <tt>t</tt> """ all_sp = list(nx.all_shortest_paths(G, source=s_id, target=t_id)) min_sp = float("inf") for sp in all_sp: curr_length = 0 for s_index in range(0, len(sp)-1): t_index = s_index+1 s_id = sp[s_index] t_id = sp[t_index] s = G.node[s_id] t = G.node[t_id] curr_length += compute_euclidean_distance(s, t) min_sp = min(min_sp, curr_length) return min_sp def compute_smoothness(G): """ Smoothness is the difference between the Euclidean Distance and the distance on the graph of any pair of leaves of the given Tree """ leaves = extract_leaves(G) total_error=0 sp_avg_len = nx.average_shortest_path_length(G) for s_index in range(0, len(leaves)): for t_index in range(s_index+1, len(leaves)): s_id = leaves[s_index] t_id = leaves[t_index] s = G.node[s_id] t = G.node[t_id] curr_distance = compute_euclidean_distance(s, t) path_distance = compute_distance_on_graph(G, s_id, t_id) sp_length = nx.shortest_path_length(G, s_id, t_id) penalization = (math.e**(-sp_avg_len)) curr_error = (path_distance-curr_distance)*penalization total_error += curr_error print(total_error)
2,471
24.484536
102
py
mlgd
mlgd-master/layout_quality_measurement/betametrics/vertexangularresolution.py
import sys import os import pygraphviz as pgv import networkx as nx import math import random def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex) def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def getAngleOfLineBetweenTwoPoints(point1X, point1Y, point2X, point2Y): xDiff = point2X - point1X yDiff = point2Y - point1Y return math.degrees(math.atan2(yDiff, xDiff)) def computeSectorsAngles(G, centralVertex): angle_dict = dict() for currN in set(nx.all_neighbors(G, centralVertex)): v1 = G.node[centralVertex] v2 = G.node[currN] v1_x, v1_y = getCoordinate(v1) v2_x, v2_y = getCoordinate(v2) angle = getAngleOfLineBetweenTwoPoints(v1_x, v1_y, v2_x, v2_y) if(angle < 0): angle = 360-abs(angle) if(angle not in angle_dict.keys()): angle_dict[angle] = list() angle_dict[angle].append(currN) sorted_slopes = sorted(angle_dict.keys()) sector_angle_dict = dict() sector_angles_list = list() for i in range(0, len(sorted_slopes)): first_index = i second_index = i+1 if(second_index>=len(sorted_slopes)): second_index = 0 first_slope = sorted_slopes[first_index] next_slope = sorted_slopes[second_index] v1_id = angle_dict[first_slope][0] v2_id = angle_dict[next_slope][0] center = G.node[centralVertex] v1 = G.node[v1_id] v2 = G.node[v2_id] angular_resolution = next_slope-first_slope if(angular_resolution < 0): angular_resolution = 360-abs(angular_resolution) if(angular_resolution not in sector_angle_dict.keys()): sector_angle_dict[angular_resolution] = list() sector_angle_dict[angular_resolution].append([v1_id, v2_id]) sector_angles_list.append(angular_resolution) return sector_angle_dict, sector_angles_list def compute(G): vertices = list(G.nodes()) angle_sum = 0.0 angle_count = 0 for currVertex in vertices: adjsIterator = nx.all_neighbors(G, currVertex) adjs = list(adjsIterator) if(len(adjs)<=1): continue # Translate Drawing for convenience translation_dx, translation_dy = getCoordinate(G.node[currVertex]) translateGraph(G, -translation_dx, -translation_dy) # # Extract subcomponents, draw, sacle and attach it to the widest sector for currN in adjs: # Compute sector angle and get the largest sector_angle_dict, sector_angles_list = computeSectorsAngles(G, currVertex) sorted_angles = sorted(sector_angles_list) angle_sum += sorted_angles[0] angle_count += 1 #Place back the graph at original position translateGraph(G, translation_dx, translation_dy) angle_avg = angle_sum / angle_count return angle_avg
3,364
24.11194
87
py
mlgd
mlgd-master/layout_quality_measurement/betametrics/continuity.py
#continuity property #Evaluates the quality of an highway import networkx as nx import math import re def continuity(G): avg_sp = nx.average_shortest_path_length(G) total_sp = len(nx.nodes(G))*(len(nx.nodes(G))-1) long_sp = total_sp global_max_jumps = 0 global_min_jumps = float('inf') zero_jumps_sp = 0 single_jump_sp = 0 many_jumps_sp = 0 # source identifier for source in nx.nodes(G): # target identifier for target in nx.nodes(G): if(source == target): continue # Compute the length of the sp sp_len = nx.shortest_path_length(G, source=str(source), target=str(target)) # ignore the sp shorter than avg if sp_len < avg_sp or sp_len <= 1: long_sp -= 1 continue min_jumps = float('inf') # all shortest paths between source and target all_shortest_paths = [p for p in nx.all_shortest_paths(G, source=str(source), target=str(target))] for curr_sp_arr_index in range(len(all_shortest_paths)): # for each shortest path if the length is longer than avg # then compute the jumps and return the minimum value curr_sp = all_shortest_paths[curr_sp_arr_index] jumps = 0 prev_highway_edge = False for curr_s_index in range(len(curr_sp)-1): curr_t_index = curr_s_index + 1 s = curr_sp[curr_s_index] t = curr_sp[curr_t_index] edge = G[s][t] highway_edge = is_highway_edge(edge) # Count when the shortest path jumps on level 1 edges if(highway_edge and prev_highway_edge != highway_edge): jumps += 1 prev_highway_edge = highway_edge if(jumps == 1): min_jumps = 1 else: min_jumps = min(min_jumps, jumps) # Store the computed value of Continuiti global_max_jumps = max(global_max_jumps, min_jumps) global_min_jumps = min(global_min_jumps, min_jumps) if(min_jumps == 0): zero_jumps_sp += 1 if(min_jumps == 1): single_jump_sp += 1 if(min_jumps > 1): many_jumps_sp += 1 print("avg sp: " + str(avg_sp)) print("# total shortest paths: " + str(total_sp)) print("# long shortest paths: " + str(long_sp)) print("global max jumps: " + str(global_max_jumps)) print("global min jumps: " + str(global_min_jumps)) print("zero jumps: " + str(zero_jumps_sp)) print("one jump: " + str(single_jump_sp)) print("many jumps: " + str(many_jumps_sp)) print("zero jumps (%): " + str(zero_jumps_sp*100/long_sp)) print("one jump (%): " + str(single_jump_sp*100/long_sp)) print("many jumps (%): " + str(many_jumps_sp*100/long_sp)) ''' Check whether the given edge is an highway edge TODO: Define how to extract highway info from edge ''' def is_highway_edge(edge): # edge_layer_attr = edge["layer"].split(":")[0] edge_layer = int(re.findall('\d+', edge_layer_attr)[0]) return (edge_layer == 1)
3,330
30.130841
111
py
mlgd
mlgd-master/layout_quality_measurement/betametrics/speed_on_network.py
import networkx as nx import math import re alpha = 0.5 #Speed on Highway beta = 1 #Speed on non Highway def highwayness(GD): # Set the speed attribute on each edge based on the edge type add_speed_attribute(GD) # computes the average edge length and average shortest path length edge_lengths = sorted([float(p) for p in nx.get_edge_attributes(GD, "length").values()]) avg_length = sum(edge_lengths) / float(len(edge_lengths)) avg_sp = nx.average_shortest_path_length(GD) # compute the average route length min_travel_time_route = avg_length*avg_sp tot_network_length = 0 tot_travel_time = 0 # Get leaves as the vertices with degree 1 leaves = [x for x in GD.nodes() if GD.degree(x)==32] for i in range(0, len(leaves)): sourceStr = leaves[i] for j in range(i+1, len(leaves)): targetStr = leaves[j] if(sourceStr == targetStr): continue sp = nx.shortest_path(GD, sourceStr, targetStr, weight="travel_time") length = compute_path_length(GD,sp) travel_time = compute_path_travel_time(GD, sp) if(min_travel_time_route > travel_time): continue tot_network_length += length tot_travel_time += travel_time highwayness = tot_travel_time/tot_network_length return highwayness def highwayness_multilevel_ratio(GD_prev, GD_curr): GD_curr_with_old_positions = GD_curr.copy() vertices_old_pos = nx.get_node_attributes(GD_prev, 'pos') nx.set_node_attributes(GD_curr_with_old_positions, vertices_old_pos, 'pos') highwayness_curr = highwayness(GD_curr) highwayness_curr_old_pos = highwayness(GD_curr_with_old_positions) return highwayness_curr/highwayness_curr_old_pos def compute_path_travel_time(GD, path): travel_time = 0 for i in range(0, len(path)-1): src = path[i] trg = path[i+1] travel_time += float(GD[src][trg]["travel_time"]) return travel_time def compute_path_length(GD, path): length = 0 for i in range(0, len(path)-1): src = path[i] trg = path[i+1] length += float(GD[src][trg]["length"]) return length def add_speed_attribute(GD): vertices_pos = nx.get_node_attributes(GD, 'pos') edge_layer_attributes = nx.get_edge_attributes(GD, "layer") for curr_edge in nx.edges(GD): u = curr_edge[0] v = curr_edge[1] u_pos = vertices_pos[u] v_pos = vertices_pos[v] u_x = float(u_pos.split(",")[0]) v_x = float(v_pos.split(",")[0]) u_y = float(u_pos.split(",")[1]) v_y = float(v_pos.split(",")[1]) distance = math.sqrt( (u_x - v_x)**2 + (u_y - v_y)**2) curr_edge_layer_attr = edge_layer_attributes[curr_edge] speed = beta if (int(re.findall('\d+', curr_edge_layer_attr.split(":")[0])[0])==1): speed = alpha travel_time = distance * speed GD[u][v]['travel_time'] = travel_time GD[u][v]['length'] = distance ''' Check whether the given edge is an highway edge TODO: Define how to extract highway info from edge ''' def is_highway_edge(edge): edge_layer_attr = edge["layer"].split(":")[0] edge_layer = int(re.findall('\d+', edge_layer_attr)[0]) return (edge_layer == 1)
3,128
21.191489
89
py
mlgd
mlgd-master/layout_quality_measurement/betametrics/drawing_highwayness.py
import networkx as nx import math import re def boundingBox(G, vertices=[]): all_pos = nx.get_node_attributes(G, "pos") if(len(vertices)>1): all_pos = dict((k, all_pos[k]) for k in vertices if k in all_pos) all_pos = all_pos.values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) max_x = float(coo_x[-1]) min_y = float(coo_y[0]) max_y = float(coo_y[-1]) width = abs(max_x - min_x) height = abs(max_y - min_y) return (width, height) def highwayDrawingCoverage(GD): all_layers = nx.get_edge_attributes(GD, "layer") highway_edges = {k: v for k, v in all_layers.items() if (int(re.findall('\d+', v.split(":")[0])[0])==1)} highway_vertices = set() for curr_edge in highway_edges.keys(): highway_vertices.add(curr_edge[0]) highway_vertices.add(curr_edge[1]) gd_bb = boundingBox(GD) hw_bb = boundingBox(GD, highway_vertices) gb_area = gd_bb[0] * gd_bb[1] hw_area = hw_bb[0] * hw_bb[1] return hw_area/gb_area
1,121
22.87234
109
py
mlgd
mlgd-master/layout_quality_measurement/betametrics/zigzagness.py
#zigzagness import networkx as nx import math import numpy as np def angleBetweenTwoPointsWithFixedPoint(point1X, point1Y, point2X, point2Y, fixedX, fixedY): """Computes the angle between two lines defined by three points.""" angle1 = math.atan2(point1Y - fixedY, point1X - fixedX) angle2 = math.atan2(point2Y - fixedY, point2X - fixedX) angle = angle1-angle2 if(angle<0): angle = 2*math.pi- abs(angle) degree = math.degrees(angle) min_degree = min(degree, 360-degree) return min_degree def slopeBetweenPoints(point1X, point1Y, point2X, point2Y): """Computes the slope between two points.""" dy = (point2Y-point1Y) dx = (point2X-point1X) if (dx == 0): dx += 1* math.pow(10, -100) print(dx) return dy/dx def compute_zigzagness(G): """Computes the zigzagness of the given tree.""" total_zigzagness = 0 # Get leaves as the vertices with degree 1 leaves = [x for x in G.nodes() if G.degree(x)==1] for i in range(0, len(leaves)): sourceStr = leaves[i] for j in range(i+1, len(leaves)): targetStr = leaves[j] if(sourceStr == targetStr): continue sp = nx.shortest_path(G, sourceStr, targetStr) curr_zigzagness = 0 prev_slope = 0 for firstIndex in range(0, len(sp)-2): secondIndex = firstIndex + 1 thirdIndex = secondIndex + 1 v1Identifier = sp[firstIndex] v2Identifier = sp[secondIndex] v3Identifier = sp[thirdIndex] v1 = G.node[v1Identifier] v2 = G.node[v2Identifier] v3 = G.node[v3Identifier] v1_x = float(v1['pos'].split(",")[0]) v1_y = float(v1['pos'].split(",")[1]) v2_x = float(v2['pos'].split(",")[0]) v2_y = float(v2['pos'].split(",")[1]) v3_x = float(v3['pos'].split(",")[0]) v3_y = float(v3['pos'].split(",")[1]) # Angle Version curr_angle = 180-angleBetweenTwoPointsWithFixedPoint(v1_x, v1_y, v3_x, v3_y, v2_x, v2_y) curr_zigzagness += curr_angle print(curr_angle) # # Slope Version # curr_slope = slopeBetweenPoints(v1_x, v1_y, v2_x, v2_y) # print(curr_slope) # if(firstIndex > 0): # curr_zigzagness += math.fabs(prev_slope - curr_slope) # prev_slope = curr_slope total_zigzagness += curr_zigzagness return total_zigzagness def compute_zigzagness_angle(GD): total_zigzagness = 0 # Get leaves as the vertices with degree 1 leaves = [x for x in GD.nodes() if GD.degree(x)==1] vertices_pos = nx.get_node_attributes(GD, 'pos') tot_penalty = 0 for i in range(0, len(leaves)): src = leaves[i] for j in range(i+1, len(leaves)): trg = leaves[j] if(src == trg): continue sp = nx.shortest_path(GD, src, trg) print(sp) path_angle_penality = 0 prev_angle = 0 prev_diff = 0 for k in range(0, len(sp)-1): v1 = sp[k] v2 = sp[k+1] v1_x = float(vertices_pos[v1].split(",")[0]) v1_y = float(vertices_pos[v1].split(",")[1]) v2_x = float(vertices_pos[v2].split(",")[0]) v2_y = float(vertices_pos[v2].split(",")[1]) curr_angle = np.rad2deg(np.arctan2(v2_y - v1_y, v2_x - v1_x)) if(k == 0): prev_angle = curr_angle angle_diff = curr_angle - prev_angle print("prev: "+ str(prev_angle) + " curr: " + str(curr_angle) + "prev diff: "+ str(prev_diff) + "curr diff: " + str(angle_diff)) curr_penality = compute_angle_penalty_continuous(prev_angle, curr_angle, prev_diff) print("pen: " + str(curr_penality)) path_angle_penality += curr_penality prev_angle = curr_angle prev_diff = angle_diff tot_penalty += path_angle_penality return tot_penalty def compute_angle_penalty_continuous(prev_angle, curr_angle, prev_diff): angle_diff = curr_angle - prev_angle if(angle_diff == 0): return 0 if(prev_angle == 0): print("test") if((np.sign(angle_diff) == np.sign(prev_diff)) or prev_diff == 0): angle_diff = abs(angle_diff) if(angle_diff >= 0 and angle_diff <=45): return angle_diff else: if(angle_diff >= 45 and angle_diff <=90): return abs(90-angle_diff) return abs(angle_diff-90) * 2 else: angle_diff = abs(angle_diff) if(angle_diff >= 0 and angle_diff <=45): return angle_diff * 2 else: if(angle_diff >= 45 and angle_diff <=90): return abs(90-angle_diff) * 2 return abs(angle_diff-90) * 3 def compute_angle_penalty_discrete(prev_angle, curr_angle, prev_diff): angle_diff = curr_angle - prev_angle if(angle_diff == 0): return 0 different_direction_penalty = 1 if((np.sign(angle_diff) == np.sign(prev_diff)) or prev_diff == 0): different_direction_penalty = 0 print("different direction") if (angle_diff >= -45 and angle_diff <= 45): return 1 + different_direction_penalty if (angle_diff >= -90 and angle_diff <= 90): return 2 + different_direction_penalty if (angle_diff >= -135 and angle_diff <= 135): return 4 + different_direction_penalty return 5 + different_direction_penalty print("missing value: " + str(angle_diff)) return 0
5,545
21.917355
134
py
mlgd
mlgd-master/ml_tree_extractor/fix_node_att_add_font_box.py
import sys import networkx as nx import pygraphviz as pgv from networkx.readwrite import json_graph import tkinter from tqdm import tqdm from tkinter import * fontsize=[30,25,20,15,12,10,9,8] fontname='Arial' def getBoxSize(txt,l): Window = Tk() Window.geometry("500x500+80+80") frame = Frame(Window) # this will hold the label frame.pack(side = "top") measure = Label(frame, font = (fontname, fontsize[l]), text = txt) measure.grid(row = 0, column = 0) # put the label in measure.update_idletasks() # this is VERY important, it makes python calculate the width width = round( round(measure.winfo_width() / 72, 2) * 72 * 1.10, 2) # get the width height= round( round(measure.winfo_height()/72 ,2) * 72 * 1.10, 2 ) # width = round(measure.winfo_width() /72, 2) # get the width # height= round(measure.winfo_height()/72,2) return height,width, str( fontsize[l]) def get_all_node_att(T,G): allboxatt={} for x in tqdm(T.nodes()): layer=str(getLayer(x)) h,w,s=getBoxSize(G.nodes[x]["label"],int(layer)-1) hw=" height="+str(h) + ", width="+ str( w)+ ", fontsize= "+ s+", fontname=\""+fontname+"\"" nodes= "" + str( x) + " [label=\""+G.nodes[x]["label"]+"\", level="+layer+", weight=\""+ G.nodes[x]["weight"] +"\" , "+ hw+"];\n" allboxatt[str( x)]=nodes #print(x) return allboxatt from networkx.drawing.nx_agraph import write_dot T=[] L=8 # #folderpath="EU/" input_folderpath="tmp/" output_folder='outputs/' #fileformat="Layer_{0}_EU_core.dot" input_file_format="Layer_{0}.dot" outformat="output_Layer_{0}.dot" G_file_name="graph_connected.dot" #G_file_name="EU_core_orginal.dot" #G_out="G_EU_core_id.dot" G_out="output_graph.dot" G=nx.Graph(pgv.AGraph(input_folderpath+G_file_name)) for i in range(0,L): R=nx.Graph(pgv.AGraph(input_folderpath+input_file_format.format(i+1))) T.append(R) def getLayer(x): for i in range(0,L): if x in T[i].nodes(): return i+1 def write_to_file(folderpath,G_out, nodes, edges ): f=open(folderpath+G_out,"w") txt="graph {" + nodes + edges + "}" f.write(txt) f.close() print("done writing G", ) def writeG(T,G,allboxatt): nodes="" edges="" for x in T.nodes(): nodes= nodes+allboxsizes[ str( x)] for x in G.edges(): w=G[x[0]][x[1]]['weight'] edges=edges + x[0] + " -- " + x[1] + "[weight=\""+ str(w)+"\"];\n" write_to_file(output_folder,G_out, nodes, edges ) def writeLayer(T,l,allboxatt): nodes="" edges="" for x in T.nodes(): nodes= nodes+allboxsizes[ str( x)] for x in T.edges(): w=G[x[0]][x[1]]['weight'] edges=edges + x[0] + " -- " + x[1] + "[weight=\""+ str(w)+"\"];\n" write_to_file(output_folder,outformat.format(l), nodes, edges ) allboxsizes=get_all_node_att(T[L-1],G) for i in range(0,L): writeLayer(T[i],str(i+1),allboxsizes) writeG( T[L-1],G,allboxsizes)
2,965
28.366337
139
py
mlgd
mlgd-master/ml_tree_extractor/mltree_generator_weighted.py
import sys import networkx as nx import pygraphviz as pgv import math from networkx.readwrite import json_graph from networkx.drawing.nx_agraph import write_dot #EU-core nodecountinlevels=[0.10,0.25,0.30,0.40,0.70,0.80,0.95,1.0] nodecountinlevels=[0.005,0.05,0.10,0.20,0.30,0.50,0.85,1.0] filepath=sys.argv[1] output_dir='tmp/' def isEnglish(s): try: s.encode(encoding='utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True def fixEdgeWeightAndRemoveNonEngNode(G): H=G.copy() data=H.nodes() c=0 for x in data: if isEnglish(x)==False: print("droping",c) c=c+1 G.remove_node(x) for x in G.edges(): G[x[0]][x[1]]['weight']=float(G[x[0]][x[1]]['weight']) return G def getnodes(s,n): selected=[] for node in range(0,n): selected.append(s[node][0]) return selected def genTree(G,selectednodes): for x in range(0, len(selectednodes)): for y in range(x+1, len(selectednodes)): p=nx.shortest_path(G,x,y) def extract(mst,selectednodes): H=nx.Graph() for x in range(0, len(selectednodes)): for y in range(x+1, len(selectednodes)): p=nx.shortest_path(mst,selectednodes[x],selectednodes[y]) for i in range(0,len(p)-1): H.add_node(p[i]) H.add_edge(p[i], p[i+1]) return H def extract2(paths,selectednodes): H=nx.Graph() for x in range(0, len(selectednodes)): for y in range(x+1, len(selectednodes)): p=paths[selectednodes[x]][selectednodes[y]] for i in range(0,len(p)-1): H.add_node(p[i]) #import pdb; pdb.set_trace() H.add_edge(p[i], p[i+1]) return H G=nx.Graph(pgv.AGraph(filepath)) G=fixEdgeWeightAndRemoveNonEngNode(G) H=nx.connected_component_subgraphs(G) G=list(H)[0] #mst=nx.minimum_spanning_tree(G) mst=nx.maximum_spanning_tree(G) paths=nx.shortest_path(mst) #c=nx.algorithms.degree_centrality(G) c=nx.get_node_attributes(G,'weight') c={k:int(v) for k, v in c.items()} s=sorted(c.items(), key=lambda x: x[1], reverse=True) T=nx.Graph() ''' for i in range(0, len(nodecountinlevels)): gn=nx.Graph() nodes=getnodes(s,int(nodecountinlevels[i] * len(G.nodes()))) gn.add_nodes_from(nodes) print(len(nodes), " ", round(100* len(nodes)/len(G.nodes() )), "%") write_dot(gn,'Layer_'+str(i+1)+'_terminals.dot') # import pdb; pdb.set_trace() ''' for i in range(0, len(nodecountinlevels)): selectednodes= list(set(list(T.nodes())+ getnodes(s,int(nodecountinlevels[i] * len(G.nodes()))))) print(len(selectednodes)) T=extract2(paths,selectednodes) print("Layer", i+1, "nodes:", len(T.nodes())) write_dot(T,output_dir+'Layer_'+str(i+1)+'.dot') write_dot(G,output_dir+'graph_connected.dot')
2,892
25.3
101
py
mlgd
mlgd-master/ml_tree_extractor/degree_reducer.py
#idea of degree reduce comes from Faryad Darabi Sahneh #written by Iqbal Hossain import networkx as nx import pygraphviz as pgv import argparse from networkx.drawing.nx_agraph import write_dot def graph_reducer(G, cuttoff=50): """Reduce degree by using ZTest with cuttoff 50 Parameters ---------- G : node and edge weighted graph Returns ------- G: output reduced graph """ node_frequency = nx.get_node_attributes(G, 'weight') total = sum(int(node_frequency[k]) for k in node_frequency.keys()) # updating edge weight based on ZTest edges = list(G.edges()) for e in edges: topicFreq_i = int(G.nodes[e[0]]["weight"]) topicProb_j = int(G.nodes[e[1]]["weight"]) / total expected = topicFreq_i * topicProb_j ZTest = (int(G.edges[e]["weight"]) - expected)/(expected**0.5) if ZTest < cuttoff: G.remove_edge(*e) else: G.edges[e]["weight"] = ZTest #taking only max connected component Gc = max(nx.connected_components(G), key=len) G = nx.subgraph(G, Gc) return G if __name__ == "__main__": parser = argparse.ArgumentParser(description='graph reducer') parser.add_argument('-i', '--input_dot', default='input', help='input dot path', required=True) parser.add_argument('-o', '--output_dot', default='outputs', help='Output dot path', required=True) args = parser.parse_args() G = nx.Graph(pgv.AGraph(args.input_dot)) print("old max degree:", max([d for n, d in G.degree()])) G=graph_reducer(G) print("new max degree:", max([d for n, d in G.degree()])) write_dot(G,args.output_dot)
1,716
29.660714
70
py
mlgd
mlgd-master/ml_tree_extractor/old_files/json_write.py
from networkx.drawing.nx_agraph import write_dot import networkx as nx import pygraphviz as pgv dotpath='/Users/iqbal/MLGD/mlgd/datasets/topics/set2/input/Topics_Layer_8.dot' G=nx.Graph(pgv.AGraph(dotpath)) weightededgedot= open('Layer8.js', 'w') # as csv_file: e = "\"source\":\"{}\", \"target\":\"{}\", \"weight\":{}" #854 -- 3860[weight="7"]; # #v ='''[label:"immunology", level=1, weight="2783" , height=0.56, width=2.33, fontsize= 30, fontname="Arial"];''' v ='"id":"{}", "label":"{}", "level":{}, "weight":{} , "height":{}, "width":{}, "fontsize": {}, "fontname":"{}"' nlist="" for n in G.nodes(): nlist=nlist+ "{ " + v.format(n,G.node[n]["label"],G.node[n]["level"],G.node[n]["weight"],G.node[n]["height"],G.node[n]["width"],G.node[n]["fontsize"],G.node[n]["fontname"] ) + " },\n" nlist=nlist[:len(nlist)-3]+"}" eid=0 elist="" for edge in G.edges(): elist=elist + "{"+e.format(edge[0],edge[1], G[edge[0]][edge[1]]["weight"]) + "},\n" eid=eid+1 elist=elist[:len(elist)-3]+"}" weightededgedot.write ("var graph={ \"nodes\":[ " + nlist + "],\n \"links\":[ " + elist + "] }")
1,091
36.655172
185
py
mlgd
mlgd-master/ml_tree_extractor/old_files/MLST_cost.py
import sys, os import networkx as nx import pygraphviz as pgv import numpy as np import matplotlib.pyplot as plt def edges_sum(T): """ takes a tree and find cost of edges :param T: tree :return cost: sum of cost of edges """ s=0 for x in T.edges(): s=s+1/(float(T[x[0]][x[1]]['weight'])) return s def main(folderpath,fileformat): """ calculates cost of a set of trees (dot file with edge attribute: weight) :param folderpath: folder location of trees :param fileformat: format of file name :return MLST cost """ cost=0 costs=[] nodes_count=[] for i in range(0,8): t=nx.Graph(pgv.AGraph(folderpath+fileformat.format(i+1))) c=edges_sum(t) cost=cost+c costs.append( c) nodes_count.append(len(t.nodes())) con= "Connected" if nx.is_connected(t)==True else "Disconnected" print("tree" , i+1, ": nodes: ", len(t.nodes()) ,"edges: ", len(t.edges()), " cost:", c , con ) x = np.arange(0,8) plt.plot(x, costs, 'o-') plt.plot(x, nodes_count, 'o-') for i,j in zip(x,costs): plt.annotate( str(int(j)) ,xy=(i,j+10)) for i,j in zip(x,nodes_count): plt.annotate( str(int(j))+ " (" + str(int(100* int(j)/nodes_count[7])) + "%)" ,xy=(i+0.1,j+5)) plt.xlabel('levels') plt.ylabel('costs or node count') plt.legend(['costs (total '+ str(int(cost)) +')', 'node count'], loc='upper left') plt.show() # print(nx.is_connected(t)) # print("tree" , i+1, ": edge count: ", len(t.edges()) , " cost:", c ) return cost if __name__=="__main__": folderpath="../../datasets/topics/set2/input/" fileformat="Topics_Layer_{0}.dot" folderpath="" fileformat="Layer_{0}.dot" cost=main(folderpath,fileformat) print("Total Cost", cost)
1,834
27.230769
103
py
mlgd
mlgd-master/ml_tree_extractor/old_files/mltree_generator_non_weighted.py
import sys import networkx as nx import pygraphviz as pgv import math from networkx.readwrite import json_graph from networkx.drawing.nx_agraph import write_dot #EU-core nodecountinlevels=[0.10,0.25,0.30,0.40,0.70,0.80,0.95,1.0] nodecountinlevels=[0.10,0.25,0.30,0.40,0.70,0.80,0.95,1.0] def getnodes(s,n): selected=[] for node in range(0,n): selected.append(s[node][0]) return selected def genTree(G,selectednodes): for x in range(0, len(selectednodes)): for y in range(x+1, len(selectednodes)): p=nx.shortest_path(G,x,y) def extract(mst,selectednodes): H=nx.Graph() for x in mst.nodes(): if x in selectednodes: H.add_node(x,G.node[x]) for x in T.edges(): H.add_edge(x[0],x[1]) return H def extract(mst,selectednodes): H=nx.Graph() for x in range(0, len(selectednodes)): for y in range(x+1, len(selectednodes)): p=nx.shortest_path(mst,selectednodes[x],selectednodes[y]) for i in range(0,len(p)-1): H.add_node(p[i]) H.add_edge(p[i], p[i+1]) return H G=nx.Graph(pgv.AGraph("r.dot")) H=nx.connected_component_subgraphs(G) G=list(H)[0] mst=nx.minimum_spanning_tree(G) c=nx.degree_centrality(G) s=sorted(c.items(), key=lambda x: x[1], reverse=True) T=nx.Graph() for i in range(0, len(nodecountinlevels)): selectednodes= list(set(T.nodes()+ getnodes(s,int(nodecountinlevels[i] * len(G.nodes()))))) print(len(selectednodes)) T=extract(mst,selectednodes) print("Layer", i+1, "nodes:", len(T.nodes())) write_dot(T,'Layer_'+str(i+1)+'_EU_core.dot') write_dot(G,'EU_core.dot')
1,671
24.723077
95
py
mlgd
mlgd-master/ml_tree_extractor/old_files/text_to_id_converter_single_graph.py
import sys import networkx as nx import pygraphviz as pgv from networkx.readwrite import json_graph from networkx.drawing.nx_agraph import write_dot G_file_name="/Users/iqbal/MLGD/mlgd/datasets/topics/orginal/Topics_Graph.dot" G_out="/Users/iqbal/MLGD/mlgd/datasets/topics/orginal/Topics_Graph_Connected.dot" G=nx.Graph(pgv.AGraph(G_file_name)) H=nx.connected_component_subgraphs(G) G=list(H)[0] def replace(str): str=str.replace("\xe9","").replace("\xf3","").replace("\xed","").replace("\xe1","").replace("\xfa","") return str nodeid={} i=1 for x in G.nodes(): nodeid[x]=i i=i+1 def writeG(G): nodes="" edges="" for x in G.nodes(): #import pdb; pdb.set_trace() nodes=nodes+ "" + str( nodeid[x]) + " [label=\""+replace(G.nodes[x]["label"])+"\", weight=\""+ G.nodes[x]["weight"] +"\" ];\n" for x in G.edges(): if x[0] in nodeid and x[1] in nodeid: w=G[x[0]][x[1]]['weight'] if 'weight' in G[x[0]][x[1]] else 1 edges=edges + str(nodeid[x[0]]) + " -- " + str(nodeid[x[1]]) + "[weight=\""+ str(w)+"\"];\n" f=open(G_out,"w") txt="graph {" + nodes + edges + "}" f.write(txt) f.close() print("done writing G", ) writeG(G)
1,228
25.148936
135
py
mlgd
mlgd-master/ml_tree_extractor/old_files/MLST_cost_inverse_weight.py
import sys, os import networkx as nx import pygraphviz as pgv import matplotlib.pyplot as plt import numpy as np def edges_sum(T,G): """ takes a tree and find cost of edges :param T: tree :return cost: sum of cost of edges """ s=0 for x in T.edges(): s=s+1/float( G[x[0]][x[1]]['weight']) #s=s+float( T[x[0]][x[1]]['weight']) return s def main(folderpath,fileformat): """ calculates cost of a set of trees (dot file with edge attribute: weight) :param folderpath: folder location of trees :param fileformat: format of file name :return MLST cost """ cost=0 costs=[] nodes_count=[] G=nx.Graph(pgv.AGraph('/Users/iqbal/MLGD/mlgd/pipeline/ml_tree_extractor/topics/Topics_Graph_Connected.dot')) for i in range(0,8): t=nx.Graph(pgv.AGraph(folderpath+fileformat.format(i+1))) c=edges_sum(t,G) cost=cost+c costs.append( c) nodes_count.append(len(t.nodes())) con= "Connected" if nx.is_connected(t)==True else "Disconnected" print("tree" , i+1, ": nodes: ", len(t.nodes()) ,"edges: ", len(t.edges()), " cost:", c , con ) x = np.arange(0,8) plt.plot(x, costs, 'o-') plt.plot(x, nodes_count, 'o-') for i,j in zip(x,costs): plt.annotate( str(int(j)) ,xy=(i,j+10)) for i,j in zip(x,nodes_count): plt.annotate( str(int(j))+ " (" + str(int(100* int(j)/nodes_count[7])) + "%)" ,xy=(i+0.1,j+5)) plt.xlabel('levels') plt.ylabel('costs or node count') plt.legend(['costs (total '+ str(int(cost)) +')', 'node count'], loc='upper left') plt.show() return cost if __name__=="__main__": folderpath="/Users/iqbal/Desktop/top_down/" folderpath="/Users/iqbal/Desktop/remlst/bottom_up/" fileformat="Composite_layer_{0}.dot" fileformat="Top_down_layer_{0}.dot" fileformat="Bottom_up_layer_{0}.dot" folderpath="" fileformat="Layer_{0}_topics_v2.dot" cost=main(folderpath,fileformat) print("Total Cost", cost)
2,035
26.890411
113
py
mlgd
mlgd-master/layout_generator/raw_data/modules/backbonnessimprovement/vertexmanager.py
import networkx as nx def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex)
388
13.961538
42
py
mlgd
mlgd-master/layout_generator/raw_data/modules/backbonnessimprovement/path_straighter.py
import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random import treestraightner # Main Flow graphpath = sys.argv[1] outputpath = sys.argv[2] # Main Graph input_graph_name = os.path.basename(graphpath) graph_name = input_graph_name.split(".")[0] # Reading graph and subgraph G = nx_read_dot(graphpath) nx.set_edge_attributes(G, 'red', 'color') treestraightner.rectify_Tree(G) G = nx.Graph(G) write_dot(G, outputpath)
576
16.484848
62
py
mlgd
mlgd-master/layout_generator/raw_data/modules/backbonnessimprovement/treestraightner.py
import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random import vertexmanager def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): vertexmanager.shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def extract_leaves(G): """Extracts from <tt>G</tt> the vertices with degree 1, i.e. the leaves.""" leaves=[] for n in nx.nodes(G): if len(list(G.neighbors(n)))<=1: leaves.append(n) return leaves def rotate(G, angle): angle = math.radians(angle) for currVertex in nx.nodes(G): x, y = vertexmanager.getCoordinate(G.node[currVertex]) x_rot = x*math.cos(angle) - y*math.sin(angle) y_rot = x*math.sin(angle) + y*math.cos(angle) vertexmanager.setCoordinate(G.node[currVertex], x_rot, y_rot) return G def angle_three_vertices(p1x, p1y, p2x, p2y, p3x, p3y): result = math.atan2(p3y - p1y, p3x - p1x) - math.atan2(p2y - p1y, p2x - p1x); return result def getAngleOfLineBetweenTwoPoints(point1X, point1Y, point2X, point2Y): xDiff = point2X - point1X yDiff = point2Y - point1Y return math.degrees(math.atan2(yDiff, xDiff)) def rectify_Tree(G): leaves = extract_leaves(G) shortest_sp_len = float("-inf") shortest_sp = [] for i in range(0, len(leaves)): for j in range(i+1, len(leaves)): source_id = leaves[i] target_id = leaves[j] source = G.node[source_id] target = G.node[target_id] curr_sp_len = nx.shortest_path_length(G, source=source_id, target=target_id) if(curr_sp_len>shortest_sp_len): shortest_sp_len = curr_sp_len shortest_sp = nx.shortest_path(G, source=source_id, target=target_id) print(shortest_sp_len) print(shortest_sp) return G
2,031
23.780488
88
py
mlgd
mlgd-master/layout_generator/raw_data/modules/label_positioning/label_positioning.py
0
0
0
py
mlgd
mlgd-master/layout_generator/raw_data/modules/uniform_leaves_edges/uniform_leaves_edges.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random def getCoordinate(vertex): """Returns the coordinate of the given vertex.""" x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def compute_edge_length(G, edge): """Computes the length of the given edge the position of the vertices is given by the <tt>pos</tt> attribute <strong>return</strong> length of the given edge as a double """ s1_id,t1_id = edge nodes_position = nx.get_node_attributes(G, 'pos') s1_pos = nodes_position[s1_id] t1_pos = nodes_position[t1_id] x_source1 = float(s1_pos.split(",")[0]) x_target1 = float(t1_pos.split(",")[0]) y_source1 = float(s1_pos.split(",")[1]) y_target1 = float(t1_pos.split(",")[1]) curr_length = math.sqrt((x_source1 - x_target1)**2 + (y_source1 - y_target1)**2) return curr_length def avg_edge_length(G): """Computes the average length of the given edges set <strong>return</strong> average length of the edges as a double """ edges = G.edges() sum_edge_length = 0.0 edge_count = len(edges) for e in edges: curr_length = compute_edge_length(G, e) sum_edge_length += curr_length avg_edge_len = sum_edge_length/edge_count return avg_edge_len def extract_leaves(G): """Extracts from <tt>G</tt> the vertices with degree 1, i.e. the leaves.""" leaves=[] for n in nx.nodes(G): if len(list(G.neighbors(n)))<=1: leaves.append(n) return leaves def unify_leaves_edges_leghths(G, value=-1): """This function sets the length of the edges incident on the leaves of a tree to a fixed value. The idea is to position the leaves next to their parent to save space. The edges are set to the given <tt>value</tt> parameter. If no value is given or it is set to -1 then the edges are set to half the length of the average edge lenght.""" avgEdgeLength = avg_edge_length(G) # If the edge length value is not given set it half the length of the # average length value if value == -1: value = avgEdgeLength/3 leaves = extract_leaves(G) to_be_shortened_edges = list(nx.edges(G, leaves)) for e in to_be_shortened_edges: if compute_edge_length(G, e) <= value: continue t_id, s_id = e s = G.node[s_id] t = G.node[t_id] origin = s leaf = t origin_id = s_id leaf_id = t_id if s in leaves: origin = t origin_id = t_id leaf = s leaf_id = s_id x_origin, y_origin = getCoordinate(origin) x_leaf, y_leaf = getCoordinate(leaf) x_num = value * (x_leaf - x_origin) y_num = value * (y_leaf - y_origin) x_den = math.sqrt((x_origin-x_leaf)**2 + (y_origin-y_leaf)**2) y_den = math.sqrt((x_origin-x_leaf)**2+(y_origin-y_leaf)**2) x_leaf_new = x_origin + x_num/x_den y_leaf_new = y_origin + y_num/y_den G.node[leaf_id]['pos'] = str(x_leaf_new)+","+str(y_leaf_new) return G
3,353
23.481752
84
py
mlgd
mlgd-master/layout_generator/raw_data/modules/uniform_leaves_edges/uniform_leaves_edges_main.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random import uniform_leaves_edges as uniformer tree_path = sys.argv[1] # Main Graph tree_path_name = os.path.basename(tree_path).split(".")[0] # Reading graph and subgraph G = nx_read_dot(tree_path) G = uniformer.unify_leaves_edges_leghths(G) G = nx.Graph(G) write_dot(G, tree_path)
551
16.25
62
py
mlgd
mlgd-master/layout_generator/raw_data/modules/planar_augmentation/crossings.py
#Author #Felice De Luca #https://github.com/felicedeluca import math import networkx as nx # Given three colinear points p, q, r, the function checks if # point q lies on line segment 'pr' def onSegment(px, py, qx, qy, rx, ry): if (qx <= max(px, rx) and qx >= min(px, rx) and qy <= max(py, ry) and qy >= min(py, ry)): return True return False def strictlyOnSegment(px, py, qx, qy, rx, ry): if (qx < max(px, rx) and qx > min(px, rx) and qy < max(py, ry) and qy > min(py, ry)): return True return False # To find orientation of ordered triplet (p, q, r). # The function returns following values # 0 --> p, q and r are colinear # 1 --> Clockwise # 2 --> Counterclockwise def orientation(px, py, qx, qy, rx, ry): # See http://www.geeksforgeeks.org/orientation-3-ordered-points/ # for details of below formula. val = (qy - py) * (rx - qx) - (qx - px) * (ry - qy) if (val == 0):return 0 # clock or counterclock wise if (val > 0): return 1 else: return 2 def yInt(x1, y1, x2, y2): if (y1 == y2):return y1 return y1 - slope(x1, y1, x2, y2) * x1 def slope(x1, y1, x2, y2): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)) if (x1 == x2):return False return (y1 - y2) / (x1 - x2) # The main function that returns true if line segment 'p1q1' # and 'p2q2' intersect. def doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): # Find the four orientations needed for general and # special cases o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y) o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y) o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y) o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y) #if(o1==0 or o2==0 or o3==0 or o4==0):return False # General case if (o1 != o2 and o3 != o4): return True # Special Cases # p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 and onSegment(p1x, p1y, p2x, p2y, q1x, q1y)):return True # p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 and onSegment(p1x, p1y, q2x, q2y, q1x, q1y)):return True # p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 and onSegment(p2x, p2y, p1x, p1y, q2x, q2y)):return True # p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 and onSegment(p2x, p2y, q1x, q1y, q2x, q2y)):return True return False # Doesn't fall in any of the above cases def isSameCoord(x1, y1, x2, y2): if x1==x2 and y1==y2: return True return False # do p is an end point of edge (u,v) def isEndPoint(ux, uy, vx, vy, px, py): if isSameCoord(ux, uy, px, py) or isSameCoord(vx, vy, px, py): return True return False # is (p1,q1) is adjacent to (p2,q2)? def areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isEndPoint(p1x, p1y, q1x, q1y, p2x, p2y): return True elif isEndPoint(p1x, p1y, q1x, q1y, q2x, q2y): return True return False def isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): x1 = p1x-q1x y1 = p1y-q1y x2 = p2x-q2x y2 = p2y-q2y cross_prod_value = x1*y2 - x2*y1 if cross_prod_value==0: return True return False # here p1q1 is one segment, and p2q2 is another # this function checks first whether there is a shared vertex # then it checks whether they are colinear # finally it checks the segment intersection def doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if strictlyOnSegment(p1x, p1y, p2x, p2y, q1x, q1y) or strictlyOnSegment(p1x, p1y, q2x, q2y, q1x, q1y) or strictlyOnSegment(p2x, p2y, p1x, p1y, q2x, q2y) or strictlyOnSegment(p2x, p2y, q1x, q1y, q2x, q2y): return True else: return False else: return False return doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) def getIntersection(x11, y11, x12, y12, x21, y21, x22, y22): slope1 = 0 slope2 = 0 yint1 = 0 yint2 = 0 intx = 0 inty = 0 #TODO: Please Check all four cases if (x11 == x21 and y11 == y21):return [x11, y11] if (x12 == x22 and y12 == y22):return [x12, y22] # Check 1st point of edge 1 with 2nd point of edge 2 and viceversa slope1 = slope(x11, y11, x12, y12) slope2 = slope(x21, y21, x22, y22) #print('slope1:'+str(slope1)) #print('slope2:'+str(slope2)) if (slope1 == slope2):return False yint1 = yInt(x11, y11, x12, y12) yint2 = yInt(x21, y21, x22, y22) #print('yint1:'+str(yint1)) #print('yint2:'+str(yint2)) if (yint1 == yint2): if (yint1 == False):return False else:return [0, yint1] if(x11 == x12):return [x11, slope2*x11+yint2] if(x21 == x22):return [x21, slope1*x21+yint1] if(y11 == y12):return [(y11-yint2)/slope2,y11] if(y21 == y22):return [(y21-yint1)/slope1,y21] if (slope1 == False):return [y21, slope2 * y21 + yint2] if (slope2 == False):return [y11, slope1 * y11 + yint1] intx = (yint1 - yint2)/ (slope2-slope1) return [intx, slope1 * intx + yint1] def to_deg(rad): return rad*180/math.pi # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSegDegree(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) #return angle return to_deg(angle) # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSeg(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) return angle def count_crossings(G, all_pos_H_dict=None, edge_list_H=None, stop_when_found=False): """Counts the number of crossings of the given Graph <tt>G</tt> if <tt>stop_when_found</tt> is true then the function stops when the first crossing is found. If <tt>all_pos_H_dict</tt> and <tt>edge_list_H</tt> are given then it checks the crossings between <tt>G</tt> and <tt>H</tt>.""" count = 0 edge_list_G = list(G.edges) all_pos_G = nx.get_node_attributes(G, "pos") all_pos_G_dict = dict((k, (float(all_pos_G[k].split(",")[0]), float(all_pos_G[k].split(",")[1]))) for k in all_pos_G.keys()) external_edge_list = edge_list_G internal_edge_list = edge_list_G all_pos_external_dict = all_pos_G_dict all_pos_internal_dict = all_pos_G_dict if all_pos_H_dict is not None: all_pos_external_dict = all_pos_H_dict if edge_list_H is not None: external_edge_list = edge_list_H for c1 in range(0, len(external_edge_list)): internal_lowerbound = c1+1 if edge_list_H is not None: internal_lowerbound = 0 for c2 in range(internal_lowerbound, len(internal_edge_list)): edge1 = external_edge_list[c1] edge2 = internal_edge_list[c2] (s1,t1) = (edge1[0], edge1[1]) (s2,t2) = (edge2[0], edge2[1]) p1 = all_pos_external_dict[s1] q1 = all_pos_external_dict[t1] p2 = all_pos_internal_dict[s2] q2 = all_pos_internal_dict[t2] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): count = count + 1 if (stop_when_found): return count # if len(segment_pair)==2: # count = count + 1 # else: # count = count + comb(len(segment_pair), 2) return count
8,115
30.215385
207
py
mlgd
mlgd-master/layout_generator/raw_data/modules/planar_augmentation/planar_augmentation.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import crossings # Main Flow subgraph_path = sys.argv[1] graph_path = sys.argv[2] outputpath = sys.argv[3] # Main Graph input_subgraph_name = os.path.basename(subgraph_path) subgraph_name = input_subgraph_name.split(".")[0] # Sub Graph to be added input_graph_name = os.path.basename(graph_path) graph_name = input_graph_name.split(".")[1] # Reading graph and subgraph subG = nx_read_dot(subgraph_path) nx.set_edge_attributes(subG, 'red', 'color') # subG.remove_edges_from(subG.selfloop_edges()) subG=nx.Graph(subG) G = nx_read_dot(graph_path) nx.set_edge_attributes(G, 'black', 'color') # G.remove_edges_from(G.selfloop_edges()) G=nx.Graph(G) induced_G = nx.Graph(G.subgraph(nx.nodes(subG))) edges_to_be_added = list(nx.edges(induced_G)) fake_edges_levels = dict() v_pos = nx.get_node_attributes(subG, "pos") for e in edges_to_be_added: (s1,t1) = (e[0], e[1]) if s1 == t1: continue if e in list(nx.edges(subG)): continue single_edge_list = [e] crossing = crossings.count_crossings(G=subG, edge_list_H=single_edge_list, stop_when_found=True) if crossing > 0: continue (u, v) = e if u not in nx.nodes(subG) or v not in nx.nodes(subG): continue x_source = float(v_pos[u].split(",")[0]) y_source = float(v_pos[u].split(",")[1]) x_target = float(v_pos[v].split(",")[0]) y_target = float(v_pos[v].split(",")[1]) geomDistance = math.sqrt((x_source - x_target)**2 + (y_source - y_target)**2) if geomDistance < 0.01: continue subG.add_edges_from(single_edge_list) fake_edges_levels[e] = 1 crossing = crossings.count_crossings(G=subG, edge_list_H=single_edge_list, stop_when_found=True) selfloops=subG.selfloop_edges() subG.remove_edges_from(list(selfloops)) subG.remove_edges_from(selfloops) subG = nx.Graph(subG) print("saving in ", outputpath) write_dot(subG, outputpath) print("end")
2,169
20.27451
100
py
mlgd
mlgd-master/layout_generator/raw_data/modules/planar_augmentation/planartriangulationheuristic.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import math import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import edge_crossing # Main Flow graph_path = sys.argv[1] output_path = sys.argv[2] G = nx_read_dot(graph_path) G = nx.Graph(G) nx.set_edge_attributes(G, 'red', 'color') nodes = list(nx.nodes(G)) all_edges=[] for v_id in range(0, len(nodes)): v = nodes[v_id] for u_id in range(v_id+1, len(nodes)): u = nodes[u_id] all_edges.append((u,v)) edges = list(nx.edges(G)) for to_add_e in all_edges: u, v = to_add_e if ((u, v) in edges) or ((v, u) in edges): continue if edge_crossing.count_crossings(G, edges_to_compare=[to_add_e]): continue G.add_nodes_from([u, v]) print("edge added") G=nx.Graph(G) write_dot(G, output_path)
924
15.517857
69
py
mlgd
mlgd-master/layout_generator/raw_data/modules/planar_augmentation/subgraph_extractor.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot # Main Flow graph_path = sys.argv[1] subgraph_path = sys.argv[2] outputpath = sys.argv[3] # Main Graph input_subgraph_name = os.path.basename(subgraph_path) subgraph_name = input_subgraph_name.split(".")[0] # Sub Graph to be added input_graph_name = os.path.basename(graph_path) graph_name = input_graph_name.split(".")[1] # Reading graph and subgraph subG = nx_read_dot(subgraph_path) nx.set_edge_attributes(subG, 'red', 'color') G = nx_read_dot(graph_path) pos = nx.get_node_attributes(G, 'pos') nx.set_node_attributes(subG, pos, 'pos') induced_G = nx.Graph(subG) # print(nx.info(G)) print("saving in ", outputpath) write_dot(induced_G, outputpath) print("end")
913
20.255814
62
py
mlgd
mlgd-master/layout_generator/raw_data/modules/planar_augmentation/edge_crossing.py
#Author #Felice De Luca #https://github.com/felicedeluca # import math import networkx as nx # Given three colinear points p, q, r, the function checks if # point q lies on line segment 'pr' def onSegment(px, py, qx, qy, rx, ry): if (qx <= max(px, rx) and qx >= min(px, rx) and qy <= max(py, ry) and qy >= min(py, ry)): return True return False def strictlyOnSegment(px, py, qx, qy, rx, ry): if (qx < max(px, rx) and qx > min(px, rx) and qy < max(py, ry) and qy > min(py, ry)): return True return False # To find orientation of ordered triplet (p, q, r). # The function returns following values # 0 --> p, q and r are colinear # 1 --> Clockwise # 2 --> Counterclockwise def orientation(px, py, qx, qy, rx, ry): # See http://www.geeksforgeeks.org/orientation-3-ordered-points/ # for details of below formula. val = (qy - py) * (rx - qx) - (qx - px) * (ry - qy) if (val == 0):return 0 # clock or counterclock wise if (val > 0): return 1 else: return 2 def yInt(x1, y1, x2, y2): if (y1 == y2):return y1 return y1 - slope(x1, y1, x2, y2) * x1 def slope(x1, y1, x2, y2): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)) if (x1 == x2):return False return (y1 - y2) / (x1 - x2) # The main function that returns true if line segment 'p1q1' # and 'p2q2' intersect. def doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): # Find the four orientations needed for general and # special cases o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y) o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y) o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y) o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y) #if(o1==0 or o2==0 or o3==0 or o4==0):return False # General case if (o1 != o2 and o3 != o4): return True # Special Cases # p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 and onSegment(p1x, p1y, p2x, p2y, q1x, q1y)):return True # p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 and onSegment(p1x, p1y, q2x, q2y, q1x, q1y)):return True # p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 and onSegment(p2x, p2y, p1x, p1y, q2x, q2y)):return True # p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 and onSegment(p2x, p2y, q1x, q1y, q2x, q2y)):return True return False # Doesn't fall in any of the above cases def isSameCoord(x1, y1, x2, y2): if x1==x2 and y1==y2: return True return False # do p is an end point of edge (u,v) def isEndPoint(ux, uy, vx, vy, px, py): if isSameCoord(ux, uy, px, py) or isSameCoord(vx, vy, px, py): return True return False # is (p1,q1) is adjacent to (p2,q2)? def areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isEndPoint(p1x, p1y, q1x, q1y, p2x, p2y): return True elif isEndPoint(p1x, p1y, q1x, q1y, q2x, q2y): return True return False def isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): x1 = p1x-q1x y1 = p1y-q1y x2 = p2x-q2x y2 = p2y-q2y cross_prod_value = x1*y2 - x2*y1 if cross_prod_value==0: return True return False # here p1q1 is one segment, and p2q2 is another # this function checks first whether there is a shared vertex # then it checks whether they are colinear # finally it checks the segment intersection def doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if strictlyOnSegment(p1x, p1y, p2x, p2y, q1x, q1y) or strictlyOnSegment(p1x, p1y, q2x, q2y, q1x, q1y) or strictlyOnSegment(p2x, p2y, p1x, p1y, q2x, q2y) or strictlyOnSegment(p2x, p2y, q1x, q1y, q2x, q2y): return True else: return False else: return False return doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) def getIntersection(x11, y11, x12, y12, x21, y21, x22, y22): slope1 = 0 slope2 = 0 yint1 = 0 yint2 = 0 intx = 0 inty = 0 #TODO: Please Check all four cases if (x11 == x21 and y11 == y21):return [x11, y11] if (x12 == x22 and y12 == y22):return [x12, y22] # Check 1st point of edge 1 with 2nd point of edge 2 and viceversa slope1 = slope(x11, y11, x12, y12) slope2 = slope(x21, y21, x22, y22) #print('slope1:'+str(slope1)) #print('slope2:'+str(slope2)) if (slope1 == slope2):return False yint1 = yInt(x11, y11, x12, y12) yint2 = yInt(x21, y21, x22, y22) #print('yint1:'+str(yint1)) #print('yint2:'+str(yint2)) if (yint1 == yint2): if (yint1 == False):return False else:return [0, yint1] if(x11 == x12):return [x11, slope2*x11+yint2] if(x21 == x22):return [x21, slope1*x21+yint1] if(y11 == y12):return [(y11-yint2)/slope2,y11] if(y21 == y22):return [(y21-yint1)/slope1,y21] if (slope1 == False):return [y21, slope2 * y21 + yint2] if (slope2 == False):return [y11, slope1 * y11 + yint1] intx = (yint1 - yint2)/ (slope2-slope1) return [intx, slope1 * intx + yint1] def to_deg(rad): return rad*180/math.pi # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSegDegree(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) #return angle return to_deg(angle) # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSeg(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) return angle def count_crossings_single_graph(G): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] for c1 in range(0, len(edge_list)): for c2 in range(c1+1, len(edge_list)): edge1 = edge_list[c1] edge2 = edge_list[c2] (s1,t1) = (edge1[0], edge1[1]) (s2,t2) = (edge2[0], edge2[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): # print(cr) crossings_edges.append((edge1, edge2)) # print(edge1, edge2, p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) count = count + 1 return crossings_edges # if len(segment_pair)==2: # count = count + 1 # else: # count = count + comb(len(segment_pair), 2) return crossings_edges def count_crossings(G, edges_to_compare=None): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] edge_set_1 = edge_list if edges_to_compare is not None: edge_set_1 = edges_to_compare for c1 in range(0, len(edge_set_1)): edge1 = edge_set_1[c1] (s1,t1) = (edge1[0], edge1[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] j_start=c1+1 if edges_to_compare is not None: j_start=0 for c2 in range(j_start, len(edge_list)): edge2 = edge_list[c2] (s2,t2) = (edge2[0], edge2[1]) p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): crossings_edges.append((edge1, edge2)) count = count + 1 return crossings_edges return crossings_edges
8,633
28.267797
207
py
mlgd
mlgd-master/layout_generator/raw_data/modules/mltreedrawer/ml_tree_drawer.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random desired_edge_length = 100; def extract_leaves(G): """Extracts from <tt>G</tt> the vertices with degree 1, i.e. the leaves.""" leaves=[] for n in nx.nodes(G): if len(list(G.neighbors(n)))<=1: leaves.append(n) return leaves def get_all_leaves_paths(G): leaves = extract_leaves(G) shortest_paths={} for s_index in range(0, len(leaves)): for t_index in range(s_index+1, len(leaves)): s = leaves[s_index] t = leaves[t_index] curr_len = nx.shortest_path_length(G, source=s, target=t) curr_sp = nx.shortest_path(G, source=s, target=t) existing_keys = shortest_paths.keys() if(curr_len in existing_keys): shortest_paths[int(curr_len)].append(curr_sp) else: shortest_paths[curr_len] = [curr_sp] return shortest_paths; def extract_path_in_G_starting_from_v(G, vertices, v): ordered_v = [v] while len(ordered_v) < len(vertices): curr_v = ordered_v[-1] adj_v_in_path = set(nx.neighbors(G, curr_v)).intersection(vertices) for curr_adj in adj_v_in_path: ordered_v.append(curr_adj) return ordered_v def place_path(path, angle, edge_length, origin_x, origin_y, start_at_origin=False): lp_pos = {} placed_vertices = [] i = 1 if(start_at_origin): i = 0 for v in path: distance = edge_length*i x = origin_x + (distance)*math.cos(angle); y = origin_y + (distance)*math.sin(angle) lp_pos[v] = str(x) + "," + str(y) placed_vertices.append(v) i += 1 return lp_pos tree_path = sys.argv[1] # Main Graph tree_path_name = os.path.basename(tree_path).split(".")[0] # Reading graph and subgraph G = nx_read_dot(tree_path) placed_vertices = set() leaves_paths = get_all_leaves_paths(G) lens = sorted(leaves_paths.keys(), reverse=True) # Place one longest path first longest_index = lens[0] angle = 0 origin_x = 0 origin_y = 0 longest_path = leaves_paths[longest_index].pop(0) lp_pos = place_path(longest_path, angle, desired_edge_length, origin_x, origin_y, start_at_origin=True) nx.set_node_attributes(G, lp_pos, "pos") while(len(leaves_paths.keys()) > 0): lens = sorted(leaves_paths.keys(), reverse=True) for leng_index in range(0, len(lens)): curr_length = lens[leng_index] curr_paths = leaves_paths[curr_length] print("before len: " + str(len(leaves_paths[curr_length]))) placed_pos = nx.get_node_attributes(G, "pos") placed_vertices = placed_vertices.union(set(placed_pos.keys())) placed = False for path_index in range(0, len(curr_paths)): curr_path = curr_paths[path_index] placed_vertices_in_path = set(curr_path).intersection(placed_vertices) if(len(placed_vertices_in_path) == 0): continue angle = random.randint(0,360) min_neigh_index = float("inf") max_neigh_index = float("-inf") for common_v in placed_vertices_in_path: min_neigh_index = min(min_neigh_index, curr_path.index(common_v)) max_neigh_index = max(max_neigh_index, curr_path.index(common_v)) min_neigh_id = curr_path[min_neigh_index] max_neigh_id = curr_path[max_neigh_index] prev_sub_path = curr_path[0:min_neigh_index] post_sub_path = curr_path[max_neigh_index+1:] min_origin_x = float(placed_pos[min_neigh_id].split(",")[0]) min_origin_y = float(placed_pos[min_neigh_id].split(",")[1]) lp_pos = place_path(prev_sub_path, 180+angle, desired_edge_length, min_origin_x, min_origin_y) nx.set_node_attributes(G, lp_pos, "pos") max_origin_x = float(placed_pos[max_neigh_id].split(",")[0]) max_origin_y = float(placed_pos[max_neigh_id].split(",")[1]) lp_pos = place_path(post_sub_path, angle, desired_edge_length, max_origin_x, max_origin_y) nx.set_node_attributes(G, lp_pos, "pos") placed = True curr_paths.pop(path_index) print("after len: " + str(len(leaves_paths[curr_length]))) if(len(leaves_paths[curr_length]) == 0): leaves_paths.pop(curr_length, None) print("removed") if placed: leng_index = 0 break placed_pos = nx.get_node_attributes(G, "pos") placed_vertices = placed_vertices.union(set(placed_pos.keys())) non_placed_vertices = set(G.nodes()).difference(placed_vertices) # print(leaves_paths) # print(non_placed_vertices) G.remove_nodes_from(non_placed_vertices) G = nx.Graph(G) # print(nx.info(G)) print("saving in ", "test.dot") write_dot(G, "test.dot") print("end")
5,115
26.505376
106
py
mlgd
mlgd-master/layout_generator/raw_data/modules/labelsoverlapremoval/box.py
0
0
0
py
mlgd
mlgd-master/layout_generator/raw_data/modules/labelsoverlapremoval/leavesoverlapremoval.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import edge_crossing as crossings import boxoverlap def remove_leaves_overlap(G): print("computing overlap") overlapping_vertices = get_overlapping_vertices(G) print("computing boxes") all_boxes, all_boxes_dict = compute_boxes(G) leaves = [x for x in G.nodes() if G.degree(x)==1] poss=nx.get_node_attributes(G, "pos") for bb in overlapping_vertices: # bb=overlapping_vertices.pop() u = bb["u"] v = bb["v"] if (u not in leaves) and (v not in leaves): continue width_overlap=bb["w"] height_overlap=bb["h"] delta_l_u = float('inf') delta_l_v = float('inf') desired_length_u = float('inf') desired_length_v = float('inf') if u in leaves: leaf_id = u origin_id = list(nx.all_neighbors(G, leaf_id))[0] delta_l_u = get_delta_to_remove_ovelap(G, origin_id, leaf_id, all_boxes_dict[leaf_id], width_overlap, height_overlap) desired_length_u = compute_desired_length(G, origin_id, leaf_id, delta_l_u) if v in leaves: leaf_id = v origin_id = list(nx.all_neighbors(G, leaf_id))[0] delta_l_v = get_delta_to_remove_ovelap(G, origin_id, leaf_id, all_boxes_dict[leaf_id], width_overlap, height_overlap) desired_length_v = compute_desired_length(G, origin_id, leaf_id, delta_l_v) if desired_length_u <= 0: print("delta longer than edge") delta_l_u = float('inf') if desired_length_v <= 0: print("delta longer than edge") delta_l_v = float('inf') if delta_l_v == float('inf') and delta_l_u == float('inf'): print("impossible to shorten") continue leaf_id = u desired_length = desired_length_u # print(u, v) # print(delta_l_u, delta_l_v) if delta_l_v < delta_l_u: leaf_id = v desired_length = desired_length_v origin_id = list(nx.all_neighbors(G, leaf_id))[0] shorten_leaf(leaf_id, origin_id, G, value=desired_length) # print("removed", str(u), str(v), "shorten", str(leaf_id)) # overlapping_vertices = get_overlapping_vertices(G) def compute_hit_side(G, origin, v, v_box): poss=nx.get_node_attributes(G, "pos") x_origin=float(poss[origin].split(",")[0]) y_origin=float(poss[origin].split(",")[1]) x_v=float(poss[v].split(",")[0]) y_v=float(poss[v].split(",")[1]) # {'min_x':min_x, 'max_x':max_x, 'min_y':min_y, 'max_y':max_y, 'node':v} hit = '0' # print(v_box) if crossings.doSegmentsIntersect(float(x_origin), float(y_origin), float(x_v), float(y_v), float(v_box['min_x']), float(v_box['min_y']), float(v_box['min_x']), float(v_box['max_y'])): hit = "l" if crossings.doSegmentsIntersect(float(x_origin), float(y_origin), float(x_v), float(y_v), float(v_box['max_x']), float(v_box['min_y']), float(v_box['max_x']), float(v_box['max_y'])): hit = "r" if crossings.doSegmentsIntersect(float(x_origin), float(y_origin), float(x_v), float(y_v), float(v_box['min_x']), float(v_box['min_y']), float(v_box['max_x']), float(v_box['min_y'])): hit = "b" if crossings.doSegmentsIntersect(float(x_origin), float(y_origin), float(x_v), float(y_v), float(v_box['min_x']), float(v_box['max_y']), float(v_box['max_x']), float(v_box['max_y'])): hit = "t" return hit def compute_desired_length(G, origin_id, leaf_id, delta): poss=nx.get_node_attributes(G, "pos") x_origin=float(poss[origin_id].split(",")[0]) y_origin=float(poss[origin_id].split(",")[1]) x_leaf=float(poss[leaf_id].split(",")[0]) y_leaf=float(poss[leaf_id].split(",")[1]) length = math.sqrt((x_origin - x_leaf)**2 + (y_origin - y_leaf)**2) desired_length = length - delta # print("len des delta", length, desired_length, delta, 'id', leaf_id) return desired_length def get_delta_to_remove_ovelap(G, origin_id, leaf_id, leaf_box, width_overlap, height_overlap): poss=nx.get_node_attributes(G, "pos") x_origin=float(poss[origin_id].split(",")[0]) y_origin=float(poss[origin_id].split(",")[1]) x_leaf=float(poss[leaf_id].split(",")[0]) y_leaf=float(poss[leaf_id].split(",")[1]) theta = getAngleOfLineBetweenTwoPoints(x_origin, y_origin, x_leaf, y_leaf) hit_side = compute_hit_side(G, origin_id, leaf_id, leaf_box) x_shift = height_overlap/math.cos(theta) y_shift = width_overlap/math.sin(theta) if hit_side == 0: hitsize=0 return float('inf') if hit_side == 'l' or hit_side == 'r': return x_shift if hit_side == 'b' or hit_side == 't': return y_shift # print("no side found") return float('inf') # delta = min(abs(x_shift), abs(y_shift)) # # return delta def shorten_leaf(leaf_id, origin_id, G, value=0): poss=nx.get_node_attributes(G, "pos") x_origin=float(poss[origin_id].split(",")[0]) y_origin=float(poss[origin_id].split(",")[1]) x_leaf=float(poss[leaf_id].split(",")[0]) y_leaf=float(poss[leaf_id].split(",")[1]) x_num = value * (x_leaf - x_origin) y_num = value * (y_leaf - y_origin) x_den = math.sqrt((x_origin-x_leaf)**2 + (y_origin-y_leaf)**2) y_den = math.sqrt((x_origin-x_leaf)**2+(y_origin-y_leaf)**2) x_leaf_new = x_origin + x_num/x_den y_leaf_new = y_origin + y_num/y_den G.node[leaf_id]['pos'] = str(x_leaf_new)+","+str(y_leaf_new) def get_overlapping_vertices(G): inches_to_pixel_factor = 72 leaves = [x for x in G.nodes() if G.degree[x]>0] widths=nx.get_node_attributes(G, "width") heights=nx.get_node_attributes(G, "height") overlapping_vertices=[] found = set() for v in leaves: poss=nx.get_node_attributes(G, "pos") v_width=float(widths[v])*inches_to_pixel_factor v_height=float(heights[v])*inches_to_pixel_factor v_x=float(poss[v].split(",")[0]) v_y=float(poss[v].split(",")[1]) for u in G.nodes(): if(v == u): continue if (u not in leaves) and (v not in leaves): continue u_width=float(widths[v])*inches_to_pixel_factor u_height=float(heights[v])*inches_to_pixel_factor u_x=float(poss[u].split(",")[0]) u_y=float(poss[u].split(",")[1]) curr_overlap = boxoverlap.do_overlap(v_x, v_y, v_width, v_height, u_x, u_y, u_width, u_height) if curr_overlap['a'] == 0: continue if (u,v) in found or (v, u) in found: continue overlapping_vertices.append({'v': v, 'u':u, 'w':v_width+u_width, 'h':v_height+u_height}) # overlapping_vertices.append({'v': v, 'u':u, 'w':curr_overlap['w'] , 'h':curr_overlap['h']}) found.add((u,v)) print("overlapping: " + str(len(overlapping_vertices))) return overlapping_vertices def getAngleOfLineBetweenTwoPoints(point1X, point1Y, point2X, point2Y): xDiff = point2X - point1X yDiff = point2Y - point1Y angle = math.degrees(math.atan2(yDiff, xDiff)) return angle #math.radians(angle) def compute_boxes(G): all_boxes = [] widths=nx.get_node_attributes(G, "width") heights=nx.get_node_attributes(G, "height") poss=nx.get_node_attributes(G, "pos") all_boxes_dict = {} for v in G.nodes(): curr_box = {'min_x':0, 'max_x':0, 'min_y':0, 'max_y':0} v_x=float(poss[v].split(",")[0]) v_y=float(poss[v].split(",")[1]) v_width = float(widths[v]) v_height = float(heights[v]) min_x = v_x-(v_width/2) max_x = v_x+(v_width/2) min_y = v_y-(v_height/2) max_y = v_y+(v_height/2) all_boxes_dict[v] = {'min_x':min_x, 'max_x':max_x, 'min_y':min_y, 'max_y':max_y, 'node':v} all_boxes.append({'min_x':min_x, 'max_x':max_x, 'min_y':min_y, 'max_y':max_y, 'node':v}) return all_boxes, all_boxes_dict
8,335
27.744828
187
py
mlgd
mlgd-master/layout_generator/raw_data/modules/labelsoverlapremoval/boxoverlap.py
#Author #Felice De Luca #https://github.com/felicedeluca import math def do_overlap(x1, y1, w1, h1, x2, y2, w2, h2): x_min_1=x1-(w1/2) y_min_1=y1-(h1/2) x_max_1=x1+(w1/2) y_max_1=y1+(h1/2) x_min_2=x2-(w2/2) y_min_2=y2-(h2/2) x_max_2=x2+(w2/2) y_max_2=y2+(h2/2) if(x_max_1 <= x_min_2 or x_max_2 <= x_min_1 or y_max_1 <= y_min_2 or y_max_2 <= y_min_1): # print("No Overlap") overlap = {'w': 0, 'h': 0, 'a':0, 'u':-1, 'v':-1} return overlap l1=(x_min_1, y_min_1) l2=(x_min_2, y_min_2) r1=(x_max_1, y_max_1) r2=(x_max_2, y_max_2) area_1=w1*h1 area_2=w2*h2 # print(area_1) # print(area_2) width_overlap = (min(x_max_1, x_max_2)-max(x_min_1, x_min_2)) height_overlap = (min(y_max_1, y_max_2)-max(y_min_1, y_min_2)) areaI = width_overlap*height_overlap # print(areaI) total_area = area_1 + area_2 - areaI # print(total_area) overlap = {"w": width_overlap, "h": height_overlap, "a":areaI} return overlap
1,043
19.470588
66
py
mlgd
mlgd-master/layout_generator/raw_data/modules/labelsoverlapremoval/overlapremovalmain.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import leavesoverlapremoval # Main Flow graph_path = sys.argv[1] outputpath = sys.argv[2] G = nx_read_dot(graph_path) G=nx.Graph(G) leavesoverlapremoval.remove_leaves_overlap(G) write_dot(G, outputpath)
459
16.692308
62
py
mlgd
mlgd-master/layout_generator/raw_data/modules/labelsoverlapremoval/labelsoverlapremoval.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import boxoverlap def scale(G, scaling_factor): all_pos = nx.get_node_attributes(G, "pos") for v in nx.nodes(G): v_x=float(all_pos[v].split(",")[0]) v_y=float(all_pos[v].split(",")[1]) v_x_scaled = v_x * scaling_factor v_y_scaled = v_y * scaling_factor coo = str(v_x_scaled)+","+str(v_y_scaled) nx.set_node_attributes(G, {v:coo}, "pos") return G def getmaxoverlap(G): inches_to_pixel_factor = 1 max_overlapping_width = 0 max_overlapping_height = 0 max_overlapping_area = 0 max_alpha_x = 0 max_alpha_y = 0 widths=nx.get_node_attributes(G, "width") heights=nx.get_node_attributes(G, "height") poss=nx.get_node_attributes(G, "pos") nodelist = list(G.nodes()) for v_id in range(0, len(nodelist)): v = nodelist[v_id] v_width=float(widths[v])*inches_to_pixel_factor v_height=float(heights[v])*inches_to_pixel_factor v_x=float(poss[v].split(",")[0]) v_y=float(poss[v].split(",")[1]) for u_id in range(v_id+1, len(nodelist)): u = nodelist[u_id] if(v == u): continue u_width=float(widths[v])*inches_to_pixel_factor u_height=float(heights[v])*inches_to_pixel_factor u_x=float(poss[u].split(",")[0]) u_y=float(poss[u].split(",")[1]) curr_overlap = boxoverlap.do_overlap(v_x, v_y, v_width, v_height, u_x, u_y, u_width, u_height) curr_alpha_x = 0 curr_alpha_y = 0 if(u_x-v_x > 0): curr_alpha_x = (abs(u_width+v_width)/abs(u_x-v_x)) if(u_y-v_y > 0): curr_alpha_y = (abs(u_height+v_height)/abs(u_y-v_y)) max_overlapping_width = max(max_overlapping_width, curr_overlap['w']) max_overlapping_height = max(max_overlapping_height, curr_overlap['h']) max_overlapping_area=max(max_overlapping_area, curr_overlap['a']) # compute the scaling factor only if needed if(max_overlapping_area>0): max_alpha_x=max(max_alpha_x, curr_alpha_x) max_alpha_y=max(max_alpha_y, curr_alpha_y) return {"w": max_overlapping_width, "h": max_overlapping_height, "a":max_overlapping_area, "max_alpha_x":max_alpha_x, "max_alpha_y":max_alpha_y} # Main Flow graph_path = sys.argv[1] outputpath = sys.argv[2] input_graph_name = os.path.basename(graph_path) graph_name = input_graph_name.split(".")[1] G = nx_read_dot(graph_path) G=nx.Graph(G) # G=scale(G, 1/100000000) max_overlap=getmaxoverlap(G) print(max_overlap) scaling_factor=float(max(max_overlap['max_alpha_x'], max_overlap['max_alpha_y'])) print(scaling_factor) if(scaling_factor>0): if(scaling_factor<1): scaling_factor = 1.01 print("scaling") G=scale(G, scaling_factor) max_overlap=getmaxoverlap(G) print("after") print(max_overlap) write_dot(G, outputpath)
3,212
27.184211
148
py
mlgd
mlgd-master/layout_generator/raw_data/modules/labelsoverlapremoval/edge_crossing.py
#Author #Felice De Luca #https://github.com/felicedeluca # import math import networkx as nx # Given three colinear points p, q, r, the function checks if # point q lies on line segment 'pr' def onSegment(px, py, qx, qy, rx, ry): if (qx <= max(px, rx) and qx >= min(px, rx) and qy <= max(py, ry) and qy >= min(py, ry)): return True return False def strictlyOnSegment(px, py, qx, qy, rx, ry): if (qx < max(px, rx) and qx > min(px, rx) and qy < max(py, ry) and qy > min(py, ry)): return True return False # To find orientation of ordered triplet (p, q, r). # The function returns following values # 0 --> p, q and r are colinear # 1 --> Clockwise # 2 --> Counterclockwise def orientation(px, py, qx, qy, rx, ry): # See http://www.geeksforgeeks.org/orientation-3-ordered-points/ # for details of below formula. val = (qy - py) * (rx - qx) - (qx - px) * (ry - qy) if (val == 0):return 0 # clock or counterclock wise if (val > 0): return 1 else: return 2 def yInt(x1, y1, x2, y2): if (y1 == y2):return y1 return y1 - slope(x1, y1, x2, y2) * x1 def slope(x1, y1, x2, y2): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)) if (x1 == x2):return False return (y1 - y2) / (x1 - x2) # The main function that returns true if line segment 'p1q1' # and 'p2q2' intersect. def doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): # Find the four orientations needed for general and # special cases o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y) o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y) o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y) o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y) #if(o1==0 or o2==0 or o3==0 or o4==0):return False # General case if (o1 != o2 and o3 != o4): return True # Special Cases # p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 and onSegment(p1x, p1y, p2x, p2y, q1x, q1y)):return True # p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 and onSegment(p1x, p1y, q2x, q2y, q1x, q1y)):return True # p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 and onSegment(p2x, p2y, p1x, p1y, q2x, q2y)):return True # p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 and onSegment(p2x, p2y, q1x, q1y, q2x, q2y)):return True return False # Doesn't fall in any of the above cases def isSameCoord(x1, y1, x2, y2): if x1==x2 and y1==y2: return True return False # do p is an end point of edge (u,v) def isEndPoint(ux, uy, vx, vy, px, py): if isSameCoord(ux, uy, px, py) or isSameCoord(vx, vy, px, py): return True return False # is (p1,q1) is adjacent to (p2,q2)? def areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isEndPoint(p1x, p1y, q1x, q1y, p2x, p2y): return True elif isEndPoint(p1x, p1y, q1x, q1y, q2x, q2y): return True return False def isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): x1 = p1x-q1x y1 = p1y-q1y x2 = p2x-q2x y2 = p2y-q2y cross_prod_value = x1*y2 - x2*y1 if cross_prod_value==0: return True return False # here p1q1 is one segment, and p2q2 is another # this function checks first whether there is a shared vertex # then it checks whether they are colinear # finally it checks the segment intersection def doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if strictlyOnSegment(p1x, p1y, p2x, p2y, q1x, q1y) or strictlyOnSegment(p1x, p1y, q2x, q2y, q1x, q1y) or strictlyOnSegment(p2x, p2y, p1x, p1y, q2x, q2y) or strictlyOnSegment(p2x, p2y, q1x, q1y, q2x, q2y): return True else: return False else: return False return doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) def getIntersection(x11, y11, x12, y12, x21, y21, x22, y22): slope1 = 0 slope2 = 0 yint1 = 0 yint2 = 0 intx = 0 inty = 0 #TODO: Please Check all four cases if (x11 == x21 and y11 == y21):return [x11, y11] if (x12 == x22 and y12 == y22):return [x12, y22] # Check 1st point of edge 1 with 2nd point of edge 2 and viceversa slope1 = slope(x11, y11, x12, y12) slope2 = slope(x21, y21, x22, y22) #print('slope1:'+str(slope1)) #print('slope2:'+str(slope2)) if (slope1 == slope2):return False yint1 = yInt(x11, y11, x12, y12) yint2 = yInt(x21, y21, x22, y22) #print('yint1:'+str(yint1)) #print('yint2:'+str(yint2)) if (yint1 == yint2): if (yint1 == False):return False else:return [0, yint1] if(x11 == x12):return [x11, slope2*x11+yint2] if(x21 == x22):return [x21, slope1*x21+yint1] if(y11 == y12):return [(y11-yint2)/slope2,y11] if(y21 == y22):return [(y21-yint1)/slope1,y21] if (slope1 == False):return [y21, slope2 * y21 + yint2] if (slope2 == False):return [y11, slope1 * y11 + yint1] intx = (yint1 - yint2)/ (slope2-slope1) return [intx, slope1 * intx + yint1] def to_deg(rad): return rad*180/math.pi # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSegDegree(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) #return angle return to_deg(angle) # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSeg(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) return angle def count_crossings_single_graph(G): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] for c1 in range(0, len(edge_list)): for c2 in range(c1+1, len(edge_list)): edge1 = edge_list[c1] edge2 = edge_list[c2] (s1,t1) = (edge1[0], edge1[1]) (s2,t2) = (edge2[0], edge2[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): # print(cr) crossings_edges.append((edge1, edge2)) # print(edge1, edge2, p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) count = count + 1 return crossings_edges # if len(segment_pair)==2: # count = count + 1 # else: # count = count + comb(len(segment_pair), 2) return crossings_edges def count_crossings(G, edges_to_compare=None): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] edge_set_1 = edge_list if edges_to_compare is not None: edge_set_1 = edges_to_compare for c1 in range(0, len(edge_set_1)): edge1 = edge_set_1[c1] (s1,t1) = (edge1[0], edge1[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] j_start=c1+1 if edges_to_compare is not None: j_start=0 for c2 in range(j_start, len(edge_list)): edge2 = edge_list[c2] (s2,t2) = (edge2[0], edge2[1]) p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): crossings_edges.append((edge1, edge2)) count = count + 1 return crossings_edges return crossings_edges
8,633
28.267797
207
py
mlgd
mlgd-master/layout_generator/raw_data/modules/sublevel_extractor/sublevel_extractor.py
import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random def save_graph(G, outputpath): G = nx.Graph(G) write_dot(G, outputpath) def extract_level(G, level): G = nx.Graph(G) levels_info = nx.get_node_attributes(G, 'level') to_remove_nodes = [n for n in levels_info.keys() if int(levels_info[n]) > level] G.remove_nodes_from(to_remove_nodes) return G g_path = sys.argv[1] outputpath = sys.argv[2] g_name = os.path.basename(g_path).split(".")[0] # Reading graph and subgraph G = nx_read_dot(g_path) G = nx.Graph(G) levels_info = nx.get_node_attributes(G, 'level') levels = sorted(list(set(levels_info.values()))) for level in levels: level = int(level) sub_G = extract_level(G, level) save_graph(sub_G, outputpath+g_name+"_"+str(level)+"_final.dot")
948
22.725
84
py
mlgd
mlgd-master/layout_generator/raw_data/modules/utils/vertexmanager.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex)
446
13.9
42
py
mlgd
mlgd-master/layout_generator/raw_data/modules/drawing_improvement/impred.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random import vertexmanager def get_bounding_box(G): xmin=0 ymin=0 xmax=0 ymax=0 ofset=0 for x in G.nodes(): xmin=min(xmin,float(G.node[x]["pos"].split(",")[0]) ) xmax=max(xmax,float(G.node[x]["pos"].split(",")[0]) ) ymin=min(ymin,float(G.node[x]["pos"].split(",")[1]) ) ymax=max(ymax,float(G.node[x]["pos"].split(",")[1]) ) return xmin ,ymin ,xmax ,ymax def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): vertexmanager.shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def scale(G, scaling_factor): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) min_y = float(coo_y[0]) translateGraph(G, min_x, min_y) for currVertex in nx.nodes(G): v = G.node[currVertex] v_x, v_y = vertexmanager.getCoordinate(v) v_x_scaled = v_x * scaling_factor v_y_scaled = v_y * scaling_factor vertexmanager.setCoordinate(v, v_x_scaled, v_y_scaled) return G def avg_edge_length(G): sum_edge_length = 0.0 edge_count = len(G.edges()) for edge in G.edges(): s,t = edge s = G.node[s] t = G.node[t] x_source1, y_source1 = vertexmanager.getCoordinate(s) x_target1, y_target1 = vertexmanager.getCoordinate(t) curr_length = math.sqrt((x_source1 - x_target1)**2 + (y_source1 - y_target1)**2) sum_edge_length += curr_length avg_edge_len = sum_edge_length/edge_count return avg_edge_len # Main Flow graphpath = sys.argv[1] outputpath = graphpath # Main Graph input_graph_name = os.path.basename(graphpath) graph_name = input_graph_name.split(".")[0] # Reading graph and subgraph G = nx_read_dot(graphpath) nx.set_edge_attributes(G, 'red', 'color') avg_edge = avg_edge_length(G) xmin ,ymin ,xmax ,ymax = get_bounding_box(G) scaling_factor = 100/avg_edge translateGraph(G, -xmin, -ymin) G = scale(G, scaling_factor) G = nx.Graph(G) write_dot(G, outputpath)
2,408
22.851485
88
py
mlgd
mlgd-master/layout_generator/raw_data/modules/drawing_improvement/vertexmanager.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex)
446
13.9
42
py
mlgd
mlgd-master/layout_generator/raw_data/modules/add_forest/tree_crossings_remover.py
#Author #Felice De Luca #https://github.com/felicedeluca # This script removes the crossings from the given tree # it searches for a crossing, splits the graph in 3 components removing # the crossing edges and then scales the smaller component till there is no more # crossing. import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random import edge_crossing as crossings import vertexmanager def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): vertexmanager.shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def scale(G, scaling_factor): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) min_y = float(coo_y[0]) for currVertex in nx.nodes(G): v = G.node[currVertex] v_x, v_y = vertexmanager.getCoordinate(v) v_x_scaled = v_x * scaling_factor v_y_scaled = v_y * scaling_factor vertexmanager.setCoordinate(v, v_x_scaled, v_y_scaled) return G def remove_crossings(G): while len(crossings.count_crossings_single_graph(G)): crs = crossings.count_crossings_single_graph(G) current_crossing_edges = crs[0] G_copy = G.copy() # Removing edges to separate graph G_copy.remove_edges_from(current_crossing_edges) # Getting the smaller component to be scaled smaller_component_vertices = list([c for c in sorted(nx.connected_components(G_copy), key=len, reverse=True)][-1]) # print(smaller_component_vertices) main_edge = "" main_vertex = "" other_vertex = "" # Getting the edge connecting the main and the smaller component for curr_edge in current_crossing_edges: s = curr_edge[0] t = curr_edge[1] if s in smaller_component_vertices: main_vertex = t other_vertex = s main_edge = curr_edge break if t in smaller_component_vertices: main_vertex = s other_vertex = t main_edge = curr_edge break # print("main: " + main_vertex) # print("other: " + other_vertex) # print(main_edge) # Translating the graph for better scaling translation_dx, translation_dy = vertexmanager.getCoordinate(G.node[main_vertex]) translateGraph(G, -translation_dx, -translation_dy) subcomponet_vertices = smaller_component_vertices subcomponet_edges = G.subgraph(subcomponet_vertices).copy().edges() H = nx.Graph() H.add_nodes_from(list(subcomponet_vertices)) H.add_node(main_vertex) nx.set_node_attributes(H, nx.get_node_attributes(G, 'pos'), 'pos') H.add_edges_from(list(subcomponet_edges)) H.add_edge(main_vertex, other_vertex) # print(nx.info(H)) # print(nx.get_node_attributes(H, 'pos')) scale(H, 0.5) # print(nx.get_node_attributes(H, 'pos')) nx.set_node_attributes(G, nx.get_node_attributes(H, 'pos'), 'pos') # print("changed") print("crossings:" + str(len(crossings.count_crossings_single_graph(G)))) return G
3,499
27.92562
122
py
mlgd
mlgd-master/layout_generator/raw_data/modules/add_forest/addsubcomponentmodule_slow.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import monotone_drawing import math import random import edge_crossing as crossings import vertexmanager import tree_crossings_remover def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): vertexmanager.shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def extract_subcomponent(G, mainVertex, vertex): tempG = G.copy() tempG.remove_node(mainVertex) subcomponet_vertices = nx.node_connected_component(tempG, vertex) subcomponet_vertices.add(mainVertex) subcomponet_edges = G.subgraph(subcomponet_vertices).copy().edges() H = nx.Graph() H.add_nodes_from(list(subcomponet_vertices)) H.add_edges_from(list(subcomponet_edges)) return H def boundingBox(G): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) max_x = float(coo_x[-1]) min_y = float(coo_y[0]) max_y = float(coo_y[-1]) width = abs(max_x - min_x) height = abs(max_y - min_y) return width, height def scale(G, scaling_factor): for currVertex in nx.nodes(G): v = G.node[currVertex] x = float(v['pos'].split(",")[0]) y = float(v['pos'].split(",")[1]) v_x_scaled = v_x * scaling_factor v_y_scaled = v_y * scaling_factor v['pos'] = str(v_x_scaled)+","+str(v_y_scaled) return G def rotate(G, angle): angle = math.radians(angle) for currVertex in nx.nodes(G): x, y = vertexmanager.getCoordinate(G.node[currVertex]) x_rot = x*math.cos(angle) - y*math.sin(angle) y_rot = x*math.sin(angle) + y*math.cos(angle) vertexmanager.setCoordinate(G.node[currVertex], x_rot, y_rot) return G def getAngleOfLineBetweenTwoPoints(point1X, point1Y, point2X, point2Y): xDiff = point2X - point1X yDiff = point2Y - point1Y return math.degrees(math.atan2(yDiff, xDiff)) def computeSectorsAngles(G, commonVertex): angle_dict = dict() for currN in set(nx.all_neighbors(G, commonVertex)): v1 = G.node[commonVertex] v2 = G.node[currN] v1_x, v1_y = vertexmanager.getCoordinate(v1) v2_x, v2_y = vertexmanager.getCoordinate(v2) angle = getAngleOfLineBetweenTwoPoints(v1_x, v1_y, v2_x, v2_y) if(angle < 0): angle = 360-abs(angle) if(angle not in angle_dict.keys()): angle_dict[angle] = list() angle_dict[angle].append(currN) sorted_slopes = sorted(angle_dict.keys()) sector_angle_dict = dict() for i in range(0, len(sorted_slopes)): first_index = i second_index = i+1 if(second_index>=len(sorted_slopes)): second_index = 0 first_slope = sorted_slopes[first_index] next_slope = sorted_slopes[second_index] v1_id = angle_dict[first_slope][0] v2_id = angle_dict[next_slope][0] center = G.node[commonVertex] v1 = G.node[v1_id] v2 = G.node[v2_id] angular_resolution = next_slope-first_slope if(angular_resolution < 0): angular_resolution = 360-abs(angular_resolution) if(angular_resolution not in sector_angle_dict.keys()): sector_angle_dict[angular_resolution] = list() sector_angle_dict[angular_resolution].append([v1_id, v2_id]) return sector_angle_dict def avg_edge_length(G): sum_edge_length = 0.0 edge_count = len(G.edges()) for edge in G.edges(): s,t = edge s = G.node[s] t = G.node[t] x_source1, y_source1 = vertexmanager.getCoordinate(s) x_target1, y_target1 = vertexmanager.getCoordinate(t) curr_length = math.sqrt((x_source1 - x_target1)**2 + (y_source1 - y_target1)**2) sum_edge_length += curr_length avg_edge_len = sum_edge_length/edge_count return avg_edge_len # Main Flow graphpath = sys.argv[1] subgraphpath = sys.argv[2] outputpath = sys.argv[3] print("add subcomponent: input ", graphpath, subgraphpath, outputpath) # Main Graph input_graph_name = os.path.basename(graphpath) graph_name = input_graph_name.split(".")[0] print(graph_name) # Sub Graph to be added input_subgraph_name = os.path.basename(subgraphpath) subgraph_name = subgraphpath.split(".")[0] # Reading graph and subgraph G = nx_read_dot(graphpath) nx.set_edge_attributes(G, 'red', 'color') SubG = nx_read_dot(subgraphpath) commonVertices = set(set(G.nodes()) & set(SubG.nodes())) avg_edge_length = avg_edge_length(G) if len(crossings.count_crossings_single_graph(G)): print(graph_name + " has crossings.") print("exiting") sys.exit() v_counter=0 for commonVertex in commonVertices: v_counter+=1 translation_dx, translation_dy = vertexmanager.getCoordinate(G.node[commonVertex]) translateGraph(G, -translation_dx, -translation_dy) a_counter=0 # # Extract subcomponents, draw, sacle and attach it to the widest sector for currN in set(nx.all_neighbors(SubG, commonVertex)): a_counter+=1 # Compute sector angle and get the largest sector_angle_dict = computeSectorsAngles(G, commonVertex) sorted_angles = sorted(sector_angle_dict.keys()) largest_sector_angle = sorted_angles[-1] # Get First vertex sector_vertices = sector_angle_dict[largest_sector_angle][0] if(largest_sector_angle == 0): largest_sector_angle = 360 center_v_id = commonVertex first_v_id = sector_vertices[0] center_v = G.node[commonVertex] first_v = G.node[first_v_id] center_v_x, center_v_y = vertexmanager.getCoordinate(center_v) first_v_x, first_v_y = vertexmanager.getCoordinate(first_v) min_sector_angle = getAngleOfLineBetweenTwoPoints(center_v_x, center_v_y, first_v_x, first_v_y) if(min_sector_angle < 0): min_sector_angle = 360-abs(min_sector_angle) drawing_rotation_factor = -min_sector_angle # Rotate rotate(G, drawing_rotation_factor) # Compute subcomponent Drawing H = extract_subcomponent(SubG, commonVertex, currN) H = monotone_drawing.monotone_draw(H, commonVertex, avg_edge_length) mid_sector_angle = largest_sector_angle/2 # Place first vertex of new component on bisector currN_v = H.node[currN] currN_v_x, currN_v_y = vertexmanager.getCoordinate(currN_v) first_H_vertex_angle = getAngleOfLineBetweenTwoPoints(center_v_x, center_v_y, currN_v_x, currN_v_y) if(first_H_vertex_angle < 0): first_H_vertex_angle = 360-abs(first_H_vertex_angle) desired_first_H_angle = mid_sector_angle - first_H_vertex_angle rotate(H, desired_first_H_angle) scaling_factor = 0.5 # # # Add subcomponent G.add_nodes_from(H.copy()) nx.set_node_attributes(G, nx.get_node_attributes(H, 'pos'), 'pos') G.add_edges_from(H.edges) G.add_edge(currN, commonVertex) while len(crossings.count_crossings_single_graph(G)): H = scale(H, scaling_factor) H_pos = nx.get_node_attributes(H, 'pos') # print(nx.nodes(H)) nx.set_node_attributes(G, H_pos, 'pos') rotate(G, -drawing_rotation_factor) #Place back the graph at original position translateGraph(G, translation_dx, translation_dy) G = nx.Graph(G) #G = tree_crossings_remover.remove_crossings(G) #G = nx.Graph(G) nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'level'), 'level') nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'label'), 'label') nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'width'), 'width') nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'height'), 'height') write_dot(G, outputpath)
8,154
26.550676
107
py
mlgd
mlgd-master/layout_generator/raw_data/modules/add_forest/propertyfetcher.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot # Main Flow graph_path = sys.argv[1] tree_path = sys.argv[2] outputpath = tree_path #sys.argv[3] input_graph_name = os.path.basename(graph_path) graph_name = input_graph_name.split(".")[1] G=nx_read_dot(graph_path) G=nx.Graph(G) T=nx_read_dot(tree_path) T=nx.Graph(T) weight_V_info=nx.get_node_attributes(G, 'weight') label_V_info=nx.get_node_attributes(G, 'label') width_V_info=nx.get_node_attributes(G, 'width') heigth_V_info=nx.get_node_attributes(G, 'height') level_V_info=nx.get_node_attributes(G, 'level') # pos_V_info=nx.get_node_attributes(G, 'pos') fontname_V_info=nx.get_node_attributes(G, 'fontname') fontsize_V_info=nx.get_node_attributes(G, 'fontsize') nx.set_node_attributes(T, weight_V_info, 'weight') nx.set_node_attributes(T, label_V_info, 'label') nx.set_node_attributes(T, width_V_info, 'width') nx.set_node_attributes(T, heigth_V_info, 'height') nx.set_node_attributes(T, level_V_info, 'level') # nx.set_node_attributes(T, pos_V_info, 'pos') nx.set_node_attributes(T, fontname_V_info, 'fontname') nx.set_node_attributes(T, fontsize_V_info, 'fontsize') write_dot(T, outputpath)
1,359
25.666667
62
py
mlgd
mlgd-master/layout_generator/raw_data/modules/add_forest/addsubcomponentmodule.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import monotone_drawing import math import random import edge_crossing as crossings import vertexmanager import tree_crossings_remover def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): vertexmanager.shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def extract_subcomponent(G, mainVertex, vertex): tempG = G.copy() tempG.remove_node(mainVertex) subcomponet_vertices = nx.node_connected_component(tempG, vertex) subcomponet_vertices.add(mainVertex) subcomponet_edges = G.subgraph(subcomponet_vertices).copy().edges() H = nx.Graph() H.add_nodes_from(list(subcomponet_vertices)) H.add_edges_from(list(subcomponet_edges)) return H def boundingBox(G): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) max_x = float(coo_x[-1]) min_y = float(coo_y[0]) max_y = float(coo_y[-1]) width = abs(max_x - min_x) height = abs(max_y - min_y) return width, height def scale(G, scaling_factor): for currVertex in nx.nodes(G): v = G.node[currVertex] x = float(v['pos'].split(",")[0]) y = float(v['pos'].split(",")[1]) v_x_scaled = x * scaling_factor v_y_scaled = y * scaling_factor v['pos'] = str(v_x_scaled)+","+str(v_y_scaled) return G def rotate(G, angle): angle = math.radians(angle) for currVertex in nx.nodes(G): x, y = vertexmanager.getCoordinate(G.node[currVertex]) x_rot = x*math.cos(angle) - y*math.sin(angle) y_rot = x*math.sin(angle) + y*math.cos(angle) vertexmanager.setCoordinate(G.node[currVertex], x_rot, y_rot) return G def getAngleOfLineBetweenTwoPoints(point1X, point1Y, point2X, point2Y): xDiff = point2X - point1X yDiff = point2Y - point1Y return math.degrees(math.atan2(yDiff, xDiff)) def computeSectorsAngles(G, commonVertex): angle_dict = dict() for currN in set(nx.all_neighbors(G, commonVertex)): v1 = G.node[commonVertex] v2 = G.node[currN] v1_x, v1_y = vertexmanager.getCoordinate(v1) v2_x, v2_y = vertexmanager.getCoordinate(v2) angle = getAngleOfLineBetweenTwoPoints(v1_x, v1_y, v2_x, v2_y) if(angle < 0): angle = 360-abs(angle) if(angle not in angle_dict.keys()): angle_dict[angle] = list() angle_dict[angle].append(currN) sorted_slopes = sorted(angle_dict.keys()) sector_angle_dict = dict() for i in range(0, len(sorted_slopes)): first_index = i second_index = i+1 if(second_index>=len(sorted_slopes)): second_index = 0 first_slope = sorted_slopes[first_index] next_slope = sorted_slopes[second_index] v1_id = angle_dict[first_slope][0] v2_id = angle_dict[next_slope][0] center = G.node[commonVertex] v1 = G.node[v1_id] v2 = G.node[v2_id] angular_resolution = next_slope-first_slope if(angular_resolution < 0): angular_resolution = 360-abs(angular_resolution) if(angular_resolution not in sector_angle_dict.keys()): sector_angle_dict[angular_resolution] = list() sector_angle_dict[angular_resolution].append([v1_id, v2_id]) return sector_angle_dict def avg_edge_length(G): sum_edge_length = 0.0 edge_count = len(G.edges()) for edge in G.edges(): s,t = edge s = G.node[s] t = G.node[t] x_source1, y_source1 = vertexmanager.getCoordinate(s) x_target1, y_target1 = vertexmanager.getCoordinate(t) curr_length = math.sqrt((x_source1 - x_target1)**2 + (y_source1 - y_target1)**2) sum_edge_length += curr_length avg_edge_len = sum_edge_length/edge_count return avg_edge_len # Main Flow graphpath = sys.argv[1] subgraphpath = sys.argv[2] outputpath = sys.argv[3] print("add subcomponent: input ", graphpath, subgraphpath, outputpath) # Main Graph input_graph_name = os.path.basename(graphpath) graph_name = input_graph_name.split(".")[0] print(graph_name) # Sub Graph to be added input_subgraph_name = os.path.basename(subgraphpath) subgraph_name = subgraphpath.split(".")[0] # Reading graph and subgraph G = nx_read_dot(graphpath) nx.set_edge_attributes(G, 'red', 'color') SubG = nx_read_dot(subgraphpath) commonVertices = set(set(G.nodes()) & set(SubG.nodes())) avg_edge_length = avg_edge_length(G) if len(crossings.count_crossings_single_graph(G)): print(graph_name + " has crossings.") print("exiting") sys.exit() v_counter=0 for commonVertex in commonVertices: v_counter+=1 translation_dx, translation_dy = vertexmanager.getCoordinate(G.node[commonVertex]) translateGraph(G, -translation_dx, -translation_dy) a_counter=0 # # Extract subcomponents, draw, sacle and attach it to the widest sector for currN in set(nx.all_neighbors(SubG, commonVertex)): a_counter+=1 # Compute sector angle and get the largest sector_angle_dict = computeSectorsAngles(G, commonVertex) sorted_angles = sorted(sector_angle_dict.keys()) largest_sector_angle = sorted_angles[-1] # Get First vertex sector_vertices = sector_angle_dict[largest_sector_angle][0] if(largest_sector_angle == 0): largest_sector_angle = 360 center_v_id = commonVertex first_v_id = sector_vertices[0] center_v = G.node[commonVertex] first_v = G.node[first_v_id] center_v_x, center_v_y = vertexmanager.getCoordinate(center_v) first_v_x, first_v_y = vertexmanager.getCoordinate(first_v) min_sector_angle = getAngleOfLineBetweenTwoPoints(center_v_x, center_v_y, first_v_x, first_v_y) if(min_sector_angle < 0): min_sector_angle = 360-abs(min_sector_angle) drawing_rotation_factor = -min_sector_angle # Rotate rotate(G, drawing_rotation_factor) # Compute subcomponent Drawing H = extract_subcomponent(SubG, commonVertex, currN) H = monotone_drawing.monotone_draw(H, commonVertex, avg_edge_length) mid_sector_angle = largest_sector_angle/2 # Place first vertex of new component on bisector currN_v = H.node[currN] currN_v_x, currN_v_y = vertexmanager.getCoordinate(currN_v) first_H_vertex_angle = getAngleOfLineBetweenTwoPoints(center_v_x, center_v_y, currN_v_x, currN_v_y) if(first_H_vertex_angle < 0): first_H_vertex_angle = 360-abs(first_H_vertex_angle) desired_first_H_angle = mid_sector_angle - first_H_vertex_angle rotate(H, desired_first_H_angle) scaling_factor = 0.5 # # # Add subcomponent G.add_nodes_from(H.copy()) nx.set_node_attributes(G, nx.get_node_attributes(H, 'pos'), 'pos') G.add_edges_from(H.edges) G.add_edge(currN, commonVertex) # Count crossings between H and G edges_to_compare = list(H.edges) edges_to_compare.append((currN, commonVertex)) crossing_pair=crossings.count_crossings(G, edges_to_compare) while len(crossing_pair): H = scale(H, scaling_factor) H_pos = nx.get_node_attributes(H, 'pos') # print(nx.nodes(H)) nx.set_node_attributes(G, H_pos, 'pos') edges_to_compare = list(H.edges) edges_to_compare.append((currN, commonVertex)) crossing_pair=crossings.count_crossings(G, edges_to_compare) rotate(G, -drawing_rotation_factor) #Place back the graph at original position translateGraph(G, translation_dx, translation_dy) G = nx.Graph(G) #G = tree_crossings_remover.remove_crossings(G) #G = nx.Graph(G) nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'level'), 'level') nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'label'), 'label') # lbl_scaling_factor = 72 # # scaled_w = nx.get_node_attributes(SubG, 'width') # for k in scaled_w.keys(): # scaled_w[k] = float(scaled_w[k])/lbl_scaling_factor # # scaled_h = nx.get_node_attributes(SubG, 'height') # for k in scaled_w.keys(): # scaled_h[k] = float(scaled_h[k])/lbl_scaling_factor nx.set_node_attributes(G, scaled_w, 'width') nx.set_node_attributes(G, scaled_h, 'height') write_dot(G, outputpath)
8,755
26.708861
107
py
mlgd
mlgd-master/layout_generator/raw_data/modules/add_forest/monotone_drawing.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx import math import vertexmanager def monotone_draw(G, root, edge_length): """ take tree assign unique slope use tan-1 for slopes if path, may consider same slop run DFS """ i = 1 vertexmanager.setCoordinate(G.node[root], 0.0, 0.0) for e in nx.dfs_edges(G,root): u, v = e slp = math.atan(i) x_u, y_u = vertexmanager.getCoordinate(G.node[u]) x_v = x_u + math.cos(slp) y_v = y_u + math.sin(slp) vertexmanager.setCoordinate(G.node[v], x_v+edge_length, y_v+edge_length) i = i + 1 return G
622
16.305556
76
py
mlgd
mlgd-master/layout_generator/raw_data/modules/add_forest/vertexmanager.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex)
446
13.9
42
py
mlgd
mlgd-master/layout_generator/raw_data/modules/add_forest/edge_crossing.py
#Author #Felice De Luca #https://github.com/felicedeluca # import math import networkx as nx # Given three colinear points p, q, r, the function checks if # point q lies on line segment 'pr' def onSegment(px, py, qx, qy, rx, ry): if (qx <= max(px, rx) and qx >= min(px, rx) and qy <= max(py, ry) and qy >= min(py, ry)): return True return False def strictlyOnSegment(px, py, qx, qy, rx, ry): if (qx < max(px, rx) and qx > min(px, rx) and qy < max(py, ry) and qy > min(py, ry)): return True return False # To find orientation of ordered triplet (p, q, r). # The function returns following values # 0 --> p, q and r are colinear # 1 --> Clockwise # 2 --> Counterclockwise def orientation(px, py, qx, qy, rx, ry): # See http://www.geeksforgeeks.org/orientation-3-ordered-points/ # for details of below formula. val = (qy - py) * (rx - qx) - (qx - px) * (ry - qy) if (val == 0):return 0 # clock or counterclock wise if (val > 0): return 1 else: return 2 def yInt(x1, y1, x2, y2): if (y1 == y2):return y1 return y1 - slope(x1, y1, x2, y2) * x1 def slope(x1, y1, x2, y2): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)) if (x1 == x2):return False return (y1 - y2) / (x1 - x2) # The main function that returns true if line segment 'p1q1' # and 'p2q2' intersect. def doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): # Find the four orientations needed for general and # special cases o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y) o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y) o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y) o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y) #if(o1==0 or o2==0 or o3==0 or o4==0):return False # General case if (o1 != o2 and o3 != o4): return True # Special Cases # p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 and onSegment(p1x, p1y, p2x, p2y, q1x, q1y)):return True # p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 and onSegment(p1x, p1y, q2x, q2y, q1x, q1y)):return True # p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 and onSegment(p2x, p2y, p1x, p1y, q2x, q2y)):return True # p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 and onSegment(p2x, p2y, q1x, q1y, q2x, q2y)):return True return False # Doesn't fall in any of the above cases def isSameCoord(x1, y1, x2, y2): if x1==x2 and y1==y2: return True return False # do p is an end point of edge (u,v) def isEndPoint(ux, uy, vx, vy, px, py): if isSameCoord(ux, uy, px, py) or isSameCoord(vx, vy, px, py): return True return False # is (p1,q1) is adjacent to (p2,q2)? def areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isEndPoint(p1x, p1y, q1x, q1y, p2x, p2y): return True elif isEndPoint(p1x, p1y, q1x, q1y, q2x, q2y): return True return False def isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): x1 = p1x-q1x y1 = p1y-q1y x2 = p2x-q2x y2 = p2y-q2y cross_prod_value = x1*y2 - x2*y1 if cross_prod_value==0: return True return False # here p1q1 is one segment, and p2q2 is another # this function checks first whether there is a shared vertex # then it checks whether they are colinear # finally it checks the segment intersection def doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if strictlyOnSegment(p1x, p1y, p2x, p2y, q1x, q1y) or strictlyOnSegment(p1x, p1y, q2x, q2y, q1x, q1y) or strictlyOnSegment(p2x, p2y, p1x, p1y, q2x, q2y) or strictlyOnSegment(p2x, p2y, q1x, q1y, q2x, q2y): return True else: return False else: return False return doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) def getIntersection(x11, y11, x12, y12, x21, y21, x22, y22): slope1 = 0 slope2 = 0 yint1 = 0 yint2 = 0 intx = 0 inty = 0 #TODO: Please Check all four cases if (x11 == x21 and y11 == y21):return [x11, y11] if (x12 == x22 and y12 == y22):return [x12, y22] # Check 1st point of edge 1 with 2nd point of edge 2 and viceversa slope1 = slope(x11, y11, x12, y12) slope2 = slope(x21, y21, x22, y22) #print('slope1:'+str(slope1)) #print('slope2:'+str(slope2)) if (slope1 == slope2):return False yint1 = yInt(x11, y11, x12, y12) yint2 = yInt(x21, y21, x22, y22) #print('yint1:'+str(yint1)) #print('yint2:'+str(yint2)) if (yint1 == yint2): if (yint1 == False):return False else:return [0, yint1] if(x11 == x12):return [x11, slope2*x11+yint2] if(x21 == x22):return [x21, slope1*x21+yint1] if(y11 == y12):return [(y11-yint2)/slope2,y11] if(y21 == y22):return [(y21-yint1)/slope1,y21] if (slope1 == False):return [y21, slope2 * y21 + yint2] if (slope2 == False):return [y11, slope1 * y11 + yint1] intx = (yint1 - yint2)/ (slope2-slope1) return [intx, slope1 * intx + yint1] def to_deg(rad): return rad*180/math.pi # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSegDegree(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) #return angle return to_deg(angle) # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSeg(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) return angle def count_crossings_single_graph(G): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] for c1 in range(0, len(edge_list)): for c2 in range(c1+1, len(edge_list)): edge1 = edge_list[c1] edge2 = edge_list[c2] (s1,t1) = (edge1[0], edge1[1]) (s2,t2) = (edge2[0], edge2[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): # print(cr) crossings_edges.append((edge1, edge2)) # print(edge1, edge2, p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) count = count + 1 return crossings_edges # if len(segment_pair)==2: # count = count + 1 # else: # count = count + comb(len(segment_pair), 2) return crossings_edges def count_crossings(G, edges_to_compare=None): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] edge_set_1 = edge_list if edges_to_compare is not None: edge_set_1 = edges_to_compare for c1 in range(0, len(edge_set_1)): edge1 = edge_set_1[c1] (s1,t1) = (edge1[0], edge1[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] j_start=c1+1 if edges_to_compare is not None: j_start=0 for c2 in range(j_start, len(edge_list)): edge2 = edge_list[c2] (s2,t2) = (edge2[0], edge2[1]) p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): crossings_edges.append((edge1, edge2)) count = count + 1 return crossings_edges return crossings_edges
8,633
28.267797
207
py
mlgd
mlgd-master/layout_generator/raw_data/data_manager/graphfile_converter/dot2txt.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx from networkx.drawing.nx_agraph import read_dot as nx_read_dot import vertexmanager def dot_to_txt(input_file, output_file): G = nx_read_dot(input_file) print(nx.info(G)) f = open(output_file, 'w') f.write(str(len(G.nodes()))+'\n') id_to_name = dict() name_to_id = dict() count = 0 for node_id in G.nodes(): node = G.node[node_id] name_to_id[node_id] = count count += 1 x, y = vertexmanager.getCoordinate(node) f.write(str(x) + ' ' + str(y) + '\n') print(name_to_id) for edg in G.edges(): f.write(str(name_to_id[edg[0]]) + " " + str(name_to_id[edg[1]]) + "\n") f.close() # Main Flow input_path = sys.argv[1] output_path = sys.argv[2] dot_to_txt(input_path, output_path)
849
21.972973
79
py
mlgd
mlgd-master/layout_generator/raw_data/data_manager/graphfile_converter/vertexmanager.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex)
446
13.9
42
py
mlgd
mlgd-master/layout_generator/raw_data/data_manager/graphfile_converter/ericscsvconverter.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math graphpath = sys.argv[1] path_folder = os.path.dirname(graphpath) input_file_name = os.path.basename(graphpath) graph_name = input_file_name.split(".")[0] graphs_folder = path_folder+'/graphs' layouts_folder = path_folder+'/layouts' print(graphs_folder) print(layouts_folder) if not os.path.exists(graphs_folder): os.makedirs(graphs_folder) if not os.path.exists(layouts_folder): os.makedirs(layouts_folder) print(path_folder) G = nx_read_dot(graphpath) all_pos = nx.get_node_attributes(G, "pos") # all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) vertices_ids = sorted(all_pos.keys()) edges_str = "" for currEdge in nx.edges(G): edges_str = edges_str + currEdge[0]+","+currEdge[1] + "\n" layout_str = "" for value in vertices_ids: layout_str = layout_str + all_pos[value] + "\n" f_graph = open(graphs_folder+'/'+graph_name+"_graph.csv", "w") f_graph.write(edges_str) f_layout = open(layouts_folder+'/'+graph_name+"_layout.csv", "w") f_layout.write(layout_str)
1,311
22.428571
118
py
mlgd
mlgd-master/layout_generator/raw_data/data_manager/graphfile_converter/gml2dot.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot g_path = sys.argv[1] outputpath = sys.argv[2] g_name = os.path.basename(g_path).split(".")[0] # Reading graph and subgraph G = nx.read_gml(g_path) G = nx.Graph(G) graphics = nx.get_node_attributes(G, "graphics") # print(graphics) for k in graphics.keys(): pos = str(graphics[k]['x']) +"," + str(graphics[k]['y']) nx.set_node_attributes(G, {k:pos}, 'pos') nx.set_node_attributes(G, {k:""}, "graphics") nx.set_node_attributes(G, {k:k}, "label") G = nx.Graph(G) write_dot(G, outputpath)
748
20.4
62
py
mlgd
mlgd-master/layout_generator/raw_data/data_manager/graphfile_converter/levelsfetcher.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot g_path = sys.argv[1] h_path = sys.argv[2] outputpath = sys.argv[3] g_name = os.path.basename(g_path).split(".")[0] # Reading graph and subgraph G=nx_read_dot(g_path) G = nx.Graph(G) H=nx_read_dot(h_path) H=nx.Graph(H) glevels=nx.get_node_attributes(G, "level") glabels=nx.get_node_attributes(G,'label') gfontsize=nx.get_node_attributes(G, "fontsize") gweight=nx.get_node_attributes(G, "weight") gwidth=nx.get_node_attributes(G, "width") gheight=nx.get_node_attributes(G, "height") gfontname=nx.get_node_attributes(G, "fontname") levels_n = {} id_n={} fontsize_n={} weight_n={} width_n={} height_n={} fontname_n={} for k in glabels.keys(): levels_n[glabels[k]]=glevels[k] id_n[glabels[k]]=k fontsize_n[glabels[k]]=gfontsize[k] weight_n[glabels[k]]=gweight[k] height_n[glabels[k]]=gheight[k] fontname_n[glabels[k]]=gfontname[k] width_n[glabels[k]]=gwidth[k] nx.set_node_attributes(H, levels_n, "level") nx.set_node_attributes(H, id_n, "identifier") nx.set_node_attributes(H, fontsize_n, "fontsize") nx.set_node_attributes(H, weight_n, "weight") nx.set_node_attributes(H, width_n, "width") nx.set_node_attributes(H, height_n, "height") nx.set_node_attributes(H, fontname_n, "fontname") write_dot(H, outputpath)
1,488
22.265625
62
py
mlgd
mlgd-master/layout_generator/raw_data/data_manager/levels_manager/forest_extractor.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random # Main Flow t1path = sys.argv[1] t2path = sys.argv[2] outputpath = sys.argv[3] # Main Graph t1_name = os.path.basename(t1path).split(".")[0] t2_name = os.path.basename(t2path).split(".")[0] print(t1_name, t2_name) # Reading graph and subgraph G_t1 = nx_read_dot(t1path) G_t2 = nx_read_dot(t2path) # print(nx.info(G_t1)) # print(nx.info(G_t2)) t1_label_dict = nx.get_node_attributes(G_t1, 'label') t2_label_dict = nx.get_node_attributes(G_t2, 'label') for k in t1_label_dict.keys(): t1_label_dict[k] = t1_label_dict[k].encode('utf-8') for k in t2_label_dict.keys(): t2_label_dict[k] = t2_label_dict[k].encode('utf-8') nx.set_node_attributes(G_t1, t1_label_dict, 'label') nx.set_node_attributes(G_t2, t2_label_dict, 'label') # Extract common vertices commonVertices = set(set(G_t1.nodes()) & set(G_t2.nodes())) t2_only_vertices = set(G_t2.nodes()).difference(set(G_t1.nodes())) forest_vertices = set() forest_vertices = set(G_t2.nodes()).difference(set(G_t1.nodes())) for v_id in commonVertices: v_adjs = set(nx.neighbors(G_t2, v_id)) adjs_new = v_adjs.difference(commonVertices) if len(adjs_new)>0: # v is connected to new vertices forest_vertices.add(v_id) # print("forest vertices", forest_vertices) t2_forest = nx.Graph(nx.subgraph(G_t2, forest_vertices)) t2_forest.remove_edges_from(nx.edges(G_t1)) # print("forest", nx.info(t2_forest)) write_dot(t2_forest, outputpath+t2_name+"_forest.dot") print("done")
1,727
22.04
66
py
mlgd
mlgd-master/layout_generator/raw_data/data_manager/levels_manager/forest_extractor_new.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random # Main Flow t1path = sys.argv[1] t2path = sys.argv[2] outputpath = sys.argv[3] # Main Graph t1_name = os.path.basename(t1path).split(".")[0] t2_name = os.path.basename(t2path).split(".")[0] print(t1_name, t2_name) # Reading graph and subgraph G_t1 = nx_read_dot(t1path) G_t2 = nx_read_dot(t2path) # print(nx.info(G_t1)) # print(nx.info(G_t2)) #t1_label_dict = nx.get_node_attributes(G_t1, 'label') #t2_label_dict = nx.get_node_attributes(G_t2, 'label') #for k in t1_label_dict.keys(): # t1_label_dict[k] = t1_label_dict[k].encode('utf-8') #for k in t2_label_dict.keys(): # t2_label_dict[k] = t2_label_dict[k].encode('utf-8') #nx.set_node_attributes(G_t1, t1_label_dict, 'label') #nx.set_node_attributes(G_t2, t2_label_dict, 'label') # Extract common vertices commonVertices = set(set(G_t1.nodes()) & set(G_t2.nodes())) t2_only_vertices = set(G_t2.nodes()).difference(set(G_t1.nodes())) forest_vertices = set() forest_vertices = set(G_t2.nodes()).difference(set(G_t1.nodes())) for v_id in commonVertices: v_adjs = set(nx.neighbors(G_t2, v_id)) adjs_new = v_adjs.difference(commonVertices) if len(adjs_new)>0: # v is connected to new vertices forest_vertices.add(v_id) # print("forest vertices", forest_vertices) t2_forest = nx.Graph(nx.subgraph(G_t2, forest_vertices)) t2_forest.remove_edges_from(nx.edges(G_t1)) # print("forest", nx.info(t2_forest)) write_dot(t2_forest, outputpath+t2_name+"_forest.dot") print("done")
1,735
22.146667
66
py
mlgd
mlgd-master/layout_generator/raw_data/framework/modules/propertyfetcher.py
import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot # Main Flow graph_path = sys.argv[1] tree_path = sys.argv[2] outputpath = tree_path #sys.argv[3] input_graph_name = os.path.basename(graph_path) graph_name = input_graph_name.split(".")[1] G=nx_read_dot(graph_path) G=nx.Graph(G) T=nx_read_dot(tree_path) T=nx.Graph(T) print(nx.info(G)) print(nx.info(T)) # weight_V_info=nx.get_node_attributes(G, 'weight') label_V_info=nx.get_node_attributes(G, 'label') width_V_info=nx.get_node_attributes(G, 'width') heigth_V_info=nx.get_node_attributes(G, 'height') level_V_info=nx.get_node_attributes(G, 'level') #pos_V_info=nx.get_node_attributes(G, 'pos') fontname_V_info=nx.get_node_attributes(G, 'fontname') fontsize_V_info=nx.get_node_attributes(G, 'fontsize') # nx.set_node_attributes(T, weight_V_info, 'weight') nx.set_node_attributes(T, label_V_info, 'label') nx.set_node_attributes(T, width_V_info, 'width') nx.set_node_attributes(T, heigth_V_info, 'height') # nx.set_node_attributes(T, level_V_info, 'level') #nx.set_node_attributes(T, pos_V_info, 'pos') nx.set_node_attributes(T, fontname_V_info, 'fontname') nx.set_node_attributes(T, fontsize_V_info, 'fontsize') write_dot(T, outputpath)
1,342
25.86
62
py
mlgd
mlgd-master/layout_generator/raw_data/framework/modules/augment/tree_crossings_remover.py
#Author #Felice De Luca #https://github.com/felicedeluca # This script removes the crossings from the given tree # it searches for a crossing, splits the graph in 3 components removing # the crossing edges and then scales the smaller component till there is no more # crossing. import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random import edge_crossing as crossings import vertexmanager def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): vertexmanager.shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def scale(G, scaling_factor): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) min_y = float(coo_y[0]) for currVertex in nx.nodes(G): v = G.node[currVertex] v_x, v_y = vertexmanager.getCoordinate(v) v_x_scaled = v_x * scaling_factor v_y_scaled = v_y * scaling_factor vertexmanager.setCoordinate(v, v_x_scaled, v_y_scaled) return G def remove_crossings(G): while len(crossings.count_crossings_single_graph(G)): crs = crossings.count_crossings_single_graph(G) current_crossing_edges = crs[0] G_copy = G.copy() # Removing edges to separate graph G_copy.remove_edges_from(current_crossing_edges) # Getting the smaller component to be scaled smaller_component_vertices = list([c for c in sorted(nx.connected_components(G_copy), key=len, reverse=True)][-1]) # print(smaller_component_vertices) main_edge = "" main_vertex = "" other_vertex = "" # Getting the edge connecting the main and the smaller component for curr_edge in current_crossing_edges: s = curr_edge[0] t = curr_edge[1] if s in smaller_component_vertices: main_vertex = t other_vertex = s main_edge = curr_edge break if t in smaller_component_vertices: main_vertex = s other_vertex = t main_edge = curr_edge break # print("main: " + main_vertex) # print("other: " + other_vertex) # print(main_edge) # Translating the graph for better scaling translation_dx, translation_dy = vertexmanager.getCoordinate(G.node[main_vertex]) translateGraph(G, -translation_dx, -translation_dy) subcomponet_vertices = smaller_component_vertices subcomponet_edges = G.subgraph(subcomponet_vertices).copy().edges() H = nx.Graph() H.add_nodes_from(list(subcomponet_vertices)) H.add_node(main_vertex) nx.set_node_attributes(H, nx.get_node_attributes(G, 'pos'), 'pos') H.add_edges_from(list(subcomponet_edges)) H.add_edge(main_vertex, other_vertex) # print(nx.info(H)) # print(nx.get_node_attributes(H, 'pos')) scale(H, 0.5) # print(nx.get_node_attributes(H, 'pos')) nx.set_node_attributes(G, nx.get_node_attributes(H, 'pos'), 'pos') # print("changed") print("crossings:" + str(len(crossings.count_crossings_single_graph(G)))) return G
3,499
27.92562
122
py
mlgd
mlgd-master/layout_generator/raw_data/framework/modules/augment/addsubcomponentmodule.py
#Author #Felice De Luca #https://github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import monotone_drawing import math import random import edge_crossing as crossings import vertexmanager import tree_crossings_remover def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): vertexmanager.shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def extract_subcomponent(G, mainVertex, vertex): tempG = G.copy() tempG.remove_node(mainVertex) subcomponet_vertices = nx.node_connected_component(tempG, vertex) subcomponet_vertices.add(mainVertex) subcomponet_edges = G.subgraph(subcomponet_vertices).copy().edges() H = nx.Graph() H.add_nodes_from(list(subcomponet_vertices)) H.add_edges_from(list(subcomponet_edges)) return H def boundingBox(G): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) max_x = float(coo_x[-1]) min_y = float(coo_y[0]) max_y = float(coo_y[-1]) width = abs(max_x - min_x) height = abs(max_y - min_y) return width, height def scale(G, scaling_factor): for currVertex in nx.nodes(G): v = G.node[currVertex] x = float(v['pos'].split(",")[0]) y = float(v['pos'].split(",")[1]) v_x_scaled = x * scaling_factor v_y_scaled = y * scaling_factor v['pos'] = str(v_x_scaled)+","+str(v_y_scaled) return G def rotate(G, angle): angle = math.radians(angle) for currVertex in nx.nodes(G): x, y = vertexmanager.getCoordinate(G.node[currVertex]) x_rot = x*math.cos(angle) - y*math.sin(angle) y_rot = x*math.sin(angle) + y*math.cos(angle) vertexmanager.setCoordinate(G.node[currVertex], x_rot, y_rot) return G def getAngleOfLineBetweenTwoPoints(point1X, point1Y, point2X, point2Y): xDiff = point2X - point1X yDiff = point2Y - point1Y return math.degrees(math.atan2(yDiff, xDiff)) def computeSectorsAngles(G, commonVertex): angle_dict = dict() for currN in set(nx.all_neighbors(G, commonVertex)): v1 = G.node[commonVertex] v2 = G.node[currN] v1_x, v1_y = vertexmanager.getCoordinate(v1) v2_x, v2_y = vertexmanager.getCoordinate(v2) angle = getAngleOfLineBetweenTwoPoints(v1_x, v1_y, v2_x, v2_y) if(angle < 0): angle = 360-abs(angle) if(angle not in angle_dict.keys()): angle_dict[angle] = list() angle_dict[angle].append(currN) sorted_slopes = sorted(angle_dict.keys()) sector_angle_dict = dict() for i in range(0, len(sorted_slopes)): first_index = i second_index = i+1 if(second_index>=len(sorted_slopes)): second_index = 0 first_slope = sorted_slopes[first_index] next_slope = sorted_slopes[second_index] v1_id = angle_dict[first_slope][0] v2_id = angle_dict[next_slope][0] center = G.node[commonVertex] v1 = G.node[v1_id] v2 = G.node[v2_id] angular_resolution = next_slope-first_slope if(angular_resolution < 0): angular_resolution = 360-abs(angular_resolution) if(angular_resolution not in sector_angle_dict.keys()): sector_angle_dict[angular_resolution] = list() sector_angle_dict[angular_resolution].append([v1_id, v2_id]) return sector_angle_dict def avg_edge_length(G): sum_edge_length = 0.0 edge_count = len(G.edges()) for edge in G.edges(): s,t = edge s = G.node[s] t = G.node[t] x_source1, y_source1 = vertexmanager.getCoordinate(s) x_target1, y_target1 = vertexmanager.getCoordinate(t) curr_length = math.sqrt((x_source1 - x_target1)**2 + (y_source1 - y_target1)**2) sum_edge_length += curr_length avg_edge_len = sum_edge_length/edge_count return avg_edge_len # Main Flow graphpath = sys.argv[1] subgraphpath = sys.argv[2] outputpath = sys.argv[3] print("add subcomponent: input ", graphpath, subgraphpath, outputpath) # Main Graph input_graph_name = os.path.basename(graphpath) graph_name = input_graph_name.split(".")[0] print(graph_name) # Sub Graph to be added input_subgraph_name = os.path.basename(subgraphpath) subgraph_name = subgraphpath.split(".")[0] # Reading graph and subgraph G = nx_read_dot(graphpath) nx.set_edge_attributes(G, 'red', 'color') SubG = nx_read_dot(subgraphpath) commonVertices = set(set(G.nodes()) & set(SubG.nodes())) avg_edge_length = avg_edge_length(G) if len(crossings.count_crossings_single_graph(G)): print(graph_name + " has crossings.") print("exiting") sys.exit() v_counter=0 for commonVertex in commonVertices: v_counter+=1 translation_dx, translation_dy = vertexmanager.getCoordinate(G.node[commonVertex]) translateGraph(G, -translation_dx, -translation_dy) a_counter=0 # # Extract subcomponents, draw, sacle and attach it to the widest sector for currN in set(nx.all_neighbors(SubG, commonVertex)): a_counter+=1 # Compute sector angle and get the largest sector_angle_dict = computeSectorsAngles(G, commonVertex) sorted_angles = sorted(sector_angle_dict.keys()) largest_sector_angle = sorted_angles[-1] # Get First vertex sector_vertices = sector_angle_dict[largest_sector_angle][0] if(largest_sector_angle == 0): largest_sector_angle = 360 center_v_id = commonVertex first_v_id = sector_vertices[0] center_v = G.node[commonVertex] first_v = G.node[first_v_id] center_v_x, center_v_y = vertexmanager.getCoordinate(center_v) first_v_x, first_v_y = vertexmanager.getCoordinate(first_v) min_sector_angle = getAngleOfLineBetweenTwoPoints(center_v_x, center_v_y, first_v_x, first_v_y) if(min_sector_angle < 0): min_sector_angle = 360-abs(min_sector_angle) drawing_rotation_factor = -min_sector_angle # Rotate rotate(G, drawing_rotation_factor) # Compute subcomponent Drawing H = extract_subcomponent(SubG, commonVertex, currN) H = monotone_drawing.monotone_draw(H, commonVertex, avg_edge_length) mid_sector_angle = largest_sector_angle/2 # Place first vertex of new component on bisector currN_v = H.node[currN] currN_v_x, currN_v_y = vertexmanager.getCoordinate(currN_v) first_H_vertex_angle = getAngleOfLineBetweenTwoPoints(center_v_x, center_v_y, currN_v_x, currN_v_y) if(first_H_vertex_angle < 0): first_H_vertex_angle = 360-abs(first_H_vertex_angle) desired_first_H_angle = mid_sector_angle - first_H_vertex_angle rotate(H, desired_first_H_angle) scaling_factor = 0.5 # # # Add subcomponent G.add_nodes_from(H.copy()) nx.set_node_attributes(G, nx.get_node_attributes(H, 'pos'), 'pos') G.add_edges_from(H.edges) G.add_edge(currN, commonVertex) # Count crossings between H and G edges_to_compare = list(H.edges) edges_to_compare.append((currN, commonVertex)) crossing_pair=crossings.count_crossings(G, edges_to_compare) while len(crossing_pair): H = scale(H, scaling_factor) H_pos = nx.get_node_attributes(H, 'pos') # print(nx.nodes(H)) nx.set_node_attributes(G, H_pos, 'pos') edges_to_compare = list(H.edges) edges_to_compare.append((currN, commonVertex)) crossing_pair=crossings.count_crossings(G, edges_to_compare) rotate(G, -drawing_rotation_factor) #Place back the graph at original position translateGraph(G, translation_dx, translation_dy) G = nx.Graph(G) #G = tree_crossings_remover.remove_crossings(G) #G = nx.Graph(G) nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'level'), 'level') nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'label'), 'label') # lbl_scaling_factor = 72 # # scaled_w = nx.get_node_attributes(SubG, 'width') # for k in scaled_w.keys(): # scaled_w[k] = float(scaled_w[k])/lbl_scaling_factor # # scaled_h = nx.get_node_attributes(SubG, 'height') # for k in scaled_w.keys(): # scaled_h[k] = float(scaled_h[k])/lbl_scaling_factor # #nx.set_node_attributes(G, scaled_w, 'width') #nx.set_node_attributes(G, scaled_h, 'height') write_dot(G, outputpath)
8,758
26.718354
107
py
mlgd
mlgd-master/layout_generator/raw_data/framework/modules/augment/monotone_drawing.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx import math import vertexmanager def monotone_draw(G, root, edge_length): """ take tree assign unique slope use tan-1 for slopes if path, may consider same slop run DFS """ i = 1 vertexmanager.setCoordinate(G.node[root], 0.0, 0.0) for e in nx.dfs_edges(G,root): u, v = e slp = math.atan(i) x_u, y_u = vertexmanager.getCoordinate(G.node[u]) x_v = x_u + math.cos(slp) y_v = y_u + math.sin(slp) vertexmanager.setCoordinate(G.node[v], x_v+edge_length, y_v+edge_length) i = i + 1 return G
622
16.305556
76
py
mlgd
mlgd-master/layout_generator/raw_data/framework/modules/augment/vertexmanager.py
#Author #Felice De Luca #https://github.com/felicedeluca import networkx as nx def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex)
446
13.9
42
py
mlgd
mlgd-master/layout_generator/raw_data/framework/modules/augment/edge_crossing.py
#Author #Felice De Luca #https://github.com/felicedeluca # import math import networkx as nx # Given three colinear points p, q, r, the function checks if # point q lies on line segment 'pr' def onSegment(px, py, qx, qy, rx, ry): if (qx <= max(px, rx) and qx >= min(px, rx) and qy <= max(py, ry) and qy >= min(py, ry)): return True return False def strictlyOnSegment(px, py, qx, qy, rx, ry): if (qx < max(px, rx) and qx > min(px, rx) and qy < max(py, ry) and qy > min(py, ry)): return True return False # To find orientation of ordered triplet (p, q, r). # The function returns following values # 0 --> p, q and r are colinear # 1 --> Clockwise # 2 --> Counterclockwise def orientation(px, py, qx, qy, rx, ry): # See http://www.geeksforgeeks.org/orientation-3-ordered-points/ # for details of below formula. val = (qy - py) * (rx - qx) - (qx - px) * (ry - qy) if (val == 0):return 0 # clock or counterclock wise if (val > 0): return 1 else: return 2 def yInt(x1, y1, x2, y2): if (y1 == y2):return y1 return y1 - slope(x1, y1, x2, y2) * x1 def slope(x1, y1, x2, y2): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)) if (x1 == x2):return False return (y1 - y2) / (x1 - x2) # The main function that returns true if line segment 'p1q1' # and 'p2q2' intersect. def doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): # Find the four orientations needed for general and # special cases o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y) o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y) o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y) o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y) #if(o1==0 or o2==0 or o3==0 or o4==0):return False # General case if (o1 != o2 and o3 != o4): return True # Special Cases # p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 and onSegment(p1x, p1y, p2x, p2y, q1x, q1y)):return True # p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 and onSegment(p1x, p1y, q2x, q2y, q1x, q1y)):return True # p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 and onSegment(p2x, p2y, p1x, p1y, q2x, q2y)):return True # p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 and onSegment(p2x, p2y, q1x, q1y, q2x, q2y)):return True return False # Doesn't fall in any of the above cases def isSameCoord(x1, y1, x2, y2): if x1==x2 and y1==y2: return True return False # do p is an end point of edge (u,v) def isEndPoint(ux, uy, vx, vy, px, py): if isSameCoord(ux, uy, px, py) or isSameCoord(vx, vy, px, py): return True return False # is (p1,q1) is adjacent to (p2,q2)? def areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isEndPoint(p1x, p1y, q1x, q1y, p2x, p2y): return True elif isEndPoint(p1x, p1y, q1x, q1y, q2x, q2y): return True return False def isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): x1 = p1x-q1x y1 = p1y-q1y x2 = p2x-q2x y2 = p2y-q2y cross_prod_value = x1*y2 - x2*y1 if cross_prod_value==0: return True return False # here p1q1 is one segment, and p2q2 is another # this function checks first whether there is a shared vertex # then it checks whether they are colinear # finally it checks the segment intersection def doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if strictlyOnSegment(p1x, p1y, p2x, p2y, q1x, q1y) or strictlyOnSegment(p1x, p1y, q2x, q2y, q1x, q1y) or strictlyOnSegment(p2x, p2y, p1x, p1y, q2x, q2y) or strictlyOnSegment(p2x, p2y, q1x, q1y, q2x, q2y): return True else: return False else: return False return doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) def getIntersection(x11, y11, x12, y12, x21, y21, x22, y22): slope1 = 0 slope2 = 0 yint1 = 0 yint2 = 0 intx = 0 inty = 0 #TODO: Please Check all four cases if (x11 == x21 and y11 == y21):return [x11, y11] if (x12 == x22 and y12 == y22):return [x12, y22] # Check 1st point of edge 1 with 2nd point of edge 2 and viceversa slope1 = slope(x11, y11, x12, y12) slope2 = slope(x21, y21, x22, y22) #print('slope1:'+str(slope1)) #print('slope2:'+str(slope2)) if (slope1 == slope2):return False yint1 = yInt(x11, y11, x12, y12) yint2 = yInt(x21, y21, x22, y22) #print('yint1:'+str(yint1)) #print('yint2:'+str(yint2)) if (yint1 == yint2): if (yint1 == False):return False else:return [0, yint1] if(x11 == x12):return [x11, slope2*x11+yint2] if(x21 == x22):return [x21, slope1*x21+yint1] if(y11 == y12):return [(y11-yint2)/slope2,y11] if(y21 == y22):return [(y21-yint1)/slope1,y21] if (slope1 == False):return [y21, slope2 * y21 + yint2] if (slope2 == False):return [y11, slope1 * y11 + yint1] intx = (yint1 - yint2)/ (slope2-slope1) return [intx, slope1 * intx + yint1] def to_deg(rad): return rad*180/math.pi # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSegDegree(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) #return angle return to_deg(angle) # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSeg(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) return angle def count_crossings_single_graph(G): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] for c1 in range(0, len(edge_list)): for c2 in range(c1+1, len(edge_list)): edge1 = edge_list[c1] edge2 = edge_list[c2] (s1,t1) = (edge1[0], edge1[1]) (s2,t2) = (edge2[0], edge2[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): # print(cr) crossings_edges.append((edge1, edge2)) # print(edge1, edge2, p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) count = count + 1 return crossings_edges # if len(segment_pair)==2: # count = count + 1 # else: # count = count + comb(len(segment_pair), 2) return crossings_edges def count_crossings(G, edges_to_compare=None): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] edge_set_1 = edge_list if edges_to_compare is not None: edge_set_1 = edges_to_compare for c1 in range(0, len(edge_set_1)): edge1 = edge_set_1[c1] (s1,t1) = (edge1[0], edge1[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] j_start=c1+1 if edges_to_compare is not None: j_start=0 for c2 in range(j_start, len(edge_list)): edge2 = edge_list[c2] (s2,t2) = (edge2[0], edge2[1]) p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): crossings_edges.append((edge1, edge2)) count = count + 1 return crossings_edges return crossings_edges
8,633
28.267797
207
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/propertyfetcher.py
#Author #Felice De Luca #https://github.com/felicedeluca """ Fetch from a given graph the attributes of the vertices and copies them to the new graph. Fetched properties are given as input. The graph with the fetched properties overrides the old one. standard parameters: pos width height pos label weigth #Author #Felice De Luca #https://github.com/felicedeluca """ import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot parameters = list(sys.argv) # Main Flow graph_path = parameters[1] tree_path = parameters[2] outputpath = tree_path properties_to_fetch = ["label", "weight", "fontsize", "level", "width","height","label"] if len(parameters) > 3: properties_to_fetch = parameters[3].split(",") # Fetching parameters list input_graph_name = os.path.basename(graph_path) graph_name = input_graph_name.split(".")[1] print("fetching labels",graph_path, tree_path, properties_to_fetch, ": ", end=" ") from_graph=nx_read_dot(graph_path) from_graph=nx.Graph(from_graph) to_graph=nx_read_dot(tree_path) to_graph=nx.Graph(to_graph) for param in properties_to_fetch: nx.set_node_attributes(to_graph, nx.get_node_attributes(from_graph, param), param) print(param, end=" ") print("") write_dot(to_graph, tree_path)
1,375
21.557377
88
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/removelabelsize.py
#Author #Felice De Luca #https://github.com/felicedeluca """ Fetch from a given graph the attributes of the vertices and copies them to the new graph. Fetched properties are given as input. The graph with the fetched properties overrides the old one. standard parameters: pos width height pos label weigth #Author #Felice De Luca #https://github.com/felicedeluca """ import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot parameters = list(sys.argv) # Main Flow graph_path = parameters[1] G=nx_read_dot(graph_path) for v in nx.nodes(G): nx.set_node_attributes(G, {v:0}, "width") nx.set_node_attributes(G, {v:0}, "height") nx.set_node_attributes(G, {v:0}, "fontsize") write_dot(G, graph_path)
851
19.780488
62
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/vertexmanager.py
# Author # Felice De Luca # https://www.github.com/felicedeluca import networkx as nx def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex)
453
14.133333
42
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/resizegraph.py
# Author # Felice De Luca # https://www.github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex) def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def boundingBox(G): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) max_x = float(coo_x[-1]) min_y = float(coo_y[0]) max_y = float(coo_y[-1]) width = abs(max_x - min_x) height = abs(max_y - min_y) return width, height def scale(G, scaling_factor): for currVertex in nx.nodes(G): v = G.node[currVertex] x = float(v['pos'].split(",")[0]) y = float(v['pos'].split(",")[1]) v_x_scaled = x * scaling_factor v_y_scaled = y * scaling_factor v['pos'] = str(v_x_scaled)+","+str(v_y_scaled) return G # Main Flow graphpath = sys.argv[1] max_side = int(sys.argv[2]) # Main Graph input_graph_name = os.path.basename(graphpath) graph_name = input_graph_name.split(".")[0] # Reading graph and subgraph G = nx_read_dot(graphpath) width, height = boundingBox(G) longest_side = max(width, height) scaling_factor = max_side/longest_side G = scale(G, scaling_factor) width, height = boundingBox(G) longest_side_after = max(width, height) print("Scaling Graph from ", longest_side, "to", longest_side_after) write_dot(G, graphpath)
2,093
18.570093
71
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/refinement/uniform_leaves_edges/uniform_leaves_edges.py
import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random import leavesoverlapremoval def getCoordinate(vertex): """Returns the coordinate of the given vertex.""" x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def compute_edge_length(G, edge): """Computes the length of the given edge the position of the vertices is given by the <tt>pos</tt> attribute <strong>return</strong> length of the given edge as a double """ s1_id,t1_id = edge nodes_position = nx.get_node_attributes(G, 'pos') s1_pos = nodes_position[s1_id] t1_pos = nodes_position[t1_id] x_source1 = float(s1_pos.split(",")[0]) x_target1 = float(t1_pos.split(",")[0]) y_source1 = float(s1_pos.split(",")[1]) y_target1 = float(t1_pos.split(",")[1]) curr_length = math.sqrt((x_source1 - x_target1)**2 + (y_source1 - y_target1)**2) return curr_length def avg_edge_length(G): """Computes the average length of the given edges set <strong>return</strong> average length of the edges as a double """ edges = G.edges() sum_edge_length = 0.0 edge_count = len(edges) for e in edges: curr_length = compute_edge_length(G, e) sum_edge_length += curr_length avg_edge_len = sum_edge_length/edge_count return avg_edge_len def extract_leaves(G): """Extracts from <tt>G</tt> the vertices with degree 1, i.e. the leaves.""" leaves=[] for n in nx.nodes(G): if len(list(G.neighbors(n)))<=1: leaves.append(n) return leaves def unify_leaves_edges_leghths(G, value=-1): """This function sets the length of the edges incident on the leaves of a tree to a fixed value. The idea is to position the leaves next to their parent to save space. The edges are set to the given <tt>value</tt> parameter. If no value is given or it is set to -1 then the edges are set to half the length of the average edge lenght.""" # If the edge length value is not given set it half the length of the # average length value if value == -1: avgEdgeLength = avg_edge_length(G) value = avgEdgeLength/3 leaves = extract_leaves(G) to_be_shortened_edges = list(nx.edges(G, leaves)) print("Shortening " + str(len(to_be_shortened_edges)) + " edges.") for e in to_be_shortened_edges: if compute_edge_length(G, e) <= value: continue t_id, s_id = e s = G.node[s_id] t = G.node[t_id] origin = s leaf = t origin_id = s_id leaf_id = t_id if s in leaves: origin = t origin_id = t_id leaf = s leaf_id = s_id x_origin, y_origin = getCoordinate(origin) x_leaf, y_leaf = getCoordinate(leaf) original_edge_length = math.sqrt((x_origin-x_leaf)**2 + (y_origin-y_leaf)**2) x_num = value * (x_leaf - x_origin) y_num = value * (y_leaf - y_origin) x_den = math.sqrt((x_origin-x_leaf)**2 + (y_origin-y_leaf)**2) y_den = math.sqrt((x_origin-x_leaf)**2 + (y_origin-y_leaf)**2) x_leaf_new = x_origin + x_num/x_den y_leaf_new = y_origin + y_num/y_den G.node[leaf_id]['pos'] = str(x_leaf_new)+","+str(y_leaf_new) # ovelapping = leavesoverlapremoval.get_overlapping_vertices(G, with_vertices=[origin_id, leaf_id]) return G
3,599
24.352113
107
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/refinement/uniform_leaves_edges/leavesoverlapremoval.py
import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot # import edge_crossing as crossings import boxoverlap def remove_leaves_overlap(G): # print("computing overlap") overlapping_vertices = get_overlapping_vertices(G) # print("computing boxes") all_boxes, all_boxes_dict = compute_boxes(G) leaves = [x for x in G.nodes() if G.degree(x)==1] poss=nx.get_node_attributes(G, "pos") for bb in overlapping_vertices: # bb=overlapping_vertices.pop() u = bb["u"] v = bb["v"] if (u not in leaves) and (v not in leaves): continue width_overlap=bb["w"] height_overlap=bb["h"] delta_l_u = float('inf') delta_l_v = float('inf') desired_length_u = float('inf') desired_length_v = float('inf') if u in leaves: leaf_id = u origin_id = list(nx.all_neighbors(G, leaf_id))[0] delta_l_u = get_delta_to_remove_ovelap(G, origin_id, leaf_id, all_boxes_dict[leaf_id], width_overlap, height_overlap) desired_length_u = compute_desired_length(G, origin_id, leaf_id, delta_l_u) if v in leaves: leaf_id = v origin_id = list(nx.all_neighbors(G, leaf_id))[0] delta_l_v = get_delta_to_remove_ovelap(G, origin_id, leaf_id, all_boxes_dict[leaf_id], width_overlap, height_overlap) desired_length_v = compute_desired_length(G, origin_id, leaf_id, delta_l_v) if desired_length_u <= 0: print("delta longer than edge") delta_l_u = float('inf') if desired_length_v <= 0: print("delta longer than edge") delta_l_v = float('inf') if delta_l_v == float('inf') and delta_l_u == float('inf'): print("impossible to shorten") continue leaf_id = u desired_length = desired_length_u # print(u, v) # print(delta_l_u, delta_l_v) if delta_l_v < delta_l_u: leaf_id = v desired_length = desired_length_v origin_id = list(nx.all_neighbors(G, leaf_id))[0] shorten_leaf(leaf_id, origin_id, G, value=desired_length) # print("removed", str(u), str(v), "shorten", str(leaf_id)) # overlapping_vertices = get_overlapping_vertices(G) def compute_hit_side(G, origin, v, v_box): poss=nx.get_node_attributes(G, "pos") x_origin=float(poss[origin].split(",")[0]) y_origin=float(poss[origin].split(",")[1]) x_v=float(poss[v].split(",")[0]) y_v=float(poss[v].split(",")[1]) # {'min_x':min_x, 'max_x':max_x, 'min_y':min_y, 'max_y':max_y, 'node':v} hit = '0' # print(v_box) if crossings.doSegmentsIntersect(float(x_origin), float(y_origin), float(x_v), float(y_v), float(v_box['min_x']), float(v_box['min_y']), float(v_box['min_x']), float(v_box['max_y'])): hit = "l" if crossings.doSegmentsIntersect(float(x_origin), float(y_origin), float(x_v), float(y_v), float(v_box['max_x']), float(v_box['min_y']), float(v_box['max_x']), float(v_box['max_y'])): hit = "r" if crossings.doSegmentsIntersect(float(x_origin), float(y_origin), float(x_v), float(y_v), float(v_box['min_x']), float(v_box['min_y']), float(v_box['max_x']), float(v_box['min_y'])): hit = "b" if crossings.doSegmentsIntersect(float(x_origin), float(y_origin), float(x_v), float(y_v), float(v_box['min_x']), float(v_box['max_y']), float(v_box['max_x']), float(v_box['max_y'])): hit = "t" return hit def compute_desired_length(G, origin_id, leaf_id, delta): poss=nx.get_node_attributes(G, "pos") x_origin=float(poss[origin_id].split(",")[0]) y_origin=float(poss[origin_id].split(",")[1]) x_leaf=float(poss[leaf_id].split(",")[0]) y_leaf=float(poss[leaf_id].split(",")[1]) length = math.sqrt((x_origin - x_leaf)**2 + (y_origin - y_leaf)**2) desired_length = length - delta # print("len des delta", length, desired_length, delta, 'id', leaf_id) return desired_length def get_delta_to_remove_ovelap(G, origin_id, leaf_id, leaf_box, width_overlap, height_overlap): poss=nx.get_node_attributes(G, "pos") x_origin=float(poss[origin_id].split(",")[0]) y_origin=float(poss[origin_id].split(",")[1]) x_leaf=float(poss[leaf_id].split(",")[0]) y_leaf=float(poss[leaf_id].split(",")[1]) theta = getAngleOfLineBetweenTwoPoints(x_origin, y_origin, x_leaf, y_leaf) hit_side = compute_hit_side(G, origin_id, leaf_id, leaf_box) x_shift = height_overlap/math.cos(theta) y_shift = width_overlap/math.sin(theta) if hit_side == 0: hitsize=0 return float('inf') if hit_side == 'l' or hit_side == 'r': return x_shift if hit_side == 'b' or hit_side == 't': return y_shift # print("no side found") return float('inf') # delta = min(abs(x_shift), abs(y_shift)) # # return delta def shorten_leaf(leaf_id, origin_id, G, value=0): poss=nx.get_node_attributes(G, "pos") x_origin=float(poss[origin_id].split(",")[0]) y_origin=float(poss[origin_id].split(",")[1]) x_leaf=float(poss[leaf_id].split(",")[0]) y_leaf=float(poss[leaf_id].split(",")[1]) x_num = value * (x_leaf - x_origin) y_num = value * (y_leaf - y_origin) x_den = math.sqrt((x_origin-x_leaf)**2 + (y_origin-y_leaf)**2) y_den = math.sqrt((x_origin-x_leaf)**2+(y_origin-y_leaf)**2) x_leaf_new = x_origin + x_num/x_den y_leaf_new = y_origin + y_num/y_den G.node[leaf_id]['pos'] = str(x_leaf_new)+","+str(y_leaf_new) def get_overlapping_vertices(G, with_vertices=None): inches_to_pixel_factor = 72 leaves = [x for x in G.nodes() if G.degree[x]>0] widths=nx.get_node_attributes(G, "width") heights=nx.get_node_attributes(G, "height") overlapping_vertices=[] found = set() if with_vertices is None: with_vertices = G.nodes() for v in leaves: poss=nx.get_node_attributes(G, "pos") v_width=float(widths[v])*inches_to_pixel_factor v_height=float(heights[v])*inches_to_pixel_factor v_x=float(poss[v].split(",")[0]) v_y=float(poss[v].split(",")[1]) for u in with_vertices: if(v == u): continue if (u not in leaves) and (v not in leaves): continue u_width=float(widths[v])*inches_to_pixel_factor u_height=float(heights[v])*inches_to_pixel_factor u_x=float(poss[u].split(",")[0]) u_y=float(poss[u].split(",")[1]) curr_overlap = boxoverlap.do_overlap(v_x, v_y, v_width, v_height, u_x, u_y, u_width, u_height) if curr_overlap['a'] == 0: continue if (u,v) in found or (v, u) in found: continue overlapping_vertices.append({'v': v, 'u':u, 'w':v_width+u_width, 'h':v_height+u_height}) # overlapping_vertices.append({'v': v, 'u':u, 'w':curr_overlap['w'] , 'h':curr_overlap['h']}) found.add((u,v)) if len(overlapping_vertices)>1: print("overlapping: " + str(len(overlapping_vertices))) return overlapping_vertices def getAngleOfLineBetweenTwoPoints(point1X, point1Y, point2X, point2Y): xDiff = point2X - point1X yDiff = point2Y - point1Y angle = math.degrees(math.atan2(yDiff, xDiff)) return angle #math.radians(angle) def compute_boxes(G): all_boxes = [] widths=nx.get_node_attributes(G, "width") heights=nx.get_node_attributes(G, "height") poss=nx.get_node_attributes(G, "pos") all_boxes_dict = {} for v in G.nodes(): curr_box = {'min_x':0, 'max_x':0, 'min_y':0, 'max_y':0} v_x=float(poss[v].split(",")[0]) v_y=float(poss[v].split(",")[1]) v_width = float(widths[v]) v_height = float(heights[v]) min_x = v_x-(v_width/2) max_x = v_x+(v_width/2) min_y = v_y-(v_height/2) max_y = v_y+(v_height/2) all_boxes_dict[v] = {'min_x':min_x, 'max_x':max_x, 'min_y':min_y, 'max_y':max_y, 'node':v} all_boxes.append({'min_x':min_x, 'max_x':max_x, 'min_y':min_y, 'max_y':max_y, 'node':v}) return all_boxes, all_boxes_dict
8,414
27.818493
187
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/refinement/uniform_leaves_edges/uniform_leaves_edges_main.py
import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random import uniform_leaves_edges as uniformer tree_path = sys.argv[1] # Main Graph tree_path_name = os.path.basename(tree_path).split(".")[0] # Reading graph and subgraph G = nx_read_dot(tree_path) G = uniformer.unify_leaves_edges_leghths(G) G = nx.Graph(G) write_dot(G, tree_path)
493
16.642857
62
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/refinement/uniform_leaves_edges/boxoverlap.py
import math def do_overlap(x1, y1, w1, h1, x2, y2, w2, h2): x_min_1=x1-(w1/2) y_min_1=y1-(h1/2) x_max_1=x1+(w1/2) y_max_1=y1+(h1/2) x_min_2=x2-(w2/2) y_min_2=y2-(h2/2) x_max_2=x2+(w2/2) y_max_2=y2+(h2/2) if(x_max_1 <= x_min_2 or x_max_2 <= x_min_1 or y_max_1 <= y_min_2 or y_max_2 <= y_min_1): # print("No Overlap") overlap = {'w': 0, 'h': 0, 'a':0, 'u':-1, 'v':-1} return overlap l1=(x_min_1, y_min_1) l2=(x_min_2, y_min_2) r1=(x_max_1, y_max_1) r2=(x_max_2, y_max_2) area_1=w1*h1 area_2=w2*h2 # print(area_1) # print(area_2) width_overlap = (min(x_max_1, x_max_2)-max(x_min_1, x_min_2)) height_overlap = (min(y_max_1, y_max_2)-max(y_min_1, y_min_2)) areaI = width_overlap*height_overlap # print(areaI) total_area = area_1 + area_2 - areaI # print(total_area) overlap = {"w": width_overlap, "h": height_overlap, "a":areaI} return overlap
985
19.978723
66
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/sublevel_extractor/sublevel_extractor.py
# Author # Felice De Luca # https://www.github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random def save_graph(G, outputpath): G = nx.Graph(G) write_dot(G, outputpath) def extract_level(G, level): G = nx.Graph(G) levels_info = nx.get_node_attributes(G, 'level') to_remove_nodes = [n for n in levels_info.keys() if int(levels_info[n]) > level] G.remove_nodes_from(to_remove_nodes) return G g_path = sys.argv[1] outputpath = sys.argv[2] g_name = os.path.basename(g_path).split(".")[0] # Reading graph and subgraph G = nx_read_dot(g_path) G = nx.Graph(G) levels_info = nx.get_node_attributes(G, 'level') levels = sorted(list(set(levels_info.values()))) for level in levels: level = int(level) sub_G = extract_level(G, level) save_graph(sub_G, outputpath+g_name+"_"+str(level)+"_final.dot")
1,013
22.045455
84
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/utils/vertexmanager.py
import networkx as nx def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex)
388
13.961538
42
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/preprocessing/forest_extractor.py
#Author #Felice De Luca #https://github.com/felicedeluca """ This script extracts the forest for given two graphs with 'level' attribute on nodes #Author #Felice De Luca #https://github.com/felicedeluca """ import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random # Main Flow t1path = sys.argv[1] t2path = sys.argv[2] outputpath = sys.argv[3] # Main Graph t1_name = os.path.basename(t1path).split(".")[0] t2_name = os.path.basename(t2path).split(".")[0] print(t1_name, t2_name) # Reading graph and subgraph G_t1 = nx_read_dot(t1path) G_t2 = nx_read_dot(t2path) # print(nx.info(G_t1)) # print(nx.info(G_t2)) t1_label_dict = nx.get_node_attributes(G_t1, 'label') t2_label_dict = nx.get_node_attributes(G_t2, 'label') for k in t1_label_dict.keys(): t1_label_dict[k] = t1_label_dict[k].encode('utf-8') for k in t2_label_dict.keys(): t2_label_dict[k] = t2_label_dict[k].encode('utf-8') nx.set_node_attributes(G_t1, t1_label_dict, 'label') nx.set_node_attributes(G_t2, t2_label_dict, 'label') # Extract common vertices commonVertices = set(set(G_t1.nodes()) & set(G_t2.nodes())) t2_only_vertices = set(G_t2.nodes()).difference(set(G_t1.nodes())) forest_vertices = set() forest_vertices = set(G_t2.nodes()).difference(set(G_t1.nodes())) for v_id in commonVertices: v_adjs = set(nx.neighbors(G_t2, v_id)) adjs_new = v_adjs.difference(commonVertices) if len(adjs_new)>0: # v is connected to new vertices forest_vertices.add(v_id) # print("forest vertices", forest_vertices) t2_forest = nx.Graph(nx.subgraph(G_t2, forest_vertices)) t2_forest.remove_edges_from(nx.edges(G_t1)) # print("forest", nx.info(t2_forest)) write_dot(t2_forest, outputpath+t2_name+"_forest.dot") print("done")
1,879
21.650602
84
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/preprocessing/labelproperties.py
import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import tkinter from tkinter import * # def getBoxSize(txt, fs): # # Window = Tk() # Window.geometry("500x500+80+80") # frame = Frame(Window) # this will hold the label # frame.pack(side = "top") # measure = Label(frame, font = ('Arial', fs), text = txt) # measure.grid(row = 0, column = 0) # put the label in # measure.update_idletasks() # this is VERY important, it makes python calculate the width # width = round(round(measure.winfo_width()/72,2)*72*1.10, 2) # get the width # height= round(round(measure.winfo_height()/72,2)*72*1.10, 2) # get the height # # return height,width, fs tkinter.Frame().destroy() # Enough to initialize resources # Main Flow graph_path = sys.argv[1] outputpath = graph_path font_size = 12 if len(sys.argv)==3: font_size=int(sys.argv[2]) input_graph_name = os.path.basename(graph_path) graph_name = input_graph_name.split(".")[1] G = nx_read_dot(graph_path) G=nx.Graph(G) v_labels = nx.get_node_attributes(G, "label") v_levels = nx.get_node_attributes(G, "level") font_sizes=[30,25,20,15,12,10,9,8] # use font size array Window = Tk() Window.geometry("500x500+80+80") frame = Frame(Window) # this will hold the label frame.pack(side = "top") max_w = 0 max_h = 0 for v in v_labels.keys(): v_label = v_labels[v] v_level = 0 if v in v_levels.keys(): v_level = int(v_levels[v])-1 font_size = font_sizes[v_level] # arial36b = tkFont.Font(family='Arial', size=font_size, weight='normal') # # width = arial36b.measure(v_label) # height = arial36b.metrics('linespace') # fs = 12 fs = font_size measure = Label(frame, font = ('Arial', fs), text = v_label) measure.grid(row = 0, column = 0) # put the label in measure.update_idletasks() # this is VERY important, it makes python calculate the width width = round(round(measure.winfo_width() / 72, 2) * 72 * 1.10, 2) # get the width height= round(round(measure.winfo_height()/72 ,2) * 72 * 1.10, 2) width /= 72 height /= 72 # # max_h = max(max_h, height) # max_w = max(max_w, width) nx.set_node_attributes(G, {v:width}, "width") nx.set_node_attributes(G, {v:height}, "height") nx.set_node_attributes(G, {v:fs}, "fontsize") # for v in v_labels.keys(): # nx.set_node_attributes(G, {v:max_w}, "width") # nx.set_node_attributes(G, {v:max_h}, "height") # nx.set_node_attributes(G, {v:12}, "fontsize") # print("assigning font size",font_size, "and width and height", max_w, max_h) write_dot(G, outputpath)
2,752
25.471154
94
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/preprocessing/preparegraph.py
#Author #Felice De Luca #https://github.com/felicedeluca """ This script is to clean and prepare the graph for the next steps. First it changes the id of the vertices to integers, and sets the string of the id as label_attribute Then it extracts the levels if the 'level' info is present Finally it extracts the forests if the 'level info is present' #Author #Felice De Luca #https://github.com/felicedeluca """ import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot def extract_level(G, level): G = nx.Graph(G) levels_info = nx.get_node_attributes(G, 'level') to_remove_nodes = [n for n in levels_info.keys() if int(levels_info[n]) > level] G.remove_nodes_from(to_remove_nodes) return G parameters = list(sys.argv) # Main Flow graph_path = parameters[1] outputpath = parameters[2] input_graph_name = os.path.basename(graph_path) g_name = os.path.basename(graph_path).split(".")[0] G=nx_read_dot(graph_path) G=nx.Graph(G) print(nx.info(G)) labels_info = nx.get_node_attributes(G, 'label') G = nx.convert_node_labels_to_integers(G, label_attribute='label') if len(labels_info.keys()) > 0: nx.set_node_attributes(G, labels_info, 'label') #TODO add label size info: width height font name font size write_dot(G, outputpath+g_name+"intid.dot") levels_info = nx.get_node_attributes(G, 'level') levels = sorted(list(set(levels_info.values()))) level_to_graph_map = dict() if len(levels) < 1 : print("No level info") quit() print("extracting levels") for level in levels: level = int(level) sub_G = extract_level(G, level) level_to_graph_map[level] = nx.Graph(sub_G) write_dot(sub_G, outputpath+g_name+"_"+str(level)+".dot") print("extracting forests") print(level_to_graph_map.keys()) for i in range(0, len(levels)-1): prev_level_index = int(levels[i]) next_level_index = int(levels[i+1]) G_t1 = nx.Graph(level_to_graph_map[prev_level_index]) G_t2 = nx.Graph(level_to_graph_map[next_level_index]) commonVertices = set(set(G_t1.nodes()) & set(G_t2.nodes())) t2_only_vertices = set(G_t2.nodes()).difference(set(G_t1.nodes())) forest_vertices = set() forest_vertices = set(G_t2.nodes()).difference(set(G_t1.nodes())) for v_id in commonVertices: v_adjs = set(nx.neighbors(G_t2, v_id)) adjs_new = v_adjs.difference(commonVertices) if len(adjs_new)>0: # v is connected to new vertices forest_vertices.add(v_id) # print("forest vertices", forest_vertices) t2_forest = nx.Graph(nx.subgraph(G_t2, forest_vertices)) t2_forest.remove_edges_from(nx.edges(G_t1)) write_dot(t2_forest, outputpath+g_name+"_"+str(next_level_index)+"_forest.dot")
2,847
24.428571
84
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/add_forest/tree_crossings_remover.py
# Author # Felice De Luca # https://www.github.com/felicedeluca # This script removes the crossings from the given tree # it searches for a crossing, splits the graph in 3 components removing # the crossing edges and then scales the smaller component till there is no more # crossing. import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import math import random import edge_crossing as crossings import vertexmanager def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): vertexmanager.shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def scale(G, scaling_factor): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) min_y = float(coo_y[0]) for currVertex in nx.nodes(G): v = G.node[currVertex] v_x, v_y = vertexmanager.getCoordinate(v) v_x_scaled = v_x * scaling_factor v_y_scaled = v_y * scaling_factor vertexmanager.setCoordinate(v, v_x_scaled, v_y_scaled) return G def remove_crossings(G): while len(crossings.count_crossings_single_graph(G)): crs = crossings.count_crossings_single_graph(G) current_crossing_edges = crs[0] G_copy = G.copy() # Removing edges to separate graph G_copy.remove_edges_from(current_crossing_edges) # Getting the smaller component to be scaled smaller_component_vertices = list([c for c in sorted(nx.connected_components(G_copy), key=len, reverse=True)][-1]) # print(smaller_component_vertices) main_edge = "" main_vertex = "" other_vertex = "" # Getting the edge connecting the main and the smaller component for curr_edge in current_crossing_edges: s = curr_edge[0] t = curr_edge[1] if s in smaller_component_vertices: main_vertex = t other_vertex = s main_edge = curr_edge break if t in smaller_component_vertices: main_vertex = s other_vertex = t main_edge = curr_edge break # print("main: " + main_vertex) # print("other: " + other_vertex) # print(main_edge) # Translating the graph for better scaling translation_dx, translation_dy = vertexmanager.getCoordinate(G.node[main_vertex]) translateGraph(G, -translation_dx, -translation_dy) subcomponet_vertices = smaller_component_vertices subcomponet_edges = G.subgraph(subcomponet_vertices).copy().edges() H = nx.Graph() H.add_nodes_from(list(subcomponet_vertices)) H.add_node(main_vertex) nx.set_node_attributes(H, nx.get_node_attributes(G, 'pos'), 'pos') H.add_edges_from(list(subcomponet_edges)) H.add_edge(main_vertex, other_vertex) # print(nx.info(H)) # print(nx.get_node_attributes(H, 'pos')) scale(H, 0.5) # print(nx.get_node_attributes(H, 'pos')) nx.set_node_attributes(G, nx.get_node_attributes(H, 'pos'), 'pos') # print("changed") print("crossings:" + str(len(crossings.count_crossings_single_graph(G)))) return G
3,506
27.983471
122
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/add_forest/propertyfetcher.py
#Author #Felice De Luca #https://github.com/felicedeluca """ Fetch from a given graph the attributes of the vertices and copies them to the new graph. Fetched properties are given as input. The graph with the fetched properties overrides the old one. standard parameters: pos width height pos label weigth #Author #Felice De Luca #https://github.com/felicedeluca """ import sys import os import math import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot parameters = list(sys.argv) # Main Flow graph_path = parameters[1] tree_path = parameters[2] outputpath = tree_path properties_to_fetch = [] if len(parameters) <= 3: properties_to_fetch = ["label", "weight", "fontsize", "fontname", "level","width","height", "pos"] else: properties_to_fetch = parameters[3:] # Fetching parameters list input_graph_name = os.path.basename(graph_path) graph_name = input_graph_name.split(".")[1] from_graph=nx_read_dot(graph_path) from_graph=nx.Graph(from_graph) to_graph=nx_read_dot(tree_path) to_graph=nx.Graph(to_graph) # looping over all properties to be fetched for param in properties_to_fetch: nx.set_node_attributes(to_graph, nx.get_node_attributes(from_graph, param), param) # Uncomment to fetch edges properties as well # nx.set_edge_attributes(to_graph, nx.set_edge_attributes(from_graph, param), param) write_dot(to_graph, outputpath)
1,474
22.790323
102
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/add_forest/addsubcomponentmodule.py
# Author # Felice De Luca # https://www.github.com/felicedeluca import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import monotone_drawing import math import random import edge_crossing as crossings import vertexmanager import tree_crossings_remover def translateGraph(G, translation_dx, translation_dy): for currVertex in nx.nodes(G): vertexmanager.shiftVertex(G.node[currVertex], translation_dx, translation_dy) return G def extract_subcomponent(G, mainVertex, vertex): tempG = G.copy() tempG.remove_node(mainVertex) subcomponet_vertices = nx.node_connected_component(tempG, vertex) subcomponet_vertices.add(mainVertex) subcomponet_edges = G.subgraph(subcomponet_vertices).copy().edges() H = nx.Graph() H.add_nodes_from(list(subcomponet_vertices)) H.add_edges_from(list(subcomponet_edges)) return H def boundingBox(G): all_pos = nx.get_node_attributes(G, "pos").values() coo_x = sorted([float(p.split(",")[0]) for p in all_pos]) coo_y = sorted([float(p.split(",")[1]) for p in all_pos]) min_x = float(coo_x[0]) max_x = float(coo_x[-1]) min_y = float(coo_y[0]) max_y = float(coo_y[-1]) width = abs(max_x - min_x) height = abs(max_y - min_y) return width, height def scale(G, scaling_factor): for currVertex in nx.nodes(G): v = G.node[currVertex] x = float(v['pos'].split(",")[0]) y = float(v['pos'].split(",")[1]) v_x_scaled = x * scaling_factor v_y_scaled = y * scaling_factor v['pos'] = str(v_x_scaled)+","+str(v_y_scaled) return G def rotate(G, angle): angle = math.radians(angle) for currVertex in nx.nodes(G): x, y = vertexmanager.getCoordinate(G.node[currVertex]) x_rot = x*math.cos(angle) - y*math.sin(angle) y_rot = x*math.sin(angle) + y*math.cos(angle) vertexmanager.setCoordinate(G.node[currVertex], x_rot, y_rot) return G def getAngleOfLineBetweenTwoPoints(point1X, point1Y, point2X, point2Y): xDiff = point2X - point1X yDiff = point2Y - point1Y return math.degrees(math.atan2(yDiff, xDiff)) def computeSectorsAngles(G, commonVertex): angle_dict = dict() for currN in set(nx.all_neighbors(G, commonVertex)): v1 = G.node[commonVertex] v2 = G.node[currN] v1_x, v1_y = vertexmanager.getCoordinate(v1) v2_x, v2_y = vertexmanager.getCoordinate(v2) angle = getAngleOfLineBetweenTwoPoints(v1_x, v1_y, v2_x, v2_y) if(angle < 0): angle = 360-abs(angle) if(angle not in angle_dict.keys()): angle_dict[angle] = list() angle_dict[angle].append(currN) sorted_slopes = sorted(angle_dict.keys()) sector_angle_dict = dict() for i in range(0, len(sorted_slopes)): first_index = i second_index = i+1 if(second_index>=len(sorted_slopes)): second_index = 0 first_slope = sorted_slopes[first_index] next_slope = sorted_slopes[second_index] v1_id = angle_dict[first_slope][0] v2_id = angle_dict[next_slope][0] center = G.node[commonVertex] v1 = G.node[v1_id] v2 = G.node[v2_id] angular_resolution = next_slope-first_slope if(angular_resolution < 0): angular_resolution = 360-abs(angular_resolution) if(angular_resolution not in sector_angle_dict.keys()): sector_angle_dict[angular_resolution] = list() sector_angle_dict[angular_resolution].append([v1_id, v2_id]) return sector_angle_dict def avg_edge_length(G): sum_edge_length = 0.0 edge_count = len(G.edges()) for edge in G.edges(): s,t = edge s = G.node[s] t = G.node[t] x_source1, y_source1 = vertexmanager.getCoordinate(s) x_target1, y_target1 = vertexmanager.getCoordinate(t) curr_length = math.sqrt((x_source1 - x_target1)**2 + (y_source1 - y_target1)**2) sum_edge_length += curr_length avg_edge_len = sum_edge_length/edge_count return avg_edge_len # Main Flow graphpath = sys.argv[1] subgraphpath = sys.argv[2] outputpath = sys.argv[3] print("add subcomponent: input ", graphpath, subgraphpath, outputpath) # Main Graph input_graph_name = os.path.basename(graphpath) graph_name = input_graph_name.split(".")[0] print(graph_name) # Sub Graph to be added input_subgraph_name = os.path.basename(subgraphpath) subgraph_name = subgraphpath.split(".")[0] # Reading graph and subgraph G = nx_read_dot(graphpath) nx.set_edge_attributes(G, 'red', 'color') SubG = nx_read_dot(subgraphpath) commonVertices = set(set(G.nodes()) & set(SubG.nodes())) avg_edge_length = avg_edge_length(G) if len(crossings.count_crossings_single_graph(G)): print(graph_name + " has crossings.") print("exiting") sys.exit() v_counter=0 for commonVertex in commonVertices: v_counter+=1 translation_dx, translation_dy = vertexmanager.getCoordinate(G.node[commonVertex]) translateGraph(G, -translation_dx, -translation_dy) a_counter=0 # # Extract subcomponents, draw, sacle and attach it to the widest sector for currN in set(nx.all_neighbors(SubG, commonVertex)): a_counter+=1 # Compute sector angle and get the largest sector_angle_dict = computeSectorsAngles(G, commonVertex) sorted_angles = sorted(sector_angle_dict.keys()) largest_sector_angle = sorted_angles[-1] # Get First vertex sector_vertices = sector_angle_dict[largest_sector_angle][0] if(largest_sector_angle == 0): largest_sector_angle = 360 mid_sector_angle = largest_sector_angle/2 center_v_id = commonVertex first_v_id = sector_vertices[0] center_v = G.node[commonVertex] first_v = G.node[first_v_id] center_v_x, center_v_y = vertexmanager.getCoordinate(center_v) first_v_x, first_v_y = vertexmanager.getCoordinate(first_v) # get the angle of the first segment of the sector min_sector_angle = getAngleOfLineBetweenTwoPoints(center_v_x, center_v_y, first_v_x, first_v_y) if(min_sector_angle < 0): min_sector_angle = 360-abs(min_sector_angle) #this places the center of the sector on x axis. drawing_rotation_factor = -(min_sector_angle+mid_sector_angle) # Rotate rotate(G, drawing_rotation_factor) # Compute subcomponent Drawing H = extract_subcomponent(SubG, commonVertex, currN) H = monotone_drawing.monotone_draw(H, commonVertex, avg_edge_length) # Place first vertex of new component on bisector currN_v = H.node[currN] currN_v_x, currN_v_y = vertexmanager.getCoordinate(currN_v) first_H_vertex_angle = getAngleOfLineBetweenTwoPoints(center_v_x, center_v_y, currN_v_x, currN_v_y) if(first_H_vertex_angle < 0): first_H_vertex_angle = 360-abs(first_H_vertex_angle) rotate(H, -first_H_vertex_angle) currN_v_x, currN_v_y = vertexmanager.getCoordinate(currN_v) first_H_vertex_angle = getAngleOfLineBetweenTwoPoints(center_v_x, center_v_y, currN_v_x, currN_v_y) # desired_first_H_angle = mid_sector_angle - first_H_vertex_angle # rotate(H, desired_first_H_angle) scaling_factor = 0.5 # # # Add subcomponent G.add_nodes_from(H.copy()) nx.set_node_attributes(G, nx.get_node_attributes(H, 'pos'), 'pos') G.add_edges_from(H.edges) G.add_edge(currN, commonVertex) # Count crossings between H and G edges_to_compare = list(H.edges) edges_to_compare.append((currN, commonVertex)) crossing_pair=crossings.count_crossings(G, edges_to_compare) while len(crossing_pair): H = scale(H, scaling_factor) H_pos = nx.get_node_attributes(H, 'pos') # print(nx.nodes(H)) nx.set_node_attributes(G, H_pos, 'pos') edges_to_compare = list(H.edges) edges_to_compare.append((currN, commonVertex)) crossing_pair=crossings.count_crossings(G, edges_to_compare) rotate(G, -drawing_rotation_factor) #Place back the graph at original position translateGraph(G, translation_dx, translation_dy) G = nx.Graph(G) #G = tree_crossings_remover.remove_crossings(G) #G = nx.Graph(G) nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'level'), 'level') nx.set_node_attributes(G, nx.get_node_attributes(SubG, 'label'), 'label') # lbl_scaling_factor = 72 # # scaled_w = nx.get_node_attributes(SubG, 'width') # for k in scaled_w.keys(): # scaled_w[k] = float(scaled_w[k])/lbl_scaling_factor # # scaled_h = nx.get_node_attributes(SubG, 'height') # for k in scaled_w.keys(): # scaled_h[k] = float(scaled_h[k])/lbl_scaling_factor # #nx.set_node_attributes(G, scaled_w, 'width') #nx.set_node_attributes(G, scaled_h, 'height') write_dot(G, outputpath)
9,127
26.914373
107
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/add_forest/remove_crossings_main.py
# Author # Felice De Luca # https://www.github.com/felicedeluca # This script removes the crossings from the given tree # it searches for a crossing, splits the graph in 3 components removing # the crossing edges and then scales the smaller component till there is no more # crossing. import sys import os import pygraphviz as pgv import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import tree_crossings_remover parameters = list(sys.argv) # Main Flow graph_path = parameters[1] G=nx_read_dot(graph_path) G=nx.Graph(G) G = tree_crossings_remover.remove_crossings(G) write_dot(G, graph_path)
688
18.138889
80
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/add_forest/monotone_drawing.py
# Author # Felice De Luca # https://www.github.com/felicedeluca import networkx as nx import math import vertexmanager def monotone_draw(G, root, edge_length): """ take tree assign unique slope use tan-1 for slopes if path, may consider same slop run DFS """ i = 0 # starting with zero angle vertexmanager.setCoordinate(G.node[root], 0.0, 0.0) for e in nx.dfs_edges(G,root): u, v = e slp = math.atan(i) x_u, y_u = vertexmanager.getCoordinate(G.node[u]) x_v = x_u + math.cos(slp) y_v = y_u + math.sin(slp) vertexmanager.setCoordinate(G.node[v], x_v+edge_length, y_v+edge_length) i = i + 1 return G
657
16.783784
76
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/add_forest/vertexmanager.py
# Author # Felice De Luca # https://www.github.com/felicedeluca import networkx as nx def getCoordinate(vertex): x = float(vertex['pos'].split(",")[0]) y = float(vertex['pos'].split(",")[1]) return x, y def setCoordinate(vertex, x, y): vertex['pos'] = str(x)+","+str(y) return x, y def shiftVertex(vertex, dx, dy): x, y = getCoordinate(vertex) setCoordinate(vertex, x+dx, y+dy) return getCoordinate(vertex)
453
14.133333
42
py
mlgd
mlgd-master/layout_generator/ZMLTpipeline/modules/add_forest/edge_crossing.py
# Author # Felice De Luca # https://www.github.com/felicedeluca import networkx as nx # Given three colinear points p, q, r, the function checks if # point q lies on line segment 'pr' def onSegment(px, py, qx, qy, rx, ry): if (qx <= max(px, rx) and qx >= min(px, rx) and qy <= max(py, ry) and qy >= min(py, ry)): return True return False def strictlyOnSegment(px, py, qx, qy, rx, ry): if (qx < max(px, rx) and qx > min(px, rx) and qy < max(py, ry) and qy > min(py, ry)): return True return False # To find orientation of ordered triplet (p, q, r). # The function returns following values # 0 --> p, q and r are colinear # 1 --> Clockwise # 2 --> Counterclockwise def orientation(px, py, qx, qy, rx, ry): # See http://www.geeksforgeeks.org/orientation-3-ordered-points/ # for details of below formula. val = (qy - py) * (rx - qx) - (qx - px) * (ry - qy) if (val == 0):return 0 # clock or counterclock wise if (val > 0): return 1 else: return 2 def yInt(x1, y1, x2, y2): if (y1 == y2):return y1 return y1 - slope(x1, y1, x2, y2) * x1 def slope(x1, y1, x2, y2): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)) if (x1 == x2):return False return (y1 - y2) / (x1 - x2) # The main function that returns true if line segment 'p1q1' # and 'p2q2' intersect. def doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): # Find the four orientations needed for general and # special cases o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y) o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y) o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y) o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y) #if(o1==0 or o2==0 or o3==0 or o4==0):return False # General case if (o1 != o2 and o3 != o4): return True # Special Cases # p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 and onSegment(p1x, p1y, p2x, p2y, q1x, q1y)):return True # p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 and onSegment(p1x, p1y, q2x, q2y, q1x, q1y)):return True # p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 and onSegment(p2x, p2y, p1x, p1y, q2x, q2y)):return True # p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 and onSegment(p2x, p2y, q1x, q1y, q2x, q2y)):return True return False # Doesn't fall in any of the above cases def isSameCoord(x1, y1, x2, y2): if x1==x2 and y1==y2: return True return False # do p is an end point of edge (u,v) def isEndPoint(ux, uy, vx, vy, px, py): if isSameCoord(ux, uy, px, py) or isSameCoord(vx, vy, px, py): return True return False # is (p1,q1) is adjacent to (p2,q2)? def areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isEndPoint(p1x, p1y, q1x, q1y, p2x, p2y): return True elif isEndPoint(p1x, p1y, q1x, q1y, q2x, q2y): return True return False def isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): x1 = p1x-q1x y1 = p1y-q1y x2 = p2x-q2x y2 = p2y-q2y cross_prod_value = x1*y2 - x2*y1 if cross_prod_value==0: return True return False # here p1q1 is one segment, and p2q2 is another # this function checks first whether there is a shared vertex # then it checks whether they are colinear # finally it checks the segment intersection def doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if areEdgesAdjacent(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if isColinear(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y): if strictlyOnSegment(p1x, p1y, p2x, p2y, q1x, q1y) or strictlyOnSegment(p1x, p1y, q2x, q2y, q1x, q1y) or strictlyOnSegment(p2x, p2y, p1x, p1y, q2x, q2y) or strictlyOnSegment(p2x, p2y, q1x, q1y, q2x, q2y): return True else: return False else: return False return doSegmentsIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) def getIntersection(x11, y11, x12, y12, x21, y21, x22, y22): slope1 = 0 slope2 = 0 yint1 = 0 yint2 = 0 intx = 0 inty = 0 #TODO: Please Check all four cases if (x11 == x21 and y11 == y21):return [x11, y11] if (x12 == x22 and y12 == y22):return [x12, y22] # Check 1st point of edge 1 with 2nd point of edge 2 and viceversa slope1 = slope(x11, y11, x12, y12) slope2 = slope(x21, y21, x22, y22) #print('slope1:'+str(slope1)) #print('slope2:'+str(slope2)) if (slope1 == slope2):return False yint1 = yInt(x11, y11, x12, y12) yint2 = yInt(x21, y21, x22, y22) #print('yint1:'+str(yint1)) #print('yint2:'+str(yint2)) if (yint1 == yint2): if (yint1 == False):return False else:return [0, yint1] if(x11 == x12):return [x11, slope2*x11+yint2] if(x21 == x22):return [x21, slope1*x21+yint1] if(y11 == y12):return [(y11-yint2)/slope2,y11] if(y21 == y22):return [(y21-yint1)/slope1,y21] if (slope1 == False):return [y21, slope2 * y21 + yint2] if (slope2 == False):return [y11, slope1 * y11 + yint1] intx = (yint1 - yint2)/ (slope2-slope1) return [intx, slope1 * intx + yint1] def to_deg(rad): return rad*180/math.pi # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSegDegree(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) #return angle return to_deg(angle) # x1,y1 is the 1st pt, x2,y2 is the 2nd pt, x3,y3 is the intersection pt def getAngleLineSeg(x1,y1,x2,y2,x3,y3): #print('x1:'+str(x1)+',y1:'+str(y1)+',x2:'+str(x2)+',y2:'+str(y2)+',x3:'+str(x3)+',y3:'+str(y3)) # Uses dot product dc1x = x1-x3 dc2x = x2-x3 dc1y = y1-y3 dc2y = y2-y3 norm1 = math.sqrt(math.pow(dc1x,2) + math.pow(dc1y,2)) norm2 = math.sqrt(math.pow(dc2x,2) + math.pow(dc2y,2)) if norm1==0 or norm2==0: return -1 angle = math.acos((dc1x*dc2x + dc1y*dc2y)/(norm1*norm2)) # if angle > math.pi/2.0: # angle = math.pi - angle #print('angle:'+str(angle)) return angle def count_crossings_single_graph(G): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] for c1 in range(0, len(edge_list)): for c2 in range(c1+1, len(edge_list)): edge1 = edge_list[c1] edge2 = edge_list[c2] (s1,t1) = (edge1[0], edge1[1]) (s2,t2) = (edge2[0], edge2[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): # print(cr) crossings_edges.append((edge1, edge2)) # print(edge1, edge2, p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) count = count + 1 return crossings_edges # if len(segment_pair)==2: # count = count + 1 # else: # count = count + comb(len(segment_pair), 2) return crossings_edges def count_crossings(G, edges_to_compare=None): count = 0 crossings_edges = [] all_pos = nx.get_node_attributes(G, "pos") all_pos_dict = dict((k, (float(all_pos[k].split(",")[0]), float(all_pos[k].split(",")[1]))) for k in all_pos.keys()) edge_list = [e for e in G.edges] edge_set_1 = edge_list if edges_to_compare is not None: edge_set_1 = edges_to_compare for c1 in range(0, len(edge_set_1)): edge1 = edge_set_1[c1] (s1,t1) = (edge1[0], edge1[1]) p1 = all_pos_dict[s1] q1 = all_pos_dict[t1] p1x, p1y = p1[0], p1[1] q1x, q1y = q1[0], q1[1] j_start=c1+1 if edges_to_compare is not None: j_start=0 for c2 in range(j_start, len(edge_list)): edge2 = edge_list[c2] (s2,t2) = (edge2[0], edge2[1]) p2 = all_pos_dict[s2] q2 = all_pos_dict[t2] p2x, p2y = p2[0], p2[1] q2x, q2y = q2[0], q2[1] if(doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y)): crossings_edges.append((edge1, edge2)) count = count + 1 return crossings_edges return crossings_edges
8,626
28.343537
207
py
mlgd
mlgd-master/geojson_generator/svg_to_geojson-mw.py
#see license.txt import xml.etree.ElementTree as ET import numpy as np import json import networkx as nx import pygraphviz as pgv from natsort import natsorted from glob import glob import sys def getLayer0(t1): numberofnodes= min(30, len(t1)) paths=nx.shortest_path(t1) c=nx.get_node_attributes(t1,'weight') c={k:int(v) for k, v in c.items()} s=sorted(c.items(), key=lambda x: x[1], reverse=True) selectednodes=[] for node in range(0,numberofnodes): selectednodes.append(s[node][0]) H=nx.Graph() for x in range(0, len(selectednodes)): for y in range(x+1, len(selectednodes)): p = paths[selectednodes[x]][selectednodes[y]] for i in range(0,len(p)-1): H.add_node(p[i]) H.add_edge(p[i], p[i+1]) return H #direct_topics/impred_topics/impred_lastfm #layout_name="direct_topics" #layout_name="impred_topics" # layout_name="impred_topics" nodecoordinate={} #input dir_in = sys.argv[1]#'../map_generator/mingwei-topics-refined' fn_map = f'{dir_in}/map.svg' fn_graph = f'{dir_in}/graph.dot' fn_layers = natsorted(glob(f'{dir_in}/layers/graph-*.dot')) # output dir_out = sys.argv[2] ##'../visualization_system/geojson/mingwei_topics_refined' print(fn_layers) # # if layout_name=="direct_topics": # #for direct approach # mappath="../direct_approach_output/mapDirect_modularity.svg" # # clusteroutput=globaldatapath + layout_output_dir+ "/cluster.geojson" # # polylineoutput=globaldatapath + layout_output_dir+"/cluster_boundary.geojson" # # edgesoutput=globaldatapath + layout_output_dir+"/edges.geojson" # # nodesoutput=globaldatapath + layout_output_dir+"/nodes.geojson" # # alledges=globaldatapath + layout_output_dir+"/alledges.geojson" # inputdir="../data/datasets/topics/set2/input/" # input_graph="Topics_Graph.dot" # layer_file_format="Topics_layer_{0}.dot" # if layout_name=="impred_topics": # mappath="../map_generator/impred/map.svg" # # clusteroutput=globaldatapath + layout_output_dir+"/im_cluster.geojson" # # polylineoutput=globaldatapath + layout_output_dir+"/im_cluster_boundary.geojson" # # edgesoutput=globaldatapath + layout_output_dir+"/im_edges.geojson" # # nodesoutput=globaldatapath + layout_output_dir+"/im_nodes.geojson" # # alledges=globaldatapath + layout_output_dir+"/im_alledges.geojson" # inputdir="../data/datasets/topics/set2/input/" # input_graph="Topics_Graph.dot" # layer_file_format="Topics_layer_{0}.dot" # layout_cordinate_path="../map_generator/impred/T8_for_map.dot" # if layout_name=="impred_lastfm": # mappath="../map_generator/maplastfm/map.svg" # # clusteroutput=globaldatapath + layout_output_dir+"/im_cluster.geojson" # # polylineoutput=globaldatapath + layout_output_dir+"/im_cluster_boundary.geojson" # # edgesoutput=globaldatapath + layout_output_dir+"/im_edges.geojson" # # nodesoutput=globaldatapath + layout_output_dir+"/im_nodes.geojson" # # alledges=globaldatapath + layout_output_dir+"/im_alledges.geojson" # inputdir="../ml_tree_extractor/outputs/" # input_graph="output_graph.dot" # layer_file_format="output_Layer_{0}.dot" # layout_cordinate_path="../layout_generator/ZMLTpipeline/tmp_workspace/lastfm/final/output_Layer_8.dot" clusteroutput = f'{dir_out}/im_cluster.geojson' polylineoutput = f'{dir_out}/im_cluster_boundary.geojson' edgesoutput = f'{dir_out}/im_edges.geojson' nodesoutput = f'{dir_out}/im_nodes.geojson' alledges = f'{dir_out}/im_alledges.geojson' G = nx.Graph(pgv.AGraph(fn_graph)) print('graph edges:', len(G.edges)) T = [] L = len(fn_layers) #################adding layer0############### t1 = nx.Graph(pgv.AGraph(fn_layers[0])) t = getLayer0(t1) T.append(t) ########### for i in range(1,L): R = nx.Graph(pgv.AGraph(fn_layers[i])) T.append(R) print('levels:', len(T)) def process_alledges(G,alledges): G=nx.Graph(pgv.AGraph(fn_graph)) G_cord=nx.Graph(pgv.AGraph(fn_graph)) id=0 txt="" for e in G.edges(): #import pdb; pdb.set_trace() edge = n.copy() edge["id"]= id id = id +1 edge["geometry"]["type"]="LineString" edge["properties"]=G.edges[e] n1=e[0] n2=e[1] edge["properties"]["src"]=int(n1) edge["properties"]["dest"]=int(n2) #print(n1, n2) if "weight" in G.edges[e]: edge["properties"]["weight"]=G.edges[e]['weight'] #import pdb; pdb.set_trace() a=G_cord.nodes[n1]["pos"] b=G_cord.nodes[n2]["pos"] ''' x1=float(a.split(",")[0]) y1=float(a.split(",")[1]) h = float(G_cord.nodes[n1]["height"]) * 1.10 * 72 # inch to pixel conversion w =float(G_cord.nodes[n1]["width"]) * 1.10 * 72 # inch to pixel conversion x2=float(b.split(",")[0]) y2=float(b.split(",")[1]) points_array=[[x1-w/2,y1-h/2], [x2+w/2,y2-h/2] ] ''' a=nodecoordinate[G.nodes[n1]["label"]] b=nodecoordinate[G.nodes[n2]["label"]] points_array=[a, b] #print(points_array) #print(e) edge["geometry"]["coordinates"]=points_array #import pdb; pdb.set_trace() # edge["properties"]["level"]=str(max( int(G.nodess[e1]['level']), int(G.nodess[e2]['level']))) txt=txt+ json.dumps(edge, indent=2)+ ", \n" #import pdb; pdb.set_trace() write_to_file(txt,alledges) # def getLayer(x): # for i in range(0,L+1): #considering added layer0 # if x in T[i].edges(): # return i+1 def getLevel(x): for i in range(0,len(T)): #considering added layer0 if x in T[i].nodes(): return i+1 #for direct approach root = ET.parse(fn_map).getroot() n={} n["type"]="Feature" n["geometry"]={} n["geometry"]["type"]="" n["geometry"]["coordinates"]={} n["properties"]={} header='''{ "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "EPSG:3857" } }, "features": [ ''' footer= "\n]}" def process_polygon(xml,id): polygon=n.copy() polygon["geometry"]["type"]="Polygon" polygon["id"]="cluster" + str(id) points=xml.attrib.pop('points') points_array=[[ float(p.split(",")[0]), float(p.split(",")[1]) ] for p in points.split(" ")] polygon["properties"]=xml.attrib polygon["properties"]["label"]="" polygon["geometry"]["coordinates"]=[points_array] return json.dumps(polygon, indent=2) def process_polyline(xml): polygon=n.copy() polygon["geometry"]["type"]="LineString" points=xml.attrib.pop('points') #import pdb; pdb.set_trace() points_array=[[ float(p.split(",")[0]), float(p.split(",")[1]) ] for p in points.strip().split(" ")] polygon["properties"]=xml.attrib polygon["properties"]["label"]="" polygon["geometry"]["coordinates"]=points_array return json.dumps(polygon, indent=2) def process_edge(xml,G): #import pdb; pdb.set_trace() edge=n.copy() edge["geometry"]["type"]="LineString" points=xml[1].attrib.pop('d') points=points.replace("M"," ").replace("D"," ").replace("C"," ") #import pdb; pdb.set_trace() points_array=[[ float(p.split(",")[0]), float(p.split(",")[1]) ] for p in points.strip().split(" ")] edge["properties"]=xml[1].attrib n1=xml[0].text.split("--")[0] n2=xml[0].text.split("--")[1] a=nodecoordinate[G.nodes[n1]["label"]] b=nodecoordinate[G.nodes[n2]["label"]] edge["properties"]["src"]=n1 edge["properties"]["dest"]=n2 edge["properties"]["label"]=G.nodes[n1]["label"] + " -- " + G.nodes[n2]["label"] #edge["properties"]["weight"]=G.edges[(n1,n2)]["weight"] #todo: ignoring edge weights for lastfm data edge["geometry"]["coordinates"]=[a,b] # edge["properties"]["level"]=getLevel((n1,n2)) edge["properties"]["level"]=G.edges[n1,n2]["level"] return json.dumps(edge, indent=2) def process_node(xml,G): node_g=xml[0].text node=n.copy() node["geometry"]["type"]="Point" #"Point" node["id"]="node" + node_g node["properties"]=G.nodes[node_g] x=float(xml[2].attrib.pop('x')) y=float(xml[2].attrib.pop('y')) nodecoordinate[G.nodes[node_g]["label"]]=[x,y] # h = float(node["properties"]["height"]) * 1.10 * 72 # inch to pixel conversion # w = float(node["properties"]["width"]) * 1.10 * 72 # inch to pixel conversion # points_array=[[x-w/2,y-h/2], [x+w/2,y-h/2], [x+w/2,y+h/2], [x-w/2,y+h/2], [x-w/2,y-h/2]] # node["properties"]["height"]=h # node["properties"]["width"]= w node["geometry"]["coordinates"]= [x,y] #//[x,y] node["properties"]["level"]=G.nodes[node_g]['level'] # node["properties"]["level"]=getLevel(node_g) return json.dumps(node, indent=2) def write_to_file(data,file): data=data[0:len(data)-3] data=header+ data+footer f=open(file,"w") f.write(data) f.close() polygonCount=0 polylindCount=0 nodeCount=0 edgeCount=0 polygons="" polylines="" edges="" nodes="" for child in root.findall('*[@id="graph0"]/*'): if "{http://www.w3.org/2000/svg}g"==child.tag: if child.attrib["class"]=="node": nodeCount += 1 nodes += process_node(child,G) + ", \n" for child in root.findall('*[@id="graph0"]/*'): if "polygon" in child.tag: if polygonCount!=0: #scape 1st rectangle polygons=polygons+ process_polygon(child,polygonCount) + ", \n" polygonCount=polygonCount+1 if "polyline" in child.tag: polylines=polylines+ process_polyline(child) + ", \n" if "{http://www.w3.org/2000/svg}g"==child.tag: if child.attrib["class"]=="edge": edges=edges+ process_edge(child,G)+ ", \n" edgeCount=edgeCount+1 process_alledges(G,alledges) print('polygons:', polygonCount, 'polylines:', polylindCount, 'nodes:', nodeCount) write_to_file(polygons,clusteroutput) write_to_file(polylines,polylineoutput) write_to_file(edges,edgesoutput) write_to_file(nodes,nodesoutput) ''' <g id="node2830" class="node"> <title>3506</title> <text text-anchor="middle" x="23888.5" y="-6861.22" font-family="Helvetica,sans-Serif" font-weight="bold" font-size="15.00">block copolymers</text> </g> ''' ''' <g id="edge5238" class="edge"> <title>3324&#45;&#45;971</title> <path fill="none" stroke="grey" d="M7023.05,-6911.53C7021.39,-6919.29 7019.08,-6930.12 7017.69,-6936.64"/> </g> '''
10,490
29.146552
147
py
mlgd
mlgd-master/geojson_generator/svg_to_geojson.py
#see license.txt import xml.etree.ElementTree as ET import numpy as np import json import networkx as nx import pygraphviz as pgv #direct_topics/impred_topics/impred_lastfm #layout_name="direct_topics" #layout_name="impred_topics" layout_name="impred_topics" layout_output_dir="impred_topics2" nodecoordinate={} def getLayer0(t1): numberofnodes=30 paths=nx.shortest_path(t1) c=nx.get_node_attributes(t1,'weight') c={k:int(v) for k, v in c.items()} s=sorted(c.items(), key=lambda x: x[1], reverse=True) selectednodes=[] for node in range(0,numberofnodes): selectednodes.append(s[node][0]) H=nx.Graph() for x in range(0, len(selectednodes)): for y in range(x+1, len(selectednodes)): p=paths[selectednodes[x]][selectednodes[y]] for i in range(0,len(p)-1): H.add_node(p[i]) H.add_edge(p[i], p[i+1]) print(len(H.nodes())) return H globaldatapath="../visualization_system/geojson/" if layout_name=="direct_topics": #for direct approach mappath="../direct_approach_output/mapDirect_modularity.svg" clusteroutput=globaldatapath + layout_output_dir+ "/cluster.geojson" polylineoutput=globaldatapath + layout_output_dir+"/cluster_boundary.geojson" edgesoutput=globaldatapath + layout_output_dir+"/edges.geojson" nodesoutput=globaldatapath + layout_output_dir+"/nodes.geojson" alledges=globaldatapath + layout_output_dir+"/alledges.geojson" inputdir="../data/datasets/topics/set2/input/" input_graph="Topics_Graph.dot" layer_file_format="Topics_layer_{0}.dot" if layout_name=="impred_topics": mappath="../map_generator/impred/map.svg" clusteroutput=globaldatapath + layout_output_dir+"/im_cluster.geojson" polylineoutput=globaldatapath + layout_output_dir+"/im_cluster_boundary.geojson" edgesoutput=globaldatapath + layout_output_dir+"/im_edges.geojson" nodesoutput=globaldatapath + layout_output_dir+"/im_nodes.geojson" alledges=globaldatapath + layout_output_dir+"/im_alledges.geojson" inputdir="../data/datasets/topics/set2/input/" input_graph="Topics_Graph.dot" layer_file_format="Topics_layer_{0}.dot" layout_cordinate_path="../map_generator/impred/T8_for_map.dot" if layout_name=="impred_lastfm": mappath="../map_generator/maplastfm/map.svg" clusteroutput=globaldatapath + layout_output_dir+"/im_cluster.geojson" polylineoutput=globaldatapath + layout_output_dir+"/im_cluster_boundary.geojson" edgesoutput=globaldatapath + layout_output_dir+"/im_edges.geojson" nodesoutput=globaldatapath + layout_output_dir+"/im_nodes.geojson" alledges=globaldatapath + layout_output_dir+"/im_alledges.geojson" inputdir="../ml_tree_extractor/outputs/" input_graph="output_graph.dot" layer_file_format="output_Layer_{0}.dot" layout_cordinate_path="../layout_generator/ZMLTpipeline/tmp_workspace/lastfm/final/output_Layer_8.dot" G=nx.Graph(pgv.AGraph(inputdir+input_graph)) T=[] L=8 #################adding layer0############### t1=nx.Graph(pgv.AGraph(inputdir+layer_file_format.format(1))) t=getLayer0(t1) T.append(t) ########### for i in range(0,L): R=nx.Graph(pgv.AGraph(inputdir+layer_file_format.format(i+1))) T.append(R) def process_alledges(G,alledges): global inputdir global input_graph global layout_cordinate_path G=nx.Graph(pgv.AGraph(inputdir+ input_graph)) G_cord=nx.Graph(pgv.AGraph(layout_cordinate_path)) id=0 txt="" for e in G.edges(): #import pdb; pdb.set_trace() edge=n.copy() edge["id"]= id id =id +1 edge["geometry"]["type"]="LineString" edge["properties"]=G.edges[e] n1=e[0] n2=e[1] edge["properties"]["src"]=int(n1) edge["properties"]["dest"]=int(n2) #print(n1, n2) if "weight" in G.edges[e]: edge["properties"]["weight"]=G.edges[e]['weight'] #import pdb; pdb.set_trace() a=G_cord.nodes[n1]["pos"] b=G_cord.nodes[n2]["pos"] ''' x1=float(a.split(",")[0]) y1=float(a.split(",")[1]) h = float(G_cord.nodes[n1]["height"]) * 1.10 * 72 # inch to pixel conversion w =float(G_cord.nodes[n1]["width"]) * 1.10 * 72 # inch to pixel conversion x2=float(b.split(",")[0]) y2=float(b.split(",")[1]) points_array=[[x1-w/2,y1-h/2], [x2+w/2,y2-h/2] ] ''' a=nodecoordinate[G.node[n1]["label"]] b=nodecoordinate[G.node[n2]["label"]] points_array=[a, b] #print(points_array) #print(e) edge["geometry"]["coordinates"]=points_array #import pdb; pdb.set_trace() # edge["properties"]["level"]=str(max( int(G.nodes[e1]['level']), int(G.nodes[e2]['level']))) txt=txt+ json.dumps(edge, indent=2)+ ", \n" #import pdb; pdb.set_trace() write_to_file(txt,alledges) def getLayer(x): for i in range(0,L+1): #considering added layer0 if x in T[i].edges(): return i+1 def getLevel(x): for i in range(0,L+1): #considering added layer0 if x in T[i].nodes(): return i+1 #for direct approach root = ET.parse(mappath).getroot() n={} n["type"]="Feature" n["geometry"]={} n["geometry"]["type"]="" n["geometry"]["coordinates"]={} n["properties"]={} header='''{ "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "EPSG:3857" } }, "features": [ ''' footer= "\n]}" def process_polygon(xml,id): polygon=n.copy() polygon["geometry"]["type"]="Polygon" polygon["id"]="cluster" + str(id) points=xml.attrib.pop('points') points_array=[[ float(p.split(",")[0]), float(p.split(",")[1]) ] for p in points.split(" ")] polygon["properties"]=xml.attrib polygon["properties"]["label"]="" polygon["geometry"]["coordinates"]=[points_array] return json.dumps(polygon, indent=2) def process_polyline(xml): polygon=n.copy() polygon["geometry"]["type"]="LineString" points=xml.attrib.pop('points') #import pdb; pdb.set_trace() points_array=[[ float(p.split(",")[0]), float(p.split(",")[1]) ] for p in points.strip().split(" ")] polygon["properties"]=xml.attrib polygon["properties"]["label"]="" polygon["geometry"]["coordinates"]=points_array return json.dumps(polygon, indent=2) def process_edge(xml,G): #import pdb; pdb.set_trace() edge=n.copy() edge["geometry"]["type"]="LineString" points=xml[1].attrib.pop('d') points=points.replace("M"," ").replace("D"," ").replace("C"," ") #import pdb; pdb.set_trace() points_array=[[ float(p.split(",")[0]), float(p.split(",")[1]) ] for p in points.strip().split(" ")] edge["properties"]=xml[1].attrib n1=xml[0].text.split("--")[0] n2=xml[0].text.split("--")[1] a=nodecoordinate[G.node[n1]["label"]] b=nodecoordinate[G.node[n2]["label"]] edge["properties"]["src"]=n1 edge["properties"]["dest"]=n2 edge["properties"]["label"]=G.node[n1]["label"] + " -- " + G.node[n2]["label"] #edge["properties"]["weight"]=G.edges[(n1,n2)]["weight"] #todo: ignoring edge weights for lastfm data edge["geometry"]["coordinates"]=[a,b] edge["properties"]["level"]=getLayer((n1,n2)) return json.dumps(edge, indent=2) def process_node(xml,G): node_g=xml[0].text node=n.copy() node["geometry"]["type"]="Point" #"Point" node["id"]="node" + node_g node["properties"]=G.node[node_g] x=float(xml[2].attrib.pop('x')) y=float(xml[2].attrib.pop('y')) nodecoordinate[G.node[node_g]["label"]]=[x,y] h= float(node["properties"]["height"]) * 1.10 * 72 # inch to pixel conversion w=float(node["properties"]["width"]) * 1.10 * 72 # inch to pixel conversion points_array=[[x-w/2,y-h/2], [x+w/2,y-h/2], [x+w/2,y+h/2], [x-w/2,y+h/2], [x-w/2,y-h/2]] node["properties"]["height"]=h node["properties"]["width"]= w node["geometry"]["coordinates"]= [x,y] #//[x,y] node["properties"]["level"]=getLevel(node_g) return json.dumps(node, indent=2) def write_to_file(data,file): data=data[0:len(data)-3] data=header+ data+footer f=open(file,"w") f.write(data) f.close() polygonCount=0 polylindCount=0 nodeCount=0 edgeCount=0 polygons="" polylines="" edges="" nodes="" for child in root.findall('*[@id="graph0"]/*'): if "{http://www.w3.org/2000/svg}g"==child.tag: if child.attrib["class"]=="node": nodeCount=nodeCount+1 nodes=nodes+ process_node(child,G)+ ", \n" for child in root.findall('*[@id="graph0"]/*'): if "polygon" in child.tag: if polygonCount!=0: #scape 1st rectangle polygons=polygons+ process_polygon(child,polygonCount) + ", \n" polygonCount=polygonCount+1 if "polyline" in child.tag: polylines=polylines+ process_polyline(child) + ", \n" if "{http://www.w3.org/2000/svg}g"==child.tag: if child.attrib["class"]=="edge": edges=edges+ process_edge(child,G)+ ", \n" edgeCount=edgeCount+1 process_alledges(G,alledges) print(polygonCount,polylindCount,nodeCount) write_to_file(polygons,clusteroutput) write_to_file(polylines,polylineoutput) write_to_file(edges,edgesoutput) write_to_file(nodes,nodesoutput) ''' <g id="node2830" class="node"> <title>3506</title> <text text-anchor="middle" x="23888.5" y="-6861.22" font-family="Helvetica,sans-Serif" font-weight="bold" font-size="15.00">block copolymers</text> </g> ''' ''' <g id="edge5238" class="edge"> <title>3324&#45;&#45;971</title> <path fill="none" stroke="grey" d="M7023.05,-6911.53C7021.39,-6919.29 7019.08,-6930.12 7017.69,-6936.64"/> </g> '''
9,763
28.409639
147
py
mlgd
mlgd-master/geojson_generator/dot_to_geojson.py
#see license.txt import networkx as nx import pygraphviz as pgv import json f="../T8.dot" output="/Users/iqbal/openlayerapp/T8.geojson" #/Users/iqbal/openlayerapp/map.geojson G=nx.Graph(pgv.AGraph(f)) layerinput="/Users/iqbal/MLGD/mlgd/datasets/topics/set2/input/Topics_Graph.dot" GL=nx.Graph(pgv.AGraph(layerinput)) n={} n["type"]="Feature" n["geometry"]={} n["geometry"]["type"]="Point" n["geometry"]["coordinates"]={} n["properties"]={} txt="" i=0 for node in G.nodes(): nodejson=n.copy() data= G.node[node] x=float(data["pos"].split(",")[0]) y=float(data["pos"].split(",")[1]) nodejson["geometry"]["coordinates"]=[x,y] nodejson["properties"]=data nodejson["properties"]["level"]= GL.node[node]["level"] txt=txt + json.dumps(nodejson, indent=2) + ", \n" i=i+1 if i==6000: break txt=txt[0:len(txt)-3] txt= '''{ "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "EPSG:3857" } }, "features": [ '''+txt + "\n]}" f=open(output,"w") f.write(txt) f.close()
1,065
20.32
79
py
mlgd
mlgd-master/data/direct_approach_output/old/levelextrator.py
import sys, os import networkx as nx import pygraphviz as pgv import math from networkx.readwrite import json_graph from networkx.drawing.nx_agraph import write_dot #G=nx.read_graphml('g.graphml') #write_dot(G, 'g.dot') G=nx.Graph(pgv.AGraph("g.dot")) nx.write_graphml() L=8 folderpath="../../../datasets/topics/set2/input/" outformat="Topics_Layer_{0}.dot" T=[] for i in range(0,L): t=nx.Graph(pgv.AGraph(folderpath+outformat.format(i+1))) T.append(t) def extract(G,T): H=nx.Graph() attr={} for x in G.nodes(): #import pdb; pdb.set_trace() # print(x) nid=str(int (float((G.nodes[x]["Node Id"])))) #print(nid) # if str(nid) in T.nodes(): H.add_node(nid) #k=G.nodes[x] k={} k["label"]=G.nodes[x]["label"].replace("&","") #k["pos"]=G.nodes[x]["x"] +","+ G.nodes[x]["y"] k["pos"]=str(float(G.nodes[x]["x"]) + float(G.nodes[x]["Widthpx"])/2 ) + "," + str(float( G.nodes[x]["y"])+ float(G.nodes[x]["Heightpx"])/2) #k["pos"]=str(float(G.nodes[x]["x"]) ) + "," + str(float( G.nodes[x]["y"])- float(G.nodes[x]["Heightpx"])/2) k["fontsize"]=int(G.nodes[x]["Label Font Size"]) k["height"]=float(G.nodes[x]["Heightpx"]) k["width"]=float(G.nodes[x]["Widthpx"]) k["boxxy"]=G.nodes[x]["x"] + ","+ G.nodes[x]["y"] #del k["Height"] #del k["Width"] #k["Height"]= round( float(k["Height"]) - 0.2, 2) attr[nid]=k #import pdb; pdb.set_trace() nx.set_node_attributes(H,attr) for x in T.edges(): H.add_edge(x[0],x[1]) return H for i in range(0,L): T_i=extract(G,T[i]) f='T'+str(i+1)+'.dot' o='T'+str(i+1)+'.svg' pdf='T'+str(i+1)+'.pdf' write_dot(T_i,f) #os.system('neato -n2 ' + f + " -Nfixedsize=true -Nshape=rectangle -Tsvg > "+ o) os.system('python3 dot_to_svg.py '+ f ) os.system('/Applications/Inkscape.app/Contents/Resources/script --without-gui --export-pdf=$PWD/'+pdf+' $PWD/'+o)
2,096
30.772727
155
py
mlgd
mlgd-master/data/direct_approach_output/old/dot_to_svg.py
#dot_to_svg.py g_path , outputpath , scalefactor , vertexsize import os import sys import networkx as nx import pygraphviz as pgv import math from networkx.readwrite import json_graph vertexsize='5' def scale(G,times): for x in G.nodes(): x1=float( G.node[x]['pos'].split(",")[0]) * times y1=float(G.node[x]['pos'].split(",")[1]) * times G.node[x]['pos']= str(x1) + "," + str(y1) # G.node[x]['pos']= "" + str( float(G.node[x]['pos'].split(",")[0])* times ) + ","+ str( float(G.node[x]['pos'].split(",")[1] * times)) return G def nodes_drawing(G): circles="" lines="" fillcolor="#000000" rect="" lbl="" combined="" for x in G.nodes(): x1,y1= G.node[x]["pos"].split(",") w=round(float( G.node[x]["width"]),2) h=round(float(G.node[x]["height"]),2) xtxt=str((float(x1)+w/2)) ytxt=str((float(y1)+h/2)) boxxy=G.node[x]["boxxy"].split(",") rect= '<rect width="'+str(w)+'" x="'+boxxy[0] +'" y="'+ boxxy[1] +'" height="'+str(h)+'" style="fill:rgb(255,255,255);stroke-width:2;stroke:rgb(0,0,0)" />\n' lbl= '<text text-anchor="left" x="'+str( float(boxxy[0])+3 ) +'" y="'+ str((float(boxxy[1]) + h/2+5)) +'" font-size="'+G.node[x]["fontsize"]+'" font-family="arial" fill="black">'+G.node[x]["label"] +'</text>' combined=combined+ '<g>' + rect + lbl + "</g>" circles=circles+ '<circle cx="'+ x1 + '" cy="'+ y1+'" r="'+vertexsize+'" stroke="'+fillcolor+'" stroke-width="1" fill="'+fillcolor+'"/>\n' for x in G.edges(): x1,y1=G.node[x[0]]["pos"].split(",") x2,y2=G.node[x[1]]["pos"].split(",") lines=lines+ ' <line x1="'+x1+'" y1="'+y1+'" x2="'+x2+'" y2="'+y2+'" stroke="'+fillcolor+'" stroke-width="1" />\n' return rect, lines, lbl, combined def get_bounding_box(G): xmin=0 ymin=0 xmax=0 ymax=0 ofset=0 for x in G.nodes(): xmin=min(xmin,float(G.node[x]["pos"].split(",")[0]) ) xmax=max(xmax,float(G.node[x]["pos"].split(",")[0]) ) ymin=min(ymin,float(G.node[x]["pos"].split(",")[1]) ) ymax=max(ymax,float(G.node[x]["pos"].split(",")[1]) ) return xmin ,ymin ,xmax ,ymax if len(sys.argv)<2: print ("Enter dot file with positions:") quit() g_path = sys.argv[1] outputpath = "" scalefactor=1#sys.argv[2] vertexsize='10'#sys.argv[3] g_name = os.path.basename(g_path).split(".")[0] G=nx.Graph(pgv.AGraph(g_path)) G=nx.Graph(G) #To remove multiple edges (if exist) scalefactor=float(scalefactor) #G=scale(G,scalefactor) nodes, egeds, lbl,combined =nodes_drawing(G) xmin,ymin,xmax,ymax=get_bounding_box(G) print(xmin,ymin,xmax,ymax) padding=50 w=xmax-xmin+padding h=ymax-ymin+padding #<svg height="15000" width="15000" viewBox="-10000 -10000 15000 15000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink" > svgtag='<svg width="'+str( w) +'" height="'+str(h)+'" viewBox="'+ str(xmin-padding) +' '+str(ymin-padding)+ ' ' + str( w) +' ' + str(h) + '\" xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink" >' svg_header='<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' svg_header=svg_header+svgtag+ '<rect x="'+str(xmin)+'" y="'+str(ymin)+'" width="100%" height="100%" fill="white"/>' bcurve_svg=svg_header+egeds+combined+"</svg>" x=open(outputpath+g_name+'.svg','w') x.write(bcurve_svg) x.close()
3,358
33.989583
229
py
mlgd
mlgd-master/data/datasets/small(Ryn)/print_javascript_data.py
import networkx as nx from networkx.drawing.nx_agraph import read_dot as nx_read_dot import sys levels = int(sys.argv[1]) folder_name = "lastfm" file_name = ["lastfm_12nodes.dot", "lastfm_20nodes.dot", "lastfm_43nodes.dot", "lastfm_86nodes.dot", "lastfm_155nodes.dot"] #folder_name = "topics_layer" #file_name = ["Topics_Layer_1.dot", "Topics_Layer_2.dot", "Topics_Layer_3.dot", "Topics_Layer_4.dot", "Topics_Layer_5.dot", "Topics_Layer_6.dot", "Topics_Layer_7.dot", "Topics_Layer_8.dot"] # check trees for fname in file_name: G = nx_read_dot(folder_name + '/' + fname) print(len(G.nodes())) cycle = None try: cycle = nx.find_cycle(G) except: pass if not cycle==None: print("Found cycle in ", fname) quit() G = nx_read_dot(folder_name + '/' + file_name[levels-1]) number_lab_to_name_lab = dict() name_lab_to_number_lab = dict() edges_to_index = dict() edge_distance = dict() for n in G.nodes(): number_lab_to_name_lab[n] = G.nodes[n]["label"] name_lab_to_number_lab[G.nodes[n]["label"]] = n label_to_index = dict() index_to_label = dict() bfs_edges = [] #center = "1149" center = nx.center(G)[0] for e in nx.bfs_edges(G, center): u, v = e bfs_edges.append((u, v)) bfs_edges2 = [] for e in bfs_edges: u, v = e u, v = number_lab_to_name_lab[u], number_lab_to_name_lab[v] u = u[:12] v = v[:12] bfs_edges2.append([u, v]) bfs_edges = bfs_edges2 G2 = nx.Graph() for e in G.edges(): u, v = e u, v = number_lab_to_name_lab[u], number_lab_to_name_lab[v] u = u[:12] v = v[:12] G2.add_edge(u, v) G = G2 for i in range(len(bfs_edges)): edges_to_index[(bfs_edges[i][0], bfs_edges[i][1])] = i edge_list = [] #for e in nx.bfs_edges(G, "machine learning"): for e in bfs_edges: #print(e) u, v = e if not u in label_to_index.keys(): label_to_index[u] = len(label_to_index.keys()) index_to_label[len(label_to_index.keys())-1] = u if not v in label_to_index.keys(): label_to_index[v] = len(label_to_index.keys()) index_to_label[len(label_to_index.keys())-1] = v edge_list.append([label_to_index[u], label_to_index[v]]) #print(label_to_index) #print(index_to_label) print("my_edges = ", bfs_edges) print("label_to_id = ", label_to_index) print("id_to_label = ", index_to_label) l = levels-1 cur_dis = 50 while l>=0: G = nx_read_dot(folder_name + '/' + file_name[l]) bfs_edges = [] center = nx.center(G)[0] for e in nx.bfs_edges(G, center): u, v = e bfs_edges.append((u, v)) bfs_edges2 = [] for e in bfs_edges: u, v = e u, v = number_lab_to_name_lab[u], number_lab_to_name_lab[v] u = u[:12] v = v[:12] bfs_edges2.append([u, v]) bfs_edges = bfs_edges2 for i in range(len(bfs_edges)): e = bfs_edges[i] if (e[0], e[1]) in edges_to_index.keys(): edge_index = edges_to_index[(e[0], e[1])] elif (e[1], e[0]) in edges_to_index.keys(): edge_index = edges_to_index[(e[1], e[0])] else: print("Edge not found!") quit() edge_distance[edge_index] = cur_dis l -= 1 cur_dis += 50 print("edge_distance = ", edge_distance)
3,041
25
189
py
mlgd
mlgd-master/data/datasets/refined/tree_size_reducer.py
import networkx as nx from networkx.drawing.nx_agraph import write_dot from networkx.drawing.nx_agraph import read_dot as nx_read_dot import copy def read_txt_file(fname): G = nx.Graph() f = open(fname, "r") while True: l = f.readline() if len(l)==0: break l = l.split('"') u = l[1] v = l[3] G.add_edge(u, v) f.close() return G def write_txt_file(fname, G): f = open(fname, "w") for u, v in G.edges(): f.write('"'+u+'" -- "'+v+'"\n') f.close() def reduce_tree(bot_tree, top_tree, reduction_size_arr): output_trees = [] for i in range(len(reduction_size_arr)): cur_reduction_size = reduction_size_arr[i] while cur_reduction_size>0: leaf_nodes = [x for x in bot_tree.nodes() if bot_tree.degree(x)==1] found_node_to_remove = False for l in leaf_nodes: if not l in top_tree.nodes(): bot_tree.remove_node(l) found_node_to_remove = True cur_reduction_size -= 1 if cur_reduction_size==0: break if not found_node_to_remove: print("Error: no node to remove") quit() output_trees.append(copy.deepcopy(bot_tree)) return output_trees ''' folder_name = "TopicsLayersData" file_name = ["Tree_level_0.txt", "Tree_level_1.txt", "Tree_level_2.txt", "Tree_level_3.txt", "Tree_level_4.txt"] bot_tree = read_txt_file(folder_name + '/' + file_name[0]) reduction_size_arr = [55] file_names = ["Graph_100.txt"] reduced_trees = reduce_tree(bot_tree, nx.Graph(), reduction_size_arr) for i in range(len(reduced_trees)): fname = folder_name + '/' + file_names[i] G = reduced_trees[i] write_txt_file(fname, G) bot_tree = read_txt_file(folder_name + '/' + "Graph_100.txt") reduction_size_arr = [50] file_names = ["Graph_50.txt"] reduced_trees = reduce_tree(bot_tree, nx.Graph(), reduction_size_arr) for i in range(len(reduced_trees)): fname = folder_name + '/' + file_names[i] G = reduced_trees[i] write_txt_file(fname, G) top_tree = read_txt_file(folder_name + '/' + file_name[0]) bot_tree = read_txt_file(folder_name + '/' + file_name[1]) reduction_size_arr = [98] file_names = ["Graph_200.txt"] reduced_trees = reduce_tree(bot_tree, top_tree, reduction_size_arr) for i in range(len(reduced_trees)): fname = folder_name + '/' + file_names[i] G = reduced_trees[i] write_txt_file(fname, G) top_tree = read_txt_file(folder_name + '/' + file_name[1]) bot_tree = read_txt_file(folder_name + '/' + file_name[2]) reduction_size_arr = [162] file_names = ["Graph_500.txt"] reduced_trees = reduce_tree(bot_tree, top_tree, reduction_size_arr) for i in range(len(reduced_trees)): fname = folder_name + '/' + file_names[i] G = reduced_trees[i] write_txt_file(fname, G) ''' ''' folder_name = "lastfm_felice" file_name = ["lastfm_1.dot", "lastfm_2.dot"] bot_tree = nx_read_dot(folder_name + '/' + file_name[0]) reduction_size_arr = [99, 100, 50] file_names = ["Graph_200.dot", "Graph_100.dot", "Graph_50.dot"] reduced_trees = reduce_tree(bot_tree, nx.Graph(), reduction_size_arr) for i in range(len(reduced_trees)): fname = folder_name + '/' + file_names[i] G = reduced_trees[i] write_dot(G, fname) bot_tree = nx_read_dot(folder_name + '/' + file_name[1]) top_tree = nx_read_dot(folder_name + '/' + file_name[0]) reduction_size_arr = [119] file_names = ["Graph_500.dot"] reduced_trees = reduce_tree(bot_tree, top_tree, reduction_size_arr) for i in range(len(reduced_trees)): fname = folder_name + '/' + file_names[i] G = reduced_trees[i] write_dot(G, fname) ''' folder_name = "topics_iqbal" file_name = ["Topics_Layer_1.dot", "Topics_Layer_2.dot"] bot_tree = nx_read_dot(folder_name + '/' + file_name[0]) reduction_size_arr = [113, 100, 50] file_names = ["Graph_200.dot", "Graph_100.dot", "Graph_50.dot"] reduced_trees = reduce_tree(bot_tree, nx.Graph(), reduction_size_arr) for i in range(len(reduced_trees)): fname = folder_name + '/' + file_names[i] G = reduced_trees[i] write_dot(G, fname) bot_tree = nx_read_dot(folder_name + '/' + file_name[1]) top_tree = nx_read_dot(folder_name + '/' + file_name[0]) reduction_size_arr = [400] file_names = ["Graph_500.dot"] reduced_trees = reduce_tree(bot_tree, top_tree, reduction_size_arr) for i in range(len(reduced_trees)): fname = folder_name + '/' + file_names[i] G = reduced_trees[i] write_dot(G, fname)
4,259
30.323529
112
py
mlgd
mlgd-master/data/datasets/lastfm/preprocess/preprocess.py
import networkx as nx import pygraphviz as pgv from networkx.drawing.nx_agraph import write_dot def containsNonAscii(s): return any(ord(i)>127 for i in s) G=nx.Graph(pgv.AGraph("lastfm.dot")) G2=nx.Graph(pgv.AGraph("lastfm.dot")) for n in G.nodes(): lbl=G.node[n]["label"] lbl=lbl.replace("\\n"," ") lbl=lbl.replace("\'"," ") lbl=lbl.replace("\"","") lbl=lbl.replace("&","and") if containsNonAscii(lbl): G2.remove_node(n) print (lbl) continue if len(lbl)>15: lbl=lbl[0:20]+"..." G2.node[n]["label"]=lbl write_dot(G2,"lastfm_cleaned.dot")
611
21.666667
48
py
mlgd
mlgd-master/data/datasets/topics/low_degree(Faryad)/print_javascript_data_topics.py
import networkx as nx from networkx.drawing.nx_agraph import read_dot as nx_read_dot import sys levels = int(sys.argv[1]) #folder_name = "lastfm" #file_name = ["lastfm_12nodes.dot", "lastfm_20nodes.dot", "lastfm_43nodes.dot", "lastfm_86nodes.dot", "lastfm_155nodes.dot"] #folder_name = "." #file_name = ["Layer1.dot", "Layer2.dot", "Layer3.dot", "Layer4.dot", "Layer5.dot", "Layer6.dot", "Layer7.dot"] folder_name = "TopicsLayersData" file_name = ["Tree_level_0.txt", "Tree_level_1.txt", "Tree_level_2.txt", "Tree_level_3.txt", "Tree_level_4.txt"] def create_alphanum_dict(G): org_to_alphanum = dict() alphanum_to_org = dict() for n in G.nodes(): n_short = n[:12] if n_short in alphanum_to_org.keys(): n_short = n[:10] cnt = 2 while True: cnt_str = str(cnt) if len(cnt_str)==1: cnt_str = '0'+cnt_str n_alphanum = n_short+cnt_str if not n_alphanum in alphanum_to_org.keys(): org_to_alphanum[n] = n_alphanum alphanum_to_org[n_alphanum] = n break cnt = cnt + 1 else: org_to_alphanum[n] = n_short alphanum_to_org[n_short] = n return org_to_alphanum, alphanum_to_org def convert_nodes_to_alphanum(G, org_to_alphanum, alphanum_to_org): G2 = nx.Graph() for e in G.edges(): u, v = e u2, v2 = org_to_alphanum[u], org_to_alphanum[v] G2.add_edge(u2, v2) return G2 def read_txt_file(fname): G = nx.Graph() f = open(fname, "r") while True: l = f.readline() if len(l)==0: break l = l.split('"') u = l[1] v = l[3] G.add_edge(u, v) f.close() return G org_to_alphanum, alphanum_to_org = None, None # check trees for fname in file_name: if folder_name == "TopicsLayersData": G = read_txt_file(folder_name + '/' + fname) else: G = nx_read_dot(folder_name + '/' + file_name) org_to_alphanum, alphanum_to_org = create_alphanum_dict(G) if not nx.is_connected(G): print("not connected:", fname) quit() cycle = None try: cycle = nx.find_cycle(G) except: pass if not cycle==None: print("Found cycle in ", fname) quit() if folder_name == "TopicsLayersData": G = read_txt_file(folder_name + '/' + file_name[levels-1]) else: G = nx_read_dot(folder_name + '/' + file_name[levels-1]) G = convert_nodes_to_alphanum(G, org_to_alphanum, alphanum_to_org) number_lab_to_name_lab = dict() name_lab_to_number_lab = dict() edges_to_index = dict() edge_distance = dict() #for n in G.nodes(): # number_lab_to_name_lab[n] = G.nodes[n]["label"] # name_lab_to_number_lab[G.nodes[n]["label"]] = n for u in G.nodes(): if not u in name_lab_to_number_lab.keys(): name_lab_to_number_lab[u] = len(name_lab_to_number_lab.keys()) number_lab_to_name_lab[len(name_lab_to_number_lab.keys())-1] = u label_to_index = dict() index_to_label = dict() bfs_edges = [] #center = "1149" center = nx.center(G)[0] for e in nx.bfs_edges(G, center): u, v = e bfs_edges.append((u, v)) bfs_edges2 = [] for e in bfs_edges: u, v = e #u, v = number_lab_to_name_lab[u], number_lab_to_name_lab[v] u = u[:12] v = v[:12] bfs_edges2.append([u, v]) bfs_edges = bfs_edges2 G2 = nx.Graph() for e in G.edges(): u, v = e #u, v = number_lab_to_name_lab[u], number_lab_to_name_lab[v] u = u[:12] v = v[:12] G2.add_edge(u, v) G = G2 for i in range(len(bfs_edges)): edges_to_index[(bfs_edges[i][0], bfs_edges[i][1])] = i edge_list = [] #for e in nx.bfs_edges(G, "machine learning"): for e in bfs_edges: #print(e) u, v = e if not u in label_to_index.keys(): label_to_index[u] = len(label_to_index.keys()) index_to_label[len(label_to_index.keys())-1] = u if not v in label_to_index.keys(): label_to_index[v] = len(label_to_index.keys()) index_to_label[len(label_to_index.keys())-1] = v edge_list.append([label_to_index[u], label_to_index[v]]) #print(label_to_index) #print(index_to_label) print("my_edges = ", bfs_edges) print("label_to_id = ", label_to_index) print("id_to_label = ", index_to_label) l = levels-1 cur_dis = 50 while l>=0: if folder_name == "TopicsLayersData": G = read_txt_file(folder_name + '/' + file_name[l]) else: G = nx_read_dot(folder_name + '/' + file_name[l]) G = convert_nodes_to_alphanum(G, org_to_alphanum, alphanum_to_org) bfs_edges = [] center = nx.center(G)[0] for e in nx.bfs_edges(G, center): u, v = e bfs_edges.append((u, v)) bfs_edges2 = [] for e in bfs_edges: u, v = e #u, v = number_lab_to_name_lab[u], number_lab_to_name_lab[v] u = u[:12] v = v[:12] bfs_edges2.append([u, v]) bfs_edges = bfs_edges2 for i in range(len(bfs_edges)): e = bfs_edges[i] if (e[0], e[1]) in edges_to_index.keys(): edge_index = edges_to_index[(e[0], e[1])] elif (e[1], e[0]) in edges_to_index.keys(): edge_index = edges_to_index[(e[1], e[0])] else: print("Edge not found!") quit() edge_distance[edge_index] = cur_dis l -= 1 cur_dis += 50 print("edge_distance = ", edge_distance)
4,920
25.744565
124
py