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