KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sim_signal_utils.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 3
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
21
22#include <algorithm>
23#include <set>
24
25#include <wx/wxcrt.h>
26
27
28namespace
29{
30
31bool isIdentChar( wxUniChar aChar )
32{
33 return wxIsalnum( aChar ) || aChar == '_';
34}
35
36
37bool isGround( const wxString& aNet )
38{
39 return aNet.IsSameAs( wxS( "GND" ), false ) || aNet == wxS( "0" );
40}
41
42} // namespace
43
44
45namespace SIM_SIGNAL
46{
47
48bool IsSingleVoltageRef( const wxString& aExpression )
49{
50 if( aExpression.Length() < 4 || !aExpression.Upper().StartsWith( wxS( "V(" ) ) )
51 return false;
52
53 int depth = 0;
54
55 for( size_t ii = 1; ii < aExpression.Length(); ++ii )
56 {
57 if( aExpression[ii] == '(' )
58 {
59 depth++;
60 }
61 else if( aExpression[ii] == ')' && --depth == 0 )
62 {
63 return ii == aExpression.Length() - 1;
64 }
65 }
66
67 return false;
68}
69
70
71bool IsMeasVector( const wxString& aSignal )
72{
73 static const std::set<wxString> refs = { wxS( "V" ), wxS( "VDB" ), wxS( "VM" ), wxS( "VP" ),
74 wxS( "VR" ), wxS( "VI" ), wxS( "I" ) };
75
76 int open = aSignal.Find( '(' );
77
78 if( open == wxNOT_FOUND )
79 return !aSignal.IsEmpty() && aSignal.find_first_of( wxS( " +-*/^,<>=" ) ) == wxString::npos;
80
81 if( !refs.count( aSignal.Left( open ).Upper() ) )
82 return false;
83
84 int depth = 0;
85 bool quoted = false;
86
87 for( size_t ii = open; ii < aSignal.Length(); ++ii )
88 {
89 if( aSignal[ii] == '"' )
90 quoted = !quoted;
91 else if( quoted )
92 continue;
93 else if( aSignal[ii] == '(' )
94 depth++;
95 else if( aSignal[ii] == ')' && --depth == 0 )
96 return ii == aSignal.Length() - 1;
97 }
98
99 return false;
100}
101
102
103bool MeasurableSignal( const wxString& aBase, PART aPart, wxString& aResult )
104{
105 switch( aPart )
106 {
107 case PART::PHASE:
108 return false;
109
110 case PART::GAIN:
111 if( IsSingleVoltageRef( aBase ) )
112 aResult = wxS( "vdb" ) + aBase.Mid( 1 );
113 else
114 aResult = wxS( "db(" ) + aBase + wxS( ")" );
115
116 return true;
117
118 case PART::AMPLITUDE:
119 aResult = wxS( "mag(" ) + aBase + wxS( ")" );
120 return true;
121
122 case PART::VALUE:
123 break;
124 }
125
126 aResult = aBase;
127 return true;
128}
129
130
131void SplitMeasurement( const wxString& aCmd, wxString& aFunc, wxString& aSignal, wxString& aParams )
132{
133 wxString cmd = aCmd;
134 cmd.Trim( false ).Trim( true );
135
136 aFunc = cmd;
137 aSignal.clear();
138 aParams.clear();
139
140 size_t space = cmd.find_first_of( wxS( " \t" ) );
141
142 if( space == wxString::npos )
143 return;
144
145 aFunc = cmd.Left( space );
146
147 wxString rest = cmd.Mid( space );
148 rest.Trim( false );
149
150 size_t len = rest.Length();
151 size_t paramStart = wxString::npos;
152 int depth = 0;
153 bool quoted = false;
154
155 for( size_t ii = 0; ii < len && paramStart == wxString::npos; ++ii )
156 {
157 wxUniChar ch = rest[ii];
158
159 if( ch == '"' )
160 quoted = !quoted;
161
162 if( quoted || ch == '"' )
163 continue;
164
165 if( ch == '(' )
166 {
167 depth++;
168 }
169 else if( ch == ')' )
170 {
171 depth--;
172 }
173 else if( depth == 0 && ii > 0 && wxIsspace( rest[ii - 1] ) && wxIsalpha( ch ) )
174 {
175 size_t jj = ii;
176
177 while( jj < len && isIdentChar( rest[jj] ) )
178 jj++;
179
180 while( jj < len && wxIsspace( rest[jj] ) )
181 jj++;
182
183 // "==" is a comparison, not an assignment
184 if( jj < len && rest[jj] == '=' && ( jj + 1 == len || rest[jj + 1] != '=' ) )
185 paramStart = ii;
186 }
187 }
188
189 aSignal = rest.Left( paramStart );
190 aSignal.Trim( true );
191
192 if( paramStart != wxString::npos )
193 {
194 aParams = rest.Mid( paramStart );
195 aParams.Trim( true );
196 }
197}
198
199
200wxString ExpandDeviceVoltages( const wxString& aExpression, const std::map<wxString, wxString>& aDeviceExprs )
201{
202 if( aDeviceExprs.empty() )
203 return aExpression;
204
205 // VDB(R1), VM(R1), ... wrap the difference in the ngspice function they stand for
206 static const std::pair<wxString, wxString> forms[] = {
207 { wxS( "VDB(" ), wxS( "db" ) }, { wxS( "VM(" ), wxS( "mag" ) }, { wxS( "VP(" ), wxS( "ph" ) },
208 { wxS( "VR(" ), wxS( "real" ) }, { wxS( "VI(" ), wxS( "imag" ) }, { wxS( "V(" ), wxS( "" ) }
209 };
210
211 std::map<wxString, wxString> byUpper;
212
213 for( const auto& [ref, expr] : aDeviceExprs )
214 byUpper[ref.Upper()] = expr;
215
216 wxString upper = aExpression.Upper();
217 wxString result;
218 size_t len = aExpression.Length();
219 bool quoted = false;
220
221 for( size_t ii = 0; ii < len; )
222 {
223 if( aExpression[ii] == '"' )
224 quoted = !quoted;
225
226 bool matched = false;
227
228 if( !quoted && ( ii == 0 || !isIdentChar( aExpression[ii - 1] ) ) )
229 {
230 for( const auto& [prefix, function] : forms )
231 {
232 if( upper.compare( ii, prefix.Length(), prefix ) != 0 )
233 continue;
234
235 size_t open = ii + prefix.Length();
236 size_t close = aExpression.find( ')', open );
237
238 if( close == wxString::npos )
239 break;
240
241 wxString ref = upper.Mid( open, close - open );
242 ref.Trim( true ).Trim( false );
243
244 auto it = byUpper.find( ref );
245
246 if( it == byUpper.end() )
247 break;
248
249 result << function << wxS( "(" ) << it->second << wxS( ")" );
250 ii = close + 1;
251 matched = true;
252 break;
253 }
254 }
255
256 if( !matched )
257 result << aExpression[ii++];
258 }
259
260 return result;
261}
262
263
264wxString QuoteNetNames( const wxString& aExpression, const std::vector<wxString>& aNetnames )
265{
266 size_t len = aExpression.length();
267 std::vector<bool> mask( len, false );
268 std::vector<bool> userQuoted( len, false );
269 wxString lower = aExpression.Lower();
270
271 auto isNetnameChar = []( wxUniChar aChar ) -> bool
272 {
273 wxUint32 value = aChar.GetValue();
274
275 if( ( value >= '0' && value <= '9' ) || ( value >= 'A' && value <= 'Z' ) || ( value >= 'a' && value <= 'z' ) )
276 return true;
277
278 switch( value )
279 {
280 case '_':
281 case '/':
282 case '+':
283 case '-':
284 case '~':
285 case '.':
286 return true;
287
288 default:
289 return false;
290 }
291 };
292
293 bool inQuote = false;
294
295 for( size_t ii = 0; ii < len; ++ii )
296 {
297 if( aExpression[ii] == '"' )
298 inQuote = !inQuote;
299
300 userQuoted[ii] = inQuote || aExpression[ii] == '"';
301 }
302
303 for( const wxString& netname : aNetnames )
304 {
305 if( netname.IsEmpty() )
306 continue;
307
308 wxString needle = netname.Lower();
309 size_t pos = lower.find( needle );
310
311 while( pos != wxString::npos )
312 {
313 size_t end = pos + needle.length();
314
315 // Whole names only, so not "IN" in "SIN(" nor "A" in net "A-B"
316 bool whole = ( pos == 0 || !isNetnameChar( aExpression[pos - 1] ) )
317 && ( end == len || !isNetnameChar( aExpression[end] ) );
318
319 if( whole && !userQuoted[pos] )
320 {
321 for( size_t ii = pos; ii < end; ++ii )
322 mask[ii] = true;
323 }
324
325 pos = lower.find( needle, pos + 1 );
326 }
327 }
328
329 wxString quoted;
330 bool open = false;
331
332 for( size_t ii = 0; ii < len; ++ii )
333 {
334 if( mask[ii] != open )
335 {
336 quoted << '"';
337 open = mask[ii];
338 }
339
340 quoted << aExpression[ii];
341 }
342
343 if( open )
344 quoted << '"';
345
346 return quoted;
347}
348
349
350bool ParensBalanced( const wxString& aExpression )
351{
352 int depth = 0;
353 bool inQuote = false;
354
355 for( wxUniChar ch : aExpression )
356 {
357 // Quoted net names may contain parentheses
358 if( ch == '"' )
359 {
360 inQuote = !inQuote;
361 continue;
362 }
363
364 if( inQuote )
365 continue;
366
367 if( ch == '(' )
368 {
369 depth++;
370 }
371 else if( ch == ')' )
372 {
373 if( --depth < 0 )
374 return false;
375 }
376 }
377
378 return depth == 0;
379}
380
381
382std::vector<wxString> ExtractSignalRefs( const wxString& aExpression )
383{
384 std::vector<wxString> refs;
385 size_t len = aExpression.length();
386
387 for( size_t ii = 0; ii < len; ++ii )
388 {
389 // Whole identifiers only, since the 'v' in "div(" is not a voltage
390 if( ii > 0 && isIdentChar( aExpression[ii - 1] ) )
391 continue;
392
393 wxUniChar prefix = wxToupper( aExpression[ii] );
394
395 if( prefix != 'V' && prefix != 'I' && prefix != 'P' )
396 continue;
397
398 size_t open = ii + 1;
399
400 // Only voltages have VDB(), VM(), VP(), VR() and VI(); "im(" is ngspice's imaginary part
401 if( prefix == 'V' )
402 {
403 static const wxString variants[] = { wxS( "DB" ), wxS( "M" ), wxS( "P" ), wxS( "R" ), wxS( "I" ) };
404
405 for( const wxString& variant : variants )
406 {
407 size_t after = open + variant.length();
408
409 if( after < len && aExpression.Mid( open, variant.length() ).Upper() == variant
410 && aExpression[after] == '(' )
411 {
412 open = after;
413 break;
414 }
415 }
416 }
417
418 if( open >= len || aExpression[open] != '(' )
419 continue;
420
421 std::vector<wxString> args;
422 wxString arg;
423 int depth = 0;
424 bool inQuote = false;
425 size_t jj = open;
426
427 for( ; jj < len; ++jj )
428 {
429 wxUniChar ch = aExpression[jj];
430
431 if( ch == '"' )
432 inQuote = !inQuote;
433
434 // Quoted net names may contain parentheses and commas
435 if( inQuote || ch == '"' )
436 {
437 arg += ch;
438 continue;
439 }
440
441 if( ch == '(' )
442 {
443 if( ++depth == 1 )
444 continue;
445 }
446 else if( ch == ')' )
447 {
448 if( --depth == 0 )
449 {
450 args.push_back( arg );
451 break;
452 }
453 }
454 else if( ch == ',' && depth == 1 )
455 {
456 args.push_back( arg );
457 arg.clear();
458 continue;
459 }
460
461 arg += ch;
462 }
463
464 for( wxString& each : args )
465 {
466 each.Replace( wxS( "\"" ), wxEmptyString );
467 each.Trim( true ).Trim( false );
468
469 if( each.IsEmpty() || isGround( each ) )
470 continue;
471
472 refs.push_back( wxString( prefix ) + wxS( "(" ) + each + wxS( ")" ) );
473 }
474
475 ii = jj;
476 }
477
478 return refs;
479}
480
481
482wxString DeviceVoltageExpression( const std::vector<std::string>& aModelPins,
483 const std::vector<std::string>& aPinNumbers,
484 const std::vector<std::string>& aPinNetNames )
485{
486 if( aModelPins.size() != 2 )
487 return wxEmptyString;
488
489 wxString nets[2];
490
491 for( size_t ii = 0; ii < 2; ++ii )
492 {
493 auto it = std::find( aPinNumbers.begin(), aPinNumbers.end(), aModelPins[ii] );
494
495 if( it == aPinNumbers.end() )
496 return wxEmptyString;
497
498 size_t index = std::distance( aPinNumbers.begin(), it );
499
500 if( index >= aPinNetNames.size() )
501 return wxEmptyString;
502
503 nets[ii] = wxString( aPinNetNames[index] );
504 }
505
506 const wxString& netA = nets[0];
507 const wxString& netB = nets[1];
508
509 if( netA.IsEmpty() || netB.IsEmpty() || netA == netB )
510 return wxEmptyString;
511
512 if( isGround( netA ) && isGround( netB ) )
513 return wxEmptyString;
514
515 if( isGround( netB ) )
516 return wxString::Format( wxS( "V(%s)" ), netA );
517
518 if( isGround( netA ) )
519 return wxString::Format( wxS( "-V(%s)" ), netB );
520
521 return wxString::Format( wxS( "V(%s) - V(%s)" ), netA, netB );
522}
523
524
525bool IsDerivedSignalVector( const wxString& aVectorName )
526{
527 wxString lower = aVectorName.Lower();
528 wxString digits;
529
530 if( !lower.StartsWith( wxS( "user" ), &digits ) && !lower.StartsWith( DEVICE_VECTOR_PREFIX, &digits ) )
531 return false;
532
533 return !digits.IsEmpty() && digits.find_first_not_of( wxS( "0123456789" ) ) == wxString::npos;
534}
535
536} // namespace SIM_SIGNAL
int index
Text handling for simulator signal expressions and measurement commands.
bool ParensBalanced(const wxString &aExpression)
bool MeasurableSignal(const wxString &aBase, PART aPart, wxString &aResult)
Build the signal a measurement should read so it matches what is plotted.
wxString QuoteNetNames(const wxString &aExpression, const std::vector< wxString > &aNetnames)
Quote every whole occurrence of a net name that ngspice would otherwise parse as an expression.
void SplitMeasurement(const wxString &aCmd, wxString &aFunc, wxString &aSignal, wxString &aParams)
Split "MAX V(out) from=1m to=2m" into its function, signal and trailing parameters.
wxString DeviceVoltageExpression(const std::vector< std::string > &aModelPins, const std::vector< std::string > &aPinNumbers, const std::vector< std::string > &aPinNetNames)
Build the voltage across a two-terminal part in its model's pin order, matching the sign of I() and P...
const wxString DEVICE_VECTOR_PREFIX
Vector name prefix for the voltage across a component, "kicad_vdev3".
bool IsDerivedSignalVector(const wxString &aVectorName)
std::vector< wxString > ExtractSignalRefs(const wxString &aExpression)
Extract the V() and I() and P() node or device references from an expression, unquoted.
PART
Which part of a complex signal a plotted row shows.
@ GAIN
AC magnitude, plotted in dB.
@ AMPLITUDE
S-parameter magnitude, plotted linear.
bool IsSingleVoltageRef(const wxString &aExpression)
bool IsMeasVector(const wxString &aSignal)
wxString ExpandDeviceVoltages(const wxString &aExpression, const std::map< wxString, wxString > &aDeviceExprs)
Replace V(R1), VDB(R1), VM(R1), ... with the terminal voltage expression of the part.
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.