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