forked from ckuhlmann/lt2circuitikz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lt2ti.py
2593 lines (2030 loc) · 95.5 KB
/
lt2ti.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import uuid;
import re;
import math;
import copy;
import os;
import configparser;
class lt2circuiTikz:
lastASCfile = None;
reIsHdr = re.compile(r'[\s]*Version 4[\s]+', flags=re.IGNORECASE);
reIsSym = re.compile(r'[\s]*SymbolType[\s]+(.*)$', flags=re.IGNORECASE);# ASY file symbol type definition do NOT confuse with reIsComponent: an instance of a symbol
reIsSheet = re.compile(r'^[\s]*SHEET[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)', flags=re.IGNORECASE);
# SHEET no wx1 wy1
reIsWire = re.compile(r'^[\s]*WIRE[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)', flags=re.IGNORECASE);
# WIRE x1 y1 x2 y2
reIsNetLabel = re.compile(r'^[\s]*FLAG[\s]+([-\d]+)[\s]+([-\d]+)[\s]+(.*)', flags=re.IGNORECASE);
# FLAG x1 y1 label
reIsComponent = re.compile(r'^[\s]*SYMBOL[\s]+([\S]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([R|M])([-\d]+)', flags=re.IGNORECASE);
# SYMBOL path\\type x1 x2 [R|M] rotation
reIsCAttrName = re.compile(r'^[\s]*SYMATTR[\s]+InstName[\s]+(.*)', flags=re.IGNORECASE);
# SYMATTR InstName name
reIsCAttrValue = re.compile(r'^[\s]*SYMATTR[\s]+Value[\s]+(.*)', flags=re.IGNORECASE);
# SYMATTR Value value
reIsCAttrValue2 = re.compile(r'^[\s]*SYMATTR[\s]+Value2[\s]+(.*)', flags=re.IGNORECASE);
# SYMATTR Value2 value
reIsCAttrGeneric = re.compile(r'^[\s]*SYMATTR[\s]+([\S]+)[\s]+(.*)', flags=re.IGNORECASE);
# SYMATTR attr.name value
reIsWindow = re.compile(r'^[\s]*WINDOW[\s]+([-\d]+)[\s]+([-\d]+)[\s]([-\d]+)[\s]+([\S]+)[\s]+([-\d]+)', flags=re.IGNORECASE);
# WINDOW attr.No.Id rel.x1 rel y1 pos.str. size?=2
reIsText = re.compile(r'^[\s]*TEXT[\s]+([-\d]+)[\s]+([-\d]+)[\s]([\S]+)[\s]+([-\d]+)[\s]+[;!](.*)', flags=re.IGNORECASE);
# TEXT x1 y1 pos.str. size?=2 string
reIsLine = re.compile(r'^[\s]*LINE[\s]+([\S]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]*([-\d]*)', flags=re.IGNORECASE);
# Line type x1 y1 x2 y2 stype
reIsRect = re.compile(r'^[\s]*RECTANGLE[\s]+([\S]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]*([-\d]*)', flags=re.IGNORECASE);
# Rect type x1 y1 x2 y2 stype
reIsCircle = re.compile(r'^[\s]*CIRCLE[\s]+([\S]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]*([-\d]*)', flags=re.IGNORECASE);
# Circle/Oval type x1 y1 x2 y2 stype
# symbols:
reIsPin = re.compile(r'^[\s]*PIN[\s]+([-\d]+)[\s]+([-\d]+)[\s]([\S]+)[\s]+([-\d]+)', flags=re.IGNORECASE);
# PIN x1 y1 pos.str. offset
reIsPinName = re.compile(r'^[\s]*PINATTR[\s]+PinName[\s]+(.*)', flags=re.IGNORECASE);
# PIN PinName pin label
reIsPinOrder = re.compile(r'^[\s]*PINATTR[\s]+SpiceOrder[\s]+([-\d]+)', flags=re.IGNORECASE);
# PIN PinName pin order
reIsSAttrValue = re.compile(r'^[\s]*SYMATTR[\s]+Value[\s]+(.*)', flags=re.IGNORECASE);
# SYMATTR Value value
reIsSAttrPrefix = re.compile(r'^[\s]*SYMATTR[\s]+Prefix[\s]+(.*)', flags=re.IGNORECASE);
# SYMATTR Prefix value
reIsSAttrDescr = re.compile(r'^[\s]*SYMATTR[\s]+Description[\s]+(.*)', flags=re.IGNORECASE);
# SYMATTR Description value
reIsSAttrGeneric = re.compile(r'^[\s]*SYMATTR[\s]+([\S]+)[\s]+(.*)', flags=re.IGNORECASE);
# SYMATTR kind value
attrid2attr = {0:'InstName',3:'Value',123:'Value2',39:'SpiceLine',40:'SpiceLine2',38:'SpiceModel'};
attr2attrid = {'InstName':0,'Value':3, 'Value2':123, 'SpiceLine':39, 'SpiceLine2':40,'SpiceModel':38};
lastComponent = None;
lastWire = None;
lastLabel = None;
lastText = None;
lastPin =None;
lastSymbol =None;
lastAttributesDict = {};
lastLine = '';
lastSymLine = '';
linecnt = 0;
symlinecnt = 0;
translinecnt = 0;
config = None;
def __init__(self):
self.circDict = CircuitDict();
self.symbolDict = SymbolDict();
self.validInputFile = False;
#self.lt2tscale = 1.0/32.0;
#self.lt2tscale = (1.0/64.0);
self.lt2tscale = (1.0/48.0);
self.includepreamble = True;
self.lastASCfile = None;
try:
approot2 = (os.path.dirname(os.path.realpath(__file__)));
approot = os.path.dirname(os.path.abspath(__file__))
self.scriptmode = 'script'
except NameError: # We are the main py2exe script, not a module
import sys
approot = os.path.dirname(os.path.abspath(sys.argv[0]))
self.scriptmode = 'py2exe'
self.scriptdir = (approot);
self.symfilebasepath = 'sym'+os.sep;
configfileloc = self.scriptdir+os.sep+'lt2ti.ini'
print('lt2ti: Loading config at "'+configfileloc+'"')
self.config = configparser.RawConfigParser()
self.config.read(configfileloc)
if (self.config.has_option('general', 'symdir')):
self.symfilebasepath = self.config.get('general', 'symdir') + os.sep;
print('lt2ti: initial sym basepath="'+self.symfilebasepath+'"')
self.config = configparser.RawConfigParser()
conffiles = self.config.read([self.scriptdir+os.sep+'lt2ti.ini', self.scriptdir+os.sep+ self.symfilebasepath + 'sym.ini'])
#print('lt2ti: config sym basepath="' + self.config.get('general', 'symdir') + os.sep + '"')
self.defaultgnd = r'circuiTikz\\gnd'
if (self.config.has_option('general', 'lt2tscale')):
self.lt2tscale = float(self.config.get('general', 'lt2tscale'));
if (self.config.has_option('general', 'lt2tscale_inverse')):
self.lt2tscale = 1.0/float(self.config.get('general', 'lt2tscale_inverse'));
if (self.config.has_option('general', 'default_gnd')):
self.defaultgnd = (self.config.get('general', 'default_gnd'));
if (self.config.has_option('general', 'includepreamble')):
includepreamble = self.config.get('general', 'includepreamble');
self.includepreamble = ((str(includepreamble).lower() == 'true') or ((includepreamble) == '1'))
print('lt2ti ready for conversion.')
def _symresetSymbol(self):
if (self.lastPin != None):
if (self.lastSymbol != None):
self.lastSymbol.addPin(self.lastPin);
self.lastPin = None;
if (self.lastSymbol != None):
self.symbolDict.addSymbol(self.lastSymbol);
self.lastSymbol = None;
def symresetPin(self):
if (self.lastPin != None):
if (self.lastSymbol != None):
self.lastSymbol.addPin(self.lastPin);
self.lastPin = None;
return;
def translate2ospath(self,aPath):
tPath = aPath.replace("\\",os.sep) # localize to OS path, since LTSpice under Wine/Windows always uses \
return tPath
def readASYFile(self, relfileandpath):
relfileandpath_orig = relfileandpath
relfileandpath = self.translate2ospath(relfileandpath_orig) # localize to OS path, since LTSpice under Wine/Windows always uses \
print('Loading Symbol file "'+relfileandpath+'" (orig="'+relfileandpath_orig+'")...')
# read symbol file
self.symlinecnt = 0;
aSymbol = None;
try :
fhy = open(self.scriptdir+os.sep+ relfileandpath, mode='r', newline=None);
except Exception as e:
print('could not open ASY file "'+relfileandpath+'" (cwd="'+os.curdir+'", scriptdir="'+self.scriptdir+'", mode='+self.scriptmode+', fullpath="'+self.scriptdir+os.sep+ relfileandpath+'")');
return None;
for line in fhy:
self.symlinecnt = self.symlinecnt + 1;
self.lastSymLine = line;
m = self.reIsHdr.match(line);
if (m != None):
print('valid file header found:'+line);
self.validInputFile = True;
continue;
m = self.reIsSym.match(line);
if (m != None):
print('symbol of type '+m.group(1)+': '+line);
self._handleSType(m);
continue;
m = self.reIsSAttrPrefix.match(line);
if (m != None):
self._handleSymPrefix(m);
continue;
m = self.reIsSAttrDescr.match(line);
if (m != None):
self._handleSymDescr(m);
continue;
m = self.reIsSAttrValue.match(line);
if (m != None):
self._handleSymValue(m);
continue;
m = self.reIsSAttrGeneric.match(line);
if (m != None):
self._handleSymAttrGeneric(m);
continue;
m = self.reIsPin.match(line);
if (m != None):
self._handleSymPin(m);
continue;
m = self.reIsPinName.match(line);
if (m != None):
self._handleSymPinName(m);
continue;
m = self.reIsPinOrder.match(line);
if (m != None):
self._handlePinOrder(m);
continue;
print("could not match symbol line '"+line.replace('\n','')+"'");
aSymbol = self.lastSymbol;
self._symresetSymbol(); # handle last item
fhy.close();
return aSymbol;
def readASY2TexFile(self, relfileandpath, symbol):
relfileandpath_orig = relfileandpath
relfileandpath = self.translate2ospath(relfileandpath_orig)
asy2texfileandpath = self.scriptdir+os.sep+ relfileandpath
try :
fht = open(asy2texfileandpath, mode='r', newline=None);
except Exception as e:
print('Could not open requested asy2tex tile: "'+relfileandpath+'" (orig="'+relfileandpath_orig+'", cwd="'+os.curdir+'")');
return None;
print('Processing asy2tex file: "'+relfileandpath+'" (orig="'+relfileandpath_orig+'", cwd="'+os.curdir+'")');
rAliasFile = re.compile(r'ALIASFOR (.*\.asy2tex)[\s]*$', flags=re.IGNORECASE);
rType = re.compile(r'^[\s]*Type[\s]+([\S]+)', flags=re.IGNORECASE); # compile(r'^[\s]*SYMATTR[\s]+([\S]+)[\s]+(.*)', flags=re.IGNORECASE);
rOriginTex = re.compile(r'^[\s]*TexOrigin[\s]+([-\d\.]+)[\s]+([-\d\.]+)[\s]+([-\d]+)[\s]+([01TRUEtrueFALSEfalse]+)', flags=re.IGNORECASE);
rOriginSym = re.compile(r'^[\s]*SymOrigin[\s]+([-\d\.]+)[\s]+([-\d\.]+)[\s]+([-\d]+)[\s]+([01TRUEtrueFALSEfalse]+)', flags=re.IGNORECASE);
# x1 y1 rot mirror
rPinList_be = re.compile(r'^[\s]*(BeginPinList)[\s]*$', flags=re.IGNORECASE);
rPinListEntry = re.compile(r'^[\s]*([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+([-\d]+)[\s]+(.*)$', flags=re.IGNORECASE);
# ord x1 y1 rot length PinName
rPinList_en = re.compile(r'^[\s]*(EndPinList)[\s]*$', flags=re.IGNORECASE);
rConKV_be = re.compile(r'^[\s]*(BeginConversionKeyvals)[\s]*$', flags=re.IGNORECASE); #BeginConversionKeyvals
rConKV_en = re.compile(r'^[\s]*(EndConversionKeyvals)[\s]*$', flags=re.IGNORECASE); #EndConversionKeyvals
rConvKVList = re.compile(r'([^=]+)=(.*)$', flags=re.IGNORECASE);
rTexName = re.compile(r'^[\s]*TexElementName[\s]+(.*)$', flags=re.IGNORECASE);
rTex_be = re.compile(r'^[\s]*(BeginTex)[\s]*$', flags=re.IGNORECASE);
rTex_en = re.compile(r'^[\s]*(EndTex)[\s]*$', flags=re.IGNORECASE);
ispinlist = False;
istexlist = False;
isconvkv = False;
texlist = [];
aTSymbol = copy.deepcopy(symbol);
self.translinecnt = 0;
for line in fht:
self.translinecnt = self.translinecnt+1;
m = rAliasFile.match(line);
if ((m != None) and (self.translinecnt < 2)): # must be at the beginning
fht.close();
pathtofile = os.path.dirname(asy2texfileandpath);
aliasfile = m.group(1);
aliasfileandpath = pathtofile+os.sep+aliasfile;
relaliasfileandpath = os.path.relpath(aliasfileandpath, self.scriptdir+os.sep);
print('Found an alias entry: "'+aliasfile+'" which resolved to "'+aliasfileandpath+'" and "'+relaliasfileandpath+'" ');
aTSymbol = self.readASY2TexFile(relaliasfileandpath, symbol);
return aTSymbol;
m = rPinList_be.match(line);
if (m != None):
ispinlist = True;
continue;
m = rPinList_en.match(line);
if (m != None):
ispinlist = False;
continue;
if (ispinlist):
m = rPinListEntry.match(line);
if (m != None):
# add pinlist entry
# Pinlist entry: ord x1 y1 rot length PinName
lxPin = SymPin();
lxPin.order = m.group(1);
lxPin.x1 = m.group(2);
lxPin.y1 = m.group(3);
lxPin.rot = m.group(4);
lxPin.length = m.group(5);
lxPin.name = m.group(6);
aTSymbol.latexPins.addPin(lxPin);
continue;
m = rConKV_be.match(line);
if (m != None):
ispinlist = False;
istexlist = False;
isconvkv = True;
continue;
m = rConKV_en.match(line);
if (m != None):
ispinlist = False;
istexlist = False;
isconvkv = False;
continue;
if (isconvkv):
m = rConvKVList.match(line);
if (m != None):
aTSymbol.conversionKV[m.group(1)] = m.group(2);
continue;
m = rTex_be.match(line);
if (m != None):
ispinlist = False;
istexlist = True;
isconvkv = False;
continue;
m = rTex_en.match(line);
if (m != None):
ispinlist = False;
istexlist = False;
isconvkv = False;
continue;
if (istexlist):
texlist.append(line);
continue;
m = rTexName.match(line);
if (m != None):
aTSymbol.latexElementName = m.group(1);
continue;
m = rType.match(line);
if (m != None):
aTSymbol.latexType = m.group(1);
continue;
m = rOriginTex.match(line);
if (m != None):
aTSymbol.latexOriginX1 = float(m.group(1));
aTSymbol.latexOriginY1 = float(m.group(2));
aTSymbol.latexOriginRot = int(m.group(3));
aTSymbol.latexOriginMirror = ((m.group(4) == '1') or (str.lower(m.group(4)) == 'true'));
continue;
m = rOriginSym.match(line);
if (m != None):
aTSymbol.symbolOriginX1 = float(m.group(1));
aTSymbol.symbolOriginY1 = float(m.group(2));
aTSymbol.symbolOriginRot = int(m.group(3));
aTSymbol.symbolOriginMirror = ((m.group(4) == '1') or (str.lower(m.group(4)) == 'true'));
continue;
print("coult not match line "+str(self.translinecnt)+" in asy2tex file '"+relfileandpath+"' :"+line);
aTSymbol.latexTemplate = texlist;
fht.close();
return aTSymbol;
def _handleSType(self, m):
self._symresetSymbol(); # no more attributes for previous lines
self.lastSymbol = Symbol(m.group(1))
self.lastSymbol.lt2tscale = self.lt2tscale;
return;
def _handleSymPrefix(self, m):
self.lastSymbol.prefix = m.group(1);
self.lastSymbol.attributes['Prefix'] = m.group(1);
return;
def _handleSymDescr(self, m):
self.lastSymbol.description = m.group(1);
self.lastSymbol.attributes['Description'] = m.group(1);
return;
def _handleSymValue(self, m):
self.lastSymbol.value = m.group(1);
self.lastSymbol.attributes['Value'] = m.group(1);
return;
def _handleSymAttrGeneric(self, m):
self.lastSymbol.attributes[m.group(1)] = m.group(2);
return;
def _handleSymPin(self, m):
self.symresetPin();
self.lastPin = SymPin();
self.lastPin.x1 = int(m.group(1));
self.lastPin.y1 = int(m.group(2));
self.lastPin.labelpos = (m.group(3));
self.lastPin.labeloffset = int(m.group(4));
return;
def _handleSymPinName(self, m):
self.lastPin.name = m.group(1);
def _handlePinOrder(self, m):
self.lastPin.order = int(m.group(1));
def _resetLast(self):
if (len(self.lastAttributesDict) > 0):
for aid, attr in self.lastAttributesDict.items():
self.lastComponent.addAttribute(attr);
#print("Adding component attrib kind="+str(attr.kind)+" val="+str(attr.value)+" to list, len="+str(len(self.lastComponent.attrlist)))
self.lastAttributesDict = {};
if (self.lastComponent != None):
self.circDict.addComponent(self.lastComponent);
self.lastComponent = None;
if (self.lastWire != None):
self.circDict.addWire(self.lastWire);
self.lastWire = None;
if (self.lastLabel != None):
self.circDict.addNetLabel(self.lastLabel);
self.lastLabel = None;
if (self.lastText != None):
self.circDict.addText(self.lastText);
self.lastText = None;
def readASCFile(self, fileandpath):
print('Reading ASC file "'+fileandpath+'"...')
self.lastComponent = None;
self.lastSymbol = None;
self.lastAttributesDict = {};
self.lastLabel = None;
self.lastWire = None
self.lastPin = None;
self.circDict = CircuitDict();
self.symbolDict = SymbolDict();
self.lastText = None
self.lastASCfile = fileandpath;
self.linecnt = 0;
try :
fhs = open(fileandpath, mode='r', newline=None, encoding='iso-8859-1');
except Exception as e:
print('could not open ASC file "'+fileandpath+'" (cwd="'+os.curdir+'")');
return None;
for line in fhs:
self.linecnt = self.linecnt + 1;
self.lastLine = line;
m = self.reIsHdr.match(line);
if (m != None):
print('valid file header found:'+line);
self.validInputFile = True;
continue;
m = self.reIsSheet.match(line);
if (m != None):
print('sheet: '+line);
continue;
m = self.reIsNetLabel.match(line);
if (m != None):
self._handleNetLabel(m);
continue;
m = self.reIsComponent.match(line);
if (m != None):
self._handleComponent(m);
continue;
m = self.reIsCAttrName.match(line);
if (m != None):
self._handleComponentName(m);
continue;
m = self.reIsCAttrValue.match(line);
if (m != None):
self._handleComponentValue(m);
continue;
m = self.reIsCAttrValue2.match(line);
if (m != None):
self._handleComponentValue2(m);
continue;
m = self.reIsCAttrGeneric.match(line);
if (m != None):
self._handleAttributeGeneric(m);
continue;
m = self.reIsWire.match(line);
if (m != None):
self._handleWire(m);
continue;
m = self.reIsWindow.match(line);
if (m != None):
self._handleWindow(m);
continue;
m = self.reIsText.match(line);
if (m != None):
self._handleText(m);
continue;
m = self.reIsLine.match(line);
if (m != None):
self._handleLine(m);
continue;
m = self.reIsRect.match(line);
if (m != None):
self._handleRect(m);
continue;
m = self.reIsCircle.match(line);
if (m != None):
self._handleCircle(m);
continue;
print("could not match line '"+line.replace('\n','')+"'");
self._resetLast(); # handle last item
fhs.close();
return self.circDict;
def _handleNetLabel(self, m):
self._resetLast(); # no more attributes for previous lines
# FLAG <x1> <y1> <label>
if (m.group(3) == '0'): # more a ground symbol than a net label
gndcomp = self.defaultgnd;
c = Component(gndcomp, int(m.group(1)), int(m.group(2)), 0, False, 'GND'+str(self.linecnt), '')
self._handleComponent_worker(c);
else:
lbl = NetLabel(m.group(3), int(m.group(1)), int(m.group(2)));
lbl.value = 'lbl'+str(self.linecnt)
pathandctype = 'netlabel';
if not self.symbolDict.hasSymbolPath(pathandctype):
# not cached, try to load
fullpath = self.symfilebasepath + pathandctype.replace('\\\\','\\');
sym = self.readASYFile(fullpath+'.asy');
sym.path = '';
sym.ctype = pathandctype;
sym.pathandctype = pathandctype;
tsym = self.readASY2TexFile(fullpath+'.asy2tex',sym);
if (tsym != None):
self.symbolDict.addSymbol(tsym); # add symbol and translation information
else:
# already existing in cache
tsym = self.symbolDict.getSymbolByPath(pathandctype);
lbl.symbol = tsym;
self.lastLabel = lbl;
return;
def _handleComponent(self, m):
self._resetLast(); # no more attributes for previous lines
# SYMBOL path\\type x1 x2 [R|M] rotation
# Component ( ctype, x1, y1, rot, mirror, name, value)
c = Component(m.group(1), int(m.group(2)), int(m.group(3)), int(m.group(5)), (str.upper(m.group(4)) == 'M'), '', "");
self._handleComponent_worker(c);
def _handleComponent_worker(self, c):
if not self.symbolDict.hasSymbolPath(c.pathandctype):
# not cached, try to load
fullpath = self.symfilebasepath + c.pathandctype.replace('\\\\','\\');
sym = self.readASYFile(fullpath+'.asy');
sym.path = c.path;
sym.ctype = c.ctype;
sym.pathandctype = c.pathandctype;
tsym = self.readASY2TexFile(fullpath+'.asy2tex',sym);
if (tsym != None):
self.symbolDict.addSymbol(tsym); # add symbol and translation information
else:
# already existing in cache
tsym = self.symbolDict.getSymbolByPath(c.pathandctype);
c.symbol = tsym;
self.lastComponent = c;
print('Found component: \n'+c.asString(' '));
return;
def _handleComponentName(self, m):
# SYMATTR InstName <name>
self.lastComponent.name = m.group(1);
attrkind = 'InstName';
attrval = m.group(1);
if (not attrkind in self.lastAttributesDict):
attr = Attribute(attrkind, attrval);
else:
attr = self.lastAttributesDict[attrkind];
attr.value = attrval;
if (attrval != "*"):
attr.visible = True;
self.lastAttributesDict[attr.kind] = attr;
return;
def _handleComponentValue(self, m):
# SYMATTR Value <value>
attrkind = 'Value';
attrval = m.group(1);
if (attrval == '""'): # this is the way LTspice indicates an empty value
attrval = '';
self.lastComponent.value = attrval;
if (not attrkind in self.lastAttributesDict):
attr = Attribute(attrkind, attrval);
else:
attr = self.lastAttributesDict[attrkind];
attr.value = attrval;
if (attrval != "*"):
attr.visible = True;
self.lastAttributesDict[attr.kind] = attr;
return;
def _handleComponentValue2(self, m):
#SYMATTR Value2 <value>
self.lastComponent.value2 = m.group(1);
attrkind = 'Value2';
attrval = m.group(1);
if (not attrkind in self.lastAttributesDict):
attr = Attribute(attrkind, attrval);
else:
attr = self.lastAttributesDict[attrkind];
attr.value = attrval;
if (attrval != "*"):
attr.visible = True;
self.lastAttributesDict[attr.kind] = attr;
return;
def _handleAttributeGeneric(self, m):
#SYMATTR <attrib.name> <value>
attrkind = m.group(1);
attrval = m.group(2);
if (not attrkind in self.lastAttributesDict):
attr = Attribute(attrkind, attrval);
self.lastAttributesDict[attr.kind] = attr;
#print("Added AttributeGeneric kind="+str(attr.kind)+" val="+str(attrval))
else:
attr = self.lastAttributesDict[attrkind];
attr.value = attrval;
self.lastAttributesDict[attr.kind] = attr;
#print("Updated AttributeGeneric kind="+str(attr.kind)+" val="+str(attrval))
return;
def _handleWire(self, m):
self._resetLast(); # no more attributes for previous lines
# WIRE <x1> <y1> <x2> <y2>
self.lastWire = Wire("w"+str(self.linecnt),int(m.group(1)),int(m.group(2)), int(m.group(3)), int(m.group(4)))
return;
def _handleWindow(self, m): # attribute display position
# WINDOW attr.No.Id rel.x1 rel y1 pos.str. size?=2
attrid = int(m.group(1));
if (attrid in self.attrid2attr):
attrkind = self.attrid2attr[attrid];
else:
print("Could not match attr.id="+m.group(1)+" to an attribute.")
return;
if (attrkind in self.lastAttributesDict):
# attribute exists: modify its values
attr = self.lastAttributesDict[attrkind];
else: # create new
attr = Attribute(attrkind, 'undefined');
attr.visible = True;
attr.idnum = m.group(1);
attr.x1rel = int(m.group(2));
attr.y1rel = int(m.group(3));
attr.align = m.group(4);
attr.size = float(m.group(5));
self.lastAttributesDict[attrkind] = attr;
return;
def _handleText(self, m): # attribute display position
self._resetLast(); # no more attributes for previous lines
# TEXT x1 y1 pos.str. size?=2 string
txt = SchText(m.group(5), int(m.group(1)), int(m.group(2)))
txt.align = m.group(3);
txt.size = float(m.group(4));
txt.value = 'lbl'+str(self.linecnt)
pathandctype = 'text';
if not self.symbolDict.hasSymbolPath(pathandctype):
# not cached, try to load
fullpath = self.symfilebasepath + pathandctype.replace('\\\\','\\');
sym = self.readASYFile(fullpath+'.asy');
sym.path = '';
sym.ctype = pathandctype;
sym.pathandctype = pathandctype;
tsym = self.readASY2TexFile(fullpath+'.asy2tex',sym);
if (tsym != None):
self.symbolDict.addSymbol(tsym); # add symbol and translation information
else:
# already existing in cache
tsym = self.symbolDict.getSymbolByPath(pathandctype);
txt.symbol = tsym;
self.lastText = txt;
return;
def _handleLine(self, m):
if ((m.group(6)) != ''):
lstyle = int(m.group(6));
else:
lstyle = 0;
schline = SchLine(int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5)), lstyle)
schline.kind = (m.group(1));
pathandctype = 'SchLine';
if not self.symbolDict.hasSymbolPath(pathandctype):
# not cached, try to load
fullpath = self.symfilebasepath + pathandctype.replace('\\\\','\\');
#sym = self.readASYFile(fullpath+'.asy');
sym = Symbol(pathandctype);
sym.lt2tscale = self.lt2tscale;
sym.path = '';
sym.ctype = pathandctype;
sym.pathandctype = pathandctype;
tsym = self.readASY2TexFile(fullpath+'.asy2tex',sym);
if (tsym != None):
self.symbolDict.addSymbol(tsym); # add symbol and translation information
else:
# already existing in cache
tsym = self.symbolDict.getSymbolByPath(pathandctype);
schline.symbol = tsym;
self.circDict.addSchLine(schline);
return;
def _handleRect(self, m):
if ((m.group(6)) != ''):
lstyle = int(m.group(6));
else:
lstyle = 0;
schrect = SchRect(int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5)), lstyle)
schrect.kind = (m.group(1));
pathandctype = 'SchRect';
if not self.symbolDict.hasSymbolPath(pathandctype):
# not cached, try to load
fullpath = self.symfilebasepath + pathandctype.replace('\\\\','\\');
#sym = self.readASYFile(fullpath+'.asy');
sym = Symbol(pathandctype);
sym.lt2tscale = self.lt2tscale;
sym.path = '';
sym.ctype = pathandctype;
sym.pathandctype = pathandctype;
tsym = self.readASY2TexFile(fullpath+'.asy2tex',sym);
if (tsym != None):
self.symbolDict.addSymbol(tsym); # add symbol and translation information
else:
# already existing in cache
tsym = self.symbolDict.getSymbolByPath(pathandctype);
schrect.symbol = tsym;
self.circDict.addSchLine(schrect);
return;
def _handleCircle(self, m):
if ((m.group(6)) != ''):
lstyle = int(m.group(6));
else:
lstyle = 0;
schcirc = SchCirc(int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5)), lstyle)
schcirc.kind = (m.group(1));
pathandctype = 'SchCirc';
if not self.symbolDict.hasSymbolPath(pathandctype):
# not cached, try to load
fullpath = self.symfilebasepath + pathandctype.replace('\\\\','\\');
#sym = self.readASYFile(fullpath+'.asy');
sym = Symbol(pathandctype);
sym.lt2tscale = self.lt2tscale;
sym.path = '';
sym.ctype = pathandctype;
sym.pathandctype = pathandctype;
tsym = self.readASY2TexFile(fullpath+'.asy2tex',sym);
if (tsym != None):
self.symbolDict.addSymbol(tsym); # add symbol and translation information
else:
# already existing in cache
tsym = self.symbolDict.getSymbolByPath(pathandctype);
schcirc.symbol = tsym;
self.circDict.addSchLine(schcirc);
return;
def copyFileContents(self,source,destination):
fhs = open(source, mode='r', newline='');
fhd = open(destination, mode='a', newline=''); # prevent automatic newline conversion to have more control over nl chars.
for line in fhs:
#print('copying line "'+line+'" from source to destination');
fhd.write(line);
fhd.close();
fhs.close();
def copyFile(self,source,destination):
fhs = open(source, mode='r', newline='');
fhd = open(destination, mode='w', newline=''); # prevent automatic newline conversion to have more control over nl chars.
for line in fhs:
#print('copying line "'+line+'" from source to destination');
fhd.write(line);
fhd.close();
fhs.close();
def copyFileContentsToHandle(self,source,hdestination):
fhs = open(source, mode='r', newline=None);
for line in fhs:
#print('copying line "'+line+'" from source to destination');
hdestination.write(line);
fhs.close();
def writeCircuiTikz(self, outfile):
print('Writing Tex commands to "'+outfile+'"...')
xscale = 1 * self.lt2tscale;
yscale = -1 * self.lt2tscale; # y is inverse for LTspice files
xoffset = 0;
yoffset = 0;
fhd = open(outfile, mode='w', newline='\r\n'); # prevent automatic newline conversion to have more control over nl chars.
if (self.includepreamble):
self.copyFileContentsToHandle(self.scriptdir+os.sep+ self.symfilebasepath+'latex_preamble.tex', fhd);
if (self.config.has_option('general','latexincludes')):
incfiles = self.config.get('general','latexincludes');
incfiles = incfiles.split(';');
for incfile in incfiles:
srcfile = self.scriptdir+os.sep+ self.symfilebasepath + incfile;
dstfile = os.path.dirname(os.path.abspath(outfile)) +os.sep + os.path.basename(incfile);
self.copyFile(srcfile, dstfile)
print(' copying latexincludes: "'+srcfile+'" to "'+dstfile+'" ...')
if (self.config.has_option('general','bipoles_length')):
bipoles_length = self.config.get('general','bipoles_length');
fhd.write(r'\ctikzset{bipoles/length='+bipoles_length+'}\n');
self.circDict.wiresToPolyWires();
#output wires:
wireDict = self.circDict.getWiresByCoord();
for pp, dictWires in wireDict.items():
# all wires at the pp position
#jcnt = self.circDict.getJunctionCound(pp);
jcnt = self.circDict.getJunctionCount(pp);
if (jcnt <= 2): # no junction
p1junction = '';
else: # junction
p1junction = '*';
for uuid, wire in dictWires.items():
pp1 = wire.getP1Tuple();
if (pp1 == pp): # only draw wire if pos1 is attached. Otherwise wires will get drawn multiple times.
pp2 = wire.getP2Tuple();
jcnt2 = self.circDict.getJunctionCount(pp2);
if (jcnt2 <= 2):
p2junction = '';
else:
p2junction = '*';
x1 = pp[0]*xscale+xoffset;
y1 = pp[1]*yscale+yoffset;
x2 = pp2[0]*xscale+xoffset;
y2 = pp2[1]*yscale+yoffset;
lenxn = 0;
if ((type(wire) is PolyWire)):
lenxn = len(wire.xn);
if ( ((type(wire) is Wire) and not (type(wire) is PolyWire)) or ( (type(wire) is PolyWire) and ( len(wire.xn) <= 0) )): # normal wire or polywire with no intermediate segments
# \draw (8,2)to[*short,*-] (8,4);%
fhd.write(r'\draw [/lt2ti/Net]('+str(x1)+r','+str(y1)+r')to[*short,'+p1junction+'-'+p2junction+', color=netcolor] ('+str(x2)+','+str(y2)+');% wire '+wire.name+'\n');
else:
# polywire
# \draw (4,2) -- (4,4) -- (6,4);
xn = wire.xn;
yn = wire.yn;
x1b = xn[0]*xscale+xoffset;
y1b = yn[0]*yscale+yoffset;
x2b = xn[len(xn)-1]*xscale+xoffset;
y2b = yn[len(yn)-1]*yscale+yoffset;
# normal wire segments for junctions: (this works with zero length segements, so we do not use the x1b/y1b, x2b/y2b points any longer.)
fhd.write(r'\draw [/lt2ti/Net]('+str(x1)+r','+str(y1)+r')to[*short,'+p1junction+'-, color=netcolor] ('+str(x1)+','+str(y1)+');% wire '+wire.name+' start\n');
fhd.write(r'\draw [/lt2ti/Net]('+str(x2)+r','+str(y2)+r')to[*short,-'+p2junction+', color=netcolor] ('+str(x2)+','+str(y2)+');% wire '+wire.name+' end\n');
#fhd.write(r'\draw [/lt2ti/Net]('+str(x1)+r','+str(y1)+r')to[*short,'+p1junction+'-] ('+str(x1b)+','+str(y1b)+');% wire '+wire.name+' start\n');
#fhd.write(r'\draw [/lt2ti/Net]('+str(x2b)+r','+str(y2b)+r')to[*short,-'+p2junction+'] ('+str(x2)+','+str(y2)+');% wire '+wire.name+' end\n');
# polyline
wstr = '\draw [/lt2ti/Net]('+str(x1)+r','+str(y1)+r')';
for i in range(0, (len(xn))):
xni = xn[i]*xscale+xoffset;
yni = yn[i]*yscale+yoffset;
wstr = wstr + ' -- '
wstr = wstr + ' ('+str(xni)+','+str(yni)+')' ;
wstr = wstr + ' -- ('+str(x2)+','+str(y2)+'); % wire '+wire.name+ ' polyline \n' ;
fhd.write(wstr);
# output components
for pp, compDict in self.circDict.coordCompDict.items():
for c, comp in compDict.items():
comp.circuitDict = self.circDict; # used for junction lookup etc.
comp.config = self.config; # allow config parameters in components to be used
texlines = comp.translateToLatex({}); # ToDo: apply xoffset, yoffset (currently not in use)
for tl in texlines:
tl = re.sub(r'[\r]*[\n]$', '', tl); # remove trailing line break since we add it after the comment.
fhd.write(tl+' % component "'+comp.pathandctype+'" "'+comp.name+'" \n');
# output labels
for pp, labeldict in self.circDict.coordLabelDict.items():
for l, label in labeldict.items():
label.circuitDict = self.circDict;
texlines = label.translateToLatex({}); # ToDo: apply xoffset, yoffset (currently not in use)
for tl in texlines:
tl = re.sub(r'[\r]*[\n]$', '', tl); # remove trailing line break since we add it after the comment.
fhd.write(tl+' % label "'+label.pathandctype+'" "'+label.label+'" '+label.value+' \n');