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