SINGr 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
SINGr/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from importlib.metadata import version
2
+
3
+ __version__ = version("SINGr")
SINGr/analysis.py ADDED
@@ -0,0 +1,129 @@
1
+ '''
2
+ Module containing all analysis workflows implemented in SINGr.
3
+ Implemented analyses include:
4
+ - Eye Analysis (only NRZ/PAM2 signalling are supported)
5
+ - Waveform Analysis
6
+ '''
7
+
8
+ import pandas as pd
9
+ import seaborn as sns
10
+ import matplotlib.pyplot as plt
11
+ from typing import List, Optional, Literal
12
+
13
+ from .signal_tools import capture_transitions, characterise_transitions
14
+ from .eye_tools import generate_eye_histogram
15
+
16
+ _ANALYSES = Literal['EYE', 'WAVEFORM']
17
+ sns.set_theme("paper", "whitegrid","tab20")
18
+
19
+ def generate_report():
20
+ '''
21
+ [WIP] Target v0.0.2
22
+ '''
23
+ pass
24
+
25
+ def perform_eye_analysis(
26
+ df: pd.DataFrame, key:str,
27
+ clock_frequency:float, v_high:float,
28
+ v_low:float, threshold_pct:float,
29
+ statistical_jitter_s: float=0, datastream: Optional[List[int]]=None,
30
+ visualise:bool=False, output_report:bool=True
31
+ ):
32
+ '''
33
+ The eye analysis assesses groups all transitions into overlapping sets of 3
34
+ and then overlays all groups to measure eye height, width, amplitude and logic levels.
35
+
36
+ Parameters
37
+ ----------
38
+ df : pd.DataFrame
39
+ DataFrame containing all InSPICE simulation data
40
+ key : str
41
+ column of df containing the data to analyse
42
+ clock_frequency : float
43
+ frequency in Hz at which the transitions are supposed to be occurring
44
+ v_high : float
45
+ logic HIGH voltage
46
+ v_low : float
47
+ logic LOW voltage
48
+ threshold_pct : float
49
+ threshold percent of high-low voltage range about each logic level at which point the logic level is reached
50
+ statistical_jitter_s : float
51
+ any statistical jitter to apply !! Experimental !!
52
+ datastream : Optional[List[int]]
53
+ a series of data values (currently only 0,1 supported) to check for a match
54
+ visualise : bool, optional
55
+ generate plots if true
56
+ output_report : bool, optional
57
+ generate html output report if true
58
+ '''
59
+ transitions_df = capture_transitions(df, key, clock_frequency, v_high, v_low, threshold_pct, datastream)
60
+
61
+ chunk_df, hist_measurements = generate_eye_histogram(transitions_df, key, statistical_jitter_s)
62
+ if visualise or output_report:
63
+ threshold_dist = (v_high-v_low)*(1-threshold_pct)
64
+ ax = sns.lineplot(chunk_df, x='chunk_time', y=key, units='sequence', estimator=None, alpha=0.2, label=None, color="tab:orange")
65
+ ax.set_title(f'Eye Diagram {key.capitalize()}')
66
+ ax.set_xlabel('Volts (V)')
67
+ # TODO time prefix for key for easier legibility
68
+ ax.set_ylabel('Time (s)')
69
+ ax.hlines([v_low, v_high], xmin=0, xmax=chunk_df['chunk_time'].max(), linestyles='dashed', label='Expected Voltage Levels', colors='r')
70
+ ax.fill_between([chunk_df['chunk_time'].min(), chunk_df['chunk_time'].max()], v_low+threshold_dist, v_low-threshold_dist, alpha=0.2, color='r')
71
+ ax.fill_between([chunk_df['chunk_time'].min(), chunk_df['chunk_time'].max()], v_high+threshold_dist, v_high-threshold_dist, alpha=0.2, color='r')
72
+ ax.legend()
73
+ ax.set_xlim(chunk_df['chunk_time'].min(), chunk_df['chunk_time'].max())
74
+ hist_measurements = {key: f'{val:.3E}' for key, val in hist_measurements.items()}
75
+ if visualise:
76
+ plt.show()
77
+ print('\n'.join([f'|{key}: {val}|' for key, val in hist_measurements.items()]))
78
+
79
+ def perform_waveform_analysis(
80
+ df: pd.DataFrame, key:str,
81
+ clock_frequency:float, v_high:float,
82
+ v_low:float, threshold_pct:float,
83
+ datastream: Optional[List[int]]=None, visualise:bool=True,
84
+ output_report:bool=True
85
+ ):
86
+ '''
87
+ The waveform analysis categorises all clock periods into RISE, FALL, HIGH and LOW
88
+ and uses these categories to assess rise/fall time (90%-10%), slew rate, settling time
89
+ overshoot and undershoot.
90
+
91
+ Parameters
92
+ ----------
93
+ df : pd.DataFrame
94
+ DataFrame containing all InSPICE simulation data
95
+ key : str
96
+ column of df containing the data to analyse
97
+ clock_frequency : float
98
+ frequency in Hz at which the transitions are supposed to be occurring
99
+ v_high : float
100
+ logic HIGH voltage
101
+ v_low : float
102
+ logic LOW voltage
103
+ threshold_pct : float
104
+ threshold percent of high-low voltage range about each logic level at which point the logic level is reached
105
+ statistical_jitter_s : float
106
+ any statistical jitter to apply !! Experimental !!
107
+ datastream : Optional[List[int]]
108
+ a series of data values (currently only 0,1 supported) to check for a match
109
+ visualise : bool, optional
110
+ generate plots if true
111
+ output_report : bool, optional
112
+ generate html output report if true
113
+ '''
114
+ transitions_df = capture_transitions(df, key, clock_frequency, v_high, v_low, threshold_pct, datastream)
115
+ transition_features = characterise_transitions(transitions_df, key, v_high, v_low, threshold_pct)
116
+
117
+ if visualise or output_report:
118
+
119
+ grid = sns.relplot(
120
+ transitions_df, y=key, x='period_time', col='event',
121
+ kind='line', estimator=None, units='period_index',
122
+ alpha=0.33, col_wrap=2, col_order=['rise', 'fall', 'high', 'low']
123
+ )
124
+ grid.figure.suptitle(f'Waveform Analysis {key.capitalize()}')
125
+ grid.set_axis_labels('Time (s)', 'Voltage (V)')
126
+ transition_features = {key: f'{val:.3E}' for key, val in transition_features.items()}
127
+ if visualise:
128
+ plt.show()
129
+ print('\n'.join([f'|{key}: {val}|' for key, val in transition_features.items()]))
SINGr/composition.py ADDED
@@ -0,0 +1,62 @@
1
+ '''
2
+ Module comprised of Pydantic BaseModel \'Composition\' which
3
+ enables one to compose an ngSPICE simulation to be run from
4
+ a configuration.
5
+ '''
6
+
7
+ from pydantic import BaseModel
8
+ from typing import List, Optional, Tuple
9
+ from .analysis import _ANALYSES
10
+ from .model import Model
11
+
12
+ class Composition(BaseModel):
13
+ '''
14
+ Compositions are simulation recipes comprising of a structure to simulate, configured specifically
15
+ and a series of simulation and analysis workflows to perform on said structure.
16
+ '''
17
+ name: str
18
+ '''name of the composition, used for identification'''
19
+ analyses: List[_ANALYSES]
20
+ '''a list of simulation and analysis workflows to run on the given net tree'''
21
+ net_tree: CommunicationNet
22
+ '''the structure to be simulated'''
23
+
24
+ class CommunicationNet(BaseModel):
25
+ '''
26
+ The CommunicationNet is a structure intended to be used recursively with each net being built
27
+ around a transmission line. At each of the inputs of the transmission line, one can connect:
28
+
29
+ - an input node which may either be a simple SPICE node name or may be a subcircuit model to connect to,
30
+ - and a termination which may either be in series with the input node and transmission line input or parallel
31
+
32
+ At each of the outputs of the transmission line, one can connect:
33
+
34
+ - an output node which may either be a simple SPICE node name, a subcircuit model to connect to or even another communication net,
35
+ - and a termination which may either be in series with the output node and transmission line output or parallel,
36
+
37
+ For all input nodes, one can also specify a number of configuration features including clock frequency, stimulus delay, logic levels,
38
+ and stimulus definition.
39
+
40
+ The transmission line that connects these nodes must simply be another model which provides sufficient input and output nodes for all inputs
41
+ and outputs. If this is a model configurable with length such as a distributed RLC model, one can also specify the length of the transmission line.
42
+ '''
43
+ t_line_nodes_in: List[Model|str]
44
+ '''connections at input nodes'''
45
+ t_line_nodes_out: List[Model|CommunicationNet|str]
46
+ '''connections at output nodes'''
47
+ transmission_line: Model
48
+ '''transmission line model'''
49
+ l_tline_m: float = 0
50
+ '''transmission line length'''
51
+ clock_frequencies_Hz: List[Optional[float]] = []
52
+ '''input stimulus clock frequencies'''
53
+ delays_s: List[Optional[float]] = []
54
+ '''stimulus delays in seconds'''
55
+ v_logic: List[Optional[Tuple[Optional[float], float]]] = []
56
+ '''logic levels (currently only 2)'''
57
+ stimuli: List[Optional[str|int]] = []
58
+ '''input stimuli corresponding to the input nodes'''
59
+ terminations_start: List[Optional[Model]] = []
60
+ '''terminations connected at the input nodes'''
61
+ terminations_end: List[Optional[Model]] = []
62
+ '''terminations connected at the output nodes'''
SINGr/eye_tools.py ADDED
@@ -0,0 +1,173 @@
1
+ '''
2
+ Module containing all functions which enable one to build, visualise and characterise
3
+ signal eye diagrams.
4
+ '''
5
+
6
+ from numpy import histogram2d, floor, ceil, linspace, mean, diff, argmin
7
+ from scipy.signal import fftconvolve
8
+ from scipy.stats import norm
9
+ import kmeans1d
10
+ import pandas as pd
11
+
12
+ def chunk_data_for_eye(transitions_df: pd.DataFrame, chunk_periods:int=3):
13
+ '''
14
+ Chunk the available data into consecutive sequences which can be identified as valid events.
15
+ '''
16
+ chunk_df = pd.DataFrame()
17
+ for chunk, data in transitions_df.groupby(transitions_df['period_index'] // chunk_periods):
18
+ data['sequence'] = chunk if not None in data['event'].unique() else None
19
+ data['chunk_time'] = data['time']-data['time'].min()
20
+ data['sequence_events'] = ' '.join([event for event in data['event'].unique()])
21
+ chunk_df = pd.concat([chunk_df, data], ignore_index=True)
22
+ chunk_df=chunk_df.dropna(ignore_index=True)
23
+ return chunk_df
24
+
25
+ def generate_eye_histogram(
26
+ transitions_df: pd.DataFrame, key:str,
27
+ statistical_jitter_s:float, signaling:str = 'NRZ'
28
+ ):
29
+ '''
30
+ Generate 2d histogram to be visualised as the eye diagram and apply any statistical jitter to it.
31
+ Eye features will also be measured.
32
+
33
+ Note The 2D histogram is not currently output for plotting in preference of the overlay of
34
+ all voltage traces.
35
+
36
+ Eye measurements are performed using methods detailed in:
37
+
38
+ [1] Jargon, J. and Cheron, J. (2021), A Robust Algorithm for PAM4 Eye-Diagram Analysis, Proceedings of the Asia Pacific Microwave Conference, Brisbane, AU, [online], https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=932331 (Accessed June 29, 2026)
39
+
40
+ [2] Jargon, Jeffrey & Wang, Chih-Ming Jack & Hale, Paul. (2008). A Robust Algorithm for Eye-Diagram Analysis. Journal of Lightwave Technology. 26. 3592-3600. [online], https://ieeexplore.ieee.org/document/4758639 (Accessed June 29, 2026)
41
+
42
+ The algorithm works as follows:
43
+ - k-means clustering performed to make a first guess of logic levels
44
+ - least mean of squares method used to estimate the mode of each cluster to more accurately estimate the logic levels
45
+ - take midpoints between estimated logic levels to estimate crossing voltages
46
+ - use k-means clustering to group voltages about transition times to find the mean crossing times at the right and left of the eye
47
+ - take the midpoint of crossing times to estimate the eye center time
48
+ - use the voltages occuring central 5% of the eye in time to calculate the logic levels using estimated voltage levels of the eye
49
+ - calculate the eye height and amplitude using the minimum and mean distances between logic levels respectively
50
+ - use more accurate estimates of logic levels to find the crossing voltages and measure the eye width at these voltages
51
+
52
+ Usage Note: Statistical Jitter must be given in terms of the standard deviation of jitter to be
53
+ applied to the distribution. If a maximum jitter is known, treat it as a 3 sigma value and divide
54
+ it by 3 to use as the `statistical_jitter_s` argument.
55
+
56
+ TODO: Add chunking settings for eyes that have more clock periods such as where distortions are
57
+ caused by lower frequency signals coupling into the data line.
58
+ '''
59
+
60
+ chunk_df = chunk_data_for_eye(transitions_df)
61
+ num_bins_v = 300
62
+ num_bins_per_period = 300
63
+ hist, x_edges, y_edges = histogram2d(
64
+ chunk_df[key],
65
+ chunk_df['chunk_time'],
66
+ bins=[num_bins_v, num_bins_per_period*3],
67
+ density=True
68
+ )
69
+
70
+ if statistical_jitter_s > 0:
71
+ # create filter kernel 6 sigma wide in each direction
72
+ # the number of samples per standard deviation is the period divided by the statistical jitter
73
+ six_sig = linspace(-6, 6, ceil(chunk_df['chunk_time'].max()/statistical_jitter_s)*6*2)
74
+ kernel = norm.pdf(six_sig)
75
+ # apply the kernel as a time spread by convolving the pdf (total sum of 1 to conserve total power)
76
+ # with the histogram (overlay of all signal periods)
77
+ for row_idx in range(500):
78
+ hist[row_idx,:] = fftconvolve(hist[row_idx,:], kernel, 'same')
79
+
80
+ # identify logic levels
81
+ if signaling == 'NRZ' or signaling == 'RZ':
82
+ logic_levels = 2
83
+ elif signaling == 'PAM4':
84
+ logic_levels = 4
85
+ elif signaling == 'PAM6':
86
+ logic_levels = 6
87
+ else:
88
+ raise NotImplementedError(f'Signaling method {signaling} not supported')
89
+
90
+ hist_measurements = {}
91
+ # Perform K-Means clustering based on the expected number of voltage levels
92
+ clusters, centers = kmeans1d.cluster(chunk_df[key], logic_levels)
93
+ chunk_df['cluster'] = clusters
94
+
95
+ # estimate voltage levels by making least mean of squares estimates of the mean from the clustered observations
96
+ lms_estimates = []
97
+ for grp, data in chunk_df.groupby('cluster'):
98
+ observations = data[key].sort_values(ignore_index=True)
99
+ h = int(floor(len(observations)/2) + 1)
100
+ top_obs = list(observations[h:-1])
101
+ bottom_obs = list(observations[0:h-1])
102
+ intervals = [a-b for a, b in zip(top_obs, bottom_obs)]
103
+ min_interval = argmin(intervals)
104
+ lms_estimates.append(mean([top_obs[min_interval], bottom_obs[min_interval]]))
105
+
106
+ # estimate the eye center time by finding the clustered crossing voltage at the halfway points
107
+ # between each pair of estimated voltage levels
108
+ t_left = []
109
+ t_right = []
110
+ for i in range(1, logic_levels):
111
+ midpoint_v = (lms_estimates[i-1]+lms_estimates[i])/2
112
+ tol_v = (lms_estimates[i]-lms_estimates[i-1])*0.01
113
+ cluster_df = chunk_df.where(abs(chunk_df[key]-midpoint_v) < tol_v).dropna()
114
+ clusters, centers = kmeans1d.cluster(cluster_df['chunk_time'], 2)
115
+ cluster_df['cluster'] = clusters
116
+ t_left.append(
117
+ cluster_df['chunk_time'].where(
118
+ cluster_df['cluster'] == 0
119
+ ).max()
120
+ )
121
+ t_right.append(
122
+ cluster_df['chunk_time'].where(
123
+ cluster_df['cluster'] == 1
124
+ ).min()
125
+ )
126
+ t_mid = (max(t_left)+min(t_right))/2
127
+ hist_measurements.update({'Time Eye Center': t_mid})
128
+
129
+ # using the time +/-2.5% about the centre of the central eye estimate voltage levels
130
+ dividers = [chunk_df[key].min()]
131
+ for space in diff(lms_estimates)/2:
132
+ dividers.append(space)
133
+ dividers.append(chunk_df[key].max())
134
+ t_tol = abs(0.025*(max(t_left)-min(t_right)))
135
+ mins = []
136
+ maxes = []
137
+ means = []
138
+ for i in range(logic_levels):
139
+
140
+ division_df = chunk_df.where(
141
+ dividers[i] <= chunk_df[key]
142
+ ).where(
143
+ chunk_df[key] <= dividers[i+1]
144
+ ).where(
145
+ abs(chunk_df['chunk_time']-t_mid) < t_tol
146
+ ).dropna()
147
+
148
+ hist_measurements.update({f'{i} Level':division_df[key].mean()})
149
+ mins.append(division_df[key].min())
150
+ maxes.append(division_df[key].max())
151
+ means.append(division_df[key].mean())
152
+ if i > 0:
153
+ hist_measurements.update({f'Eye Height {i-1}': mins[i]-maxes[i-1]})
154
+ hist_measurements.update({f'Eye Amplitude {i-1}': means[i]-means[i-1]})
155
+
156
+ for i in range(1, logic_levels):
157
+ midpoint_v = (means[i-1]+means[i])/2
158
+ tol_v = (means[i]-means[i-1])*0.01
159
+ cluster_df = chunk_df.where(abs(chunk_df[key]-midpoint_v) < tol_v).dropna()
160
+ clusters, centers = kmeans1d.cluster(cluster_df[key], 2)
161
+ cluster_df['cluster'] = clusters
162
+ t_left = cluster_df[key].where(
163
+ cluster_df['cluster'] == 0
164
+ ).max()
165
+ t_right = cluster_df[key].where(
166
+ cluster_df['cluster'] == 1
167
+ ).min()
168
+ hist_measurements.update({f'Eye Width {i-1}':t_right-t_left})
169
+
170
+ return chunk_df, hist_measurements
171
+
172
+ def apply_mask(mask, eye):
173
+ raise NotImplementedError()
SINGr/model.py ADDED
@@ -0,0 +1,163 @@
1
+ '''
2
+ Module for generation of InSpice/ngSPICE compatible models from various types of inputs.
3
+ '''
4
+
5
+ from pybis2spice import subcircuit as sckt, circuit_builder as ckt_build, data_model as dm
6
+ from ecdtools import ibis as ecd #type:ignore
7
+ from pydantic import BaseModel
8
+ from pathlib import Path
9
+ from typing import Literal, Optional
10
+ import re
11
+ import os
12
+
13
+ # supported RLGC File Sources
14
+ _SOURCE = Literal['Zuken'] # TODO add support for openEMS to generate RLGC values
15
+ _MODEL_TYPE = Literal['PIN', 'TLINE', ] # TODO add support for terminations
16
+
17
+ def build_model(model_type: _MODEL_TYPE, **kwargs) -> Model|None:
18
+ '''
19
+ Generalised model building wrapper function for the purpose of generating direct from
20
+ configuration files.
21
+
22
+ Parameters
23
+ ----------
24
+ model_type : _MODEL_TYPE
25
+ string name of model type to be generated
26
+
27
+ **kwargs: Dict
28
+ dictionary of keyword arguments which match one of the model generation functions
29
+
30
+ Returns
31
+ -------
32
+ Model|None
33
+ Generated Model object
34
+ '''
35
+ if model_type == 'PIN':
36
+ if not kwargs.get('ibis_file') is None:
37
+ return IBISModel.build_model_from_file(**kwargs)
38
+
39
+ elif model_type == 'TLINE':
40
+ if not kwargs.get('file_name') is None:
41
+ return CoupledTlineModel.build_model_from_file(**kwargs)
42
+
43
+ class Model(BaseModel):
44
+ '''
45
+ Pydantic BaseModel object setting out the required components for a model to be imported into an ngSPICE simulation
46
+ and for additional information for the user.
47
+ '''
48
+ model_name: str
49
+ '''name of model to be generated'''
50
+ component_name: str
51
+ '''name of component ie product name or component type'''
52
+ subcircuit_card: str
53
+ '''.SUBCKT file directive as a single string'''
54
+ lib: Path
55
+ '''path to directory where subcircuit card is stored'''
56
+ spice_model_name: str
57
+ '''name to be used directly for import into ngSPICE'''
58
+
59
+ @classmethod
60
+ def build_model_from_file(cls, *args, **kwargs) -> Model:
61
+ raise NotImplementedError()
62
+
63
+ class CoupledTlineModel(Model):
64
+ '''
65
+ Extension of Model object to implement reading in coupled transmission line model parameters from different sources
66
+ and using them to build a coupled multiconductor transmission line with the KSPICE models implemented in ngSPICE.
67
+ '''
68
+ num_lines:int
69
+ '''number of transmission lines'''
70
+ @classmethod
71
+ def build_model_from_file(cls, file_name:str, source:_SOURCE='Zuken', lib_path:str = '.') -> Model:
72
+ vals = [[], [], [], []]
73
+ model_name = f'cpl_{file_name.split('.')[0]}'
74
+ _tline_str = f'.MODEL {model_name} CPL length=0.1'
75
+ if source == 'Zuken':
76
+ try:
77
+ with open(Path(lib_path, file_name), 'r') as f:
78
+ idx = 0
79
+ for line in f.readlines():
80
+ if '.model' in line:
81
+ continue
82
+ elif 'Lo' in line:
83
+ idx = 0
84
+ elif 'Co' in line:
85
+ idx = 1
86
+ elif 'Ro' in line:
87
+ idx = 2
88
+ elif 'Go' in line:
89
+ idx = 3
90
+ elif 'Rs' in line:
91
+ break
92
+ else:
93
+ row = []
94
+ for val in re.findall(r'[\d.e-]+', line):
95
+ row.append(float(val))
96
+ vals[idx].append(row)
97
+
98
+ except FileNotFoundError as e:
99
+ e.add_note(f"Transmission Line RLGC Model file: {file_name} not found.")
100
+ raise e
101
+ if not len(vals[0]) == len(vals[1]) and not len(vals[2]) == len(vals[3]):
102
+ raise ValueError()
103
+ num_lines = len(vals[0])
104
+ for property, values in zip(['L', 'C', 'R', 'G'], vals):
105
+ _tline_str = _tline_str + f' {property}='
106
+ property_vals = ''
107
+ dim = len(values)
108
+ for col in range(dim):
109
+ for row in range(col, dim):
110
+ if row == col and property == 'R':
111
+ property_vals += str(1.0 if values[row][col] == 0.0 else [row][col]) + ' '
112
+ else:
113
+ property_vals += str(values[row][col]) + ' '
114
+ property_vals += ' '
115
+ _tline_str += property_vals
116
+ _tline_str = _tline_str + ' \n'
117
+
118
+ spice_str = _tline_str
119
+ subcircuit_card_path = Path(lib_path, f'{model_name}.lib')
120
+ with open(subcircuit_card_path, 'w+') as fp:
121
+ fp.write(spice_str)
122
+ return CoupledTlineModel(
123
+ model_name=model_name, component_name='Coupled Transmission Line',
124
+ subcircuit_card=spice_str, lib=subcircuit_card_path,
125
+ spice_model_name=model_name, num_lines=num_lines
126
+ )
127
+
128
+ class IBISModel(Model):
129
+ '''
130
+ Extension of Model object to implement reading in IBIS files using ecdtools and pybis2SPICE and generating ngSPICE
131
+ subcircuit strings out of them.
132
+ '''
133
+
134
+ @classmethod
135
+ def build_model_from_file(cls, model_name:str, component_name: str, ibis_file:str, io_type:sckt._IO_TYPE, corner:sckt._CORNER, stimulus:Optional[sckt._STIMULUS]='ALL', lib_path:Path|str = '.') -> Model:
136
+ if stimulus == 'ALL' or stimulus is None:
137
+ spice_model_name = f'{model_name}_{io_type}_{corner}'
138
+ subcircuit_card_path = Path(lib_path, f'{model_name}_{component_name}_{corner}_{io_type}.lib')
139
+ else:
140
+ spice_model_name = f'{model_name}_{io_type}_{corner}_{stimulus}'
141
+ subcircuit_card_path = Path(lib_path, f'{model_name}_{component_name}_{corner}_{io_type}_{stimulus}.lib')
142
+ if subcircuit_card_path.name in os.listdir(Path(lib_path)):
143
+ spice_str = open(subcircuit_card_path, 'r').read()
144
+ return IBISModel(model_name=model_name, component_name=component_name, subcircuit_card=spice_str, lib=subcircuit_card_path, spice_model_name=spice_model_name)
145
+ try:
146
+ ibis = ecd.load_file(Path(lib_path) / ibis_file, transform=True)
147
+ except FileNotFoundError as e:
148
+ e.add_note(f"IBIS Model file: {ibis_file} not found.")
149
+ raise e
150
+
151
+ model = dm.DataModel(ibis_file=ibis, model_name=model_name, component_name=component_name)
152
+ if stimulus == 'ALL':
153
+ subcircuit_card_path = Path(lib_path, f'{model_name}_{component_name}_{corner}_{io_type}.lib')
154
+ else:
155
+ subcircuit_card_path = Path(lib_path, f'{model_name}_{component_name}_{corner}_{io_type}_{stimulus}.lib')
156
+ spice_str = ckt_build.generate_spice_model_file(io_type, 'ngSPICE', model, corner, truncation=0.01, stimulus=stimulus, output_filepath=subcircuit_card_path)
157
+
158
+ return IBISModel(model_name=model.model_name, component_name=component_name, subcircuit_card=spice_str, lib=subcircuit_card_path, spice_model_name=spice_model_name)
159
+
160
+ class TerminationModel(Model):
161
+ @classmethod
162
+ def build_model_from_file(cls, *args, **kwargs) -> Model:
163
+ raise NotImplementedError
SINGr/net_builder.py ADDED
@@ -0,0 +1,161 @@
1
+ '''
2
+ Module which implements functions to recurse through a CommunicationNet Structure and build a netlist
3
+ using InSpice.
4
+ '''
5
+
6
+ from InSpice import Circuit
7
+ from typing import List, Dict
8
+ import re
9
+ from numpy.random import randint
10
+
11
+ from .model import Model
12
+ from .composition import CommunicationNet
13
+ from .sim_tools import find_subckt_line, make_pwl_from_bitstream
14
+
15
+ _NG_PARAMS = re.compile(r'(\w+)(?:=)(?:\d+)')
16
+
17
+ def instantiate_subckt_with_instance_params(
18
+ circ:Circuit, model:Model,
19
+ pins:List[str], instance_name:str = '',
20
+ custom_params: Dict = {}, default_val:str = '0'
21
+ ) -> None:
22
+ '''
23
+ Instantiates a subcircuit instance of the given subcircuit model and adds named parameters to the netlist
24
+ for later editing.
25
+
26
+ Parameters
27
+ ----------
28
+ circ: Circuit
29
+ circuit for subcircuit to be added into
30
+ model: Model
31
+ SINGr model to be used to inject subcircuit
32
+ pins: List[str]
33
+ pin names in order
34
+ instance_name: str
35
+ name of subcircuit instance
36
+ custom_params: Dict
37
+ dictionary of named parameters to add to be able to be changed parametrically
38
+ default_val: str
39
+ default value for all instance parameters if there is no preconfigured default in the custom params dict
40
+ '''
41
+ sckt_line_start, sckt_line_end = find_subckt_line(model.subcircuit_card)
42
+ param_names = re.findall(_NG_PARAMS, model.subcircuit_card[sckt_line_start:sckt_line_end])
43
+ param_dict = {}
44
+ for param_name in param_names:
45
+ instance_param_name = param_name+'_'+instance_name
46
+ circ.parameter(instance_param_name, custom_params.get(param_name, default_val))
47
+ param_dict.update({param_name: f'{{{instance_param_name}}}'})
48
+ circ.X(instance_name, model.spice_model_name, *pins, **param_dict)
49
+
50
+ def traverse_net_tree_and_build(net_tree: CommunicationNet, tree_level:int = 0, circ: Circuit = Circuit('Net_Tree')) -> Circuit:
51
+ '''
52
+ Traverses the net tree structure and progressively connects all objects. This function recurses down the net tree and builds each
53
+ communication net in turn, connecting named nodes directly and adding all required subcircuits into the circuit with appropriate
54
+ configuration.
55
+
56
+ Parameters
57
+ ----------
58
+ net_tree: CommunicationNet
59
+ net tree to be built
60
+ tree_level: int
61
+ current recursion depth
62
+ circ: Circuit
63
+ current state of InSPICE circuit to be passed through different recursive calls
64
+
65
+ Returns
66
+ -------
67
+ InSPICE circuit with completed net tree from the current depth
68
+ '''
69
+ tline_ins = []
70
+ for idx, (node_in, termination_in, stimulus, freq, delay) in enumerate(zip(net_tree.t_line_nodes_in, net_tree.terminations_start, net_tree.stimuli, net_tree.clock_frequencies_Hz, net_tree.delays_s)):
71
+ if isinstance(node_in, str):
72
+ if 'gnd' in node_in:
73
+ name_node_in = circ.gnd
74
+ else:
75
+ name_node_in = node_in
76
+ else:
77
+ name_node_in = f'pin_in_{tree_level}_{idx}'
78
+ name_series_node = f'line_in_{tree_level}_{idx}'
79
+ series_termination = False
80
+ if not termination_in is None:
81
+ circ.include(termination_in.lib)
82
+ sckt_line:str = find_subckt_line(termination_in.subcircuit_card, True)
83
+ termination_nodes = []
84
+ for entry in sckt_line.split(' ')[2:]:
85
+ if not '=' in entry:
86
+ termination_nodes.append(entry)
87
+ if len(termination_nodes) > 1:
88
+ series_termination = True
89
+ instantiate_subckt_with_instance_params(circ, termination_in, [name_node_in, name_series_node], f'start_termination_{tree_level}_{idx}')
90
+ tline_ins.append(name_series_node)
91
+ if isinstance(node_in, Model):
92
+ params_dict = {}
93
+ if not net_tree.clock_frequencies_Hz[idx] is None:
94
+ params_dict.update({'freq': net_tree.clock_frequencies_Hz[idx]})
95
+ circ.include(node_in.lib)
96
+ if 'TRIG' in node_in.subcircuit_card and stimulus == 'TRIG':
97
+ if freq is None:
98
+ raise ValueError('TRIG Stimulus given without clock frequency')
99
+ period = 1/freq
100
+ pwl_vals = make_pwl_from_bitstream(randint(2, size=128), period)
101
+ circ.PieceWiseLinearVoltageSource(
102
+ f'pwl{idx}', f'trig_{tree_level}_{idx}', circ.gnd,
103
+ pwl_vals, repeat_time=0, delay_time=delay)
104
+ instantiate_subckt_with_instance_params(circ, node_in, [name_node_in, f'trig_{tree_level}_{idx}'], f'sender_{tree_level}_{idx}')
105
+ else:
106
+ instantiate_subckt_with_instance_params(circ, node_in, [name_node_in], f'sender_{tree_level}_{idx}')
107
+ if not series_termination:
108
+ tline_ins.append(name_node_in)
109
+
110
+ # Output nodes
111
+ tline_outs = []
112
+ for idx, (node_out, termination_out) in enumerate(zip(net_tree.t_line_nodes_out, net_tree.terminations_end)):
113
+ # check if node type is string to connect directly to an arbitrary node, this can also be used to inject ground connections
114
+ if isinstance(node_out, str):
115
+ if 'gnd' in node_out:
116
+ name_node_out = circ.gnd
117
+ else:
118
+ name_node_out = node_out
119
+ else:
120
+ name_node_out = f'pin_out_{tree_level}_{idx}'
121
+ name_series_node = f'line_out_{tree_level}_{idx}'
122
+ series_termination = False
123
+
124
+ # First handle termination
125
+ if not termination_out is None:
126
+ circ.include(termination_out.lib)
127
+ sckt_line:str = find_subckt_line(termination_out.subcircuit_card, True)
128
+ termination_nodes = []
129
+ for entry in sckt_line.split(' ')[2:]:
130
+ if not '=' in entry:
131
+ termination_nodes.append(entry)
132
+ if len(termination_nodes) > 1:
133
+ series_termination = True
134
+ instantiate_subckt_with_instance_params(circ, termination_out, [name_node_out, name_series_node], f'end_termination_{tree_level}_{idx}')
135
+
136
+ # then handle node
137
+ if isinstance(node_out, Model):
138
+ params_dict = {}
139
+ if not net_tree.clock_frequencies_Hz[idx] is None:
140
+ params_dict.update({'freq': net_tree.clock_frequencies_Hz[idx]})
141
+ circ.include(node_out.lib)
142
+ instantiate_subckt_with_instance_params(circ, node_out, [name_node_out], f'receiver_{tree_level}_{idx}')
143
+ # if node is another tree then traverse deeper and recurse back up
144
+ elif type(node_out) is CommunicationNet:
145
+ node_out.t_line_nodes_in[0] = str(name_node_out)
146
+ circ = traverse_net_tree_and_build(node_out, tree_level+1, circ)
147
+
148
+ if not series_termination:
149
+ tline_outs.append(name_node_out)
150
+ else:
151
+ tline_outs.append(name_series_node)
152
+
153
+ # Add transmission line model
154
+ circ.include(net_tree.transmission_line.lib)
155
+ circ.CoupledMulticonductorLine(
156
+ f'TLINE_{tree_level}', *tline_outs, circ.gnd,
157
+ *tline_ins, circ.gnd, length=net_tree.l_tline_m,
158
+ model=net_tree.transmission_line.model_name
159
+ )
160
+
161
+ return circ
SINGr/runner.py ADDED
@@ -0,0 +1,142 @@
1
+ from InSpice.Spice.Simulator import Simulator
2
+ from InSpice.Probe.WaveForm import TransientAnalysis
3
+ from InSpice import Circuit
4
+ import pandas as pd, numpy as np
5
+ from typing import Dict
6
+
7
+ from . import net_builder as build
8
+
9
+ from .composition import Composition
10
+ from .analysis import perform_eye_analysis, perform_waveform_analysis
11
+
12
+ def compose_and_run_simulation(composition: Composition) -> TransientAnalysis:
13
+ '''
14
+ Utility function which takes a Composition object and builds the InSPICE circuit
15
+ to be simulated, calculates simulation parameters such as duration and max time step
16
+ and runs the simulation.
17
+
18
+ Parameters
19
+ ----------
20
+ composition : Composition
21
+ Structure to be simulated
22
+
23
+ Returns
24
+ -------
25
+ TransientAnalysis
26
+ Results of simulation
27
+
28
+ Raises
29
+ ------
30
+ ValueError
31
+ No clock frequency provided for an active stimulus.
32
+ '''
33
+ # determine simulation timing features incl. simulation duration, max step size, initial settling delay
34
+ # TODO apply frequency check to all layers of net tree
35
+ min_freq_to_resolve = min(composition.net_tree.clock_frequencies_Hz)
36
+ max_period_to_resolve_s = 1/(max(composition.net_tree.clock_frequencies_Hz))
37
+ IBIS_MIN_SAMPLES_PER_RISE_AND_FALL = 200
38
+ minimum_periods = 3
39
+ max_step_s = 1/min_freq_to_resolve/IBIS_MIN_SAMPLES_PER_RISE_AND_FALL
40
+ min_duration_s = max_period_to_resolve_s*minimum_periods
41
+ min_delay = 1/min_freq_to_resolve
42
+ # TODO apply delay to all levels of net tree
43
+ delays_new = []
44
+ for delay in composition.net_tree.delays_s:
45
+ if delay is None:
46
+ delays_new.append(min_delay)
47
+ else:
48
+ delays_new.append(delay+min_delay)
49
+ composition.net_tree.delays_s = delays_new
50
+ for idx, stimulus in enumerate(composition.net_tree.stimuli):
51
+ if stimulus == 'TRIG':
52
+ if not composition.net_tree.clock_frequencies_Hz[idx] is None:
53
+ min_duration_s = (128+1)/composition.net_tree.clock_frequencies_Hz[idx]
54
+ else:
55
+ raise ValueError("No clock frequency given for active stimulus.")
56
+ # compose circuit structure based on topology
57
+ circ = Circuit(composition.name)
58
+ circ: Circuit = build.traverse_net_tree_and_build(composition.net_tree, circ=circ)
59
+
60
+ simulator = Simulator.factory()
61
+ simulation = simulator.simulation(circ)
62
+ results: TransientAnalysis = simulation.transient(step_time=max_step_s/100, end_time=min_duration_s, max_time=max_step_s)
63
+ return results
64
+
65
+ def analyse_simulation_results(
66
+ composition:Composition, results:TransientAnalysis,
67
+ visualise:bool=False, output_report:bool=True,
68
+ eye_config:Dict={}, waveform_config:Dict={}
69
+ ):
70
+ '''
71
+ Wrapper function that takes simulation setup (Composition) and simulation results (TransientAnalysis)
72
+ and passes them to the required analysis workflows.
73
+
74
+ Parameters
75
+ ----------
76
+ composition : Composition
77
+ Structure that was simulated.
78
+ results : TransientAnalysis
79
+ Results data from transient analysis performed by InSPICE
80
+ visualise : bool, optional
81
+ generates plots if true
82
+ output_report : bool, optional
83
+ generates reports if true
84
+ eye_config : Dict, optional
85
+ changes the configuration of eye analysis
86
+ waveform_config : Dict, optional
87
+ changes the configuration of waveform analysis
88
+ '''
89
+ results_df = pd.DataFrame()
90
+ results_df['time'] = pd.Series(results.time, dtype=np.float64, name='time')
91
+ if "EYE" in composition.analyses:
92
+ config = {
93
+ 'key': 'pin_out_0_0',
94
+ 'clock_frequency': composition.net_tree.clock_frequencies_Hz[0],
95
+ 'v_high': composition.net_tree.v_logic[0][1],
96
+ 'v_low': composition.net_tree.v_logic[0][0],
97
+ 'threshold_pct': 0.9,
98
+ 'statistical_jitter_s': 0,
99
+ 'datastream': None,
100
+ 'visualise': True,
101
+ 'output_report': False
102
+ }
103
+ config.update(eye_config)
104
+ if not results_df.get(config['key']):
105
+ results_df[config['key']] = pd.Series(results[config['key']], dtype=np.float64, name=config['key'])
106
+ perform_eye_analysis(
107
+ results_df,
108
+ config['key'],
109
+ config['clock_frequency'],
110
+ config['v_high'],
111
+ config['v_low'],
112
+ config['threshold_pct'],
113
+ config['statistical_jitter_s'],
114
+ config['datastream'],
115
+ config['visualise'],
116
+ config['output_report']
117
+ )
118
+ if "WAVEFORM" in composition.analyses:
119
+ config = {
120
+ 'key': 'pin_out_0_0',
121
+ 'clock_frequency': composition.net_tree.clock_frequencies_Hz[0],
122
+ 'v_high': composition.net_tree.v_logic[0][1],
123
+ 'v_low': composition.net_tree.v_logic[0][0],
124
+ 'threshold_pct': 0.9,
125
+ 'datastream': None,
126
+ 'visualise': True,
127
+ 'output_report': False
128
+ }
129
+ config.update(waveform_config)
130
+ if results_df.get(config['key']) is None:
131
+ results_df[config['key']] = pd.Series(results[config['key']], dtype=np.float64, name=config['key'])
132
+ perform_waveform_analysis(
133
+ results_df,
134
+ config['key'],
135
+ config['clock_frequency'],
136
+ config['v_high'],
137
+ config['v_low'],
138
+ config['threshold_pct'],
139
+ config['datastream'],
140
+ config['visualise'],
141
+ config['output_report']
142
+ )
SINGr/signal_tools.py ADDED
@@ -0,0 +1,192 @@
1
+ '''
2
+ General utility functions for processing time series signals.
3
+ '''
4
+
5
+ from numpy import isclose, floor, ceil, linspace
6
+ from typing import List, Optional, Dict
7
+ from scipy.interpolate import make_interp_spline, BSpline
8
+ import pandas as pd
9
+
10
+ def walk_forward_to_logic_level(
11
+ df:pd.DataFrame, t_transition_detected: float,
12
+ logic_level_v:float, v_tol: float, key: str
13
+ ) -> float:
14
+ '''
15
+ Walks from transition being detected to the next logic level.
16
+ '''
17
+
18
+ df_walk = df.where(df['time']>=t_transition_detected).dropna()
19
+ for row, data in df_walk.iterrows():
20
+ if isclose(data[key], logic_level_v, atol=v_tol):
21
+ return data['time']
22
+ else:
23
+ raise Exception()
24
+
25
+ def classify_period(
26
+ df:pd.DataFrame, key:str,
27
+ v_high_th:float, v_low_th:float,
28
+ min_transition_slope:float
29
+ ) -> pd.DataFrame:
30
+ '''
31
+ Classifies time series in single clock period as one of 'high', 'low',
32
+ 'rise', 'fall' or None if no valid event can be classified due to the signal
33
+ staying mostly in between the logic thresholds.
34
+
35
+ Distinguishes between rise/fall and high/low based on if the mean slope is sufficient to
36
+ have achieved a full transition within the period and where the end voltage sits for the period.
37
+
38
+ '''
39
+
40
+ window_length = 10
41
+ derivative_threshold = min_transition_slope*window_length
42
+ mean_diff_df = df.diff(window_length).mean()
43
+ dxdt = mean_diff_df[key]
44
+ end_state_voltage = df.iloc[-1-window_length:-1][key].mean()
45
+ if dxdt > derivative_threshold and end_state_voltage >= v_high_th:
46
+ df['event'] = 'rise'
47
+ return df
48
+ elif dxdt < -derivative_threshold and end_state_voltage <= v_low_th:
49
+ df['event'] = 'fall'
50
+ return df
51
+ else:
52
+ if df[key].median()>v_high_th:
53
+ df['event'] = 'high'
54
+ return df
55
+ elif df[key].median()<v_low_th:
56
+ df['event'] = 'low'
57
+ return df
58
+ else:
59
+ df['event'] = None
60
+ return df
61
+
62
+ def capture_transitions(
63
+ df: pd.DataFrame, key:str,
64
+ clock_frequency:float, v_high:float,
65
+ v_low:float, threshold_pct:float,
66
+ datastream:Optional[List] = None
67
+ ) -> pd.DataFrame:
68
+ '''
69
+ Reads a datastream and triggers on valid logic transition, before classifying every
70
+ clock period thereafter. Classifies into simple binary logic events of 'high', 'low',
71
+ 'rising', 'falling' or None if no valid event can be classified due to the signal
72
+ staying mostly in between the logic thresholds.
73
+
74
+ Returns a resampled and fully classified time series dataframe with equidistant time
75
+ samples at 1000 samples per period.
76
+
77
+ Triggering is done as follows:
78
+ - by detecting a logic transition with a sufficient slope to suggest that it is not simply common mode drift
79
+ - once a transition is detected, it is observed if a valid logic level is maintained for at least a full clock period
80
+ - the first detected transition is then excluded from the first captured period and all subsequent periods are classified
81
+
82
+ TODO: If a datastream is provided,
83
+ the data will be classified by matching with the datastream.
84
+
85
+ TODO: Implement parallel option as this is completely parallelisable after triggering
86
+ has occurred.
87
+
88
+ TODO: Implement fallback triggering if no triggering is achieved.
89
+ '''
90
+
91
+ v_high_th = v_low+(v_high-v_low)*threshold_pct
92
+ v_low_th = v_high-(v_high-v_low)*threshold_pct
93
+ clock_period = 1/clock_frequency
94
+ min_transition_slope = (v_high_th-v_low_th)/1000/2
95
+ resolving_sample_period = clock_period/1000
96
+ min_delay = clock_period
97
+ hold = False
98
+ t_transition = 0
99
+ triggered = False
100
+ first_edge_rising = False
101
+ # Use smoothed signal to find a transition
102
+ resample_time = linspace(min_delay, df['time'].max(), num=int(ceil((df['time'].max()-min_delay)/resolving_sample_period)))
103
+ df_trim = df.where(df['time']>=min_delay).dropna()
104
+ interp_data: BSpline = make_interp_spline(y=df_trim[key], x=df_trim['time'])
105
+ df_resampled = pd.DataFrame({key: interp_data(resample_time), 'time': resample_time})
106
+ df_smoothed = df_resampled.rolling(window=10).median().dropna(ignore_index=True)
107
+ for i in range(1, len(df_smoothed.index)):
108
+ if triggered:
109
+ break
110
+ elif not hold:
111
+ # Check to see if signal deviates outside of logic level
112
+ if df_smoothed[key][i] - df_smoothed[key][i-1] < -min_transition_slope and df_smoothed[key][i] < v_high_th:
113
+ hold = True
114
+ t_transition = df['time'][i]
115
+ first_edge_rising = False
116
+ elif df_smoothed[key][i] - df_smoothed[key][i-1] > min_transition_slope and df_smoothed[key][i] > v_low_th:
117
+ hold = True
118
+ t_transition = df_smoothed['time'][i]
119
+ first_edge_rising = True
120
+ else:
121
+ continue
122
+ else:
123
+ # Check to see if signal has completed a transition from one level to the next
124
+ is_high_to_low = first_edge_rising and df_resampled[key][i] < df_resampled[key][i-1] and df_resampled[key][i] < v_low_th
125
+ is_low_to_high = not first_edge_rising and df_resampled[key][i] > df_resampled[key][i-1] and df_resampled[key][i] > v_high_th
126
+ if is_high_to_low or is_low_to_high:
127
+ if t_transition + df_resampled['time'][i] >= clock_period:
128
+ triggered = True
129
+ try:
130
+ t_transition = walk_forward_to_logic_level(
131
+ df_resampled, t_transition,
132
+ v_low if is_high_to_low else v_high,
133
+ v_high*0.01, key
134
+ )
135
+ break
136
+ except:
137
+ triggered = False
138
+ continue
139
+ else:
140
+ hold = False
141
+ if not triggered:
142
+ raise Exception()
143
+
144
+ # take signal from half a clock period before the transition
145
+ df_trig = df_resampled.where(df_resampled['time']>=t_transition-clock_period).dropna(ignore_index=True)
146
+ # rezero the time of the data signal from the triggered point
147
+ df_trig['time'] = df_trig['time']-df_trig['time'][0]
148
+ df_classified = pd.DataFrame()
149
+ for _, data in df_trig.groupby(df_trig.index // 1000):
150
+ period_df = classify_period(data, key, v_high_th, v_low_th, min_transition_slope)
151
+ period_df['period_index'] = floor(period_df['time'].min()/clock_period)
152
+ period_df['period_time'] = period_df['time']-period_df['time'].min()
153
+ df_classified = pd.concat(
154
+ [
155
+ df_classified,
156
+ period_df
157
+ ]
158
+ )
159
+ return df_classified
160
+
161
+ def characterise_transitions(
162
+ transitions_df: pd.DataFrame, key:str,
163
+ v_high:float, v_low:float,
164
+ threshold_pct:float
165
+ ) -> Dict:
166
+ '''
167
+ Takes all transitions and measures transition features including rise/fall time
168
+ slew rates, settling time, overshoot and undershoot. Mean values across the whole
169
+ dataset are given.
170
+
171
+ TODO: Potentially add preshoot analysis and ringing analysis.
172
+ '''
173
+
174
+ v_tol = (v_high-v_low)*(1-threshold_pct)
175
+ v_low_th = v_low+v_tol
176
+ v_high_th = v_high-v_tol
177
+ measurements_dict = {}
178
+ edge_v = v_high_th-v_low_th
179
+ mid_v = edge_v/2+v_low_th
180
+ edge_df = transitions_df.where((transitions_df['event'] == 'rise')|(transitions_df['event'] == 'fall')).dropna()
181
+ for edge, data in edge_df.where(abs(edge_df[key]-mid_v)<=mid_v).dropna().groupby('event'):
182
+ edge_sign = 1 if edge=='rise' else -1
183
+ measurements_dict.update({f'{edge.capitalize()} Time': data.groupby('period_index').apply(lambda period: period['time'].max()-period['time'].min()).mean()})
184
+ measurements_dict.update({f'Slew Rate {edge.capitalize()}': edge_v/measurements_dict[f'{edge.capitalize()} Time']*edge_sign})
185
+
186
+ measurements_dict.update({
187
+ 'Overshoot': edge_df.where(edge_df['event']=='rise').dropna().groupby('period_index').max(numeric_only=True).mean()[key]-v_high,
188
+ 'Undershoot': edge_df.where(edge_df['event']=='fall').dropna().groupby('period_index').min(numeric_only=True).mean()[key]-v_low,
189
+ 'Settling Time': edge_df.groupby('period_index').apply(lambda period: period['period_time'].where(abs(period[key]-mid_v)<=mid_v).max()).mean()
190
+ })
191
+
192
+ return measurements_dict
SINGr/sim_tools.py ADDED
@@ -0,0 +1,22 @@
1
+ '''
2
+ Module with generic utilities for generating simulations.
3
+ '''
4
+
5
+ from typing import List, Tuple
6
+
7
+ def make_pwl_from_bitstream(bitstream:List[int], period:float) -> List[Tuple[float]]:
8
+ '''
9
+ Make a PWL value sequence to be used in any InSpice source which implements PieceWiseLinearMixIn.
10
+ '''
11
+ pwl_vals = []
12
+ for i, v_bit in enumerate(bitstream):
13
+ pwl_vals.append((i*period, v_bit))
14
+ pwl_vals.append((i*period+period*0.99, v_bit))
15
+ return pwl_vals
16
+
17
+ def find_subckt_line(subcircuit_card: str, return_string: bool = False) -> str|Tuple[int,int]:
18
+ sckt_line_start = subcircuit_card.find('.SUBCKT')
19
+ sckt_line_end = subcircuit_card.find('\n', sckt_line_start)
20
+ if return_string:
21
+ return subcircuit_card[sckt_line_start:sckt_line_end]
22
+ return (sckt_line_start, sckt_line_end)
File without changes
@@ -0,0 +1,35 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <title>Report: {{analysis_title}}</title>
5
+ </head>
6
+ <body>
7
+ <h1>Simulation Composition Details</h1>
8
+ <table>
9
+ <tr>
10
+ {% for key in composition_metadata.keys() %}
11
+ <th scope="col">{{key}}</th>
12
+ {% endfor %}
13
+ </tr>
14
+ <tr>
15
+ {% for val in composition_metadata.values() %}
16
+ <td scope="row">{{key}}</th>
17
+ {% endfor %}
18
+ </tr>
19
+ </table>
20
+ <img class="graph" src='{{ graphic_path }}'>
21
+ <h1>{{analysis_title}} Results</h1>
22
+ <table>
23
+ <tr>
24
+ {% for key in results.keys() %}
25
+ <th scope="col">{{key}}</th>
26
+ {% endfor %}
27
+ </tr>
28
+ <tr>
29
+ {% for val in results.values() %}
30
+ <td scope="row">{{key}}</th>
31
+ {% endfor %}
32
+ </tr>
33
+ </table>
34
+ </body>
35
+ </html>
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.3
2
+ Name: SINGr
3
+ Version: 0.0.1
4
+ Summary: ngSPICE Based Signal-Integrity Simulator and Analyser.
5
+ Author: Thomas Damjanovic
6
+ Requires-Dist: numpy
7
+ Requires-Dist: seaborn
8
+ Requires-Dist: inspice>=1.7.0.5
9
+ Requires-Dist: ecdtools>=0.7.0
10
+ Requires-Dist: pybis2spice
11
+ Requires-Dist: scipy
12
+ Requires-Dist: kmeans1d
13
+ Requires-Dist: pandas
14
+ Requires-Dist: jinja2
15
+ Requires-Dist: pydantic>=2.13.4
16
+ Maintainer: Thomas Damjanovic
17
+ Requires-Python: >=3.12
18
+ Description-Content-Type: text/markdown
19
+
20
+ # SINGr: An ngSPICE SI Simulation and Analysis Tool for Automated Simulation and Optimisation Workflows
21
+
22
+ **S**ignal **I**ntegrity **ng**SPICE Analyser or SINGr (like singer) for short
23
+
24
+ This package is designed for the purpose of allowing one to specify arbitrary net topologies with modular structural components such as transmission line models, terminations, and behavioural models of components and then simulate them with a range of different workflows.
25
+
26
+ ## Features
27
+ Currently, only the base configuration structure is implemented, which uses a recursive tree structure with arbitrary node connections to allow for more complex structures. There are, however, two automated simulation and analysis workflows that have been implemented:
28
+
29
+ - **Waveform Analysis**
30
+ - This assesses all valid transitions and logic states (currently limited to NRZ/PAM2 waveforms) and provides, *rise/fall time* (at 10% and 90%), *settling time* (within 10% margin of stable value), *slew rate*, *overshoot*, and *undershoot*.
31
+ - **Eye Analysis**
32
+ - This segments a time series of logic transitions into chunks of 3 and then overlays them to assess eye width, eye height, eye amplitude, and logic levels.
33
+
34
+ For full API docs go here: https://singr.readthedocs.io/en/latest/index.html
35
+
36
+ ## Contribution
37
+ Developers can contribute to the tool by forking the repository and submitting pull requests.
38
+
39
+ ## Issues and Feature Requests
40
+ * Please record any bugs, issues and feature requests here: https://github.com/Jamanaman/SINGr/issues
41
+ * Detailed information on how any issue can be reproduced should be provided including any IBIS files used and version number of the program. Screenshots would also help.
42
+
43
+ ## References
44
+ This tool is built off of pyBIS2PICE (https://github.com/Jamanaman/pybis2spice) to translate IBIS Models that are used in SI simulations, ecdtools which allows one to parse and process ibis files, and InSpice as the interface into ngSPICE.
45
+
46
+ Eye Diagram analysis was implemented using a PAM4 Eye-Diagram Analysis algorithm [1] using Least Mean of Squares mode estimation instead of shorth mode estimation [2].
47
+
48
+ [1] Jargon, J. and Cheron, J. (2021), A Robust Algorithm for PAM4 Eye-Diagram Analysis, Proceedings of the Asia Pacific Microwave Conference, Brisbane, AU, [online], https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=932331 (Accessed June 29, 2026)
49
+
50
+ [2] Jargon, Jeffrey & Wang, Chih-Ming Jack & Hale, Paul. (2008). A Robust Algorithm for Eye-Diagram Analysis. Journal of Lightwave Technology. 26. 3592-3600. [online], https://ieeexplore.ieee.org/document/4758639 (Accessed June 29, 2026)
51
+
52
+ ![uv](https://img.shields.io/badge/uv-%23DE5FE9.svg?style=for-the-badge&logo=uv&logoColor=white)
53
+ ![Pydantic](https://img.shields.io/badge/pydantic-%23E92063.svg?style=for-the-badge&logo=pydantic&logoColor=)
54
+ ![NumPy](https://img.shields.io/badge/NumPy-%23013243.svg?style=for-the-badge&logo=numpy&logoColor=yellow)
55
+ ![Pandas](https://img.shields.io/badge/Pandas-%23150458.svg?style=for-the-badge&logo=pandas&logoColor=cyan)
56
+ ![SciPy](https://img.shields.io/badge/SciPy-%230C55A5.svg?style=for-the-badge&logo=scipy&logoColor=%white)
57
+ ![Python](https://img.shields.io/badge/python-%233670A0.svg?style=for-the-badge&logo=python&logoColor=ffdd54)
@@ -0,0 +1,14 @@
1
+ SINGr/__init__.py,sha256=RvzXLz2i9SsNS1221ynD5Q6CIMQbKbSnIiiesCvdImU,70
2
+ SINGr/analysis.py,sha256=DXOZ8wic4P_T-dOAuzyRG_keySMADFogFRGUoniVMPE,5530
3
+ SINGr/composition.py,sha256=psGMKwmyr_qOuzuVJxS0YmxTWAri8x86P55NVKg4H8I,2908
4
+ SINGr/eye_tools.py,sha256=27oKDpR-glskyVEsOm6fz7vUuWJdBL5gphC0rxG85P4,8008
5
+ SINGr/model.py,sha256=zbkgh0QWFdlfnMZY6QtRPiBok8YVGuEZbNrnx4rqetc,7150
6
+ SINGr/net_builder.py,sha256=qFPlP8OK2ydRx0PdaLEFTaHB88uhZPXlreqBRB6m4Rw,7240
7
+ SINGr/runner.py,sha256=CBuDkaAFuPksbDLL1ziQMB4i7P_K3X2e9DRjMI0gmMA,5527
8
+ SINGr/signal_tools.py,sha256=Fzjk0TRqLI1tjlzE5nnNg6H1w3sy-IN5MspmkHGqQnM,8518
9
+ SINGr/sim_tools.py,sha256=N292iMcIquKMAiL27KO-nso3WDUXphtOrQcbC90UqG0,822
10
+ SINGr/templates/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ SINGr/templates/single_sim_and_analysis_page.html.jinja2,sha256=hdSkGCxwQ0HBorp6YdXkd0VgWXk1A6gSPQi6jX8yizA,765
12
+ singr-0.0.1.dist-info/WHEEL,sha256=Lkz__M3n3EKWmzMwHnFILNW2SHO43bOxmbqnBjwb--4,80
13
+ singr-0.0.1.dist-info/METADATA,sha256=GlhlfKRWvdCgdSDhaM--HiqXnUc1OoGV8bPleKtx3sc,3733
14
+ singr-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.12.6
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any