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 const std::vector<SCH_PIN*>& 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::unique_ptr<SIM_MODEL> SIM_MODEL::Create( TYPE aType, const std::vector<SCH_PIN*>& aPins,
483 REPORTER& aReporter )
484{
485 std::unique_ptr<SIM_MODEL> model = Create( aType );
486
487 try
488 {
489 // Passing nullptr to ReadDataFields will make it act as if all fields were empty.
490 model->ReadDataFields( static_cast<const std::vector<SCH_FIELD>*>( nullptr ),
491 false, 0, aPins );
492 }
493 catch( IO_ERROR& )
494 {
495 wxFAIL_MSG( "Shouldn't throw reading empty fields!" );
496 }
497
498 return model;
499}
500
501
502std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const SIM_MODEL* aBaseModel,
503 const std::vector<SCH_PIN*>& aPins,
504 REPORTER& aReporter )
505{
506 std::unique_ptr<SIM_MODEL> model;
507
508 if( aBaseModel )
509 {
510 TYPE type = aBaseModel->GetType();
511
512 if( dynamic_cast<const SIM_MODEL_SPICE_FALLBACK*>( aBaseModel ) )
513 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
514 else if( dynamic_cast< const SIM_MODEL_RAW_SPICE*>( aBaseModel ) )
515 model = std::make_unique<SIM_MODEL_RAW_SPICE>();
516 else
517 model = Create( type );
518
519 model->SetBaseModel( *aBaseModel );
520 }
521 else // No base model means the model wasn't found in the library, so create a fallback
522 {
523 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( TYPE::NONE );
524 }
525
526 try
527 {
528 model->ReadDataFields( static_cast<const std::vector<SCH_FIELD>*>( nullptr ),
529 false, 0, aPins );
530 }
531 catch( IO_ERROR& )
532 {
533 wxFAIL_MSG( "Shouldn't throw reading empty fields!" );
534 }
535
536 return model;
537}
538
539
540std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const SIM_MODEL* aBaseModel,
541 const std::vector<SCH_PIN*>& aPins,
542 const std::vector<SCH_FIELD>& aFields,
543 bool aResolve, int aDepth, REPORTER& aReporter )
544{
545 std::unique_ptr<SIM_MODEL> model;
546
547 if( aBaseModel )
548 {
549 NULL_REPORTER devnull;
550 TYPE type = aBaseModel->GetType();
551 TYPE type_override = ReadTypeFromFields( aFields, aResolve, aDepth, devnull );
552
553 // Check for an override in the case of IBIS models.
554 // The other models require type to be set from the base model.
555 if( dynamic_cast<const SIM_MODEL_IBIS*>( aBaseModel ) &&
556 type_override != TYPE::NONE )
557 {
558 type = type_override;
559 }
560
561 if( dynamic_cast<const SIM_MODEL_SPICE_FALLBACK*>( aBaseModel ) )
562 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
563 else if( dynamic_cast< const SIM_MODEL_RAW_SPICE*>( aBaseModel ) )
564 model = std::make_unique<SIM_MODEL_RAW_SPICE>();
565 else
566 model = Create( type );
567
568 model->SetBaseModel( *aBaseModel );
569 }
570 else // No base model means the model wasn't found in the library, so create a fallback
571 {
572 TYPE type = ReadTypeFromFields( aFields, aResolve, aDepth, aReporter );
573 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
574 }
575
576 try
577 {
578 model->ReadDataFields( &aFields, aResolve, aDepth, aPins );
579 }
580 catch( IO_ERROR& err )
581 {
582 aReporter.Report( wxString::Format( _( "Error reading simulation model from symbol '%s':\n%s" ),
584 err.Problem() ),
586 }
587
588 return model;
589}
590
591
592std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const std::vector<SCH_FIELD>& aFields,
593 bool aResolve, int aDepth,
594 const std::vector<SCH_PIN*>& aPins, REPORTER& aReporter )
595{
596 TYPE type = ReadTypeFromFields( aFields, aResolve, aDepth, aReporter );
597 std::unique_ptr<SIM_MODEL> model = SIM_MODEL::Create( type );
598
599 try
600 {
601 model->ReadDataFields( &aFields, aResolve, aDepth, aPins );
602 }
603 catch( const IO_ERROR& parse_err )
604 {
605 if( !aResolve )
606 {
607 aReporter.Report( parse_err.What(), RPT_SEVERITY_ERROR );
608 return model;
609 }
610
611 // Just because we can't parse it doesn't mean that a SPICE interpreter can't. Fall
612 // back to a raw spice code model.
613
614 std::string modelData = GetFieldValue( &aFields, SIM_PARAMS_FIELD, aResolve, aDepth );
615
616 if( modelData.empty() )
617 modelData = GetFieldValue( &aFields, SIM_VALUE_FIELD, aResolve, aDepth );
618
619 model = std::make_unique<SIM_MODEL_RAW_SPICE>( modelData );
620
621 try
622 {
623 model->createPins( aPins );
624 model->m_serializer->ParsePins( GetFieldValue( &aFields, SIM_PINS_FIELD, aResolve, aDepth ) );
625 }
626 catch( const IO_ERROR& err )
627 {
628 // We own the pin syntax, so if we can't parse it then there's an error.
629 aReporter.Report( wxString::Format( _( "Error reading simulation model from symbol '%s':\n%s" ),
631 err.Problem() ),
633 }
634 }
635
636 return model;
637}
638
639
640SIM_MODEL::~SIM_MODEL() = default;
641
642
644{
645 m_modelPins.push_back( aPin );
646}
647
648
650{
651 m_modelPins.clear();
652}
653
654
655int SIM_MODEL::FindModelPinIndex( const std::string& aSymbolPinNumber )
656{
657 for( int modelPinIndex = 0; modelPinIndex < GetPinCount(); ++modelPinIndex )
658 {
659 if( GetPin( modelPinIndex ).symbolPinNumber == aSymbolPinNumber )
660 return modelPinIndex;
661 }
662
664}
665
666
668{
669 m_params.emplace_back( aInfo );
670
671 // Enums are initialized with their default values.
672 if( aInfo.enumValues.size() >= 1 )
673 m_params.back().value = aInfo.defaultValue;
674}
675
676
677void SIM_MODEL::SetBaseModel( const SIM_MODEL& aBaseModel )
678{
679 wxASSERT_MSG( GetType() == aBaseModel.GetType(),
680 wxS( "Simulation model type must be the same as its base class!" ) );
681
682 m_baseModel = &aBaseModel;
683}
684
685
686std::vector<std::reference_wrapper<const SIM_MODEL_PIN>> SIM_MODEL::GetPins() const
687{
688 std::vector<std::reference_wrapper<const SIM_MODEL_PIN>> pins;
689
690 for( int modelPinIndex = 0; modelPinIndex < GetPinCount(); ++modelPinIndex )
691 pins.emplace_back( GetPin( modelPinIndex ) );
692
693 return pins;
694}
695
697 const wxString& aSymbolPinNumber )
698{
699 if( aModelPinIndex >= 0 && aModelPinIndex < (int) m_modelPins.size() )
700 m_modelPins.at( aModelPinIndex ).symbolPinNumber = aSymbolPinNumber;
701}
702
703
704void SIM_MODEL::AssignSymbolPinNumberToModelPin( const std::string& aModelPinName,
705 const wxString& aSymbolPinNumber )
706{
708 {
709 if( pin.modelPinName == aModelPinName )
710 {
711 pin.symbolPinNumber = aSymbolPinNumber;
712 return;
713 }
714 }
715
716 // If aPinName wasn't in fact a name, see if it's a raw (1-based) index. This is required
717 // for legacy files which didn't use pin names.
718 int pinIndex = (int) strtol( aModelPinName.c_str(), nullptr, 10 );
719
720 if( pinIndex < 1 || pinIndex > (int) m_modelPins.size() )
721 THROW_IO_ERROR( wxString::Format( _( "Unknown simulation model pin '%s'" ), aModelPinName ) );
722
723 m_modelPins[ --pinIndex /* convert to 0-based */ ].symbolPinNumber = aSymbolPinNumber;
724}
725
726
727const SIM_MODEL::PARAM& SIM_MODEL::GetParam( unsigned aParamIndex ) const
728{
729 if( m_baseModel && m_params.at( aParamIndex ).value == "" )
730 return m_baseModel->GetParam( aParamIndex );
731 else
732 return m_params.at( aParamIndex );
733}
734
735
736bool SIM_MODEL::PARAM::INFO::Matches( const std::string& aParamName ) const
737{
738 return boost::iequals( name, aParamName );
739}
740
741
742int SIM_MODEL::doFindParam( const std::string& aParamName ) const
743{
744 for( int ii = 0; ii < (int) GetParamCount(); ++ii )
745 {
746 if( GetParam( ii ).Matches( aParamName ) )
747 return ii;
748 }
749
750 return -1;
751}
752
753
754const SIM_MODEL::PARAM* SIM_MODEL::FindParam( const std::string& aParamName ) const
755{
756 int idx = doFindParam( aParamName );
757
758 return idx >= 0 ? &GetParam( idx ) : nullptr;
759}
760
761
762const SIM_MODEL::PARAM& SIM_MODEL::GetParamOverride( unsigned aParamIndex ) const
763{
764 return m_params.at( aParamIndex );
765}
766
767
768const SIM_MODEL::PARAM& SIM_MODEL::GetBaseParam( unsigned aParamIndex ) const
769{
770 if( m_baseModel )
771 return m_baseModel->GetParam( aParamIndex );
772 else
773 return m_params.at( aParamIndex );
774}
775
776
777void SIM_MODEL::doSetParamValue( int aParamIndex, const std::string& aValue )
778{
779 m_params.at( aParamIndex ).value = aValue;
780}
781
782
783void SIM_MODEL::SetParamValue( int aParamIndex, const std::string& aValue,
784 SIM_VALUE::NOTATION aNotation )
785{
786 // Notation conversion is very slow. Avoid if possible.
787
788 auto plainNumber =
789 []( const std::string& aString )
790 {
791 for( char c : aString )
792 {
793 if( c != '.' && ( c < '0' || c > '9' ) )
794 return false;
795 }
796
797 return true;
798 };
799
800
801 if( aValue.find( ',' ) != std::string::npos )
802 {
803 doSetParamValue( aParamIndex, SIM_VALUE::ConvertNotation( aValue, aNotation,
804 SIM_VALUE::NOTATION::SI ) );
805 }
806 else if( aNotation != SIM_VALUE::NOTATION::SI && !plainNumber( aValue ) )
807 {
808 doSetParamValue( aParamIndex, SIM_VALUE::ConvertNotation( aValue, aNotation,
809 SIM_VALUE::NOTATION::SI ) );
810 }
811 else
812 {
813 doSetParamValue( aParamIndex, aValue );
814 }
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_ERROR( wxString::Format( "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( const std::vector<SCH_PIN*>& 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 ]->GetNumber().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{
1024 // SPICE notation is case-insensitive and locale-insensitve. This means it uses "Meg" for
1025 // mega (as both 'M' and 'm' must mean milli), and "." (always) for a decimal separator.
1026 //
1027 // KiCad's GUI uses the SI-standard 'M' for mega and 'm' for milli, and a locale-dependent
1028 // decimal separator.
1029 //
1030 // KiCad's Sim.* fields are in-between, using SI notation but a fixed decimal separator.
1031 //
1032 // So where does that leave inferred value fields? Behavioural models must be passed in
1033 // straight, because we don't (at present) know how to parse them.
1034 //
1035 // However, behavioural models _look_ like SPICE code, so it's not a stretch to expect them
1036 // to _be_ SPICE code. A passive capacitor model on the other hand, just looks like a
1037 // capacitance. Some users might expect 3,3u to work, while others might expect 3,300uF to
1038 // work.
1039 //
1040 // Checking the locale isn't reliable because it assumes the current computer's locale is
1041 // the same as the locale the schematic was authored in -- something that isn't true, for
1042 // instance, when sharing designs over DIYAudio.com.
1043 //
1044 // However, even the E192 series of preferred values uses only 3 significant digits, so a ','
1045 // or '.' followed by 3 digits _could_ reasonably-reliably be interpreted as a thousands
1046 // separator.
1047 //
1048 // Or we could just say inferred values are locale-independent, with "." used as a decimal
1049 // separator and "," used as a thousands separator. 3,300uF works, but 3,3 does not.
1050
1051 auto convertNotation =
1052 [&]( const wxString& units ) -> wxString
1053 {
1056 if( units == wxS( "µ" ) || units == wxS( "μ" ) )
1057 return wxS( "u" );
1058
1059 if( aNotation == SIM_VALUE_GRAMMAR::NOTATION::SPICE )
1060 {
1061 if( units == wxT( "M" ) )
1062 return wxT( "Meg" );
1063 }
1064 else if( aNotation == SIM_VALUE_GRAMMAR::NOTATION::SI )
1065 {
1066 if( units.Capitalize() == wxT( "Meg" ) )
1067 return wxT( "M" );
1068 }
1069
1070 return units;
1071 };
1072
1073 auto convertSeparators =
1074 []( wxString* mantissa )
1075 {
1076 mantissa->Replace( wxS( " " ), wxEmptyString );
1077
1078 wxChar ambiguousSeparator = '?';
1079 wxChar thousandsSeparator = '?';
1080 bool thousandsSeparatorFound = false;
1081 wxChar decimalSeparator = '?';
1082 bool decimalSeparatorFound = false;
1083 int digits = 0;
1084
1085 for( int ii = (int) mantissa->length() - 1; ii >= 0; --ii )
1086 {
1087 wxChar c = mantissa->GetChar( ii );
1088
1089 if( c >= '0' && c <= '9' )
1090 {
1091 digits += 1;
1092 }
1093 else if( c == '.' || c == ',' )
1094 {
1095 if( decimalSeparator != '?' || thousandsSeparator != '?' )
1096 {
1097 // We've previously found a non-ambiguous separator...
1098
1099 if( c == decimalSeparator )
1100 {
1101 if( thousandsSeparatorFound )
1102 return false; // decimal before thousands
1103 else if( decimalSeparatorFound )
1104 return false; // more than one decimal
1105 else
1106 decimalSeparatorFound = true;
1107 }
1108 else if( c == thousandsSeparator )
1109 {
1110 if( digits != 3 )
1111 return false; // thousands not followed by 3 digits
1112 else
1113 thousandsSeparatorFound = true;
1114 }
1115 }
1116 else if( ambiguousSeparator != '?' )
1117 {
1118 // We've previously found a separator, but we don't know for sure
1119 // which...
1120
1121 if( c == ambiguousSeparator )
1122 {
1123 // They both must be thousands separators
1124 thousandsSeparator = ambiguousSeparator;
1125 thousandsSeparatorFound = true;
1126 decimalSeparator = c == '.' ? ',' : '.';
1127 }
1128 else
1129 {
1130 // The first must have been a decimal, and this must be a
1131 // thousands.
1132 decimalSeparator = ambiguousSeparator;
1133 decimalSeparatorFound = true;
1134 thousandsSeparator = c;
1135 thousandsSeparatorFound = true;
1136 }
1137 }
1138 else
1139 {
1140 // This is the first separator...
1141
1142 // If it's preceeded by a '0' (only), or if it's followed by some
1143 // number of digits not equal to 3, then it -must- be a decimal
1144 // separator.
1145 //
1146 // In all other cases we don't really know what it is yet.
1147
1148 if( ( ii == 1 && mantissa->GetChar( 0 ) == '0' ) || digits != 3 )
1149 {
1150 decimalSeparator = c;
1151 decimalSeparatorFound = true;
1152 thousandsSeparator = c == '.' ? ',' : '.';
1153 }
1154 else
1155 {
1156 ambiguousSeparator = c;
1157 }
1158 }
1159
1160 digits = 0;
1161 }
1162 else
1163 {
1164 digits = 0;
1165 }
1166 }
1167
1168 // If we found nothing difinitive then we have to assume SPICE-native syntax
1169 if( decimalSeparator == '?' && thousandsSeparator == '?' )
1170 {
1171 decimalSeparator = '.';
1172 thousandsSeparator = ',';
1173 }
1174
1175 mantissa->Replace( thousandsSeparator, wxEmptyString );
1176 mantissa->Replace( decimalSeparator, '.' );
1177
1178 return true;
1179 };
1180
1181 wxString prefix = aSymbol.GetPrefix();
1182 wxString library = GetFieldValue( aFields, SIM_LIBRARY_FIELD, aResolve, aDepth );
1183 wxString modelName = GetFieldValue( aFields, SIM_NAME_FIELD, aResolve, aDepth );
1184 wxString value = GetFieldValue( aFields, SIM_VALUE_FIELD, aResolve, aDepth );
1185 std::vector<SCH_PIN*> pins;
1186
1187 if constexpr (std::is_same_v<T, SCH_SYMBOL>)
1188 pins = static_cast<SCH_SYMBOL*>( &aSymbol )->GetPins( nullptr );
1189 else if constexpr (std::is_same_v<T, LIB_SYMBOL>)
1190 pins = static_cast<LIB_SYMBOL*>( &aSymbol )->GetGraphicalPins( 0, 0 );
1191
1192
1193 // ensure the pins are sorted by number (not guaranteed in the symbol)
1194 // because the inferred spice model pin assignment here and elsewhere depends on
1195 // us maintaing the list of pins in order
1196 std::sort( pins.begin(), pins.end(),
1197 []( const SCH_PIN* a, const SCH_PIN* b )
1198 {
1199 return a->GetNumber() < b->GetNumber();
1200 } );
1201
1202 *aDeviceType = GetFieldValue( aFields, SIM_DEVICE_FIELD, aResolve, aDepth );
1203 *aModelType = GetFieldValue( aFields, SIM_DEVICE_SUBTYPE_FIELD, aResolve, aDepth );
1204 *aModelParams = GetFieldValue( aFields, SIM_PARAMS_FIELD, aResolve, aDepth );
1205 *aPinMap = GetFieldValue( aFields, SIM_PINS_FIELD, aResolve, aDepth );
1206
1207 if( pins.size() != 2 )
1208 return false;
1209
1210 if( ( ( *aDeviceType == "R" || *aDeviceType == "L" || *aDeviceType == "C" )
1211 && aModelType->IsEmpty() )
1212 ||
1213 ( library.IsEmpty() && modelName.IsEmpty()
1214 && aDeviceType->IsEmpty()
1215 && aModelType->IsEmpty()
1216 && !value.IsEmpty()
1217 && ( prefix.StartsWith( "R" ) || prefix.StartsWith( "L" ) || prefix.StartsWith( "C" ) ) ) )
1218 {
1219 if( aModelParams->IsEmpty() )
1220 {
1221 wxRegEx idealVal( wxT( "^"
1222 "([0-9\\,\\. ]+)"
1223 "([fFpPnNuUmMkKgGtTμµ𝛍𝜇𝝁 ]|M(e|E)(g|G))?"
1224 "([fFhHΩΩ𝛀𝛺𝝮rR]|ohm)?"
1225 "([-1-9 ]*)"
1226 "([fFhHΩΩ𝛀𝛺𝝮rR]|ohm)?"
1227 "$" ) );
1228
1229 if( idealVal.Matches( value ) ) // Ideal
1230 {
1231 wxString valueMantissa( idealVal.GetMatch( value, 1 ) );
1232 wxString valueExponent( idealVal.GetMatch( value, 2 ) );
1233 wxString valueFraction( idealVal.GetMatch( value, 6 ) );
1234
1235 if( !convertSeparators( &valueMantissa ) )
1236 return false;
1237
1238 if( valueMantissa.Contains( wxT( "." ) ) || valueFraction.IsEmpty() )
1239 {
1240 aModelParams->Printf( wxT( "%s=\"%s%s\"" ),
1241 prefix.Left(1).Lower(),
1242 std::move( valueMantissa ),
1243 convertNotation( valueExponent ) );
1244 }
1245 else
1246 {
1247 aModelParams->Printf( wxT( "%s=\"%s.%s%s\"" ),
1248 prefix.Left(1).Lower(),
1249 std::move( valueMantissa ),
1250 std::move( valueFraction ),
1251 convertNotation( valueExponent ) );
1252 }
1253 }
1254 else // Behavioral
1255 {
1256 *aModelType = wxT( "=" );
1257 aModelParams->Printf( wxT( "%s=\"%s\"" ), prefix.Left(1).Lower(), std::move( value ) );
1258 }
1259 }
1260
1261 if( aDeviceType->IsEmpty() )
1262 *aDeviceType = prefix.Left( 1 );
1263
1264 if( aPinMap->IsEmpty() )
1265 aPinMap->Printf( wxT( "%s=+ %s=-" ), pins[0]->GetNumber(), pins[1]->GetNumber() );
1266
1267 return true;
1268 }
1269
1270 if( ( ( *aDeviceType == wxT( "V" ) || *aDeviceType == wxT( "I" ) )
1271 && ( aModelType->IsEmpty() || *aModelType == wxT( "DC" ) ) )
1272 ||
1273 ( aDeviceType->IsEmpty()
1274 && aModelType->IsEmpty()
1275 && !value.IsEmpty()
1276 && ( prefix.StartsWith( "V" ) || prefix.StartsWith( "I" ) ) ) )
1277 {
1278 if( !value.IsEmpty() )
1279 {
1280 wxString param = "dc";
1281
1282 if( value.StartsWith( wxT( "DC " ) ) )
1283 {
1284 value = value.Right( value.Length() - 3 );
1285 }
1286 else if( value.StartsWith( wxT( "AC " ) ) )
1287 {
1288 value = value.Right( value.Length() - 3 );
1289 param = "ac";
1290 }
1291
1292 wxRegEx sourceVal( wxT( "^"
1293 "([0-9\\,\\. ]+)"
1294 "([fFpPnNuUmMkKgGtTμµ𝛍𝜇𝝁 ]|M(e|E)(g|G))?"
1295 "([vVaA])?"
1296 "([-1-9 ]*)"
1297 "([vVaA])?"
1298 "$" ) );
1299
1300 if( sourceVal.Matches( value ) )
1301 {
1302 wxString valueMantissa( sourceVal.GetMatch( value, 1 ) );
1303 wxString valueExponent( sourceVal.GetMatch( value, 2 ) );
1304 wxString valueFraction( sourceVal.GetMatch( value, 6 ) );
1305
1306 if( !convertSeparators( &valueMantissa ) )
1307 return false;
1308
1309 if( valueMantissa.Contains( wxT( "." ) ) || valueFraction.IsEmpty() )
1310 {
1311 aModelParams->Printf( wxT( "%s=\"%s%s\" %s" ),
1312 std::move( param ),
1313 std::move( valueMantissa ),
1314 convertNotation( valueExponent ),
1315 *aModelParams );
1316 }
1317 else
1318 {
1319 aModelParams->Printf( wxT( "%s=\"%s.%s%s\" %s" ),
1320 std::move( param ),
1321 std::move( valueMantissa ),
1322 std::move( valueFraction ),
1323 convertNotation( valueExponent ),
1324 *aModelParams );
1325 }
1326 }
1327 else
1328 {
1329 aModelParams->Printf( wxT( "%s=\"%s\" %s" ),
1330 std::move( param ),
1331 std::move( value ),
1332 *aModelParams );
1333 }
1334 }
1335
1336 if( aDeviceType->IsEmpty() )
1337 *aDeviceType = prefix.Left( 1 );
1338
1339 if( aModelType->IsEmpty() )
1340 *aModelType = wxT( "DC" );
1341
1342 if( aPinMap->IsEmpty() )
1343 aPinMap->Printf( wxT( "%s=+ %s=-" ), pins[0]->GetNumber(), pins[1]->GetNumber() );
1344
1345 return true;
1346 }
1347
1348 return false;
1349}
1350
1351
1352template bool SIM_MODEL::InferSimModel<SCH_SYMBOL>( SCH_SYMBOL& aSymbol, std::vector<SCH_FIELD>* aFields,
1353 bool aResolve, int aDepth,
1355 wxString* aDeviceType, wxString* aModelType,
1356 wxString* aModelParams, wxString* aPinMap );
1357template bool SIM_MODEL::InferSimModel<LIB_SYMBOL>( LIB_SYMBOL& aSymbol, std::vector<SCH_FIELD>* aFields,
1358 bool aResolve, int aDepth,
1360 wxString* aDeviceType, wxString* aModelType,
1361 wxString* aModelParams, wxString* aPinMap );
1362
1363
1364template <typename T>
1365void SIM_MODEL::MigrateSimModel( T& aSymbol, const PROJECT* aProject )
1366{
1367 class FIELD_INFO
1368 {
1369 public:
1370 FIELD_INFO()
1371 {
1372 m_Visible = false;
1373 m_Attributes.m_Size = VECTOR2I( DEFAULT_SIZE_TEXT * schIUScale.IU_PER_MILS,
1374 DEFAULT_SIZE_TEXT * schIUScale.IU_PER_MILS );
1375 };
1376
1377 FIELD_INFO( const wxString& aText, SCH_FIELD* aField ) :
1378 m_Text( aText ),
1379 m_Visible( aField->IsVisible() ),
1380 m_Attributes( aField->GetAttributes() ),
1381 m_Pos( aField->GetPosition() )
1382 {}
1383
1384 bool IsEmpty() const { return m_Text.IsEmpty(); }
1385
1386 SCH_FIELD CreateField( T* aSymbol, const wxString& aFieldName )
1387 {
1388 SCH_FIELD field( aSymbol, FIELD_T::USER, aFieldName );
1389
1390 field.SetText( m_Text );
1391 field.SetVisible( m_Visible );
1392 field.SetAttributes( m_Attributes );
1393 field.SetPosition( m_Pos );
1394
1395 return field;
1396 }
1397
1398 public:
1399 wxString m_Text;
1400 bool m_Visible;
1401 TEXT_ATTRIBUTES m_Attributes;
1402 VECTOR2I m_Pos;
1403 };
1404
1405 SCH_FIELD* existing_deviceField = aSymbol.GetField( SIM_DEVICE_FIELD );
1406 SCH_FIELD* existing_deviceSubtypeField = aSymbol.GetField( SIM_DEVICE_SUBTYPE_FIELD );
1407 SCH_FIELD* existing_pinsField = aSymbol.GetField( SIM_PINS_FIELD );
1408 SCH_FIELD* existing_paramsField = aSymbol.GetField( SIM_PARAMS_FIELD );
1409
1410 wxString existing_deviceSubtype;
1411
1412 if( existing_deviceSubtypeField )
1413 existing_deviceSubtype = existing_deviceSubtypeField->GetShownText( false ).Upper();
1414
1415 if( existing_deviceField
1416 || existing_deviceSubtypeField
1417 || existing_pinsField
1418 || existing_paramsField )
1419 {
1420 // Has a current (V7+) model field.
1421
1422 // Up until 7.0RC2 we used '+' and '-' for potentiometer pins, which doesn't match
1423 // SPICE. Here we remap them to 'r0' and 'r1'.
1424 if( existing_deviceSubtype == wxS( "POT" ) )
1425 {
1426 if( existing_pinsField )
1427 {
1428 wxString pinMap = existing_pinsField->GetText();
1429 pinMap.Replace( wxS( "=+" ), wxS( "=r1" ) );
1430 pinMap.Replace( wxS( "=-" ), wxS( "=r0" ) );
1431 existing_pinsField->SetText( pinMap );
1432 }
1433 }
1434
1435 // Up until 8.0RC1 random voltage/current sources were a bit of a mess.
1436 if( existing_deviceSubtype.StartsWith( wxS( "RAND" ) ) )
1437 {
1438 // Re-fetch value without resolving references. If it's an indirect value then we
1439 // can't migrate it.
1440 existing_deviceSubtype = existing_deviceSubtypeField->GetText().Upper();
1441
1442 if( existing_deviceSubtype.Replace( wxS( "NORMAL" ), wxS( "GAUSSIAN" ) ) )
1443 existing_deviceSubtypeField->SetText( existing_deviceSubtype );
1444
1445 if( existing_paramsField )
1446 {
1447 wxString params = existing_paramsField->GetText().Lower();
1448 size_t count = 0;
1449
1450 // We used to support 'min' and 'max' instead of 'range' and 'offset', but we
1451 // wrote all 4 to the netlist which would cause ngspice to barf, so no one has
1452 // working documents with min and max specified. Just delete them if they're
1453 // uninitialized.
1454 count += params.Replace( wxS( "min=0 " ), wxEmptyString );
1455 count += params.Replace( wxS( "max=0 " ), wxEmptyString );
1456
1457 // We used to use 'dt', but the correct ngspice name is 'ts'.
1458 count += params.Replace( wxS( "dt=" ), wxS( "ts=" ) );
1459
1460 if( count )
1461 existing_paramsField->SetText( params );
1462 }
1463 }
1464
1465 // Up until 8.0.1 we treated a mutual inductance statement as a type of inductor --
1466 // which is confusing because it doesn't represent a device at all.
1467 if( existing_deviceSubtype == wxS( "MUTUAL" ) )
1468 {
1469 if( existing_deviceSubtypeField ) // Can't be null, but Coverity doesn't know that
1470 aSymbol.RemoveField( existing_deviceSubtypeField );
1471
1472 if( existing_deviceField )
1473 {
1474 existing_deviceField->SetText( wxS( "K" ) );
1475 }
1476 else
1477 {
1478 FIELD_INFO deviceFieldInfo;
1479 deviceFieldInfo.m_Text = wxS( "K" );
1480
1481 SCH_FIELD deviceField = deviceFieldInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1482 aSymbol.AddField( deviceField );
1483 }
1484 }
1485
1486 return;
1487 }
1488
1489 auto getSIValue =
1490 []( SCH_FIELD* aField )
1491 {
1492 if( !aField ) // no, not really, but it keeps Coverity happy
1493 return wxString( wxEmptyString );
1494
1495 wxRegEx regex( wxT( "([^a-z])(M)(e|E)(g|G)($|[^a-z])" ) );
1496 wxString value = aField->GetText();
1497
1498 // Keep prefix, M, and suffix, but drop e|E and g|G
1499 regex.ReplaceAll( &value, wxT( "\\1\\2\\5" ) );
1500
1501 return value;
1502 };
1503
1504 auto generateDefaultPinMapFromSymbol =
1505 []( const std::vector<SCH_PIN*>& sourcePins )
1506 {
1507 wxString pinMap;
1508
1509 // If we're creating the pinMap from the symbol it means we don't know what the
1510 // SIM_MODEL's pin names are, so just use indexes.
1511
1512 for( unsigned ii = 0; ii < sourcePins.size(); ++ii )
1513 {
1514 if( ii > 0 )
1515 pinMap.Append( wxS( " " ) );
1516
1517 pinMap.Append( wxString::Format( wxT( "%s=%u" ),
1518 sourcePins[ii]->GetNumber(),
1519 ii + 1 ) );
1520 }
1521
1522 return pinMap;
1523 };
1524
1525 wxString prefix = aSymbol.GetPrefix();
1526 SCH_FIELD* valueField = aSymbol.GetField( FIELD_T::VALUE );
1527 bool sourcePinsSorted = false;
1528 std::vector<SCH_PIN*> sourcePins;
1529
1530 if constexpr (std::is_same_v<T, SCH_SYMBOL>)
1531 sourcePins = static_cast<SCH_SYMBOL*>( &aSymbol )->GetPins( nullptr );
1532 else if constexpr (std::is_same_v<T, LIB_SYMBOL>)
1533 sourcePins = static_cast<LIB_SYMBOL*>( &aSymbol )->GetGraphicalPins( 0, 0 );
1534
1535 auto lazySortSourcePins =
1536 [&sourcePins, &sourcePinsSorted]()
1537 {
1538 if( !sourcePinsSorted )
1539 {
1540 std::sort( sourcePins.begin(), sourcePins.end(),
1541 []( const SCH_PIN* lhs, const SCH_PIN* rhs )
1542 {
1543 return StrNumCmp( lhs->GetNumber(), rhs->GetNumber(), true ) < 0;
1544 } );
1545 }
1546
1547 sourcePinsSorted = true;
1548 };
1549
1550 FIELD_INFO deviceInfo;
1551 FIELD_INFO modelInfo;
1552 FIELD_INFO deviceSubtypeInfo;
1553 FIELD_INFO libInfo;
1554 FIELD_INFO spiceParamsInfo;
1555 FIELD_INFO pinMapInfo;
1556 bool modelFromValueField = false;
1557
1558 if( aSymbol.GetField( SIM_LEGACY_PRIMITIVE_FIELD )
1559 || aSymbol.GetField( SIM_LEGACY_PINS_FIELD )
1560 || aSymbol.GetField( SIM_LEGACY_MODEL_FIELD )
1561 || aSymbol.GetField( SIM_LEGACY_ENABLE_FIELD )
1562 || aSymbol.GetField( SIM_LEGACY_LIBRARY_FIELD ) )
1563 {
1564 if( SCH_FIELD* primitiveField = aSymbol.GetField( SIM_LEGACY_PRIMITIVE_FIELD ) )
1565 {
1566 deviceInfo = FIELD_INFO( primitiveField->GetText(), primitiveField );
1567 aSymbol.RemoveField( primitiveField );
1568 }
1569
1570 if( SCH_FIELD* nodeSequenceField = aSymbol.GetField( SIM_LEGACY_PINS_FIELD ) )
1571 {
1572 const wxString delimiters( "{:,; }" );
1573 const wxString& nodeSequence = nodeSequenceField->GetText();
1574 wxString pinMap;
1575
1576 if( nodeSequence != "" )
1577 {
1578 wxStringTokenizer tkz( nodeSequence, delimiters );
1579
1580 for( long modelPinNumber = 1; tkz.HasMoreTokens(); ++modelPinNumber )
1581 {
1582 long symbolPinNumber = 1;
1583 tkz.GetNextToken().ToLong( &symbolPinNumber );
1584
1585 if( modelPinNumber != 1 )
1586 pinMap.Append( " " );
1587
1588 pinMap.Append( wxString::Format( "%ld=%ld", symbolPinNumber, modelPinNumber ) );
1589 }
1590 }
1591
1592 pinMapInfo = FIELD_INFO( pinMap, nodeSequenceField );
1593 aSymbol.RemoveField( nodeSequenceField );
1594 }
1595
1596 if( SCH_FIELD* modelField = aSymbol.GetField( SIM_LEGACY_MODEL_FIELD ) )
1597 {
1598 modelInfo = FIELD_INFO( getSIValue( modelField ), modelField );
1599 aSymbol.RemoveField( modelField );
1600 }
1601 else if( valueField )
1602 {
1603 modelInfo = FIELD_INFO( getSIValue( valueField ), valueField );
1604 modelFromValueField = true;
1605 }
1606
1607 if( SCH_FIELD* libFileField = aSymbol.GetField( SIM_LEGACY_LIBRARY_FIELD ) )
1608 {
1609 libInfo = FIELD_INFO( libFileField->GetText(), libFileField );
1610 aSymbol.RemoveField( libFileField );
1611 }
1612 }
1613 else
1614 {
1615 // Auto convert some legacy fields used in the middle of 7.0 development...
1616
1617 if( SCH_FIELD* legacyType = aSymbol.GetField( wxT( "Sim_Type" ) ) )
1618 {
1619 legacyType->SetName( SIM_DEVICE_SUBTYPE_FIELD );
1620 }
1621
1622 if( SCH_FIELD* legacyDevice = aSymbol.GetField( wxT( "Sim_Device" ) ) )
1623 {
1624 legacyDevice->SetName( SIM_DEVICE_FIELD );
1625 }
1626
1627 if( SCH_FIELD* legacyPins = aSymbol.GetField( wxT( "Sim_Pins" ) ) )
1628 {
1629 bool isPassive = prefix.StartsWith( wxT( "R" ) )
1630 || prefix.StartsWith( wxT( "L" ) )
1631 || prefix.StartsWith( wxT( "C" ) );
1632
1633 // Migrate pins from array of indexes to name-value-pairs
1634 wxString pinMap;
1635 wxArrayString pinIndexes;
1636
1637 wxStringSplit( legacyPins->GetText(), pinIndexes, ' ' );
1638
1639 lazySortSourcePins();
1640
1641 if( isPassive && pinIndexes.size() == 2 && sourcePins.size() == 2 )
1642 {
1643 if( pinIndexes[0] == wxT( "2" ) )
1644 {
1645 pinMap.Printf( wxT( "%s=- %s=+" ),
1646 sourcePins[0]->GetNumber(),
1647 sourcePins[1]->GetNumber() );
1648 }
1649 else
1650 {
1651 pinMap.Printf( wxT( "%s=+ %s=-" ),
1652 sourcePins[0]->GetNumber(),
1653 sourcePins[1]->GetNumber() );
1654 }
1655 }
1656 else
1657 {
1658 for( unsigned ii = 0; ii < pinIndexes.size() && ii < sourcePins.size(); ++ii )
1659 {
1660 if( ii > 0 )
1661 pinMap.Append( wxS( " " ) );
1662
1663 pinMap.Append( wxString::Format( wxT( "%s=%s" ),
1664 sourcePins[ii]->GetNumber(),
1665 pinIndexes[ ii ] ) );
1666 }
1667 }
1668
1669 legacyPins->SetName( SIM_PINS_FIELD );
1670 legacyPins->SetText( pinMap );
1671 }
1672
1673 if( SCH_FIELD* legacyParams = aSymbol.GetField( wxT( "Sim_Params" ) ) )
1674 {
1675 legacyParams->SetName( SIM_PARAMS_FIELD );
1676 }
1677
1678 return;
1679 }
1680
1681 wxString device = deviceInfo.m_Text.Trim( true ).Trim( false );
1682 wxString lib = libInfo.m_Text.Trim( true ).Trim( false );
1683 wxString model = modelInfo.m_Text.Trim( true ).Trim( false );
1684 wxString modelLineParams;
1685
1686 bool libraryModel = false;
1687 bool inferredModel = false;
1688 bool internalModel = false;
1689
1690 if( !lib.IsEmpty() )
1691 {
1693 SIM_LIB_MGR libMgr( aProject );
1694 std::vector<SCH_FIELD> emptyFields;
1695 std::vector<EMBEDDED_FILES*> embeddedFilesStack;
1696
1697 if constexpr (std::is_same_v<T, SCH_SYMBOL>)
1698 {
1699 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( &aSymbol );
1700 embeddedFilesStack.push_back( symbol->Schematic()->GetEmbeddedFiles() );
1701 }
1702
1703 if( EMBEDDED_FILES* symbolEmbeddedFiles = aSymbol.GetEmbeddedFiles() )
1704 {
1705 embeddedFilesStack.push_back( symbolEmbeddedFiles );
1706
1707 if constexpr (std::is_same_v<T, SCH_SYMBOL>)
1708 {
1709 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( &aSymbol );
1710 symbol->GetLibSymbolRef()->AppendParentEmbeddedFiles( embeddedFilesStack );
1711 }
1712 else if constexpr (std::is_same_v<T, LIB_SYMBOL>)
1713 {
1714 LIB_SYMBOL* symbol = static_cast<LIB_SYMBOL*>( &aSymbol );
1715 symbol->AppendParentEmbeddedFiles( embeddedFilesStack );
1716 }
1717 }
1718
1719 libMgr.SetFilesStack( std::move( embeddedFilesStack ) );
1720
1721 // Pull out any following parameters from model name
1722 model = model.BeforeFirst( ' ', &modelLineParams );
1723 modelInfo.m_Text = model;
1724
1725 lazySortSourcePins();
1726
1727 SIM_LIBRARY::MODEL simModel = libMgr.CreateModel( lib, model.ToStdString(),
1728 emptyFields, false, 0,
1729 sourcePins, reporter );
1730
1731 if( reporter.HasMessage() )
1732 libraryModel = false; // Fall back to raw spice model
1733 else
1734 libraryModel = true;
1735
1736 if( pinMapInfo.IsEmpty() )
1737 {
1738 // Try to generate a default pin map from the SIM_MODEL's pins; if that fails,
1739 // generate one from the symbol's pins
1740 pinMapInfo.m_Text = wxString( simModel.model.Serializer().GeneratePins() );
1741
1742 if( pinMapInfo.IsEmpty() )
1743 pinMapInfo.m_Text = generateDefaultPinMapFromSymbol( sourcePins );
1744 }
1745 }
1746 else if( ( device == wxS( "R" )
1747 || device == wxS( "L" )
1748 || device == wxS( "C" )
1749 || device == wxS( "V" )
1750 || device == wxS( "I" ) )
1751 && prefix.StartsWith( device )
1752 && modelFromValueField )
1753 {
1754 inferredModel = true;
1755 }
1756 else if( device == wxS( "V" ) || device == wxS( "I" ) )
1757 {
1758 // See if we have a SPICE time-dependent function such as "sin(0 1 60)" or "sin 0 1 60"
1759 // that can be handled by a built-in SIM_MODEL_SOURCE.
1760
1761 wxStringTokenizer tokenizer( model, wxT( "() " ), wxTOKEN_STRTOK );
1762
1763 if( tokenizer.HasMoreTokens() )
1764 {
1765 deviceSubtypeInfo.m_Text = tokenizer.GetNextToken();
1766 deviceSubtypeInfo.m_Text.MakeUpper();
1767
1768 for( SIM_MODEL::TYPE type : SIM_MODEL::TYPE_ITERATOR() )
1769 {
1770 if( device == SIM_MODEL::SpiceInfo( type ).itemType
1771 && deviceSubtypeInfo.m_Text == SIM_MODEL::SpiceInfo( type ).functionName )
1772 {
1773 try
1774 {
1775 std::unique_ptr<SIM_MODEL> simModel = SIM_MODEL::Create( type );
1776
1777 if( deviceSubtypeInfo.m_Text == wxT( "DC" ) && tokenizer.CountTokens() == 1 )
1778 {
1779 wxCHECK( valueField, /* void */ );
1780 valueField->SetText( tokenizer.GetNextToken() );
1781 modelFromValueField = false;
1782 }
1783 else
1784 {
1785 for( int ii = 0; tokenizer.HasMoreTokens(); ++ii )
1786 {
1787 simModel->SetParamValue( ii, tokenizer.GetNextToken().ToStdString(),
1789 }
1790
1791 deviceSubtypeInfo.m_Text = SIM_MODEL::TypeInfo( type ).fieldValue;
1792
1793 spiceParamsInfo = modelInfo;
1794 spiceParamsInfo.m_Text = wxString( simModel->Serializer().GenerateParams() );
1795 }
1796
1797 internalModel = true;
1798
1799 if( pinMapInfo.IsEmpty() )
1800 {
1801 lazySortSourcePins();
1802
1803 // Generate a default pin map from the SIM_MODEL's pins
1804 simModel->createPins( sourcePins );
1805 pinMapInfo.m_Text = wxString( simModel->Serializer().GeneratePins() );
1806 }
1807 }
1808 catch( ... )
1809 {
1810 // Fall back to raw spice model
1811 }
1812
1813 break;
1814 }
1815 }
1816 }
1817 }
1818
1819 if( libraryModel )
1820 {
1821 SCH_FIELD libField = libInfo.CreateField( &aSymbol, SIM_LIBRARY_FIELD );
1822 aSymbol.AddField( libField );
1823
1824 SCH_FIELD nameField = modelInfo.CreateField( &aSymbol, SIM_NAME_FIELD );
1825 aSymbol.AddField( nameField );
1826
1827 if( !modelLineParams.IsEmpty() )
1828 {
1829 spiceParamsInfo = modelInfo;
1830 spiceParamsInfo.m_Pos.x += nameField.GetBoundingBox().GetWidth();
1831 spiceParamsInfo.m_Text = modelLineParams;
1832
1833 BOX2I nameBBox = nameField.GetBoundingBox();
1834 int nameWidth = nameBBox.GetWidth();
1835
1836 // Add space between model name and additional parameters
1837 nameWidth += KiROUND( nameBBox.GetHeight() * 1.25 );
1838
1839 if( nameField.GetHorizJustify() == GR_TEXT_H_ALIGN_RIGHT )
1840 spiceParamsInfo.m_Pos.x -= nameWidth;
1841 else
1842 spiceParamsInfo.m_Pos.x += nameWidth;
1843
1844 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1845 aSymbol.AddField( paramsField );
1846 }
1847
1848 if( modelFromValueField )
1849 valueField->SetText( wxT( "${SIM.NAME}" ) );
1850 }
1851 else if( inferredModel )
1852 {
1853 // DeviceType is left in the reference designator and Model is left in the value field,
1854 // so there's nothing to do here....
1855 }
1856 else if( internalModel )
1857 {
1858 SCH_FIELD deviceField = deviceInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1859 aSymbol.AddField( deviceField );
1860
1861 if( !deviceSubtypeInfo.m_Text.IsEmpty() )
1862 {
1863 SCH_FIELD subtypeField = deviceSubtypeInfo.CreateField( &aSymbol, SIM_DEVICE_SUBTYPE_FIELD );
1864 aSymbol.AddField( subtypeField );
1865 }
1866
1867 if( !spiceParamsInfo.IsEmpty() )
1868 {
1869 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1870 aSymbol.AddField( paramsField );
1871 }
1872
1873 if( modelFromValueField )
1874 valueField->SetText( wxT( "${SIM.PARAMS}" ) );
1875 }
1876 else // Insert a raw spice model as a substitute.
1877 {
1878 if( device.IsEmpty() && lib.IsEmpty() )
1879 {
1880 spiceParamsInfo = modelInfo;
1881 }
1882 else
1883 {
1884 spiceParamsInfo.m_Text.Printf( wxT( "type=\"%s\" model=\"%s\" lib=\"%s\"" ), device,
1885 model, lib );
1886 }
1887
1888 deviceInfo.m_Text = SIM_MODEL::DeviceInfo( SIM_MODEL::DEVICE_T::SPICE ).fieldValue;
1889
1890 SCH_FIELD deviceField = deviceInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1891 aSymbol.AddField( deviceField );
1892
1893 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1894 aSymbol.AddField( paramsField );
1895
1896 if( modelFromValueField )
1897 {
1898 // Get the current Value field, after previous changes.
1899 valueField = aSymbol.GetField( FIELD_T::VALUE );
1900
1901 if( valueField )
1902 valueField->SetText( wxT( "${SIM.PARAMS}" ) );
1903 }
1904
1905 // We know nothing about the SPICE model here, so we've got no choice but to generate
1906 // the default pin map from the symbol's pins.
1907
1908 if( pinMapInfo.IsEmpty() )
1909 {
1910 lazySortSourcePins();
1911 pinMapInfo.m_Text = generateDefaultPinMapFromSymbol( sourcePins );
1912 }
1913 }
1914
1915 if( !pinMapInfo.IsEmpty() )
1916 {
1917 SCH_FIELD pinsField = pinMapInfo.CreateField( &aSymbol, SIM_PINS_FIELD );
1918 aSymbol.AddField( pinsField );
1919 }
1920}
1921
1922
1924 const PROJECT* aProject );
1926 const PROJECT* aProject );
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:123
BOX2< VECTOR2I > BOX2I
Definition box2.h:918
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:986
constexpr size_type GetWidth() const
Definition box2.h:210
constexpr size_type GetHeight() const
Definition box2.h:211
virtual bool IsVisible() const
Definition eda_text.h:208
void SetAttributes(const EDA_TEXT &aSrc, bool aSetPosition=true)
Set the text attributes from another instance.
Definition eda_text.cpp:428
GR_TEXT_H_ALIGN_T GetHorizJustify() const
Definition eda_text.h:221
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:381
const TEXT_ATTRIBUTES & GetAttributes() const
Definition eda_text.h:252
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:79
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:214
Container for project specific data.
Definition project.h:62
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:71
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:100
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:128
wxString GetShownText(const SCH_SHEET_PATH *aPath, bool aAllowExtraText, int aDepth=0, const wxString &aVariantName=wxEmptyString) 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:268
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:69
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:177
static constexpr auto DIFF_FIELD
SIM_MODEL & CreateModel(SIM_MODEL::TYPE aType, const std::vector< SCH_PIN * > &aPins, REPORTER &aReporter)
void SetFilesStack(std::vector< EMBEDDED_FILES * > aFilesStack)
Definition sim_lib_mgr.h:44
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:503
virtual std::vector< std::string > GetPinNames() const
Definition sim_model.h:463
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:538
virtual bool requiresSpiceModelLine(const SPICE_ITEM &aItem) const
void ClearPins()
std::vector< SIM_MODEL_PIN > m_modelPins
Definition sim_model.h:533
static INFO TypeInfo(TYPE aType)
int GetPinCount() const
Definition sim_model.h:465
void AddPin(const SIM_MODEL_PIN &aPin)
static SPICE_INFO SpiceInfo(TYPE aType)
const SIM_MODEL_SERIALIZER & Serializer() const
Definition sim_model.h:429
bool m_isEnabled
Definition sim_model.h:541
void ReadDataFields(const std::vector< SCH_FIELD > *aFields, bool aResolve, int aDepth, const std::vector< SCH_PIN * > &aPins)
static bool InferSimModel(T &aSymbol, std::vector< SCH_FIELD > *aFields, bool aResolve, int aDepth, SIM_VALUE_GRAMMAR::NOTATION aNotation, wxString *aDeviceType, wxString *aModelType, wxString *aModelParams, wxString *aPinMap)
virtual const PARAM & GetParam(unsigned aParamIndex) const
bool m_isStoredInValue
Definition sim_model.h:542
void createPins(const std::vector< SCH_PIN * > &aSymbolPins)
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)
int GetParamCount() const
Definition sim_model.h:475
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:532
const PARAM & GetParamOverride(unsigned aParamIndex) const
friend class SPICE_GENERATOR
Definition sim_model.h:77
virtual ~SIM_MODEL()
static std::unique_ptr< SIM_MODEL > Create(TYPE aType, const std::vector< SCH_PIN * > &aPins, REPORTER &aReporter)
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:505
const SIM_MODEL_PIN & GetPin(unsigned aIndex) const
Definition sim_model.h:466
std::unique_ptr< SIM_MODEL_SERIALIZER > m_serializer
Definition sim_model.h:535
virtual int doFindParam(const std::string &aParamName) const
TYPE GetType() const
Definition sim_model.h:458
std::vector< std::reference_wrapper< const SIM_MODEL_PIN > > GetPins() const
const TYPE m_type
Definition sim_model.h:540
const SIM_MODEL * m_baseModel
Definition sim_model.h:534
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:189
#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:79
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
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:446
wxString GetFieldValue(const std::vector< SCH_FIELD > *aFields, FIELD_T aFieldType)
Definition sch_field.h:421
SIM_MODEL::TYPE TYPE
Definition sim_model.cpp:54
#define SIM_PINS_FIELD
Definition sim_model.h:50
#define SIM_DEVICE_FIELD
Definition sim_model.h:48
#define SIM_NAME_FIELD
Definition sim_model.h:54
#define SIM_LIBRARY_FIELD
Definition sim_model.h:53
#define SIM_LEGACY_ENABLE_FIELD
Definition sim_model.h:61
#define SIM_LEGACY_ENABLE_FIELD_V7
Definition sim_model.h:57
#define SIM_LEGACY_MODEL_FIELD
Definition sim_model.h:59
#define SIM_LEGACY_PINS_FIELD
Definition sim_model.h:60
#define SIM_LEGACY_LIBRARY_FIELD
Definition sim_model.h:62
#define SIM_PARAMS_FIELD
Definition sim_model.h:52
#define SIM_VALUE_FIELD
Definition sim_model.h:46
#define SIM_LEGACY_PRIMITIVE_FIELD
Definition sim_model.h:58
#define SIM_DEVICE_SUBTYPE_FIELD
Definition sim_model.h:49
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:385
bool Matches(const std::string &aName) const
std::string defaultValue
Definition sim_model.h:379
bool Matches(const std::string &aName) const
Definition sim_model.h:392
std::string value
Definition sim_model.h:397
const INFO & info
Definition sim_model.h:398
static constexpr auto NOT_CONNECTED
Definition sim_model.h:70
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