/
svgBondGraph.py
498 lines (415 loc) · 15.9 KB
/
svgBondGraph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
"""Convert bond graph diagram in SVG format to BondGraphTools format"""
import BondGraphTools as bgt
import numpy as np
import sympy as sp
import svgpathtools as svgp
from lxml import etree
import datetime
def indices(list,element):
""" Find all indices of matching elements in list
"""
indexList = [i for i, x in enumerate(list) if x == element]
return indexList
def getBonds(svg,allowedColour=["#000000","#ff0000"]):
""" Extract the bonds from the SVG file.
"""
paths, attributes = svgp.svg2paths(svg)
bondList = []
for i_path,path in enumerate(paths):
colour = attributes[i_path]["stroke"]
isBond = (colour in allowedColour) and (len(path)>1)
if isBond:
segLen = []
for i,segment in enumerate(path):
#print(i,segment,segment.length())
segLen.append(segment.length())
#print(segLen,segLen[0],segLen[-1])
if segLen[0]>segLen[-1]:
## Tail at start
bondTail = path[0][0]
bondHead = path[-2][1]
else:
bondTail = path[-1][1]
bondHead = path[1][0]
#print("Tail:",bondTail, "Head:", bondHead )
bondList.append([bondTail,bondHead])
return bondList
def getComponents(svg,allowedColour=["#000000","#ff0000"],convertR=False,convertCe=False):
""" Extract BG components from the svg file
"""
prefix = 'BGT'
convertList = ['Re','re']
if convertR:
convertList.append('R')
convertListCe = []
if convertCe:
convertListCe.append('Ce')
compList = []
compLocation = [];
ReList = []
CeList = []
portList = []
portLocation = [];
junIndex = 0
tree = etree.parse(svg)
root = tree.getroot()
for i,item in enumerate(root[-1]):
tag = item.tag
if isinstance(tag, str):
if '}g' in tag:
## Rotated component
## So extract the translated coordinates
# print("Found g",item.tag)
# print(item.attrib)
transform = item.attrib['transform']
## Extract x,y coords
s = transform.split('(')
s = s[1].split(',')
x_trans = int(s[0])
s = s[1].split(')')
y_trans = int(s[0])
Item = item.getchildren()[0]
tag = Item.tag
else:
Item = item
x_trans = 0
y_trans = 0
if '}text' in tag:
comp = Item.text
colour = Item.attrib["fill"]
isComponent = ( ((":" in comp)
or (comp in ["0","1"] ))
and (colour in allowedColour )
)
isPort = (comp[0] in ['[']) and (comp[-1] in [']'])
if isPort:
portList.append(comp[1:-1])
x = int(Item.attrib['x'])
y = int(Item.attrib['y'])
portLocation.append(complex(x+x_trans,y+y_trans))
if isComponent:
if ":" not in comp:
comp = comp+":"+prefix+str(junIndex)
junIndex += 1
compList.append(comp)
s = comp.split(':')
if s[0] in convertList:
ReList.append(s[1])
if s[0] in convertListCe:
CeList.append(s[1])
x = int(Item.attrib['x'])
y = int(Item.attrib['y'])
compLocation.append(complex(x+x_trans,y+y_trans))
return compList,compLocation,portList,portLocation,ReList,CeList
def makeConnections(bondList,
compList,compLocation,
portList,portLocation,
convertR=False,convertCe=False,quiet=False):
"""Create connections in BondGraphTools format
"""
indent = " "
bondList = np.array(bondList)
compLocation = np.array(compLocation)
twoPortList = ['Re','re']
if convertR:
twoPortList.append('R')
headList = []
tailList = []
tailPort = {}
headPort = {}
compPort = {}
tails = bondList.T[0]
heads = bondList.T[1]
tailhead = np.hstack((tails,heads))
n_bond = len(tails)
for i,port in enumerate(portList):
## Locate nearest bond end to port
distance = np.abs(tailhead-portLocation[i])
nearest = np.argmin(distance)
if nearest<n_bond:
tailPort[nearest] = port
else:
headPort[nearest-n_bond] = port
## Locate nearest component to port
distance = np.abs(compLocation-portLocation[i])
nearest = np.argmin(distance)
if port in compPort.keys():
compPort[port].append(compList[nearest])
else:
compPort[port] = [compList[nearest]]
# print("tailPort:", tailPort)
# print("headPort:", headPort)
for i_bond,bond in enumerate(bondList):
comps = []; types = []; names = []
for tailHead in bond:
distance = np.abs(compLocation-tailHead)
# print('tailHead:',tailHead)
# print('compLocation:',compLocation)
# print('distance:',distance)
nearest = np.argmin(distance)
# print(nearest)
comp = compList[nearest]
s = comp.split(":")
comps.append(comp)
types.append(s[0])
names.append(s[1])
# print(comps)
## Tail
if types[0] in twoPortList:
tail = "("+names[0]+",1)"
else:
if i_bond in tailPort.keys():
tail = "("+names[0]+",'"+tailPort[i_bond]+"')"
else:
tail = names[0]
##Head
if types[1] in twoPortList:
head = "("+names[1]+",0)"
else:
if i_bond in headPort.keys():
head = "("+names[1]+",'"+headPort[i_bond]+"')"
else:
head = names[1]
headList.append(head)
tailList.append(tail)
# print("compPort:",compPort)
return headList,tailList,compPort
def makeBond(headList,tailList):
"""Create bonds in BondGraphTools format
"""
indent = " "
strBond = indent+"## Bonds\n"
bond = "{0}bgt.connect({1},{2})\n"
for i,tail in enumerate(tailList):
strBond += bond.format(indent,tail,headList[i])
return strBond
def makeSubsystem(compType,compName,compPort,rename=True):
""" Create subsystem in BondGraphTools format
"""
indent = " "
print("Creating subsystem:",compType+":"+compName)
subStr = ("\n{0}## Subsystem {1}:{2}\n"
"{0}import {1}_abg\n"
"{0}{2} = {1}_abg.model()\n"
"{0}{2}.name = '{2}'\n"
"{0}model.add({2})\n"
)
compStr = "{0}:{1}"
renameStr = "{0}mbg.renameSub({1},portList={2})\n"
exposeStr = "{0}bgt.expose({1} / '{2}','{2}')\n"
strSub = subStr.format(indent,compType,compName)
ports = []
for port,sysName in compPort.items():
if compStr.format(compType,compName) in sysName:
strSub += exposeStr.format(indent,compName,port)
ports.append(port)
if rename:
strSub += renameStr.format(indent,compName,ports)
#print(strSub)
return strSub
def makeComponents(compList,compPort,convertR=False,convertCe=False,rename=True):
"""Create components in BondGraphTools format
"""
indent = " "
strComp = ""
SeStr = ("\n{0}## Component Se:{1}\n"
"{0}{1} = bgt.new('Se',name='{1}')\n"
"{0}model.add({1})\n"
)
SfStr = ("\n{0}## Component Sf:{1}\n"
"{0}{1} = bgt.new('Sf',name='{1}')\n"
"{0}model.add({1})\n"
)
CStr = ("\n{0}## Component C:{1}\n"
"{0}{1} = sp.symbols('{1}')\n"
"{0}{1} = bgt.new('C',name='{1}',value={{'C':{1}}})\n"
"{0}model.add({1})\n"
)
RStr = ("\n{0}## Component R:{1}\n"
"{0}{1} = sp.symbols('{1}')\n"
"{0}{1} = bgt.new('R',name='{1}',value={{'r':{1}}})\n"
"{0}model.add({1})\n"
)
RStrTwoPort = ("\n{0}## Component R:{1} (Two port version: convertR=True)\n"
"{0}kappa_{1} = sp.symbols('kappa_{1}')\n"
"{0}RT = sp.symbols('RT')\n"
"{0}{1} = bgt.new('Re',name='{1}',value={{'r':kappa_{1},'R':RT,'T':1}},library='BioChem')\n"
"{0}model.add({1})\n"
)
CeStr = ("\n{0}## Component Ce:{1}\n"
"{0}K_{1} = sp.symbols('K_{1}')\n"
"{0}RT = sp.symbols('RT')\n"
"{0}{1} = bgt.new('Ce',name='{1}',value={{'k':K_{1},'R':RT,'T':1}},library='BioChem')\n"
"{0}model.add({1})\n"
)
## If Ce has an argument (eg C:A:2) create additional TF and 0 to give appropriate stoichiometry
CeArgStr = ("\n{0}## Component Ce:{1}\n"
"{0}K_{1} = sp.symbols('K_{1}')\n"
"{0}RT = sp.symbols('RT')\n"
"{0}{1}_Ce = bgt.new('Ce',name='{1}',value={{'k':K_{1},'R':RT,'T':1}},library='BioChem')\n"
"{0}model.add({1}_Ce)\n"
"{0}{1}_TF = bgt.new('TF',value={2},name='{1}_TF')\n"
"{0}model.add({1}_TF)\n"
"{0}{1} = bgt.new('0')\n"
"{0}model.add({1})\n"
"{0}bgt.connect(({1}_TF,0),{1}_Ce)\n"
"{0}bgt.connect({1},({1}_TF,1))\n"
)
ReStr = ("\n{0}## Component Re:{1}\n"
"{0}kappa_{1} = sp.symbols('kappa_{1}')\n"
"{0}RT = sp.symbols('RT')\n"
"{0}{1} = bgt.new('Re',name='{1}',value={{'r':kappa_{1},'R':RT,'T':1}},library='BioChem')\n"
"{0}model.add({1})\n"
)
junStr = ("\n{0}## Junction {1}:{2}\n"
"{0}{2} = bgt.new('{1}')\n"
"{0}model.add({2})\n"
)
compNames = []
for comp in compList:
s = comp.split(":")
compType = s[0]
compName = s[1]
if len(s)>2:
compArg = s[2]
else:
compArg = None
#print(comp,compArg)
compNames.append(compName)
if compType in ["C"]:
strComp = strComp+CStr.format(indent,compName)
elif (compType in ["R"]):
if convertR:
strComp = strComp+RStrTwoPort.format(indent,compName)
else:
strComp = strComp+RStr.format(indent,compName)
elif compType in ["Ce"]:
if compArg is None:
strComp = strComp+CeStr.format(indent,compName)
else:
strComp = strComp+CeArgStr.format(indent,compName,compArg)
elif compType in ["Re"]:
strComp = strComp+ReStr.format(indent,compName)
elif compType in ["0","1"]:
strComp = strComp+junStr.format(indent,compType,compName)
elif compType in ["Se"]:
strComp = strComp+SeStr.format(indent,compName)
elif compType in ["Sf"]:
strComp = strComp+SfStr.format(indent,compName)
else:
#print("UNKNOWN:",compType+":"+compName)
strComp += makeSubsystem(compType,compName,compPort,rename=rename)
# strComp = (strComp+"\n"+indent+"## Component list\n"
# +indent+"components = (\n"
# )
# for compName in compNames:
# strComp = strComp+" "+compName+",\n"
# strComp = (strComp[:-2]+indent+"\n"+indent+")\n\n"
# +indent+"bgt.add(model, *components)\n"
#)
return strComp
def convertRe(ReList,headList,tailList,quiet=False):
""" Convert one-port Re to two-port
"""
compList = [] # Extra junctions
for re in ReList:
port0 = "({0},0)".format(re)
port1 = "({0},1)".format(re)
if port1 not in tailList:
if not quiet:
print("Converting one-port "+re, "to two-port")
## Find junction at tail of bond
iRe = headList.index(port0)
jun = tailList[iRe]
## New reverse junction
junR = jun+"r"
compList.append("1:"+junR)
## Connect the tails of bonds to new junction
for i,tail in enumerate(tailList):
if (tail in [jun]) and (headList[i] not in [port0]):
#print(" Swap", jun, "for", junR, "("+headList[i]+")")
tailList[i] = junR
## Connect the Re to the new junction
tailList.append(port1)
headList.append(junR)
return headList,tailList,compList
def ConvertCe(CeList,headList,tailList,quiet=False):
""" Convert Ce to zero junction and Ce
"""
compList = [] # Extra junctions
for Ce in CeList:
if not quiet:
print("Appending zero junction to Ce:"+Ce)
junCe = Ce+"z"
compList.append("0:"+junCe)
if Ce in headList:
iCe = indices(headList,Ce)
#print('iCe:',iCe)
for i in iCe:
headList[i] = junCe
headList.append(Ce)
tailList.append(junCe)
if Ce in tailList:
iCe = indices(tailList,Ce)
#print('iCe:',iCe)
for i in iCe:
tailList[i] = junCe
tailList.append(Ce)
headList.append(junCe)
return headList,tailList,compList
def model(svg,convertR=False,convertCe=False,quiet=False,rename=True):
""" Converts the SVG graphical BG to the BondGraphTools computational BG
"""
indent = " "
## File handling
s = svg.split('_abg')
name = s[0]
filename = name+"_abg.py"
f = open(filename,'w')
header = ("import BondGraphTools as bgt\n"
"import modularBondGraph as mbg\n"
"import sympy as sp\n\n"
"def model():\n"
"{0}{3} Acausal bond graph {1}_abg.py\n"
"{0}Created by svgBondGraph at {2} from {1}_abg.svg\n\n"
"{0}Usage:\n"
"{0}import {1}_abg; model = {1}_abg.model()\n"
"{0}{3}\n\n"
'{0}model = bgt.new(name="{1}")\n'
)
## get Bonds and the location of head and tail
bondList = getBonds(svg)
## Get components and their location
compList,compLocation,portList,portLocation,ReList,CeList = getComponents(svg,convertR=convertR,convertCe=convertCe)
# ## Create the components - return as string
# strComp = makeComponents(compList,convertR=convertR)
## Create the bond connections
if len(bondList)>0:
headList,tailList,compPort = makeConnections(bondList,
compList,compLocation,
portList,portLocation,
convertR=convertR,convertCe=convertCe)
else:
headList=[]
tailList=[]
compPort={}
## Convert one port Re to two port
headList,tailList,compListNew = convertRe(ReList,headList,tailList,quiet=quiet)
compList.extend(compListNew)
## Convert one port Ce to zero + Ce
headList,tailList,compListNew = ConvertCe(CeList,headList,tailList,quiet=quiet)
compList.extend(compListNew)
## Make bond connection str
strBond = makeBond(headList,tailList)
# print(compList)
# print(sorted(compList))
## Create the components - return as string
strComp = makeComponents(sorted(compList),compPort,convertR=convertR,convertCe=convertCe)
## Write out the _abg.py file
## Header
f.write(header.format(indent,name,datetime.datetime.now().ctime(),'"""'))
## Body
f.write(strComp+"\n"+strBond+"\n")
## End
f.write(indent+"return model\n")
f.close