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, 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(), aSchematic )
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(), FIELD_T::USER, symbol,
188 field.GetName() );
189
190 if( field.GetId() == FIELD_T::REFERENCE )
191 spiceItem.fields.back().SetText( symbol->GetRef( &sheet ) );
192 else
193 spiceItem.fields.back().SetText( field.GetShownText( &sheet, false ) );
194 }
195
196 readRefName( sheet, *symbol, spiceItem, refNames );
197 readModel( sheet, *symbol, spiceItem, aReporter );
198 readPinNumbers( *symbol, spiceItem, pins );
199 readPinNetNames( *symbol, spiceItem, pins, ncCounter );
200 readNodePattern( spiceItem );
201 // TODO: transmission line handling?
202
203 m_items.push_back( std::move( spiceItem ) );
204 }
205 catch( IO_ERROR& e )
206 {
207 aReporter.Report( e.What(), RPT_SEVERITY_ERROR );
208 }
209 }
210 }
211
213}
214
215
217{
218 MARKUP::MARKUP_PARSER markupParser( aNetName->ToStdString() );
219 std::unique_ptr<MARKUP::NODE> root = markupParser.Parse();
220
221 std::function<void( const std::unique_ptr<MARKUP::NODE>&)> convertMarkup =
222 [&]( const std::unique_ptr<MARKUP::NODE>& aNode )
223 {
224 if( aNode )
225 {
226 if( !aNode->is_root() )
227 {
228 if( aNode->isOverbar() )
229 {
230 // ~{CLK} is a different signal than CLK
231 *aNetName += '~';
232 }
233 else if( aNode->isSubscript() || aNode->isSuperscript() )
234 {
235 // V_{OUT} is just a pretty-printed version of VOUT
236 }
237
238 if( aNode->has_content() )
239 *aNetName += aNode->string();
240 }
241
242 for( const std::unique_ptr<MARKUP::NODE>& child : aNode->children )
243 convertMarkup( child );
244 }
245 };
246
247 *aNetName = wxEmptyString;
248 convertMarkup( root );
249
250 // Replace all ngspice-disallowed chars in netnames by a '_'
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 aNetName->Replace( ' ', '_' );
261
262 // A net name on the root sheet with a label '/foo' is going to get titled "//foo". This
263 // will trip up ngspice as "//" opens a line comment.
264 if( aNetName->StartsWith( wxS( "//" ) ) )
265 aNetName->Replace( wxS( "//" ), wxS( "/root/" ), false /* replace all */ );
266}
267
268
269wxString NETLIST_EXPORTER_SPICE::GetItemName( const wxString& aRefName ) const
270{
271 if( const SPICE_ITEM* item = FindItem( aRefName ) )
272 return item->model->SpiceGenerator().ItemName( *item );
273
274 return wxEmptyString;
275}
276
277
278const SPICE_ITEM* NETLIST_EXPORTER_SPICE::FindItem( const wxString& aRefName ) const
279{
280 const std::string refName = aRefName.ToStdString();
281 const std::list<SPICE_ITEM>& spiceItems = GetItems();
282
283 auto it = std::find_if( spiceItems.begin(), spiceItems.end(),
284 [refName]( const SPICE_ITEM& item )
285 {
286 return item.refName == refName;
287 } );
288
289 if( it != spiceItems.end() )
290 return &*it;
291
292 return nullptr;
293}
294
295
296void NETLIST_EXPORTER_SPICE::ReadDirectives( unsigned aNetlistOptions )
297{
298 wxString msg;
299 wxString text;
300
301 m_directives.clear();
302
303 for( const SCH_SHEET_PATH& sheet : BuildSheetList( aNetlistOptions ) )
304 {
305 for( SCH_ITEM* item : sheet.LastScreen()->Items() )
306 {
307 if( item->GetExcludedFromSim() )
308 continue;
309
310 if( item->Type() == SCH_TEXT_T )
311 text = static_cast<SCH_TEXT*>( item )->GetShownText( &sheet, false );
312 else if( item->Type() == SCH_TEXTBOX_T )
313 text = static_cast<SCH_TEXTBOX*>( item )->GetShownText( &sheet, false );
314 else
315 continue;
316
317 // Send anything that contains directives to SPICE
318 wxStringTokenizer tokenizer( text, wxT( "\r\n" ), wxTOKEN_STRTOK );
319 bool foundDirective = false;
320
321 auto isDirective =
322 []( const wxString& line, const wxString& dir )
323 {
324 return line == dir || line.StartsWith( dir + wxS( " " ) );
325 };
326
327 while( tokenizer.HasMoreTokens() )
328 {
329 wxString line = tokenizer.GetNextToken().Upper();
330
331 if( line.StartsWith( wxT( "." ) ) )
332 {
333 if( isDirective( line, wxS( ".AC" ) )
334 || isDirective( line, wxS( ".CONTROL" ) )
335 || isDirective( line, wxS( ".CSPARAM" ) )
336 || isDirective( line, wxS( ".DISTO" ) )
337 || isDirective( line, wxS( ".DC" ) )
338 || isDirective( line, wxS( ".ELSE" ) )
339 || isDirective( line, wxS( ".ELSEIF" ) )
340 || isDirective( line, wxS( ".END" ) )
341 || isDirective( line, wxS( ".ENDC" ) )
342 || isDirective( line, wxS( ".ENDIF" ) )
343 || isDirective( line, wxS( ".ENDS" ) )
344 || isDirective( line, wxS( ".FOUR" ) )
345 || isDirective( line, wxS( ".FUNC" ) )
346 || isDirective( line, wxS( ".GLOBAL" ) )
347 || isDirective( line, wxS( ".IC" ) )
348 || isDirective( line, wxS( ".IF" ) )
349 || isDirective( line, wxS( ".INCLUDE" ) )
350 || isDirective( line, wxS( ".LIB" ) )
351 || isDirective( line, wxS( ".MEAS" ) )
352 || isDirective( line, wxS( ".MODEL" ) )
353 || isDirective( line, wxS( ".NODESET" ) )
354 || isDirective( line, wxS( ".NOISE" ) )
355 || isDirective( line, wxS( ".OP" ) )
356 || isDirective( line, wxS( ".OPTIONS" ) )
357 || isDirective( line, wxS( ".PARAM" ) )
358 || isDirective( line, wxS( ".PLOT" ) )
359 || isDirective( line, wxS( ".PRINT" ) )
360 || isDirective( line, wxS( ".PROBE" ) )
361 || isDirective( line, wxS( ".PZ" ) )
362 || isDirective( line, wxS( ".SAVE" ) )
363 || isDirective( line, wxS( ".SENS" ) )
364 || isDirective( line, wxS( ".SP" ) )
365 || isDirective( line, wxS( ".SUBCKT" ) )
366 || isDirective( line, wxS( ".TEMP" ) )
367 || isDirective( line, wxS( ".TF" ) )
368 || isDirective( line, wxS( ".TITLE" ) )
369 || isDirective( line, wxS( ".TRAN" ) )
370 || isDirective( line, wxS( ".WIDTH" ) ) )
371 {
372 foundDirective = true;
373 break;
374 }
375 }
376 else if( line.StartsWith( wxT( "K" ) ) )
377 {
378 // Check for mutual inductor declaration
379 wxStringTokenizer line_t( line, wxT( " \t" ), wxTOKEN_STRTOK );
380
381 // Coupling ID
382 if( !line_t.HasMoreTokens() || !line_t.GetNextToken().StartsWith( wxT( "K" ) ) )
383 continue;
384
385 // Inductor 1 ID
386 if( !line_t.HasMoreTokens() || !line_t.GetNextToken().StartsWith( wxT( "L" ) ) )
387 continue;
388
389 // Inductor 2 ID
390 if( !line_t.HasMoreTokens() || !line_t.GetNextToken().StartsWith( wxT( "L" ) ) )
391 continue;
392
393 // That's probably distinctive enough not to bother trying to parse the
394 // coupling value. If there's anything else, assume it's the value.
395 if( line_t.HasMoreTokens() )
396 {
397 foundDirective = true;
398 break;
399 }
400 }
401 }
402
403 if( foundDirective )
404 m_directives.emplace_back( text );
405 }
406 }
407}
408
409
411 SPICE_ITEM& aItem, std::set<std::string>& aRefNames )
412{
413 aItem.refName = aSymbol.GetRef( &aSheet );
414
415 if( !aRefNames.insert( aItem.refName ).second )
416 wxASSERT( wxT( "Duplicate refdes encountered; what happened to ReadyToNetlist()?" ) );
417}
418
419
421 SPICE_ITEM& aItem, REPORTER& aReporter )
422{
423 const SIM_LIBRARY::MODEL& libModel = m_libMgr.CreateModel( &aSheet, aSymbol, aReporter );
424
425 aItem.baseModelName = libModel.name;
426 aItem.model = &libModel.model;
427
428 std::string modelName = aItem.model->SpiceGenerator().ModelName( aItem );
429 // Resolve model name collisions.
430 aItem.modelName = m_modelNameGenerator.Generate( modelName );
431
432 // FIXME: Don't have special cases for raw Spice models and KIBIS.
433 if( auto rawSpiceModel = dynamic_cast<const SIM_MODEL_RAW_SPICE*>( aItem.model ) )
434 {
435 int libParamIndex = static_cast<int>( SIM_MODEL_RAW_SPICE::SPICE_PARAM::LIB );
436 wxString path = rawSpiceModel->GetParam( libParamIndex ).value;
437
438 if( !path.IsEmpty() )
439 m_rawIncludes.insert( path );
440 }
441 else if( auto ibisModel = dynamic_cast<const SIM_MODEL_IBIS*>( aItem.model ) )
442 {
443 wxFileName cacheFn;
444 cacheFn.AssignDir( PATHS::GetUserCachePath() );
445 cacheFn.AppendDir( wxT( "ibis" ) );
446 cacheFn.SetFullName( aSymbol.GetRef( &aSheet ) + wxT( ".cache" ) );
447
448 wxFile cacheFile( cacheFn.GetFullPath(), wxFile::write );
449
450 if( !cacheFile.IsOpened() )
451 {
452 wxLogError( _( "Could not open file '%s' to write IBIS model" ),
453 cacheFn.GetFullPath() );
454 }
455
456 auto spiceGenerator = static_cast<const SPICE_GENERATOR_IBIS&>( ibisModel->SpiceGenerator() );
457
458 wxString cacheFilepath = cacheFn.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR );
459 std::string modelData = spiceGenerator.IbisDevice( aItem, m_schematic,
460 cacheFilepath, aReporter );
461
462 cacheFile.Write( wxString( modelData ) );
463 m_rawIncludes.insert( cacheFn.GetFullPath() );
464 }
465}
466
467
469 const std::vector<PIN_INFO>& aPins )
470{
471 for( const PIN_INFO& pin : aPins )
472 aItem.pinNumbers.emplace_back( pin.num.ToStdString() );
473}
474
475
477 const std::vector<PIN_INFO>& aPins, int& aNcCounter )
478{
479 for( const PIN_INFO& pinInfo : aPins )
480 {
481 wxString netName = GenerateItemPinNetName( pinInfo.netName, aNcCounter );
482
483 aItem.pinNetNames.push_back( netName.ToStdString() );
484 m_nets.insert( netName );
485 }
486}
487
488
490 std::vector<std::string>& aModifiers )
491{
492 std::string input = GetFieldValue( &aItem.fields, SIM_NODES_FORMAT_FIELD, true );
493
494 if( input == "" )
495 return;
496
497 tao::pegtl::string_input<> in( input, "Sim.NodesFormat field" );
498 std::unique_ptr<tao::pegtl::parse_tree::node> root;
499 std::string singleNodeModifier;
500
501 try
502 {
503 root = tao::pegtl::parse_tree::parse<SIM_XSPICE_PARSER_GRAMMAR::nodeSequenceGrammar,
505 tao::pegtl::nothing,
507 for( const auto& node : root->children )
508 {
509 if( node->is_type<SIM_XSPICE_PARSER_GRAMMAR::squareBracketC>() )
510 {
511 //we want ']' to close previous ?
512 aModifiers.back().append( node->string() );
513 }
514 else
515 { //rest goes to the new singleNodeModifier
516 singleNodeModifier.append( node->string() );
517 }
518
519 if( node->is_type<SIM_XSPICE_PARSER_GRAMMAR::nodeName>() )
520 {
521 aModifiers.push_back( singleNodeModifier );
522 singleNodeModifier.erase( singleNodeModifier.begin(), singleNodeModifier.end() );
523 }
524 }
525 }
526 catch( const tao::pegtl::parse_error& e )
527 {
528 THROW_IO_ERROR( wxString::Format( _( "Error in parsing model '%s', error: '%s'" ),
529 aItem.refName, e.what() ) );
530 }
531}
533{
534 std::vector<std::string> xspicePattern;
535 NETLIST_EXPORTER_SPICE::getNodePattern( aItem, xspicePattern );
536
537 if( xspicePattern.empty() )
538 return;
539
540 if( xspicePattern.size() != aItem.pinNetNames.size() )
541 {
542 THROW_IO_ERROR( wxString::Format( _( "Error in parsing model '%s', wrong number of nodes "
543 "'?' in Sim.NodesFormat compared to connections" ),
544 aItem.refName ) );
545 return;
546 }
547
548 auto itNetNames = aItem.pinNetNames.begin();
549
550 for( std::string& pattern : xspicePattern )
551 {
552 // ngspice does not care about aditional spaces, and we make sure that "%d?" is separated
553 const std::string netName = " " + *itNetNames + " ";
554 pattern.replace( pattern.find( "?" ), 1, netName );
555 *itNetNames = pattern;
556 ++itNetNames;
557 }
558}
559
560void NETLIST_EXPORTER_SPICE::writeInclude( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions,
561 const wxString& aPath )
562{
563 // First, expand env vars, if any.
564 wxString expandedPath = ExpandEnvVarSubstitutions( aPath, &m_schematic->Prj() );
565
566 // Path may have been authored by someone on a Windows box; convert it to UNIX format
567 expandedPath.Replace( '\\', '/' );
568
569 wxString fullPath;
570
571 if( aNetlistOptions & OPTION_ADJUST_INCLUDE_PATHS )
572 {
573 // Look for the library in known search locations.
574 fullPath = ResolveFile( expandedPath, &Pgm().GetLocalEnvVariables(), &m_schematic->Prj() );
575
576 if( fullPath.IsEmpty() )
577 {
578 wxLogError( _( "Could not find library file '%s'" ), expandedPath );
579 fullPath = expandedPath;
580 }
581 else if( wxFileName::GetPathSeparator() == '\\' )
582 {
583 // Convert it to UNIX format (again) if ResolveFile() returned a Windows style path
584 fullPath.Replace( '\\', '/' );
585 }
586 }
587 else
588 {
589 fullPath = expandedPath;
590 }
591
592 aFormatter.Print( 0, ".include \"%s\"\n", TO_UTF8( fullPath ) );
593}
594
595
596void NETLIST_EXPORTER_SPICE::writeIncludes( OUTPUTFORMATTER& aFormatter, unsigned aNetlistOptions )
597{
598 for( const auto& [path, library] : m_libMgr.GetLibraries() )
599 {
600 if( dynamic_cast<const SIM_LIBRARY_SPICE*>( &library.get() ) )
601 writeInclude( aFormatter, aNetlistOptions, path );
602 }
603
604 for( const wxString& path : m_rawIncludes )
605 writeInclude( aFormatter, aNetlistOptions, path );
606}
607
608
610{
611 for( const SPICE_ITEM& item : m_items )
612 {
613 if( !item.model->IsEnabled() )
614 continue;
615
616 aFormatter.Print( 0, "%s", item.model->SpiceGenerator().ModelLine( item ).c_str() );
617 }
618}
619
620
622{
623 for( const SPICE_ITEM& item : m_items )
624 {
625 if( !item.model->IsEnabled() )
626 continue;
627
628 aFormatter.Print( 0, "%s", item.model->SpiceGenerator().ItemLine( item ).c_str() );
629 }
630}
631
632
633void NETLIST_EXPORTER_SPICE::WriteDirectives( const wxString& aSimCommand, unsigned aSimOptions,
634 OUTPUTFORMATTER& aFormatter ) const
635{
636 if( aSimOptions & OPTION_SAVE_ALL_VOLTAGES )
637 aFormatter.Print( 0, ".save all\n" );
638
639 if( aSimOptions & OPTION_SAVE_ALL_CURRENTS )
640 aFormatter.Print( 0, ".probe alli\n" );
641
642 if( aSimOptions & OPTION_SAVE_ALL_DISSIPATIONS )
643 {
644 for( const SPICE_ITEM& item : m_items )
645 {
646 // ngspice (v39) does not support power measurement for XSPICE devices
647 // XPSICE devices are marked with 'A'
648 std::string itemName = item.model->SpiceGenerator().ItemName( item );
649
650 if( ( item.model->GetPinCount() >= 2 ) && ( itemName.size() > 0 )
651 && ( itemName.c_str()[0] != 'A' ) )
652 {
653 aFormatter.Print( 0, ".probe p(%s)\n", itemName.c_str() );
654 }
655 }
656 }
657
658 auto isSimCommand =
659 []( const wxString& candidate, const wxString& dir )
660 {
661 return candidate == dir || candidate.StartsWith( dir + wxS( " " ) );
662 };
663
664 for( const wxString& directive : m_directives )
665 {
666 bool simCommand = false;
667
668 if( directive.StartsWith( "." ) )
669 {
670 wxString candidate = directive.Upper();
671
672 simCommand = ( isSimCommand( candidate, wxS( ".AC" ) )
673 || isSimCommand( candidate, wxS( ".DC" ) )
674 || isSimCommand( candidate, wxS( ".TRAN" ) )
675 || isSimCommand( candidate, wxS( ".OP" ) )
676 || isSimCommand( candidate, wxS( ".DISTO" ) )
677 || isSimCommand( candidate, wxS( ".NOISE" ) )
678 || isSimCommand( candidate, wxS( ".PZ" ) )
679 || isSimCommand( candidate, wxS( ".SENS" ) )
680 || isSimCommand( candidate, wxS( ".TF" ) ) );
681 }
682
683 if( !simCommand || ( aSimOptions & OPTION_SIM_COMMAND ) )
684 aFormatter.Print( 0, "%s\n", UTF8( directive ).c_str() );
685 }
686}
687
688
689wxString NETLIST_EXPORTER_SPICE::GenerateItemPinNetName( const wxString& aNetName,
690 int& aNcCounter ) const
691{
692 wxString netName = UnescapeString( aNetName );
693
694 ConvertToSpiceMarkup( &netName );
695
696 if( netName.IsEmpty() )
697 netName.Printf( wxS( "NC-%d" ), aNcCounter++ );
698
699 return netName;
700}
701
702
704{
705 SCH_SHEET_LIST sheets;
706
707 if( aNetlistOptions & OPTION_CUR_SHEET_AS_ROOT )
709 else
710 sheets = m_schematic->Hierarchy();
711
712 alg::delete_if( sheets,
713 [&]( const SCH_SHEET_PATH& sheet )
714 {
715 return sheet.GetExcludedFromSim();
716 } );
717
718 return sheets;
719}
720
const char * name
Definition: DXF_plotter.cpp:59
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.
SCHEMATIC * m_schematic
The schematic we're generating a netlist for.
std::vector< PIN_INFO > CreatePinList(SCH_SYMBOL *aSymbol, const SCH_SHEET_PATH &aSheetPath, bool aKeepUnconnectedPins)
Find a symbol from the DrawList and builds its pin list.
SCH_SYMBOL * findNextSymbol(EDA_ITEM *aItem, const SCH_SHEET_PATH &aSheetPath)
Check if the given symbol should be processed for netlisting.
std::set< LIB_SYMBOL *, LIB_SYMBOL_LESS_THAN > m_libParts
unique library symbols used. LIB_SYMBOL items are sorted by names
UNIQUE_STRINGS m_referencesAlreadyFound
Used for "multiple symbols per package" symbols to avoid processing a lib symbol more than once.
void readPinNetNames(SCH_SYMBOL &aSymbol, SPICE_ITEM &aItem, const std::vector< PIN_INFO > &aPins, int &aNcCounter)
void writeModels(OUTPUTFORMATTER &aFormatter)
void writeIncludes(OUTPUTFORMATTER &aFormatter, unsigned aNetlistOptions)
std::list< SPICE_ITEM > m_items
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
NETLIST_EXPORTER_SPICE(SCHEMATIC *aSchematic)
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.
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:460
static wxString GetUserCachePath()
Gets the stock (install) 3d viewer plugins path.
Definition: paths.cpp:424
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:73
virtual bool HasMessageOfSeverity(int aSeverityMask) const
Returns true if the reporter has one or more messages matching the specified severity mask.
Definition: reporter.cpp:56
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Report a string with a given severity.
Holds all the data relating to one schematic.
Definition: schematic.h:69
PROJECT & Prj() const
Return a reference to the project this schematic is part of.
Definition: schematic.h:84
SCH_SHEET_LIST Hierarchy() const
Return the full schematic flattened hierarchical sheet list.
Definition: schematic.cpp:208
SCH_SHEET_PATH & CurrentSheet() const
Definition: schematic.h:148
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition: sch_item.h:167
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) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
Definition: sch_symbol.cpp:841
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
Definition: sch_symbol.cpp:611
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:428
std::string IbisDevice(const SPICE_ITEM &aItem, SCHEMATIC *aSchematic, const wxString &aCacheDir, REPORTER &aReporter) const
virtual std::string ModelName(const SPICE_ITEM &aItem) const
bool GetExcludedFromSim() const override
Definition: symbol.h:175
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:351
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:166
Helper functions to substitute paths with environmental variables.
#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:1073
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:406
#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:403
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
@ 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:695