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