KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sim_model.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2022 Mikolaj Wielgus
5 * Copyright (C) 2022 CERN
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 3
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22#include <wx/tokenzr.h>
23#include <ki_exception.h>
24#include <lib_symbol.h>
25#include <sch_symbol.h>
26#include <string_utils.h>
27#include <wx/regex.h>
28
29#include <iterator>
30
31#include <sim/sim_model.h>
33#include <sim/sim_model_ideal.h>
36#include <sim/sim_model_r_pot.h>
37#include <sim/sim_model_ibis.h>
42#include <sim/sim_model_tline.h>
44#include <sim/sim_lib_mgr.h>
46
47#include <boost/algorithm/string.hpp>
48#include <fmt/core.h>
49#include <pegtl/contrib/parse_tree.hpp>
50
51
53
54using TYPE = SIM_MODEL::TYPE;
55
56
57SIM_MODEL::DEVICE_INFO SIM_MODEL::DeviceInfo( DEVICE_T aDeviceType )
58{
59 switch( aDeviceType )
60 {
61 // | fieldValue | description | showInMenu |
62 // -------------------------------------------------------
63 //
64 case DEVICE_T::NONE: return { "", "", true };
65 case DEVICE_T::R: return { "R", "Resistor", true };
66 case DEVICE_T::C: return { "C", "Capacitor", true };
67 case DEVICE_T::L: return { "L", "Inductor", true };
68 case DEVICE_T::K: return { "K", "Mutual Inductance Statement", true };
69 case DEVICE_T::TLINE: return { "TLINE", "Transmission Line", true };
70 case DEVICE_T::SW: return { "SW", "Switch", true };
71
72 case DEVICE_T::D: return { "D", "Diode", true };
73 case DEVICE_T::NPN: return { "NPN", "NPN BJT", true };
74 case DEVICE_T::PNP: return { "PNP", "PNP BJT", true };
75
76 case DEVICE_T::NJFET: return { "NJFET", "N-channel JFET", true };
77 case DEVICE_T::PJFET: return { "PJFET", "P-channel JFET", true };
78
79 case DEVICE_T::NMOS: return { "NMOS", "N-channel MOSFET", true };
80 case DEVICE_T::PMOS: return { "PMOS", "P-channel MOSFET", true };
81 case DEVICE_T::NMES: return { "NMES", "N-channel MESFET", true };
82 case DEVICE_T::PMES: return { "PMES", "P-channel MESFET", true };
83
84 case DEVICE_T::V: return { "V", "Voltage Source", true };
85 case DEVICE_T::I: return { "I", "Current Source", true };
86 case DEVICE_T::E: return { "E", "Voltage Source", false };
87 case DEVICE_T::F: return { "F", "Current Source", false };
88 case DEVICE_T::G: return { "G", "Current Source", false };
89 case DEVICE_T::H: return { "H", "Voltage Source", false };
90
91 case DEVICE_T::KIBIS: return { "IBIS", "IBIS Model", false };
92
93 case DEVICE_T::SUBCKT: return { "SUBCKT", "Subcircuit", false };
94 case DEVICE_T::XSPICE: return { "XSPICE", "XSPICE Code Model", true };
95 case DEVICE_T::SPICE: return { "SPICE", "Raw SPICE Element", true };
96
97 default: wxFAIL; return {};
98 }
99}
100
101
102SIM_MODEL::INFO SIM_MODEL::TypeInfo( TYPE aType )
103{
104 switch( aType )
105 {
106 // | deviceType | fieldValue | description |
107 // ---------------------------------------------------------------------
108 //
109 case TYPE::NONE: return { DEVICE_T::NONE, "", "" };
110
111 case TYPE::R: return { DEVICE_T::R, "", "Ideal" };
112 case TYPE::R_POT: return { DEVICE_T::R, "POT", "Potentiometer" };
113 case TYPE::R_BEHAVIORAL: return { DEVICE_T::R, "=", "Behavioral" };
114
115 case TYPE::C: return { DEVICE_T::C, "", "Ideal" };
116 case TYPE::C_BEHAVIORAL: return { DEVICE_T::C, "=", "Behavioral" };
117
118 case TYPE::L: return { DEVICE_T::L, "", "Ideal" };
119 case TYPE::L_BEHAVIORAL: return { DEVICE_T::L, "=", "Behavioral" };
120
121 case TYPE::K: return { DEVICE_T::K, "", "Mutual Inductance Statement" };
122
123 case TYPE::TLINE_Z0: return { DEVICE_T::TLINE, "", "Characteristic impedance" };
124 case TYPE::TLINE_RLGC: return { DEVICE_T::TLINE, "RLGC", "RLGC" };
125
126 case TYPE::SW_V: return { DEVICE_T::SW, "V", "Voltage-controlled" };
127 case TYPE::SW_I: return { DEVICE_T::SW, "I", "Current-controlled" };
128
129 case TYPE::D: return { DEVICE_T::D, "", "" };
130
131 case TYPE::NPN_VBIC: return { DEVICE_T::NPN, "VBIC", "VBIC" };
132 case TYPE::PNP_VBIC: return { DEVICE_T::PNP, "VBIC", "VBIC" };
133 case TYPE::NPN_GUMMELPOON: return { DEVICE_T::NPN, "GUMMELPOON", "Gummel-Poon" };
134 case TYPE::PNP_GUMMELPOON: return { DEVICE_T::PNP, "GUMMELPOON", "Gummel-Poon" };
135 //case TYPE::BJT_MEXTRAM: return {};
136 case TYPE::NPN_HICUM2: return { DEVICE_T::NPN, "HICUML2", "HICUM level 2" };
137 case TYPE::PNP_HICUM2: return { DEVICE_T::PNP, "HICUML2", "HICUM level 2" };
138 //case TYPE::BJT_HICUM_L0: return {};
139
140 case TYPE::NJFET_SHICHMANHODGES: return { DEVICE_T::NJFET, "SHICHMANHODGES", "Shichman-Hodges" };
141 case TYPE::PJFET_SHICHMANHODGES: return { DEVICE_T::PJFET, "SHICHMANHODGES", "Shichman-Hodges" };
142 case TYPE::NJFET_PARKERSKELLERN: return { DEVICE_T::NJFET, "PARKERSKELLERN", "Parker-Skellern" };
143 case TYPE::PJFET_PARKERSKELLERN: return { DEVICE_T::PJFET, "PARKERSKELLERN", "Parker-Skellern" };
144
145 case TYPE::NMES_STATZ: return { DEVICE_T::NMES, "STATZ", "Statz" };
146 case TYPE::PMES_STATZ: return { DEVICE_T::PMES, "STATZ", "Statz" };
147 case TYPE::NMES_YTTERDAL: return { DEVICE_T::NMES, "YTTERDAL", "Ytterdal" };
148 case TYPE::PMES_YTTERDAL: return { DEVICE_T::PMES, "YTTERDAL", "Ytterdal" };
149 case TYPE::NMES_HFET1: return { DEVICE_T::NMES, "HFET1", "HFET1" };
150 case TYPE::PMES_HFET1: return { DEVICE_T::PMES, "HFET1", "HFET1" };
151 case TYPE::NMES_HFET2: return { DEVICE_T::NMES, "HFET2", "HFET2" };
152 case TYPE::PMES_HFET2: return { DEVICE_T::PMES, "HFET2", "HFET2" };
153
154 case TYPE::NMOS_VDMOS: return { DEVICE_T::NMOS, "VDMOS", "VDMOS" };
155 case TYPE::PMOS_VDMOS: return { DEVICE_T::PMOS, "VDMOS", "VDMOS" };
156 case TYPE::NMOS_MOS1: return { DEVICE_T::NMOS, "MOS1", "Classical quadratic (MOS1)" };
157 case TYPE::PMOS_MOS1: return { DEVICE_T::PMOS, "MOS1", "Classical quadratic (MOS1)" };
158 case TYPE::NMOS_MOS2: return { DEVICE_T::NMOS, "MOS2", "Grove-Frohman (MOS2)" };
159 case TYPE::PMOS_MOS2: return { DEVICE_T::PMOS, "MOS2", "Grove-Frohman (MOS2)" };
160 case TYPE::NMOS_MOS3: return { DEVICE_T::NMOS, "MOS3", "MOS3" };
161 case TYPE::PMOS_MOS3: return { DEVICE_T::PMOS, "MOS3", "MOS3" };
162 case TYPE::NMOS_BSIM1: return { DEVICE_T::NMOS, "BSIM1", "BSIM1" };
163 case TYPE::PMOS_BSIM1: return { DEVICE_T::PMOS, "BSIM1", "BSIM1" };
164 case TYPE::NMOS_BSIM2: return { DEVICE_T::NMOS, "BSIM2", "BSIM2" };
165 case TYPE::PMOS_BSIM2: return { DEVICE_T::PMOS, "BSIM2", "BSIM2" };
166 case TYPE::NMOS_MOS6: return { DEVICE_T::NMOS, "MOS6", "MOS6" };
167 case TYPE::PMOS_MOS6: return { DEVICE_T::PMOS, "MOS6", "MOS6" };
168 case TYPE::NMOS_BSIM3: return { DEVICE_T::NMOS, "BSIM3", "BSIM3" };
169 case TYPE::PMOS_BSIM3: return { DEVICE_T::PMOS, "BSIM3", "BSIM3" };
170 case TYPE::NMOS_MOS9: return { DEVICE_T::NMOS, "MOS9", "MOS9" };
171 case TYPE::PMOS_MOS9: return { DEVICE_T::PMOS, "MOS9", "MOS9" };
172 case TYPE::NMOS_B4SOI: return { DEVICE_T::NMOS, "B4SOI", "BSIM4 SOI (B4SOI)" };
173 case TYPE::PMOS_B4SOI: return { DEVICE_T::PMOS, "B4SOI", "BSIM4 SOI (B4SOI)" };
174 case TYPE::NMOS_BSIM4: return { DEVICE_T::NMOS, "BSIM4", "BSIM4" };
175 case TYPE::PMOS_BSIM4: return { DEVICE_T::PMOS, "BSIM4", "BSIM4" };
176 //case TYPE::NMOS_EKV2_6: return {};
177 //case TYPE::PMOS_EKV2_6: return {};
178 //case TYPE::NMOS_PSP: return {};
179 //case TYPE::PMOS_PSP: return {};
180 case TYPE::NMOS_B3SOIFD: return { DEVICE_T::NMOS, "B3SOIFD", "B3SOIFD (BSIM3 FD-SOI)" };
181 case TYPE::PMOS_B3SOIFD: return { DEVICE_T::PMOS, "B3SOIFD", "B3SOIFD (BSIM3 FD-SOI)" };
182 case TYPE::NMOS_B3SOIDD: return { DEVICE_T::NMOS, "B3SOIDD", "B3SOIDD (BSIM3 SOI)" };
183 case TYPE::PMOS_B3SOIDD: return { DEVICE_T::PMOS, "B3SOIDD", "B3SOIDD (BSIM3 SOI)" };
184 case TYPE::NMOS_B3SOIPD: return { DEVICE_T::NMOS, "B3SOIPD", "B3SOIPD (BSIM3 PD-SOI)" };
185 case TYPE::PMOS_B3SOIPD: return { DEVICE_T::PMOS, "B3SOIPD", "B3SOIPD (BSIM3 PD-SOI)" };
186 //case TYPE::NMOS_STAG: return {};
187 //case TYPE::PMOS_STAG: return {};
188 case TYPE::NMOS_HISIM2: return { DEVICE_T::NMOS, "HISIM2", "HiSIM2" };
189 case TYPE::PMOS_HISIM2: return { DEVICE_T::PMOS, "HISIM2", "HiSIM2" };
190 case TYPE::NMOS_HISIMHV1: return { DEVICE_T::NMOS, "HISIMHV1", "HiSIM_HV1" };
191 case TYPE::PMOS_HISIMHV1: return { DEVICE_T::PMOS, "HISIMHV1", "HiSIM_HV1" };
192 case TYPE::NMOS_HISIMHV2: return { DEVICE_T::NMOS, "HISIMHV2", "HiSIM_HV2" };
193 case TYPE::PMOS_HISIMHV2: return { DEVICE_T::PMOS, "HISIMHV2", "HiSIM_HV2" };
194
195 case TYPE::V: return { DEVICE_T::V, "DC", "DC", };
196 case TYPE::V_SIN: return { DEVICE_T::V, "SIN", "Sine" };
197 case TYPE::V_PULSE: return { DEVICE_T::V, "PULSE", "Pulse" };
198 case TYPE::V_EXP: return { DEVICE_T::V, "EXP", "Exponential" };
199 case TYPE::V_AM: return { DEVICE_T::V, "AM", "Amplitude modulated" };
200 case TYPE::V_SFFM: return { DEVICE_T::V, "SFFM", "Single-frequency FM" };
201 case TYPE::V_VCL: return { DEVICE_T::E, "", "Voltage-controlled" };
202 case TYPE::V_CCL: return { DEVICE_T::H, "", "Current-controlled" };
203 case TYPE::V_PWL: return { DEVICE_T::V, "PWL", "Piecewise linear" };
204 case TYPE::V_WHITENOISE: return { DEVICE_T::V, "WHITENOISE", "White noise" };
205 case TYPE::V_PINKNOISE: return { DEVICE_T::V, "PINKNOISE", "Pink noise (1/f)" };
206 case TYPE::V_BURSTNOISE: return { DEVICE_T::V, "BURSTNOISE", "Burst noise" };
207 case TYPE::V_RANDUNIFORM: return { DEVICE_T::V, "RANDUNIFORM", "Random uniform" };
208 case TYPE::V_RANDGAUSSIAN: return { DEVICE_T::V, "RANDGAUSSIAN", "Random Gaussian" };
209 case TYPE::V_RANDEXP: return { DEVICE_T::V, "RANDEXP", "Random exponential" };
210 case TYPE::V_RANDPOISSON: return { DEVICE_T::V, "RANDPOISSON", "Random Poisson" };
211 case TYPE::V_BEHAVIORAL: return { DEVICE_T::V, "=", "Behavioral" };
212
213 case TYPE::I: return { DEVICE_T::I, "DC", "DC", };
214 case TYPE::I_SIN: return { DEVICE_T::I, "SIN", "Sine" };
215 case TYPE::I_PULSE: return { DEVICE_T::I, "PULSE", "Pulse" };
216 case TYPE::I_EXP: return { DEVICE_T::I, "EXP", "Exponential" };
217 case TYPE::I_AM: return { DEVICE_T::I, "AM", "Amplitude modulated" };
218 case TYPE::I_SFFM: return { DEVICE_T::I, "SFFM", "Single-frequency FM" };
219 case TYPE::I_VCL: return { DEVICE_T::G, "", "Voltage-controlled" };
220 case TYPE::I_CCL: return { DEVICE_T::F, "", "Current-controlled" };
221 case TYPE::I_PWL: return { DEVICE_T::I, "PWL", "Piecewise linear" };
222 case TYPE::I_WHITENOISE: return { DEVICE_T::I, "WHITENOISE", "White noise" };
223 case TYPE::I_PINKNOISE: return { DEVICE_T::I, "PINKNOISE", "Pink noise (1/f)" };
224 case TYPE::I_BURSTNOISE: return { DEVICE_T::I, "BURSTNOISE", "Burst noise" };
225 case TYPE::I_RANDUNIFORM: return { DEVICE_T::I, "RANDUNIFORM", "Random uniform" };
226 case TYPE::I_RANDGAUSSIAN: return { DEVICE_T::I, "RANDGAUSSIAN", "Random Gaussian" };
227 case TYPE::I_RANDEXP: return { DEVICE_T::I, "RANDEXP", "Random exponential" };
228 case TYPE::I_RANDPOISSON: return { DEVICE_T::I, "RANDPOISSON", "Random Poisson" };
229 case TYPE::I_BEHAVIORAL: return { DEVICE_T::I, "=", "Behavioral" };
230
231 case TYPE::SUBCKT: return { DEVICE_T::SUBCKT, "", "Subcircuit" };
232 case TYPE::XSPICE: return { DEVICE_T::XSPICE, "", "" };
233
234 case TYPE::KIBIS_DEVICE: return { DEVICE_T::KIBIS, "DEVICE", "Device" };
235 case TYPE::KIBIS_DRIVER_DC: return { DEVICE_T::KIBIS, "DCDRIVER", "DC driver" };
236 case TYPE::KIBIS_DRIVER_RECT: return { DEVICE_T::KIBIS, "RECTDRIVER", "Rectangular wave driver" };
237 case TYPE::KIBIS_DRIVER_PRBS: return { DEVICE_T::KIBIS, "PRBSDRIVER", "PRBS driver" };
238
239 case TYPE::RAWSPICE: return { DEVICE_T::SPICE, "", "" };
240
241 default: wxFAIL; return {};
242 }
243}
244
245
247{
248 switch( aType )
249 {
250 // | itemType | modelType | fnName | level |isDefaultLvl|hasExpr|version|
251 // -------------------------------------------------------------------------
252 case TYPE::R: return { "R", "" };
253 case TYPE::R_POT: return { "A", "" };
254 case TYPE::R_BEHAVIORAL: return { "R", "", "", "0", false, true };
255
256 case TYPE::C: return { "C", "" };
257 case TYPE::C_BEHAVIORAL: return { "C", "", "", "0", false, true };
258
259 case TYPE::L: return { "L", "" };
260 case TYPE::L_BEHAVIORAL: return { "L", "", "", "0", false, true };
261
262 case TYPE::K: return { "K", "" };
263
264 //case TYPE::TLINE_Z0: return { "T" };
265 case TYPE::TLINE_Z0: return { "O", "LTRA" };
266 case TYPE::TLINE_RLGC: return { "O", "LTRA" };
267
268 case TYPE::SW_V: return { "S", "SW" };
269 case TYPE::SW_I: return { "W", "CSW" };
270
271 case TYPE::D: return { "D", "D" };
272
273 case TYPE::NPN_VBIC: return { "Q", "NPN", "", "4" };
274 case TYPE::PNP_VBIC: return { "Q", "PNP", "", "4" };
275 case TYPE::NPN_GUMMELPOON: return { "Q", "NPN", "", "1", true };
276 case TYPE::PNP_GUMMELPOON: return { "Q", "PNP", "", "1", true };
277 case TYPE::NPN_HICUM2: return { "Q", "NPN", "", "8" };
278 case TYPE::PNP_HICUM2: return { "Q", "PNP", "", "8" };
279
280 case TYPE::NJFET_SHICHMANHODGES: return { "J", "NJF", "", "1", true };
281 case TYPE::PJFET_SHICHMANHODGES: return { "J", "PJF", "", "1", true };
282 case TYPE::NJFET_PARKERSKELLERN: return { "J", "NJF", "", "2" };
283 case TYPE::PJFET_PARKERSKELLERN: return { "J", "PJF", "", "2" };
284
285 case TYPE::NMES_STATZ: return { "Z", "NMF", "", "1", true };
286 case TYPE::PMES_STATZ: return { "Z", "PMF", "", "1", true };
287 case TYPE::NMES_YTTERDAL: return { "Z", "NMF", "", "2" };
288 case TYPE::PMES_YTTERDAL: return { "Z", "PMF", "", "2" };
289 case TYPE::NMES_HFET1: return { "Z", "NMF", "", "5" };
290 case TYPE::PMES_HFET1: return { "Z", "PMF", "", "5" };
291 case TYPE::NMES_HFET2: return { "Z", "NMF", "", "6" };
292 case TYPE::PMES_HFET2: return { "Z", "PMF", "", "6" };
293
294 case TYPE::NMOS_VDMOS: return { "M", "VDMOS NCHAN" };
295 case TYPE::PMOS_VDMOS: return { "M", "VDMOS PCHAN" };
296 case TYPE::NMOS_MOS1: return { "M", "NMOS", "", "1", true };
297 case TYPE::PMOS_MOS1: return { "M", "PMOS", "", "1", true };
298 case TYPE::NMOS_MOS2: return { "M", "NMOS", "", "2" };
299 case TYPE::PMOS_MOS2: return { "M", "PMOS", "", "2" };
300 case TYPE::NMOS_MOS3: return { "M", "NMOS", "", "3" };
301 case TYPE::PMOS_MOS3: return { "M", "PMOS", "", "3" };
302 case TYPE::NMOS_BSIM1: return { "M", "NMOS", "", "4" };
303 case TYPE::PMOS_BSIM1: return { "M", "PMOS", "", "4" };
304 case TYPE::NMOS_BSIM2: return { "M", "NMOS", "", "5" };
305 case TYPE::PMOS_BSIM2: return { "M", "PMOS", "", "5" };
306 case TYPE::NMOS_MOS6: return { "M", "NMOS", "", "6" };
307 case TYPE::PMOS_MOS6: return { "M", "PMOS", "", "6" };
308 case TYPE::NMOS_BSIM3: return { "M", "NMOS", "", "8" };
309 case TYPE::PMOS_BSIM3: return { "M", "PMOS", "", "8" };
310 case TYPE::NMOS_MOS9: return { "M", "NMOS", "", "9" };
311 case TYPE::PMOS_MOS9: return { "M", "PMOS", "", "9" };
312 case TYPE::NMOS_B4SOI: return { "M", "NMOS", "", "10" };
313 case TYPE::PMOS_B4SOI: return { "M", "PMOS", "", "10" };
314 case TYPE::NMOS_BSIM4: return { "M", "NMOS", "", "14" };
315 case TYPE::PMOS_BSIM4: return { "M", "PMOS", "", "14" };
316 //case TYPE::NMOS_EKV2_6: return {};
317 //case TYPE::PMOS_EKV2_6: return {};
318 //case TYPE::NMOS_PSP: return {};
319 //case TYPE::PMOS_PSP: return {};
320 case TYPE::NMOS_B3SOIFD: return { "M", "NMOS", "", "55" };
321 case TYPE::PMOS_B3SOIFD: return { "M", "PMOS", "", "55" };
322 case TYPE::NMOS_B3SOIDD: return { "M", "NMOS", "", "56" };
323 case TYPE::PMOS_B3SOIDD: return { "M", "PMOS", "", "56" };
324 case TYPE::NMOS_B3SOIPD: return { "M", "NMOS", "", "57" };
325 case TYPE::PMOS_B3SOIPD: return { "M", "PMOS", "", "57" };
326 //case TYPE::NMOS_STAG: return {};
327 //case TYPE::PMOS_STAG: return {};
328 case TYPE::NMOS_HISIM2: return { "M", "NMOS", "", "68" };
329 case TYPE::PMOS_HISIM2: return { "M", "PMOS", "", "68" };
330 case TYPE::NMOS_HISIMHV1: return { "M", "NMOS", "", "73", false, false, "1.2.4" };
331 case TYPE::PMOS_HISIMHV1: return { "M", "PMOS", "", "73", false, false, "1.2.4" };
332 case TYPE::NMOS_HISIMHV2: return { "M", "NMOS", "", "73", false, false, "2.2.0" };
333 case TYPE::PMOS_HISIMHV2: return { "M", "PMOS", "", "73", false, false, "2.2.0" };
334
335 case TYPE::V: return { "V", "", "DC" };
336 case TYPE::V_SIN: return { "V", "", "SIN" };
337 case TYPE::V_PULSE: return { "V", "", "PULSE" };
338 case TYPE::V_EXP: return { "V", "", "EXP" };
339 case TYPE::V_AM: return { "V", "", "AM" };
340 case TYPE::V_SFFM: return { "V", "", "SFFM" };
341 case TYPE::V_VCL: return { "E", "", "" };
342 case TYPE::V_CCL: return { "H", "", "" };
343 case TYPE::V_PWL: return { "V", "", "PWL" };
344 case TYPE::V_WHITENOISE: return { "V", "", "TRNOISE" };
345 case TYPE::V_PINKNOISE: return { "V", "", "TRNOISE" };
346 case TYPE::V_BURSTNOISE: return { "V", "", "TRNOISE" };
347 case TYPE::V_RANDUNIFORM: return { "V", "", "TRRANDOM" };
348 case TYPE::V_RANDGAUSSIAN: return { "V", "", "TRRANDOM" };
349 case TYPE::V_RANDEXP: return { "V", "", "TRRANDOM" };
350 case TYPE::V_RANDPOISSON: return { "V", "", "TRRANDOM" };
351 case TYPE::V_BEHAVIORAL: return { "B" };
352
353 case TYPE::I: return { "I", "", "DC" };
354 case TYPE::I_PULSE: return { "I", "", "PULSE" };
355 case TYPE::I_SIN: return { "I", "", "SIN" };
356 case TYPE::I_EXP: return { "I", "", "EXP" };
357 case TYPE::I_AM: return { "I", "", "AM" };
358 case TYPE::I_SFFM: return { "I", "", "SFFM" };
359 case TYPE::I_VCL: return { "G", "", "" };
360 case TYPE::I_CCL: return { "F", "", "" };
361 case TYPE::I_PWL: return { "I", "", "PWL" };
362 case TYPE::I_WHITENOISE: return { "I", "", "TRNOISE" };
363 case TYPE::I_PINKNOISE: return { "I", "", "TRNOISE" };
364 case TYPE::I_BURSTNOISE: return { "I", "", "TRNOISE" };
365 case TYPE::I_RANDUNIFORM: return { "I", "", "TRRANDOM" };
366 case TYPE::I_RANDGAUSSIAN: return { "I", "", "TRRANDOM" };
367 case TYPE::I_RANDEXP: return { "I", "", "TRRANDOM" };
368 case TYPE::I_RANDPOISSON: return { "I", "", "TRRANDOM" };
369 case TYPE::I_BEHAVIORAL: return { "B" };
370
371 case TYPE::SUBCKT: return { "X" };
372 case TYPE::XSPICE: return { "A" };
373
374 case TYPE::KIBIS_DEVICE: return { "X" };
375 case TYPE::KIBIS_DRIVER_DC: return { "X" };
376 case TYPE::KIBIS_DRIVER_RECT: return { "X" };
377 case TYPE::KIBIS_DRIVER_PRBS: return { "X" };
378
379 case TYPE::NONE:
380 case TYPE::RAWSPICE: return {};
381
382 default: wxFAIL; return {};
383 }
384}
385
386
387TYPE SIM_MODEL::ReadTypeFromFields( const std::vector<SCH_FIELD>& aFields, bool aResolve, int aDepth,
388 REPORTER& aReporter )
389{
390 std::string deviceTypeFieldValue = GetFieldValue( &aFields, SIM_DEVICE_FIELD, aResolve, aDepth );
391 std::string typeFieldValue = GetFieldValue( &aFields, SIM_DEVICE_SUBTYPE_FIELD, aResolve, aDepth );
392
393 if( !deviceTypeFieldValue.empty() )
394 {
395 for( TYPE type : TYPE_ITERATOR() )
396 {
397 if( typeFieldValue == TypeInfo( type ).fieldValue )
398 {
399 if( deviceTypeFieldValue == DeviceInfo( TypeInfo( type ).deviceType ).fieldValue )
400 return type;
401 }
402 }
403 }
404
405 if( typeFieldValue.empty() )
406 return TYPE::NONE;
407
408 wxString reference = GetFieldValue( &aFields, FIELD_T::REFERENCE );
409
410 if( !reference.IsEmpty() )
411 {
412 aReporter.Report( wxString::Format( _( "No simulation model definition found for "
413 "symbol '%s'." ),
414 reference ),
416 }
417 else
418 {
419 aReporter.Report( _( "No simulation model definition found." ),
421 }
422
423 return TYPE::NONE;
424}
425
426
427void SIM_MODEL::ReadDataFields( const std::vector<SCH_FIELD>* aFields, bool aResolve, int aDepth,
428 std::span<const wxString> aPins )
429{
430 bool diffMode = GetFieldValue( aFields, SIM_LIBRARY_IBIS::DIFF_FIELD, aResolve, aDepth ) == "1";
431 SwitchSingleEndedDiff( diffMode );
432
433 m_serializer->ParseEnable( GetFieldValue( aFields, SIM_LEGACY_ENABLE_FIELD_V7, aResolve, aDepth ) );
434
435 createPins( aPins );
436 m_serializer->ParsePins( GetFieldValue( aFields, SIM_PINS_FIELD, aResolve, aDepth ) );
437
438 std::string paramsField = GetFieldValue( aFields, SIM_PARAMS_FIELD, aResolve, aDepth );
439
440 if( !m_serializer->ParseParams( paramsField ) )
441 m_serializer->ParseValue( GetFieldValue( aFields, SIM_VALUE_FIELD, aResolve, aDepth ) );
442}
443
444
445void SIM_MODEL::WriteFields( std::vector<SCH_FIELD>& aFields, const SCH_SHEET_PATH* aSheetPath,
446 const wxString& aVariantName ) const
447{
448 // Remove duplicate fields: they are at the end of list
449 for( size_t ii = aFields.size() - 1; ii > 0; ii-- )
450 {
451 wxString currFieldName = aFields[ii].GetName();
452
453 auto end_candidate_list = aFields.begin() + ii - 1;
454
455 auto fieldIt = std::find_if( aFields.begin(), end_candidate_list,
456 [&]( const SCH_FIELD& f )
457 {
458 return f.GetName() == currFieldName;
459 } );
460
461 // If duplicate field found: remove current checked item
462 if( fieldIt != end_candidate_list )
463 aFields.erase( aFields.begin() + ii );
464 }
465
466 SetFieldValue( aFields, SIM_DEVICE_FIELD, m_serializer->GenerateDevice(), false,
467 aSheetPath, aVariantName );
468 SetFieldValue( aFields, SIM_DEVICE_SUBTYPE_FIELD, m_serializer->GenerateDeviceSubtype(), false,
469 aSheetPath, aVariantName );
470
471 SetFieldValue( aFields, SIM_LEGACY_ENABLE_FIELD_V7, m_serializer->GenerateEnable(), false,
472 aSheetPath, aVariantName );
473 SetFieldValue( aFields, SIM_PINS_FIELD, m_serializer->GeneratePins(), false, aSheetPath, aVariantName );
474
475 SetFieldValue( aFields, SIM_PARAMS_FIELD, m_serializer->GenerateParams(), false, aSheetPath, aVariantName );
476
477 if( IsStoredInValue() )
478 SetFieldValue( aFields, SIM_VALUE_FIELD, m_serializer->GenerateValue(), false, aSheetPath, aVariantName );
479}
480
481
482std::vector<wxString> SIM_MODEL::PinNumbers( std::span<const SCH_PIN* const> aPins )
483{
484 std::vector<wxString> numbers;
485 numbers.reserve( aPins.size() );
486
487 for( const SCH_PIN* pin : aPins )
488 numbers.push_back( pin->GetNumber() );
489
490 return numbers;
491}
492
493
494std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( TYPE aType, std::span<const wxString> aPins, REPORTER& aReporter )
495{
496 std::unique_ptr<SIM_MODEL> model = Create( aType );
497
498 try
499 {
500 // Passing nullptr to ReadDataFields will make it act as if all fields were empty.
501 model->ReadDataFields( static_cast<const std::vector<SCH_FIELD>*>( nullptr ), false, 0, aPins );
502 }
503 catch( IO_ERROR& )
504 {
505 wxFAIL_MSG( "Shouldn't throw reading empty fields!" );
506 }
507
508 return model;
509}
510
511
512std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const SIM_MODEL* aBaseModel, std::span<const wxString> aPins,
513 REPORTER& aReporter )
514{
515 std::unique_ptr<SIM_MODEL> model;
516
517 if( aBaseModel )
518 {
519 TYPE type = aBaseModel->GetType();
520
521 if( dynamic_cast<const SIM_MODEL_SPICE_FALLBACK*>( aBaseModel ) )
522 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
523 else if( dynamic_cast< const SIM_MODEL_RAW_SPICE*>( aBaseModel ) )
524 model = std::make_unique<SIM_MODEL_RAW_SPICE>();
525 else
526 model = Create( type );
527
528 model->SetBaseModel( *aBaseModel );
529 }
530 else // No base model means the model wasn't found in the library, so create a fallback
531 {
532 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( TYPE::NONE );
533 }
534
535 try
536 {
537 model->ReadDataFields( static_cast<const std::vector<SCH_FIELD>*>( nullptr ), false, 0, aPins );
538 }
539 catch( IO_ERROR& )
540 {
541 wxFAIL_MSG( "Shouldn't throw reading empty fields!" );
542 }
543
544 return model;
545}
546
547
548std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const SIM_MODEL* aBaseModel, std::span<const wxString> aPins,
549 const std::vector<SCH_FIELD>& aFields, bool aResolve, int aDepth,
550 REPORTER& aReporter )
551{
552 std::unique_ptr<SIM_MODEL> model;
553
554 if( aBaseModel )
555 {
556 NULL_REPORTER devnull;
557 TYPE type = aBaseModel->GetType();
558 TYPE type_override = ReadTypeFromFields( aFields, aResolve, aDepth, devnull );
559
560 // Check for an override in the case of IBIS models.
561 // The other models require type to be set from the base model.
562 if( dynamic_cast<const SIM_MODEL_IBIS*>( aBaseModel ) && type_override != TYPE::NONE )
563 type = type_override;
564
565 if( dynamic_cast<const SIM_MODEL_SPICE_FALLBACK*>( aBaseModel ) )
566 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
567 else if( dynamic_cast< const SIM_MODEL_RAW_SPICE*>( aBaseModel ) )
568 model = std::make_unique<SIM_MODEL_RAW_SPICE>();
569 else
570 model = Create( type );
571
572 model->SetBaseModel( *aBaseModel );
573 }
574 else // No base model means the model wasn't found in the library, so create a fallback
575 {
576 TYPE type = ReadTypeFromFields( aFields, aResolve, aDepth, aReporter );
577 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
578 }
579
580 try
581 {
582 model->ReadDataFields( &aFields, aResolve, aDepth, aPins );
583 }
584 catch( IO_ERROR& err )
585 {
586 aReporter.Report( wxString::Format( _( "Error reading simulation model from symbol '%s':\n%s" ),
588 err.Problem() ),
590 }
591
592 return model;
593}
594
595
596std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const std::vector<SCH_FIELD>& aFields, bool aResolve, int aDepth,
597 std::span<const wxString> aPins, REPORTER& aReporter )
598{
599 return Create( aFields, aResolve, aDepth, aPins, aReporter, aResolve );
600}
601
602
603std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const std::vector<SCH_FIELD>& aFields, bool aResolve, int aDepth,
604 std::span<const wxString> aPins, REPORTER& aReporter,
605 bool aAllowRawFallback )
606{
607 TYPE type = ReadTypeFromFields( aFields, aResolve, aDepth, aReporter );
608 std::unique_ptr<SIM_MODEL> model = SIM_MODEL::Create( type );
609
610 try
611 {
612 model->ReadDataFields( &aFields, aResolve, aDepth, aPins );
613 }
614 catch( const IO_ERROR& parse_err )
615 {
616 if( !aAllowRawFallback )
617 {
618 aReporter.Report( parse_err.What(), RPT_SEVERITY_ERROR );
619 return model;
620 }
621
622 // Just because we can't parse it doesn't mean that a SPICE interpreter can't. Fall
623 // back to a raw spice code model.
624
625 std::string modelData = GetFieldValue( &aFields, SIM_PARAMS_FIELD, aResolve, aDepth );
626
627 if( modelData.empty() )
628 modelData = GetFieldValue( &aFields, SIM_VALUE_FIELD, aResolve, aDepth );
629
630 model = std::make_unique<SIM_MODEL_RAW_SPICE>( modelData );
631
632 try
633 {
634 model->createPins( aPins );
635 model->m_serializer->ParsePins( GetFieldValue( &aFields, SIM_PINS_FIELD, aResolve, aDepth ) );
636 }
637 catch( const IO_ERROR& err )
638 {
639 // We own the pin syntax, so if we can't parse it then there's an error.
640 aReporter.Report( wxString::Format( _( "Error reading simulation model from symbol '%s':\n%s" ),
642 err.Problem() ),
644 }
645 }
646
647 return model;
648}
649
650
651SIM_MODEL::~SIM_MODEL() = default;
652
653
655{
656 m_modelPins.push_back( aPin );
657}
658
659
661{
662 m_modelPins.clear();
663}
664
665
666int SIM_MODEL::FindModelPinIndex( const std::string& aSymbolPinNumber )
667{
668 for( int modelPinIndex = 0; modelPinIndex < GetPinCount(); ++modelPinIndex )
669 {
670 if( GetPin( modelPinIndex ).symbolPinNumber == aSymbolPinNumber )
671 return modelPinIndex;
672 }
673
675}
676
677
679{
680 m_params.emplace_back( aInfo );
681
682 // Enums are initialized with their default values.
683 if( aInfo.enumValues.size() >= 1 )
684 m_params.back().value = aInfo.defaultValue;
685}
686
687
688void SIM_MODEL::SetBaseModel( const SIM_MODEL& aBaseModel )
689{
690 wxASSERT_MSG( GetType() == aBaseModel.GetType(),
691 wxS( "Simulation model type must be the same as its base class!" ) );
692
693 m_baseModel = &aBaseModel;
694}
695
696
697std::vector<std::reference_wrapper<const SIM_MODEL_PIN>> SIM_MODEL::GetPins() const
698{
699 std::vector<std::reference_wrapper<const SIM_MODEL_PIN>> pins;
700
701 for( int modelPinIndex = 0; modelPinIndex < GetPinCount(); ++modelPinIndex )
702 pins.emplace_back( GetPin( modelPinIndex ) );
703
704 return pins;
705}
706
707void SIM_MODEL::AssignSymbolPinNumberToModelPin( int aModelPinIndex, const wxString& aSymbolPinNumber )
708{
709 if( aModelPinIndex >= 0 && aModelPinIndex < (int) m_modelPins.size() )
710 m_modelPins.at( aModelPinIndex ).symbolPinNumber = aSymbolPinNumber;
711}
712
713
714void SIM_MODEL::AssignSymbolPinNumberToModelPin( const std::string& aModelPinName, const wxString& aSymbolPinNumber )
715{
717 {
718 if( pin.modelPinName == aModelPinName )
719 {
720 pin.symbolPinNumber = aSymbolPinNumber;
721 return;
722 }
723 }
724
725 // If aPinName wasn't in fact a name, see if it's a raw (1-based) index. This is required
726 // for legacy files which didn't use pin names.
727 int pinIndex = (int) strtol( aModelPinName.c_str(), nullptr, 10 );
728
729 if( pinIndex < 1 || pinIndex > (int) m_modelPins.size() )
730 THROW_IO_ERRORF( _( "Unknown simulation model pin '%s'" ), aModelPinName );
731
732 m_modelPins[ --pinIndex /* convert to 0-based */ ].symbolPinNumber = aSymbolPinNumber;
733}
734
735
736const SIM_MODEL::PARAM& SIM_MODEL::GetParam( unsigned aParamIndex ) const
737{
738 if( m_baseModel && m_params.at( aParamIndex ).value == "" )
739 return m_baseModel->GetParam( aParamIndex );
740 else
741 return m_params.at( aParamIndex );
742}
743
744
745bool SIM_MODEL::PARAM::INFO::Matches( const std::string& aParamName ) const
746{
747 return boost::iequals( name, aParamName );
748}
749
750
751int SIM_MODEL::doFindParam( const std::string& aParamName ) const
752{
753 for( int ii = 0; ii < (int) GetParamCount(); ++ii )
754 {
755 if( GetParam( ii ).Matches( aParamName ) )
756 return ii;
757 }
758
759 return -1;
760}
761
762
763const SIM_MODEL::PARAM* SIM_MODEL::FindParam( const std::string& aParamName ) const
764{
765 int idx = doFindParam( aParamName );
766
767 return idx >= 0 ? &GetParam( idx ) : nullptr;
768}
769
770
771const SIM_MODEL::PARAM& SIM_MODEL::GetParamOverride( unsigned aParamIndex ) const
772{
773 return m_params.at( aParamIndex );
774}
775
776
777const SIM_MODEL::PARAM& SIM_MODEL::GetBaseParam( unsigned aParamIndex ) const
778{
779 if( m_baseModel )
780 return m_baseModel->GetParam( aParamIndex );
781 else
782 return m_params.at( aParamIndex );
783}
784
785
786void SIM_MODEL::doSetParamValue( int aParamIndex, const std::string& aValue )
787{
788 m_params.at( aParamIndex ).value = aValue;
789}
790
791
792void SIM_MODEL::SetParamValue( int aParamIndex, const std::string& aValue, SIM_VALUE::NOTATION aNotation )
793{
794 // Notation conversion is very slow. Avoid if possible.
795
796 auto plainNumber =
797 []( const std::string& aString )
798 {
799 for( char c : aString )
800 {
801 if( c != '.' && ( c < '0' || c > '9' ) )
802 return false;
803 }
804
805 return true;
806 };
807
808
809 if( aValue.find( ',' ) != std::string::npos )
810 doSetParamValue( aParamIndex, SIM_VALUE::ConvertNotation( aValue, aNotation, SIM_VALUE::NOTATION::SI ) );
811 else if( aNotation != SIM_VALUE::NOTATION::SI && !plainNumber( aValue ) )
812 doSetParamValue( aParamIndex, SIM_VALUE::ConvertNotation( aValue, aNotation, SIM_VALUE::NOTATION::SI ) );
813 else
814 doSetParamValue( aParamIndex, aValue );
815}
816
817
818void SIM_MODEL::SetParamValue( const std::string& aParamName, const std::string& aValue,
819 SIM_VALUE::NOTATION aNotation )
820{
821 int idx = doFindParam( aParamName );
822
823 if( idx < 0 )
824 THROW_IO_ERRORF( _( "Unknown simulation model parameter '%s'" ), aParamName );
825
826 SetParamValue( idx, aValue, aNotation );
827}
828
829
830std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( TYPE aType )
831{
832 switch( aType )
833 {
834 case TYPE::R:
835 case TYPE::C:
836 case TYPE::L:
837 return std::make_unique<SIM_MODEL_IDEAL>( aType );
838
839 case TYPE::R_POT:
840 return std::make_unique<SIM_MODEL_R_POT>();
841
842 case TYPE::K:
843 return std::make_unique<SIM_MODEL_L_MUTUAL>();
844
845 case TYPE::R_BEHAVIORAL:
846 case TYPE::C_BEHAVIORAL:
847 case TYPE::L_BEHAVIORAL:
848 case TYPE::V_BEHAVIORAL:
849 case TYPE::I_BEHAVIORAL:
850 return std::make_unique<SIM_MODEL_BEHAVIORAL>( aType );
851
852 case TYPE::TLINE_Z0:
853 case TYPE::TLINE_RLGC:
854 return std::make_unique<SIM_MODEL_TLINE>( aType );
855
856 case TYPE::SW_V:
857 case TYPE::SW_I:
858 return std::make_unique<SIM_MODEL_SWITCH>( aType );
859
860 case TYPE::V:
861 case TYPE::I:
862 case TYPE::V_SIN:
863 case TYPE::I_SIN:
864 case TYPE::V_PULSE:
865 case TYPE::I_PULSE:
866 case TYPE::V_EXP:
867 case TYPE::I_EXP:
868 case TYPE::V_AM:
869 case TYPE::I_AM:
870 case TYPE::V_SFFM:
871 case TYPE::I_SFFM:
872 case TYPE::V_VCL:
873 case TYPE::V_CCL:
874 case TYPE::V_PWL:
875 case TYPE::I_VCL:
876 case TYPE::I_CCL:
877 case TYPE::I_PWL:
878 case TYPE::V_WHITENOISE:
879 case TYPE::I_WHITENOISE:
880 case TYPE::V_PINKNOISE:
881 case TYPE::I_PINKNOISE:
882 case TYPE::V_BURSTNOISE:
883 case TYPE::I_BURSTNOISE:
884 case TYPE::V_RANDUNIFORM:
885 case TYPE::I_RANDUNIFORM:
886 case TYPE::V_RANDGAUSSIAN:
887 case TYPE::I_RANDGAUSSIAN:
888 case TYPE::V_RANDEXP:
889 case TYPE::I_RANDEXP:
890 case TYPE::V_RANDPOISSON:
891 case TYPE::I_RANDPOISSON:
892 return std::make_unique<SIM_MODEL_SOURCE>( aType );
893
894 case TYPE::SUBCKT:
895 return std::make_unique<SIM_MODEL_SUBCKT>();
896
897 case TYPE::XSPICE:
898 return std::make_unique<SIM_MODEL_XSPICE>( aType );
899
900 case TYPE::KIBIS_DEVICE:
901 case TYPE::KIBIS_DRIVER_DC:
902 case TYPE::KIBIS_DRIVER_RECT:
903 case TYPE::KIBIS_DRIVER_PRBS:
904 return std::make_unique<SIM_MODEL_IBIS>( aType );
905
906 case TYPE::RAWSPICE:
907 return std::make_unique<SIM_MODEL_RAW_SPICE>();
908
909 default:
910 return std::make_unique<SIM_MODEL_NGSPICE>( aType );
911 }
912}
913
914
916 SIM_MODEL( aType, std::make_unique<SPICE_GENERATOR>( *this ),
917 std::make_unique<SIM_MODEL_SERIALIZER>( *this ) )
918{
919}
920
921
922SIM_MODEL::SIM_MODEL( TYPE aType, std::unique_ptr<SPICE_GENERATOR> aSpiceGenerator ) :
923 SIM_MODEL( aType, std::move( aSpiceGenerator ),
924 std::make_unique<SIM_MODEL_SERIALIZER>( *this ) )
925{
926}
927
928
929SIM_MODEL::SIM_MODEL( TYPE aType, std::unique_ptr<SPICE_GENERATOR> aSpiceGenerator,
930 std::unique_ptr<SIM_MODEL_SERIALIZER> aSerializer ) :
931 m_baseModel( nullptr ),
932 m_serializer( std::move( aSerializer ) ),
933 m_spiceGenerator( std::move( aSpiceGenerator ) ),
934 m_type( aType ),
935 m_isEnabled( true ),
936 m_isStoredInValue( false )
937{
938}
939
940
941void SIM_MODEL::createPins( std::span<const wxString> aSymbolPins )
942{
943 // Default pin sequence: model pins are the same as symbol pins.
944 // Excess model pins are set as Not Connected.
945 // Note that intentionally nothing is added if `GetPinNames()` returns an empty vector.
946
947 // SIM_MODEL pins must be ordered by symbol pin numbers -- this is assumed by the code that
948 // accesses them.
949
950 std::vector<std::string> pinNames = GetPinNames();
951
952 for( unsigned modelPinIndex = 0; modelPinIndex < pinNames.size(); ++modelPinIndex )
953 {
954 wxString pinName = pinNames[ modelPinIndex ];
955 bool optional = false;
956
957 if( pinName.StartsWith( '<' ) && pinName.EndsWith( '>' ) )
958 {
959 pinName = pinName.Mid( 1, pinName.Length() - 2 );
960 optional = true;
961 }
962
963 if( modelPinIndex < aSymbolPins.size() )
964 {
965 AddPin( { pinNames.at( modelPinIndex ),
966 aSymbolPins[ modelPinIndex ].ToStdString() } );
967 }
968 else if( !optional )
969 {
970 AddPin( { pinNames.at( modelPinIndex ), "" } );
971 }
972 }
973}
974
975
977{
978 // SUBCKTs are a single level; there's never a baseModel.
979 if( m_type == TYPE::SUBCKT )
980 return false;
981
982 // Model must be written if there's no base model or the base model is an internal model
983 if( !m_baseModel || aItem.baseModelName == "" )
984 return true;
985
986 for( int ii = 0; ii < GetParamCount(); ++ii )
987 {
988 const PARAM& param = m_params[ii];
989
990 // Instance parameters are written in item lines
991 if( param.info.isSpiceInstanceParam )
992 continue;
993
994 // Empty parameters are interpreted as default-value
995 if ( param.value == "" )
996 continue;
997
998 if( const SIM_MODEL* baseModel = dynamic_cast<const SIM_MODEL*>( m_baseModel ) )
999 {
1000 const std::string& baseValue = baseModel->m_params[ii].value;
1001
1002 if( param.value == baseValue )
1003 continue;
1004
1005 // One more check for equivalence, mostly for early 7.0 files which wrote all
1006 // parameters to the Sim.Params field in normalized format
1007 if( param.value == SIM_VALUE::Normalize( SIM_VALUE::ToDouble( baseValue ) ) )
1008 continue;
1009
1010 // Overrides must be written
1011 return true;
1012 }
1013 }
1014
1015 return false;
1016}
1017
1018
1019template <class T>
1020bool SIM_MODEL::InferSimModel( T& aSymbol, std::vector<SCH_FIELD>* aFields, bool aResolve, int aDepth,
1021 SIM_VALUE_GRAMMAR::NOTATION aNotation, wxString* aDeviceType,
1022 wxString* aModelType, wxString* aModelParams, wxString* aPinMap,
1023 const SCH_SHEET_PATH* aSheetPath )
1024{
1025 std::vector<wxString> pins;
1026
1027 if constexpr (std::is_same_v<T, SCH_SYMBOL>)
1028 pins = PinNumbers( aSymbol.GetPins( aSheetPath ) );
1029 else if constexpr (std::is_same_v<T, LIB_SYMBOL>)
1030 pins = PinNumbers( aSymbol.GetGraphicalPins( 0, 0 ) );
1031
1032 std::sort( pins.begin(), pins.end() );
1033 return InferSimModel( aSymbol.GetPrefix(), pins, aFields, aResolve, aDepth, aNotation,
1034 aDeviceType, aModelType, aModelParams, aPinMap );
1035}
1036
1037
1038bool SIM_MODEL::InferSimModel( const wxString& aPrefix, std::span<const wxString> aPins,
1039 std::vector<SCH_FIELD>* aFields, bool aResolve, int aDepth,
1040 SIM_VALUE_GRAMMAR::NOTATION aNotation, wxString* aDeviceType,
1041 wxString* aModelType, wxString* aModelParams, wxString* aPinMap )
1042{
1043 // SPICE notation is case-insensitive and locale-insensitve. This means it uses "Meg" for
1044 // mega (as both 'M' and 'm' must mean milli), and "." (always) for a decimal separator.
1045 //
1046 // KiCad's GUI uses the SI-standard 'M' for mega and 'm' for milli, and a locale-dependent
1047 // decimal separator.
1048 //
1049 // KiCad's Sim.* fields are in-between, using SI notation but a fixed decimal separator.
1050 //
1051 // So where does that leave inferred value fields? Behavioural models must be passed in
1052 // straight, because we don't (at present) know how to parse them.
1053 //
1054 // However, behavioural models _look_ like SPICE code, so it's not a stretch to expect them
1055 // to _be_ SPICE code. A passive capacitor model on the other hand, just looks like a
1056 // capacitance. Some users might expect 3,3u to work, while others might expect 3,300uF to
1057 // work.
1058 //
1059 // Checking the locale isn't reliable because it assumes the current computer's locale is
1060 // the same as the locale the schematic was authored in -- something that isn't true, for
1061 // instance, when sharing designs over DIYAudio.com.
1062 //
1063 // However, even the E192 series of preferred values uses only 3 significant digits, so a ','
1064 // or '.' followed by 3 digits _could_ reasonably-reliably be interpreted as a thousands
1065 // separator.
1066 //
1067 // Or we could just say inferred values are locale-independent, with "." used as a decimal
1068 // separator and "," used as a thousands separator. 3,300uF works, but 3,3 does not.
1069
1070 auto convertNotation =
1071 [&]( const wxString& units ) -> wxString
1072 {
1075 if( units == wxS( "µ" ) || units == wxS( "μ" ) )
1076 return wxS( "u" );
1077
1078 if( aNotation == SIM_VALUE_GRAMMAR::NOTATION::SPICE )
1079 {
1080 if( units == wxT( "M" ) )
1081 return wxT( "Meg" );
1082 }
1083 else if( aNotation == SIM_VALUE_GRAMMAR::NOTATION::SI )
1084 {
1085 if( units.Capitalize() == wxT( "Meg" ) )
1086 return wxT( "M" );
1087 }
1088
1089 return units;
1090 };
1091
1092 auto convertSeparators =
1093 []( wxString* mantissa )
1094 {
1095 mantissa->Replace( wxS( " " ), wxEmptyString );
1096
1097 wxChar ambiguousSeparator = '?';
1098 wxChar thousandsSeparator = '?';
1099 bool thousandsSeparatorFound = false;
1100 wxChar decimalSeparator = '?';
1101 bool decimalSeparatorFound = false;
1102 int digits = 0;
1103
1104 for( int ii = (int) mantissa->length() - 1; ii >= 0; --ii )
1105 {
1106 wxChar c = mantissa->GetChar( ii );
1107
1108 if( c >= '0' && c <= '9' )
1109 {
1110 digits += 1;
1111 }
1112 else if( c == '.' || c == ',' )
1113 {
1114 if( decimalSeparator != '?' || thousandsSeparator != '?' )
1115 {
1116 // We've previously found a non-ambiguous separator...
1117
1118 if( c == decimalSeparator )
1119 {
1120 if( thousandsSeparatorFound )
1121 return false; // decimal before thousands
1122 else if( decimalSeparatorFound )
1123 return false; // more than one decimal
1124 else
1125 decimalSeparatorFound = true;
1126 }
1127 else if( c == thousandsSeparator )
1128 {
1129 if( digits != 3 )
1130 return false; // thousands not followed by 3 digits
1131 else
1132 thousandsSeparatorFound = true;
1133 }
1134 }
1135 else if( ambiguousSeparator != '?' )
1136 {
1137 // We've previously found a separator, but we don't know for sure
1138 // which...
1139
1140 if( c == ambiguousSeparator )
1141 {
1142 // They both must be thousands separators
1143 thousandsSeparator = ambiguousSeparator;
1144 thousandsSeparatorFound = true;
1145 decimalSeparator = c == '.' ? ',' : '.';
1146 }
1147 else
1148 {
1149 // The first must have been a decimal, and this must be a
1150 // thousands.
1151 decimalSeparator = ambiguousSeparator;
1152 decimalSeparatorFound = true;
1153 thousandsSeparator = c;
1154 thousandsSeparatorFound = true;
1155 }
1156 }
1157 else
1158 {
1159 // This is the first separator...
1160
1161 // If it's preceeded by a '0' (only), or if it's followed by some
1162 // number of digits not equal to 3, then it -must- be a decimal
1163 // separator.
1164 //
1165 // In all other cases we don't really know what it is yet.
1166
1167 if( ( ii == 1 && mantissa->GetChar( 0 ) == '0' ) || digits != 3 )
1168 {
1169 decimalSeparator = c;
1170 decimalSeparatorFound = true;
1171 thousandsSeparator = c == '.' ? ',' : '.';
1172 }
1173 else
1174 {
1175 ambiguousSeparator = c;
1176 }
1177 }
1178
1179 digits = 0;
1180 }
1181 else
1182 {
1183 digits = 0;
1184 }
1185 }
1186
1187 // If we found nothing difinitive then we have to assume SPICE-native syntax
1188 if( decimalSeparator == '?' && thousandsSeparator == '?' )
1189 {
1190 decimalSeparator = '.';
1191 thousandsSeparator = ',';
1192 }
1193
1194 mantissa->Replace( thousandsSeparator, wxEmptyString );
1195 mantissa->Replace( decimalSeparator, '.' );
1196
1197 return true;
1198 };
1199
1200 wxString library = GetFieldValue( aFields, SIM_LIBRARY_FIELD, aResolve, aDepth );
1201 wxString modelName = GetFieldValue( aFields, SIM_NAME_FIELD, aResolve, aDepth );
1202 wxString value = GetFieldValue( aFields, SIM_VALUE_FIELD, aResolve, aDepth );
1203 *aDeviceType = GetFieldValue( aFields, SIM_DEVICE_FIELD, aResolve, aDepth );
1204 *aModelType = GetFieldValue( aFields, SIM_DEVICE_SUBTYPE_FIELD, aResolve, aDepth );
1205 *aModelParams = GetFieldValue( aFields, SIM_PARAMS_FIELD, aResolve, aDepth );
1206 *aPinMap = GetFieldValue( aFields, SIM_PINS_FIELD, aResolve, aDepth );
1207
1208 if( aPins.size() != 2 )
1209 return false;
1210
1211 if( ( ( *aDeviceType == "R" || *aDeviceType == "L" || *aDeviceType == "C" )
1212 && aModelType->IsEmpty() )
1213 ||
1214 ( library.IsEmpty() && modelName.IsEmpty()
1215 && aDeviceType->IsEmpty()
1216 && aModelType->IsEmpty()
1217 && !value.IsEmpty()
1218 && ( aPrefix.StartsWith( "R" ) || aPrefix.StartsWith( "L" ) || aPrefix.StartsWith( "C" ) ) ) )
1219 {
1220 if( aModelParams->IsEmpty() )
1221 {
1222 wxRegEx idealVal( wxT( "^"
1223 "([0-9\\,\\. ]+)"
1224 "([fFpPnNuUmMkKgGtTμµ𝛍𝜇𝝁 ]|M(e|E)(g|G))?"
1225 "([fFhHΩΩ𝛀𝛺𝝮rR]|ohm)?"
1226 "([-1-9 ]*)"
1227 "([fFhHΩΩ𝛀𝛺𝝮rR]|ohm)?"
1228 "$" ) );
1229
1230 if( idealVal.Matches( value ) ) // Ideal
1231 {
1232 wxString valueMantissa( idealVal.GetMatch( value, 1 ) );
1233 wxString valueExponent( idealVal.GetMatch( value, 2 ) );
1234 wxString valueFraction( idealVal.GetMatch( value, 6 ) );
1235
1236 if( !convertSeparators( &valueMantissa ) )
1237 return false;
1238
1239 if( valueMantissa.Contains( wxT( "." ) ) || valueFraction.IsEmpty() )
1240 {
1241 aModelParams->Printf( wxT( "%s=\"%s%s\"" ),
1242 aPrefix.Left(1).Lower(),
1243 std::move( valueMantissa ),
1244 convertNotation( valueExponent ) );
1245 }
1246 else
1247 {
1248 aModelParams->Printf( wxT( "%s=\"%s.%s%s\"" ),
1249 aPrefix.Left(1).Lower(),
1250 std::move( valueMantissa ),
1251 std::move( valueFraction ),
1252 convertNotation( valueExponent ) );
1253 }
1254 }
1255 else // Behavioral
1256 {
1257 *aModelType = wxT( "=" );
1258 aModelParams->Printf( wxT( "%s=\"%s\"" ), aPrefix.Left(1).Lower(), std::move( value ) );
1259 }
1260 }
1261
1262 if( aDeviceType->IsEmpty() )
1263 *aDeviceType = aPrefix.Left( 1 );
1264
1265 if( aPinMap->IsEmpty() )
1266 aPinMap->Printf( wxT( "%s=+ %s=-" ), aPins[0], aPins[1] );
1267
1268 return true;
1269 }
1270
1271 if( ( ( *aDeviceType == wxT( "V" ) || *aDeviceType == wxT( "I" ) )
1272 && ( aModelType->IsEmpty() || *aModelType == wxT( "DC" ) ) )
1273 ||
1274 ( aDeviceType->IsEmpty()
1275 && aModelType->IsEmpty()
1276 && !value.IsEmpty()
1277 && ( aPrefix.StartsWith( "V" ) || aPrefix.StartsWith( "I" ) ) ) )
1278 {
1279 if( !value.IsEmpty() )
1280 {
1281 wxString param = "dc";
1282
1283 if( value.StartsWith( wxT( "DC " ) ) )
1284 {
1285 value = value.Right( value.Length() - 3 );
1286 }
1287 else if( value.StartsWith( wxT( "AC " ) ) )
1288 {
1289 value = value.Right( value.Length() - 3 );
1290 param = "ac";
1291 }
1292
1293 wxRegEx sourceVal( wxT( "^"
1294 "([0-9\\,\\. ]+)"
1295 "([fFpPnNuUmMkKgGtTμµ𝛍𝜇𝝁 ]|M(e|E)(g|G))?"
1296 "([vVaA])?"
1297 "([-1-9 ]*)"
1298 "([vVaA])?"
1299 "$" ) );
1300
1301 if( sourceVal.Matches( value ) )
1302 {
1303 wxString valueMantissa( sourceVal.GetMatch( value, 1 ) );
1304 wxString valueExponent( sourceVal.GetMatch( value, 2 ) );
1305 wxString valueFraction( sourceVal.GetMatch( value, 6 ) );
1306
1307 if( !convertSeparators( &valueMantissa ) )
1308 return false;
1309
1310 if( valueMantissa.Contains( wxT( "." ) ) || valueFraction.IsEmpty() )
1311 {
1312 aModelParams->Printf( wxT( "%s=\"%s%s\" %s" ),
1313 std::move( param ),
1314 std::move( valueMantissa ),
1315 convertNotation( valueExponent ),
1316 *aModelParams );
1317 }
1318 else
1319 {
1320 aModelParams->Printf( wxT( "%s=\"%s.%s%s\" %s" ),
1321 std::move( param ),
1322 std::move( valueMantissa ),
1323 std::move( valueFraction ),
1324 convertNotation( valueExponent ),
1325 *aModelParams );
1326 }
1327 }
1328 else
1329 {
1330 aModelParams->Printf( wxT( "%s=\"%s\" %s" ),
1331 std::move( param ),
1332 std::move( value ),
1333 *aModelParams );
1334 }
1335 }
1336
1337 if( aDeviceType->IsEmpty() )
1338 *aDeviceType = aPrefix.Left( 1 );
1339
1340 if( aModelType->IsEmpty() )
1341 *aModelType = wxT( "DC" );
1342
1343 if( aPinMap->IsEmpty() )
1344 aPinMap->Printf( wxT( "%s=+ %s=-" ), aPins[0], aPins[1] );
1345
1346 return true;
1347 }
1348
1349 return false;
1350}
1351
1352
1353template bool SIM_MODEL::InferSimModel<SCH_SYMBOL>( SCH_SYMBOL& aSymbol, std::vector<SCH_FIELD>* aFields,
1354 bool aResolve, int aDepth,
1356 wxString* aDeviceType, wxString* aModelType,
1357 wxString* aModelParams, wxString* aPinMap,
1358 const SCH_SHEET_PATH* aSheetPath );
1359template bool SIM_MODEL::InferSimModel<LIB_SYMBOL>( LIB_SYMBOL& aSymbol, std::vector<SCH_FIELD>* aFields,
1360 bool aResolve, int aDepth,
1362 wxString* aDeviceType, wxString* aModelType,
1363 wxString* aModelParams, wxString* aPinMap,
1364 const SCH_SHEET_PATH* aSheetPath );
1365
1366
1367template <typename T>
1368void SIM_MODEL::MigrateSimModel( T& aSymbol, const PROJECT* aProject )
1369{
1370 class FIELD_INFO
1371 {
1372 public:
1373 FIELD_INFO()
1374 {
1375 m_Visible = false;
1376 m_Attributes.m_Size = VECTOR2I( DEFAULT_SIZE_TEXT * schIUScale.IU_PER_MILS,
1377 DEFAULT_SIZE_TEXT * schIUScale.IU_PER_MILS );
1378 };
1379
1380 FIELD_INFO( const wxString& aText, SCH_FIELD* aField ) :
1381 m_Text( aText ),
1382 m_Visible( aField->IsVisible() ),
1383 m_Attributes( aField->GetAttributes() ),
1384 m_Pos( aField->GetPosition() )
1385 {}
1386
1387 bool IsEmpty() const { return m_Text.IsEmpty(); }
1388
1389 SCH_FIELD CreateField( T* aSymbol, const wxString& aFieldName )
1390 {
1391 SCH_FIELD field( aSymbol, FIELD_T::USER, aFieldName );
1392
1393 field.SetText( m_Text );
1394 field.SetVisible( m_Visible );
1395 field.SetAttributes( m_Attributes );
1396 field.SetPosition( m_Pos );
1397
1398 return field;
1399 }
1400
1401 public:
1402 wxString m_Text;
1403 bool m_Visible;
1404 TEXT_ATTRIBUTES m_Attributes;
1405 VECTOR2I m_Pos;
1406 };
1407
1408 SCH_FIELD* existing_deviceField = aSymbol.GetField( SIM_DEVICE_FIELD );
1409 SCH_FIELD* existing_deviceSubtypeField = aSymbol.GetField( SIM_DEVICE_SUBTYPE_FIELD );
1410 SCH_FIELD* existing_pinsField = aSymbol.GetField( SIM_PINS_FIELD );
1411 SCH_FIELD* existing_paramsField = aSymbol.GetField( SIM_PARAMS_FIELD );
1412
1413 wxString existing_deviceSubtype;
1414
1415 if( existing_deviceSubtypeField )
1416 existing_deviceSubtype = existing_deviceSubtypeField->GetShownText( FOR_NETNAME ).Upper();
1417
1418 if( existing_deviceField
1419 || existing_deviceSubtypeField
1420 || existing_pinsField
1421 || existing_paramsField )
1422 {
1423 // Has a current (V7+) model field.
1424
1425 // Up until 7.0RC2 we used '+' and '-' for potentiometer pins, which doesn't match
1426 // SPICE. Here we remap them to 'r0' and 'r1'.
1427 if( existing_deviceSubtype == wxS( "POT" ) )
1428 {
1429 if( existing_pinsField )
1430 {
1431 wxString pinMap = existing_pinsField->GetText();
1432 pinMap.Replace( wxS( "=+" ), wxS( "=r1" ) );
1433 pinMap.Replace( wxS( "=-" ), wxS( "=r0" ) );
1434 existing_pinsField->SetText( pinMap );
1435 }
1436 }
1437
1438 // Up until 8.0RC1 random voltage/current sources were a bit of a mess.
1439 if( existing_deviceSubtype.StartsWith( wxS( "RAND" ) ) )
1440 {
1441 // Re-fetch value without resolving references. If it's an indirect value then we
1442 // can't migrate it.
1443 existing_deviceSubtype = existing_deviceSubtypeField->GetText().Upper();
1444
1445 if( existing_deviceSubtype.Replace( wxS( "NORMAL" ), wxS( "GAUSSIAN" ) ) )
1446 existing_deviceSubtypeField->SetText( existing_deviceSubtype );
1447
1448 if( existing_paramsField )
1449 {
1450 wxString params = existing_paramsField->GetText().Lower();
1451 size_t count = 0;
1452
1453 // We used to support 'min' and 'max' instead of 'range' and 'offset', but we
1454 // wrote all 4 to the netlist which would cause ngspice to barf, so no one has
1455 // working documents with min and max specified. Just delete them if they're
1456 // uninitialized.
1457 count += params.Replace( wxS( "min=0 " ), wxEmptyString );
1458 count += params.Replace( wxS( "max=0 " ), wxEmptyString );
1459
1460 // We used to use 'dt', but the correct ngspice name is 'ts'.
1461 count += params.Replace( wxS( "dt=" ), wxS( "ts=" ) );
1462
1463 if( count )
1464 existing_paramsField->SetText( params );
1465 }
1466 }
1467
1468 // Up until 8.0.1 we treated a mutual inductance statement as a type of inductor --
1469 // which is confusing because it doesn't represent a device at all.
1470 if( existing_deviceSubtype == wxS( "MUTUAL" ) )
1471 {
1472 if( existing_deviceSubtypeField ) // Can't be null, but Coverity doesn't know that
1473 aSymbol.RemoveField( existing_deviceSubtypeField );
1474
1475 if( existing_deviceField )
1476 {
1477 existing_deviceField->SetText( wxS( "K" ) );
1478 }
1479 else
1480 {
1481 FIELD_INFO deviceFieldInfo;
1482 deviceFieldInfo.m_Text = wxS( "K" );
1483
1484 SCH_FIELD deviceField = deviceFieldInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1485 aSymbol.AddField( deviceField );
1486 }
1487 }
1488
1489 return;
1490 }
1491
1492 auto getSIValue =
1493 []( SCH_FIELD* aField )
1494 {
1495 if( !aField ) // no, not really, but it keeps Coverity happy
1496 return wxString( wxEmptyString );
1497
1498 wxRegEx regex( wxT( "([^a-z])(M)(e|E)(g|G)($|[^a-z])" ) );
1499 wxString value = aField->GetText();
1500
1501 // Keep prefix, M, and suffix, but drop e|E and g|G
1502 regex.ReplaceAll( &value, wxT( "\\1\\2\\5" ) );
1503
1504 return value;
1505 };
1506
1507 auto generateDefaultPinMapFromSymbol =
1508 []( const std::vector<SCH_PIN*>& sourcePins )
1509 {
1510 wxString pinMap;
1511
1512 // If we're creating the pinMap from the symbol it means we don't know what the
1513 // SIM_MODEL's pin names are, so just use indexes.
1514
1515 for( unsigned ii = 0; ii < sourcePins.size(); ++ii )
1516 {
1517 if( ii > 0 )
1518 pinMap.Append( wxS( " " ) );
1519
1520 pinMap.Append( wxString::Format( wxT( "%s=%u" ),
1521 sourcePins[ii]->GetNumber(),
1522 ii + 1 ) );
1523 }
1524
1525 return pinMap;
1526 };
1527
1528 wxString prefix = aSymbol.GetPrefix();
1529 SCH_FIELD* valueField = aSymbol.GetField( FIELD_T::VALUE );
1530 bool sourcePinsSorted = false;
1531 std::vector<SCH_PIN*> sourcePins;
1532
1533 if constexpr (std::is_same_v<T, SCH_SYMBOL>)
1534 sourcePins = static_cast<SCH_SYMBOL*>( &aSymbol )->GetPins( nullptr );
1535 else if constexpr (std::is_same_v<T, LIB_SYMBOL>)
1536 sourcePins = static_cast<LIB_SYMBOL*>( &aSymbol )->GetGraphicalPins( 0, 0 );
1537
1538 auto lazySortSourcePins =
1539 [&sourcePins, &sourcePinsSorted]()
1540 {
1541 if( !sourcePinsSorted )
1542 {
1543 std::sort( sourcePins.begin(), sourcePins.end(),
1544 []( const SCH_PIN* lhs, const SCH_PIN* rhs )
1545 {
1546 return StrNumCmp( lhs->GetNumber(), rhs->GetNumber(), true ) < 0;
1547 } );
1548 }
1549
1550 sourcePinsSorted = true;
1551 };
1552
1553 FIELD_INFO deviceInfo;
1554 FIELD_INFO modelInfo;
1555 FIELD_INFO deviceSubtypeInfo;
1556 FIELD_INFO libInfo;
1557 FIELD_INFO spiceParamsInfo;
1558 FIELD_INFO pinMapInfo;
1559 bool modelFromValueField = false;
1560
1561 if( aSymbol.GetField( SIM_LEGACY_PRIMITIVE_FIELD )
1562 || aSymbol.GetField( SIM_LEGACY_PINS_FIELD )
1563 || aSymbol.GetField( SIM_LEGACY_MODEL_FIELD )
1564 || aSymbol.GetField( SIM_LEGACY_ENABLE_FIELD )
1565 || aSymbol.GetField( SIM_LEGACY_LIBRARY_FIELD ) )
1566 {
1567 if( SCH_FIELD* primitiveField = aSymbol.GetField( SIM_LEGACY_PRIMITIVE_FIELD ) )
1568 {
1569 deviceInfo = FIELD_INFO( primitiveField->GetText(), primitiveField );
1570 aSymbol.RemoveField( primitiveField );
1571 }
1572
1573 if( SCH_FIELD* nodeSequenceField = aSymbol.GetField( SIM_LEGACY_PINS_FIELD ) )
1574 {
1575 const wxString delimiters( "{:,; }" );
1576 const wxString& nodeSequence = nodeSequenceField->GetText();
1577 wxString pinMap;
1578
1579 if( nodeSequence != "" )
1580 {
1581 wxStringTokenizer tkz( nodeSequence, delimiters );
1582
1583 for( long modelPinNumber = 1; tkz.HasMoreTokens(); ++modelPinNumber )
1584 {
1585 long symbolPinNumber = 1;
1586 tkz.GetNextToken().ToLong( &symbolPinNumber );
1587
1588 if( modelPinNumber != 1 )
1589 pinMap.Append( " " );
1590
1591 pinMap.Append( wxString::Format( "%ld=%ld", symbolPinNumber, modelPinNumber ) );
1592 }
1593 }
1594
1595 pinMapInfo = FIELD_INFO( pinMap, nodeSequenceField );
1596 aSymbol.RemoveField( nodeSequenceField );
1597 }
1598
1599 if( SCH_FIELD* modelField = aSymbol.GetField( SIM_LEGACY_MODEL_FIELD ) )
1600 {
1601 modelInfo = FIELD_INFO( getSIValue( modelField ), modelField );
1602 aSymbol.RemoveField( modelField );
1603 }
1604 else if( valueField )
1605 {
1606 modelInfo = FIELD_INFO( getSIValue( valueField ), valueField );
1607 modelFromValueField = true;
1608 }
1609
1610 if( SCH_FIELD* libFileField = aSymbol.GetField( SIM_LEGACY_LIBRARY_FIELD ) )
1611 {
1612 libInfo = FIELD_INFO( libFileField->GetText(), libFileField );
1613 aSymbol.RemoveField( libFileField );
1614 }
1615 }
1616 else
1617 {
1618 // Auto convert some legacy fields used in the middle of 7.0 development...
1619
1620 if( SCH_FIELD* legacyType = aSymbol.GetField( wxT( "Sim_Type" ) ) )
1621 {
1622 legacyType->SetName( SIM_DEVICE_SUBTYPE_FIELD );
1623 }
1624
1625 if( SCH_FIELD* legacyDevice = aSymbol.GetField( wxT( "Sim_Device" ) ) )
1626 {
1627 legacyDevice->SetName( SIM_DEVICE_FIELD );
1628 }
1629
1630 if( SCH_FIELD* legacyPins = aSymbol.GetField( wxT( "Sim_Pins" ) ) )
1631 {
1632 bool isPassive = prefix.StartsWith( wxT( "R" ) )
1633 || prefix.StartsWith( wxT( "L" ) )
1634 || prefix.StartsWith( wxT( "C" ) );
1635
1636 // Migrate pins from array of indexes to name-value-pairs
1637 wxString pinMap;
1638 wxArrayString pinIndexes;
1639
1640 wxStringSplit( legacyPins->GetText(), pinIndexes, ' ' );
1641
1642 lazySortSourcePins();
1643
1644 if( isPassive && pinIndexes.size() == 2 && sourcePins.size() == 2 )
1645 {
1646 if( pinIndexes[0] == wxT( "2" ) )
1647 {
1648 pinMap.Printf( wxT( "%s=- %s=+" ),
1649 sourcePins[0]->GetNumber(),
1650 sourcePins[1]->GetNumber() );
1651 }
1652 else
1653 {
1654 pinMap.Printf( wxT( "%s=+ %s=-" ),
1655 sourcePins[0]->GetNumber(),
1656 sourcePins[1]->GetNumber() );
1657 }
1658 }
1659 else
1660 {
1661 for( unsigned ii = 0; ii < pinIndexes.size() && ii < sourcePins.size(); ++ii )
1662 {
1663 if( ii > 0 )
1664 pinMap.Append( wxS( " " ) );
1665
1666 pinMap.Append( wxString::Format( wxT( "%s=%s" ),
1667 sourcePins[ii]->GetNumber(),
1668 pinIndexes[ ii ] ) );
1669 }
1670 }
1671
1672 legacyPins->SetName( SIM_PINS_FIELD );
1673 legacyPins->SetText( pinMap );
1674 }
1675
1676 if( SCH_FIELD* legacyParams = aSymbol.GetField( wxT( "Sim_Params" ) ) )
1677 {
1678 legacyParams->SetName( SIM_PARAMS_FIELD );
1679 }
1680
1681 return;
1682 }
1683
1684 wxString device = deviceInfo.m_Text.Trim( true ).Trim( false );
1685 wxString lib = libInfo.m_Text.Trim( true ).Trim( false );
1686 wxString model = modelInfo.m_Text.Trim( true ).Trim( false );
1687 wxString modelLineParams;
1688
1689 bool libraryModel = false;
1690 bool inferredModel = false;
1691 bool internalModel = false;
1692
1693 if( !lib.IsEmpty() )
1694 {
1696 SIM_LIB_MGR libMgr( aProject );
1697 std::vector<SCH_FIELD> emptyFields;
1698 std::vector<EMBEDDED_FILES*> embeddedFilesStack;
1699
1700 if constexpr (std::is_same_v<T, SCH_SYMBOL>)
1701 {
1702 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( &aSymbol );
1703 embeddedFilesStack.push_back( symbol->Schematic()->GetEmbeddedFiles() );
1704 }
1705
1706 if( EMBEDDED_FILES* symbolEmbeddedFiles = aSymbol.GetEmbeddedFiles() )
1707 {
1708 embeddedFilesStack.push_back( symbolEmbeddedFiles );
1709
1710 if constexpr (std::is_same_v<T, SCH_SYMBOL>)
1711 {
1712 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( &aSymbol );
1713 symbol->GetLibSymbolRef()->AppendParentEmbeddedFiles( embeddedFilesStack );
1714 }
1715 else if constexpr (std::is_same_v<T, LIB_SYMBOL>)
1716 {
1717 LIB_SYMBOL* symbol = static_cast<LIB_SYMBOL*>( &aSymbol );
1718 symbol->AppendParentEmbeddedFiles( embeddedFilesStack );
1719 }
1720 }
1721
1722 libMgr.SetFilesStack( std::move( embeddedFilesStack ) );
1723
1724 // Pull out any following parameters from model name
1725 model = model.BeforeFirst( ' ', &modelLineParams );
1726 modelInfo.m_Text = model;
1727
1728 lazySortSourcePins();
1729
1730 SIM_LIBRARY::MODEL simModel = libMgr.CreateModel( lib, model.ToStdString(),
1731 emptyFields, false, 0,
1732 PinNumbers( sourcePins ), reporter );
1733
1734 if( reporter.HasMessage() )
1735 libraryModel = false; // Fall back to raw spice model
1736 else
1737 libraryModel = true;
1738
1739 if( pinMapInfo.IsEmpty() )
1740 {
1741 // Try to generate a default pin map from the SIM_MODEL's pins; if that fails,
1742 // generate one from the symbol's pins
1743 pinMapInfo.m_Text = wxString( simModel.model.Serializer().GeneratePins() );
1744
1745 if( pinMapInfo.IsEmpty() )
1746 pinMapInfo.m_Text = generateDefaultPinMapFromSymbol( sourcePins );
1747 }
1748 }
1749 else if( ( device == wxS( "R" )
1750 || device == wxS( "L" )
1751 || device == wxS( "C" )
1752 || device == wxS( "V" )
1753 || device == wxS( "I" ) )
1754 && prefix.StartsWith( device )
1755 && modelFromValueField )
1756 {
1757 inferredModel = true;
1758 }
1759 else if( device == wxS( "V" ) || device == wxS( "I" ) )
1760 {
1761 // See if we have a SPICE time-dependent function such as "sin(0 1 60)" or "sin 0 1 60"
1762 // that can be handled by a built-in SIM_MODEL_SOURCE.
1763
1764 wxStringTokenizer tokenizer( model, wxT( "() " ), wxTOKEN_STRTOK );
1765
1766 if( tokenizer.HasMoreTokens() )
1767 {
1768 deviceSubtypeInfo.m_Text = tokenizer.GetNextToken();
1769 deviceSubtypeInfo.m_Text.MakeUpper();
1770
1771 for( SIM_MODEL::TYPE type : SIM_MODEL::TYPE_ITERATOR() )
1772 {
1773 if( device == SIM_MODEL::SpiceInfo( type ).itemType
1774 && deviceSubtypeInfo.m_Text == SIM_MODEL::SpiceInfo( type ).functionName )
1775 {
1776 try
1777 {
1778 std::unique_ptr<SIM_MODEL> simModel = SIM_MODEL::Create( type );
1779
1780 if( deviceSubtypeInfo.m_Text == wxT( "DC" ) && tokenizer.CountTokens() == 1 )
1781 {
1782 wxCHECK( valueField, /* void */ );
1783 valueField->SetText( tokenizer.GetNextToken() );
1784 modelFromValueField = false;
1785 }
1786 else
1787 {
1788 for( int ii = 0; tokenizer.HasMoreTokens(); ++ii )
1789 {
1790 simModel->SetParamValue( ii, tokenizer.GetNextToken().ToStdString(),
1792 }
1793
1794 deviceSubtypeInfo.m_Text = SIM_MODEL::TypeInfo( type ).fieldValue;
1795
1796 spiceParamsInfo = modelInfo;
1797 spiceParamsInfo.m_Text = wxString( simModel->Serializer().GenerateParams() );
1798 }
1799
1800 internalModel = true;
1801
1802 if( pinMapInfo.IsEmpty() )
1803 {
1804 lazySortSourcePins();
1805
1806 // Generate a default pin map from the SIM_MODEL's pins
1807 simModel->createPins( PinNumbers( sourcePins ) );
1808 pinMapInfo.m_Text = wxString( simModel->Serializer().GeneratePins() );
1809 }
1810 }
1811 catch( ... )
1812 {
1813 // Fall back to raw spice model
1814 }
1815
1816 break;
1817 }
1818 }
1819 }
1820 }
1821
1822 if( libraryModel )
1823 {
1824 SCH_FIELD libField = libInfo.CreateField( &aSymbol, SIM_LIBRARY_FIELD );
1825 aSymbol.AddField( libField );
1826
1827 SCH_FIELD nameField = modelInfo.CreateField( &aSymbol, SIM_NAME_FIELD );
1828 aSymbol.AddField( nameField );
1829
1830 if( !modelLineParams.IsEmpty() )
1831 {
1832 spiceParamsInfo = modelInfo;
1833 spiceParamsInfo.m_Pos.x += nameField.GetBoundingBox().GetWidth();
1834 spiceParamsInfo.m_Text = modelLineParams;
1835
1836 BOX2I nameBBox = nameField.GetBoundingBox();
1837 int nameWidth = nameBBox.GetWidth();
1838
1839 // Add space between model name and additional parameters
1840 nameWidth += KiROUND( nameBBox.GetHeight() * 1.25 );
1841
1842 if( nameField.GetHorizJustify() == GR_TEXT_H_ALIGN_RIGHT )
1843 spiceParamsInfo.m_Pos.x -= nameWidth;
1844 else
1845 spiceParamsInfo.m_Pos.x += nameWidth;
1846
1847 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1848 aSymbol.AddField( paramsField );
1849 }
1850
1851 if( modelFromValueField )
1852 valueField->SetText( wxT( "${SIM.NAME}" ) );
1853 }
1854 else if( inferredModel )
1855 {
1856 // DeviceType is left in the reference designator and Model is left in the value field,
1857 // so there's nothing to do here....
1858 }
1859 else if( internalModel )
1860 {
1861 SCH_FIELD deviceField = deviceInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1862 aSymbol.AddField( deviceField );
1863
1864 if( !deviceSubtypeInfo.m_Text.IsEmpty() )
1865 {
1866 SCH_FIELD subtypeField = deviceSubtypeInfo.CreateField( &aSymbol, SIM_DEVICE_SUBTYPE_FIELD );
1867 aSymbol.AddField( subtypeField );
1868 }
1869
1870 if( !spiceParamsInfo.IsEmpty() )
1871 {
1872 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1873 aSymbol.AddField( paramsField );
1874 }
1875
1876 if( modelFromValueField )
1877 valueField->SetText( wxT( "${SIM.PARAMS}" ) );
1878 }
1879 else // Insert a raw spice model as a substitute.
1880 {
1881 if( device.IsEmpty() && lib.IsEmpty() )
1882 {
1883 spiceParamsInfo = modelInfo;
1884 }
1885 else
1886 {
1887 spiceParamsInfo.m_Text.Printf( wxT( "type=\"%s\" model=\"%s\" lib=\"%s\"" ),
1888 device,
1889 model,
1890 lib );
1891 }
1892
1893 deviceInfo.m_Text = SIM_MODEL::DeviceInfo( SIM_MODEL::DEVICE_T::SPICE ).fieldValue;
1894
1895 SCH_FIELD deviceField = deviceInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1896 aSymbol.AddField( deviceField );
1897
1898 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1899 aSymbol.AddField( paramsField );
1900
1901 if( modelFromValueField )
1902 {
1903 // Get the current Value field, after previous changes.
1904 valueField = aSymbol.GetField( FIELD_T::VALUE );
1905
1906 if( valueField )
1907 valueField->SetText( wxT( "${SIM.PARAMS}" ) );
1908 }
1909
1910 // We know nothing about the SPICE model here, so we've got no choice but to generate
1911 // the default pin map from the symbol's pins.
1912
1913 if( pinMapInfo.IsEmpty() )
1914 {
1915 lazySortSourcePins();
1916 pinMapInfo.m_Text = generateDefaultPinMapFromSymbol( sourcePins );
1917 }
1918 }
1919
1920 if( !pinMapInfo.IsEmpty() )
1921 {
1922 SCH_FIELD pinsField = pinMapInfo.CreateField( &aSymbol, SIM_PINS_FIELD );
1923 aSymbol.AddField( pinsField );
1924 }
1925}
1926
1927
1928template void SIM_MODEL::MigrateSimModel<SCH_SYMBOL>( SCH_SYMBOL& aSymbol, const PROJECT* aProject );
1929template void SIM_MODEL::MigrateSimModel<LIB_SYMBOL>( LIB_SYMBOL& aSymbol, const PROJECT* aProject );
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:123
BOX2< VECTOR2I > BOX2I
Definition box2.h:927
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:995
constexpr size_type GetWidth() const
Definition box2.h:211
constexpr size_type GetHeight() const
Definition box2.h:212
virtual bool IsVisible() const
Definition eda_text.h:226
void SetAttributes(const EDA_TEXT &aSrc, bool aSetPosition=true)
Set the text attributes from another instance.
Definition eda_text.cpp:389
GR_TEXT_H_ALIGN_T GetHorizJustify() const
Definition eda_text.h:239
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:342
const TEXT_ATTRIBUTES & GetAttributes() const
Definition eda_text.h:270
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
virtual const wxString Problem() const
what was the problem?
Define a library symbol object.
Definition lib_symbol.h:119
std::vector< const SCH_PIN * > GetGraphicalPins(int aUnit=0, int aBodyStyle=0) const
Graphical pins: Return schematic pin objects as drawn (unexpanded), filtered by unit/body.
void AppendParentEmbeddedFiles(std::vector< EMBEDDED_FILES * > &aStack) const
A singleton reporter that reports to nowhere.
Definition reporter.h:267
Container for project specific data.
Definition project.h:63
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:102
EMBEDDED_FILES * GetEmbeddedFiles() override
const BOX2I GetBoundingBox() const override
Return the orthogonal bounding box of this object for display purposes.
VECTOR2I GetPosition() const override
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:138
wxString GetShownText(const SCH_SHEET_PATH *aPath, RESOLUTION_CONTEXT aContext, const wxString &aVariantName=wxEmptyString, int aDepth=0) const
void SetPosition(const VECTOR2I &aPosition) override
void SetText(const wxString &aText) override
SCHEMATIC * Schematic() const
Search the item hierarchy to find a SCHEMATIC.
Definition sch_item.cpp:281
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
Schematic symbol object.
Definition sch_symbol.h:75
std::vector< const SCH_PIN * > GetPins(const SCH_SHEET_PATH *aSheet) const
Retrieve a list of the SCH_PINs for the given sheet path.
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:183
static constexpr auto DIFF_FIELD
SIM_MODEL & CreateModel(SIM_MODEL::TYPE aType, std::span< const wxString > aPins, REPORTER &aReporter)
void SetFilesStack(std::vector< EMBEDDED_FILES * > aFilesStack)
Definition sim_lib_mgr.h:45
Serializes/deserializes a SIM_MODEL for storage in LIB_FIELDs/SCH_FIELDs.
std::string GeneratePins() const
int FindModelPinIndex(const std::string &aSymbolPinNumber)
static void MigrateSimModel(T &aSymbol, const PROJECT *aProject)
const PARAM & GetBaseParam(unsigned aParamIndex) const
void AddParam(const PARAM::INFO &aInfo)
bool IsStoredInValue() const
Definition sim_model.h:516
virtual std::vector< std::string > GetPinNames() const
Definition sim_model.h:476
void WriteFields(std::vector< SCH_FIELD > &aFields, const SCH_SHEET_PATH *aSheetPath=nullptr, const wxString &aVariantName=wxEmptyString) const
std::unique_ptr< SPICE_GENERATOR > m_spiceGenerator
Definition sim_model.h:558
virtual bool requiresSpiceModelLine(const SPICE_ITEM &aItem) const
void ClearPins()
static std::unique_ptr< SIM_MODEL > Create(TYPE aType, std::span< const wxString > aPins, REPORTER &aReporter)
std::vector< SIM_MODEL_PIN > m_modelPins
Definition sim_model.h:553
static INFO TypeInfo(TYPE aType)
int GetPinCount() const
Definition sim_model.h:478
void ReadDataFields(const std::vector< SCH_FIELD > *aFields, bool aResolve, int aDepth, std::span< const wxString > aPins)
static bool InferSimModel(const wxString &aPrefix, std::span< const wxString > aPins, std::vector< SCH_FIELD > *aFields, bool aResolve, int aDepth, SIM_VALUE_GRAMMAR::NOTATION aNotation, wxString *aDeviceType, wxString *aModelType, wxString *aModelParams, wxString *aPinMap)
aPins follows lexical symbol-pin number order, including duplicate numbers.
void AddPin(const SIM_MODEL_PIN &aPin)
static SPICE_INFO SpiceInfo(TYPE aType)
const SIM_MODEL_SERIALIZER & Serializer() const
Definition sim_model.h:430
bool m_isEnabled
Definition sim_model.h:561
virtual const PARAM & GetParam(unsigned aParamIndex) const
bool m_isStoredInValue
Definition sim_model.h:562
virtual void SetBaseModel(const SIM_MODEL &aBaseModel)
SIM_MODEL()=delete
static TYPE ReadTypeFromFields(const std::vector< SCH_FIELD > &aFields, bool aResolve, int aDepth, REPORTER &aReporter)
void createPins(std::span< const wxString > aSymbolPins)
int GetParamCount() const
Definition sim_model.h:488
void AssignSymbolPinNumberToModelPin(int aPinIndex, const wxString &aSymbolPinNumber)
static DEVICE_INFO DeviceInfo(DEVICE_T aDeviceType)
Definition sim_model.cpp:57
const PARAM * FindParam(const std::string &aParamName) const
virtual void doSetParamValue(int aParamIndex, const std::string &aValue)
std::vector< PARAM > m_params
Definition sim_model.h:552
const PARAM & GetParamOverride(unsigned aParamIndex) const
friend class SPICE_GENERATOR
Definition sim_model.h:78
virtual ~SIM_MODEL()
void SetParamValue(int aParamIndex, const std::string &aValue, SIM_VALUE::NOTATION aNotation=SIM_VALUE::NOTATION::SI)
virtual void SwitchSingleEndedDiff(bool aDiff)
Definition sim_model.h:518
const SIM_MODEL_PIN & GetPin(unsigned aIndex) const
Definition sim_model.h:479
std::unique_ptr< SIM_MODEL_SERIALIZER > m_serializer
Definition sim_model.h:555
virtual int doFindParam(const std::string &aParamName) const
TYPE GetType() const
Definition sim_model.h:471
static std::vector< wxString > PinNumbers(std::span< const SCH_PIN *const > aPins)
std::vector< std::reference_wrapper< const SIM_MODEL_PIN > > GetPins() const
const TYPE m_type
Definition sim_model.h:560
const SIM_MODEL * m_baseModel
Definition sim_model.h:554
static std::string Normalize(double aValue)
static std::string ConvertNotation(const std::string &aString, NOTATION aFromNotation, NOTATION aToNotation)
static double ToDouble(const std::string &aString, double aDefault=NAN)
SIM_VALUE_GRAMMAR::NOTATION NOTATION
Definition sim_value.h:57
A wrapper for reporting to a wxString object.
Definition reporter.h:242
@ FOR_NETNAME
Definition common.h:90
#define _(s)
#define DEFAULT_SIZE_TEXT
This is the "default-of-the-default" hardcoded text size; individual application define their own def...
Definition eda_text.h:84
#define THROW_IO_ERRORF(msg,...)
STL namespace.
@ RPT_SEVERITY_ERROR
void SetFieldValue(std::vector< SCH_FIELD > &aFields, const wxString &aFieldName, const std::string &aValue, bool aIsVisible=true, const SCH_SHEET_PATH *aSheetPath=nullptr, const wxString &aVariantName=wxEmptyString)
Definition sch_field.h:456
wxString GetFieldValue(const std::vector< SCH_FIELD > *aFields, FIELD_T aFieldType)
Definition sch_field.h:431
SIM_MODEL::TYPE TYPE
Definition sim_model.cpp:54
#define SIM_PINS_FIELD
Definition sim_model.h:51
#define SIM_DEVICE_FIELD
Definition sim_model.h:49
#define SIM_NAME_FIELD
Definition sim_model.h:55
#define SIM_LIBRARY_FIELD
Definition sim_model.h:54
#define SIM_LEGACY_ENABLE_FIELD
Definition sim_model.h:62
#define SIM_LEGACY_ENABLE_FIELD_V7
Definition sim_model.h:58
#define SIM_LEGACY_MODEL_FIELD
Definition sim_model.h:60
#define SIM_LEGACY_PINS_FIELD
Definition sim_model.h:61
#define SIM_LEGACY_LIBRARY_FIELD
Definition sim_model.h:63
#define SIM_PARAMS_FIELD
Definition sim_model.h:53
#define SIM_VALUE_FIELD
Definition sim_model.h:47
#define SIM_LEGACY_PRIMITIVE_FIELD
Definition sim_model.h:59
#define SIM_DEVICE_SUBTYPE_FIELD
Definition sim_model.h:50
bool convertSeparators(wxString *value)
void wxStringSplit(const wxString &aText, wxArrayString &aStrings, wxChar aSplitter)
Split aString to a string list separated at aSplitter.
SIM_MODEL & model
Definition sim_library.h:37
std::vector< std::string > enumValues
Definition sim_model.h:386
bool Matches(const std::string &aName) const
std::string defaultValue
Definition sim_model.h:380
bool Matches(const std::string &aName) const
Definition sim_model.h:393
std::string value
Definition sim_model.h:398
const INFO & info
Definition sim_model.h:399
static constexpr auto NOT_CONNECTED
Definition sim_model.h:71
std::string baseModelName
@ USER
The field ID hasn't been set yet; field is invalid.
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
IbisParser parser & reporter
KIBIS_MODEL * model
KIBIS_PIN * pin
@ GR_TEXT_H_ALIGN_RIGHT
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683