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 (C) 1992-2024 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, you may find one here:
20 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
21 * or you may search the http://www.gnu.org website for the version 2 license,
22 * or you may write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 */
25
26#include <sim/kibis/kibis.h>
31#include <common.h>
32#include <confirm.h>
33#include <pgm_base.h>
34#include <env_paths.h>
37#include <sch_screen.h>
38#include <sch_textbox.h>
39#include <string_utils.h>
40#include <ki_exception.h>
41
43#include <fmt/core.h>
44#include <paths.h>
45#include <wx/dir.h>
46#include <wx/log.h>
47#include <locale_io.h>
48#include "markup_parser.h"
49
50
51std::string NAME_GENERATOR::Generate( const std::string& aProposedName )
52{
53 std::string name = aProposedName;
54 int ii = 1;
55
56 while( m_names.contains( name ) )
57 name = fmt::format( "{}#{}", aProposedName, ii++ );
58
59 return name;
60}
61
62
64 NETLIST_EXPORTER_BASE( aSchematic ),
65 m_libMgr( &aSchematic->Prj() )
66{
67}
68
69
70bool NETLIST_EXPORTER_SPICE::WriteNetlist( const wxString& aOutFileName, unsigned aNetlistOptions,
71 REPORTER& aReporter )
72{
73 FILE_OUTPUTFORMATTER formatter( aOutFileName, wxT( "wt" ), '\'' );
74 return DoWriteNetlist( wxEmptyString, aNetlistOptions, formatter, aReporter );
75}
76
77
78bool NETLIST_EXPORTER_SPICE::DoWriteNetlist( const wxString& aSimCommand, unsigned aSimOptions,
79 OUTPUTFORMATTER& aFormatter, REPORTER& aReporter )
80{
82
83 // Cleanup list to avoid duplicate if the netlist exporter is run more than once.
84 m_rawIncludes.clear();
85
86 bool result = ReadSchematicAndLibraries( aSimOptions, aReporter );
87
88 WriteHead( aFormatter, aSimOptions );
89
90 writeIncludes( aFormatter, aSimOptions );
91 writeModels( aFormatter );
92
93 // Skip this if there is no netlist to avoid an ngspice segfault
94 if( !m_items.empty() )
95 WriteDirectives( aSimCommand, aSimOptions, aFormatter );
96
97 writeItems( aFormatter );
98
99 WriteTail( aFormatter, aSimOptions );
100
101 return result;
102}
103
104
105void NETLIST_EXPORTER_SPICE::WriteHead( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions )
106{
107 aFormatter.Print( 0, ".title KiCad schematic\n" );
108}
109
110
111void NETLIST_EXPORTER_SPICE::WriteTail( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions )
112{
113 aFormatter.Print( 0, ".end\n" );
114}
115
116
118 REPORTER& aReporter )
119{
120 wxString msg;
121 std::set<std::string> refNames; // Set of reference names to check for duplication.
122 int ncCounter = 1;
123
124 ReadDirectives( aNetlistOptions );
125
126 m_nets.clear();
127 m_items.clear();
129 m_libParts.clear();
130
131 wxFileName cacheDir;
132 cacheDir.AssignDir( PATHS::GetUserCachePath() );
133 cacheDir.AppendDir( wxT( "ibis" ) );
134
135 if( !cacheDir.DirExists() )
136 {
137 cacheDir.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
138
139 if( !cacheDir.DirExists() )
140 {
141 wxLogTrace( wxT( "IBIS_CACHE:" ),
142 wxT( "%s:%s:%d\n * failed to create ibis cache directory '%s'" ),
143 __FILE__, __FUNCTION__, __LINE__, cacheDir.GetPath() );
144
145 return false;
146 }
147 }
148
149 wxDir dir;
150 wxString dirName = cacheDir.GetFullPath();
151
152 if( !dir.Open( dirName ) )
153 return false;
154
155 wxFileName thisFile;
156 wxArrayString fileList;
157 wxString fileSpec = wxT( "*.cache" );
158
159 thisFile.SetPath( dirName ); // Set the base path to the cache folder
160
161 size_t numFilesFound = wxDir::GetAllFiles( dirName, &fileList, fileSpec );
162
163 for( size_t ii = 0; ii < numFilesFound; ii++ )
164 {
165 // Completes path to specific file so we can get its "last access" date
166 thisFile.SetFullName( fileList[ii] );
167 wxRemoveFile( thisFile.GetFullPath() );
168 }
169
170 for( SCH_SHEET_PATH& sheet : BuildSheetList( aNetlistOptions ) )
171 {
172 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
173 {
174 SCH_SYMBOL* symbol = findNextSymbol( item, sheet );
175
176 if( !symbol || symbol->GetExcludedFromSim() )
177 continue;
178
179 try
180 {
181 SPICE_ITEM spiceItem;
182 std::vector<PIN_INFO> pins = CreatePinList( symbol, sheet, true );
183
184 for( const SCH_FIELD& field : symbol->GetFields() )
185 {
186 spiceItem.fields.emplace_back( VECTOR2I(), -1, symbol, field.GetName() );
187
188 if( field.GetId() == REFERENCE_FIELD )
189 spiceItem.fields.back().SetText( symbol->GetRef( &sheet ) );
190 else
191 spiceItem.fields.back().SetText( field.GetShownText( &sheet, false ) );
192 }
193
194 readRefName( sheet, *symbol, spiceItem, refNames );
195 readModel( sheet, *symbol, spiceItem, aReporter );
196 readPinNumbers( *symbol, spiceItem, pins );
197 readPinNetNames( *symbol, spiceItem, pins, ncCounter );
198 readNodePattern( spiceItem );
199 // TODO: transmission line handling?
200
201 m_items.push_back( std::move( spiceItem ) );
202 }
203 catch( IO_ERROR& e )
204 {
205 aReporter.Report( e.What(), RPT_SEVERITY_ERROR );
206 }
207 }
208 }
209
211}
212
213
215{
216 MARKUP::MARKUP_PARSER markupParser( aNetName->ToStdString() );
217 std::unique_ptr<MARKUP::NODE> root = markupParser.Parse();
218
219 std::function<void( const std::unique_ptr<MARKUP::NODE>&)> convertMarkup =
220 [&]( const std::unique_ptr<MARKUP::NODE>& aNode )
221 {
222 if( aNode )
223 {
224 if( !aNode->is_root() )
225 {
226 if( aNode->isOverbar() )
227 {
228 // ~{CLK} is a different signal than CLK
229 *aNetName += '~';
230 }
231 else if( aNode->isSubscript() || aNode->isSuperscript() )
232 {
233 // V_{OUT} is just a pretty-printed version of VOUT
234 }
235
236 if( aNode->has_content() )
237 *aNetName += aNode->string();
238 }
239
240 for( const std::unique_ptr<MARKUP::NODE>& child : aNode->children )
241 convertMarkup( child );
242 }
243 };
244
245 *aNetName = wxEmptyString;
246 convertMarkup( root );
247
248 // Replace all ngspice-disallowed chars in netnames by a '_'
249 aNetName->Replace( '%', '_' );
250 aNetName->Replace( '(', '_' );
251 aNetName->Replace( ')', '_' );
252 aNetName->Replace( ',', '_' );
253 aNetName->Replace( '[', '_' );
254 aNetName->Replace( ']', '_' );
255 aNetName->Replace( '<', '_' );
256 aNetName->Replace( '>', '_' );
257 aNetName->Replace( '~', '_' );
258 aNetName->Replace( ' ', '_' );
259
260 // A net name on the root sheet with a label '/foo' is going to get titled "//foo". This
261 // will trip up ngspice as "//" opens a line comment.
262 if( aNetName->StartsWith( wxS( "//" ) ) )
263 aNetName->Replace( wxS( "//" ), wxS( "/root/" ), false /* replace all */ );
264}
265
266
267wxString NETLIST_EXPORTER_SPICE::GetItemName( const wxString& aRefName ) const
268{
269 if( const SPICE_ITEM* item = FindItem( aRefName ) )
270 return item->model->SpiceGenerator().ItemName( *item );
271
272 return wxEmptyString;
273}
274
275
276const SPICE_ITEM* NETLIST_EXPORTER_SPICE::FindItem( const wxString& aRefName ) const
277{
278 const std::string refName = aRefName.ToStdString();
279 const std::list<SPICE_ITEM>& spiceItems = GetItems();
280
281 auto it = std::find_if( spiceItems.begin(), spiceItems.end(),
282 [refName]( const SPICE_ITEM& item )
283 {
284 return item.refName == refName;
285 } );
286
287 if( it != spiceItems.end() )
288 return &*it;
289
290 return nullptr;
291}
292
293
294void NETLIST_EXPORTER_SPICE::ReadDirectives( unsigned aNetlistOptions )
295{
296 wxString msg;
297 wxString text;
298
299 m_directives.clear();
300
301 for( const SCH_SHEET_PATH& sheet : BuildSheetList( aNetlistOptions ) )
302 {
303 for( SCH_ITEM* item : sheet.LastScreen()->Items() )
304 {
305 if( item->GetExcludedFromSim() )
306 continue;
307
308 if( item->Type() == SCH_TEXT_T )
309 text = static_cast<SCH_TEXT*>( item )->GetShownText( &sheet, false );
310 else if( item->Type() == SCH_TEXTBOX_T )
311 text = static_cast<SCH_TEXTBOX*>( item )->GetShownText( &sheet, false );
312 else
313 continue;
314
315 // Send anything that contains directives to SPICE
316 wxStringTokenizer tokenizer( text, wxT( "\r\n" ), wxTOKEN_STRTOK );
317 bool foundDirective = false;
318
319 auto isDirective =
320 []( const wxString& line, const wxString& dir )
321 {
322 return line == dir || line.StartsWith( dir + wxS( " " ) );
323 };
324
325 while( tokenizer.HasMoreTokens() )
326 {
327 wxString line = tokenizer.GetNextToken().Upper();
328
329 if( line.StartsWith( wxT( "." ) ) )
330 {
331 if( isDirective( line, wxS( ".AC" ) )
332 || isDirective( line, wxS( ".CONTROL" ) )
333 || isDirective( line, wxS( ".CSPARAM" ) )
334 || isDirective( line, wxS( ".DISTO" ) )
335 || isDirective( line, wxS( ".DC" ) )
336 || isDirective( line, wxS( ".ELSE" ) )
337 || isDirective( line, wxS( ".ELSEIF" ) )
338 || isDirective( line, wxS( ".END" ) )
339 || isDirective( line, wxS( ".ENDC" ) )
340 || isDirective( line, wxS( ".ENDIF" ) )
341 || isDirective( line, wxS( ".ENDS" ) )
342 || isDirective( line, wxS( ".FOUR" ) )
343 || isDirective( line, wxS( ".FUNC" ) )
344 || isDirective( line, wxS( ".GLOBAL" ) )
345 || isDirective( line, wxS( ".IC" ) )
346 || isDirective( line, wxS( ".IF" ) )
347 || isDirective( line, wxS( ".INCLUDE" ) )
348 || isDirective( line, wxS( ".LIB" ) )
349 || isDirective( line, wxS( ".MEAS" ) )
350 || isDirective( line, wxS( ".MODEL" ) )
351 || isDirective( line, wxS( ".NODESET" ) )
352 || isDirective( line, wxS( ".NOISE" ) )
353 || isDirective( line, wxS( ".OP" ) )
354 || isDirective( line, wxS( ".OPTIONS" ) )
355 || isDirective( line, wxS( ".PARAM" ) )
356 || isDirective( line, wxS( ".PLOT" ) )
357 || isDirective( line, wxS( ".PRINT" ) )
358 || isDirective( line, wxS( ".PROBE" ) )
359 || isDirective( line, wxS( ".PZ" ) )
360 || isDirective( line, wxS( ".SAVE" ) )
361 || isDirective( line, wxS( ".SENS" ) )
362 || isDirective( line, wxS( ".SP" ) )
363 || isDirective( line, wxS( ".SUBCKT" ) )
364 || isDirective( line, wxS( ".TEMP" ) )
365 || isDirective( line, wxS( ".TF" ) )
366 || isDirective( line, wxS( ".TITLE" ) )
367 || isDirective( line, wxS( ".TRAN" ) )
368 || isDirective( line, wxS( ".WIDTH" ) ) )
369 {
370 foundDirective = true;
371 break;
372 }
373 }
374 else if( line.StartsWith( wxT( "K" ) ) )
375 {
376 // Check for mutual inductor declaration
377 wxStringTokenizer line_t( line, wxT( " \t" ), wxTOKEN_STRTOK );
378
379 // Coupling ID
380 if( !line_t.HasMoreTokens() || !line_t.GetNextToken().StartsWith( wxT( "K" ) ) )
381 continue;
382
383 // Inductor 1 ID
384 if( !line_t.HasMoreTokens() || !line_t.GetNextToken().StartsWith( wxT( "L" ) ) )
385 continue;
386
387 // Inductor 2 ID
388 if( !line_t.HasMoreTokens() || !line_t.GetNextToken().StartsWith( wxT( "L" ) ) )
389 continue;
390
391 // That's probably distinctive enough not to bother trying to parse the
392 // coupling value. If there's anything else, assume it's the value.
393 if( line_t.HasMoreTokens() )
394 {
395 foundDirective = true;
396 break;
397 }
398 }
399 }
400
401 if( foundDirective )
402 m_directives.emplace_back( text );
403 }
404 }
405}
406
407
409 SPICE_ITEM& aItem, std::set<std::string>& aRefNames )
410{
411 aItem.refName = aSymbol.GetRef( &aSheet );
412
413 if( !aRefNames.insert( aItem.refName ).second )
414 wxASSERT( wxT( "Duplicate refdes encountered; what happened to ReadyToNetlist()?" ) );
415}
416
417
419 SPICE_ITEM& aItem, REPORTER& aReporter )
420{
421 const SIM_LIBRARY::MODEL& libModel = m_libMgr.CreateModel( &aSheet, aSymbol, aReporter );
422
423 aItem.baseModelName = libModel.name;
424 aItem.model = &libModel.model;
425
426 std::string modelName = aItem.model->SpiceGenerator().ModelName( aItem );
427 // Resolve model name collisions.
428 aItem.modelName = m_modelNameGenerator.Generate( modelName );
429
430 // FIXME: Don't have special cases for raw Spice models and KIBIS.
431 if( auto rawSpiceModel = dynamic_cast<const SIM_MODEL_RAW_SPICE*>( aItem.model ) )
432 {
433 int libParamIndex = static_cast<int>( SIM_MODEL_RAW_SPICE::SPICE_PARAM::LIB );
434 wxString path = rawSpiceModel->GetParam( libParamIndex ).value;
435
436 if( !path.IsEmpty() )
437 m_rawIncludes.insert( path );
438 }
439 else if( auto ibisModel = dynamic_cast<const SIM_MODEL_IBIS*>( aItem.model ) )
440 {
441 wxFileName cacheFn;
442 cacheFn.AssignDir( PATHS::GetUserCachePath() );
443 cacheFn.AppendDir( wxT( "ibis" ) );
444 cacheFn.SetFullName( aSymbol.GetRef( &aSheet ) + wxT( ".cache" ) );
445
446 wxFile cacheFile( cacheFn.GetFullPath(), wxFile::write );
447
448 if( !cacheFile.IsOpened() )
449 {
450 wxLogError( _( "Could not open file '%s' to write IBIS model" ),
451 cacheFn.GetFullPath() );
452 }
453
454 auto spiceGenerator = static_cast<const SPICE_GENERATOR_IBIS&>( ibisModel->SpiceGenerator() );
455
456 wxString cacheFilepath = cacheFn.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR );
457 std::string modelData = spiceGenerator.IbisDevice( aItem, m_schematic->Prj(),
458 cacheFilepath, aReporter );
459
460 cacheFile.Write( wxString( modelData ) );
461 m_rawIncludes.insert( cacheFn.GetFullPath() );
462 }
463}
464
465
467 const std::vector<PIN_INFO>& aPins )
468{
469 for( const PIN_INFO& pin : aPins )
470 aItem.pinNumbers.emplace_back( pin.num.ToStdString() );
471}
472
473
475 const std::vector<PIN_INFO>& aPins, int& aNcCounter )
476{
477 for( const PIN_INFO& pinInfo : aPins )
478 {
479 wxString netName = GenerateItemPinNetName( pinInfo.netName, aNcCounter );
480
481 aItem.pinNetNames.push_back( netName.ToStdString() );
482 m_nets.insert( netName );
483 }
484}
485
486
488 std::vector<std::string>& aModifiers )
489{
490 std::string input = SIM_MODEL::GetFieldValue( &aItem.fields, SIM_NODES_FORMAT_FIELD, true );
491
492 if( input == "" )
493 return;
494
495 tao::pegtl::string_input<> in( input, "Sim.NodesFormat field" );
496 std::unique_ptr<tao::pegtl::parse_tree::node> root;
497 std::string singleNodeModifier;
498
499 try
500 {
501 root = tao::pegtl::parse_tree::parse<SIM_XSPICE_PARSER_GRAMMAR::nodeSequenceGrammar,
503 tao::pegtl::nothing,
505 for( const auto& node : root->children )
506 {
507 if( node->is_type<SIM_XSPICE_PARSER_GRAMMAR::squareBracketC>() )
508 {
509 //we want ']' to close previous ?
510 aModifiers.back().append( node->string() );
511 }
512 else
513 { //rest goes to the new singleNodeModifier
514 singleNodeModifier.append( node->string() );
515 }
516
517 if( node->is_type<SIM_XSPICE_PARSER_GRAMMAR::nodeName>() )
518 {
519 aModifiers.push_back( singleNodeModifier );
520 singleNodeModifier.erase( singleNodeModifier.begin(), singleNodeModifier.end() );
521 }
522 }
523 }
524 catch( const tao::pegtl::parse_error& e )
525 {
526 THROW_IO_ERROR( wxString::Format( _( "Error in parsing model '%s', error: '%s'" ),
527 aItem.refName, e.what() ) );
528 }
529}
531{
532 std::vector<std::string> xspicePattern;
533 NETLIST_EXPORTER_SPICE::getNodePattern( aItem, xspicePattern );
534
535 if( xspicePattern.empty() )
536 return;
537
538 if( xspicePattern.size() != aItem.pinNetNames.size() )
539 {
540 THROW_IO_ERROR( wxString::Format( _( "Error in parsing model '%s', wrong number of nodes "
541 "'?' in Sim.NodesFormat compared to connections" ),
542 aItem.refName ) );
543 return;
544 }
545
546 auto itNetNames = aItem.pinNetNames.begin();
547
548 for( std::string& pattern : xspicePattern )
549 {
550 // ngspice does not care about aditional spaces, and we make sure that "%d?" is separated
551 const std::string netName = " " + *itNetNames + " ";
552 pattern.replace( pattern.find( "?" ), 1, netName );
553 *itNetNames = pattern;
554 ++itNetNames;
555 }
556}
557
558void NETLIST_EXPORTER_SPICE::writeInclude( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions,
559 const wxString& aPath )
560{
561 // First, expand env vars, if any.
562 wxString expandedPath = ExpandEnvVarSubstitutions( aPath, &m_schematic->Prj() );
563
564 // Path may have been authored by someone on a Windows box; convert it to UNIX format
565 expandedPath.Replace( '\\', '/' );
566
567 wxString fullPath;
568
569 if( aNetlistOptions & OPTION_ADJUST_INCLUDE_PATHS )
570 {
571 // Look for the library in known search locations.
572 fullPath = ResolveFile( expandedPath, &Pgm().GetLocalEnvVariables(), &m_schematic->Prj() );
573
574 if( fullPath.IsEmpty() )
575 {
576 wxLogError( _( "Could not find library file '%s'" ), expandedPath );
577 fullPath = expandedPath;
578 }
579 else if( wxFileName::GetPathSeparator() == '\\' )
580 {
581 // Convert it to UNIX format (again) if ResolveFile() returned a Windows style path
582 fullPath.Replace( '\\', '/' );
583 }
584 }
585 else
586 {
587 fullPath = expandedPath;
588 }
589
590 aFormatter.Print( 0, ".include \"%s\"\n", TO_UTF8( fullPath ) );
591}
592
593
594void NETLIST_EXPORTER_SPICE::writeIncludes( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions )
595{
596 for( const auto& [path, library] : m_libMgr.GetLibraries() )
597 {
598 if( dynamic_cast<const SIM_LIBRARY_SPICE*>( &library.get() ) )
599 writeInclude( aFormatter, aNetlistOptions, path );
600 }
601
602 for( const wxString& path : m_rawIncludes )
603 writeInclude( aFormatter, aNetlistOptions, path );
604}
605
606
608{
609 for( const SPICE_ITEM& item : m_items )
610 {
611 if( !item.model->IsEnabled() )
612 continue;
613
614 aFormatter.Print( 0, "%s", item.model->SpiceGenerator().ModelLine( item ).c_str() );
615 }
616}
617
618
620{
621 for( const SPICE_ITEM& item : m_items )
622 {
623 if( !item.model->IsEnabled() )
624 continue;
625
626 aFormatter.Print( 0, "%s", item.model->SpiceGenerator().ItemLine( item ).c_str() );
627 }
628}
629
630
631void NETLIST_EXPORTER_SPICE::WriteDirectives( const wxString& aSimCommand, unsigned aSimOptions,
632 OUTPUTFORMATTER& aFormatter ) const
633{
634 if( aSimOptions & OPTION_SAVE_ALL_VOLTAGES )
635 aFormatter.Print( 0, ".save all\n" );
636
637 if( aSimOptions & OPTION_SAVE_ALL_CURRENTS )
638 aFormatter.Print( 0, ".probe alli\n" );
639
640 if( aSimOptions & OPTION_SAVE_ALL_DISSIPATIONS )
641 {
642 for( const SPICE_ITEM& item : m_items )
643 {
644 // ngspice (v39) does not support power measurement for XSPICE devices
645 // XPSICE devices are marked with 'A'
646 std::string itemName = item.model->SpiceGenerator().ItemName( item );
647
648 if( ( item.model->GetPinCount() >= 2 ) && ( itemName.size() > 0 )
649 && ( itemName.c_str()[0] != 'A' ) )
650 {
651 aFormatter.Print( 0, ".probe p(%s)\n", itemName.c_str() );
652 }
653 }
654 }
655
656 auto isSimCommand =
657 []( const wxString& candidate, const wxString& dir )
658 {
659 return candidate == dir || candidate.StartsWith( dir + wxS( " " ) );
660 };
661
662 for( const wxString& directive : m_directives )
663 {
664 bool simCommand = false;
665
666 if( directive.StartsWith( "." ) )
667 {
668 wxString candidate = directive.Upper();
669
670 simCommand = ( isSimCommand( candidate, wxS( ".AC" ) )
671 || isSimCommand( candidate, wxS( ".DC" ) )
672 || isSimCommand( candidate, wxS( ".TRAN" ) )
673 || isSimCommand( candidate, wxS( ".OP" ) )
674 || isSimCommand( candidate, wxS( ".DISTO" ) )
675 || isSimCommand( candidate, wxS( ".NOISE" ) )
676 || isSimCommand( candidate, wxS( ".PZ" ) )
677 || isSimCommand( candidate, wxS( ".SENS" ) )
678 || isSimCommand( candidate, wxS( ".TF" ) ) );
679 }
680
681 if( !simCommand || ( aSimOptions & OPTION_SIM_COMMAND ) )
682 aFormatter.Print( 0, "%s\n", UTF8( directive ).c_str() );
683 }
684}
685
686
687wxString NETLIST_EXPORTER_SPICE::GenerateItemPinNetName( const wxString& aNetName,
688 int& aNcCounter ) const
689{
690 wxString netName = UnescapeString( aNetName );
691
692 ConvertToSpiceMarkup( &netName );
693
694 if( netName.IsEmpty() )
695 netName.Printf( wxS( "NC-%d" ), aNcCounter++ );
696
697 return netName;
698}
699
700
702{
703 SCH_SHEET_LIST sheets;
704
705 if( aNetlistOptions & OPTION_CUR_SHEET_AS_ROOT )
707 else
709
710 alg::delete_if( sheets,
711 [&]( const SCH_SHEET_PATH& sheet )
712 {
713 return sheet.GetExcludedFromSim();
714 } );
715
716 return sheets;
717}
718
const char * name
Definition: DXF_plotter.cpp:57
Used for text file output.
Definition: richio.h:478
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
Definition: ki_exception.h:77
virtual const wxString What() const
A composite of Problem() and Where()
Definition: exceptions.cpp:30
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:49
std::unique_ptr< NODE > Parse()
std::unordered_set< std::string > m_names
std::string Generate(const std::string &aProposedName)
An abstract class used for the netlist exporters that Eeschema supports.
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
UNIQUE_STRINGS m_referencesAlreadyFound
Used for "multiple symbols per package" symbols to avoid processing a lib symbol more than once.
SCHEMATIC_IFACE * m_schematic
The schematic we're generating a netlist for.
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
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).
void readModel(SCH_SHEET_PATH &aSheet, SCH_SYMBOL &aSymbol, SPICE_ITEM &aItem, REPORTER &aReporter)
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
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.
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
virtual void WriteTail(OUTPUTFORMATTER &aFormatter, unsigned aNetlistOptions)
Write the tail (.end).
NAME_GENERATOR m_modelNameGenerator
Generates unique model names.
NETLIST_EXPORTER_SPICE(SCHEMATIC_IFACE *aSchematic)
bool WriteNetlist(const wxString &aOutFileName, unsigned aNetlistOptions, REPORTER &aReporter) override
Write to specified output file.
An interface used to output 8 bit text in a convenient way.
Definition: richio.h:322
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:458
static wxString GetUserCachePath()
Gets the stock (install) 3d viewer plugins path.
Definition: paths.cpp:365
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:72
virtual bool HasMessageOfSeverity(int aSeverityMask) const
Returns true if the reporter has one or more messages matching the specified severity mask.
Definition: reporter.cpp:53
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Report a string with a given severity.
virtual SCH_SHEET_PATH & CurrentSheet() const =0
virtual SCH_SHEET_LIST BuildSheetListSortedByPageNumbers() const =0
virtual PROJECT & Prj() const =0
Instances are attached to a symbol or sheet and provide a place for the symbol's value,...
Definition: sch_field.h:51
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition: sch_item.h:166
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
SCH_SHEET * Last() const
Return a pointer to the last SCH_SHEET of the list.
Schematic symbol object.
Definition: sch_symbol.h:106
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly)
Populate a std::vector with SCH_FIELDs.
Definition: sch_symbol.cpp:982
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
Definition: sch_symbol.cpp:735
virtual wxString GetShownText(const SCH_SHEET_PATH *aPath, bool aAllowExtraText, int aDepth=0) const
SIM_MODEL & CreateModel(SIM_MODEL::TYPE aType, const std::vector< SCH_PIN * > &aPins, REPORTER &aReporter)
std::map< wxString, std::reference_wrapper< const SIM_LIBRARY > > GetLibraries() const
const SPICE_GENERATOR & SpiceGenerator() const
Definition: sim_model.h:435
static std::string GetFieldValue(const std::vector< SCH_FIELD > *aFields, const wxString &aFieldName, bool aResolve=true)
Definition: sim_model.cpp:650
std::string IbisDevice(const SPICE_ITEM &aItem, const PROJECT &aProject, const wxString &aCacheDir, REPORTER &aReporter) const
virtual std::string ModelName(const SPICE_ITEM &aItem) const
bool GetExcludedFromSim() const override
Definition: symbol.h:136
void Clear()
Erase the record.
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition: utf8.h:72
const char * c_str() const
Definition: utf8.h:103
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:343
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.
Definition: env_paths.cpp:164
#define THROW_IO_ERROR(msg)
Definition: ki_exception.h:39
PROJECT & Prj()
Definition: kicad.cpp:595
must_if< error >::control< Rule > control
void delete_if(_Container &__c, _Function &&__f)
Deletes all values from __c for which __f returns true.
Definition: kicad_algo.h:174
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: pgm_base.cpp:1059
see class PGM_BASE
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_UNDEFINED
#define SIM_NODES_FORMAT_FIELD
Definition: sim_model.h:58
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.
Definition: string_utils.h:391
SIM_MODEL & model
Definition: sim_library.h:41
std::string name
Definition: sim_library.h:40
Notes: spaces are allowed everywhere in any number ~ can only be before ? ~~ is not allowed [] can en...
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
@ REFERENCE_FIELD
Field Reference of part, i.e. "IC21".
@ SCH_SYMBOL_T
Definition: typeinfo.h:172
@ SCH_TEXT_T
Definition: typeinfo.h:151
@ SCH_TEXTBOX_T
Definition: typeinfo.h:152
VECTOR2< int32_t > VECTOR2I
Definition: vector2d.h:691