This repository has been archived by the owner on Jun 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathspice_analyser.py
1620 lines (1380 loc) · 61.5 KB
/
spice_analyser.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
# vim: set shiftwidth=2 softtabstop=2 ts=2 expandtab:
#
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
import textwrap
import re
import csv
from enum import Enum
from datetime import datetime
import numpy as np
import math
import matplotlib.pyplot as plt
import pdb
import os
import circuit
import spice
import spice_util
from spice_util import NumericalValue, SIUnitPrefix
from google.protobuf import text_format
import proto.test_manifest_pb2 as manifest_pb
import proto.circuit_analysis_pb2 as analysis_pb
DUT_TYPE_TO_PROTO = {
circuit.DesignRegion.DUTType.SUB_REGION:
analysis_pb.DesignRegion.DeviceUnderTestType.SUB_REGION,
circuit.DesignRegion.DUTType.MODULE:
analysis_pb.DesignRegion.DeviceUnderTestType.MODULE,
circuit.DesignRegion.DUTType.EXTERNAL_MODULE:
analysis_pb.DesignRegion.DeviceUnderTestType.EXTERNAL_MODULE,
}
PROTO_TO_DUT_TYPE = {
analysis_pb.DesignRegion.DeviceUnderTestType.SUB_REGION:
circuit.DesignRegion.DUTType.SUB_REGION,
analysis_pb.DesignRegion.DeviceUnderTestType.MODULE:
circuit.DesignRegion.DUTType.MODULE,
analysis_pb.DesignRegion.DeviceUnderTestType.EXTERNAL_MODULE:
circuit.DesignRegion.DUTType.EXTERNAL_MODULE,
}
SIGNAL_FROM_XYCE_V_STATEMENT_RE = re.compile('^V\((.*)\)$')
class SpiceTestHarness:
def __init__(self, design, region, spice_libs,
output_directory=None, subckt_name=None, include_subckt=None,
test_suffix=None, tags=[]):
self.design = design
self.region = region
self.include_subckt = include_subckt
self.output_directory = output_directory
self.test_suffix = test_suffix
self.tags = tags
# FIXME(growly): This is a hack. Could just put this in DesignRegion.
# Should rename DesignRegion to SpiceTestSpec or something.
self.subckt_name = subckt_name or self.region.name
self.spice_libs = spice_libs
# TODO(growly): Replace with option from Design.
self.ground_name = '0'
self.ground_wire = circuit.Wire(
circuit.Signal(self.ground_name, width=1), 0)
self.vdd_v = 0.7
self.default_fixed_dc_bias_v = self.vdd_v/2
# Test-specific, in addition to those in the region.
self.input_waveforms = []
self.biases = []
self.instances = []
self.voltage_probes = []
# Multiple objects might refer to the same parameter, collected here by
# name.
self.sweep_parameters = {}
def AddBias(self, bias):
self.biases.append(bias)
def AddInputWaveform(self, input_waveform):
self.input_waveforms.append(input_waveform)
def AddInstance(self, instance):
self.instances.append(instance)
def AddVoltageProbe(self, probe):
self.voltage_probes.append(probe)
def DeckPreamble(self):
pins = self.region.OrderedWires()
pin_names = []
for pin in pins:
if not isinstance(pin, circuit.Wire):
raise NotImplementedError()
pin_names.append(pin.SpiceName())
spice_test = textwrap.dedent(f"""\
** {self.description}
** Harness generated by bigspicy.py at {datetime.utcnow().ctime()} UTC
.OPTIONS DEVICE TNOM=25 ; converted options using xdm
.PREPROCESS REPLACEGROUND TRUE
.GLOBAL VSS ; TODO(growly): parameterise.
R0 VSS 0 R=0
""")
spice_test += '\n' + self.ReportComment() + '\n'
for lib in self.spice_libs:
spice_test += f'.INCLUDE {lib}\n'
if self.include_subckt:
spice_test += f'.INCLUDE {self.include_subckt}\n'
spice_test += '\n' + self.ParamStatements()
spice_test += textwrap.dedent(f"""
** circuit under test
X0 {' '.join(pin_names)} {self.subckt_name}
""")
return spice_test
def GetOrCreateSweepParameter(self, sweep_parameter):
try:
return self.sweep_parameters[sweep_parameter.name]
except KeyError:
self.sweep_parameters[sweep_parameter.name] = sweep_parameter
return sweep_parameter
def ReportComment(self):
return ''
def ParamStatements(self):
out = ''
for parameter in self.sweep_parameters.values():
out += f'.PARAM {parameter.name}={parameter.low}\n'
return out
def StepStatements(self):
out = ''
for parameter in self.sweep_parameters.values():
out += f'.STEP {parameter.name} {parameter.low} {parameter.high} {parameter.step}\n'
return out
class TransientTest(SpiceTestHarness):
def __init__(self,
design,
region,
test_manifest,
spice_libs,
output_directory=None,
include_subckt=None,
subckt_name=None,
step_size_fs=0.01,
duration_ps=4000.0,
input_delay_ps=1.0,
input_rise_time_ps=5.0,
input_fall_time_ps=5.0,
input_width_ps=2000.0,
input_period_ps=4000.0,
test_suffix=None,
tags=[]):
super().__init__(design, region, spice_libs,
output_directory=output_directory,
subckt_name=subckt_name,
include_subckt=include_subckt,
test_suffix=test_suffix,
tags=tags)
if include_subckt:
root = include_subckt.removesuffix('.sp')
else:
root = os.path.join(output_directory, region.name)
suffix = f'.transient_{self.test_suffix}.sp' if self.test_suffix else '.transient.sp'
self.test_file_name = root + suffix
self.description = f'Transient Analysis for region "{self.region.name}"'
self.step_size_fs = step_size_fs
self.duration_ps = duration_ps
self.fft_specs = []
self.delay_measurements = []
self.other_measurements = []
self.default_input_driver = spice.StepInput(
self.ground_wire,
reference_wire=self.ground_wire,
low_voltage=NumericalValue(0.0),
high_voltage=NumericalValue(self.vdd_v),
delay_s=NumericalValue(
input_delay_ps, SIUnitPrefix.PICO),
rise_time_s=NumericalValue(
input_rise_time_ps, SIUnitPrefix.PICO),
fall_time_s=NumericalValue(
input_fall_time_ps, SIUnitPrefix.PICO),
pulse_width_s=NumericalValue(
input_width_ps, SIUnitPrefix.PICO),
period_s=NumericalValue(
input_period_ps, SIUnitPrefix.PICO))
for transient in test_manifest.transient_analyses:
if transient.spice_source_file == self.test_file_name:
print('warning: overwriting existing test entry in manifest for '
f'{transient.spice_source_file}')
test_manifest.transient_analyses.remove(transient)
self.manifest = test_manifest.transient_analyses.add()
self.manifest.design_region_name = region.name
self.manifest.spice_source_file = self.test_file_name
self.manifest.tags.extend(self.tags)
def ReportComment(self):
loads = ' '.join(map(lambda load: load.wire.SpiceName(), self.region.loads.values()))
ports = ' '.join(map(lambda port: port.wire.SpiceName(), self.region.port_network_ports.values()))
dc_biases = ' '.join(map(lambda dc_bias: dc_bias.wire.SpiceName(), self.region.dc_biases.values()))
dc_sources = ' '.join(map(lambda dc_load: dc_load.wire.SpiceName(), self.region.dc_sources.values()))
drivers = ' '.join(map(lambda driver: driver.wire.SpiceName(), self.region.simulated_drivers.values()))
probes = ' '.join(map(lambda probe: probe.wire.SpiceName(), self.region.voltage_probes.values()))
sub_probes = ' '.join(map(lambda probe: 'X0:' + probe.wire.SpiceName(), self.region.subcircuit_voltage_probes))
return textwrap.dedent(f"""\
** bigspicy info:
** loads: {loads}
** ports: {ports}
** fixed nets (dc biases): {dc_biases}
** fixed dc sources: {dc_sources}
** inputs (simulated drivers): {drivers}
** outputs (voltage probes): {probes}
** subcircuit probes (voltage probes): {probes}
""")
def AddFFTSpec(self, fft_spec):
self.fft_specs.append(fft_spec)
def AddDelayMeasurement(self, measurement):
self.delay_measurements.append(measurement)
def AddOtherMeasurement(self, measurement):
self.other_measurements.append(measurement)
def Write(self):
spice_test = self.DeckPreamble()
spice_writer = spice.SpiceWriter(self.design)
if self.instances:
spice_test += '\n** test-specific instances\n'
for instance in self.instances:
spice_test += spice_writer.SpiceInstance(instance, generate_names=False)
num_dc_sources = 1
print_list = []
if self.region.dc_sources:
spice_test += '\n** dc sources\n'
for dc_source in self.region.dc_sources.values():
potential_v = dc_source.value or self.default_fixed_dc_bias_v
spice_test += f'VSRC{num_dc_sources} {dc_source.wire.SpiceName()} {self.ground_name} DC {potential_v}'
num_dc_sources += 1
spice_test += '\n** simulated signal drivers\n'
for driver in self.region.simulated_drivers.values():
device_name = f'VSRC{num_dc_sources}'
node_name = driver.wire.SpiceName()
if driver.input_waveform is None:
self.default_input_driver.wire = driver.wire
spice_test += self.default_input_driver.SpiceLine(
device_name) + '\n'
else:
spice_test += driver.input_waveform.SpiceLine(device_name) + '\n'
print_list.append(f'V({node_name})')
num_dc_sources += 1
for input_waveform in self.input_waveforms:
device_name = f'VSRC{num_dc_sources}'
node_name = input_waveform.wire.SpiceName()
spice_test += input_waveform.SpiceLine(device_name) + '\n'
print_list.append(f'V({node_name})')
num_dc_sources += 1
for probe in list(self.region.voltage_probes.values()) + self.voltage_probes:
node_name = probe.wire.SpiceName()
print_list.append(f'V({probe.wire.SpiceName()})')
for probe in self.region.subcircuit_voltage_probes:
node_name = probe.wire.SpiceName()
print_list.append(f'V(X0:{probe.wire.SpiceName()})')
# DC sources at 0V potential are equivalent to a 0 resistance path to ground.
biases = list(self.region.dc_biases.values()) + self.biases
if biases:
spice_test += '\n** dc biases\n'
num_dc_biases = 1
for dc_bias in biases:
bias_v = dc_bias.value or self.default_fixed_dc_bias_v
spice_test += f'.NODESET {dc_bias.wire.SpiceName()} {bias_v}\n'
num_dc_biases += 1
if self.region.loads:
spice_test += '\n** simulated loads\n'
num_caps = 1
for load in self.region.loads.values():
spice_test += f'C{num_caps} {load.wire.SpiceName()} {self.ground_name} C={load.value}\n'
num_caps += 1
for fft_spec in self.fft_specs:
spice_test += '\n' + fft_spec.SpiceLine()
spice_test += textwrap.dedent(f"""
.TRAN {self.step_size_fs}f {self.duration_ps}p
.PRINT TRAN FORMAT=GNUPLOT {' '.join(sorted(print_list))}
""")
for delay_measurement in self.delay_measurements:
targ_name = delay_measurement.sink_wire.SpiceName()
targ_value = str(delay_measurement.sink_value) or str(self.vdd_v/2)
delay_computation = self.manifest.delay_computations.add()
if delay_measurement.source_wire:
trig_name = delay_measurement.source_wire.SpiceName()
delay_computation.trigger_node = trig_name
trig_value = str(delay_measurement.source_value) or str(self.vdd_v/2)
variable_name = delay_measurement.name or f'{trig_name}_to_{targ_name}_delay'
spice_test += (
f'.MEASURE TRAN {variable_name} TRIG V({trig_name})={trig_value} '
f'TARG V({targ_name})={targ_value}\n')
else:
variable_name = delay_measurement.name or f'{targ_name}_time'
spice_test += (
f'.MEASURE TRAN {variable_name} WHEN V({targ_name})={targ_value}\n')
delay_computation.spice_variable_name = variable_name.upper()
delay_computation.target_node = targ_name
for measurement in self.other_measurements:
target_name = measurement.target_wire.SpiceName()
measure_type = measurement.measure_type
measure_spec = spice.Measurement.MEASURE_TYPE_TO_XYCE[measure_type]
variable_name = measurement.name or f'{target_name}_{measure_spec}'
measure_pb = self.manifest.measurements.add()
measure_pb.spice_variable_name = variable_name.upper()
measure_pb.target_node = target_name
spice_test += (
f'.MEASURE TRAN {variable_name} {measure_spec} V({target_name})')
if measurement.target_value:
spice_test += f'={measurement.target_value}'
if measurement.from_time:
spice_test += f' FROM={measurement.from_time}'
spice_test += '\n'
# This is the full matrix of input to output delays.
# TODO(growly): Express as more general spice.DelayMeasurements that are
# passed in.
for driver in self.region.simulated_drivers.values():
trig_name = driver.wire.SpiceName()
#spice_test += f'.MEASURE TRAN {node_name}_cross WHEN V({node_name})={self.vdd_v / 2}\n'
for probe in self.region.voltage_probes.values():
targ_name = probe.wire.SpiceName()
#spice_test += f'.MEASURE TRAN {node_name}_cross WHEN V({node_name})={self.vdd_v / 2}\n'
variable_name = f'{trig_name}_to_{targ_name}_delay'
spice_test += f'.MEASURE TRAN {variable_name} TRIG V({trig_name})={self.vdd_v/2} TARG V({targ_name})={self.vdd_v/2}\n'
delay_computation = self.manifest.delay_computations.add()
delay_computation.spice_variable_name = variable_name.upper()
delay_computation.trigger_node = trig_name
delay_computation.target_node = targ_name
# Measurements of signals in the subcircuit.
for delay_measurement in self.region.subcircuit_delay_measurements:
trig_name = f'X0:{delay_measurement.source_wire.SpiceName()}'
targ_name = f'X0:{delay_measurement.sink_wire.SpiceName()}'
variable_name = f'{trig_name}_to_{targ_name}_delay'
spice_test += f'.MEASURE TRAN {variable_name} TRIG V({trig_name})={self.vdd_v/2} TARG V({targ_name})={self.vdd_v/2}\n'
delay_computation = self.manifest.delay_computations.add()
delay_computation.spice_variable_name = variable_name.upper()
delay_computation.trigger_node = trig_name
delay_computation.target_node = targ_name
spice_test += '.END\n'
with open(self.test_file_name, 'w') as f:
f.write(spice_test)
print(f'wrote {self.test_file_name}')
class LinearAnalysisTest(SpiceTestHarness):
class Type(Enum):
Y = 1
Z = 2
S = 3
H = 4
TYPE_TO_PROTO = {
Type.Y: manifest_pb.LinearAnalysis.Type.Y,
Type.Z: manifest_pb.LinearAnalysis.Type.Z,
Type.S: manifest_pb.LinearAnalysis.Type.S,
Type.H: manifest_pb.LinearAnalysis.Type.H
}
def __init__(self, design, region, test_manifest, spice_libs,
output_directory=None,
include_subckt=None,
subckt_name=None,
parameter_type=Type.Y,
start_freq_hz=1E0,
stop_freq_hz=100E12,
num_points=100,
tags=[]):
super().__init__(design,
region,
spice_libs,
subckt_name=subckt_name,
output_directory=output_directory,
include_subckt=include_subckt,
tags=tags)
if include_subckt:
root = include_subckt.removesuffix('.sp')
else:
root = os.path.join(self.output_directory, region.name)
self.test_file_name = f'{root}.linear{parameter_type.name}.sp'
self.description = (
f'Linear {parameter_type.name}-parameter test for region '
f'"{self.region.name}"')
self.start_freq_hz = start_freq_hz
self.stop_freq_hz = stop_freq_hz
self.num_points = num_points
self.parameter_type = parameter_type
for linear in test_manifest.linear_analyses:
if linear.spice_source_file == self.test_file_name:
print('warning: overwriting existing test entry in manifest for '
f'{linear.spice_source_file}')
test_manifest.linear_analyses.remove(linear)
self.manifest = test_manifest.linear_analyses.add()
self.manifest.design_region_name = region.name
self.manifest.analysis_type = LinearAnalysisTest.TYPE_TO_PROTO[parameter_type]
self.manifest.spice_source_file = self.test_file_name
self.manifest.sweep_type = manifest_pb.LinearAnalysis.SweepType.DECADE
self.manifest.start_freq_hz = self.start_freq_hz
self.manifest.stop_freq_hz = self.stop_freq_hz
self.manifest.num_points = self.num_points
self.manifest.tags.extend(self.tags)
def ReportComment(self):
loads = ' '.join(map(lambda load: load.wire.SpiceName(),
list(self.region.loads.values())))
ports = ' '.join(map(lambda port: port.wire.SpiceName(),
list(self.region.port_network_ports.values())))
dc_biases = ' '.join(map(lambda dc_bias: dc_bias.wire.SpiceName(), self.region.dc_biases))
return textwrap.dedent(f"""\
** bigspicy report:
** loads: {loads}
** ports: {ports}
** fixed nets (dc sources) @ {self.default_fixed_dc_bias_v}V: {dc_biases}
""")
def Write(self):
spice_test = self.DeckPreamble()
# When performing N-port network analysis:
if not self.region.port_network_ports:
raise RuntimeError('need ports for Linear test')
num_dc_sources = 0
print_list = []
if self.region.dc_sources:
spice_test += '\n** dc sources\n'
for dc_source in self.region.dc_sources.values():
potential_v = dc_source.value or self.default_fixed_dc_bias_v
spice_test += f'VSRC{num_dc_sources} {dc_source.wire.SpiceName()} {self.ground_name} DC {potential_v}'
num_dc_sources += 1
spice_test += '\n** N-port ports\n'
num_ports = 0
for port in self.region.port_network_ports.values():
port_pb = self.manifest.ports.add()
port_pb.number = num_ports + 1
port_pb.node = port.wire.SpiceName()
port_pb.generating_impedance_ohms = 0
if port.dc_bias is not None:
param = port.dc_bias
node_name = port.wire.SpiceName() + '_syn'
spice_test += (f'V{num_dc_sources} {port.wire.SpiceName()} '
f'{node_name} DC {{{param.name}}}\n')
num_dc_sources += 1
else:
node_name = port.wire.SpiceName()
spice_test += f'P{num_ports} {node_name} {self.ground_name} port={num_ports+1} z0=0\n'
num_ports += 1
# DC sources at 0V potential are equivalent to a 0 resistance path to ground.
if self.region.dc_biases:
spice_test += '\n** dc biases\n'
num_dc_biases = 0
for dc_bias in self.region.dc_biases.values():
spice_test += f'.NODESET {dc_bias.wire.SpiceName()} 0\n'
num_dc_biases += 1
if self.region.loads:
spice_test += '\n** simulated loads ommitted for linear analysis\n'
#num_caps = 0
#for load in self.region.loads:
# spice_test += f'C{num_caps} {load.wire.SpiceName()} {self.ground_name} C={load.value}\n'
# num_caps += 1
spice_test += '\n' + self.StepStatements()
spice_test += textwrap.dedent(f"""
.AC DEC {self.num_points} {self.start_freq_hz} {self.stop_freq_hz}
.PRINT AC FORMAT=CSV
.LIN LINTYPE={self.parameter_type.name}
.END
""")
with open(self.test_file_name, 'w') as f:
f.write(spice_test)
print(f'wrote {self.test_file_name}')
class LinearAnalysisResults:
def __init__(self):
self.ac_params = None
self.ac_analysis = None
self.ports = []
self.tags = []
class SpiceAnalyser:
def __init__(self, design, output_directory, spice_libs):
self.design = design
self.spice_writer = spice.SpiceWriter(design)
self.output_directory = output_directory
self.spice_libs = spice_libs
self.regions = {}
self.manifest = manifest_pb.TestManifest()
self.analysis = analysis_pb.CircuitAnalysis()
# A sparse matrix of the delays (plural!) measured between some source
# and sink wire. A wire is a net - a signal and an index.
self.wire_delays = collections.defaultdict(
lambda: collections.defaultdict(list))
def LoadRegionList(self, region_list):
self.regions = {region.name: region for region in region_list}
def _LoadDesignRegionsFromAnalysis(self):
regions = []
for region_pb in self.analysis.design_regions:
region = circuit.DesignRegion([])
region.name = region_pb.name
region.dut_type = PROTO_TO_DUT_TYPE[region_pb.dut_type]
# We need to have the complete module loaded for this to make sense.
if region.dut_type in (
circuit.DesignRegion.DUTType.SUB_REGION,
circuit.DesignRegion.DUTType.MODULE):
module = self.design.known_modules[region_pb.for_top_module]
else:
module = self.design.external_modules[region_pb.for_top_module]
region.module = module
for instance_name in region_pb.instances:
region.instances.append(module.instances[instance_name])
for dc_bias in region_pb.dc_biases:
wire = SpiceAnalyser._NetToWire(module, dc_bias.net)
region.dc_biases[wire.SpiceName()] = spice.DCVoltageSource(wire)
for voltage_probe in region_pb.voltage_probes:
wire = SpiceAnalyser._NetToWire(module, voltage_probe.net)
region.voltage_probes[wire.SpiceName()] = spice.VoltageProbe(wire)
for driver in region_pb.drivers:
wire = SpiceAnalyser._NetToWire(module, driver.net)
region.simulated_drivers[wire.SpiceName()] = spice.SimulatedDriver(wire)
for port_pb in region_pb.ports:
wire = SpiceAnalyser._NetToWire(module, port_pb.net)
spice_port = spice.Port(wire)
spice_port.load_capacitance = NumericalValue(port_pb.load_capacitance_f)
region.port_network_ports[wire.SpiceName()] = spice_port
region.loads = []
regions.append(region)
self.LoadRegionList(regions)
def _LoadTestManifest(self):
for linear in self.manifest.linear_analyses:
try:
region = self.regions[linear.design_region_name]
except KeyError:
continue
ports = {port.wire.SpiceName(): port
for port in region.port_network_ports.values()}
for test_port in linear.ports:
try:
port = ports[test_port.node]
port.number = test_port.number
except KeyError:
continue
def _ReadProtos(self, manifest_proto_path, analysis_proto_path):
with open(manifest_proto_path, 'rb') as f:
self.manifest.ParseFromString(f.read())
with open(analysis_proto_path, 'rb') as f:
self.analysis.ParseFromString(f.read())
self._LoadDesignRegionsFromAnalysis()
self._LoadTestManifest()
@staticmethod
def _NetToWire(module, net_pb):
if type(module) is circuit.Module:
signal_name = net_pb.signal_name
signal = module.signals[signal_name]
index = net_pb.index
return circuit.Wire(signal, index)
elif type(module) is circuit.ExternalModule:
signal = module.ports[net_pb.signal_name].signal
return circuit.Wire(signal, net_pb.index)
@staticmethod
def _NameToWire(module, spice_name, strip_prefixes=False):
def SplitIndex(string):
match = re.match('^(.*)\.(\d+)$', string)
if not match:
return string, 0
return match.group(1), int(match.group(2))
name = spice_name
if strip_prefixes:
name = SpiceAnalyser._StripStringPrefix(name, 'X0')
name, index = SplitIndex(name)
if type(module) is circuit.ExternalModule:
try:
signal = module.ports[name].signal
return circuit.Wire(signal, index)
except KeyError:
print(f'Could not find port for external module from spice net {spice_name}')
try:
signal = module.signals[name]
return circuit.Wire(signal, index)
except KeyError:
print(f'Could not find signal and index for spice net {spice_name}')
return None
@staticmethod
def _StripStringPrefix(string, prefix):
if string.startswith(prefix):
return string[len(prefix) + 1:]
return string
def _ReadTransientResults(self, tags=None):
tags_set = set(tags) if tags else None
regions = []
for transient in self.manifest.transient_analyses:
if tags_set and not tags_set.intersection(set(transient.tags)):
continue
region_name = transient.design_region_name
try:
region = self.regions[region_name]
except KeyError as e:
print(f'Region not found: {region_name}; test: {transient}')
continue
module = region.module
regions.append(region)
strip_prefixes = False
if region.dut_type == circuit.DesignRegion.DUTType.MODULE:
strip_prefixes = True
# NOTE(growly): Xyce variable names are printed uppercase. We have to
# make our matches case-insensitive.
# NOTE(growly): We should include in the test manifest what kinds of
# results to expect. For example, the .mt0 files will only be created if
# the test has a .MEASURE statement. Likewise, .fft0 will only be created
# if there are .FFT statements.
measure_results_file = f'{transient.spice_source_file}.mt0'
delays = {}
for delay_computation in transient.delay_computations:
trigger = delay_computation.trigger_node
target = delay_computation.target_node
variable_name = delay_computation.spice_variable_name.upper()
delays[variable_name] = (trigger, target)
others = {}
for measurement in transient.measurements:
others[measurement.spice_variable_name] = None
measured = spice_util.ReadMeasurementsFile(measure_results_file)
for key, value in measured.items():
variable_name = key.upper()
if variable_name in others:
others[variable_name] = value
continue
try:
trigger, target = delays[variable_name]
except KeyError as e:
print(f'Unexpected measurement "{variable_name}" in file '
f'{measure_results_file} for {transient}')
continue
try:
trigger_wire = SpiceAnalyser._NameToWire(
module, trigger, strip_prefixes)
except:
trigger_wire = None
try:
target_wire = SpiceAnalyser._NameToWire(
module, target, strip_prefixes)
except:
trigger_wire = None
if trigger_wire and target_wire:
self.wire_delays[trigger_wire][target_wire].append(
(transient.tags, value, transient))
else:
region.other_delays.append(
(variable_name, trigger, target, value, transient))
region.other_measurements[measure_results_file] = (
others, transient)
fft_results_file = f'{transient.spice_source_file}.fft0'
fft = spice_util.ReadFFTFile(fft_results_file)
# Just store results per signal name, don't bother resolving to
# Signal/Wire objects.
# TODO(growly): To track additional dimensionality to FFT results, just
# as we do for LinearAnalysisResults, contain them in an 'FFTResult'
# object or similar.
region.fft_results[fft_results_file] = fft
probe_results_file = f'{transient.spice_source_file}.prn'
probe_results = spice_util.ReadPrintFileForTimeSeries(probe_results_file)
if 'TIME' in probe_results:
time = probe_results['TIME']
for key, series in probe_results.items():
if key in ('TIME', 'Index'):
continue
match = SIGNAL_FROM_XYCE_V_STATEMENT_RE.match(key)
if match:
signal_name = match.group(1)
series = probe_results[key]
region.probe_results[
signal_name] = np.array([time, series]).transpose()
region.transient_pbs.append(transient)
return regions
def _ReadLinearResults(self, tags=None):
tags_set = set(tags) if tags else None
regions = []
for linear in self.manifest.linear_analyses:
if tags_set and not tags_set.intersection(set(linear.tags)):
continue
region_name = linear.design_region_name
try:
region = self.regions[region_name]
except KeyError as e:
print(f'Region not found: {region_name}; test: {linear}')
continue
num_ports = len(region.port_network_ports)
linear_sweep_file = f'{linear.spice_source_file}.s{num_ports}p'
linear_step_file = f'{linear.spice_source_file}.res'
module = region.module
regions.append(region)
results = LinearAnalysisResults()
results.tags.extend(linear.tags)
ports_pb = sorted(linear.ports, key=lambda x: x.number)
for port in ports_pb:
wire = SpiceAnalyser._NameToWire(module, port.node)
results.ports.append(wire)
results.ac_analysis = spice_util.ReadACAnalysisFile(linear_sweep_file)
results.ac_params = spice_util.ReadStepFile(linear_step_file)
region.linear_analyses = results
region.linear_pbs.append(linear)
return regions
def _GetEffectiveLoadCapacitanceForSpicePort(self, port):
if port.load_capacitance:
return port.load_capacitance
wire = port.wire
signal = wire.signal
index = wire.index
possible_ports = signal.FindLoadPorts(index=index)
if not possible_ports:
return None
# Just take the first one.
port_name, module, load_port = possible_ports.pop()
if type(module) is circuit.ExternalModule:
return module.MakeReasonableGuessAtInputCapacitanceForPort(port_name, index)
return None
def _ApproximateDelaysFromAdmittances(self, region, results):
# TODO(growly): Same problems as _FindSmallSignalInputCapacitance.
results = region.linear_analyses
if not results or not results.ac_analysis:
return
num_ports = len(region.port_network_ports)
print(f'approximating delay from {num_ports}-port network Y parameters '
f'for {region.name}')
module = region.module
for step, ac in results.ac_analysis.items():
# We don't have multiple params for these runs yet:
params = results.ac_params[step] if step in results.ac_params else None
if params:
raise NotImplementedError('can\'t do approximations per step yet')
num_points = len(ac)
phase_delays = collections.defaultdict(lambda: collections.defaultdict(
lambda: np.zeros((num_points, 2))))
for spice_port in region.port_network_ports.values():
# Here we deal only with numpy data structures, so indices are 0-based,
# as is sane.
i = spice_port.number - 1
# We load all ports but i with the input capacitance we expect for the
# module.
load_capacitances = np.zeros(num_ports)
for other_spice_port in region.port_network_ports.values():
if other_spice_port is spice_port:
continue
load = self._GetEffectiveLoadCapacitanceForSpicePort(other_spice_port)
if load is not None:
load_capacitances[other_spice_port.number - 1] = load.InBaseUnits().value
frequencies_hz = []
for k, (freq_hz, small_signal_params) in enumerate(ac.items()):
frequencies_hz.append(freq_hz)
Y = small_signal_params.matrix + np.diag(
load_capacitances * np.complex(0, 1) * 2 * np.pi * freq_hz)
# Set up system to solve. Fix input port current to 1 and other to 0,
# since they are not independent.
I = np.zeros(num_ports)
I[i] = 1.0
V = np.linalg.solve(Y, I)
# Overall input admittance at port i:
#Y_in = 1/V[i]
period = 1/freq_hz
for other_spice_port in region.port_network_ports.values():
if other_spice_port is spice_port:
continue
j = other_spice_port.number - 1
transfer_i_j = V[j]/V[i]
phase = np.angle(transfer_i_j)
phase_delay = -phase/(2*np.pi)*period
# We have the phase_delay of the freq_hz harmonic component from
# input i to output j.
phase_delays[spice_port][other_spice_port][k, 0] = freq_hz
phase_delays[spice_port][other_spice_port][k, 1] = phase_delay
return phase_delays
def ReportWholeModuleInputRamps(self):
# Separate regions from the module test:
sub_regions = []
whole_module_regions = []
for region in self.regions.values():
if region.HasResultsForTag('module_test'):
whole_module_regions.append(region)
if region.HasResultsForTag('region_test'):
sub_regions.append(region)
sub_region_drivers = []
for region in sub_regions:
sub_region_drivers.extend(region.simulated_drivers.values())
print(f'will extract input ramps from {len(sub_regions)} regions in '
f'{len(whole_module_regions)} whole module regions')
for region in whole_module_regions:
results_by_signal = region.probe_results
if not results_by_signal:
continue
signals_to_plot = [
driver.wire.SpiceName().upper()
for driver in region.simulated_drivers.values()] + [
'X0:' + driver.wire.SpiceName().upper()
for driver in sub_region_drivers]
for spice_name in signals_to_plot:
if spice_name not in results_by_signal:
continue
print(f'extracting probe data for {spice_name} in {region.name}')
results = results_by_signal[spice_name]
time = results[:, 0]
values = results[:, 1]
# Centre graphs around VDD/2.
min_y = min(values)
max_y = max(values)
half_y = (max_y - min_y)/2 + min_y
x_centre = None
for i, y in enumerate(values):
if y > half_y:
x_centre = time[i]
break
if x_centre is not None:
window = 60E-11 # seconds
x_min = x_centre - window/2
x_min_index = 0
x_max = x_centre + window/2
x_max_index = len(values)
for i, x in enumerate(time):
if x >= x_min and x_min_index == 0:
x_min_index = i
if x >= x_max and x_max_index == len(values):
x_max_index = i
values = values[x_min_index:x_max_index]
time = time[x_min_index:x_max_index]
h = plt.figure()
plt.plot(time, values)
file_name = f'auto.{region.name}.{spice_name}.input_ramp.png'
save_path = os.path.join(self.output_directory, file_name)
plt.title(f'{spice_name} ramp, {region.name}')
plt.xlabel('time (s)')
plt.ylabel('voltage (V)')
#plt.show()
plt.savefig(save_path)
plt.close(h)
def AnalyseModuleTests(self,
manifest_proto_path,
analysis_proto_path,
csv_file_path):
self._ReadProtos(manifest_proto_path, analysis_proto_path)
tags = ['module_test', 'region_test']
self._ReadTransientResults(tags=tags)
self._ReadLinearResults(tags=tags)
#self.ReportWholeModuleInputRamps()
# TODO(you): Other analysis can go here.
if csv_file_path:
self.DumpRegionTestDelayMeasurements(csv_file_path)
def DumpRegionTestDelayMeasurements(self, csv_file_name):
headers = set()
rows = []
for source, sinks in self.wire_delays.items():
for sink, values in sinks.items():
row = {
'source': source.SpiceName(),
'sink': sink.SpiceName()
}
for tags, measurement, _ in values:
tag = tags[0] if tags else 'none'
row[tag] = measurement
headers.add(tag)
rows.append(row)
with open(csv_file_name, 'w') as f:
field_names = ['source', 'sink'] + sorted(headers)
csv_writer = csv.DictWriter(f, field_names)