SINGr 0.0.1.dev2__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,127 @@
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, 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
+
78
+ def perform_waveform_analysis(
79
+ df: pd.DataFrame, key:str,
80
+ clock_frequency:float, v_high:float,
81
+ v_low:float, threshold_pct:float,
82
+ datastream: Optional[List[int]]=None, visualise:bool=True,
83
+ output_report:bool=True
84
+ ):
85
+ '''
86
+ The waveform analysis categorises all clock periods into RISE, FALL, HIGH and LOW
87
+ and uses these categories to assess rise/fall time (90%-10%), slew rate, settling time
88
+ overshoot and undershoot.
89
+
90
+ Parameters
91
+ ----------
92
+ df : pd.DataFrame
93
+ DataFrame containing all InSPICE simulation data
94
+ key : str
95
+ column of df containing the data to analyse
96
+ clock_frequency : float
97
+ frequency in Hz at which the transitions are supposed to be occurring
98
+ v_high : float
99
+ logic HIGH voltage
100
+ v_low : float
101
+ logic LOW voltage
102
+ threshold_pct : float
103
+ threshold percent of high-low voltage range about each logic level at which point the logic level is reached
104
+ statistical_jitter_s : float
105
+ any statistical jitter to apply !! Experimental !!
106
+ datastream : Optional[List[int]]
107
+ a series of data values (currently only 0,1 supported) to check for a match
108
+ visualise : bool, optional
109
+ generate plots if true
110
+ output_report : bool, optional
111
+ generate html output report if true
112
+ '''
113
+ transitions_df = capture_transitions(df, key, clock_frequency, v_high, v_low, threshold_pct, datastream)
114
+ transition_features = characterise_transitions(transitions_df, key, v_high, v_low, threshold_pct)
115
+
116
+ if visualise or output_report:
117
+
118
+ grid = sns.relplot(
119
+ transitions_df, y=key, x='period_time', col='event',
120
+ kind='line', estimator=None, units='period_index',
121
+ alpha=0.33, col_wrap=2, col_order=['rise', 'fall', 'high', 'low']
122
+ )
123
+ grid.figure.suptitle(f'Waveform Analysis {key.capitalize()}')
124
+ grid.set_axis_labels('Time (s)', 'Voltage (V)')
125
+ transition_features = {key: f'{val:.3E}' for key, val in transition_features.items()}
126
+ if visualise:
127
+ plt.show()
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,154 @@
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
+ Usage Note: Statistical Jitter must be given in terms of the standard deviation of jitter to be
34
+ applied to the distribution. If a maximum jitter is known, treat it as a 3 sigma value and divide
35
+ it by 3 to use as the `statistical_jitter_s` argument.
36
+
37
+ TODO: Add chunking settings for eyes that have more clock periods such as where distortions are
38
+ caused by lower frequency signals coupling into the data line.
39
+ '''
40
+
41
+ chunk_df = chunk_data_for_eye(transitions_df)
42
+ num_bins_v = 300
43
+ num_bins_per_period = 300
44
+ hist, x_edges, y_edges = histogram2d(
45
+ chunk_df[key],
46
+ chunk_df['chunk_time'],
47
+ bins=[num_bins_v, num_bins_per_period*3],
48
+ density=True
49
+ )
50
+
51
+ if statistical_jitter_s > 0:
52
+ # create filter kernel 6 sigma wide in each direction
53
+ # the number of samples per standard deviation is the period divided by the statistical jitter
54
+ six_sig = linspace(-6, 6, ceil(chunk_df['chunk_time'].max()/statistical_jitter_s)*6*2)
55
+ kernel = norm.pdf(six_sig)
56
+ # apply the kernel as a time spread by convolving the pdf (total sum of 1 to conserve total power)
57
+ # with the histogram (overlay of all signal periods)
58
+ for row_idx in range(500):
59
+ hist[row_idx,:] = fftconvolve(hist[row_idx,:], kernel, 'same')
60
+
61
+ # identify logic levels
62
+ if signaling == 'NRZ' or signaling == 'RZ':
63
+ logic_levels = 2
64
+ elif signaling == 'PAM4':
65
+ logic_levels = 4
66
+ elif signaling == 'PAM6':
67
+ logic_levels = 6
68
+ else:
69
+ raise NotImplementedError(f'Signaling method {signaling} not supported')
70
+
71
+ hist_measurements = {}
72
+ # Perform K-Means clustering based on the expected number of voltage levels
73
+ clusters, centers = kmeans1d.cluster(chunk_df[key], logic_levels)
74
+ chunk_df['cluster'] = clusters
75
+
76
+ # estimate voltage levels by making shorth estimates of the mean from the clustered observations
77
+ lms_estimates = []
78
+ for grp, data in chunk_df.groupby('cluster'):
79
+ observations = data[key].sort_values(ignore_index=True)
80
+ h = int(floor(len(observations)/2) + 1)
81
+ top_obs = list(observations[h:-1])
82
+ bottom_obs = list(observations[0:h-1])
83
+ intervals = [a-b for a, b in zip(top_obs, bottom_obs)]
84
+ min_interval = argmin(intervals)
85
+ lms_estimates.append(mean([top_obs[min_interval], bottom_obs[min_interval]]))
86
+
87
+ # estimate the eye center time by finding the clustered crossing voltage at the halfway points
88
+ # between each pair of estimated voltage levels
89
+ t_left = []
90
+ t_right = []
91
+ for i in range(1, logic_levels):
92
+ midpoint_v = (lms_estimates[i-1]+lms_estimates[i])/2
93
+ tol_v = (lms_estimates[i]-lms_estimates[i-1])*0.01
94
+ cluster_df = chunk_df.where(abs(chunk_df[key]-midpoint_v) < tol_v).dropna()
95
+ clusters, centers = kmeans1d.cluster(cluster_df['chunk_time'], 2)
96
+ cluster_df['cluster'] = clusters
97
+ t_left.append(
98
+ cluster_df['chunk_time'].where(
99
+ cluster_df['cluster'] == 0
100
+ ).max()
101
+ )
102
+ t_right.append(
103
+ cluster_df['chunk_time'].where(
104
+ cluster_df['cluster'] == 1
105
+ ).min()
106
+ )
107
+ t_mid = (max(t_left)+min(t_right))/2
108
+ hist_measurements.update({'t_mid': t_mid})
109
+
110
+ # using the time +/-2.5% about the centre of the central eye estimate voltage levels
111
+ dividers = [chunk_df[key].min()]
112
+ for space in diff(lms_estimates)/2:
113
+ dividers.append(space)
114
+ dividers.append(chunk_df[key].max())
115
+ t_tol = abs(0.025*(max(t_left)-min(t_right)))
116
+ mins = []
117
+ maxes = []
118
+ means = []
119
+ for i in range(logic_levels):
120
+
121
+ division_df = chunk_df.where(
122
+ dividers[i] <= chunk_df[key]
123
+ ).where(
124
+ chunk_df[key] <= dividers[i+1]
125
+ ).where(
126
+ abs(chunk_df['chunk_time']-t_mid) < t_tol
127
+ ).dropna()
128
+
129
+ hist_measurements.update({f'logic_{i}':division_df[key].mean()})
130
+ mins.append(division_df[key].min())
131
+ maxes.append(division_df[key].max())
132
+ means.append(division_df[key].mean())
133
+ if i > 0:
134
+ hist_measurements.update({f'eye_height_{i-1}': mins[i]-maxes[i-1]})
135
+ hist_measurements.update({f'eye_amplitude_{i-1}': means[i]-means[i-1]})
136
+
137
+ for i in range(1, logic_levels):
138
+ midpoint_v = (means[i-1]+means[i])/2
139
+ tol_v = (means[i]-means[i-1])*0.01
140
+ cluster_df = chunk_df.where(abs(chunk_df[key]-midpoint_v) < tol_v).dropna()
141
+ clusters, centers = kmeans1d.cluster(cluster_df[key], 2)
142
+ cluster_df['cluster'] = clusters
143
+ t_left = cluster_df[key].where(
144
+ cluster_df['cluster'] == 0
145
+ ).max()
146
+ t_right = cluster_df[key].where(
147
+ cluster_df['cluster'] == 1
148
+ ).min()
149
+ hist_measurements.update({f'eye_width_{i-1}':t_right-t_left})
150
+
151
+ return chunk_df, hist_measurements
152
+
153
+ def apply_mask(mask, eye):
154
+ pass
SINGr/model.py ADDED
@@ -0,0 +1,160 @@
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
+ property_vals += str(values[row][col]) + ' '
111
+ property_vals += ' '
112
+ _tline_str += property_vals
113
+ _tline_str = _tline_str + ' \n'
114
+
115
+ spice_str = _tline_str
116
+ subcircuit_card_path = Path(lib_path, f'{model_name}.lib')
117
+ with open(subcircuit_card_path, 'w+') as fp:
118
+ fp.write(spice_str)
119
+ return CoupledTlineModel(
120
+ model_name=model_name, component_name='Coupled Transmission Line',
121
+ subcircuit_card=spice_str, lib=subcircuit_card_path,
122
+ spice_model_name=model_name, num_lines=num_lines
123
+ )
124
+
125
+ class IBISModel(Model):
126
+ '''
127
+ Extension of Model object to implement reading in IBIS files using ecdtools and pybis2SPICE and generating ngSPICE
128
+ subcircuit strings out of them.
129
+ '''
130
+
131
+ @classmethod
132
+ 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:
133
+ if stimulus == 'ALL' or stimulus is None:
134
+ spice_model_name = f'{model_name}_{io_type}_{corner}'
135
+ subcircuit_card_path = Path(lib_path, f'{model_name}_{component_name}_{corner}_{io_type}.lib')
136
+ else:
137
+ spice_model_name = f'{model_name}_{io_type}_{corner}_{stimulus}'
138
+ subcircuit_card_path = Path(lib_path, f'{model_name}_{component_name}_{corner}_{io_type}_{stimulus}.lib')
139
+ if subcircuit_card_path.name in os.listdir(Path(lib_path)):
140
+ spice_str = open(subcircuit_card_path, 'r').read()
141
+ return IBISModel(model_name=model_name, component_name=component_name, subcircuit_card=spice_str, lib=subcircuit_card_path, spice_model_name=spice_model_name)
142
+ try:
143
+ ibis = ecd.load_file(Path(lib_path) / ibis_file, transform=True)
144
+ except FileNotFoundError as e:
145
+ e.add_note(f"IBIS Model file: {ibis_file} not found.")
146
+ raise e
147
+
148
+ model = dm.DataModel(ibis_file=ibis, model_name=model_name, component_name=component_name)
149
+ if stimulus == 'ALL':
150
+ subcircuit_card_path = Path(lib_path, f'{model_name}_{component_name}_{corner}_{io_type}.lib')
151
+ else:
152
+ subcircuit_card_path = Path(lib_path, f'{model_name}_{component_name}_{corner}_{io_type}_{stimulus}.lib')
153
+ spice_str = ckt_build.generate_spice_model_file(io_type, 'ngSPICE', model, corner, truncation=0.01, stimulus=stimulus, output_filepath=subcircuit_card_path)
154
+
155
+ 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)
156
+
157
+ class TerminationModel(Model):
158
+ @classmethod
159
+ def build_model_from_file(cls, *args, **kwargs) -> Model:
160
+ raise NotImplementedError
SINGr/net_builder.py ADDED
@@ -0,0 +1,160 @@
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
+ circ = traverse_net_tree_and_build(node_out, tree_level+1, circ)
146
+
147
+ if not series_termination:
148
+ tline_outs.append(name_node_out)
149
+ else:
150
+ tline_outs.append(name_series_node)
151
+
152
+ # Add transmission line model
153
+ circ.include(net_tree.transmission_line.lib)
154
+ circ.CoupledMulticonductorLine(
155
+ f'TLINE', *tline_outs, circ.gnd,
156
+ *tline_ins, circ.gnd, length=net_tree.l_tline_m,
157
+ model=net_tree.transmission_line.model_name
158
+ )
159
+
160
+ return circ
SINGr/runner.py ADDED
@@ -0,0 +1,114 @@
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['pin_out_0_0'] = pd.Series(results['pin_out_0_0'], dtype=np.float64, name='pin_out_0_0')
91
+ results_df['time'] = pd.Series(results.time, dtype=np.float64, name='time')
92
+ if "EYE" in composition.analyses:
93
+ perform_eye_analysis(
94
+ results_df,
95
+ 'pin_out_0_0',
96
+ composition.net_tree.clock_frequencies_Hz[0],
97
+ composition.net_tree.v_logic[0][1],
98
+ composition.net_tree.v_logic[0][0],
99
+ 0.9,
100
+ 0,
101
+ visualise=visualise,
102
+ output_report=output_report
103
+ )
104
+ if "WAVEFORM" in composition.analyses:
105
+ perform_waveform_analysis(
106
+ results_df,
107
+ 'pin_out_0_0',
108
+ composition.net_tree.clock_frequencies_Hz[0],
109
+ composition.net_tree.v_logic[0][1],
110
+ composition.net_tree.v_logic[0][0],
111
+ 0.9,
112
+ visualise=visualise,
113
+ output_report=output_report
114
+ )
SINGr/signal_tools.py ADDED
@@ -0,0 +1,178 @@
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
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 in df_walk.itertuples():
20
+ if isclose(row[1], logic_level_v, atol=v_tol):
21
+ return row[2]
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
+
36
+ window_length = 10
37
+ derivative_threshold = min_transition_slope*window_length
38
+ mean_diff_df = df.diff(window_length).mean()
39
+ dxdt = mean_diff_df[key]
40
+ end_state_voltage = df.iloc[-1-window_length:-1][key].mean()
41
+ if dxdt > derivative_threshold and end_state_voltage >= v_high_th:
42
+ df['event'] = 'rise'
43
+ return df
44
+ elif dxdt < -derivative_threshold and end_state_voltage <= v_low_th:
45
+ df['event'] = 'fall'
46
+ return df
47
+ else:
48
+ if df[key].median()>v_high_th:
49
+ df['event'] = 'high'
50
+ return df
51
+ elif df[key].median()<v_low_th:
52
+ df['event'] = 'low'
53
+ return df
54
+ else:
55
+ df['event'] = None
56
+ return df
57
+
58
+ def capture_transitions(
59
+ df: pd.DataFrame, key:str,
60
+ clock_frequency:float, v_high:float,
61
+ v_low:float, threshold_pct:float,
62
+ datastream:Optional[List] = None
63
+ ) -> pd.DataFrame:
64
+ '''
65
+ Reads a datastream and triggers on valid logic transition, before classifying every
66
+ clock period thereafter. Classifies into simple binary logic events of 'high', 'low',
67
+ 'rising', 'falling' or None if no valid event can be classified due to the signal
68
+ staying mostly in between the logic thresholds.
69
+
70
+ Returns a resampled and fully classified time series dataframe with equidistant time
71
+ samples at 1000 samples per period.
72
+
73
+ TODO: If a datastream is provided,
74
+ the data will be classified by matching with the datastream.
75
+
76
+ TODO: Implement parallel option as this is completely parallelisable after triggering
77
+ has occurred.
78
+ '''
79
+
80
+ v_high_th = v_low+(v_high-v_low)*threshold_pct
81
+ v_low_th = v_high-(v_high-v_low)*threshold_pct
82
+ clock_period = 1/clock_frequency
83
+ min_transition_slope = (v_high_th-v_low_th)/1000/2
84
+ resolving_sample_period = clock_period/1000
85
+ min_delay = clock_period
86
+ hold = False
87
+ t_transition = 0
88
+ triggered = False
89
+ first_edge_rising = False
90
+ # Use smoothed signal to find a transition
91
+ resample_time = linspace(min_delay, df['time'].max(), num=int(ceil((df['time'].max()-min_delay)/resolving_sample_period)))
92
+ df_trim = df.where(df['time']>=min_delay).dropna()
93
+ interp_data: BSpline = make_interp_spline(y=df_trim[key], x=df_trim['time'])
94
+ df_resampled = pd.DataFrame({key: interp_data(resample_time), 'time': resample_time})
95
+ df_smoothed = df_resampled.rolling(window=10).median().dropna(ignore_index=True)
96
+ for i in range(1, len(df_smoothed.index)):
97
+ if triggered:
98
+ break
99
+ if not hold:
100
+ # Check to see if signal deviates outside of logic level
101
+ if df_smoothed[key][i] - df_smoothed[key][i-1] < -min_transition_slope and df_smoothed[key][i] < v_high_th:
102
+ hold = True
103
+ t_transition = df['time'][i]
104
+ first_edge_rising = False
105
+ elif df_smoothed[key][i] - df_smoothed[key][i-1] > min_transition_slope and df_smoothed[key][i] > v_low_th:
106
+ hold = True
107
+ t_transition = df_smoothed['time'][i]
108
+ first_edge_rising = True
109
+ else:
110
+ continue
111
+ else:
112
+ # Check to see if signal has completed a transition from one level to the next
113
+ is_high_to_low = first_edge_rising and df[key][i] < df[key][i-1] and df[key][i] < v_low_th
114
+ is_low_to_high = not first_edge_rising and df[key][i] > df[key] [i-1] and df[key][i] > v_high_th
115
+ if is_high_to_low or is_low_to_high:
116
+ if t_transition + df['time'][i] >= clock_period:
117
+ triggered = True
118
+ t_transition = walk_forward_to_logic_level(
119
+ df,
120
+ t_transition,
121
+ v_low if is_high_to_low else v_high,
122
+ v_high*0.01
123
+ )
124
+ break
125
+ else:
126
+ hold = False
127
+ if not triggered:
128
+ raise Exception()
129
+
130
+ # take signal from half a clock period before the transition
131
+ df_trig = df_resampled.where(df_resampled['time']>=t_transition-clock_period).dropna(ignore_index=True)
132
+ # rezero the time of the data signal from the triggered point
133
+ df_trig['time'] = df_trig['time']-df_trig['time'][0]
134
+ df_classified = pd.DataFrame()
135
+ for _, data in df_trig.groupby(df_trig.index // 1000):
136
+ period_df = classify_period(data, key, v_high_th, v_low_th, min_transition_slope)
137
+ period_df['period_index'] = floor(period_df['time'].min()/clock_period)
138
+ period_df['period_time'] = period_df['time']-period_df['time'].min()
139
+ df_classified = pd.concat(
140
+ [
141
+ df_classified,
142
+ period_df
143
+ ]
144
+ )
145
+ return df_classified
146
+
147
+ def characterise_transitions(
148
+ transitions_df: pd.DataFrame, key:str,
149
+ v_high:float, v_low:float,
150
+ threshold_pct:float
151
+ ) -> Dict:
152
+ '''
153
+ Takes all transitions and measures transition features including rise/fall time
154
+ slew rates, settling time, overshoot and undershoot. Mean values across the whole
155
+ dataset are given.
156
+
157
+ TODO: Potentially add preshoot analysis and ringing analysis.
158
+ '''
159
+
160
+ v_tol = (v_high-v_low)*(1-threshold_pct)
161
+ v_low_th = v_low+v_tol
162
+ v_high_th = v_high-v_tol
163
+ measurements_dict = {}
164
+ edge_v = v_high_th-v_low_th
165
+ mid_v = edge_v/2+v_low_th
166
+ edge_df = transitions_df.where((transitions_df['event'] == 'rise')|(transitions_df['event'] == 'fall')).dropna()
167
+ for edge, data in edge_df.where(abs(edge_df[key]-mid_v)<=mid_v).dropna().groupby('event'):
168
+ edge_sign = 1 if edge=='rise' else -1
169
+ measurements_dict.update({f'{edge.capitalize()} Time': data.groupby('period_index').apply(lambda period: period['time'].max()-period['time'].min()).mean()})
170
+ measurements_dict.update({f'Slew Rate {edge.capitalize()}': edge_v/measurements_dict[f'{edge.capitalize()} Time']*edge_sign})
171
+
172
+ measurements_dict.update({
173
+ 'Overshoot': edge_df.where(edge_df['event']=='rise').dropna().groupby('period_index').max(numeric_only=True).mean()[key]-v_high,
174
+ 'Undershoot': edge_df.where(edge_df['event']=='fall').dropna().groupby('period_index').min(numeric_only=True).mean()[key]-v_low,
175
+ 'Settling Time': edge_df.groupby('period_index').apply(lambda period: period['period_time'].where(abs(period[key]-mid_v)<=mid_v).max()).mean()
176
+ })
177
+
178
+ 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,48 @@
1
+ Metadata-Version: 2.3
2
+ Name: SINGr
3
+ Version: 0.0.1.dev2
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.6
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
+ ## Contribution
35
+ Developers can contribute to the tool by forking the repository and submitting pull requests.
36
+
37
+ ## Issues and Feature Requests
38
+ * Please record any bugs, issues and feature requests here: https://github.com/Jamanaman/SINGr/issues
39
+ * 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.
40
+
41
+ ## References
42
+ 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.
43
+
44
+ Eye Diagram analysis was implemented using a PAM4 Eye-Diagram Analysis algorithm [1] using Least Median of Squares mode estimation instead of shorth mode estimation [2].
45
+
46
+ [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)
47
+
48
+ [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)
@@ -0,0 +1,14 @@
1
+ SINGr/__init__.py,sha256=RvzXLz2i9SsNS1221ynD5Q6CIMQbKbSnIiiesCvdImU,70
2
+ SINGr/analysis.py,sha256=1qvLV2NjzBl4P2_MxcxgJQtMMPyzpiahkXgpm5YOlmA,5350
3
+ SINGr/composition.py,sha256=psGMKwmyr_qOuzuVJxS0YmxTWAri8x86P55NVKg4H8I,2908
4
+ SINGr/eye_tools.py,sha256=wEihYkr344wh7cwPAglgROt0oVQBgdXK8ZADeikXOMs,6330
5
+ SINGr/model.py,sha256=gVtHUzdcnZeruX4EP0opXeRvKODpuCp0tIzv3vCykLA,6966
6
+ SINGr/net_builder.py,sha256=-9PinAISCmV2V1Ry5EaQSVAqXrL70NdyUtZs0ETpiWQ,7174
7
+ SINGr/runner.py,sha256=Jz31RVZMbZAPNxHSETozk7o05b7JyGIAZauYl0FMWgg,4402
8
+ SINGr/signal_tools.py,sha256=8Hhjl30b1kp1dboRwyvwxXmdpSPGb_hhgW28t-3W8Lw,7603
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.dev2.dist-info/WHEEL,sha256=4OL6Foqnnp3xRY5wMkjgc25_i5YJC6dKsC6LPcjqEoU,80
13
+ singr-0.0.1.dev2.dist-info/METADATA,sha256=qsTM0R2Vc0xwaK3vcetTKSxCp7MTiRG7eshfnhLMiDs,3022
14
+ singr-0.0.1.dev2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.12.5
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any