-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.py
More file actions
179 lines (170 loc) · 8.64 KB
/
Copy pathparse.py
File metadata and controls
179 lines (170 loc) · 8.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import sys
from lxml import etree
import geometry
from model import ValidationException, ERSchema, EntitySet, Multiplicity, RelationshipSet, ISA
class ParseException(Exception):
pass
def parse_style(style):
props = {}
for entry in style.split(';'):
entry = entry.strip()
if len(entry) == 0:
continue
fields = entry.split('=')
if len(fields) == 2:
props[fields[0]] = fields[1]
elif len(fields) == 1:
props[fields[0]] = "1"
elif len(fields) > 2:
raise ValueError
return props
def parse_underlined(value):
value = value.strip()
begin_underline, end_underline = '<u>', '</u>'
underlined = False
if value.startswith(begin_underline) and value.endswith(end_underline):
underlined = True
value = value[len(begin_underline):(len(value)-len(end_underline))].strip()
return value, underlined
def get_geometry_box(mxcell):
style = parse_style(mxcell.get('style', default=''))
mxgeometry = mxcell.find('mxGeometry')
return (
float(mxgeometry.get('x', 0)),
float(mxgeometry.get('y', 0)),
float(mxgeometry.get('width')),
float(mxgeometry.get('height')),
float(style.get('rotation', 0)))
def get_geometry_edge(edge_mxcell, source_mxcell, target_mxcell):
style = parse_style(edge_mxcell.get('style', default=''))
source_conn_loc = geometry.connection_point(
*get_geometry_box(source_mxcell),
float(style.get('exitX', 0)),
float(style.get('exitY', 0)))
target_conn_loc = geometry.connection_point(
*get_geometry_box(target_mxcell),
float(style.get('entryX', 0)),
float(style.get('entryY', 0)))
# following can be the fallback if the above style specs are missing:
# mxgeometry = edge_mxcell.find('mxGeometry')
# if mxgeometry is not None:
# for mxpoint in mxgeometry.xpath('./mxPoint'):
# if mxpoint.get('as') == 'sourcePoint':
# source_conn_loc = (float(mxpoint.get('x', 0)), float(mxpoint.get('y', 0)))
# elif mxpoint.get('as') == 'targetPoint':
# target_conn_loc = (float(mxpoint.get('x', 0)), float(mxpoint.get('y', 0)))
return source_conn_loc, target_conn_loc
def parse(xml_file_path):
tree = etree.parse(xml_file_path)
root = tree.getroot()
# parse out vertices and edges:
vertices, edges = {}, {}
for mxcell in root.xpath(".//mxGraphModel//mxCell"):
if mxcell.get('vertex') == '1':
style = parse_style(mxcell.get('style', default=''))
if 'edgeLabel' in style: # label on a rel-ent edge
if (label := mxcell.get('value')) is not None:
edges[mxcell.get('parent')]['role'] = label
elif mxcell.get('value') in ('0:N', '1:1', '0:1'): # multiplicity on a rel-ent edge
edges[mxcell.get('parent')]['multiplicity'] = mxcell.get('value')
elif style.get('shape', None) == 'rhombus': # relationship set
v = { 'type': 'relationship', 'name': mxcell.get('value') }
if style.get('double', None) == '1': # connecting relationship set
v['connecting'] = True
vertices[mxcell.get('id')] = v
elif style.get('shape', None) == 'ext' and style.get('double', None) == '1': # weak entity set
vertices[mxcell.get('id')] = { 'type': 'entity', 'name': mxcell.get('value'), 'weak': True }
elif 'ellipse' in style: # attribute
value, underlined = parse_underlined(mxcell.get('value'))
v = { 'type': 'attribute', 'name': value }
if underlined:
v['underlined'] = True
vertices[mxcell.get('id')] = v
elif 'triangle' in style: # ISA relationship
if mxcell.get('value', None) != 'ISA':
raise ParseException(f'triangle ({id}) should be labeled as "ISA"')
tip_loc, tip_slack = geometry.triangle_tip(*get_geometry_box(mxcell))
vertices[mxcell.get('id')] = { 'type': 'ISA', 'tip_loc': tip_loc, 'tip_slack': tip_slack }
else: # entity set
vertices[mxcell.get('id')] = { 'type': 'entity', 'name': mxcell.get('value') }
elif mxcell.get('edge') == '1':
if mxcell.get('source') is None or mxcell.get('target') is None:
raise ParseException('edge ({}) should connect two nodes'.format(mxcell.get('id')))
e = { 'source': mxcell.get('source'), 'target': mxcell.get('target') }
source = root.xpath('.//mxCell[@id="{}"]'.format(mxcell.get('source')))[0]
target = root.xpath('.//mxCell[@id="{}"]'.format(mxcell.get('target')))[0]
source_conn_loc, target_conn_loc = get_geometry_edge(mxcell, source, target)
e['source_conn_loc'] = source_conn_loc
e['target_conn_loc'] = target_conn_loc
value = mxcell.get('value', '').strip()
if value != '':
e['role'] = value
edges[mxcell.get('id')] = e
# debugging print:
# for id, obj in vertices.items():
# print(id, obj)
# for id, obj in edges.items():
# print(id, obj)
# build E/R:
attribute_vertices = {}
schema = ERSchema({}, {}, {})
for id, v in vertices.items():
if v['type'] == 'entity':
schema.add_entity_set(EntitySet(id, v['name'], 'weak' in v, [], []))
elif v['type'] == 'relationship':
schema.add_relationship_set(RelationshipSet(id, v['name'], 'connecting' in v, [], [], [], []))
elif v['type'] == 'ISA':
schema.add_isa(ISA(id, None, None))
elif v['type'] == 'attribute':
attribute_vertices[id] = v
for id, e in edges.items():
if e['source'] in attribute_vertices or e['target'] in attribute_vertices:
aid = e['source'] if e['source'] in attribute_vertices else e['target']
oid = e['target'] if e['source'] in attribute_vertices else e['source']
if oid in schema.entity_sets:
schema.get_entity_set(oid).attributes.append(attribute_vertices[aid]['name'])
schema.get_entity_set(oid).is_in_key.append('underlined' in attribute_vertices[aid])
elif oid in schema.relationship_sets:
schema.get_relationship_set(oid).attributes.append(attribute_vertices[aid]['name'])
if 'underlined' in attribute_vertices[aid]:
raise ParseException(f'attribute ({aid}) of relationship sets cannot be specified as part of key')
else:
raise ParseException(f'attribute ({aid}) must be attached to an entity or relationship set')
elif e['source'] in schema.isas or e['target'] in schema.isas:
if e['source'] in schema.isas:
iid, eid = e['source'], e['target']
conn_loc = e['source_conn_loc']
else:
iid, eid = e['target'], e['source']
conn_loc = e['target_conn_loc']
# if this edge connects to iid's triangle tip then eid is super (else sub):
if geometry.points_within_dist(*conn_loc, *(vertices[iid]['tip_loc']), vertices[iid]['tip_slack']):
if schema.get_isa(iid).superclass is not None:
raise ParseException(f'ISA ({id}) cannot point to multiple superclasses')
schema.get_isa(iid).superclass = schema.get_entity_set(eid)
else:
if schema.get_isa(iid).subclass is not None:
raise ParseException(f'{ISA ({id})} cannot point away from multiple subclasses')
schema.get_isa(iid).subclass = schema.get_entity_set(eid)
else:
if e['source'] not in schema.relationship_sets:
raise ParseException(f'edge ({id}) should point away from a relationship set')
if e['target'] not in schema.entity_sets:
raise ParseException(f'edge ({id}) should point into an entity set')
if 'multiplicity' not in e:
raise ParseException(f'edge ({id}) pointing from a relationship set to an entity should specify mutiplicity')
schema.get_relationship_set(e['source']).add_entity_set(
schema.get_entity_set(e['target']),
Multiplicity(e['multiplicity']),
e.get('role', None))
schema.validate()
schema.print()
if __name__ == '__main__':
try:
parse(sys.argv[1])
except ParseException as e:
print(f'ERROR PARSING {sys.argv[1]}: {e}')
sys.exit(1)
except ValidationException as e:
print(f'ERROR VALIDATING {sys.argv[1]}: {e}')
sys.exit(1)