KiCad PCB EDA Suite
netlist_exporter_pspice.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 <dick@softplc.com>
6  * Copyright (C) 1992-2021 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 
27 #include <build_version.h>
28 #include <confirm.h>
29 
30 #include <map>
31 #include <search_stack.h>
32 
33 #include <connection_graph.h>
34 #include <kicad_string.h>
35 #include <sch_edit_frame.h>
36 #include <sch_reference_list.h>
37 #include <env_paths.h>
38 #include <pgm_base.h>
39 #include <common.h>
40 
41 #include <wx/tokenzr.h>
42 #include <wx/regex.h>
43 
44 
45 wxString NETLIST_EXPORTER_PSPICE::GetSpiceDevice( const wxString& aSymbol ) const
46 {
47  const std::list<SPICE_ITEM>& spiceItems = GetSpiceItems();
48 
49  auto it = std::find_if( spiceItems.begin(), spiceItems.end(),
50  [&]( const SPICE_ITEM& item )
51  {
52  return item.m_refName == aSymbol;
53  } );
54 
55  if( it == spiceItems.end() )
56  return wxEmptyString;
57 
58  // Prefix the device type if plain reference would result in a different device type
59  return it->m_primitive != it->m_refName[0] ? wxString( it->m_primitive + it->m_refName )
60  : it->m_refName;
61 }
62 
63 
64 bool NETLIST_EXPORTER_PSPICE::WriteNetlist( const wxString& aOutFileName, unsigned aNetlistOptions )
65 {
66  FILE_OUTPUTFORMATTER outputFile( aOutFileName, wxT( "wt" ), '\'' );
67 
68  return Format( &outputFile, aNetlistOptions );
69 }
70 
71 
73 {
74  // some chars are not accepted in netnames in spice netlists, because they are separators
75  // they are replaced an underscore or some other allowed char.
76  // Note: this is a static function
77 
78  aNetName.Replace( "(", "_" );
79  aNetName.Replace( ")", "_" );
80  aNetName.Replace( " ", "_" );
81 }
82 
83 
84 bool NETLIST_EXPORTER_PSPICE::Format( OUTPUTFORMATTER* aFormatter, unsigned aCtl )
85 {
86  // Netlist options
87  const bool useNetcodeAsNetName = false;//aCtl & NET_USE_NETCODES_AS_NETNAMES;
88 
89  // default title
90  m_title = "KiCad schematic";
91 
92  if( !ProcessNetlist( aCtl ) )
93  return false;
94 
95  aFormatter->Print( 0, ".title %s\n", TO_UTF8( m_title ) );
96 
97  // Write .include directives
98  for( const wxString& curr_lib : m_libraries )
99  {
100  // First, expand env vars, if any
101  wxString libname = ExpandEnvVarSubstitutions( curr_lib, &m_schematic->Prj() );
102  wxString full_path;
103 
104  if( ( aCtl & NET_ADJUST_INCLUDE_PATHS ) )
105  {
106  // Look for the library in known search locations
107  full_path = ResolveFile( libname, &Pgm().GetLocalEnvVariables(), &m_schematic->Prj() );
108 
109  if( full_path.IsEmpty() )
110  {
111  DisplayError( nullptr, wxString::Format( _( "Could not find library file %s." ),
112  libname ) );
113  full_path = libname;
114  }
115  }
116  else
117  {
118  full_path = libname; // just use the unaltered path
119  }
120 
121  aFormatter->Print( 0, ".include \"%s\"\n", TO_UTF8( full_path ) );
122  }
123 
124  unsigned int NC_counter = 1;
125 
126  for( const SPICE_ITEM& item : m_spiceItems )
127  {
128  if( !item.m_enabled )
129  continue;
130 
131  wxString device = GetSpiceDevice( item.m_refName );
132  aFormatter->Print( 0, "%s ", TO_UTF8( device ) );
133 
134  size_t pspiceNodes =
135  item.m_pinSequence.empty() ? item.m_pins.size() : item.m_pinSequence.size();
136 
137  for( size_t ii = 0; ii < pspiceNodes; ii++ )
138  {
139  // Use the custom order if defined, otherwise use the standard pin order as defined
140  // in the symbol.
141  size_t activePinIndex = item.m_pinSequence.empty() ? ii : item.m_pinSequence[ii];
142 
143  // Valid used Node Indexes are in the set
144  // {0,1,2,...m_item.m_pin.size()-1}
145  if( activePinIndex >= item.m_pins.size() )
146  {
147  wxASSERT_MSG( false, "Used an invalid pin number in node sequence" );
148  continue;
149  }
150 
151  wxString netName = item.m_pins[activePinIndex];
152 
153  wxASSERT( m_netMap.count( netName ) );
154 
155  if( useNetcodeAsNetName )
156  {
157  aFormatter->Print( 0, "%d ", m_netMap[netName] );
158  }
159  else
160  {
161  // Replace parenthesis with underscore to prevent parse issues with simulators
162  ReplaceForbiddenChars( netName );
163 
164  // unescape net names that contain a escaped sequence ("{slash}"):
165  netName = UnescapeString( netName );
166 
167  // Borrow LTSpice's nomenclature for unconnected nets
168  if( netName.IsEmpty() )
169  netName = wxString::Format( wxT( "NC_%.2u" ), NC_counter++ );
170 
171  aFormatter->Print( 0, "%s ", TO_UTF8( netName ) );
172  }
173  }
174 
175  aFormatter->Print( 0, "%s\n", TO_UTF8( item.m_model ) );
176  }
177 
178  // Print out all directives found in the text fields on the schematics
179  writeDirectives( aFormatter, aCtl );
180 
181  aFormatter->Print( 0, ".end\n" );
182 
183  return true;
184 }
185 
186 
188  unsigned aCtl )
189 {
190  SCH_FIELD* field = aSymbol->FindField( GetSpiceFieldName( aField ) );
191  return field ? field->GetShownText() : GetSpiceFieldDefVal( aField, aSymbol, aCtl );
192 }
193 
194 
196  unsigned aCtl )
197 {
198  switch( aField )
199  {
200  case SF_PRIMITIVE:
201  {
202  const wxString refName = aSymbol->GetField( REFERENCE_FIELD )->GetShownText();
203  return refName.GetChar( 0 );
204  }
205 
206  case SF_MODEL:
207  {
208  wxChar prim = aSymbol->GetField( REFERENCE_FIELD )->GetShownText().GetChar( 0 );
209  wxString value = aSymbol->GetField( VALUE_FIELD )->GetShownText();
210 
211  // Is it a passive component?
212  if( aCtl & NET_ADJUST_PASSIVE_VALS && ( prim == 'C' || prim == 'L' || prim == 'R' ) )
213  {
214  // Regular expression to match common formats used for passive parts description
215  // (e.g. 100k, 2k3, 1 uF)
216  wxRegEx passiveVal(
217  "^([0-9\\. ]+)([fFpPnNuUmMkKgGtT]|M(e|E)(g|G))?([fFhH]|ohm)?([-1-9 ]*)$" );
218 
219  if( passiveVal.Matches( value ) )
220  {
221  wxString prefix( passiveVal.GetMatch( value, 1 ) );
222  wxString unit( passiveVal.GetMatch( value, 2 ) );
223  wxString suffix( passiveVal.GetMatch( value, 6 ) );
224 
225  prefix.Trim(); prefix.Trim( false );
226  unit.Trim(); unit.Trim( false );
227  suffix.Trim(); suffix.Trim( false );
228 
229  // Make 'mega' units comply with the Spice expectations
230  if( unit == "M" )
231  unit = "Meg";
232 
233  value = prefix + unit + suffix;
234  }
235  }
236 
237  return value;
238  }
239 
240  case SF_ENABLED:
241  return wxString( "Y" );
242 
243  case SF_NODE_SEQUENCE:
244  {
245  wxString nodeSeq;
246  std::vector<LIB_PIN*> pins;
247 
248  wxCHECK( aSymbol->GetLibSymbolRef(), wxString() );
249  aSymbol->GetLibSymbolRef()->GetPins( pins );
250 
251  for( LIB_PIN* pin : pins )
252  nodeSeq += pin->GetNumber() + " ";
253 
254  nodeSeq.Trim();
255 
256  return nodeSeq;
257  }
258 
259  case SF_LIB_FILE:
260  // There is no default Spice library
261  return wxEmptyString;
262 
263  default:
264  wxASSERT_MSG( false, "Missing default value definition for a Spice field." );
265  return wxString( "<unknown>" );
266  }
267 }
268 
269 
271 {
272  const wxString delimiters( "{:,; }" );
273 
274  SCH_SHEET_LIST sheetList = m_schematic->GetSheets();
275  // Set of reference names, to check for duplication
276  std::set<wxString> refNames;
277 
278  m_netMap.clear();
279  m_netMap["GND"] = 0; // 0 is reserved for "GND"
280  int netIdx = 1;
281 
282  m_libraries.clear();
284  m_libParts.clear();
285 
286  UpdateDirectives( aCtl );
287 
288  for( unsigned sheet_idx = 0; sheet_idx < sheetList.size(); sheet_idx++ )
289  {
290  SCH_SHEET_PATH sheet = sheetList[sheet_idx];
291 
292  // Process symbol attributes to find Spice directives
293  for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
294  {
295  SCH_SYMBOL* symbol = findNextSymbol( item, &sheet );
296 
297  if( !symbol )
298  continue;
299 
300  CreatePinList( symbol, &sheet, true );
301  SPICE_ITEM spiceItem;
302  spiceItem.m_parent = symbol;
303 
304  // Obtain Spice fields
305  SCH_FIELD* fieldLibFile = symbol->FindField( GetSpiceFieldName( SF_LIB_FILE ) );
306  SCH_FIELD* fieldSeq = symbol->FindField( GetSpiceFieldName( SF_NODE_SEQUENCE ) );
307 
308  spiceItem.m_primitive = GetSpiceField( SF_PRIMITIVE, symbol, aCtl )[0];
309  spiceItem.m_model = GetSpiceField( SF_MODEL, symbol, aCtl );
310  spiceItem.m_refName = symbol->GetRef( &sheet );
311 
312  // Duplicate references will result in simulation errors
313  if( refNames.count( spiceItem.m_refName ) )
314  {
315  DisplayError( nullptr, _( "Multiple symbols have the same reference designator.\n"
316  "Annotation must be corrected before simulating." ) );
317  return false;
318  }
319 
320  refNames.insert( spiceItem.m_refName );
321 
322  // Check to see if symbol should be removed from Spice netlist
323  spiceItem.m_enabled = StringToBool( GetSpiceField( SF_ENABLED, symbol, aCtl ) );
324 
325  if( fieldLibFile && !fieldLibFile->GetShownText().IsEmpty() )
326  m_libraries.insert( fieldLibFile->GetShownText() );
327 
328  wxArrayString pinNames;
329 
330  // Store pin information
331  for( const PIN_INFO& pin : m_sortedSymbolPinList )
332  {
333  // Create net mapping
334  spiceItem.m_pins.push_back( pin.netName );
335  pinNames.Add( pin.num );
336 
337  if( m_netMap.count( pin.netName ) == 0 )
338  m_netMap[pin.netName] = netIdx++;
339  }
340 
341  // Check if an alternative pin sequence is available:
342  if( fieldSeq )
343  {
344  // Get the string containing the sequence of nodes:
345  const wxString& nodeSeqIndexLineStr = fieldSeq->GetShownText();
346 
347  // Verify field exists and is not empty:
348  if( !nodeSeqIndexLineStr.IsEmpty() )
349  {
350  // Get Alt Pin Name Array From User:
351  wxStringTokenizer tkz( nodeSeqIndexLineStr, delimiters );
352 
353  while( tkz.HasMoreTokens() )
354  {
355  wxString pinIndex = tkz.GetNextToken();
356  int seq;
357 
358  // Find PinName In Standard List assign Standard List Index to Name:
359  seq = pinNames.Index( pinIndex );
360 
361  if( seq != wxNOT_FOUND )
362  spiceItem.m_pinSequence.push_back( seq );
363  }
364  }
365  }
366 
367  m_spiceItems.push_back( spiceItem );
368  }
369  }
370 
371  return true;
372 }
373 
374 
376 {
377  const SCH_SHEET_LIST& sheetList = m_schematic->GetSheets();
378  wxRegEx couplingK( "^[kK][[:digit:]]*[[:space:]]+[[:alnum:]]+[[:space:]]+[[:alnum:]]+",
379  wxRE_ADVANCED );
380 
381  m_directives.clear();
382  bool controlBlock = false;
383  bool circuitBlock = false;
384 
385  for( unsigned i = 0; i < sheetList.size(); i++ )
386  {
387  for( SCH_ITEM* item : sheetList[i].LastScreen()->Items().OfType( SCH_TEXT_T ) )
388  {
389  wxString text = static_cast<SCH_TEXT*>( item )->GetShownText();
390 
391  if( text.IsEmpty() )
392  continue;
393 
394  // Analyze each line of a text field
395  wxStringTokenizer tokenizer( text, "\r\n" );
396 
397  // Flag to follow multiline directives
398  bool directiveStarted = false;
399 
400  while( tokenizer.HasMoreTokens() )
401  {
402  wxString line( tokenizer.GetNextToken() );
403 
404  // Cleanup: remove preceding and trailing white-space characters
405  line.Trim( true ).Trim( false );
406  // Convert to lower-case for parsing purposes only
407  wxString lowercaseline = line;
408  lowercaseline.MakeLower();
409 
410  // 'Include' directive stores the library file name, so it
411  // can be later resolved using a list of paths
412  if( lowercaseline.StartsWith( ".inc" ) )
413  {
414  wxString lib = line.AfterFirst( ' ' );
415 
416  if( lib.IsEmpty() )
417  continue;
418 
419  // Strip quotes if present
420  if( ( lib.StartsWith( "\"" ) && lib.EndsWith( "\"" ) )
421  || ( lib.StartsWith( "'" ) && lib.EndsWith( "'" ) ) )
422  {
423  lib = lib.Mid( 1, lib.Length() - 2 );
424  }
425 
426  m_libraries.insert( lib );
427  }
428 
429  // Store the title to be sure it appears
430  // in the first line of output
431  else if( lowercaseline.StartsWith( ".title " ) )
432  {
433  m_title = line.AfterFirst( ' ' );
434  }
435 
436  else if( line.StartsWith( '.' ) // one-line directives
437  || controlBlock // .control .. .endc block
438  || circuitBlock // .subckt .. .ends block
439  || couplingK.Matches( line ) // K## L## L## coupling constant
440  || ( directiveStarted && line.StartsWith( '+' ) ) ) // multiline directives
441  {
442  m_directives.push_back( line );
443  }
444 
445  // Handle .control .. .endc blocks
446  if( lowercaseline.IsSameAs( ".control" ) && ( !controlBlock ) )
447  controlBlock = true;
448 
449  if( lowercaseline.IsSameAs( ".endc" ) && controlBlock )
450  controlBlock = false;
451 
452  // Handle .subckt .. .ends blocks
453  if( lowercaseline.StartsWith( ".subckt" ) && ( !circuitBlock ) )
454  circuitBlock = true;
455 
456  if( lowercaseline.IsSameAs( ".ends" ) && circuitBlock )
457  circuitBlock = false;
458 
459  // Mark directive as started or continued in case it is a multi-line one
460  directiveStarted = line.StartsWith( '.' )
461  || ( directiveStarted && line.StartsWith( '+' ) );
462  }
463  }
464  }
465 }
466 
467 
468 void NETLIST_EXPORTER_PSPICE::writeDirectives( OUTPUTFORMATTER* aFormatter, unsigned aCtl ) const
469 {
470  for( const wxString& dir : m_directives )
471  {
472  aFormatter->Print( 0, "%s\n", TO_UTF8( dir ) );
473  }
474 }
475 
476 
477 // Entries in the vector below have to follow the order in SPICE_FIELD enum
478 const std::vector<wxString> NETLIST_EXPORTER_PSPICE::m_spiceFields = {
479  "Spice_Primitive",
480  "Spice_Model",
481  "Spice_Netlist_Enabled",
482  "Spice_Node_Sequence",
483  "Spice_Lib_File"
484 };
Field Reference of part, i.e. "IC21".
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:252
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
EE_TYPE OfType(KICAD_T aType) const
Definition: sch_rtree.h:216
Instances are attached to a symbol or sheet and provide a place for the symbol's value,...
Definition: sch_field.h:49
bool Format(OUTPUTFORMATTER *aFormatter, unsigned aCtl)
const SPICE_ITEM_LIST & GetSpiceItems() const
Return list of items representing schematic components in the Spice world.
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:152
SCH_FIELD * GetField(MANDATORY_FIELD_T aFieldType)
Return a mandatory field in this symbol.
Definition: sch_symbol.cpp:666
std::set< wxString > m_libraries
Map circuit nodes to net names.
std::vector< PIN_INFO > m_sortedSymbolPinList
Used to temporarily store and filter the list of pins of a schematic symbol when generating schematic...
This file is part of the common library.
Structure to represent a schematic symbol in the Spice simulation.
std::vector< wxString > m_pins
Numeric indices into m_SortedSymbolPinList.
static const wxString & GetSpiceFieldName(SPICE_FIELD aField)
Return a string used for a particular component field related to Spice simulation.
An interface used to output 8 bit text in a convenient way.
Definition: richio.h:309
bool m_enabled
Array containing Standard Pin Name.
void Clear()
Erase the record.
std::vector< wxString > m_directives
Libraries used by the simulated circuit.
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const
Return the reference for the given sheet path.
Definition: sch_symbol.cpp:432
const wxString ExpandEnvVarSubstitutions(const wxString &aString, PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:279
static bool StringToBool(const wxString &aStr)
Convert typical boolean string values (no/yes, true/false, 1/0) to a boolean value.
KIWAY Kiway & Pgm(), KFCTL_STANDALONE
The global Program "get" accessor.
Definition: single_top.cpp:106
SCH_SYMBOL * m_parent
< Schematic symbol represented by this SPICE_ITEM.
wxString GetShownText(int aDepth=0) const override
Return the string actually shown after processing of the base text.
Definition: sch_field.cpp:106
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition: sch_symbol.h:164
SCH_SYMBOL * findNextSymbol(EDA_ITEM *aItem, SCH_SHEET_PATH *aSheetPath)
Check if the given symbol should be processed for netlisting.
SCHEMATIC_IFACE * m_schematic
The schematic we're generating a netlist for.
virtual PROJECT & Prj() const =0
UNIQUE_STRINGS m_referencesAlreadyFound
Used for "multiple symbols per package" symbols to avoid processing a lib symbol more than once.
wxString m_refName
Flag to indicate whether the symbol should be used in simulation.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: macros.h:96
wxString m_title
< Spice simulation title found in the processed schematic sheet
NET_INDEX_MAP m_netMap
List of items representing schematic components in the Spice world.
Field Value of part, i.e. "3.3K".
static wxString GetSpiceFieldDefVal(SPICE_FIELD aField, SCH_SYMBOL *aSymbol, unsigned aCtl)
Retrieve the default value for a given field.
virtual void writeDirectives(OUTPUTFORMATTER *aFormatter, unsigned aCtl) const
Save the Spice directives.
void CreatePinList(SCH_SYMBOL *aSymbol, SCH_SHEET_PATH *aSheetPath, bool aKeepUnconnectedPins)
Find a symbol from the DrawList and builds its pin list in m_sortedSymbolPinList.
void UpdateDirectives(unsigned aCtl)
Update the vector of Spice directives placed in the schematics.
wxString GetSpiceDevice(const wxString &aSymbol) const
Return name of Spice device corresponding to a schematic symbol.
bool ProcessNetlist(unsigned aCtl)
Process the netlist to create net mapping and a list of SPICE_ITEMs.
#define _(s)
static void ReplaceForbiddenChars(wxString &aNetName)
Replace illegal spice net name characters with an underscore.
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
SCH_FIELD * FindField(const wxString &aFieldName, bool aIncludeDefaultFields=true)
Search for a SCH_FIELD with aFieldName.
Definition: sch_symbol.cpp:734
static wxString GetSpiceField(SPICE_FIELD aField, SCH_SYMBOL *aSymbol, unsigned aCtl)
Retrieve either the requested field value or the default value.
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, const CPTREE &aTree)
Output a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:200
bool WriteNetlist(const wxString &aOutFileName, unsigned aNetlistOptions) override
Write to specified output file.
see class PGM_BASE
Schematic symbol object.
Definition: sch_symbol.h:78
SCH_SCREEN * LastScreen()
wxString UnescapeString(const wxString &aSource)
Definition: string.cpp:222
EE_RTREE & Items()
Definition: sch_screen.h:102
The common library.
static const std::vector< wxString > m_spiceFields
wxChar m_primitive
Library model (for semiconductors and subcircuits), component value (for passive components) or volta...
Used for text file output.
Definition: richio.h:456
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:426
std::vector< int > m_pinSequence
std::set< LIB_SYMBOL *, LIB_SYMBOL_LESS_THAN > m_libParts
unique library symbols used. LIB_SYMBOL items are sorted by names
virtual SCH_SHEET_LIST GetSheets() const =0
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition: sch_item.h:197