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 (C) 2022-2023 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 { "V", "", "AM" };
361 case TYPE::I_SFFM: return { "V", "", "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, REPORTER& aReporter )
391{
392 std::string deviceTypeFieldValue = GetFieldValue( &aFields, SIM_DEVICE_FIELD );
393 std::string typeFieldValue = GetFieldValue( &aFields, SIM_DEVICE_SUBTYPE_FIELD );
394
395 if( !deviceTypeFieldValue.empty() )
396 {
397 for( TYPE type : TYPE_ITERATOR() )
398 {
399 if( typeFieldValue == TypeInfo( type ).fieldValue )
400 {
401 if( deviceTypeFieldValue == DeviceInfo( TypeInfo( type ).deviceType ).fieldValue )
402 return type;
403 }
404 }
405 }
406
407 if( typeFieldValue.empty() )
408 return TYPE::NONE;
409
410 if( aFields.size() > REFERENCE_FIELD )
411 {
412 aReporter.Report( wxString::Format( _( "No simulation model definition found for "
413 "symbol '%s'." ),
414 aFields[REFERENCE_FIELD].GetText() ),
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,
428 const std::vector<SCH_PIN*>& aPins )
429{
430 bool diffMode = GetFieldValue( aFields, SIM_LIBRARY_IBIS::DIFF_FIELD ) == "1";
431 SwitchSingleEndedDiff( diffMode );
432
433 m_serializer->ParseEnable( GetFieldValue( aFields, SIM_LEGACY_ENABLE_FIELD_V7 ) );
434
435 createPins( aPins );
436 m_serializer->ParsePins( GetFieldValue( aFields, SIM_PINS_FIELD ) );
437
438 std::string paramsField = GetFieldValue( aFields, SIM_PARAMS_FIELD );
439
440 if( !m_serializer->ParseParams( paramsField ) )
441 m_serializer->ParseValue( GetFieldValue( aFields, SIM_VALUE_FIELD ) );
442}
443
444
445void SIM_MODEL::WriteFields( std::vector<SCH_FIELD>& aFields ) const
446{
447 // Remove duplicate fields: they are at the end of list
448 for( size_t ii = aFields.size() - 1; ii > 0; ii-- )
449 {
450 wxString currFieldName = aFields[ii].GetName();
451
452 auto end_candidate_list = aFields.begin() + ii - 1;
453
454 auto fieldIt = std::find_if( aFields.begin(), end_candidate_list,
455 [&]( const SCH_FIELD& f )
456 {
457 return f.GetName() == currFieldName;
458 } );
459
460 // If duplicate field found: remove current checked item
461 if( fieldIt != end_candidate_list )
462 aFields.erase( aFields.begin() + ii );
463 }
464
465 SetFieldValue( aFields, SIM_DEVICE_FIELD, m_serializer->GenerateDevice() );
466 SetFieldValue( aFields, SIM_DEVICE_SUBTYPE_FIELD, m_serializer->GenerateDeviceSubtype() );
467
468 SetFieldValue( aFields, SIM_LEGACY_ENABLE_FIELD_V7, m_serializer->GenerateEnable() );
469 SetFieldValue( aFields, SIM_PINS_FIELD, m_serializer->GeneratePins() );
470
471 SetFieldValue( aFields, SIM_PARAMS_FIELD, m_serializer->GenerateParams() );
472
473 if( IsStoredInValue() )
474 SetFieldValue( aFields, SIM_VALUE_FIELD, m_serializer->GenerateValue() );
475
476 // New fields have a ID = -1 (undefined). so replace the undefined ID
477 // by a degined ID
478 int lastFreeId = MANDATORY_FIELDS;
479
480 // Search for the first available value:
481 for( auto& fld : aFields )
482 {
483 if( fld.GetId() >= lastFreeId )
484 lastFreeId = fld.GetId() + 1;
485 }
486
487 // Set undefined IDs to a better value
488 for( auto& fld : aFields )
489 {
490 if( fld.GetId() < 0 )
491 fld.SetId( lastFreeId++ );
492 }
493}
494
495
496std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( TYPE aType, const std::vector<SCH_PIN*>& aPins,
497 REPORTER& aReporter )
498{
499 std::unique_ptr<SIM_MODEL> model = Create( aType );
500
501 try
502 {
503 // Passing nullptr to ReadDataFields will make it act as if all fields were empty.
504 model->ReadDataFields( static_cast<const std::vector<SCH_FIELD>*>( nullptr ), aPins );
505 }
506 catch( IO_ERROR& )
507 {
508 wxFAIL_MSG( "Shouldn't throw reading empty fields!" );
509 }
510
511 return model;
512}
513
514
515std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const SIM_MODEL* aBaseModel,
516 const std::vector<SCH_PIN*>& aPins,
517 REPORTER& aReporter )
518{
519 std::unique_ptr<SIM_MODEL> model;
520
521 if( aBaseModel )
522 {
523 TYPE type = aBaseModel->GetType();
524
525 if( dynamic_cast<const SIM_MODEL_SPICE_FALLBACK*>( aBaseModel ) )
526 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
527 else if( dynamic_cast< const SIM_MODEL_RAW_SPICE*>( aBaseModel ) )
528 model = std::make_unique<SIM_MODEL_RAW_SPICE>();
529 else
530 model = Create( type );
531
532 model->SetBaseModel( *aBaseModel );
533 }
534 else // No base model means the model wasn't found in the library, so create a fallback
535 {
536 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( TYPE::NONE );
537 }
538
539 try
540 {
541 model->ReadDataFields( static_cast<const std::vector<SCH_FIELD>*>( nullptr ), aPins );
542 }
543 catch( IO_ERROR& )
544 {
545 wxFAIL_MSG( "Shouldn't throw reading empty fields!" );
546 }
547
548 return model;
549}
550
551
552std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const SIM_MODEL* aBaseModel,
553 const std::vector<SCH_PIN*>& aPins,
554 const std::vector<SCH_FIELD>& aFields,
555 REPORTER& aReporter )
556{
557 std::unique_ptr<SIM_MODEL> model;
558
559 if( aBaseModel )
560 {
561 NULL_REPORTER devnull;
562 TYPE type = aBaseModel->GetType();
563 TYPE type_override = ReadTypeFromFields( aFields, devnull );
564
565 // Check for an override in the case of IBIS models.
566 // The other models require type to be set from the base model.
567 if( dynamic_cast<const SIM_MODEL_IBIS*>( aBaseModel ) &&
568 type_override != TYPE::NONE )
569 {
570 type = type_override;
571 }
572
573 if( dynamic_cast<const SIM_MODEL_SPICE_FALLBACK*>( aBaseModel ) )
574 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
575 else if( dynamic_cast< const SIM_MODEL_RAW_SPICE*>( aBaseModel ) )
576 model = std::make_unique<SIM_MODEL_RAW_SPICE>();
577 else
578 model = Create( type );
579
580 model->SetBaseModel( *aBaseModel );
581 }
582 else // No base model means the model wasn't found in the library, so create a fallback
583 {
584 TYPE type = ReadTypeFromFields( aFields, aReporter );
585 model = std::make_unique<SIM_MODEL_SPICE_FALLBACK>( type );
586 }
587
588 try
589 {
590 model->ReadDataFields( &aFields, aPins );
591 }
592 catch( IO_ERROR& err )
593 {
594 aReporter.Report( wxString::Format( _( "Error reading simulation model from "
595 "symbol '%s':\n%s" ),
596 aFields[REFERENCE_FIELD].GetText(),
597 err.Problem() ),
599 }
600
601 return model;
602}
603
604
605std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( const std::vector<SCH_FIELD>& aFields,
606 const std::vector<SCH_PIN*>& aPins,
607 bool aResolved, REPORTER& aReporter )
608{
609 TYPE type = ReadTypeFromFields( aFields, aReporter );
610 std::unique_ptr<SIM_MODEL> model = SIM_MODEL::Create( type );
611
612 try
613 {
614 model->ReadDataFields( &aFields, aPins );
615 }
616 catch( const IO_ERROR& parse_err )
617 {
618 if( !aResolved )
619 {
620 aReporter.Report( parse_err.What(), RPT_SEVERITY_ERROR );
621 return model;
622 }
623
624 // Just because we can't parse it doesn't mean that a SPICE interpreter can't. Fall
625 // back to a raw spice code model.
626
627 std::string modelData = GetFieldValue( &aFields, SIM_PARAMS_FIELD );
628
629 if( modelData.empty() )
630 modelData = GetFieldValue( &aFields, SIM_VALUE_FIELD );
631
632 model = std::make_unique<SIM_MODEL_RAW_SPICE>( modelData );
633
634 try
635 {
636 model->createPins( aPins );
637 model->m_serializer->ParsePins( GetFieldValue( &aFields, SIM_PINS_FIELD ) );
638 }
639 catch( const IO_ERROR& err )
640 {
641 // We own the pin syntax, so if we can't parse it then there's an error.
642 aReporter.Report( wxString::Format( _( "Error reading simulation model from "
643 "symbol '%s':\n%s" ),
644 aFields[REFERENCE_FIELD].GetText(),
645 err.Problem() ),
647 }
648 }
649
650 return model;
651}
652
653
654std::string SIM_MODEL::GetFieldValue( const std::vector<SCH_FIELD>* aFields,
655 const wxString& aFieldName, bool aResolve )
656{
657 if( !aFields )
658 return ""; // Should not happen, T=void specialization will be called instead.
659
660 for( const SCH_FIELD& field : *aFields )
661 {
662 if( field.GetName() == aFieldName )
663 {
664 return aResolve ? field.GetShownText( false ).ToStdString()
665 : field.GetText().ToStdString();
666 }
667 }
668
669 return "";
670}
671
672
673void SIM_MODEL::SetFieldValue( std::vector<SCH_FIELD>& aFields, const wxString& aFieldName,
674 const std::string& aValue )
675{
676 auto fieldIt = std::find_if( aFields.begin(), aFields.end(),
677 [&]( const SCH_FIELD& f )
678 {
679 return f.GetName() == aFieldName;
680 } );
681
682 if( fieldIt != aFields.end() )
683 {
684 if( aValue == "" )
685 aFields.erase( fieldIt );
686 else
687 fieldIt->SetText( aValue );
688
689 return;
690 }
691
692 if( aValue == "" )
693 return;
694
695 SCH_ITEM* parent = static_cast<SCH_ITEM*>( aFields.at( 0 ).GetParent() );
696 aFields.emplace_back( VECTOR2I(), aFields.size(), parent, aFieldName );
697
698 aFields.back().SetText( aValue );
699}
700
701
702SIM_MODEL::~SIM_MODEL() = default;
703
704
706{
707 m_modelPins.push_back( aPin );
708}
709
710
712{
713 m_modelPins.clear();
714}
715
716
717int SIM_MODEL::FindModelPinIndex( const std::string& aSymbolPinNumber )
718{
719 for( int modelPinIndex = 0; modelPinIndex < GetPinCount(); ++modelPinIndex )
720 {
721 if( GetPin( modelPinIndex ).symbolPinNumber == aSymbolPinNumber )
722 return modelPinIndex;
723 }
724
726}
727
728
730{
731 m_params.emplace_back( aInfo );
732
733 // Enums are initialized with their default values.
734 if( aInfo.enumValues.size() >= 1 )
735 m_params.back().value = aInfo.defaultValue;
736}
737
738
739void SIM_MODEL::SetBaseModel( const SIM_MODEL& aBaseModel )
740{
741 wxASSERT_MSG( GetType() == aBaseModel.GetType(),
742 wxS( "Simulation model type must be the same as its base class!" ) );
743
744 m_baseModel = &aBaseModel;
745}
746
747
748std::vector<std::reference_wrapper<const SIM_MODEL_PIN>> SIM_MODEL::GetPins() const
749{
750 std::vector<std::reference_wrapper<const SIM_MODEL_PIN>> pins;
751
752 for( int modelPinIndex = 0; modelPinIndex < GetPinCount(); ++modelPinIndex )
753 pins.emplace_back( GetPin( modelPinIndex ) );
754
755 return pins;
756}
757
759 const wxString& aSymbolPinNumber )
760{
761 if( aModelPinIndex >= 0 && aModelPinIndex < (int) m_modelPins.size() )
762 m_modelPins.at( aModelPinIndex ).symbolPinNumber = aSymbolPinNumber;
763}
764
765
766void SIM_MODEL::AssignSymbolPinNumberToModelPin( const std::string& aModelPinName,
767 const wxString& aSymbolPinNumber )
768{
770 {
771 if( pin.modelPinName == aModelPinName )
772 {
773 pin.symbolPinNumber = aSymbolPinNumber;
774 return;
775 }
776 }
777
778 // If aPinName wasn't in fact a name, see if it's a raw (1-based) index. This is required
779 // for legacy files which didn't use pin names.
780 int pinIndex = (int) strtol( aModelPinName.c_str(), nullptr, 10 );
781
782 if( pinIndex < 1 || pinIndex > (int) m_modelPins.size() )
783 THROW_IO_ERROR( wxString::Format( _( "Unknown simulation model pin '%s'" ), aModelPinName ) );
784
785 m_modelPins[ --pinIndex /* convert to 0-based */ ].symbolPinNumber = aSymbolPinNumber;
786}
787
788
789const SIM_MODEL::PARAM& SIM_MODEL::GetParam( unsigned aParamIndex ) const
790{
791 if( m_baseModel && m_params.at( aParamIndex ).value == "" )
792 return m_baseModel->GetParam( aParamIndex );
793 else
794 return m_params.at( aParamIndex );
795}
796
797
798bool SIM_MODEL::PARAM::INFO::Matches( const std::string& aParamName ) const
799{
800 return boost::iequals( name, aParamName );
801}
802
803
804int SIM_MODEL::doFindParam( const std::string& aParamName ) const
805{
806 for( int ii = 0; ii < (int) GetParamCount(); ++ii )
807 {
808 if( GetParam( ii ).Matches( aParamName ) )
809 return ii;
810 }
811
812 return -1;
813}
814
815
816const SIM_MODEL::PARAM* SIM_MODEL::FindParam( const std::string& aParamName ) const
817{
818 int idx = doFindParam( aParamName );
819
820 return idx >= 0 ? &GetParam( idx ) : nullptr;
821}
822
823
824const SIM_MODEL::PARAM& SIM_MODEL::GetParamOverride( unsigned aParamIndex ) const
825{
826 return m_params.at( aParamIndex );
827}
828
829
830const SIM_MODEL::PARAM& SIM_MODEL::GetBaseParam( unsigned aParamIndex ) const
831{
832 if( m_baseModel )
833 return m_baseModel->GetParam( aParamIndex );
834 else
835 return m_params.at( aParamIndex );
836}
837
838
839void SIM_MODEL::doSetParamValue( int aParamIndex, const std::string& aValue )
840{
841 m_params.at( aParamIndex ).value = aValue;
842}
843
844
845void SIM_MODEL::SetParamValue( int aParamIndex, const std::string& aValue,
846 SIM_VALUE::NOTATION aNotation )
847{
848 // Notation conversion is very slow. Avoid if possible.
849
850 auto plainNumber =
851 []( const std::string& aString )
852 {
853 for( char c : aString )
854 {
855 if( c != '.' && ( c < '0' || c > '9' ) )
856 return false;
857 }
858
859 return true;
860 };
861
862
863 if( aValue.find( ',' ) != std::string::npos )
864 {
865 doSetParamValue( aParamIndex, SIM_VALUE::ConvertNotation( aValue, aNotation,
866 SIM_VALUE::NOTATION::SI ) );
867 }
868 else if( aNotation != SIM_VALUE::NOTATION::SI && !plainNumber( aValue ) )
869 {
870 doSetParamValue( aParamIndex, SIM_VALUE::ConvertNotation( aValue, aNotation,
871 SIM_VALUE::NOTATION::SI ) );
872 }
873 else
874 {
875 doSetParamValue( aParamIndex, aValue );
876 }
877}
878
879
880void SIM_MODEL::SetParamValue( const std::string& aParamName, const std::string& aValue,
881 SIM_VALUE::NOTATION aNotation )
882{
883 int idx = doFindParam( aParamName );
884
885 if( idx < 0 )
886 THROW_IO_ERROR( wxString::Format( "Unknown simulation model parameter '%s'", aParamName ) );
887
888 SetParamValue( idx, aValue, aNotation );
889}
890
891
892std::unique_ptr<SIM_MODEL> SIM_MODEL::Create( TYPE aType )
893{
894 switch( aType )
895 {
896 case TYPE::R:
897 case TYPE::C:
898 case TYPE::L:
899 return std::make_unique<SIM_MODEL_IDEAL>( aType );
900
901 case TYPE::R_POT:
902 return std::make_unique<SIM_MODEL_R_POT>();
903
904 case TYPE::K:
905 return std::make_unique<SIM_MODEL_L_MUTUAL>();
906
907 case TYPE::R_BEHAVIORAL:
908 case TYPE::C_BEHAVIORAL:
909 case TYPE::L_BEHAVIORAL:
910 case TYPE::V_BEHAVIORAL:
911 case TYPE::I_BEHAVIORAL:
912 return std::make_unique<SIM_MODEL_BEHAVIORAL>( aType );
913
914 case TYPE::TLINE_Z0:
915 case TYPE::TLINE_RLGC:
916 return std::make_unique<SIM_MODEL_TLINE>( aType );
917
918 case TYPE::SW_V:
919 case TYPE::SW_I:
920 return std::make_unique<SIM_MODEL_SWITCH>( aType );
921
922 case TYPE::V:
923 case TYPE::I:
924 case TYPE::V_SIN:
925 case TYPE::I_SIN:
926 case TYPE::V_PULSE:
927 case TYPE::I_PULSE:
928 case TYPE::V_EXP:
929 case TYPE::I_EXP:
930 case TYPE::V_AM:
931 case TYPE::I_AM:
932 case TYPE::V_SFFM:
933 case TYPE::I_SFFM:
934 case TYPE::V_VCL:
935 case TYPE::V_CCL:
936 case TYPE::V_PWL:
937 case TYPE::I_VCL:
938 case TYPE::I_CCL:
939 case TYPE::I_PWL:
940 case TYPE::V_WHITENOISE:
941 case TYPE::I_WHITENOISE:
942 case TYPE::V_PINKNOISE:
943 case TYPE::I_PINKNOISE:
944 case TYPE::V_BURSTNOISE:
945 case TYPE::I_BURSTNOISE:
946 case TYPE::V_RANDUNIFORM:
947 case TYPE::I_RANDUNIFORM:
948 case TYPE::V_RANDGAUSSIAN:
949 case TYPE::I_RANDGAUSSIAN:
950 case TYPE::V_RANDEXP:
951 case TYPE::I_RANDEXP:
952 case TYPE::V_RANDPOISSON:
953 case TYPE::I_RANDPOISSON:
954 return std::make_unique<SIM_MODEL_SOURCE>( aType );
955
956 case TYPE::SUBCKT:
957 return std::make_unique<SIM_MODEL_SUBCKT>();
958
959 case TYPE::XSPICE:
960 return std::make_unique<SIM_MODEL_XSPICE>( aType );
961
962 case TYPE::KIBIS_DEVICE:
963 case TYPE::KIBIS_DRIVER_DC:
964 case TYPE::KIBIS_DRIVER_RECT:
965 case TYPE::KIBIS_DRIVER_PRBS:
966 return std::make_unique<SIM_MODEL_IBIS>( aType );
967
968 case TYPE::RAWSPICE:
969 return std::make_unique<SIM_MODEL_RAW_SPICE>();
970
971 default:
972 return std::make_unique<SIM_MODEL_NGSPICE>( aType );
973 }
974}
975
976
978 SIM_MODEL( aType, std::make_unique<SPICE_GENERATOR>( *this ),
979 std::make_unique<SIM_MODEL_SERIALIZER>( *this ) )
980{
981}
982
983
984SIM_MODEL::SIM_MODEL( TYPE aType, std::unique_ptr<SPICE_GENERATOR> aSpiceGenerator ) :
985 SIM_MODEL( aType, std::move( aSpiceGenerator ),
986 std::make_unique<SIM_MODEL_SERIALIZER>( *this ) )
987{
988}
989
990
991SIM_MODEL::SIM_MODEL( TYPE aType, std::unique_ptr<SPICE_GENERATOR> aSpiceGenerator,
992 std::unique_ptr<SIM_MODEL_SERIALIZER> aSerializer ) :
993 m_baseModel( nullptr ),
994 m_serializer( std::move( aSerializer ) ),
995 m_spiceGenerator( std::move( aSpiceGenerator ) ),
996 m_type( aType ),
997 m_isEnabled( true ),
998 m_isStoredInValue( false )
999{
1000}
1001
1002
1003void SIM_MODEL::createPins( const std::vector<SCH_PIN*>& aSymbolPins )
1004{
1005 // Default pin sequence: model pins are the same as symbol pins.
1006 // Excess model pins are set as Not Connected.
1007 // Note that intentionally nothing is added if `GetPinNames()` returns an empty vector.
1008
1009 // SIM_MODEL pins must be ordered by symbol pin numbers -- this is assumed by the code that
1010 // accesses them.
1011
1012 std::vector<std::string> pinNames = GetPinNames();
1013
1014 for( unsigned modelPinIndex = 0; modelPinIndex < pinNames.size(); ++modelPinIndex )
1015 {
1016 wxString pinName = pinNames[ modelPinIndex ];
1017 bool optional = false;
1018
1019 if( pinName.StartsWith( '<' ) && pinName.EndsWith( '>' ) )
1020 {
1021 pinName = pinName.Mid( 1, pinName.Length() - 2 );
1022 optional = true;
1023 }
1024
1025 if( modelPinIndex < aSymbolPins.size() )
1026 {
1027 AddPin( { pinNames.at( modelPinIndex ),
1028 aSymbolPins[ modelPinIndex ]->GetNumber().ToStdString() } );
1029 }
1030 else if( !optional )
1031 {
1032 AddPin( { pinNames.at( modelPinIndex ), "" } );
1033 }
1034 }
1035}
1036
1037
1039{
1040 // SUBCKTs are a single level; there's never a baseModel.
1041 if( m_type == TYPE::SUBCKT )
1042 return false;
1043
1044 // Model must be written if there's no base model or the base model is an internal model
1045 if( !m_baseModel || aItem.baseModelName == "" )
1046 return true;
1047
1048 for( int ii = 0; ii < GetParamCount(); ++ii )
1049 {
1050 const PARAM& param = m_params[ii];
1051
1052 // Instance parameters are written in item lines
1053 if( param.info.isSpiceInstanceParam )
1054 continue;
1055
1056 // Empty parameters are interpreted as default-value
1057 if ( param.value == "" )
1058 continue;
1059
1060 if( const SIM_MODEL* baseModel = dynamic_cast<const SIM_MODEL*>( m_baseModel ) )
1061 {
1062 const std::string& baseValue = baseModel->m_params[ii].value;
1063
1064 if( param.value == baseValue )
1065 continue;
1066
1067 // One more check for equivalence, mostly for early 7.0 files which wrote all
1068 // parameters to the Sim.Params field in normalized format
1069 if( param.value == SIM_VALUE::Normalize( SIM_VALUE::ToDouble( baseValue ) ) )
1070 continue;
1071
1072 // Overrides must be written
1073 return true;
1074 }
1075 }
1076
1077 return false;
1078}
1079
1080
1081template <class T>
1082bool SIM_MODEL::InferSimModel( T& aSymbol, std::vector<SCH_FIELD>* aFields, bool aResolve,
1083 SIM_VALUE_GRAMMAR::NOTATION aNotation, wxString* aDeviceType,
1084 wxString* aModelType, wxString* aModelParams, wxString* aPinMap )
1085{
1086 // SPICE notation is case-insensitive and locale-insensitve. This means it uses "Meg" for
1087 // mega (as both 'M' and 'm' must mean milli), and "." (always) for a decimal separator.
1088 //
1089 // KiCad's GUI uses the SI-standard 'M' for mega and 'm' for milli, and a locale-dependent
1090 // decimal separator.
1091 //
1092 // KiCad's Sim.* fields are in-between, using SI notation but a fixed decimal separator.
1093 //
1094 // So where does that leave inferred value fields? Behavioural models must be passed in
1095 // straight, because we don't (at present) know how to parse them.
1096 //
1097 // However, behavioural models _look_ like SPICE code, so it's not a stretch to expect them
1098 // to _be_ SPICE code. A passive capacitor model on the other hand, just looks like a
1099 // capacitance. Some users might expect 3,3u to work, while others might expect 3,300uF to
1100 // work.
1101 //
1102 // Checking the locale isn't reliable because it assumes the current computer's locale is
1103 // the same as the locale the schematic was authored in -- something that isn't true, for
1104 // instance, when sharing designs over DIYAudio.com.
1105 //
1106 // However, even the E192 series of preferred values uses only 3 significant digits, so a ','
1107 // or '.' followed by 3 digits _could_ reasonably-reliably be interpreted as a thousands
1108 // separator.
1109 //
1110 // Or we could just say inferred values are locale-independent, with "." used as a decimal
1111 // separator and "," used as a thousands separator. 3,300uF works, but 3,3 does not.
1112
1113 auto convertNotation =
1114 [&]( const wxString& units ) -> wxString
1115 {
1118 if( units == wxS( "µ" ) || units == wxS( "μ" ) )
1119 return wxS( "u" );
1120
1121 if( aNotation == SIM_VALUE_GRAMMAR::NOTATION::SPICE )
1122 {
1123 if( units == wxT( "M" ) )
1124 return wxT( "Meg" );
1125 }
1126 else if( aNotation == SIM_VALUE_GRAMMAR::NOTATION::SI )
1127 {
1128 if( units.Capitalize() == wxT( "Meg" ) )
1129 return wxT( "M" );
1130 }
1131
1132 return units;
1133 };
1134
1135 auto convertSeparators =
1136 []( wxString* mantissa )
1137 {
1138 mantissa->Replace( wxS( " " ), wxEmptyString );
1139
1140 wxChar ambiguousSeparator = '?';
1141 wxChar thousandsSeparator = '?';
1142 bool thousandsSeparatorFound = false;
1143 wxChar decimalSeparator = '?';
1144 bool decimalSeparatorFound = false;
1145 int digits = 0;
1146
1147 for( int ii = (int) mantissa->length() - 1; ii >= 0; --ii )
1148 {
1149 wxChar c = mantissa->GetChar( ii );
1150
1151 if( c >= '0' && c <= '9' )
1152 {
1153 digits += 1;
1154 }
1155 else if( c == '.' || c == ',' )
1156 {
1157 if( decimalSeparator != '?' || thousandsSeparator != '?' )
1158 {
1159 // We've previously found a non-ambiguous separator...
1160
1161 if( c == decimalSeparator )
1162 {
1163 if( thousandsSeparatorFound )
1164 return false; // decimal before thousands
1165 else if( decimalSeparatorFound )
1166 return false; // more than one decimal
1167 else
1168 decimalSeparatorFound = true;
1169 }
1170 else if( c == thousandsSeparator )
1171 {
1172 if( digits != 3 )
1173 return false; // thousands not followed by 3 digits
1174 else
1175 thousandsSeparatorFound = true;
1176 }
1177 }
1178 else if( ambiguousSeparator != '?' )
1179 {
1180 // We've previously found a separator, but we don't know for sure
1181 // which...
1182
1183 if( c == ambiguousSeparator )
1184 {
1185 // They both must be thousands separators
1186 thousandsSeparator = ambiguousSeparator;
1187 thousandsSeparatorFound = true;
1188 decimalSeparator = c == '.' ? ',' : '.';
1189 }
1190 else
1191 {
1192 // The first must have been a decimal, and this must be a
1193 // thousands.
1194 decimalSeparator = ambiguousSeparator;
1195 decimalSeparatorFound = true;
1196 thousandsSeparator = c;
1197 thousandsSeparatorFound = true;
1198 }
1199 }
1200 else
1201 {
1202 // This is the first separator...
1203
1204 // If it's preceeded by a '0' (only), or if it's followed by some
1205 // number of digits not equal to 3, then it -must- be a decimal
1206 // separator.
1207 //
1208 // In all other cases we don't really know what it is yet.
1209
1210 if( ( ii == 1 && mantissa->GetChar( 0 ) == '0' ) || digits != 3 )
1211 {
1212 decimalSeparator = c;
1213 decimalSeparatorFound = true;
1214 thousandsSeparator = c == '.' ? ',' : '.';
1215 }
1216 else
1217 {
1218 ambiguousSeparator = c;
1219 }
1220 }
1221
1222 digits = 0;
1223 }
1224 else
1225 {
1226 digits = 0;
1227 }
1228 }
1229
1230 // If we found nothing difinitive then we have to assume SPICE-native syntax
1231 if( decimalSeparator == '?' && thousandsSeparator == '?' )
1232 {
1233 decimalSeparator = '.';
1234 thousandsSeparator = ',';
1235 }
1236
1237 mantissa->Replace( thousandsSeparator, wxEmptyString );
1238 mantissa->Replace( decimalSeparator, '.' );
1239
1240 return true;
1241 };
1242
1243 wxString prefix = aSymbol.GetPrefix();
1244 wxString library = GetFieldValue( aFields, SIM_LIBRARY_FIELD, aResolve );
1245 wxString modelName = GetFieldValue( aFields, SIM_NAME_FIELD, aResolve );
1246 wxString value = GetFieldValue( aFields, SIM_VALUE_FIELD, aResolve );
1247 std::vector<SCH_PIN*> pins = aSymbol.GetAllLibPins();
1248
1249 *aDeviceType = GetFieldValue( aFields, SIM_DEVICE_FIELD, aResolve );
1250 *aModelType = GetFieldValue( aFields, SIM_DEVICE_SUBTYPE_FIELD, aResolve );
1251 *aModelParams = GetFieldValue( aFields, SIM_PARAMS_FIELD, aResolve );
1252 *aPinMap = GetFieldValue( aFields, SIM_PINS_FIELD, aResolve );
1253
1254 if( pins.size() != 2 )
1255 return false;
1256
1257 if( ( ( *aDeviceType == "R" || *aDeviceType == "L" || *aDeviceType == "C" )
1258 && aModelType->IsEmpty() )
1259 ||
1260 ( library.IsEmpty() && modelName.IsEmpty()
1261 && aDeviceType->IsEmpty()
1262 && aModelType->IsEmpty()
1263 && !value.IsEmpty()
1264 && ( prefix.StartsWith( "R" ) || prefix.StartsWith( "L" ) || prefix.StartsWith( "C" ) ) ) )
1265 {
1266 if( aModelParams->IsEmpty() )
1267 {
1268 wxRegEx idealVal( wxT( "^"
1269 "([0-9\\,\\. ]+)"
1270 "([fFpPnNuUmMkKgGtTμµ𝛍𝜇𝝁 ]|M(e|E)(g|G))?"
1271 "([fFhHΩΩ𝛀𝛺𝝮rR]|ohm)?"
1272 "([-1-9 ]*)"
1273 "([fFhHΩΩ𝛀𝛺𝝮rR]|ohm)?"
1274 "$" ) );
1275
1276 if( idealVal.Matches( value ) ) // Ideal
1277 {
1278 wxString valueMantissa( idealVal.GetMatch( value, 1 ) );
1279 wxString valueExponent( idealVal.GetMatch( value, 2 ) );
1280 wxString valueFraction( idealVal.GetMatch( value, 6 ) );
1281
1282 if( !convertSeparators( &valueMantissa ) )
1283 return false;
1284
1285 if( valueMantissa.Contains( wxT( "." ) ) || valueFraction.IsEmpty() )
1286 {
1287 aModelParams->Printf( wxT( "%s=\"%s%s\"" ),
1288 prefix.Left(1).Lower(),
1289 valueMantissa,
1290 convertNotation( valueExponent ) );
1291 }
1292 else
1293 {
1294 aModelParams->Printf( wxT( "%s=\"%s.%s%s\"" ),
1295 prefix.Left(1).Lower(),
1296 valueMantissa,
1297 valueFraction,
1298 convertNotation( valueExponent ) );
1299 }
1300 }
1301 else // Behavioral
1302 {
1303 *aModelType = wxT( "=" );
1304 aModelParams->Printf( wxT( "%s=\"%s\"" ), prefix.Left(1).Lower(), value );
1305 }
1306 }
1307
1308 if( aDeviceType->IsEmpty() )
1309 *aDeviceType = prefix.Left( 1 );
1310
1311 if( aPinMap->IsEmpty() )
1312 aPinMap->Printf( wxT( "%s=+ %s=-" ), pins[0]->GetNumber(), pins[1]->GetNumber() );
1313
1314 return true;
1315 }
1316
1317 if( ( ( *aDeviceType == wxT( "V" ) || *aDeviceType == wxT( "I" ) )
1318 && ( aModelType->IsEmpty() || *aModelType == wxT( "DC" ) ) )
1319 ||
1320 ( aDeviceType->IsEmpty()
1321 && aModelType->IsEmpty()
1322 && !value.IsEmpty()
1323 && ( prefix.StartsWith( "V" ) || prefix.StartsWith( "I" ) ) ) )
1324 {
1325 if( !value.IsEmpty() )
1326 {
1327 wxString param = "dc";
1328
1329 if( value.StartsWith( wxT( "DC " ) ) )
1330 {
1331 value = value.Right( value.Length() - 3 );
1332 }
1333 else if( value.StartsWith( wxT( "AC " ) ) )
1334 {
1335 value = value.Right( value.Length() - 3 );
1336 param = "ac";
1337 }
1338
1339 wxRegEx sourceVal( wxT( "^"
1340 "([0-9\\,\\. ]+)"
1341 "([fFpPnNuUmMkKgGtTμµ𝛍𝜇𝝁 ]|M(e|E)(g|G))?"
1342 "([vVaA])?"
1343 "([-1-9 ]*)"
1344 "([vVaA])?"
1345 "$" ) );
1346
1347 if( sourceVal.Matches( value ) )
1348 {
1349 wxString valueMantissa( sourceVal.GetMatch( value, 1 ) );
1350 wxString valueExponent( sourceVal.GetMatch( value, 2 ) );
1351 wxString valueFraction( sourceVal.GetMatch( value, 6 ) );
1352
1353 if( !convertSeparators( &valueMantissa ) )
1354 return false;
1355
1356 if( valueMantissa.Contains( wxT( "." ) ) || valueFraction.IsEmpty() )
1357 {
1358 aModelParams->Printf( wxT( "%s=\"%s%s\" %s" ),
1359 param,
1360 valueMantissa,
1361 convertNotation( valueExponent ),
1362 *aModelParams );
1363 }
1364 else
1365 {
1366 aModelParams->Printf( wxT( "%s=\"%s.%s%s\" %s" ),
1367 param,
1368 valueMantissa,
1369 valueFraction,
1370 convertNotation( valueExponent ),
1371 *aModelParams );
1372 }
1373 }
1374 else
1375 {
1376 aModelParams->Printf( wxT( "%s=\"%s\" %s" ),
1377 param,
1378 value,
1379 *aModelParams );
1380 }
1381 }
1382
1383 if( aDeviceType->IsEmpty() )
1384 *aDeviceType = prefix.Left( 1 );
1385
1386 if( aModelType->IsEmpty() )
1387 *aModelType = wxT( "DC" );
1388
1389 if( aPinMap->IsEmpty() )
1390 aPinMap->Printf( wxT( "%s=+ %s=-" ), pins[0]->GetNumber(), pins[1]->GetNumber() );
1391
1392 return true;
1393 }
1394
1395 return false;
1396}
1397
1398
1399template bool SIM_MODEL::InferSimModel<SCH_SYMBOL>( SCH_SYMBOL& aSymbol,
1400 std::vector<SCH_FIELD>* aFields, bool aResolve,
1402 wxString* aDeviceType, wxString* aModelType,
1403 wxString* aModelParams, wxString* aPinMap );
1404template bool SIM_MODEL::InferSimModel<LIB_SYMBOL>( LIB_SYMBOL& aSymbol,
1405 std::vector<SCH_FIELD>* aFields, bool aResolve,
1407 wxString* aDeviceType, wxString* aModelType,
1408 wxString* aModelParams, wxString* aPinMap );
1409
1410
1411template <typename T>
1412void SIM_MODEL::MigrateSimModel( T& aSymbol, const PROJECT* aProject )
1413{
1414 class FIELD_INFO
1415 {
1416 public:
1417 FIELD_INFO()
1418 {
1419 m_Attributes.m_Visible = false;
1420 m_Attributes.m_Size = VECTOR2I( DEFAULT_SIZE_TEXT * schIUScale.IU_PER_MILS,
1422 };
1423
1424 FIELD_INFO( const wxString& aText, SCH_FIELD* aField ) :
1425 m_Text( aText ),
1426 m_Attributes( aField->GetAttributes() ),
1427 m_Pos( aField->GetPosition() )
1428 {}
1429
1430 bool IsEmpty() const { return m_Text.IsEmpty(); }
1431
1432 SCH_FIELD CreateField( T* aSymbol, const wxString& aFieldName )
1433 {
1434 SCH_FIELD field( aSymbol, -1, aFieldName );
1435
1436 field.SetText( m_Text );
1437 field.SetAttributes( m_Attributes );
1438 field.SetPosition( m_Pos );
1439
1440 return field;
1441 }
1442
1443 public:
1444 wxString m_Text;
1445 TEXT_ATTRIBUTES m_Attributes;
1446 VECTOR2I m_Pos;
1447 };
1448
1449 SCH_FIELD* existing_deviceField = aSymbol.FindField( SIM_DEVICE_FIELD );
1450 SCH_FIELD* existing_deviceSubtypeField = aSymbol.FindField( SIM_DEVICE_SUBTYPE_FIELD );
1451 SCH_FIELD* existing_pinsField = aSymbol.FindField( SIM_PINS_FIELD );
1452 SCH_FIELD* existing_paramsField = aSymbol.FindField( SIM_PARAMS_FIELD );
1453
1454 wxString existing_deviceSubtype;
1455
1456 if( existing_deviceSubtypeField )
1457 existing_deviceSubtype = existing_deviceSubtypeField->GetShownText( false ).Upper();
1458
1459 if( existing_deviceField
1460 || existing_deviceSubtypeField
1461 || existing_pinsField
1462 || existing_paramsField )
1463 {
1464 // Has a current (V7+) model field.
1465
1466 // Up until 7.0RC2 we used '+' and '-' for potentiometer pins, which doesn't match
1467 // SPICE. Here we remap them to 'r0' and 'r1'.
1468 if( existing_deviceSubtype == wxS( "POT" ) )
1469 {
1470 if( existing_pinsField )
1471 {
1472 wxString pinMap = existing_pinsField->GetText();
1473 pinMap.Replace( wxS( "=+" ), wxS( "=r1" ) );
1474 pinMap.Replace( wxS( "=-" ), wxS( "=r0" ) );
1475 existing_pinsField->SetText( pinMap );
1476 }
1477 }
1478
1479 // Up until 8.0RC1 random voltage/current sources were a bit of a mess.
1480 if( existing_deviceSubtype.StartsWith( wxS( "RAND" ) ) )
1481 {
1482 // Re-fetch value without resolving references. If it's an indirect value then we
1483 // can't migrate it.
1484 existing_deviceSubtype = existing_deviceSubtypeField->GetText().Upper();
1485
1486 if( existing_deviceSubtype.Replace( wxS( "NORMAL" ), wxS( "GAUSSIAN" ) ) )
1487 existing_deviceSubtypeField->SetText( existing_deviceSubtype );
1488
1489 if( existing_paramsField )
1490 {
1491 wxString params = existing_paramsField->GetText().Lower();
1492 size_t count = 0;
1493
1494 // We used to support 'min' and 'max' instead of 'range' and 'offset', but we
1495 // wrote all 4 to the netlist which would cause ngspice to barf, so no one has
1496 // working documents with min and max specified. Just delete them if they're
1497 // uninitialized.
1498 count += params.Replace( wxS( "min=0 " ), wxEmptyString );
1499 count += params.Replace( wxS( "max=0 " ), wxEmptyString );
1500
1501 // We used to use 'dt', but the correct ngspice name is 'ts'.
1502 count += params.Replace( wxS( "dt=" ), wxS( "ts=" ) );
1503
1504 if( count )
1505 existing_paramsField->SetText( params );
1506 }
1507 }
1508
1509 // Up until 8.0.1 we treated a mutual inductance statement as a type of inductor --
1510 // which is confusing because it doesn't represent a device at all.
1511 if( existing_deviceSubtype == wxS( "MUTUAL" ) )
1512 {
1513 if( existing_deviceSubtypeField ) // Can't be null, but Coverity doesn't know that
1514 aSymbol.RemoveField( existing_deviceSubtypeField );
1515
1516 if( existing_deviceField )
1517 {
1518 existing_deviceField->SetText( wxS( "K" ) );
1519 }
1520 else
1521 {
1522 FIELD_INFO deviceFieldInfo;
1523 deviceFieldInfo.m_Text = wxS( "K" );
1524
1525 SCH_FIELD deviceField = deviceFieldInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1526 aSymbol.AddField( deviceField );
1527 }
1528 }
1529
1530 return;
1531 }
1532
1533 auto getSIValue =
1534 []( SCH_FIELD* aField )
1535 {
1536 if( !aField ) // no, not really, but it keeps Coverity happy
1537 return wxString( wxEmptyString );
1538
1539 wxRegEx regex( wxT( "([^a-z])(M)(e|E)(g|G)($|[^a-z])" ) );
1540 wxString value = aField->GetText();
1541
1542 // Keep prefix, M, and suffix, but drop e|E and g|G
1543 regex.ReplaceAll( &value, wxT( "\\1\\2\\5" ) );
1544
1545 return value;
1546 };
1547
1548 auto generateDefaultPinMapFromSymbol =
1549 []( const std::vector<SCH_PIN*>& sourcePins )
1550 {
1551 wxString pinMap;
1552
1553 // If we're creating the pinMap from the symbol it means we don't know what the
1554 // SIM_MODEL's pin names are, so just use indexes.
1555
1556 for( unsigned ii = 0; ii < sourcePins.size(); ++ii )
1557 {
1558 if( ii > 0 )
1559 pinMap.Append( wxS( " " ) );
1560
1561 pinMap.Append( wxString::Format( wxT( "%s=%u" ),
1562 sourcePins[ii]->GetNumber(),
1563 ii + 1 ) );
1564 }
1565
1566 return pinMap;
1567 };
1568
1569 wxString prefix = aSymbol.GetPrefix();
1570 SCH_FIELD* valueField = aSymbol.FindField( wxT( "Value" ) );
1571 std::vector<SCH_PIN*> sourcePins = aSymbol.GetAllLibPins();
1572 bool sourcePinsSorted = false;
1573
1574 auto lazySortSourcePins =
1575 [&sourcePins, &sourcePinsSorted]()
1576 {
1577 if( !sourcePinsSorted )
1578 {
1579 std::sort( sourcePins.begin(), sourcePins.end(),
1580 []( const SCH_PIN* lhs, const SCH_PIN* rhs )
1581 {
1582 return StrNumCmp( lhs->GetNumber(), rhs->GetNumber(), true ) < 0;
1583 } );
1584 }
1585
1586 sourcePinsSorted = true;
1587 };
1588
1589 FIELD_INFO deviceInfo;
1590 FIELD_INFO modelInfo;
1591 FIELD_INFO deviceSubtypeInfo;
1592 FIELD_INFO libInfo;
1593 FIELD_INFO spiceParamsInfo;
1594 FIELD_INFO pinMapInfo;
1595 bool modelFromValueField = false;
1596
1597 if( aSymbol.FindField( SIM_LEGACY_PRIMITIVE_FIELD )
1598 || aSymbol.FindField( SIM_LEGACY_PINS_FIELD )
1599 || aSymbol.FindField( SIM_LEGACY_MODEL_FIELD )
1600 || aSymbol.FindField( SIM_LEGACY_ENABLE_FIELD )
1601 || aSymbol.FindField( SIM_LEGACY_LIBRARY_FIELD ) )
1602 {
1603 if( SCH_FIELD* primitiveField = aSymbol.FindField( SIM_LEGACY_PRIMITIVE_FIELD ) )
1604 {
1605 deviceInfo = FIELD_INFO( primitiveField->GetText(), primitiveField );
1606 aSymbol.RemoveField( primitiveField );
1607 }
1608
1609 if( SCH_FIELD* nodeSequenceField = aSymbol.FindField( SIM_LEGACY_PINS_FIELD ) )
1610 {
1611 const wxString delimiters( "{:,; }" );
1612 const wxString& nodeSequence = nodeSequenceField->GetText();
1613 wxString pinMap;
1614
1615 if( nodeSequence != "" )
1616 {
1617 wxStringTokenizer tkz( nodeSequence, delimiters );
1618
1619 for( long modelPinNumber = 1; tkz.HasMoreTokens(); ++modelPinNumber )
1620 {
1621 long symbolPinNumber = 1;
1622 tkz.GetNextToken().ToLong( &symbolPinNumber );
1623
1624 if( modelPinNumber != 1 )
1625 pinMap.Append( " " );
1626
1627 pinMap.Append( wxString::Format( "%ld=%ld", symbolPinNumber, modelPinNumber ) );
1628 }
1629 }
1630
1631 pinMapInfo = FIELD_INFO( pinMap, nodeSequenceField );
1632 aSymbol.RemoveField( nodeSequenceField );
1633 }
1634
1635 if( SCH_FIELD* modelField = aSymbol.FindField( SIM_LEGACY_MODEL_FIELD ) )
1636 {
1637 modelInfo = FIELD_INFO( getSIValue( modelField ), modelField );
1638 aSymbol.RemoveField( modelField );
1639 }
1640 else if( valueField )
1641 {
1642 modelInfo = FIELD_INFO( getSIValue( valueField ), valueField );
1643 modelFromValueField = true;
1644 }
1645
1646 if( SCH_FIELD* libFileField = aSymbol.FindField( SIM_LEGACY_LIBRARY_FIELD ) )
1647 {
1648 libInfo = FIELD_INFO( libFileField->GetText(), libFileField );
1649 aSymbol.RemoveField( libFileField );
1650 }
1651 }
1652 else
1653 {
1654 // Auto convert some legacy fields used in the middle of 7.0 development...
1655
1656 if( SCH_FIELD* legacyType = aSymbol.FindField( wxT( "Sim_Type" ) ) )
1657 {
1658 legacyType->SetName( SIM_DEVICE_SUBTYPE_FIELD );
1659 }
1660
1661 if( SCH_FIELD* legacyDevice = aSymbol.FindField( wxT( "Sim_Device" ) ) )
1662 {
1663 legacyDevice->SetName( SIM_DEVICE_FIELD );
1664 }
1665
1666 if( SCH_FIELD* legacyPins = aSymbol.FindField( wxT( "Sim_Pins" ) ) )
1667 {
1668 bool isPassive = prefix.StartsWith( wxT( "R" ) )
1669 || prefix.StartsWith( wxT( "L" ) )
1670 || prefix.StartsWith( wxT( "C" ) );
1671
1672 // Migrate pins from array of indexes to name-value-pairs
1673 wxString pinMap;
1674 wxArrayString pinIndexes;
1675
1676 wxStringSplit( legacyPins->GetText(), pinIndexes, ' ' );
1677
1678 lazySortSourcePins();
1679
1680 if( isPassive && pinIndexes.size() == 2 && sourcePins.size() == 2 )
1681 {
1682 if( pinIndexes[0] == wxT( "2" ) )
1683 {
1684 pinMap.Printf( wxT( "%s=- %s=+" ),
1685 sourcePins[0]->GetNumber(),
1686 sourcePins[1]->GetNumber() );
1687 }
1688 else
1689 {
1690 pinMap.Printf( wxT( "%s=+ %s=-" ),
1691 sourcePins[0]->GetNumber(),
1692 sourcePins[1]->GetNumber() );
1693 }
1694 }
1695 else
1696 {
1697 for( unsigned ii = 0; ii < pinIndexes.size() && ii < sourcePins.size(); ++ii )
1698 {
1699 if( ii > 0 )
1700 pinMap.Append( wxS( " " ) );
1701
1702 pinMap.Append( wxString::Format( wxT( "%s=%s" ),
1703 sourcePins[ii]->GetNumber(),
1704 pinIndexes[ ii ] ) );
1705 }
1706 }
1707
1708 legacyPins->SetName( SIM_PINS_FIELD );
1709 legacyPins->SetText( pinMap );
1710 }
1711
1712 if( SCH_FIELD* legacyParams = aSymbol.FindField( wxT( "Sim_Params" ) ) )
1713 {
1714 legacyParams->SetName( SIM_PARAMS_FIELD );
1715 }
1716
1717 return;
1718 }
1719
1720 wxString device = deviceInfo.m_Text.Trim( true ).Trim( false );
1721 wxString lib = libInfo.m_Text.Trim( true ).Trim( false );
1722 wxString model = modelInfo.m_Text.Trim( true ).Trim( false );
1723 wxString modelLineParams;
1724
1725 bool libraryModel = false;
1726 bool inferredModel = false;
1727 bool internalModel = false;
1728
1729 if( !lib.IsEmpty() )
1730 {
1731 WX_STRING_REPORTER reporter;
1732 SIM_LIB_MGR libMgr( aProject );
1733 std::vector<SCH_FIELD> emptyFields;
1734
1735 // Pull out any following parameters from model name
1736 model = model.BeforeFirst( ' ', &modelLineParams );
1737 modelInfo.m_Text = model;
1738
1739 lazySortSourcePins();
1740
1741 SIM_LIBRARY::MODEL simModel = libMgr.CreateModel( lib, model.ToStdString(),
1742 emptyFields, sourcePins, reporter );
1743
1744 if( reporter.HasMessage() )
1745 libraryModel = false; // Fall back to raw spice model
1746 else
1747 libraryModel = true;
1748
1749 if( pinMapInfo.IsEmpty() )
1750 {
1751 // Try to generate a default pin map from the SIM_MODEL's pins; if that fails,
1752 // generate one from the symbol's pins
1753 pinMapInfo.m_Text = wxString( simModel.model.Serializer().GeneratePins() );
1754
1755 if( pinMapInfo.IsEmpty() )
1756 pinMapInfo.m_Text = generateDefaultPinMapFromSymbol( sourcePins );
1757 }
1758 }
1759 else if( ( device == wxS( "R" )
1760 || device == wxS( "L" )
1761 || device == wxS( "C" )
1762 || device == wxS( "V" )
1763 || device == wxS( "I" ) )
1764 && prefix.StartsWith( device )
1765 && modelFromValueField )
1766 {
1767 inferredModel = true;
1768 }
1769 else if( device == wxS( "V" ) || device == wxS( "I" ) )
1770 {
1771 // See if we have a SPICE time-dependent function such as "sin(0 1 60)" or "sin 0 1 60"
1772 // that can be handled by a built-in SIM_MODEL_SOURCE.
1773
1774 wxStringTokenizer tokenizer( model, wxT( "() " ), wxTOKEN_STRTOK );
1775
1776 if( tokenizer.HasMoreTokens() )
1777 {
1778 deviceSubtypeInfo.m_Text = tokenizer.GetNextToken();
1779 deviceSubtypeInfo.m_Text.MakeUpper();
1780
1781 for( SIM_MODEL::TYPE type : SIM_MODEL::TYPE_ITERATOR() )
1782 {
1783 if( device == SIM_MODEL::SpiceInfo( type ).itemType
1784 && deviceSubtypeInfo.m_Text == SIM_MODEL::SpiceInfo( type ).functionName )
1785 {
1786 try
1787 {
1788 std::unique_ptr<SIM_MODEL> simModel = SIM_MODEL::Create( type );
1789
1790 if( deviceSubtypeInfo.m_Text == wxT( "DC" ) && tokenizer.CountTokens() == 1 )
1791 {
1792 wxCHECK( valueField, /* void */ );
1793 valueField->SetText( tokenizer.GetNextToken() );
1794 modelFromValueField = false;
1795 }
1796 else
1797 {
1798 for( int ii = 0; tokenizer.HasMoreTokens(); ++ii )
1799 {
1800 simModel->SetParamValue( ii, tokenizer.GetNextToken().ToStdString(),
1802 }
1803
1804 deviceSubtypeInfo.m_Text = SIM_MODEL::TypeInfo( type ).fieldValue;
1805
1806 spiceParamsInfo = modelInfo;
1807 spiceParamsInfo.m_Text = wxString( simModel->Serializer().GenerateParams() );
1808 }
1809
1810 internalModel = true;
1811
1812 if( pinMapInfo.IsEmpty() )
1813 {
1814 lazySortSourcePins();
1815
1816 // Generate a default pin map from the SIM_MODEL's pins
1817 simModel->createPins( sourcePins );
1818 pinMapInfo.m_Text = wxString( simModel->Serializer().GeneratePins() );
1819 }
1820 }
1821 catch( ... )
1822 {
1823 // Fall back to raw spice model
1824 }
1825
1826 break;
1827 }
1828 }
1829 }
1830 }
1831
1832 if( libraryModel )
1833 {
1834 SCH_FIELD libField = libInfo.CreateField( &aSymbol, SIM_LIBRARY_FIELD );
1835 aSymbol.AddField( libField );
1836
1837 SCH_FIELD nameField = modelInfo.CreateField( &aSymbol, SIM_NAME_FIELD );
1838 aSymbol.AddField( nameField );
1839
1840 if( !modelLineParams.IsEmpty() )
1841 {
1842 spiceParamsInfo = modelInfo;
1843 spiceParamsInfo.m_Pos.x += nameField.GetBoundingBox().GetWidth();
1844 spiceParamsInfo.m_Text = modelLineParams;
1845
1846 BOX2I nameBBox = nameField.GetBoundingBox();
1847 int nameWidth = nameBBox.GetWidth();
1848
1849 // Add space between model name and additional parameters
1850 nameWidth += KiROUND( nameBBox.GetHeight() * 1.25 );
1851
1852 if( nameField.GetHorizJustify() == GR_TEXT_H_ALIGN_RIGHT )
1853 spiceParamsInfo.m_Pos.x -= nameWidth;
1854 else
1855 spiceParamsInfo.m_Pos.x += nameWidth;
1856
1857 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1858 aSymbol.AddField( paramsField );
1859 }
1860
1861 if( modelFromValueField )
1862 valueField->SetText( wxT( "${SIM.NAME}" ) );
1863 }
1864 else if( inferredModel )
1865 {
1866 // DeviceType is left in the reference designator and Model is left in the value field,
1867 // so there's nothing to do here....
1868 }
1869 else if( internalModel )
1870 {
1871 SCH_FIELD deviceField = deviceInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1872 aSymbol.AddField( deviceField );
1873
1874 if( !deviceSubtypeInfo.m_Text.IsEmpty() )
1875 {
1876 SCH_FIELD subtypeField = deviceSubtypeInfo.CreateField( &aSymbol, SIM_DEVICE_SUBTYPE_FIELD );
1877 aSymbol.AddField( subtypeField );
1878 }
1879
1880 if( !spiceParamsInfo.IsEmpty() )
1881 {
1882 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1883 aSymbol.AddField( paramsField );
1884 }
1885
1886 if( modelFromValueField )
1887 valueField->SetText( wxT( "${SIM.PARAMS}" ) );
1888 }
1889 else // Insert a raw spice model as a substitute.
1890 {
1891 if( device.IsEmpty() && lib.IsEmpty() )
1892 {
1893 spiceParamsInfo = modelInfo;
1894 }
1895 else
1896 {
1897 spiceParamsInfo.m_Text.Printf( wxT( "type=\"%s\" model=\"%s\" lib=\"%s\"" ), device,
1898 model, lib );
1899 }
1900
1901 deviceInfo.m_Text = SIM_MODEL::DeviceInfo( SIM_MODEL::DEVICE_T::SPICE ).fieldValue;
1902
1903 SCH_FIELD deviceField = deviceInfo.CreateField( &aSymbol, SIM_DEVICE_FIELD );
1904 aSymbol.AddField( deviceField );
1905
1906 SCH_FIELD paramsField = spiceParamsInfo.CreateField( &aSymbol, SIM_PARAMS_FIELD );
1907 aSymbol.AddField( paramsField );
1908
1909 if( modelFromValueField )
1910 {
1911 // Get the current Value field, after previous changes.
1912 valueField = aSymbol.FindField( wxT( "Value" ) );
1913
1914 if( valueField )
1915 valueField->SetText( wxT( "${SIM.PARAMS}" ) );
1916 }
1917
1918 // We know nothing about the SPICE model here, so we've got no choice but to generate
1919 // the default pin map from the symbol's pins.
1920
1921 if( pinMapInfo.IsEmpty() )
1922 {
1923 lazySortSourcePins();
1924 pinMapInfo.m_Text = generateDefaultPinMapFromSymbol( sourcePins );
1925 }
1926 }
1927
1928 if( !pinMapInfo.IsEmpty() )
1929 {
1930 SCH_FIELD pinsField = pinMapInfo.CreateField( &aSymbol, SIM_PINS_FIELD );
1931 aSymbol.AddField( pinsField );
1932 }
1933}
1934
1935
1936template void SIM_MODEL::MigrateSimModel<SCH_SYMBOL>( SCH_SYMBOL& aSymbol,
1937 const PROJECT* aProject );
1938template void SIM_MODEL::MigrateSimModel<LIB_SYMBOL>( LIB_SYMBOL& aSymbol,
1939 const PROJECT* aProject );
constexpr EDA_IU_SCALE schIUScale
Definition: base_units.h:110
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 const wxString & GetText() const
Return the string associated with the text object.
Definition: eda_text.h:98
void SetAttributes(const EDA_TEXT &aSrc, bool aSetPosition=true)
Set the text attributes from another instance.
Definition: eda_text.cpp:424
GR_TEXT_H_ALIGN_T GetHorizJustify() const
Definition: eda_text.h:187
const TEXT_ATTRIBUTES & GetAttributes() const
Definition: eda_text.h:218
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
Definition: ki_exception.h:77
virtual const wxString What() const
A composite of Problem() and Where()
Definition: exceptions.cpp:30
virtual const wxString Problem() const
what was the problem?
Definition: exceptions.cpp:46
Define a library symbol object.
Definition: lib_symbol.h:78
A singleton reporter that reports to nowhere.
Definition: reporter.h:203
Container for project specific data.
Definition: project.h:64
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:72
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Report a string with a given severity.
Instances are attached to a symbol or sheet and provide a place for the symbol's value,...
Definition: sch_field.h:51
const BOX2I GetBoundingBox() const override
Return the orthogonal bounding box of this object for display purposes.
Definition: sch_field.cpp:617
VECTOR2I GetPosition() const override
Definition: sch_field.cpp:1486
void SetPosition(const VECTOR2I &aPosition) override
Definition: sch_field.cpp:1466
wxString GetShownText(const SCH_SHEET_PATH *aPath, bool aAllowExtraText, int aDepth=0) const
Definition: sch_field.cpp:211
void SetText(const wxString &aText) override
Definition: sch_field.cpp:1213
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition: sch_item.h:166
Schematic symbol object.
Definition: sch_symbol.h:104
static constexpr auto DIFF_FIELD
SIM_MODEL & CreateModel(SIM_MODEL::TYPE aType, const std::vector< SCH_PIN * > &aPins, REPORTER &aReporter)
Serializes/deserializes a SIM_MODEL for storage in LIB_FIELDs/SCH_FIELDs.
std::string GeneratePins() const
int FindModelPinIndex(const std::string &aSymbolPinNumber)
Definition: sim_model.cpp:717
static void MigrateSimModel(T &aSymbol, const PROJECT *aProject)
Definition: sim_model.cpp:1412
const PARAM & GetBaseParam(unsigned aParamIndex) const
Definition: sim_model.cpp:830
void AddParam(const PARAM::INFO &aInfo)
Definition: sim_model.cpp:729
bool IsStoredInValue() const
Definition: sim_model.h:509
virtual std::vector< std::string > GetPinNames() const
Definition: sim_model.h:469
virtual bool requiresSpiceModelLine(const SPICE_ITEM &aItem) const
Definition: sim_model.cpp:1038
void ClearPins()
Definition: sim_model.cpp:711
static TYPE ReadTypeFromFields(const std::vector< SCH_FIELD > &aFields, REPORTER &aReporter)
Definition: sim_model.cpp:390
std::vector< SIM_MODEL_PIN > m_modelPins
Definition: sim_model.h:539
static INFO TypeInfo(TYPE aType)
Definition: sim_model.cpp:105
static void SetFieldValue(std::vector< SCH_FIELD > &aFields, const wxString &aFieldName, const std::string &aValue)
Definition: sim_model.cpp:673
int GetPinCount() const
Definition: sim_model.h:471
void AddPin(const SIM_MODEL_PIN &aPin)
Definition: sim_model.cpp:705
static SPICE_INFO SpiceInfo(TYPE aType)
Definition: sim_model.cpp:249
const SIM_MODEL_SERIALIZER & Serializer() const
Definition: sim_model.h:436
void ReadDataFields(const std::vector< SCH_FIELD > *aFields, const std::vector< SCH_PIN * > &aPins)
Definition: sim_model.cpp:427
virtual const PARAM & GetParam(unsigned aParamIndex) const
Definition: sim_model.cpp:789
static bool InferSimModel(T &aSymbol, std::vector< SCH_FIELD > *aFields, bool aResolve, SIM_VALUE_GRAMMAR::NOTATION aNotation, wxString *aDeviceType, wxString *aModelType, wxString *aModelParams, wxString *aPinMap)
Definition: sim_model.cpp:1082
void createPins(const std::vector< SCH_PIN * > &aSymbolPins)
Definition: sim_model.cpp:1003
void WriteFields(std::vector< SCH_FIELD > &aFields) const
Definition: sim_model.cpp:445
virtual void SetBaseModel(const SIM_MODEL &aBaseModel)
Definition: sim_model.cpp:739
SIM_MODEL()=delete
static std::string GetFieldValue(const std::vector< SCH_FIELD > *aFields, const wxString &aFieldName, bool aResolve=true)
Definition: sim_model.cpp:654
int GetParamCount() const
Definition: sim_model.h:481
void AssignSymbolPinNumberToModelPin(int aPinIndex, const wxString &aSymbolPinNumber)
Definition: sim_model.cpp:758
static DEVICE_INFO DeviceInfo(DEVICE_T aDeviceType)
Definition: sim_model.cpp:60
const PARAM * FindParam(const std::string &aParamName) const
Definition: sim_model.cpp:816
virtual void doSetParamValue(int aParamIndex, const std::string &aValue)
Definition: sim_model.cpp:839
std::vector< PARAM > m_params
Definition: sim_model.h:538
const PARAM & GetParamOverride(unsigned aParamIndex) const
Definition: sim_model.cpp:824
virtual ~SIM_MODEL()
static std::unique_ptr< SIM_MODEL > Create(TYPE aType, const std::vector< SCH_PIN * > &aPins, REPORTER &aReporter)
Definition: sim_model.cpp:496
void SetParamValue(int aParamIndex, const std::string &aValue, SIM_VALUE::NOTATION aNotation=SIM_VALUE::NOTATION::SI)
Definition: sim_model.cpp:845
virtual void SwitchSingleEndedDiff(bool aDiff)
Definition: sim_model.h:511
const SIM_MODEL_PIN & GetPin(unsigned aIndex) const
Definition: sim_model.h:472
std::unique_ptr< SIM_MODEL_SERIALIZER > m_serializer
Definition: sim_model.h:541
virtual int doFindParam(const std::string &aParamName) const
Definition: sim_model.cpp:804
TYPE GetType() const
Definition: sim_model.h:464
std::vector< std::reference_wrapper< const SIM_MODEL_PIN > > GetPins() const
Definition: sim_model.cpp:748
const TYPE m_type
Definition: sim_model.h:546
const SIM_MODEL * m_baseModel
Definition: sim_model.h:540
static std::string Normalize(double aValue)
Definition: sim_value.cpp:406
static std::string ConvertNotation(const std::string &aString, NOTATION aFromNotation, NOTATION aToNotation)
Definition: sim_value.cpp:370
static double ToDouble(const std::string &aString, double aDefault=NAN)
Definition: sim_value.cpp:442
A wrapper for reporting to a wxString object.
Definition: reporter.h:171
bool HasMessage() const override
Returns true if the reporter client is non-empty.
Definition: reporter.cpp:97
#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)
Definition: ki_exception.h:39
STL namespace.
@ RPT_SEVERITY_ERROR
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.
const double IU_PER_MILS
Definition: base_units.h:77
SIM_MODEL & model
Definition: sim_library.h:41
std::vector< std::string > enumValues
Definition: sim_model.h:388
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
std::string functionName
Definition: sim_model.h:306
static constexpr auto NOT_CONNECTED
Definition: sim_model.h:73
wxString symbolPinNumber
Definition: sim_model.h:71
std::string baseModelName
@ MANDATORY_FIELDS
The first 5 are mandatory, and must be instantiated in SCH_COMPONENT and LIB_PART constructors.
@ REFERENCE_FIELD
Field Reference of part, i.e. "IC21".
@ GR_TEXT_H_ALIGN_RIGHT
VECTOR2< int32_t > VECTOR2I
Definition: vector2d.h:691