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