-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyLTSpice_macOS.py
More file actions
1488 lines (1303 loc) · 65.7 KB
/
PyLTSpice_macOS.py
File metadata and controls
1488 lines (1303 loc) · 65.7 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
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
#!/usr/bin/env python
# ---------------------------------------------------------------------------------------------------
# Name: PyLTSpice_macOS.py
# Purpose: Implementation of a toolchain for controlling LTSpice on Apple devices in Python
#
# Author: Simon Gapp
#
# Created: 31.05.2018
# Licence:
# ---------------------------------------------------------------------------------------------------
""" Implementation of a toolchain for controlling LTSpice on Apple devices in Python
"""
import getpass
import os
import re
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import filecmp
import shutil
import psutil
import subprocess
import time
#from PyLTSpice.LTSpice_RawRead import RawRead as RawRead
from LTSpice_RawRead import RawRead as RawRead
import DebugHelpers as debug
import DefinesDefault
def check_if_path_exists(path_to_file):
return os.path.exists(path_to_file)
class LTC:
"""Class to generate the LTSpice object
:param path_to_asc_file: Absolute or relative path to the ``.asc`` file
:type path_to_asc_file: str
:param path_to_ltspice_app: Path to LTSpice.app. Default: ``/Applications/LTSpice.app``
:type path_to_ltspice_app: str, optional
:param path_to_ltspice_library: Path to LTSpice library.
Default: ``/Users/<user name>/Library/Application Support/LTSpice/lib/sym``
:type path_to_ltspice_library: str, optional
:param simulate_data: Boolean whether a simulation is required. This can be used to create a single plot of
the schematic or if a ``.raw`` file already exists. Default: True
:type simulate_data: Bool, optional
:param ltspice_run_time: Time before LTSpice is terminated. Useful for longer simulations. Default: 1s
:type ltspice_run_time: int, optional
:param verbose: Boolean to determine the verbose output of the LTC object. Default: False
:type verbose: Bool, optional
"""
def __init__(self, path_to_asc_file,
path_to_ltspice_app=None,
path_to_ltspice_library=None,
simulate_data=True,
ltspice_run_time=None,
verbose=False):
"""Constructor method"""
# Attempt to have C/C++ style defines file
self.__defs = DefinesDefault.Defines()
# Configure LTC object
self.simulate_data = simulate_data
# If the schematic shall be simulated check if the default LTSpice directory is used or a custom directory
if self.simulate_data:
if path_to_ltspice_app:
self.path_to_ltspice_app = path_to_ltspice_app
if not check_if_path_exists(self.path_to_ltspice_app):
print('Specified location: ' + self.path_to_ltspice_app + ' not found.')
print('Trying default location: ' + self.__defs.get_define('LTSPICE_APP_DEFAULT_LOC'))
self.path_to_ltspice_app = self.__defs.get_define('LTSPICE_APP_DEFAULT_LOC')
else:
print('Using LTSpice App from default location')
self.path_to_ltspice_app = self.__defs.get_define('LTSPICE_APP_DEFAULT_LOC')
# Check if path exists
if not check_if_path_exists(self.path_to_ltspice_app):
print('Did not find the LTSpice App! Abort.')
print('Path to LTSpice App: ' + self.path_to_ltspice_app)
return
# Check whether to use the default path to the LTSpice library or a custom path
if path_to_ltspice_library:
self.path_to_ltspice_library = path_to_ltspice_library
if not check_if_path_exists(self.path_to_ltspice_library):
print('Specified location: ' + self.path_to_ltspice_library + ' not found.')
print('Trying default location: ' + self.__defs.get_define('LTSPICE_LIBRARY_DEFAULT_LOC'))
self.path_to_ltspice_library = self.__defs.get_define('LTSPICE_LIBRARY_DEFAULT_LOC')
else:
print('Using LTSpice Library from default location')
self.path_to_ltspice_library = self.__defs.get_define('LTSPICE_LIBRARY_DEFAULT_LOC')
if not check_if_path_exists(self.path_to_ltspice_library):
print('Did not find the LTSpice Library! Abort.')
print('Path to LTSpice Library: ' + self.path_to_ltspice_library)
return
# Set spice directives
self.__spiceDirectives = self.__defs.get_define('SPICE_DIRECTIVES')
self.verbose = verbose
# Generate absolute path
tmp_complete_path = os.path.abspath(path_to_asc_file)
# Check if file exists
if not check_if_path_exists(tmp_complete_path):
print('LTC init: File: ' + tmp_complete_path + ' not found. Aborting!')
else:
print("Generating object")
# Define run time for LTSpice in seconds, default: 1s
if ltspice_run_time:
try:
self.LtSpiceRunTime = int(ltspice_run_time)
except ValueError:
print('Parameter: LtSpiceRunTime is not a number. Setting default value of: ' +
str(self.__defs.get_define('LTSPICE_RUN_TIME')))
self.LtSpiceRunTime = self.__defs.get_define('LTSPICE_RUN_TIME')
else:
self.LtSpiceRunTime = self.__defs.get_define('LTSPICE_RUN_TIME')
# Store path and filename of .asc file
self.PathToAscFile = tmp_complete_path
# Extract path and filename without file ending
self.__PathOnly, self.__FilenameOnly = os.path.split(self.PathToAscFile)
self.__FilenameOnly = self.__FilenameOnly[:-4]
# Create a backup file of the original
self.__create_backup_file()
# Read asc file and check for simulation directive
self.__get_asc_file_content()
# check for simulation directive
if self.simulate_data:
if not (self.__check_for_simulation_directive()):
print("Did not find a simulation directive in the form of " + str(self.__spiceDirectives))
return
else:
# Check if an instance of LTspice is running, should be terminated before we continue
# since running LTspice on an already open file really messes with the encoding of the asc file
if self.__check_if_process_running("LTSpice"):
print(
"Found at least one LTSpice instance running. Please quit the instance before continuning")
print("Abort.")
return
else:
print("Running LTSpice to generate simulation files")
self.run_ltspice()
else:
print('+++')
print('Simulation disabled.')
print('If you wish to simulate run the call with \'simulate_data=True\'')
print('+++')
if self.verbose:
print("Creating dictionaries")
self.__asc_create_component_dicts()
# Generate schematic object
self.schematic = Schematic(self.rawData, path_to_symbol_library=self.path_to_ltspice_library)
def get_trace_data(self, trace_name):
""" Retrieve simulation data of a trace
:parameter trace_name: Name of the trace to be retrieved
:type trace_name: str
:return: values
:rtype: list
"""
# Check if the simulation is enabled
if self.simulate_data:
return self.simulationData.get_trace(trace_name).data
else:
print('Simulation was disabled.')
print('Initialize with \'simulate_data=True\' to get simulation results')
# Method for creating a backup file before heavy editing in the original
def __create_backup_file(self):
"""Creating a backup file of the original .asc file
:parameter: None
:return: void"""
if os.path.isfile(self.__PathOnly + '/' + self.__FilenameOnly + '.asc_bak'):
if (not filecmp.cmp(self.__PathOnly + '/' + self.__FilenameOnly + '.asc',
self.__PathOnly + '/' + self.__FilenameOnly + '.asc_bak')):
if self.verbose:
print("Updating backup file in: " + self.__PathOnly + self.__FilenameOnly + '.asc_bak')
shutil.copyfile(self.PathToAscFile, self.__PathOnly + '/' + self.__FilenameOnly + '.asc_bak')
else:
if self.verbose:
print("Backup file detected. No new backup file created.")
else:
if self.verbose:
print("Creating backup file in: " + self.__PathOnly + self.__FilenameOnly + '.asc_bak')
shutil.copyfile(self.PathToAscFile, self.__PathOnly + '/' + self.__FilenameOnly + '.asc_bak')
# Method to read the asc file into a list
def __get_asc_file_content(self):
"""Reads in the content of the asc file
:param: None
:return: void
"""
try:
schematic = debug.get_raw_asc_data(self.PathToAscFile)
print('utf-16-le')
if len(schematic) == 1:
print('latin9')
schematic = debug.get_raw_asc_data(self.PathToAscFile, encoding='ISO-8859-1')
except UnicodeDecodeError as err:
try:
schematic = debug.get_raw_asc_data(self.PathToAscFile, encoding='ISO-8859-1')
print('latin9')
except Exception as err:
print('In :' + str(self.PathToAscFile))
print(err)
self.rawData = schematic
# Helper to check if a process is still running
def __check_if_process_running(self, processName="LTSpice"):
"""Check if a LTSpice process is running. Running LTSpice and running a new simulation can really mess with the .asc file encoding.
:param processName: processName which is LTSpice. Default: LTSpice
:type processName: str, optional
:return: True if LTSpice runs already, False if no LTSpice process is found
:rtype: Bool
"""
# Loop through currently running proesses
for proc in psutil.process_iter():
try:
# Check if process name contains the given name string.
if processName.lower() in proc.name().lower():
# Ignore zombie processes
if proc.status() == psutil.STATUS_ZOMBIE:
return False
else:
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False
# Run LTSpice
def run_ltspice(self):
"""Start LTSpice and run the simulation
:parameter: None
:return: void
"""
if self.simulate_data:
# Open LTSpice with file and run simulation to generate .raw files
proc = subprocess.Popen([self.path_to_ltspice_app + '/Contents/MacOS/LTspice',
'-Run',
self.PathToAscFile])
# Let some time pass in order to generate the .raw file etc.
time.sleep(self.LtSpiceRunTime)
# Killing the process prevents the .net file from being deleted
proc.terminate()
self.simulationData = RawRead(self.__PathOnly + '/' + self.__FilenameOnly + '.raw')
else:
print('Simulation was disabled.')
print('Initialize with \'simulate_data=True\' to run simulation.')
# Create dictionaries for value changes etc
def __asc_create_component_dicts(self):
"""Function to create a dictionary for the single components and the assigned values
:param: None
:return: void
"""
self.__AscComponentNameIdx = {}
self.__AscComponentRawLine = {}
self.__AscComponentValue = {}
counter = 0
# TODO: Add separate line for simulation directive
# tmp_sim = line[line.find('!*') + 2:].replace('\\n', '\n')
# if tmp_sim[0] == ' ':
# tmp_sim = tmp_sim[1:]
# self.simulation_command = tmp_sim
for line in self.rawData:
if (idx := line.find(self.__defs.get_define('ASC_COMPONENT_NAME_START'))) >= 0:
identifier = line[idx + len(self.__defs.get_define('ASC_COMPONENT_NAME_START')) + 1:-1]
value_idx = self.rawData[counter + 1].find(self.__defs.get_define('ASC_COMPONENT_VALUE_START'))
value = self.rawData[counter + 1][
value_idx + len(self.__defs.get_define('ASC_COMPONENT_VALUE_START')) + 1:-1]
if len(self.__AscComponentNameIdx) == 0:
self.__AscComponentNameIdx[identifier] = counter
self.__AscComponentValue[identifier] = value
self.__AscComponentRawLine[identifier] = self.rawData[counter + 1]
else:
self.__AscComponentNameIdx.update({identifier: counter})
self.__AscComponentValue.update({identifier: value})
self.__AscComponentRawLine.update({identifier: self.rawData[counter + 1]})
counter += 1
self.get_component_names_and_values()
def change_component(self, component_name, component_value, parameter=None):
"""Call to change the value of a component
:parameter component_name: Name of the component that is changed
:type component_name: str
:parameter component_value: New value of the component
:type component_value: str
:parameter parameter: If component is a multi value component, specify what will be changed. E.g. amplitude of a sinus. Default: None
:type parameter: str, optional"""
component_value_str = str(component_value)
# Get old value
self.__component_old_val = self.__AscComponentValue[component_name]
for source_type in self.__defs.get_define('SOURCE_TYPES'):
if self.__component_old_val.upper().find(source_type) >= 0:
self.__change_sinusoidal_source(component_name, component_value, parameter)
# TODO: Cover other formats
else:
# Update new value
self.__AscComponentValue[component_name] = component_value_str
# Update raw line
self.__AscComponentRawLine[component_name] = self.__AscComponentRawLine[component_name].replace(
self.__component_old_val, component_value_str)
def __change_sinusoidal_source(self, component_name, component_value, parameter):
# TODO: Add support for all parameters of a voltage source (AC etc)
"""Function to change the DC parameters
:param component_name: Name of the component to be changed
:type component_name: str
:param component_value: Value to be changed
:type component_value: str
:param parameter: The parameter to be changed. Currently supported: 'DC_Offset', 'Amplitude', 'Frequency',
'Delay', 'Dampfing_factor', 'Phase', 'Cycles'
:type parameter: str
"""
# Split into single fields
# tmp_vals = [s for s in re.findall(r'\b\d+\b', self.__component_old_val)]
tmp_vals = self.__component_old_val[len('SINE') + 1:-1].split(' ')
# Sanity check
if len(tmp_vals) > len(self.__defs.get_define('SOURCE_PARAMETERS_SINE').keys()):
print('SINE source: More parameters detected than available.')
return
# Assign new value to respecitve parameter
else:
tmp_vals[self.__defs.get_define('SOURCE_PARAMETERS_SINE')[parameter]] = component_value
# Generate value string
value_string = str(tmp_vals[0])
for i in range(1, len(tmp_vals)):
value_string = value_string + ' ' + str(tmp_vals[i])
component_value_str = 'SINE(' + value_string + ')'
# Update new value
self.__AscComponentValue[component_name] = component_value_str
# Update raw line
self.__AscComponentRawLine[component_name] = self.__AscComponentRawLine[component_name].replace(
self.__component_old_val, component_value_str)
# Write asc file
def update(self):
"""Update the schematic an run the LTSpice simulation with new values again.
:parameter: None
:return: Void
"""
# Update the value lines in a temporary file
old_asc_file = self.rawData
new_asc_file = old_asc_file
for key in self.__AscComponentRawLine.keys():
new_asc_file[self.__AscComponentNameIdx[key] + 1] = self.__AscComponentRawLine[key]
# Copy temporary file into actual file
self.rawData = new_asc_file
# Write into .asc file
f = open(self.PathToAscFile, "w", encoding='utf-16-le')
f.writelines(self.rawData)
f.close()
self.schematic = Schematic(self.rawData, self.path_to_ltspice_library)
self.run_ltspice()
def get_component_names_and_values(self, verbose=False):
"""Get component names and values in the schematic.
:parameter verbose: verbose output. Default: False
:type verbose: Bool
:return: void
"""
if self.verbose or verbose:
print("Components in this schematic:")
for component in sorted(self.__AscComponentValue):
print(component + ": " + self.__AscComponentValue[component])
# Method to check for simulation directives
def __check_for_simulation_directive(self):
"""Checks the ``.asc`` file for a simulation directive. Without a directive no simulation can be performed.
:parameter: None
:return: True if directive is found, False if no directive is found.
:rtype: Bool
"""
# Loop from the last line, since the directive is usually at the end
for line in self.rawData[::-1]:
if line.find('TEXT') >= 0:
if line.find('!') >= 0:
if any(simulation_command in line for simulation_command in self.__spiceDirectives):
return True
return False
class Schematic:
"""Class to generate the Schematic object
:param raw_data: Raw data of the ``.asc`` file
:type raw_data: str list
:param path_to_symbol_library: Path to symbol library, Default: ``/Users/<user name>/Library/Application Support/
LTSpice/lib/sym``
:type path_to_symbol_library: str, optional
:param defines: Defines object, Default: ``DefinesDefault.Defines()``
:type defines: Defines, optional
:param verbose: Boolean for verbose output, Default: False
:type verbose: Bool, optional
"""
def __init__(self, raw_data, path_to_symbol_library=None, defines=None, verbose=False):
"""Constructor method"""
# Check if raw_data is not None
if raw_data:
if path_to_symbol_library:
self.path_to_symbol_library = path_to_symbol_library
self.plot_data = {}
tmp_schematic = [w.replace('\n', '') for w in raw_data]
self.raw_schematic = tmp_schematic
# Attempt to have C/C++ style defines file
if defines:
self.__defs = defines
else:
self.__defs = DefinesDefault.Defines()
tmp_scaling = self.raw_schematic[1].split(' ')
factor_1 = int(tmp_scaling[-2])
factor_2 = int(tmp_scaling[-1])
if factor_1 > factor_2:
self.text_scaling = factor_2 / factor_1
elif factor_1 < factor_2:
self.text_scaling = factor_1 / factor_2
else:
self.text_scaling = 1
self.verbose = verbose
self.__create_plot_data()
self.__find_junctions()
else:
print('Raw data appears to be empty. Aborting.')
def __find_junctions(self):
# TODO: Add support for symbol connections directly to a wire
"""Function to find all junctions on the schematic level
:parameter: None
:return: void
"""
if 'WIRE' in self.plot_data:
x = []
y = []
for elem in self.plot_data['WIRE']:
x.extend(elem[::2])
y.extend(elem[1::2])
x_indices = {}
self.__junction_coord = []
for elem in x:
tmp = [i for i, x in enumerate(x) if x == elem]
if len(tmp) >= 3:
x_indices[elem] = tmp
keys = x_indices.keys()
for key in keys:
selected_elements = [y[index] for index in x_indices[key]]
tmp_occurences = Counter(selected_elements)
tmp_keys = tmp_occurences.keys()
for tmp_key in tmp_keys:
if (tmp_occurences[tmp_key] >= 3):
self.__junction_coord.append([key, tmp_key])
else:
self.__junction_coord = []
def __find_attributes(self, idx, no_of_lines_after_idx=6):
"""Function to find all attributes of a component
:param idx: Index where to start searching in the ``.asc`` file
:type idx: int
:param no_of_lines_after_idx: Maximum number of lines to search after the idx. Default: 6
:type no_of_lines_after_idx: int, optional
:Returns:
- **name** (str) - name of the component
- **value** (str) - value of the component
- **value2** (str) - value2 of the component
- **spice_line** (str) - spice line of the component
"""
counter = 0
name = ''
value = ''
value2 = ''
spice_line = ''
found_name = False
found_value = False
found_value2 = False
found_spice_line = False
if self.verbose:
print('+++++++++')
for line in self.raw_schematic[idx + 1:]:
if self.verbose:
print(line)
if line.split(' ')[0] == 'SYMBOL':
break
elif (counter >= no_of_lines_after_idx) or \
(found_name and found_value and found_value2 and found_spice_line):
if self.verbose:
print('#############')
print('No of lines after idx: ' + str(no_of_lines_after_idx))
print('Counter: ' + str(counter))
print('Counter if: ' + str(counter >= no_of_lines_after_idx))
print('Found all: ' + str(found_name and found_value and found_value2 and found_spice_line))
print('Name: ' + str(name))
print('Value: ' + str(value))
print('Value2: ' + str(value2))
print('Spice Line: ' + str(spice_line))
return name, value, value2, spice_line
elif line.find('SYMATTR') >= 0:
if (line.find('InstName') >= 0) and (not found_name):
name = self.__extract_attributes(line)
found_name = True
elif (line.find('Value2') >= 0) and (not found_value2):
value2 = self.__extract_attributes(line)
found_value2 = True
elif (line.find('Value') >= 0) and (not found_value):
value = self.__extract_attributes(line)
found_value = True
elif (line.find('SpiceLine') >= 0) and (not found_spice_line):
spice_line = self.__extract_attributes(line)
found_spice_line = True
counter += 1
return name, value, value2, spice_line
def __extract_attributes(self, line):
""" Function to extract attributes
:param line: Line to extract the attribute from
:type line: str
:return: list of strings
:rtype: str list
"""
return ' '.join(line.split(' ')[2:]).replace('\"', '')
def __create_plot_data(self):
"""Function to create the plot data
:parameter: None
:return: void
"""
for i in range(2, len(self.raw_schematic)):
tmp_line = self.raw_schematic[i].split(' ')
# TODO: Separate function for line and line styles
if tmp_line[0] == 'WIRE' or tmp_line[0] == 'LINE':
identifier = tmp_line[0]
if identifier == 'WIRE':
position = [int(x) for x in tmp_line[1:]]
else:
position = [int(x) for x in tmp_line[2:-1]]
# TODO: LoopGain.asc requires different Line positions
if len(position) < 4:
position = [int(x) for x in tmp_line[2:]]
self.__write_to_PlotData_dict(key=identifier, value=position)
elif tmp_line[0] == 'FLAG':
identifier = tmp_line[0]
position = [int(x) for x in tmp_line[1:3]]
position.append(' '.join(tmp_line[3:]))
self.__write_to_PlotData_dict(key=identifier, value=position)
elif tmp_line[0] == 'SYMBOL':
tmp_window = []
# A maximum number of 4 windows will be declared after symbol
for j in range(4):
try:
tmp_preview_line = self.raw_schematic[i + 1 + j]
# New symbol will start with SYMBOL break the loop then
if tmp_preview_line.split(' ')[0] == 'SYMBOL':
break
elif tmp_preview_line.split(' ')[0] == 'WINDOW':
tmp_window.append(tmp_preview_line)
# print('Found: ' + str(tmp_preview_line))
except IndexError:
pass
# print('tmp_window: ' + str(tmp_window))
identifier = tmp_line[1]
position = [int(x) for x in tmp_line[2:4]]
rotation = tmp_line[4]
if len(tmp_window) > 0:
name, value, value2, spice_line = self.__find_attributes(idx=i + len(tmp_window))
else:
name, value, value2, spice_line = self.__find_attributes(idx=i)
# print('+++++')
# print('Identifier: ' + str(identifier))
# print('Name: ' + str(name))
# print('Value: ' + str(value))
# print('Value2: ' + str(value2))
# print('Spice line: ' + str(spice_line))
# print('Window: ' + str(tmp_window))
if name == '':
name = 'tbd'
if value == '':
value = ''
tmp_symbol = Symbol(symbol_model=identifier, symbol_name=name, symbol_value=value, symbol_value2=value2,
symbol_spice_line=spice_line,
symbol_position=position, symbol_rotation=rotation,
window=tmp_window,
text_scaling_factor=self.text_scaling,
path_to_symbol_library=self.path_to_symbol_library,
defines=self.__defs,
verbose=self.verbose)
self.__write_to_PlotData_dict(name, tmp_symbol)
elif tmp_line[0] == 'TEXT':
# print(tmp_line)
identifier = tmp_line[0]
position = [int(x) for x in tmp_line[1:3]]
position.append(tmp_line[3])
position.append(int(tmp_line[4]))
position.append(' '.join(tmp_line[5:])[1:])
self.__write_to_PlotData_dict(key=identifier, value=position)
def __write_to_PlotData_dict(self, key, value):
"""Function to write the plot data to the ``plot_data`` dict
:param key: Key of the value
:type key: str
:param value: Value of the key
:type value: str
"""
try:
self.plot_data[key].append(value)
except:
self.plot_data[key] = [value]
def __read_schematic(self):
""" Function to read the schematic in
:parameter: None
:return: void
"""
fid = open(self.path_to_file, 'r', encoding='utf-16-le')
tmp_schematic = fid.readlines()
fid.close()
tmp_schematic = [w.replace('\n', '') for w in tmp_schematic]
self.raw_schematic = tmp_schematic
def __plot_gnd(self, x_pos, y_pos):
""" Function to plot the GND symbol
:param x_pos: x position of the GND symbol
:type x_pos: int
:param y_pos: y position of the GND symbol
:type y_pos: int
"""
horizontal_line_length = 24
vertical_line_length = 16
lines = [[x_pos - horizontal_line_length / 2, y_pos, x_pos + horizontal_line_length / 2, y_pos],
[x_pos, y_pos + vertical_line_length, x_pos - horizontal_line_length / 2, y_pos],
[x_pos, y_pos + vertical_line_length, x_pos + horizontal_line_length / 2, y_pos]]
for line in lines:
plt.plot(line[::2], line[1::2], color='tab:blue')
def plot_schematic(self, figsize=None, verbose=False):
""" Function to plot the entire schematic
:param figsize: figsize, default: None
:type figsize: tuple, optional
:param verbose: verbose for plotting
:type verbose: Bool
"""
keys = self.plot_data.keys()
if figsize:
plt.figure(figsize=figsize)
else:
plt.figure(figsize=self.__defs.get_define('DEFAULT_FIG_SIZE'))
for key in keys:
for elem in self.plot_data[key]:
# print(elem)
try:
elem.plot_symbol(verbose=verbose)
except AttributeError:
if key == 'WIRE' or key == 'LINE':
if key == 'WIRE':
plt.plot(elem[::2], elem[1::2], color='tab:blue')
else:
plt.plot(elem[::2], elem[1::2], '--', color='tab:blue')
elif key == 'FLAG':
if elem[2] == '0':
self.__plot_gnd(x_pos=elem[0], y_pos=elem[1])
else:
plot_text(x_y_coordinates=[elem[0], elem[1] - 5], label=elem[2],
text_alignment='Center',
font_size=2,
symbol_rotation='R0',
text_scaling_factor=self.text_scaling,
defines=self.__defs,
verbose=verbose)
elif key == 'TEXT':
# print(elem)
# Drawing the dots draws the plot frame around the entire plot
# Otherwise far out text elements would be outside the frame
plt.plot(elem[0], elem[1], color='w')
# Plot the actual text
try:
if elem[2].lower() == 'top' or elem[2].lower() == 'bottom':
plot_text(x_y_coordinates=[elem[0], elem[1]], label=elem[4].replace('\\n', '\n'),
text_alignment=elem[2],
font_size=elem[3],
symbol_rotation='R0',
text_scaling_factor=self.text_scaling,
defines=self.__defs,
verbose=verbose)
else:
# TODO: Finish this
plot_text(x_y_coordinates=[elem[0], elem[1]], label=elem[4].replace('\\n', '\n'),
text_alignment=elem[2],
font_size=elem[3],
symbol_rotation='R0',
text_scaling_factor=self.text_scaling,
defines=self.__defs,
verbose=verbose)
# TODO: Add some kind of error log for easier debug
except AttributeError:
pass
except ValueError:
pass
if len(self.__junction_coord) > 0:
for elem in self.__junction_coord:
plt.plot(elem[0], elem[1], 'o',
markersize=self.__defs.get_define('DEFAULT_JUNCTION_SIZE') * self.text_scaling,
color='tab:blue')
plt.gca().invert_yaxis()
plt.axis('equal')
plt.tick_params(left=False,
labelleft=False,
bottom=False,
labelbottom=False)
def set_define(self, key, value):
"""Wrapper for :meth:`DefinesDefault.Defines.set_define`"""
self.__defs.set_define(key=key, value=value)
def set_font_size(self, value):
"""Function to adapt the fontsize manually
:param value: Value to set the fontsize to
:type value: int or float
:return: void
"""
self.__defs.set_define(key='DEFAULT_FONT_SIZE', value=value)
def set_junction_size(self, value):
"""Function to adapt the junction size manually
:param value: Value to set the junction size to
:type value: int or float"""
self.__defs.set_define(key='DEFAULT_JUNCTION_SIZE', value=value)
def plot_text(x_y_coordinates, label, text_alignment, font_size, symbol_rotation, text_scaling_factor, defines,
verbose=False):
"""Function to plot the labels of a component
:param x_y_coordinates: x and y coordinate of the label
:type x_y_coordinates: list
:param label: label of the component
:type label: str
:param text_alignment: Alignment of the text
:type text_alignment: str
:param font_size: Font size of the label
:type font_size: int
:param symbol_rotation: Rotation of the symbol
:type symbol_rotation: str
:param text_scaling_factor: Scaling factor of the text
:type text_scaling_factor: float
:param defines: Defines object
:type defines: Defines"""
if verbose:
try:
print('*******************')
print('plot_text(): label: ' + str(label))
print('plot_text(): X: ' + str(x_y_coordinates[0]))
print('plot_text(): Y: ' + str(x_y_coordinates[1]))
print('plot_text(): text alignment: ' + str(text_alignment))
print('plot_text(): symbol rotation: ' + str(symbol_rotation))
print('plot_text(): HA: ' + str(
defines.get_define('TEXT_HORIZONTAL_ALIGNMENTS')[text_alignment][symbol_rotation]))
print('plot_text(): VA: ' + str(
defines.get_define('TEXT_VERTICAL_ALIGNMENTS')[text_alignment][symbol_rotation]))
print(
'plot_text(): ROT: ' + str(
defines.get_define('TEXT_ROTATION_ANGLES')[text_alignment][symbol_rotation]))
print('plot_text(): FONTSIZE: ' + str(
defines.get_define('DEFAULT_FONT_SIZE') * defines.get_define('LTSPICE_FONTSIZES')[font_size] *
text_scaling_factor))
plt.plot(x_y_coordinates[0], x_y_coordinates[1], '*', markersize=4)
except Exception as excp:
print(excp)
# Check if the label contains more than one line
# Multi Lines have different requirements
if label.count('\n') > 0:
symbol_rotation = symbol_rotation + 'ML'
if label[0] == '_':
string = '$\overline{' + label[1:] + '}$'
plt.text(x_y_coordinates[0], x_y_coordinates[1], string,
horizontalalignment=defines.get_define('TEXT_HORIZONTAL_ALIGNMENTS')[text_alignment][
symbol_rotation],
verticalalignment=defines.get_define('TEXT_VERTICAL_ALIGNMENTS')[text_alignment][symbol_rotation],
rotation=defines.get_define('TEXT_ROTATION_ANGLES')[text_alignment][symbol_rotation],
fontsize=defines.get_define('DEFAULT_FONT_SIZE') * defines.get_define('LTSPICE_FONTSIZES')[
font_size] *
text_scaling_factor)
else:
plt.text(x_y_coordinates[0], x_y_coordinates[1], label,
horizontalalignment=defines.get_define('TEXT_HORIZONTAL_ALIGNMENTS')[text_alignment][
symbol_rotation],
verticalalignment=defines.get_define('TEXT_VERTICAL_ALIGNMENTS')[text_alignment][symbol_rotation],
rotation=defines.get_define('TEXT_ROTATION_ANGLES')[text_alignment][symbol_rotation],
fontsize=defines.get_define('DEFAULT_FONT_SIZE') * defines.get_define('LTSPICE_FONTSIZES')[
font_size] *
text_scaling_factor)
class Symbol:
"""Class to generate the Symbol objects
:param symbol_model: Name of the ``.asy`` file
:type symbol_model: str
:param symbol_name: Name of the symbol aka component
:type symbol_name: str
:param symbol_value: Value of the symbol
:type symbol_value: str
:param symbol_position: x- and y-coordinates of the absolute position of the symbol
:type symbol_position: int list
:param symbol_rotation: Rotation of the symbol
:type symbol_rotation: str
:param symbol_value2: Value of the second value field
:type symbol_value2: str
:param symbol_spice_line: Spice line of the symbol
:type symbol_spice_line: str
:param defines: Defines object, Default: None
:type defines: Defines, optional
:param window: Sets the window position of the value fields, default: None
:type window: int list, optional
:param text_scaling_factor: Text scaling factor, default: 1
:type text_scaling_factor: float, optional
:param verbose: Verbose output
:type verbose: Bool
:param path_to_symbol_library: Path to symbol library, default: None
:type path_to_symbol_library: Bool, optional
"""
def __init__(self, symbol_model, symbol_name, symbol_value, symbol_position, symbol_rotation,
symbol_value2=None, symbol_spice_line=None, defines=None, window=None, text_scaling_factor=1,
verbose=False, path_to_symbol_library=None):
# Store path to symbol library which is either default or can be customized
if path_to_symbol_library:
self.path_to_symbol_library = path_to_symbol_library
else:
self.path_to_symbol_library = self.__defs.get_define('LTSPICE_LIBRARY_DEFAULT_LOC')
# Create path to symbol and check if it exists
self.path_to_symbol = self.__find_file(symbol_model + '.asy')
if not os.path.isfile(self.path_to_symbol):
print('File: ' + str(self.path_to_symbol) + ' not found! Abort.')
self.path_to_symbol = None
return
else:
# Store symbol properties
self.verbose = verbose
self.symbol_model = symbol_model
self.symbol_labels = {0: symbol_name,
3: symbol_value,
123: symbol_value2,
39: symbol_spice_line}
self.symbol_position = symbol_position
self.symbol_rotation = symbol_rotation
self.text_scaling_factor = text_scaling_factor
if defines:
self.__defs = defines
else:
self.__defs = DefinesDefault.defines()
self.window = None
if window:
self.window = window
# Store symbol
self.raw_symbol = None
self.__read_symbol()
# Get symbol type
self.symbol_type = None
self.__get_symbol_type()
# Generate plot data.
# Data needs to be handled according to type
self.plot_data = {}
self.plot_texts = {}
self.create_plot_data()
def __find_file(self, filename):
""" Function to retrieve the corrct ``.asy`` file
:param filename: Name of the ``.asy`` file
:type filename: str
:return: void"""
filename_internal = filename.replace('\\\\', '/')
if (idx := filename_internal.rfind('/')) > 0:
raw_file = '/' + filename_internal[idx + 1:]
else:
raw_file = '/' + filename_internal
for root, dirnames, filenames in os.walk(self.path_to_symbol_library):
for file in filenames:
tmp_path = os.path.join(root, file.lower())
if raw_file.lower() in tmp_path:
return os.path.join(root, file)
print('find_file(): File: ' + filename_internal + ' not found! Abort.')
def __coordinate_mapper(self, tmp_coordinates):
""" Function to map the relative symbol coordinates to the absolute position coordinates
:param tmp_coordinates: List of x- and y- coordinates
:type tmp_coordinates: int list
:returns:
- **x_coordinates** (int) - x coordinate of the input
- **y_coordinates** (int) - y coordinate of the input
"""
# Non mirrored x and y values
if self.symbol_rotation == 'R0':
x_coordinates = np.array(tmp_coordinates[::2]) + self.symbol_position[0]
y_coordinates = np.array(tmp_coordinates[1::2]) + self.symbol_position[1]
elif self.symbol_rotation == 'R90':
x_coordinates = -np.array(tmp_coordinates[1::2]) + self.symbol_position[0]
y_coordinates = np.array(tmp_coordinates[::2]) + self.symbol_position[1]
elif self.symbol_rotation == 'R180':
x_coordinates = -np.array(tmp_coordinates[::2]) + self.symbol_position[0]
y_coordinates = -np.array(tmp_coordinates[1::2]) + self.symbol_position[1]
elif self.symbol_rotation == 'R270':
x_coordinates = np.array(tmp_coordinates[1::2]) + self.symbol_position[0]
y_coordinates = -np.array(tmp_coordinates[::2]) + self.symbol_position[1]
# Mirrored x and y values
elif self.symbol_rotation == 'M0':
x_coordinates = -np.array(tmp_coordinates[::2]) + self.symbol_position[0]
y_coordinates = np.array(tmp_coordinates[1::2]) + self.symbol_position[1]
elif self.symbol_rotation == 'M270':
x_coordinates = -np.array(tmp_coordinates[1::2]) + self.symbol_position[0]
y_coordinates = -np.array(tmp_coordinates[::2]) + self.symbol_position[1]
elif self.symbol_rotation == 'M180':
x_coordinates = np.array(tmp_coordinates[::2]) + self.symbol_position[0]
y_coordinates = -np.array(tmp_coordinates[1::2]) + self.symbol_position[1]
elif self.symbol_rotation == 'M90':
x_coordinates = np.array(tmp_coordinates[1::2]) + self.symbol_position[0]
y_coordinates = np.array(tmp_coordinates[::2]) + self.symbol_position[1]
# Debug function. Print unrecognized rotation command
else:
print('create_plot_data: Rotation ' + self.symbol_rotation + ' not recognized')
x_coordinates = 0
y_coordinates = 0
return x_coordinates, y_coordinates
def __offset_corrector(self, x_coordinates, y_coordinates, text_alignment, offset):
# TODO: Make sure all labels are corrected
"""Function to correct the offset of labels
:param x_coordinates: x coordinate of the label
:type x_coordinates: int
:param y_coordinates: y coordinate of the label
:type y_coordinates: int
:param text_alignment: Text alignment of the label
:type text_alignment: str
:parameter offset: offset of the label