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, you may find one here:
20 * https://www.gnu.org/licenses/gpl-3.0.html
21 * or you may search the http://www.gnu.org website for the version 3 license,
22 * or you may write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 */
25
26#include <ki_exception.h>
27#include <lib_symbol.h>
28#include <sch_symbol.h>
29#include <string_utils.h>
30#include <wx/regex.h>
31
32#include <iterator>
33
34#include <sim/sim_model.h>
36#include <sim/sim_model_ideal.h>
39#include <sim/sim_model_r_pot.h>
40#include <sim/sim_model_ibis.h>
45#include <sim/sim_model_tline.h>
47#include <sim/sim_lib_mgr.h>
49
50#include <boost/algorithm/string.hpp>
51#include <fmt/core.h>
52#include <pegtl/contrib/parse_tree.hpp>
53
54
56
57using TYPE = SIM_MODEL::TYPE;
58
59
60SIM_MODEL::DEVICE_INFO SIM_MODEL::DeviceInfo( DEVICE_T aDeviceType )
61{
62 switch( aDeviceType )
63 {
64 // | fieldValue | description | showInMenu |
65 // -------------------------------------------------------
66 //
67 case DEVICE_T::NONE: return { "", "", true };
68 case DEVICE_T::R: return { "R", "Resistor", true };
69 case DEVICE_T::C: return { "C", "Capacitor", true };
70 case DEVICE_T::L: return { "L", "Inductor", true };
71 case DEVICE_T::K: return { "K", "Mutual Inductance Statement", true };
72 case DEVICE_T::TLINE: return { "TLINE", "Transmission Line", true };
73 case DEVICE_T::SW: return { "SW", "Switch", true };
74
75 case DEVICE_T::D: return { "D", "Diode", true };
76 case DEVICE_T::NPN: return { "NPN", "NPN BJT", true };
77 case DEVICE_T::PNP: return { "PNP", "PNP BJT", true };
78
79 case DEVICE_T::NJFET: return { "NJFET", "N-channel JFET", true };
80 case DEVICE_T::PJFET: return { "PJFET", "P-channel JFET", true };
81
82 case DEVICE_T::NMOS: return { "NMOS", "N-channel MOSFET", true };
83 case DEVICE_T::PMOS: return { "PMOS", "P-channel MOSFET", true };
84 case DEVICE_T::NMES: return { "NMES", "N-channel MESFET", true };
85 case DEVICE_T::PMES: return { "PMES", "P-channel MESFET", true };
86
87 case DEVICE_T::V: return { "V", "Voltage Source", true };
88 case DEVICE_T::I: return { "I", "Current Source", true };
89 case DEVICE_T::E: return { "E", "Voltage Source", false };
90 case DEVICE_T::F: return { "F", "Current Source", false };
91 case DEVICE_T::G: return { "G", "Current Source", false };
92 case DEVICE_T::H: return { "H", "Voltage Source", false };
93
94 case DEVICE_T::KIBIS: return { "IBIS", "IBIS Model", false };
95
96 case DEVICE_T::SUBCKT: return { "SUBCKT", "Subcircuit", false };
97 case DEVICE_T::XSPICE: return { "XSPICE", "XSPICE Code Model", true };
98 case DEVICE_T::SPICE: return { "SPICE", "Raw SPICE Element", true };
99
100 default: wxFAIL; return {};
101 }
102}
103
104
105SIM_MODEL::INFO SIM_MODEL::TypeInfo( TYPE aType )
106{
107 switch( aType )
108 {
109 // | deviceType | fieldValue | description |
110 // ---------------------------------------------------------------------
111 //
112 case TYPE::NONE: return { DEVICE_T::NONE, "", "" };
113
114 case TYPE::R: return { DEVICE_T::R, "", "Ideal" };
115 case TYPE::R_POT: return { DEVICE_T::R, "POT", "Potentiometer" };
116 case TYPE::R_BEHAVIORAL: return { DEVICE_T::R, "=", "Behavioral" };
117
118 case TYPE::C: return { DEVICE_T::C, "", "Ideal" };
119 case TYPE::C_BEHAVIORAL: return { DEVICE_T::C, "=", "Behavioral" };
120
121 case TYPE::L: return { DEVICE_T::L, "", "Ideal" };
122 case TYPE::L_BEHAVIORAL: return { DEVICE_T::L, "=", "Behavioral" };
123
124 case TYPE::K: return { DEVICE_T::K, "", "Mutual Inductance Statement" };
125
126 case TYPE::TLINE_Z0: return { DEVICE_T::TLINE, "", "Characteristic impedance" };
127 case TYPE::TLINE_RLGC: return { DEVICE_T::TLINE, "RLGC", "RLGC" };
128
129 case TYPE::SW_V: return { DEVICE_T::SW, "V", "Voltage-controlled" };
130 case TYPE::SW_I: return { DEVICE_T::SW, "I", "Current-controlled" };
131
132 case TYPE::D: return { DEVICE_T::D, "", "" };
133
134 case TYPE::NPN_VBIC: return { DEVICE_T::NPN, "VBIC", "VBIC" };
135 case TYPE::PNP_VBIC: return { DEVICE_T::PNP, "VBIC", "VBIC" };
136 case TYPE::NPN_GUMMELPOON: return { DEVICE_T::NPN, "GUMMELPOON", "Gummel-Poon" };
137 case TYPE::PNP_GUMMELPOON: return { DEVICE_T::PNP, "GUMMELPOON", "Gummel-Poon" };
138 //case TYPE::BJT_MEXTRAM: return {};
139 case TYPE::NPN_HICUM2: return { DEVICE_T::NPN, "HICUML2", "HICUM level 2" };
140 case TYPE::PNP_HICUM2: return { DEVICE_T::PNP, "HICUML2", "HICUM level 2" };
141 //case TYPE::BJT_HICUM_L0: return {};
142
143 case TYPE::NJFET_SHICHMANHODGES: return { DEVICE_T::NJFET, "SHICHMANHODGES", "Shichman-Hodges" };
144 case TYPE::PJFET_SHICHMANHODGES: return { DEVICE_T::PJFET, "SHICHMANHODGES", "Shichman-Hodges" };
145 case TYPE::NJFET_PARKERSKELLERN: return { DEVICE_T::NJFET, "PARKERSKELLERN", "Parker-Skellern" };
146 case TYPE::PJFET_PARKERSKELLERN: return { DEVICE_T::PJFET, "PARKERSKELLERN", "Parker-Skellern" };
147
148 case TYPE::NMES_STATZ: return { DEVICE_T::NMES, "STATZ", "Statz" };
149 case TYPE::PMES_STATZ: return { DEVICE_T::PMES, "STATZ", "Statz" };
150 case TYPE::NMES_YTTERDAL: return { DEVICE_T::NMES, "YTTERDAL", "Ytterdal" };
151 case TYPE::PMES_YTTERDAL: return { DEVICE_T::PMES, "YTTERDAL", "Ytterdal" };
152 case TYPE::NMES_HFET1: return { DEVICE_T::NMES, "HFET1", "HFET1" };
153 case TYPE::PMES_HFET1: return { DEVICE_T::PMES, "HFET1", "HFET1" };
154 case TYPE::NMES_HFET2: return { DEVICE_T::NMES, "HFET2", "HFET2" };
155 case TYPE::PMES_HFET2: return { DEVICE_T::PMES, "HFET2", "HFET2" };
156
157 case TYPE::NMOS_VDMOS: return { DEVICE_T::NMOS, "VDMOS", "VDMOS" };
158 case TYPE::PMOS_VDMOS: return { DEVICE_T::PMOS, "VDMOS", "VDMOS" };
159 case TYPE::NMOS_MOS1: return { DEVICE_T::NMOS, "MOS1", "Classical quadratic (MOS1)" };
160 case TYPE::PMOS_MOS1: return { DEVICE_T::PMOS, "MOS1", "Classical quadratic (MOS1)" };
161 case TYPE::NMOS_MOS2: return { DEVICE_T::NMOS, "MOS2", "Grove-Frohman (MOS2)" };
162 case TYPE::PMOS_MOS2: return { DEVICE_T::PMOS, "MOS2", "Grove-Frohman (MOS2)" };
163 case TYPE::NMOS_MOS3: return { DEVICE_T::NMOS, "MOS3", "MOS3" };
164 case TYPE::PMOS_MOS3: return { DEVICE_T::PMOS, "MOS3", "MOS3" };
165 case TYPE::NMOS_BSIM1: return { DEVICE_T::NMOS, "BSIM1", "BSIM1" };
166 case TYPE::PMOS_BSIM1: return { DEVICE_T::PMOS, "BSIM1", "BSIM1" };
167 case TYPE::NMOS_BSIM2: return { DEVICE_T::NMOS, "BSIM2", "BSIM2" };
168 case TYPE::PMOS_BSIM2: return { DEVICE_T::PMOS, "BSIM2", "BSIM2" };
169 case TYPE::NMOS_MOS6: return { DEVICE_T::NMOS, "MOS6", "MOS6" };
170 case TYPE::PMOS_MOS6: return { DEVICE_T::PMOS, "MOS6", "MOS6" };
171 case TYPE::NMOS_BSIM3: return { DEVICE_T::NMOS, "BSIM3", "BSIM3" };
172 case TYPE::PMOS_BSIM3: return { DEVICE_T::PMOS, "BSIM3", "BSIM3" };
173 case TYPE::NMOS_MOS9: return { DEVICE_T::NMOS, "MOS9", "MOS9" };
174 case TYPE::PMOS_MOS9: return { DEVICE_T::PMOS, "MOS9", "MOS9" };
175 case TYPE::NMOS_B4SOI: return { DEVICE_T::NMOS, "B4SOI", "BSIM4 SOI (B4SOI)" };
176 case TYPE::PMOS_B4SOI: return { DEVICE_T::PMOS, "B4SOI", "BSIM4 SOI (B4SOI)" };
177 case TYPE::NMOS_BSIM4: return { DEVICE_T::NMOS, "BSIM4", "BSIM4" };
178 case TYPE::PMOS_BSIM4: return { DEVICE_T::PMOS, "BSIM4", "BSIM4" };
179 //case TYPE::NMOS_EKV2_6: return {};
180 //case TYPE::PMOS_EKV2_6: return {};
181 //case TYPE::NMOS_PSP: return {};
182 //case TYPE::PMOS_PSP: return {};
183 case TYPE::NMOS_B3SOIFD: return { DEVICE_T::NMOS, "B3SOIFD", "B3SOIFD (BSIM3 FD-SOI)" };
184 case TYPE::PMOS_B3SOIFD: return { DEVICE_T::PMOS, "B3SOIFD", "B3SOIFD (BSIM3 FD-SOI)" };
185 case TYPE::NMOS_B3SOIDD: return { DEVICE_T::NMOS, "B3SOIDD", "B3SOIDD (BSIM3 SOI)" };
186 case TYPE::PMOS_B3SOIDD: return { DEVICE_T::PMOS, "B3SOIDD", "B3SOIDD (BSIM3 SOI)" };
187 case TYPE::NMOS_B3SOIPD: return { DEVICE_T::NMOS, "B3SOIPD", "B3SOIPD (BSIM3 PD-SOI)" };
188 case TYPE::PMOS_B3SOIPD: return { DEVICE_T::PMOS, "B3SOIPD", "B3SOIPD (BSIM3 PD-SOI)" };
189 //case TYPE::NMOS_STAG: return {};
190 //case TYPE::PMOS_STAG: return {};
191 case TYPE::NMOS_HISIM2: return { DEVICE_T::NMOS, "HISIM2", "HiSIM2" };
192 case TYPE::PMOS_HISIM2: return { DEVICE_T::PMOS, "HISIM2", "HiSIM2" };
193 case TYPE::NMOS_HISIMHV1: return { DEVICE_T::NMOS, "HISIMHV1", "HiSIM_HV1" };
194 case TYPE::PMOS_HISIMHV1: return { DEVICE_T::PMOS, "HISIMHV1", "HiSIM_HV1" };
195 case TYPE::NMOS_HISIMHV2: return { DEVICE_T::NMOS, "HISIMHV2", "HiSIM_HV2" };
196 case TYPE::PMOS_HISIMHV2: return { DEVICE_T::PMOS, "HISIMHV2", "HiSIM_HV2" };
197
198 case TYPE::V: return { DEVICE_T::V, "DC", "DC", };
199 case TYPE::V_SIN: return { DEVICE_T::V, "SIN", "Sine" };
200 case TYPE::V_PULSE: return { DEVICE_T::V, "PULSE", "Pulse" };
201 case TYPE::V_EXP: return { DEVICE_T::V, "EXP", "Exponential" };
202 case TYPE::V_AM: return { DEVICE_T::V, "AM", "Amplitude modulated" };
203 case TYPE::V_SFFM: return { DEVICE_T::V, "SFFM", "Single-frequency FM" };
204 case TYPE::V_VCL: return { DEVICE_T::E, "", "Voltage-controlled" };
205 case TYPE::V_CCL: return { DEVICE_T::H, "", "Current-controlled" };
206 case TYPE::V_PWL: return { DEVICE_T::V, "PWL", "Piecewise linear" };
207 case TYPE::V_WHITENOISE: return { DEVICE_T::V, "WHITENOISE", "White noise" };
208 case TYPE::V_PINKNOISE: return { DEVICE_T::V, "PINKNOISE", "Pink noise (1/f)" };
209 case TYPE::V_BURSTNOISE: return { DEVICE_T::V, "BURSTNOISE", "Burst noise" };
210 case TYPE::V_RANDUNIFORM: return { DEVICE_T::V, "RANDUNIFORM", "Random uniform" };
211 case TYPE::V_RANDGAUSSIAN: return { DEVICE_T::V, "RANDGAUSSIAN", "Random Gaussian" };
212 case TYPE::V_RANDEXP: return { DEVICE_T::V, "RANDEXP", "Random exponential" };
213 case TYPE::V_RANDPOISSON: return { DEVICE_T::V, "RANDPOISSON", "Random Poisson" };
214 case TYPE::V_BEHAVIORAL: return { DEVICE_T::V, "=", "Behavioral" };
215
216 case TYPE::I: return { DEVICE_T::I, "DC", "DC", };
217 case TYPE::I_SIN: return { DEVICE_T::I, "SIN", "Sine" };
218 case TYPE::I_PULSE: return { DEVICE_T::I, "PULSE", "Pulse" };
219 case TYPE::I_EXP: return { DEVICE_T::I, "EXP", "Exponential" };
220 case TYPE::I_AM: return { DEVICE_T::I, "AM", "Amplitude modulated" };
221 case TYPE::I_SFFM: return { DEVICE_T::I, "SFFM", "Single-frequency FM" };
222 case TYPE::I_VCL: return { DEVICE_T::G, "", "Voltage-controlled" };
223 case TYPE::I_CCL: return { DEVICE_T::F, "", "Current-controlled" };
224 case TYPE::I_PWL: return { DEVICE_T::I, "PWL", "Piecewise linear" };
225 case TYPE::I_WHITENOISE: return { DEVICE_T::I, "WHITENOISE", "White noise" };
226 case TYPE::I_PINKNOISE: return { DEVICE_T::I, "PINKNOISE", "Pink noise (1/f)" };
227 case TYPE::I_BURSTNOISE: return { DEVICE_T::I, "BURSTNOISE", "Burst noise" };
228 case TYPE::I_RANDUNIFORM: return { DEVICE_T::I, "RANDUNIFORM", "Random uniform" };
229 case TYPE::I_RANDGAUSSIAN: return { DEVICE_T::I, "RANDGAUSSIAN", "Random Gaussian" };
230 case TYPE::I_RANDEXP: return { DEVICE_T::I, "RANDEXP", "Random exponential" };
231 case TYPE::I_RANDPOISSON: return { DEVICE_T::I, "RANDPOISSON", "Random Poisson" };
232 case TYPE::I_BEHAVIORAL: return { DEVICE_T::I, "=", "Behavioral" };
233
234 case TYPE::SUBCKT: return { DEVICE_T::SUBCKT, "", "Subcircuit" };
235 case TYPE::XSPICE: return { DEVICE_T::XSPICE, "", "" };
236
237 case TYPE::KIBIS_DEVICE: return { DEVICE_T::KIBIS, "DEVICE", "Device" };
238 case TYPE::KIBIS_DRIVER_DC: return { DEVICE_T::KIBIS, "DCDRIVER", "DC driver" };
239 case TYPE::KIBIS_DRIVER_RECT: return { DEVICE_T::KIBIS, "RECTDRIVER", "Rectangular wave driver" };
240 case TYPE::KIBIS_DRIVER_PRBS: return { DEVICE_T::KIBIS, "PRBSDRIVER", "PRBS driver" };
241
242 case TYPE::RAWSPICE: return { DEVICE_T::SPICE, "", "" };
243
244 default: wxFAIL; return {};
245 }
246}
247
248
250{
251 switch( aType )
252 {
253 // | itemType | modelType | fnName | level |isDefaultLvl|hasExpr|version|
254 // -------------------------------------------------------------------------
255 case TYPE::R: return { "R", "" };
256 case TYPE::R_POT: return { "A", "" };
257 case TYPE::R_BEHAVIORAL: return { "R", "", "", "0", false, true };
258
259 case TYPE::C: return { "C", "" };
260 case TYPE::C_BEHAVIORAL: return { "C", "", "", "0", false, true };
261
262 case TYPE::L: return { "L", "" };
263 case TYPE::L_BEHAVIORAL: return { "L", "", "", "0", false, true };
264
265 case TYPE::K: return { "K", "" };
266
267 //case TYPE::TLINE_Z0: return { "T" };
268 case TYPE::TLINE_Z0: return { "O", "LTRA" };
269 case TYPE::TLINE_RLGC: return { "O", "LTRA" };
270
271 case TYPE::SW_V: return { "S", "SW" };
272 case TYPE::SW_I: return { "W", "CSW" };
273
274 case TYPE::D: return { "D", "D" };
275
276 case TYPE::NPN_VBIC: return { "Q", "NPN", "", "4" };
277 case TYPE::PNP_VBIC: return { "Q", "PNP", "", "4" };
278 case TYPE::NPN_GUMMELPOON: return { "Q", "NPN", "", "1", true };
279 case TYPE::PNP_GUMMELPOON: return { "Q", "PNP", "", "1", true };
280 case TYPE::NPN_HICUM2: return { "Q", "NPN", "", "8" };
281 case TYPE::PNP_HICUM2: return { "Q", "PNP", "", "8" };
282
283 case TYPE::NJFET_SHICHMANHODGES: return { "J", "NJF", "", "1", true };
284 case TYPE::PJFET_SHICHMANHODGES: return { "J", "PJF", "", "1", true };
285 case TYPE::NJFET_PARKERSKELLERN: return { "J", "NJF", "", "2" };
286 case TYPE::PJFET_PARKERSKELLERN: return { "J", "PJF", "", "2" };
287
288 case TYPE::NMES_STATZ: return { "Z", "NMF", "", "1", true };
289 case TYPE::PMES_STATZ: return { "Z", "PMF", "", "1", true };
290 case TYPE::NMES_YTTERDAL: return { "Z", "NMF", "", "2" };
291 case TYPE::PMES_YTTERDAL: return { "Z", "PMF", "", "2" };
292 case TYPE::NMES_HFET1: return { "Z", "NMF", "", "5" };
293 case TYPE::PMES_HFET1: return { "Z", "PMF", "", "5" };
294 case TYPE::NMES_HFET2: return { "Z", "NMF", "", "6" };
295 case TYPE::PMES_HFET2: return { "Z", "PMF", "", "6" };
296
297 case TYPE::NMOS_VDMOS: return { "M", "VDMOS NCHAN" };
298 case TYPE::PMOS_VDMOS: return { "M", "VDMOS PCHAN" };
299 case TYPE::NMOS_MOS1: return { "M", "NMOS", "", "1", true };
300 case TYPE::PMOS_MOS1: return { "M", "PMOS", "", "1", true };
301 case TYPE::NMOS_MOS2: return { "M", "NMOS", "", "2" };
302 case TYPE::PMOS_MOS2: return { "M", "PMOS", "", "2" };
303 case TYPE::NMOS_MOS3: return { "M", "NMOS", "", "3" };
304 case TYPE::PMOS_MOS3: return { "M", "PMOS", "", "3" };
305 case TYPE::NMOS_BSIM1: return { "M", "NMOS", "", "4" };
306 case TYPE::PMOS_BSIM1: return { "M", "PMOS", "", "4" };
307 case TYPE::NMOS_BSIM2: return { "M", "NMOS", "", "5" };
308 case TYPE::PMOS_BSIM2: return { "M", "PMOS", "", "5" };
309 case TYPE::NMOS_MOS6: return { "M", "NMOS", "", "6" };
310 case TYPE::PMOS_MOS6: return { "M", "PMOS", "", "6" };
311 case TYPE::NMOS_BSIM3: return { "M", "NMOS", "", "8" };
312 case TYPE::PMOS_BSIM3: return { "M", "PMOS", "", "8" };
313 case TYPE::NMOS_MOS9: return { "M", "NMOS", "", "9" };
314 case TYPE::PMOS_MOS9: return { "M", "PMOS", "", "9" };
315 case TYPE::NMOS_B4SOI: return { "M", "NMOS", "", "10" };
316 case TYPE::PMOS_B4SOI: return { "M", "PMOS", "", "10" };
317 case TYPE::NMOS_BSIM4: return { "M", "NMOS", "", "14" };
318 case TYPE::PMOS_BSIM4: return { "M", "PMOS", "", "14" };
319 //case TYPE::NMOS_EKV2_6: return {};
320 //case TYPE::PMOS_EKV2_6: return {};
321 //case TYPE::NMOS_PSP: return {};
322 //case TYPE::PMOS_PSP: return {};
323 case TYPE::NMOS_B3SOIFD: return { "M", "NMOS", "", "55" };
324 case TYPE::PMOS_B3SOIFD: return { "M", "PMOS", "", "55" };
325 case TYPE::NMOS_B3SOIDD: return { "M", "NMOS", "", "56" };
326 case TYPE::PMOS_B3SOIDD: return { "M", "PMOS", "", "56" };
327 case TYPE::NMOS_B3SOIPD: return { "M", "NMOS", "", "57" };
328 case TYPE::PMOS_B3SOIPD: return { "M", "PMOS", "", "57" };
329 //case TYPE::NMOS_STAG: return {};
330 //case TYPE::PMOS_STAG: return {};
331 case TYPE::NMOS_HISIM2: return { "M", "NMOS", "", "68" };
332 case TYPE::PMOS_HISIM2: return { "M", "PMOS", "", "68" };
333 case TYPE::NMOS_HISIMHV1: return { "M", "NMOS", "", "73", false, false, "1.2.4" };
334 case TYPE::PMOS_HISIMHV1: return { "M", "PMOS", "", "73", false, false, "1.2.4" };
335 case TYPE::NMOS_HISIMHV2: return { "M", "NMOS", "", "73", false, false, "2.2.0" };
336 case TYPE::PMOS_HISIMHV2: return { "M", "PMOS", "", "73", false, false, "2.2.0" };
337
338 case TYPE::V: return { "V", "", "DC" };
339 case TYPE::V_SIN: return { "V", "", "SIN" };
340 case TYPE::V_PULSE: return { "V", "", "PULSE" };
341 case TYPE::V_EXP: return { "V", "", "EXP" };
342 case TYPE::V_AM: return { "V", "", "AM" };
343 case TYPE::V_SFFM: return { "V", "", "SFFM" };
344 case TYPE::V_VCL: return { "E", "", "" };
345 case TYPE::V_CCL: return { "H", "", "" };
346 case TYPE::V_PWL: return { "V", "", "PWL" };
347 case TYPE::V_WHITENOISE: return { "V", "", "TRNOISE" };
348 case TYPE::V_PINKNOISE: return { "V", "", "TRNOISE" };
349 case TYPE::V_BURSTNOISE: return { "V", "", "TRNOISE" };
350 case TYPE::V_RANDUNIFORM: return { "V", "", "TRRANDOM" };
351 case TYPE::V_RANDGAUSSIAN: return { "V", "", "TRRANDOM" };
352 case TYPE::V_RANDEXP: return { "V", "", "TRRANDOM" };
353 case TYPE::V_RANDPOISSON: return { "V", "", "TRRANDOM" };
354 case TYPE::V_BEHAVIORAL: return { "B" };
355
356 case TYPE::I: return { "I", "", "DC" };
357 case TYPE::I_PULSE: return { "I", "", "PULSE" };
358 case TYPE::I_SIN: return { "I", "", "SIN" };
359 case TYPE::I_EXP: return { "I", "", "EXP" };
360 case TYPE::I_AM: return { "I", "", "AM" };
361 case TYPE::I_SFFM: return { "I", "", "SFFM" };
362 case TYPE::I_VCL: return { "G", "", "" };
363 case TYPE::I_CCL: return { "F", "", "" };
364 case TYPE::I_PWL: return { "I", "", "PWL" };
365 case TYPE::I_WHITENOISE: return { "I", "", "TRNOISE" };
366 case TYPE::I_PINKNOISE: return { "I", "", "TRNOISE" };
367 case TYPE::I_BURSTNOISE: return { "I", "", "TRNOISE" };
368 case TYPE::I_RANDUNIFORM: return { "I", "", "TRRANDOM" };
369 case TYPE::I_RANDGAUSSIAN: return { "I", "", "TRRANDOM" };
370 case TYPE::I_RANDEXP: return { "I", "", "TRRANDOM" };
371 case TYPE::I_RANDPOISSON: return { "I", "", "TRRANDOM" };
372 case TYPE::I_BEHAVIORAL: return { "B" };
373
374 case TYPE::SUBCKT: return { "X" };
375 case TYPE::XSPICE: return { "A" };
376
377 case TYPE::KIBIS_DEVICE: return { "X" };
378 case TYPE::KIBIS_DRIVER_DC: return { "X" };
379 case TYPE::KIBIS_DRIVER_RECT: return { "X" };
380 case TYPE::KIBIS_DRIVER_PRBS: return { "X" };
381
382 case TYPE::NONE:
383 case TYPE::RAWSPICE: return {};
384
385 default: wxFAIL; return {};
386 }
387}
388
389
390TYPE SIM_MODEL::ReadTypeFromFields( const std::vector<SCH_FIELD>& aFields, bool aResolve, int aDepth,
391 REPORTER& aReporter )
392{
393 std::string deviceTypeFieldValue = GetFieldValue( &aFields, SIM_DEVICE_FIELD, aResolve, aDepth );
394 std::string typeFieldValue = GetFieldValue( &aFields, SIM_DEVICE_SUBTYPE_FIELD, aResolve, aDepth );
395
396 if( !deviceTypeFieldValue.empty() )
397 {
398 for( TYPE type : TYPE_ITERATOR() )
399 {
400 if( typeFieldValue == TypeInfo( type ).fieldValue )
401 {
402 if( deviceTypeFieldValue == DeviceInfo( TypeInfo( type ).deviceType ).fieldValue )
403 return type;
404 }
405 }
406 }
407
408 if( typeFieldValue.empty() )
409 return TYPE::NONE;
410
411 wxString reference = GetFieldValue( &aFields, FIELD_T::REFERENCE );
412
413 if( !reference.IsEmpty() )
414 {
415 aReporter.Report( wxString::Format( _( "No simulation model definition found for "
416 "symbol '%s'." ),
417 reference ),
419 }
420 else
421 {
422 aReporter.Report( _( "No simulation model definition found." ),
424 }
425
426 return TYPE::NONE;
427}
428
429
430void SIM_MODEL::ReadDataFields( const std::vector<SCH_FIELD>* aFields, bool aResolve, int aDepth,
431 const std::vector<SCH_PIN*>& aPins )
432{
433 bool diffMode = GetFieldValue( aFields, SIM_LIBRARY_IBIS::DIFF_FIELD, aResolve, aDepth ) == "1";
434 SwitchSingleEndedDiff( diffMode );
435
436 m_serializer->ParseEnable( GetFieldValue( aFields, SIM_LEGACY_ENABLE_FIELD_V7, aResolve, aDepth ) );
437
438 createPins( aPins );
439 m_serializer->ParsePins( GetFieldValue( aFields, SIM_PINS_FIELD, aResolve, aDepth ) );
440
441 std::string paramsField = GetFieldValue( aFields, SIM_PARAMS_FIELD, aResolve, aDepth );
442
443 if( !m_serializer->ParseParams( paramsField ) )
444 m_serializer->ParseValue( GetFieldValue( aFields, SIM_VALUE_FIELD, aResolve, aDepth ) );
445}
446
447
448void SIM_MODEL::WriteFields( std::vector<SCH_FIELD>& aFields, const SCH_SHEET_PATH* aSheetPath,
449 const wxString& aVariantName ) const
450{
451 // Remove duplicate fields: they are at the end of list
452 for( size_t ii = aFields.size() - 1; ii > 0; ii-- )
453 {
454 wxString currFieldName = aFields[ii].GetName();
455
456 auto end_candidate_list = aFields.begin() + ii - 1;
457
458 auto fieldIt = std::find_if( aFields.begin(), end_candidate_list,
459 [&]( const SCH_FIELD& f )
460 {
461 return f.GetName() == currFieldName;
462 } );
463
464 // If duplicate field found: remove current checked item
465 if( fieldIt != end_candidate_list )
466 aFields.erase( aFields.begin() + ii );
467 }
468
469 SetFieldValue( aFields, SIM_DEVICE_FIELD, m_serializer->GenerateDevice(), false,
470 aSheetPath, aVariantName );
471 SetFieldValue( aFields, SIM_DEVICE_SUBTYPE_FIELD, m_serializer->GenerateDeviceSubtype(), false,
472 aSheetPath, aVariantName );
473
474 SetFieldValue( aFields, SIM_LEGACY_ENABLE_FIELD_V7, m_serializer->GenerateEnable(), false,
475 aSheetPath, aVariantName );
476 SetFieldValue( aFields, SIM_PINS_FIELD, m_serializer->GeneratePins(), false, aSheetPath, aVariantName );
477
478 SetFieldValue( aFields, SIM_PARAMS_FIELD, m_serializer->GenerateParams(), false, aSheetPath, aVariantName );
479
480 if( IsStoredInValue() )
481 SetFieldValue( aFields, SIM_VALUE_FIELD, m_serializer->GenerateValue(), false, aSheetPath, aVariantName );
482}
483
484
485std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( TYPE aType, const std::vector<SCH_PIN*>& aPins,
486 REPORTER& aReporter )
487{
488 std::unique_ptr<SIM_MODEL> model = Create( aType );
489
490 try
491 {
492 // Passing nullptr to ReadDataFields will make it act as if all fields were empty.
493 model->ReadDataFields( static_cast<const std::vector<SCH_FIELD>*>( nullptr ),
494 false, 0, aPins );
495 }
496 catch( IO_ERROR& )
497 {
498 wxFAIL_MSG( "Shouldn't throw reading empty fields!" );
499 }
500
501 return model;
502}
503
504
505std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const SIM_MODEL* aBaseModel,
506 const std::vector<SCH_PIN*>& aPins,
507 REPORTER& aReporter )
508{
509 std::unique_ptr<SIM_MODEL> model;
510
511 if( aBaseModel )
512 {
513 TYPE type = aBaseModel->GetType();
514
515 if( dynamic_cast<const SIM_MODEL_SPICE_FALLBACK*>( aBaseModel ) )
516 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
517 else if( dynamic_cast< const SIM_MODEL_RAW_SPICE*>( aBaseModel ) )
518 model = std::make_unique<SIM_MODEL_RAW_SPICE>();
519 else
520 model = Create( type );
521
522 model->SetBaseModel( *aBaseModel );
523 }
524 else // No base model means the model wasn't found in the library, so create a fallback
525 {
526 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( TYPE::NONE );
527 }
528
529 try
530 {
531 model->ReadDataFields( static_cast<const std::vector<SCH_FIELD>*>( nullptr ),
532 false, 0, aPins );
533 }
534 catch( IO_ERROR& )
535 {
536 wxFAIL_MSG( "Shouldn't throw reading empty fields!" );
537 }
538
539 return model;
540}
541
542
543std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const SIM_MODEL* aBaseModel,
544 const std::vector<SCH_PIN*>& aPins,
545 const std::vector<SCH_FIELD>& aFields,
546 bool aResolve, int aDepth, REPORTER& aReporter )
547{
548 std::unique_ptr<SIM_MODEL> model;
549
550 if( aBaseModel )
551 {
552 NULL_REPORTER devnull;
553 TYPE type = aBaseModel->GetType();
554 TYPE type_override = ReadTypeFromFields( aFields, aResolve, aDepth, devnull );
555
556 // Check for an override in the case of IBIS models.
557 // The other models require type to be set from the base model.
558 if( dynamic_cast<const SIM_MODEL_IBIS*>( aBaseModel ) &&
559 type_override != TYPE::NONE )
560 {
561 type = type_override;
562 }
563
564 if( dynamic_cast<const SIM_MODEL_SPICE_FALLBACK*>( aBaseModel ) )
565 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
566 else if( dynamic_cast< const SIM_MODEL_RAW_SPICE*>( aBaseModel ) )
567 model = std::make_unique<SIM_MODEL_RAW_SPICE>();
568 else
569 model = Create( type );
570
571 model->SetBaseModel( *aBaseModel );
572 }
573 else // No base model means the model wasn't found in the library, so create a fallback
574 {
575 TYPE type = ReadTypeFromFields( aFields, aResolve, aDepth, aReporter );
576 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
577 }
578
579 try
580 {
581 model->ReadDataFields( &aFields, aResolve, aDepth, aPins );
582 }
583 catch( IO_ERROR& err )
584 {
585 aReporter.Report( wxString::Format( _( "Error reading simulation model from symbol '%s':\n%s" ),
587 err.Problem() ),
589 }
590
591 return model;
592}
593
594
595std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const std::vector<SCH_FIELD>& aFields,
596 bool aResolve, int aDepth,
597 const std::vector<SCH_PIN*>& aPins, REPORTER& aReporter )
598{
599 TYPE type = ReadTypeFromFields( aFields, aResolve, aDepth, aReporter );
600 std::unique_ptr<SIM_MODEL> model = SIM_MODEL::Create( type );
601
602 try
603 {
604 model->ReadDataFields( &aFields, aResolve, aDepth, aPins );
605 }
606 catch( const IO_ERROR& parse_err )
607 {
608 if( !aResolve )
609 {
610 aReporter.Report( parse_err.What(), RPT_SEVERITY_ERROR );
611 return model;
612 }
613
614 // Just because we can't parse it doesn't mean that a SPICE interpreter can't. Fall
615 // back to a raw spice code model.
616
617 std::string modelData = GetFieldValue( &aFields, SIM_PARAMS_FIELD, aResolve, aDepth );
618
619 if( modelData.empty() )
620 modelData = GetFieldValue( &aFields, SIM_VALUE_FIELD, aResolve, aDepth );
621
622 model = std::make_unique<SIM_MODEL_RAW_SPICE>( modelData );
623
624 try
625 {
626 model->createPins( aPins );
627 model->m_serializer->ParsePins( GetFieldValue( &aFields, SIM_PINS_FIELD, aResolve, aDepth ) );
628 }
629 catch( const IO_ERROR& err )
630 {
631 // We own the pin syntax, so if we can't parse it then there's an error.
632 aReporter.Report( wxString::Format( _( "Error reading simulation model from symbol '%s':\n%s" ),
634 err.Problem() ),
636 }
637 }
638
639 return model;
640}
641
642
643SIM_MODEL::~SIM_MODEL() = default;
644
645
647{
648 m_modelPins.push_back( aPin );
649}
650
651
653{
654 m_modelPins.clear();
655}
656
657
658int SIM_MODEL::FindModelPinIndex( const std::string& aSymbolPinNumber )
659{
660 for( int modelPinIndex = 0; modelPinIndex < GetPinCount(); ++modelPinIndex )
661 {
662 if( GetPin( modelPinIndex ).symbolPinNumber == aSymbolPinNumber )
663 return modelPinIndex;
664 }
665
667}
668
669
671{
672 m_params.emplace_back( aInfo );
673
674 // Enums are initialized with their default values.
675 if( aInfo.enumValues.size() >= 1 )
676 m_params.back().value = aInfo.defaultValue;
677}
678
679
680void SIM_MODEL::SetBaseModel( const SIM_MODEL& aBaseModel )
681{
682 wxASSERT_MSG( GetType() == aBaseModel.GetType(),
683 wxS( "Simulation model type must be the same as its base class!" ) );
684
685 m_baseModel = &aBaseModel;
686}
687
688
689std::vector<std::reference_wrapper<const SIM_MODEL_PIN>> SIM_MODEL::GetPins() const
690{
691 std::vector<std::reference_wrapper<const SIM_MODEL_PIN>> pins;
692
693 for( int modelPinIndex = 0; modelPinIndex < GetPinCount(); ++modelPinIndex )
694 pins.emplace_back( GetPin( modelPinIndex ) );
695
696 return pins;
697}
698
700 const wxString& aSymbolPinNumber )
701{
702 if( aModelPinIndex >= 0 && aModelPinIndex < (int) m_modelPins.size() )
703 m_modelPins.at( aModelPinIndex ).symbolPinNumber = aSymbolPinNumber;
704}
705
706
707void SIM_MODEL::AssignSymbolPinNumberToModelPin( const std::string& aModelPinName,
708 const wxString& aSymbolPinNumber )
709{
711 {
712 if( pin.modelPinName == aModelPinName )
713 {
714 pin.symbolPinNumber = aSymbolPinNumber;
715 return;
716 }
717 }
718
719 // If aPinName wasn't in fact a name, see if it's a raw (1-based) index. This is required
720 // for legacy files which didn't use pin names.
721 int pinIndex = (int) strtol( aModelPinName.c_str(), nullptr, 10 );
722
723 if( pinIndex < 1 || pinIndex > (int) m_modelPins.size() )
724 THROW_IO_ERROR( wxString::Format( _( "Unknown simulation model pin '%s'" ), aModelPinName ) );
725
726 m_modelPins[ --pinIndex /* convert to 0-based */ ].symbolPinNumber = aSymbolPinNumber;
727}
728
729
730const SIM_MODEL::PARAM& SIM_MODEL::GetParam( unsigned aParamIndex ) const
731{
732 if( m_baseModel && m_params.at( aParamIndex ).value == "" )
733 return m_baseModel->GetParam( aParamIndex );
734 else
735 return m_params.at( aParamIndex );
736}
737
738
739bool SIM_MODEL::PARAM::INFO::Matches( const std::string& aParamName ) const
740{
741 return boost::iequals( name, aParamName );
742}
743
744
745int SIM_MODEL::doFindParam( const std::string& aParamName ) const
746{
747 for( int ii = 0; ii < (int) GetParamCount(); ++ii )
748 {
749 if( GetParam( ii ).Matches( aParamName ) )
750 return ii;
751 }
752
753 return -1;
754}
755
756
757const SIM_MODEL::PARAM* SIM_MODEL::FindParam( const std::string& aParamName ) const
758{
759 int idx = doFindParam( aParamName );
760
761 return idx >= 0 ? &GetParam( idx ) : nullptr;
762}
763
764
765const SIM_MODEL::PARAM& SIM_MODEL::GetParamOverride( unsigned aParamIndex ) const
766{
767 return m_params.at( aParamIndex );
768}
769
770
771const SIM_MODEL::PARAM& SIM_MODEL::GetBaseParam( unsigned aParamIndex ) const
772{
773 if( m_baseModel )
774 return m_baseModel->GetParam( aParamIndex );
775 else
776 return m_params.at( aParamIndex );
777}
778
779
780void SIM_MODEL::doSetParamValue( int aParamIndex, const std::string& aValue )
781{
782 m_params.at( aParamIndex ).value = aValue;
783}
784
785
786void SIM_MODEL::SetParamValue( int aParamIndex, const std::string& aValue,
787 SIM_VALUE::NOTATION aNotation )
788{
789 // Notation conversion is very slow. Avoid if possible.
790
791 auto plainNumber =
792 []( const std::string& aString )
793 {
794 for( char c : aString )
795 {
796 if( c != '.' && ( c < '0' || c > '9' ) )
797 return false;
798 }
799
800 return true;
801 };
802
803
804 if( aValue.find( ',' ) != std::string::npos )
805 {
806 doSetParamValue( aParamIndex, SIM_VALUE::ConvertNotation( aValue, aNotation,
807 SIM_VALUE::NOTATION::SI ) );
808 }
809 else if( aNotation != SIM_VALUE::NOTATION::SI && !plainNumber( aValue ) )
810 {
811 doSetParamValue( aParamIndex, SIM_VALUE::ConvertNotation( aValue, aNotation,
812 SIM_VALUE::NOTATION::SI ) );
813 }
814 else
815 {
816 doSetParamValue( aParamIndex, aValue );
817 }
818}
819
820
821void SIM_MODEL::SetParamValue( const std::string& aParamName, const std::string& aValue,
822 SIM_VALUE::NOTATION aNotation )
823{
824 int idx = doFindParam( aParamName );
825
826 if( idx < 0 )
827 THROW_IO_ERROR( wxString::Format( "Unknown simulation model parameter '%s'", aParamName ) );
828
829 SetParamValue( idx, aValue, aNotation );
830}
831
832
833std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( TYPE aType )
834{
835 switch( aType )
836 {
837 case TYPE::R:
838 case TYPE::C:
839 case TYPE::L:
840 return std::make_unique<SIM_MODEL_IDEAL>( aType );
841
842 case TYPE::R_POT:
843 return std::make_unique<SIM_MODEL_R_POT>();
844
845 case TYPE::K:
846 return std::make_unique<SIM_MODEL_L_MUTUAL>();
847
848 case TYPE::R_BEHAVIORAL:
849 case TYPE::C_BEHAVIORAL:
850 case TYPE::L_BEHAVIORAL:
851 case TYPE::V_BEHAVIORAL:
852 case TYPE::I_BEHAVIORAL:
853 return std::make_unique<SIM_MODEL_BEHAVIORAL>( aType );
854
855 case TYPE::TLINE_Z0:
856 case TYPE::TLINE_RLGC:
857 return std::make_unique<SIM_MODEL_TLINE>( aType );
858
859 case TYPE::SW_V:
860 case TYPE::SW_I:
861 return std::make_unique<SIM_MODEL_SWITCH>( aType );
862
863 case TYPE::V:
864 case TYPE::I:
865 case TYPE::V_SIN:
866 case TYPE::I_SIN:
867 case TYPE::V_PULSE:
868 case TYPE::I_PULSE:
869 case TYPE::V_EXP:
870 case TYPE::I_EXP:
871 case TYPE::V_AM:
872 case TYPE::I_AM:
873 case TYPE::V_SFFM:
874 case TYPE::I_SFFM:
875 case TYPE::V_VCL:
876 case TYPE::V_CCL:
877 case TYPE::V_PWL:
878 case TYPE::I_VCL:
879 case TYPE::I_CCL:
880 case TYPE::I_PWL:
881 case TYPE::V_WHITENOISE:
882 case TYPE::I_WHITENOISE:
883 case TYPE::V_PINKNOISE:
884 case TYPE::I_PINKNOISE:
885 case TYPE::V_BURSTNOISE:
886 case TYPE::I_BURSTNOISE:
887 case TYPE::V_RANDUNIFORM:
888 case TYPE::I_RANDUNIFORM:
889 case TYPE::V_RANDGAUSSIAN:
890 case TYPE::I_RANDGAUSSIAN:
891 case TYPE::V_RANDEXP:
892 case TYPE::I_RANDEXP:
893 case TYPE::V_RANDPOISSON:
894 case TYPE::I_RANDPOISSON:
895 return std::make_unique<SIM_MODEL_SOURCE>( aType );
896
897 case TYPE::SUBCKT:
898 return std::make_unique<SIM_MODEL_SUBCKT>();
899
900 case TYPE::XSPICE:
901 return std::make_unique<SIM_MODEL_XSPICE>( aType );
902
903 case TYPE::KIBIS_DEVICE:
904 case TYPE::KIBIS_DRIVER_DC:
905 case TYPE::KIBIS_DRIVER_RECT:
906 case TYPE::KIBIS_DRIVER_PRBS:
907 return std::make_unique<SIM_MODEL_IBIS>( aType );
908
909 case TYPE::RAWSPICE:
910 return std::make_unique<SIM_MODEL_RAW_SPICE>();
911
912 default:
913 return std::make_unique<SIM_MODEL_NGSPICE>( aType );
914 }
915}
916
917
919 SIM_MODEL( aType, std::make_unique<SPICE_GENERATOR>( *this ),
920 std::make_unique<SIM_MODEL_SERIALIZER>( *this ) )
921{
922}
923
924
925SIM_MODEL::SIM_MODEL( TYPE aType, std::unique_ptr<SPICE_GENERATOR> aSpiceGenerator ) :
926 SIM_MODEL( aType, std::move( aSpiceGenerator ),
927 std::make_unique<SIM_MODEL_SERIALIZER>( *this ) )
928{
929}
930
931
932SIM_MODEL::SIM_MODEL( TYPE aType, std::unique_ptr<SPICE_GENERATOR> aSpiceGenerator,
933 std::unique_ptr<SIM_MODEL_SERIALIZER> aSerializer ) :
934 m_baseModel( nullptr ),
935 m_serializer( std::move( aSerializer ) ),
936 m_spiceGenerator( std::move( aSpiceGenerator ) ),
937 m_type( aType ),
938 m_isEnabled( true ),
939 m_isStoredInValue( false )
940{
941}
942
943
944void SIM_MODEL::createPins( const std::vector<SCH_PIN*>& aSymbolPins )
945{
946 // Default pin sequence: model pins are the same as symbol pins.
947 // Excess model pins are set as Not Connected.
948 // Note that intentionally nothing is added if `GetPinNames()` returns an empty vector.
949
950 // SIM_MODEL pins must be ordered by symbol pin numbers -- this is assumed by the code that
951 // accesses them.
952
953 std::vector<std::string> pinNames = GetPinNames();
954
955 for( unsigned modelPinIndex = 0; modelPinIndex < pinNames.size(); ++modelPinIndex )
956 {
957 wxString pinName = pinNames[ modelPinIndex ];
958 bool optional = false;
959
960 if( pinName.StartsWith( '<' ) && pinName.EndsWith( '>' ) )
961 {
962 pinName = pinName.Mid( 1, pinName.Length() - 2 );
963 optional = true;
964 }
965
966 if( modelPinIndex < aSymbolPins.size() )
967 {
968 AddPin( { pinNames.at( modelPinIndex ),
969 aSymbolPins[ modelPinIndex ]->GetNumber().ToStdString() } );
970 }
971 else if( !optional )
972 {
973 AddPin( { pinNames.at( modelPinIndex ), "" } );
974 }
975 }
976}
977
978
980{
981 // SUBCKTs are a single level; there's never a baseModel.
982 if( m_type == TYPE::SUBCKT )
983 return false;
984
985 // Model must be written if there's no base model or the base model is an internal model
986 if( !m_baseModel || aItem.baseModelName == "" )
987 return true;
988
989 for( int ii = 0; ii < GetParamCount(); ++ii )
990 {
991 const PARAM& param = m_params[ii];
992
993 // Instance parameters are written in item lines
994 if( param.info.isSpiceInstanceParam )
995 continue;
996
997 // Empty parameters are interpreted as default-value
998 if ( param.value == "" )
999 continue;
1000
1001 if( const SIM_MODEL* baseModel = dynamic_cast<const SIM_MODEL*>( m_baseModel ) )
1002 {
1003 const std::string& baseValue = baseModel->m_params[ii].value;
1004
1005 if( param.value == baseValue )
1006 continue;
1007
1008 // One more check for equivalence, mostly for early 7.0 files which wrote all
1009 // parameters to the Sim.Params field in normalized format
1010 if( param.value == SIM_VALUE::Normalize( SIM_VALUE::ToDouble( baseValue ) ) )
1011 continue;
1012
1013 // Overrides must be written
1014 return true;
1015 }
1016 }
1017
1018 return false;
1019}
1020
1021
1022template <class T>
1023bool SIM_MODEL::InferSimModel( T& aSymbol, std::vector<SCH_FIELD>* aFields, bool aResolve, int aDepth,
1024 SIM_VALUE_GRAMMAR::NOTATION aNotation, wxString* aDeviceType,
1025 wxString* aModelType, wxString* aModelParams, wxString* aPinMap )
1026{
1027 // SPICE notation is case-insensitive and locale-insensitve. This means it uses "Meg" for
1028 // mega (as both 'M' and 'm' must mean milli), and "." (always) for a decimal separator.
1029 //
1030 // KiCad's GUI uses the SI-standard 'M' for mega and 'm' for milli, and a locale-dependent
1031 // decimal separator.
1032 //
1033 // KiCad's Sim.* fields are in-between, using SI notation but a fixed decimal separator.
1034 //
1035 // So where does that leave inferred value fields? Behavioural models must be passed in
1036 // straight, because we don't (at present) know how to parse them.
1037 //
1038 // However, behavioural models _look_ like SPICE code, so it's not a stretch to expect them
1039 // to _be_ SPICE code. A passive capacitor model on the other hand, just looks like a
1040 // capacitance. Some users might expect 3,3u to work, while others might expect 3,300uF to
1041 // work.
1042 //
1043 // Checking the locale isn't reliable because it assumes the current computer's locale is
1044 // the same as the locale the schematic was authored in -- something that isn't true, for
1045 // instance, when sharing designs over DIYAudio.com.
1046 //
1047 // However, even the E192 series of preferred values uses only 3 significant digits, so a ','
1048 // or '.' followed by 3 digits _could_ reasonably-reliably be interpreted as a thousands
1049 // separator.
1050 //
1051 // Or we could just say inferred values are locale-independent, with "." used as a decimal
1052 // separator and "," used as a thousands separator. 3,300uF works, but 3,3 does not.
1053
1054 auto convertNotation =
1055 [&]( const wxString& units ) -> wxString
1056 {
1059 if( units == wxS( "µ" ) || units == wxS( "μ" ) )
1060 return wxS( "u" );
1061
1062 if( aNotation == SIM_VALUE_GRAMMAR::NOTATION::SPICE )
1063 {
1064 if( units == wxT( "M" ) )
1065 return wxT( "Meg" );
1066 }
1067 else if( aNotation == SIM_VALUE_GRAMMAR::NOTATION::SI )
1068 {
1069 if( units.Capitalize() == wxT( "Meg" ) )
1070 return wxT( "M" );
1071 }
1072
1073 return units;
1074 };
1075
1076 auto convertSeparators =
1077 []( wxString* mantissa )
1078 {
1079 mantissa->Replace( wxS( " " ), wxEmptyString );
1080
1081 wxChar ambiguousSeparator = '?';
1082 wxChar thousandsSeparator = '?';
1083 bool thousandsSeparatorFound = false;
1084 wxChar decimalSeparator = '?';
1085 bool decimalSeparatorFound = false;
1086 int digits = 0;
1087
1088 for( int ii = (int) mantissa->length() - 1; ii >= 0; --ii )
1089 {
1090 wxChar c = mantissa->GetChar( ii );
1091
1092 if( c >= '0' && c <= '9' )
1093 {
1094 digits += 1;
1095 }
1096 else if( c == '.' || c == ',' )
1097 {
1098 if( decimalSeparator != '?' || thousandsSeparator != '?' )
1099 {
1100 // We've previously found a non-ambiguous separator...
1101
1102 if( c == decimalSeparator )
1103 {
1104 if( thousandsSeparatorFound )
1105 return false; // decimal before thousands
1106 else if( decimalSeparatorFound )
1107 return false; // more than one decimal
1108 else
1109 decimalSeparatorFound = true;
1110 }
1111 else if( c == thousandsSeparator )
1112 {
1113 if( digits != 3 )
1114 return false; // thousands not followed by 3 digits
1115 else
1116 thousandsSeparatorFound = true;
1117 }
1118 }
1119 else if( ambiguousSeparator != '?' )
1120 {
1121 // We've previously found a separator, but we don't know for sure
1122 // which...
1123
1124 if( c == ambiguousSeparator )
1125 {
1126 // They both must be thousands separators
1127 thousandsSeparator = ambiguousSeparator;
1128 thousandsSeparatorFound = true;
1129 decimalSeparator = c == '.' ? ',' : '.';
1130 }
1131 else
1132 {
1133 // The first must have been a decimal, and this must be a
1134 // thousands.
1135 decimalSeparator = ambiguousSeparator;
1136 decimalSeparatorFound = true;
1137 thousandsSeparator = c;
1138 thousandsSeparatorFound = true;
1139 }
1140 }
1141 else
1142 {
1143 // This is the first separator...
1144
1145 // If it's preceeded by a '0' (only), or if it's followed by some
1146 // number of digits not equal to 3, then it -must- be a decimal
1147 // separator.
1148 //
1149 // In all other cases we don't really know what it is yet.
1150
1151 if( ( ii == 1 && mantissa->GetChar( 0 ) == '0' ) || digits != 3 )
1152 {
1153 decimalSeparator = c;
1154 decimalSeparatorFound = true;
1155 thousandsSeparator = c == '.' ? ',' : '.';
1156 }
1157 else
1158 {
1159 ambiguousSeparator = c;
1160 }
1161 }
1162
1163 digits = 0;
1164 }
1165 else
1166 {
1167 digits = 0;
1168 }
1169 }
1170
1171 // If we found nothing difinitive then we have to assume SPICE-native syntax
1172 if( decimalSeparator == '?' && thousandsSeparator == '?' )
1173 {
1174 decimalSeparator = '.';
1175 thousandsSeparator = ',';
1176 }
1177
1178 mantissa->Replace( thousandsSeparator, wxEmptyString );
1179 mantissa->Replace( decimalSeparator, '.' );
1180
1181 return true;
1182 };
1183
1184 wxString prefix = aSymbol.GetPrefix();
1185 wxString library = GetFieldValue( aFields, SIM_LIBRARY_FIELD, aResolve, aDepth );
1186 wxString modelName = GetFieldValue( aFields, SIM_NAME_FIELD, aResolve, aDepth );
1187 wxString value = GetFieldValue( aFields, SIM_VALUE_FIELD, aResolve, aDepth );
1188 std::vector<SCH_PIN*> pins;
1189
1190 if constexpr (std::is_same_v<T, SCH_SYMBOL>)
1191 pins = static_cast<SCH_SYMBOL*>( &aSymbol )->GetPins( nullptr );
1192 else if constexpr (std::is_same_v<T, LIB_SYMBOL>)
1193 pins = static_cast<LIB_SYMBOL*>( &aSymbol )->GetGraphicalPins( 0, 0 );
1194
1195
1196 // ensure the pins are sorted by number (not guaranteed in the symbol)
1197 // because the inferred spice model pin assignment here and elsewhere depends on
1198 // us maintaing the list of pins in order
1199 std::sort( pins.begin(), pins.end(),
1200 []( const SCH_PIN* a, const SCH_PIN* b )
1201 {
1202 return a->GetNumber() < b->GetNumber();
1203 } );
1204
1205 *aDeviceType = GetFieldValue( aFields, SIM_DEVICE_FIELD, aResolve, aDepth );
1206 *aModelType = GetFieldValue( aFields, SIM_DEVICE_SUBTYPE_FIELD, aResolve, aDepth );
1207 *aModelParams = GetFieldValue( aFields, SIM_PARAMS_FIELD, aResolve, aDepth );
1208 *aPinMap = GetFieldValue( aFields, SIM_PINS_FIELD, aResolve, aDepth );
1209
1210 if( pins.size() != 2 )
1211 return false;
1212
1213 if( ( ( *aDeviceType == "R" || *aDeviceType == "L" || *aDeviceType == "C" )
1214 && aModelType->IsEmpty() )
1215 ||
1216 ( library.IsEmpty() && modelName.IsEmpty()
1217 && aDeviceType->IsEmpty()
1218 && aModelType->IsEmpty()
1219 && !value.IsEmpty()
1220 && ( prefix.StartsWith( "R" ) || prefix.StartsWith( "L" ) || prefix.StartsWith( "C" ) ) ) )
1221 {
1222 if( aModelParams->IsEmpty() )
1223 {
1224 wxRegEx idealVal( wxT( "^"
1225 "([0-9\\,\\. ]+)"
1226 "([fFpPnNuUmMkKgGtTμµ𝛍𝜇𝝁 ]|M(e|E)(g|G))?"
1227 "([fFhHΩΩ𝛀𝛺𝝮rR]|ohm)?"
1228 "([-1-9 ]*)"
1229 "([fFhHΩΩ𝛀𝛺𝝮rR]|ohm)?"
1230 "$" ) );
1231
1232 if( idealVal.Matches( value ) ) // Ideal
1233 {
1234 wxString valueMantissa( idealVal.GetMatch( value, 1 ) );
1235 wxString valueExponent( idealVal.GetMatch( value, 2 ) );
1236 wxString valueFraction( idealVal.GetMatch( value, 6 ) );
1237
1238 if( !convertSeparators( &valueMantissa ) )
1239 return false;
1240
1241 if( valueMantissa.Contains( wxT( "." ) ) || valueFraction.IsEmpty() )
1242 {
1243 aModelParams->Printf( wxT( "%s=\"%s%s\"" ),
1244 prefix.Left(1).Lower(),
1245 std::move( valueMantissa ),
1246 convertNotation( valueExponent ) );
1247 }
1248 else
1249 {
1250 aModelParams->Printf( wxT( "%s=\"%s.%s%s\"" ),
1251 prefix.Left(1).Lower(),
1252 std::move( valueMantissa ),
1253 std::move( valueFraction ),
1254 convertNotation( valueExponent ) );
1255 }
1256 }
1257 else // Behavioral
1258 {
1259 *aModelType = wxT( "=" );
1260 aModelParams->Printf( wxT( "%s=\"%s\"" ), prefix.Left(1).Lower(), std::move( value ) );
1261 }
1262 }
1263
1264 if( aDeviceType->IsEmpty() )
1265 *aDeviceType = prefix.Left( 1 );
1266
1267 if( aPinMap->IsEmpty() )
1268 aPinMap->Printf( wxT( "%s=+ %s=-" ), pins[0]->GetNumber(), pins[1]->GetNumber() );
1269
1270 return true;
1271 }
1272
1273 if( ( ( *aDeviceType == wxT( "V" ) || *aDeviceType == wxT( "I" ) )
1274 && ( aModelType->IsEmpty() || *aModelType == wxT( "DC" ) ) )
1275 ||
1276 ( aDeviceType->IsEmpty()
1277 && aModelType->IsEmpty()
1278 && !value.IsEmpty()
1279 && ( prefix.StartsWith( "V" ) || prefix.StartsWith( "I" ) ) ) )
1280 {
1281 if( !value.IsEmpty() )
1282 {
1283 wxString param = "dc";
1284
1285 if( value.StartsWith( wxT( "DC " ) ) )
1286 {
1287 value = value.Right( value.Length() - 3 );
1288 }
1289 else if( value.StartsWith( wxT( "AC " ) ) )
1290 {
1291 value = value.Right( value.Length() - 3 );
1292 param = "ac";
1293 }
1294
1295 wxRegEx sourceVal( wxT( "^"
1296 "([0-9\\,\\. ]+)"
1297 "([fFpPnNuUmMkKgGtTμµ𝛍𝜇𝝁 ]|M(e|E)(g|G))?"
1298 "([vVaA])?"
1299 "([-1-9 ]*)"
1300 "([vVaA])?"
1301 "$" ) );
1302
1303 if( sourceVal.Matches( value ) )
1304 {
1305 wxString valueMantissa( sourceVal.GetMatch( value, 1 ) );
1306 wxString valueExponent( sourceVal.GetMatch( value, 2 ) );
1307 wxString valueFraction( sourceVal.GetMatch( value, 6 ) );
1308
1309 if( !convertSeparators( &valueMantissa ) )
1310 return false;
1311
1312 if( valueMantissa.Contains( wxT( "." ) ) || valueFraction.IsEmpty() )
1313 {
1314 aModelParams->Printf( wxT( "%s=\"%s%s\" %s" ),
1315 std::move( param ),
1316 std::move( valueMantissa ),
1317 convertNotation( valueExponent ),
1318 *aModelParams );
1319 }
1320 else
1321 {
1322 aModelParams->Printf( wxT( "%s=\"%s.%s%s\" %s" ),
1323 std::move( param ),
1324 std::move( valueMantissa ),
1325 std::move( valueFraction ),
1326 convertNotation( valueExponent ),
1327 *aModelParams );
1328 }
1329 }
1330 else
1331 {
1332 aModelParams->Printf( wxT( "%s=\"%s\" %s" ),
1333 std::move( param ),
1334 std::move( value ),
1335 *aModelParams );
1336 }
1337 }
1338
1339 if( aDeviceType->IsEmpty() )
1340 *aDeviceType = prefix.Left( 1 );
1341
1342 if( aModelType->IsEmpty() )
1343 *aModelType = wxT( "DC" );
1344
1345 if( aPinMap->IsEmpty() )
1346 aPinMap->Printf( wxT( "%s=+ %s=-" ), pins[0]->GetNumber(), pins[1]->GetNumber() );
1347
1348 return true;
1349 }
1350
1351 return false;
1352}
1353
1354
1355template bool SIM_MODEL::InferSimModel<SCH_SYMBOL>( SCH_SYMBOL& aSymbol, std::vector<SCH_FIELD>* aFields,
1356 bool aResolve, int aDepth,
1358 wxString* aDeviceType, wxString* aModelType,
1359 wxString* aModelParams, wxString* aPinMap );
1360template bool SIM_MODEL::InferSimModel<LIB_SYMBOL>( LIB_SYMBOL& aSymbol, std::vector<SCH_FIELD>* aFields,
1361 bool aResolve, int aDepth,
1363 wxString* aDeviceType, wxString* aModelType,
1364 wxString* aModelParams, wxString* aPinMap );
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( false ).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 {
1695 WX_STRING_REPORTER reporter;
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 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( 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\"" ), device,
1888 model, lib );
1889 }
1890
1891 deviceInfo.m_Text = SIM_MODEL::DeviceInfo( SIM_MODEL::DEVICE_T::SPICE ).fieldValue;
1892
1893 SCH_FIELD deviceField = deviceInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1894 aSymbol.AddField( deviceField );
1895
1896 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1897 aSymbol.AddField( paramsField );
1898
1899 if( modelFromValueField )
1900 {
1901 // Get the current Value field, after previous changes.
1902 valueField = aSymbol.GetField( FIELD_T::VALUE );
1903
1904 if( valueField )
1905 valueField->SetText( wxT( "${SIM.PARAMS}" ) );
1906 }
1907
1908 // We know nothing about the SPICE model here, so we've got no choice but to generate
1909 // the default pin map from the symbol's pins.
1910
1911 if( pinMapInfo.IsEmpty() )
1912 {
1913 lazySortSourcePins();
1914 pinMapInfo.m_Text = generateDefaultPinMapFromSymbol( sourcePins );
1915 }
1916 }
1917
1918 if( !pinMapInfo.IsEmpty() )
1919 {
1920 SCH_FIELD pinsField = pinMapInfo.CreateField( &aSymbol, SIM_PINS_FIELD );
1921 aSymbol.AddField( pinsField );
1922 }
1923}
1924
1925
1927 const PROJECT* aProject );
1929 const PROJECT* aProject );
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:114
BOX2< VECTOR2I > BOX2I
Definition box2.h:922
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:990
constexpr size_type GetWidth() const
Definition box2.h:214
constexpr size_type GetHeight() const
Definition box2.h:215
virtual bool IsVisible() const
Definition eda_text.h:187
void SetAttributes(const EDA_TEXT &aSrc, bool aSetPosition=true)
Set the text attributes from another instance.
Definition eda_text.cpp:445
GR_TEXT_H_ALIGN_T GetHorizJustify() const
Definition eda_text.h:200
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:398
const TEXT_ATTRIBUTES & GetAttributes() const
Definition eda_text.h:231
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:83
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:216
Container for project specific data.
Definition project.h:65
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
virtual bool HasMessage() const
Returns true if any messages were reported.
Definition reporter.h:134
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:116
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:252
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:76
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:184
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:48
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:506
virtual std::vector< std::string > GetPinNames() const
Definition sim_model.h:466
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:541
virtual bool requiresSpiceModelLine(const SPICE_ITEM &aItem) const
void ClearPins()
std::vector< SIM_MODEL_PIN > m_modelPins
Definition sim_model.h:536
static INFO TypeInfo(TYPE aType)
int GetPinCount() const
Definition sim_model.h:468
void AddPin(const SIM_MODEL_PIN &aPin)
static SPICE_INFO SpiceInfo(TYPE aType)
const SIM_MODEL_SERIALIZER & Serializer() const
Definition sim_model.h:432
bool m_isEnabled
Definition sim_model.h:544
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:545
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:478
void AssignSymbolPinNumberToModelPin(int aPinIndex, const wxString &aSymbolPinNumber)
static DEVICE_INFO DeviceInfo(DEVICE_T aDeviceType)
Definition sim_model.cpp:60
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:535
const PARAM & GetParamOverride(unsigned aParamIndex) const
friend class SPICE_GENERATOR
Definition sim_model.h:80
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:508
const SIM_MODEL_PIN & GetPin(unsigned aIndex) const
Definition sim_model.h:469
std::unique_ptr< SIM_MODEL_SERIALIZER > m_serializer
Definition sim_model.h:538
virtual int doFindParam(const std::string &aParamName) const
TYPE GetType() const
Definition sim_model.h:461
std::vector< std::reference_wrapper< const SIM_MODEL_PIN > > GetPins() const
const TYPE m_type
Definition sim_model.h:543
const SIM_MODEL * m_baseModel
Definition sim_model.h:537
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:61
A wrapper for reporting to a wxString object.
Definition reporter.h:191
#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:70
#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:428
wxString GetFieldValue(const std::vector< SCH_FIELD > *aFields, FIELD_T aFieldType)
Definition sch_field.h:403
SIM_MODEL::TYPE TYPE
Definition sim_model.cpp:57
#define SIM_PINS_FIELD
Definition sim_model.h:54
#define SIM_DEVICE_FIELD
Definition sim_model.h:52
#define SIM_NAME_FIELD
Definition sim_model.h:57
#define SIM_LIBRARY_FIELD
Definition sim_model.h:56
#define SIM_LEGACY_ENABLE_FIELD
Definition sim_model.h:64
#define SIM_LEGACY_ENABLE_FIELD_V7
Definition sim_model.h:60
#define SIM_LEGACY_MODEL_FIELD
Definition sim_model.h:62
#define SIM_LEGACY_PINS_FIELD
Definition sim_model.h:63
#define SIM_LEGACY_LIBRARY_FIELD
Definition sim_model.h:65
#define SIM_PARAMS_FIELD
Definition sim_model.h:55
#define SIM_VALUE_FIELD
Definition sim_model.h:50
#define SIM_LEGACY_PRIMITIVE_FIELD
Definition sim_model.h:61
#define SIM_DEVICE_SUBTYPE_FIELD
Definition sim_model.h:53
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:41
std::vector< std::string > enumValues
Definition sim_model.h:388
bool Matches(const std::string &aName) const
std::string defaultValue
Definition sim_model.h:382
bool Matches(const std::string &aName) const
Definition sim_model.h:395
std::string value
Definition sim_model.h:400
const INFO & info
Definition sim_model.h:401
static constexpr auto NOT_CONNECTED
Definition sim_model.h:73
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".
KIBIS_MODEL * model
KIBIS_PIN * pin
@ GR_TEXT_H_ALIGN_RIGHT
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:695