KiCad PCB EDA Suite
Loading...
Searching...
No Matches
netlist_exporter_spice.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) 1992-2013 jp.charras at wanadoo.fr
5 * Copyright (C) 2013 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
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 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22#include <sim/kibis/kibis.h>
26#include <common.h>
27#include <confirm.h>
28#include <pgm_base.h>
29#include <env_paths.h>
30#include <richio.h>
33#include <sch_screen.h>
34#include <sch_textbox.h>
35#include <string_utils.h>
36#include <algorithm>
37#include <ki_exception.h>
38
40#include <fmt/core.h>
41#include <paths.h>
42#include <wx/dir.h>
43#include <wx/log.h>
44#include <wx/tokenzr.h>
45#include <locale_io.h>
46#include "markup_parser.h"
47
48
49std::string NAME_GENERATOR::Generate( const std::string& aProposedName )
50{
51 std::string name = aProposedName;
52 int ii = 1;
53
54 // insert() both tests for the collision and records the accepted name, so subsequent calls
55 // actually see previously generated names.
56 while( !m_names.insert( name ).second )
57 name = fmt::format( "{}#{}", aProposedName, ii++ );
58
59 return name;
60}
61
62
64 NETLIST_EXPORTER_BASE( aSchematic ),
65 m_libMgr( &aSchematic->Project() )
66{
67 std::vector<EMBEDDED_FILES*> embeddedFilesStack;
68 embeddedFilesStack.push_back( aSchematic->GetEmbeddedFiles() );
69 m_libMgr.SetFilesStack( std::move( embeddedFilesStack ) );
70}
71
72
73bool NETLIST_EXPORTER_SPICE::WriteNetlist( const wxString& aOutFileName, unsigned aNetlistOptions,
74 REPORTER& aReporter )
75{
76 try
77 {
78 FILE_OUTPUTFORMATTER formatter( aOutFileName, wxT( "wt" ), '\'' );
79 bool result = DoWriteNetlist( wxEmptyString, aNetlistOptions, formatter, aReporter );
80 formatter.Finish();
81
82 return result;
83 }
84 catch( const IO_ERROR& ioe )
85 {
86 aReporter.Report( ioe.What(), RPT_SEVERITY_ERROR );
87 return false;
88 }
89}
90
91
92bool NETLIST_EXPORTER_SPICE::DoWriteNetlist( const wxString& aSimCommand, unsigned aSimOptions,
93 OUTPUTFORMATTER& aFormatter, REPORTER& aReporter )
94{
96
97 // Cleanup list to avoid duplicate if the netlist exporter is run more than once.
98 m_rawIncludes.clear();
99
100 bool result = ReadSchematicAndLibraries( aSimOptions, aReporter );
101
102 WriteHead( aFormatter, aSimOptions );
103
104 writeIncludes( aFormatter, aSimOptions );
105 writeModels( aFormatter );
106
107 // Skip this if there is no netlist to avoid an ngspice segfault
108 if( !m_items.empty() )
109 WriteDirectives( aSimCommand, aSimOptions, aFormatter );
110
111 writeItems( aFormatter );
112
113 WriteTail( aFormatter, aSimOptions );
114
115 return result;
116}
117
118
119void NETLIST_EXPORTER_SPICE::WriteHead( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions )
120{
121 aFormatter.Print( 0, ".title KiCad schematic\n" );
122}
123
124
125void NETLIST_EXPORTER_SPICE::WriteTail( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions )
126{
127 aFormatter.Print( 0, ".end\n" );
128}
129
130
132 REPORTER& aReporter )
133{
134 std::set<std::string> refNames; // Set of reference names to check for duplication.
135 int ncCounter = 1;
136 wxString variant = m_schematic->GetCurrentVariant();
137
138 ReadDirectives( aNetlistOptions );
139
140 m_nets.clear();
141 m_items.clear();
142 m_multiunitModels.clear();
143 m_modelNameGenerator.Clear();
145 m_libParts.clear();
146
147 wxFileName cacheDir;
148 cacheDir.AssignDir( PATHS::GetUserCachePath() );
149 cacheDir.AppendDir( wxT( "ibis" ) );
150
151 if( !cacheDir.DirExists() )
152 {
153 cacheDir.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
154
155 if( !cacheDir.DirExists() )
156 {
157 wxLogTrace( wxT( "IBIS_CACHE:" ),
158 wxT( "%s:%s:%d\n * failed to create ibis cache directory '%s'" ),
159 __FILE__, __FUNCTION__, __LINE__, cacheDir.GetPath() );
160
161 return false;
162 }
163 }
164
165 wxDir dir;
166 wxString dirName = cacheDir.GetFullPath();
167
168 if( !dir.Open( dirName ) )
169 return false;
170
171 wxFileName thisFile;
172 wxArrayString fileList;
173 wxString fileSpec = wxT( "*.cache" );
174
175 thisFile.SetPath( dirName ); // Set the base path to the cache folder
176
177 size_t numFilesFound = wxDir::GetAllFiles( dirName, &fileList, fileSpec );
178
179 for( size_t ii = 0; ii < numFilesFound; ii++ )
180 {
181 // Completes path to specific file so we can get its "last access" date
182 thisFile.SetFullName( fileList[ii] );
183 wxRemoveFile( thisFile.GetFullPath() );
184 }
185
186 for( SCH_SHEET_PATH& sheet : BuildSheetList( aNetlistOptions ) )
187 {
188 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
189 {
190 SCH_SYMBOL* symbol = findNextSymbol( item, sheet );
191
192 if( !symbol || symbol->ResolveExcludedFromSim( &sheet, variant ) )
193 continue;
194
195 try
196 {
197 SPICE_ITEM spiceItem;
198 std::vector<PIN_INFO> pins = CreatePinList( symbol, sheet, true );
199
200 for( const SCH_FIELD& field : symbol->GetFields() )
201 {
202 spiceItem.fields.emplace_back( symbol, FIELD_T::USER, field.GetName() );
203
204 if( field.GetId() == FIELD_T::REFERENCE )
205 spiceItem.fields.back().SetText( symbol->GetRef( &sheet ) );
206 else
207 spiceItem.fields.back().SetText( field.GetShownText( &sheet, false, 0, variant ) );
208 }
209
210 readRefName( sheet, *symbol, spiceItem, refNames );
211 readModel( sheet, *symbol, spiceItem, variant, aReporter );
212 readPinNumbers( *symbol, spiceItem, pins );
213 readPinNetNames( *symbol, spiceItem, pins, ncCounter );
214 readNodePattern( spiceItem );
215 // TODO: transmission line handling?
216
217 m_items.push_back( std::move( spiceItem ) );
218 }
219 catch( IO_ERROR& e )
220 {
221 aReporter.Report( e.What(), RPT_SEVERITY_ERROR );
222 }
223 }
224 }
225
227}
228
229
231{
232 MARKUP::MARKUP_PARSER markupParser( aNetName->ToStdString() );
233 std::unique_ptr<MARKUP::NODE> root = markupParser.Parse();
234
235 std::function<void( const std::unique_ptr<MARKUP::NODE>&)> convertMarkup =
236 [&]( const std::unique_ptr<MARKUP::NODE>& aNode )
237 {
238 if( aNode )
239 {
240 if( !aNode->is_root() )
241 {
242 if( aNode->isOverbar() )
243 {
244 // ~{CLK} is a different signal than CLK
245 *aNetName += '~';
246 }
247 else if( aNode->isSubscript() || aNode->isSuperscript() )
248 {
249 // V_{OUT} is just a pretty-printed version of VOUT
250 }
251
252 if( aNode->has_content() )
253 *aNetName += aNode->string();
254 }
255
256 for( const std::unique_ptr<MARKUP::NODE>& child : aNode->children )
257 convertMarkup( child );
258 }
259 };
260
261 *aNetName = wxEmptyString;
262 convertMarkup( root );
263
264 // Replace all ngspice-disallowed chars in netnames by a '_'
265 aNetName->Replace( '%', '_' );
266 aNetName->Replace( '(', '_' );
267 aNetName->Replace( ')', '_' );
268 aNetName->Replace( ',', '_' );
269 aNetName->Replace( '[', '_' );
270 aNetName->Replace( ']', '_' );
271 aNetName->Replace( '<', '_' );
272 aNetName->Replace( '>', '_' );
273 aNetName->Replace( '~', '_' );
274 aNetName->Replace( ' ', '_' );
275
276 // Make sure that SPICE zero should be zero anywhere, independent if it is local or not.
277 // Therefore any signal ending with '/0' is rewritten as '0' to be recognized by SPICE.
278 if( aNetName->EndsWith( wxS( "/0" ) ) && !aNetName->EndsWith( wxS( "//0" ) ) )
279 aNetName->assign( wxS( "0" ) );
280
281 // Make sure that local ground signals with leading slash ('/gnd') are rewritten as gloabal gnd to be recognized
282 // by SPICE as zero.
283 if( aNetName->IsSameAs( wxS( "/gnd" ), false /* caseSensitive=false */ ) )
284 aNetName->assign( aNetName->Mid( 1 ) );
285
286 // A net name on the root sheet with a label '/foo' is going to get titled "//foo". This
287 // will trip up ngspice as "//" opens a line comment.
288 if( aNetName->StartsWith( wxS( "//" ) ) )
289 aNetName->Replace( wxS( "//" ), wxS( "/root/" ), false /* replace all */ );
290}
291
292
293wxString NETLIST_EXPORTER_SPICE::GetItemName( const wxString& aRefName ) const
294{
295 if( const SPICE_ITEM* item = FindItem( aRefName ) )
296 return item->model->SpiceGenerator().ItemName( *item );
297
298 return wxEmptyString;
299}
300
301
302const SPICE_ITEM* NETLIST_EXPORTER_SPICE::FindItem( const wxString& aRefName ) const
303{
304 const std::string refName = aRefName.ToStdString();
305 const std::list<SPICE_ITEM>& spiceItems = GetItems();
306
307 auto it = std::find_if( spiceItems.begin(), spiceItems.end(),
308 [&refName]( const SPICE_ITEM& item )
309 {
310 return item.refName == refName;
311 } );
312
313 if( it != spiceItems.end() )
314 return &*it;
315
316 return nullptr;
317}
318
319
320void NETLIST_EXPORTER_SPICE::ReadDirectives( unsigned aNetlistOptions )
321{
322 wxString text;
323
324 m_directives.clear();
325
326 for( const SCH_SHEET_PATH& sheet : BuildSheetList( aNetlistOptions ) )
327 {
328 for( SCH_ITEM* item : sheet.LastScreen()->Items() )
329 {
330 if( item->ResolveExcludedFromSim() )
331 continue;
332
333 if( item->Type() == SCH_TEXT_T )
334 text = static_cast<SCH_TEXT*>( item )->GetShownText( &sheet, false );
335 else if( item->Type() == SCH_TEXTBOX_T )
336 text = static_cast<SCH_TEXTBOX*>( item )->GetShownText( nullptr, &sheet, false );
337 else
338 continue;
339
340 // Send anything that contains directives to SPICE
341 wxStringTokenizer tokenizer( text, "\r\n", wxTOKEN_STRTOK );
342 bool foundDirective = false;
343
344 auto isDirective =
345 []( const wxString& line, const wxString& dir )
346 {
347 return line == dir || line.StartsWith( dir + wxS( " " ) );
348 };
349
350 while( tokenizer.HasMoreTokens() )
351 {
352 wxString line = tokenizer.GetNextToken().Upper();
353
354 if( line.StartsWith( wxT( "." ) ) )
355 {
356 if( isDirective( line, wxS( ".AC" ) )
357 || isDirective( line, wxS( ".CONTROL" ) )
358 || isDirective( line, wxS( ".CSPARAM" ) )
359 || isDirective( line, wxS( ".DISTO" ) )
360 || isDirective( line, wxS( ".DC" ) )
361 || isDirective( line, wxS( ".ELSE" ) )
362 || isDirective( line, wxS( ".ELSEIF" ) )
363 || isDirective( line, wxS( ".END" ) )
364 || isDirective( line, wxS( ".ENDC" ) )
365 || isDirective( line, wxS( ".ENDIF" ) )
366 || isDirective( line, wxS( ".ENDS" ) )
367 || isDirective( line, wxS( ".FOUR" ) )
368 || isDirective( line, wxS( ".FUNC" ) )
369 || isDirective( line, wxS( ".GLOBAL" ) )
370 || isDirective( line, wxS( ".IC" ) )
371 || isDirective( line, wxS( ".IF" ) )
372 || isDirective( line, wxS( ".INCLUDE" ) )
373 || isDirective( line, wxS( ".LIB" ) )
374 || isDirective( line, wxS( ".MEAS" ) )
375 || isDirective( line, wxS( ".MODEL" ) )
376 || isDirective( line, wxS( ".NODESET" ) )
377 || isDirective( line, wxS( ".NOISE" ) )
378 || isDirective( line, wxS( ".OP" ) )
379 || isDirective( line, wxS( ".OPTIONS" ) )
380 || isDirective( line, wxS( ".PARAM" ) )
381 || isDirective( line, wxS( ".PLOT" ) )
382 || isDirective( line, wxS( ".PRINT" ) )
383 || isDirective( line, wxS( ".PROBE" ) )
384 || isDirective( line, wxS( ".PZ" ) )
385 || isDirective( line, wxS( ".SAVE" ) )
386 || isDirective( line, wxS( ".SENS" ) )
387 || isDirective( line, wxS( ".SP" ) )
388 || isDirective( line, wxS( ".SUBCKT" ) )
389 || isDirective( line, wxS( ".TEMP" ) )
390 || isDirective( line, wxS( ".TF" ) )
391 || isDirective( line, wxS( ".TITLE" ) )
392 || isDirective( line, wxS( ".TRAN" ) )
393 || isDirective( line, wxS( ".WIDTH" ) ) )
394 {
395 foundDirective = true;
396 break;
397 }
398 }
399 else if( line.StartsWith( wxT( "K" ) ) )
400 {
401 // Check for mutual inductor declaration
402 wxStringTokenizer line_t( line, " \t", wxTOKEN_STRTOK );
403
404 // Coupling ID
405 if( !line_t.HasMoreTokens() || !line_t.GetNextToken().StartsWith( wxT( "K" ) ) )
406 continue;
407
408 // Inductor 1 ID
409 if( !line_t.HasMoreTokens() || !line_t.GetNextToken().StartsWith( wxT( "L" ) ) )
410 continue;
411
412 // Inductor 2 ID
413 if( !line_t.HasMoreTokens() || !line_t.GetNextToken().StartsWith( wxT( "L" ) ) )
414 continue;
415
416 // That's probably distinctive enough not to bother trying to parse the
417 // coupling value. If there's anything else, assume it's the value.
418 if( line_t.HasMoreTokens() )
419 {
420 foundDirective = true;
421 break;
422 }
423 }
424 }
425
426 if( foundDirective )
427 m_directives.emplace_back( text );
428 }
429 }
430}
431
432
434 const SCH_SHEET_PATH& aSheet,
435 const wxString& aVariantName )
436{
437 // Only process multi-unit symbols
438 if( !aSymbol.GetLibSymbolRef() || aSymbol.GetLibSymbolRef()->GetUnitCount() <= 1 )
439 return wxEmptyString;
440
441 wxString ref = aSymbol.GetRef( &aSheet );
442 std::vector<std::pair<wxString, wxString>> pinList;
443 std::set<wxString> pinNumbers;
444
445 // Helper to parse and collect pin mappings from a Sim.Pins field value
446 auto parsePins = [&]( const wxString& aPins )
447 {
448 wxStringTokenizer tokenizer( aPins, wxS( " \t\r\n" ), wxTOKEN_STRTOK );
449
450 while( tokenizer.HasMoreTokens() )
451 {
452 wxString token = tokenizer.GetNextToken();
453 int pos = token.Find( wxS( '=' ) );
454
455 if( pos == wxNOT_FOUND )
456 continue;
457
458 wxString pinNumber = token.Left( pos );
459 wxString modelPin = token.Mid( pos + 1 );
460
461 // Only add if we haven't seen this pin number before
462 if( pinNumbers.insert( pinNumber ).second )
463 pinList.emplace_back( pinNumber, modelPin );
464 }
465 };
466
467 // First, parse pins from the current symbol
468 if( SCH_FIELD* pinsField = aSymbol.GetField( SIM_PINS_FIELD ) )
469 parsePins( pinsField->GetShownText( &aSheet, false, 0, aVariantName ) );
470
471 // Then, find all other units with the same reference and collect their Sim.Pins
472 for( const SCH_SHEET_PATH& sheet : m_schematic->Hierarchy() )
473 {
474 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
475 {
476 SCH_SYMBOL* other = static_cast<SCH_SYMBOL*>( item );
477
478 if( other == &aSymbol )
479 continue;
480
481 if( other->GetRef( &sheet ) != ref )
482 continue;
483
484 if( SCH_FIELD* pinsField = other->GetField( SIM_PINS_FIELD ) )
485 parsePins( pinsField->GetShownText( &sheet, false, 0, aVariantName ) );
486 }
487 }
488
489 // If no pins were collected or only from current symbol, return empty
490 // (let the normal processing handle it)
491 if( pinList.empty() )
492 return wxEmptyString;
493
494 // Build the merged Sim.Pins string
495 wxString merged;
496
497 for( const auto& [pinNumber, modelPin] : pinList )
498 {
499 if( !merged.IsEmpty() )
500 merged += wxS( " " );
501
502 merged += pinNumber + wxS( "=" ) + modelPin;
503 }
504
505 return merged;
506}
507
508
509std::vector<UNIT_PIN_MAP> NETLIST_EXPORTER_SPICE::collectUnitPinMaps( SCH_SYMBOL& aSymbol,
510 const SCH_SHEET_PATH& aSheet,
511 const wxString& aVariantName )
512{
513 std::vector<UNIT_PIN_MAP> unitMaps;
514
515 if( !aSymbol.GetLibSymbolRef() || aSymbol.GetLibSymbolRef()->GetUnitCount() <= 1 )
516 return unitMaps;
517
518 wxString ref = aSymbol.GetRef( &aSheet );
519 std::set<int> seenUnits;
520
521 auto parseUnit =
522 [&]( SCH_SYMBOL& aUnit, const SCH_SHEET_PATH& aUnitSheet )
523 {
524 SCH_FIELD* pinsField = aUnit.GetField( SIM_PINS_FIELD );
525
526 if( !pinsField )
527 return;
528
529 wxString pins = pinsField->GetShownText( &aUnitSheet, false, 0, aVariantName );
530
531 // The same logical unit can be reached more than once through a reused hierarchical
532 // sheet; gather it only once so it does not synthesize duplicate instances.
533 if( !seenUnits.insert( aUnit.GetUnit() ).second )
534 return;
535
536 UNIT_PIN_MAP map;
537 map.unit = aUnit.GetUnit();
538 map.pins = ParseSimPinsTokens( pins, ref );
539
540 if( !map.pins.empty() )
541 unitMaps.push_back( std::move( map ) );
542 };
543
544 // The primary unit is processed first; the remaining units are matched case-insensitively
545 // across the whole hierarchy, mirroring findAllUnitsOfSymbol().
546 parseUnit( aSymbol, aSheet );
547
548 for( const SCH_SHEET_PATH& sheet : m_schematic->Hierarchy() )
549 {
550 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
551 {
552 SCH_SYMBOL* other = static_cast<SCH_SYMBOL*>( item );
553
554 if( other == &aSymbol )
555 continue;
556
557 if( other->GetRef( &sheet ).CmpNoCase( ref ) != 0 )
558 continue;
559
560 parseUnit( *other, sheet );
561 }
562 }
563
564 // Order instances by unit number so the generated wrapper is deterministic regardless of
565 // where each unit happens to be placed on the schematic.
566 std::sort( unitMaps.begin(), unitMaps.end(),
567 []( const UNIT_PIN_MAP& lhs, const UNIT_PIN_MAP& rhs )
568 {
569 return lhs.unit < rhs.unit;
570 } );
571
572 return unitMaps;
573}
574
575
577 const SCH_SHEET_PATH& aSheet,
578 const wxString& aVariantName ) const
579{
580 auto read =
581 [&]( SCH_SYMBOL& aUnit, const SCH_SHEET_PATH& aUnitSheet ) -> wxString
582 {
583 if( SCH_FIELD* field = aUnit.GetField( SIM_DECOMPOSITION_FIELD ) )
584 return field->GetShownText( &aUnitSheet, false, 0, aVariantName );
585
586 return wxEmptyString;
587 };
588
589 // Decomposition is a component-level flag. Prefer the primary unit, but fall back to any
590 // sibling so it is found regardless of which unit carries it.
591 wxString value = read( aSymbol, aSheet );
592
593 if( value.IsEmpty() && aSymbol.GetLibSymbolRef() && aSymbol.GetLibSymbolRef()->GetUnitCount() > 1 )
594 {
595 wxString ref = aSymbol.GetRef( &aSheet );
596
597 for( const SCH_SHEET_PATH& sheet : m_schematic->Hierarchy() )
598 {
599 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
600 {
601 SCH_SYMBOL* other = static_cast<SCH_SYMBOL*>( item );
602
603 if( other == &aSymbol || other->GetRef( &sheet ).CmpNoCase( ref ) != 0 )
604 continue;
605
606 value = read( *other, sheet );
607
608 if( !value.IsEmpty() )
609 return SIM_DECOMPOSITION::Parse( value );
610 }
611 }
612 }
613
614 return SIM_DECOMPOSITION::Parse( value );
615}
616
617
619 SPICE_ITEM& aItem, std::set<std::string>& aRefNames )
620{
621 aItem.refName = aSymbol.GetRef( &aSheet );
622
623 [[maybe_unused]] bool inserted = aRefNames.insert( aItem.refName ).second;
624 wxASSERT_MSG( inserted, wxT( "Duplicate refdes encountered; what happened to ReadyToNetlist()?" ) );
625}
626
627
629 const wxString& aVariantName, REPORTER& aReporter )
630{
631 SIM_DECOMPOSITION decomposition = getDecomposition( aSymbol, aSheet, aVariantName );
632
633 bool multiUnit = aSymbol.GetLibSymbolRef() && aSymbol.GetLibSymbolRef()->GetUnitCount() > 1;
634 bool repeat = decomposition.mode == SIM_DECOMPOSITION::MODE::REPEAT_PER_UNIT && multiUnit;
635
636 // The whole-device default merges the per-unit Sim.Pins into one instance. Repeat mode keeps
637 // the units distinct and synthesizes a wrapper, so it must not merge.
638 wxString mergedSimPins = repeat ? wxString()
639 : collectMergedSimPins( aSymbol, aSheet, aVariantName );
640
641 const SIM_LIBRARY::MODEL& libModel = m_libMgr.CreateModel( &aSheet, aSymbol, true, 0, aVariantName,
642 aReporter, mergedSimPins );
643
644 aItem.baseModelName = libModel.name;
645 aItem.model = &libModel.model;
646
647 if( repeat )
648 {
649 // The wrapper instantiates the base as a subcircuit (inner X lines), so it only supports a
650 // named subcircuit base model. Built-in/IBIS/unresolved models would yield invalid inner
651 // instances, so reject them with a clear error rather than emit a broken netlist.
652 if( libModel.model.GetType() != SIM_MODEL::TYPE::SUBCKT || libModel.name.empty() )
653 {
654 THROW_IO_ERROR( wxString::Format(
655 _( "Symbol '%s' uses repeat-per-unit decomposition, which requires a named "
656 "subcircuit model." ),
657 aSymbol.GetRef( &aSheet ) ) );
658 }
659
660 std::vector<UNIT_PIN_MAP> unitMaps = collectUnitPinMaps( aSymbol, aSheet, aVariantName );
661
662 // The wrapper copies what it needs from libModel.model at construction; m_multiunitModels
663 // keeps it alive for as long as m_items references it via aItem.model. Build it even for a
664 // single functional unit so that shared pins carried by other units are still wired (the
665 // constructor throws if no instances result). It owns its content-derived name so
666 // identical components share one definition; do not run it through the per-item uniquifier.
667 auto wrapper = std::make_unique<SIM_MODEL_MULTIUNIT>( libModel.model, libModel.name, unitMaps,
668 decomposition.sharedModelPins );
669
670 aItem.model = wrapper.get();
671 aItem.baseModelName = wrapper->GetSignature();
672 aItem.modelName = wrapper->GetSignature().ToStdString();
673
674 m_multiunitModels.push_back( std::move( wrapper ) );
675 return;
676 }
677
678 std::string modelName = aItem.model->SpiceGenerator().ModelName( aItem );
679
680 // Only uniquify names that KiCad itself defines with a .model line. A subcircuit (or other
681 // externally defined) name has to match the definition pulled in from its library verbatim, and
682 // several symbols sharing one subcircuit must resolve to that same name, so it is left untouched.
683 if( aItem.model->requiresSpiceModelLine( aItem ) )
684 aItem.modelName = m_modelNameGenerator.Generate( modelName );
685 else
686 aItem.modelName = modelName;
687
688 // Each model type contributes its own external `.include` files (raw-Spice libraries, IBIS
689 // device caches, ...) so the exporter stays agnostic to the concrete model.
690 for( const wxString& include : aItem.model->GetSpiceIncludes( aItem, m_schematic, aReporter ) )
691 m_rawIncludes.insert( include );
692}
693
694
696 const std::vector<PIN_INFO>& aPins )
697{
698 for( const PIN_INFO& pin : aPins )
699 aItem.pinNumbers.emplace_back( pin.num.ToStdString() );
700}
701
702
704 const std::vector<PIN_INFO>& aPins, int& aNcCounter )
705{
706 for( const PIN_INFO& pinInfo : aPins )
707 {
708 wxString netName = GenerateItemPinNetName( pinInfo.netName, aNcCounter );
709
710 aItem.pinNetNames.push_back( netName.ToStdString() );
711 m_nets.insert( netName );
712 }
713}
714
715
717 std::vector<std::string>& aModifiers )
718{
719 std::string input = GetFieldValue( &aItem.fields, SIM_NODES_FORMAT_FIELD, true, 0 );
720
721 if( input == "" )
722 return;
723
724 tao::pegtl::string_input<> in( input, "Sim.NodesFormat field" );
725 std::unique_ptr<tao::pegtl::parse_tree::node> root;
726 std::string singleNodeModifier;
727
728 try
729 {
730 root = tao::pegtl::parse_tree::parse<SIM_XSPICE_PARSER_GRAMMAR::nodeSequenceGrammar,
732 tao::pegtl::nothing,
734 for( const auto& node : root->children )
735 {
736 if( node->is_type<SIM_XSPICE_PARSER_GRAMMAR::squareBracketC>() )
737 {
738 //we want ']' to close previous ?
739 aModifiers.back().append( node->string() );
740 }
741 else
742 { //rest goes to the new singleNodeModifier
743 singleNodeModifier.append( node->string() );
744 }
745
746 if( node->is_type<SIM_XSPICE_PARSER_GRAMMAR::nodeName>() )
747 {
748 aModifiers.push_back( singleNodeModifier );
749 singleNodeModifier.erase( singleNodeModifier.begin(), singleNodeModifier.end() );
750 }
751 }
752 }
753 catch( const tao::pegtl::parse_error& e )
754 {
755 THROW_IO_ERROR( wxString::Format( _( "Error in parsing model '%s', error: '%s'" ),
756 aItem.refName, e.what() ) );
757 }
758}
760{
761 std::vector<std::string> xspicePattern;
762 NETLIST_EXPORTER_SPICE::getNodePattern( aItem, xspicePattern );
763
764 if( xspicePattern.empty() )
765 return;
766
767 if( xspicePattern.size() != aItem.pinNetNames.size() )
768 {
769 THROW_IO_ERROR( wxString::Format( _( "Error in parsing model '%s', wrong number of nodes "
770 "'?' in Sim.NodesFormat compared to connections" ),
771 aItem.refName ) );
772 return;
773 }
774
775 auto itNetNames = aItem.pinNetNames.begin();
776
777 for( std::string& pattern : xspicePattern )
778 {
779 // ngspice does not care about aditional spaces, and we make sure that "%d?" is separated
780 const std::string netName = " " + *itNetNames + " ";
781 pattern.replace( pattern.find( "?" ), 1, netName );
782 *itNetNames = pattern;
783 ++itNetNames;
784 }
785}
786
787void NETLIST_EXPORTER_SPICE::writeInclude( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions,
788 const wxString& aPath )
789{
790 // First, expand env vars, if any.
791 wxString expandedPath = ExpandEnvVarSubstitutions( aPath, &m_schematic->Project() );
792
793 // Path may have been authored by someone on a Windows box; convert it to UNIX format
794 expandedPath.Replace( '\\', '/' );
795
796 wxString fullPath;
797
798 if( aNetlistOptions & OPTION_ADJUST_INCLUDE_PATHS )
799 {
800 // Look for the library in known search locations.
801 fullPath = ResolveFile( expandedPath, &Pgm().GetLocalEnvVariables(), &m_schematic->Project() );
802
803 if( fullPath.IsEmpty() )
804 {
805 wxLogError( _( "Could not find library file '%s'" ), expandedPath );
806 fullPath = expandedPath;
807 }
808 else if( wxFileName::GetPathSeparator() == '\\' )
809 {
810 // Convert it to UNIX format (again) if ResolveFile() returned a Windows style path
811 fullPath.Replace( '\\', '/' );
812 }
813 }
814 else
815 {
816 fullPath = expandedPath;
817 }
818
819 aFormatter.Print( 0, ".include \"%s\"\n", TO_UTF8( fullPath ) );
820}
821
822
823void NETLIST_EXPORTER_SPICE::writeIncludes( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions )
824{
825 for( const auto& [path, library] : m_libMgr.GetLibraries() )
826 {
827 if( dynamic_cast<const SIM_LIBRARY_SPICE*>( &library.get() ) )
828 writeInclude( aFormatter, aNetlistOptions, path );
829 }
830
831 for( const wxString& path : m_rawIncludes )
832 writeInclude( aFormatter, aNetlistOptions, path );
833}
834
835
837{
838 std::set<std::string> emittedWrappers;
839
840 for( const SPICE_ITEM& item : m_items )
841 {
842 if( !item.model->IsEnabled() )
843 continue;
844
845 // Identical multi-unit wrappers share one content-derived .subckt definition, but each is
846 // a distinct item, so emit any given wrapper exactly once.
847 if( dynamic_cast<const SIM_MODEL_MULTIUNIT*>( item.model )
848 && !emittedWrappers.insert( item.modelName ).second )
849 {
850 continue;
851 }
852
853 aFormatter.Print( 0, "%s", item.model->SpiceGenerator().ModelLine( item ).c_str() );
854 }
855}
856
857
859{
860 for( const SPICE_ITEM& item : m_items )
861 {
862 if( !item.model->IsEnabled() )
863 continue;
864
865 aFormatter.Print( 0, "%s", item.model->SpiceGenerator().ItemLine( item ).c_str() );
866 }
867}
868
869
870void NETLIST_EXPORTER_SPICE::WriteDirectives( const wxString& aSimCommand, unsigned aSimOptions,
871 OUTPUTFORMATTER& aFormatter ) const
872{
873 if( aSimOptions & OPTION_SAVE_ALL_VOLTAGES )
874 aFormatter.Print( 0, ".save all\n" );
875
876 if( aSimOptions & OPTION_SAVE_ALL_CURRENTS )
877 aFormatter.Print( 0, ".probe alli\n" );
878
879 if( aSimOptions & OPTION_SAVE_ALL_DISSIPATIONS )
880 {
881 for( const SPICE_ITEM& item : m_items )
882 {
883 // ngspice (v39) does not support power measurement for XSPICE devices
884 // XPSICE devices are marked with 'A'
885 std::string itemName = item.model->SpiceGenerator().ItemName( item );
886
887 if( ( item.model->GetPinCount() >= 2 ) && ( itemName.size() > 0 )
888 && ( itemName.c_str()[0] != 'A' ) )
889 {
890 aFormatter.Print( 0, ".probe p(%s)\n", itemName.c_str() );
891 }
892 }
893 }
894
895 auto isSimCommand =
896 []( const wxString& candidate, const wxString& dir )
897 {
898 return candidate == dir || candidate.StartsWith( dir + wxS( " " ) );
899 };
900
901 for( const wxString& directive : m_directives )
902 {
903 bool simCommand = false;
904
905 if( directive.StartsWith( "." ) )
906 {
907 wxString candidate = directive.Upper();
908
909 simCommand = ( isSimCommand( candidate, wxS( ".AC" ) )
910 || isSimCommand( candidate, wxS( ".DC" ) )
911 || isSimCommand( candidate, wxS( ".TRAN" ) )
912 || isSimCommand( candidate, wxS( ".OP" ) )
913 || isSimCommand( candidate, wxS( ".DISTO" ) )
914 || isSimCommand( candidate, wxS( ".NOISE" ) )
915 || isSimCommand( candidate, wxS( ".PZ" ) )
916 || isSimCommand( candidate, wxS( ".SENS" ) )
917 || isSimCommand( candidate, wxS( ".TF" ) ) );
918 }
919
920 if( !simCommand || ( aSimOptions & OPTION_SIM_COMMAND ) )
921 aFormatter.Print( 0, "%s\n", UTF8( directive ).c_str() );
922 }
923}
924
925
926wxString NETLIST_EXPORTER_SPICE::GenerateItemPinNetName( const wxString& aNetName,
927 int& aNcCounter ) const
928{
929 wxString netName = UnescapeString( aNetName );
930
931 ConvertToSpiceMarkup( &netName );
932
933 if( netName.IsEmpty() )
934 netName.Printf( wxS( "NC-%d" ), aNcCounter++ );
935
936 return netName;
937}
938
939
941{
942 SCH_SHEET_LIST sheets;
943
944 if( aNetlistOptions & OPTION_CUR_SHEET_AS_ROOT )
945 sheets = SCH_SHEET_LIST( m_schematic->CurrentSheet().Last() );
946 else
947 sheets = m_schematic->Hierarchy();
948
949 std::erase_if( sheets,
950 [&]( const SCH_SHEET_PATH& sheet )
951 {
952 return sheet.GetExcludedFromSim();
953 } );
954
955 return sheets;
956}
957
const char * name
Used for text file output.
Definition richio.h:470
bool Finish() override
Flushes the temp file to disk and atomically renames it over the final target path.
Definition richio.cpp:642
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
int GetUnitCount() const override
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition locale_io.h:37
std::unique_ptr< NODE > Parse()
std::unordered_set< std::string > m_names
std::string Generate(const std::string &aProposedName)
SCHEMATIC * m_schematic
The schematic we're generating a netlist for.
std::vector< PIN_INFO > CreatePinList(SCH_SYMBOL *aSymbol, const SCH_SHEET_PATH &aSheetPath, bool aKeepUnconnectedPins)
Find a symbol from the DrawList and builds its pin list.
SCH_SYMBOL * findNextSymbol(EDA_ITEM *aItem, const SCH_SHEET_PATH &aSheetPath)
Check if the given symbol should be processed for netlisting.
std::set< LIB_SYMBOL *, LIB_SYMBOL_LESS_THAN > m_libParts
unique library symbols used. LIB_SYMBOL items are sorted by names
NETLIST_EXPORTER_BASE(SCHEMATIC *aSchematic)
UNIQUE_STRINGS m_referencesAlreadyFound
Used for "multiple symbols per package" symbols to avoid processing a lib symbol more than once.
void readPinNetNames(SCH_SYMBOL &aSymbol, SPICE_ITEM &aItem, const std::vector< PIN_INFO > &aPins, int &aNcCounter)
void writeModels(OUTPUTFORMATTER &aFormatter)
void writeIncludes(OUTPUTFORMATTER &aFormatter, unsigned aNetlistOptions)
std::list< SPICE_ITEM > m_items
Owns the synthesized repeat-per-unit wrappers referenced by m_items.
void getNodePattern(SPICE_ITEM &aItem, std::vector< std::string > &aModifiers)
static void ConvertToSpiceMarkup(wxString *aNetName)
Remove formatting wrappers and replace illegal spice net name characters with underscores.
void ReadDirectives(unsigned aNetlistOptions)
SCH_SHEET_LIST BuildSheetList(unsigned aNetlistOptions=0) const
Return the paths of exported sheets (either all or the current one).
virtual wxString GenerateItemPinNetName(const wxString &aNetName, int &aNcCounter) const
std::set< wxString > m_nets
Items representing schematic symbols in Spice world.
void readRefName(SCH_SHEET_PATH &aSheet, SCH_SYMBOL &aSymbol, SPICE_ITEM &aItem, std::set< std::string > &aRefNames)
wxString GetItemName(const wxString &aRefName) const
Return name of Spice device corresponding to a schematic symbol.
void writeItems(OUTPUTFORMATTER &aFormatter)
std::vector< wxString > m_directives
Spice directives found in the schematic sheet.
virtual void WriteHead(OUTPUTFORMATTER &aFormatter, unsigned aNetlistOptions)
Write the netlist head (title and so on).
void writeInclude(OUTPUTFORMATTER &aFormatter, unsigned aNetlistOptions, const wxString &aPath)
virtual void WriteDirectives(const wxString &aSimCommand, unsigned aSimOptions, OUTPUTFORMATTER &candidate) const
NETLIST_EXPORTER_SPICE(SCHEMATIC *aSchematic)
wxString collectMergedSimPins(SCH_SYMBOL &aSymbol, const SCH_SHEET_PATH &aSheet, const wxString &aVariantName)
Collect merged Sim.Pins from all units of a multi-unit symbol.
SIM_LIB_MGR m_libMgr
Holds libraries and models.
const SPICE_ITEM * FindItem(const wxString &aRefName) const
Find and return the item corresponding to aRefName.
virtual bool ReadSchematicAndLibraries(unsigned aNetlistOptions, REPORTER &aReporter)
Process the schematic and Spice libraries to create net mapping and a list of SPICE_ITEMs.
SIM_DECOMPOSITION getDecomposition(SCH_SYMBOL &aSymbol, const SCH_SHEET_PATH &aSheet, const wxString &aVariantName) const
Read and parse the Sim.Decomposition field from the primary unit.
bool DoWriteNetlist(const wxString &aSimCommand, unsigned aSimOptions, OUTPUTFORMATTER &aFormatter, REPORTER &aReporter)
Write the netlist in aFormatter.
void readPinNumbers(SCH_SYMBOL &aSymbol, SPICE_ITEM &aItem, const std::vector< PIN_INFO > &aPins)
const std::list< SPICE_ITEM > & GetItems() const
Return the list of items representing schematic symbols in the Spice world.
void readNodePattern(SPICE_ITEM &aItem)
std::set< wxString > m_rawIncludes
include directives found in symbols
void readModel(SCH_SHEET_PATH &aSheet, SCH_SYMBOL &aSymbol, SPICE_ITEM &aItem, const wxString &aVariantName, REPORTER &aReporter)
virtual void WriteTail(OUTPUTFORMATTER &aFormatter, unsigned aNetlistOptions)
Write the tail (.end).
NAME_GENERATOR m_modelNameGenerator
Generates unique model names.
std::vector< std::unique_ptr< SIM_MODEL_MULTIUNIT > > m_multiunitModels
bool WriteNetlist(const wxString &aOutFileName, unsigned aNetlistOptions, REPORTER &aReporter) override
Write to specified output file.
std::vector< UNIT_PIN_MAP > collectUnitPinMaps(SCH_SYMBOL &aSymbol, const SCH_SHEET_PATH &aSheet, const wxString &aVariantName)
Gather every unit's Sim.Pins mapping for a multi-unit symbol, one entry per unit.
An interface used to output 8 bit text in a convenient way.
Definition richio.h:291
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition richio.cpp:422
static wxString GetUserCachePath()
Gets the stock (install) 3d viewer plugins path.
Definition paths.cpp:460
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:71
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:100
virtual bool HasMessageOfSeverity(int aSeverityMask) const
Returns true if the reporter has one or more messages matching the specified severity mask.
Definition reporter.h:141
Holds all the data relating to one schematic.
Definition schematic.h:90
EMBEDDED_FILES * GetEmbeddedFiles() override
wxString GetShownText(const SCH_SHEET_PATH *aPath, bool aAllowExtraText, int aDepth=0, const wxString &aVariantName=wxEmptyString) const
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:162
int GetUnit() const
Definition sch_item.h:233
bool ResolveExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const
Definition sch_item.cpp:298
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
bool GetExcludedFromSim() const
Schematic symbol object.
Definition sch_symbol.h:69
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:177
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this symbol.
Wraps a resolved single-unit base model and presents it as one component-level SPICE device.
virtual bool requiresSpiceModelLine(const SPICE_ITEM &aItem) const
const SPICE_GENERATOR & SpiceGenerator() const
Definition sim_model.h:429
virtual std::vector< wxString > GetSpiceIncludes(const SPICE_ITEM &aItem, SCHEMATIC *aSchematic, REPORTER &aReporter) const
Return the external files this model must pull into the netlist as .include directives,...
Definition sim_model.h:438
TYPE GetType() const
Definition sim_model.h:471
virtual std::string ModelName(const SPICE_ITEM &aItem) const
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition utf8.h:67
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition common.cpp:721
The common library.
This file is part of the common library.
#define _(s)
wxString ResolveFile(const wxString &aFileName, const ENV_VAR_MAP *aEnvVars, const PROJECT *aProject)
Search the default paths trying to find one with the requested file.
Helper functions to substitute paths with environmental variables.
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
must_if< error >::control< Rule > control
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_UNDEFINED
wxString GetFieldValue(const std::vector< SCH_FIELD > *aFields, FIELD_T aFieldType)
Definition sch_field.h:421
#define SIM_PINS_FIELD
Definition sim_model.h:51
#define SIM_NODES_FORMAT_FIELD
Definition sim_model.h:56
#define SIM_DECOMPOSITION_FIELD
Definition sim_model.h:52
std::vector< std::pair< wxString, wxString > > ParseSimPinsTokens(const wxString &aPins, const wxString &aRef)
Parse one unit's Sim.Pins text into (symbolPinNumber -> modelPinName) pairs, preserving the written o...
std::vector< FAB_LAYER_COLOR > dummy
wxString UnescapeString(const wxString &aSource)
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Per-component decomposition descriptor stored in the Sim.Decomposition field.
static SIM_DECOMPOSITION Parse(const wxString &aField)
std::vector< wxString > sharedModelPins
SIM_MODEL & model
Definition sim_library.h:37
std::string name
Definition sim_library.h:36
Notes: spaces are allowed everywhere in any number ~ can only be before ?
std::string refName
std::vector< SCH_FIELD > fields
std::string modelName
const SIM_MODEL * model
std::vector< std::string > pinNetNames
std::string baseModelName
std::vector< std::string > pinNumbers
One functional unit's pin map, gathered from its Sim.Pins field.
std::vector< std::pair< wxString, wxString > > pins
@ USER
The field ID hasn't been set yet; field is invalid.
@ REFERENCE
Field Reference of part, i.e. "IC21".
std::string path
KIBIS_PIN * pin
wxString result
Test unit parsing edge cases and error handling.
@ SCH_SYMBOL_T
Definition typeinfo.h:169
@ SCH_TEXT_T
Definition typeinfo.h:148
@ SCH_TEXTBOX_T
Definition typeinfo.h:149