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-2019 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 <fctsys.h>
28 #include <build_version.h>
29 #include <confirm.h>
30 
31 #include <map>
32 #include <search_stack.h>
33 
34 #include <sch_edit_frame.h>
35 #include <netlist.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 auto& spiceItems = GetSpiceItems();
46 
47  auto it = std::find_if( spiceItems.begin(), spiceItems.end(), [&]( const SPICE_ITEM& item ) {
48  return item.m_refName == aComponent;
49  } );
50 
51  if( it == spiceItems.end() )
52  return wxEmptyString;
53 
54  // Prefix the device type if plain reference would result in a different device type
55  return it->m_primitive != it->m_refName[0] ?
56  wxString( it->m_primitive + it->m_refName ) : it->m_refName;
57 }
58 
59 
60 bool NETLIST_EXPORTER_PSPICE::WriteNetlist( const wxString& aOutFileName, unsigned aNetlistOptions )
61 {
62  FILE_OUTPUTFORMATTER outputFile( aOutFileName, wxT( "wt" ), '\'' );
63 
64  return Format( &outputFile, aNetlistOptions );
65 }
66 
68 {
69  // some chars are not accepted in netnames in spice netlists, because they are separators
70  // they are replaced an underscore or some other allowed char.
71  // Note: this is a static function
72 
73  aNetName.Replace( "(", "_" );
74  aNetName.Replace( ")", "_" );
75 }
76 
77 
78 bool NETLIST_EXPORTER_PSPICE::Format( OUTPUTFORMATTER* aFormatter, unsigned aCtl )
79 {
80  // Netlist options
81  const bool useNetcodeAsNetName = false;//aCtl & NET_USE_NETCODES_AS_NETNAMES;
82 
83  // default title
84  m_title = "KiCad schematic";
85 
86  if( !ProcessNetlist( aCtl ) )
87  return false;
88 
89  aFormatter->Print( 0, ".title %s\n", (const char*) m_title.c_str() );
90 
91  // Write .include directives
92  for( const auto& lib : m_libraries )
93  {
94  wxString full_path;
95 
96  if( ( aCtl & NET_ADJUST_INCLUDE_PATHS ) )
97  {
98  // Look for the library in known search locations
99  full_path = ResolveFile( lib, &Pgm().GetLocalEnvVariables(), m_project );
100 
101  if( full_path.IsEmpty() )
102  {
103  DisplayError( NULL, wxString::Format( _( "Could not find library file %s" ), lib ) );
104  full_path = lib;
105  }
106  }
107  else
108  full_path = lib; // just use the unaltered path
109 
110  aFormatter->Print( 0, ".include \"%s\"\n", (const char*) full_path.c_str() );
111  }
112 
113  unsigned int NC_counter = 1;
114 
115  for( const auto& item : m_spiceItems )
116  {
117  if( !item.m_enabled )
118  continue;
119 
120  wxString device = GetSpiceDevice( item.m_refName );
121  aFormatter->Print( 0, "%s ", (const char*) device.c_str() );
122 
123  size_t pspiceNodes = item.m_pinSequence.empty() ? item.m_pins.size() : item.m_pinSequence.size();
124 
125  for( size_t ii = 0; ii < pspiceNodes; ii++ )
126  {
127  // Use the custom order if defined, otherwise use the standard pin order as defined in the compon
128  size_t activePinIndex = item.m_pinSequence.empty() ? ii : item.m_pinSequence[ii];
129  // Valid used Node Indexes are in the set
130  // {0,1,2,...m_item.m_pin.size()-1}
131  if( activePinIndex >= item.m_pins.size() )
132  {
133  wxASSERT_MSG( false, "Used an invalid pin number in node sequence" );
134  continue;
135  }
136 
137  NETLIST_OBJECT* pin = item.m_pins[activePinIndex];
138  assert( pin );
139  wxString netName = pin->GetNetName();
140 
141  if( useNetcodeAsNetName )
142  {
143  assert( m_netMap.count( netName ) );
144  aFormatter->Print( 0, "%d ", m_netMap[netName] );
145  }
146  else
147  {
148  sprintPinNetName( netName , wxT( "N-%.6d" ), pin, useNetcodeAsNetName );
149 
150  // Replace parenthesis with underscore to prevent parse issues with simulators
151  ReplaceForbiddenChars( netName );
152 
153  // Add quotes to nets containing slashes. This isn't added to ReplaceForbidenChars
154  // because this is only necessary for file writing; nets with slashes can be
155  // handled by ngspice after loading.
156  if( netName.Contains( "/" ) )
157  {
158  netName.Prepend( '"' );
159  netName.Append( '"' );
160  }
161 
162  // Borrow LTSpice's nomenclature for unconnected nets
163  if( netName.IsEmpty() )
164  netName = wxString::Format( wxT( "NC_%.2u" ), NC_counter++ );
165 
166  aFormatter->Print( 0, "%s ", TO_UTF8( netName ) );
167  }
168  }
169 
170  aFormatter->Print( 0, "%s\n", (const char*) item.m_model.c_str() );
171  }
172 
173  // Print out all directives found in the text fields on the schematics
174  writeDirectives( aFormatter, aCtl );
175 
176  aFormatter->Print( 0, ".end\n" );
177 
178  return true;
179 }
180 
181 
183  SCH_COMPONENT* aComponent, unsigned aCtl )
184 {
185  SCH_FIELD* field = aComponent->FindField( GetSpiceFieldName( aField ) );
186  return field ? field->GetText() : GetSpiceFieldDefVal( aField, aComponent, aCtl );
187 }
188 
189 
191  SCH_COMPONENT* aComponent, unsigned aCtl )
192 {
193  switch( aField )
194  {
195  case SF_PRIMITIVE:
196  {
197  const wxString refName = aComponent->GetField( REFERENCE )->GetText();
198  return refName.GetChar( 0 );
199  break;
200  }
201 
202  case SF_MODEL:
203  {
204  wxChar prim = aComponent->GetField( REFERENCE )->GetText().GetChar( 0 );
205  wxString value = aComponent->GetField( VALUE )->GetText();
206 
207  // Is it a passive component?
208  if( aCtl & NET_ADJUST_PASSIVE_VALS && ( prim == 'C' || prim == 'L' || prim == 'R' ) )
209  {
210  // Regular expression to match common formats used for passive parts description
211  // (e.g. 100k, 2k3, 1 uF)
212  wxRegEx passiveVal( "^([0-9\\. ]+)([fFpPnNuUmMkKgGtT]|M(e|E)(g|G))?([fFhH]|ohm)?([-1-9 ]*)$" );
213 
214  if( passiveVal.Matches( value ) )
215  {
216  wxString prefix( passiveVal.GetMatch( value, 1 ) );
217  wxString unit( passiveVal.GetMatch( value, 2 ) );
218  wxString suffix( passiveVal.GetMatch( value, 6 ) );
219 
220  prefix.Trim(); prefix.Trim( false );
221  unit.Trim(); unit.Trim( false );
222  suffix.Trim(); suffix.Trim( false );
223 
224  // Make 'mega' units comply with the Spice expectations
225  if( unit == "M" )
226  unit = "Meg";
227 
228  value = prefix + unit + suffix;
229  }
230  }
231 
232  return value;
233  break;
234  }
235 
236  case SF_ENABLED:
237  return wxString( "Y" );
238  break;
239 
240  case SF_NODE_SEQUENCE:
241  {
242  wxString nodeSeq;
243  std::vector<LIB_PIN*> pins;
244 
245  auto part = aComponent->GetPartRef().lock();
246  wxCHECK( part, wxString() );
247  part->GetPins( pins );
248 
249  for( auto pin : pins )
250  nodeSeq += pin->GetNumber() + " ";
251 
252  nodeSeq.Trim();
253 
254  return nodeSeq;
255  break;
256  }
257 
258  case SF_LIB_FILE:
259  // There is no default Spice library
260  return wxEmptyString;
261  break;
262 
263  default:
264  wxASSERT_MSG( false, "Missing default value definition for a Spice field" );
265  break;
266  }
267 
268 
269  return wxString( "<unknown>" );
270 }
271 
272 
274 {
275  const wxString delimiters( "{:,; }" );
276  SCH_SHEET_LIST sheetList( g_RootSheet );
277  // Set of reference names, to check for duplications
278  std::set<wxString> refNames;
279 
280  // Prepare list of nets generation (not used here, but...
281  for( unsigned ii = 0; ii < m_masterList->size(); ii++ )
282  m_masterList->GetItem( ii )->m_Flag = 0;
283 
284  m_netMap.clear();
285  m_netMap["GND"] = 0; // 0 is reserved for "GND"
286  int netIdx = 1;
287 
288  m_libraries.clear();
290 
291  UpdateDirectives( aCtl );
292 
293  for( unsigned sheet_idx = 0; sheet_idx < sheetList.size(); sheet_idx++ )
294  {
295  // Process component attributes to find Spice directives
296  for( EDA_ITEM* item = sheetList[sheet_idx].LastDrawList(); item; item = item->Next() )
297  {
298  SCH_COMPONENT* comp = findNextComponentAndCreatePinList( item, &sheetList[sheet_idx] );
299 
300  if( !comp )
301  break;
302 
303  item = comp;
304 
305  SPICE_ITEM spiceItem;
306  spiceItem.m_parent = comp;
307 
308  // Obtain Spice fields
309  SCH_FIELD* fieldLibFile = comp->FindField( GetSpiceFieldName( SF_LIB_FILE ) );
310  SCH_FIELD* fieldSeq = comp->FindField( GetSpiceFieldName( SF_NODE_SEQUENCE ) );
311 
312  spiceItem.m_primitive = GetSpiceField( SF_PRIMITIVE, comp, aCtl )[0];
313  spiceItem.m_model = GetSpiceField( SF_MODEL, comp, aCtl );
314  spiceItem.m_refName = comp->GetRef( &sheetList[sheet_idx] );
315 
316  // Duplicate references will result in simulation errors
317  if( refNames.count( spiceItem.m_refName ) )
318  {
319  DisplayError( NULL, wxT( "There are duplicate components. "
320  "You need to annotate schematics first." ) );
321  return false;
322  }
323 
324  refNames.insert( spiceItem.m_refName );
325 
326  // Check to see if component should be removed from Spice netlist
327  spiceItem.m_enabled = StringToBool( GetSpiceField( SF_ENABLED, comp, aCtl ) );
328 
329  if( fieldLibFile && !fieldLibFile->GetText().IsEmpty() )
330  m_libraries.insert( fieldLibFile->GetText() );
331 
332  wxArrayString pinNames;
333 
334  // Store pin information
335  for( unsigned ii = 0; ii < m_SortedComponentPinList.size(); ii++ )
336  {
338 
339  // NETLIST_EXPORTER marks removed pins by setting them to NULL
340  if( !pin )
341  continue;
342 
343  spiceItem.m_pins.push_back( pin );
344  pinNames.Add( pin->GetPinNumText() );
345 
346  // Create net mapping
347  const wxString& netName = pin->GetNetName();
348  if( m_netMap.count( netName ) == 0 )
349  m_netMap[netName] = netIdx++;
350  }
351 
352  // Check if an alternative pin sequence is available:
353  if( fieldSeq )
354  {
355  // Get the string containing the sequence of nodes:
356  const wxString nodeSeqIndexLineStr = fieldSeq->GetText();
357 
358  // Verify field exists and is not empty:
359  if( !nodeSeqIndexLineStr.IsEmpty() )
360  {
361  // Get Alt Pin Name Array From User:
362  wxStringTokenizer tkz( nodeSeqIndexLineStr, delimiters );
363 
364  while( tkz.HasMoreTokens() )
365  {
366  wxString pinIndex = tkz.GetNextToken();
367  int seq;
368 
369  // Find PinName In Standard List assign Standard List Index to Name:
370  seq = pinNames.Index( pinIndex );
371 
372  if( seq != wxNOT_FOUND )
373  spiceItem.m_pinSequence.push_back( seq );
374  }
375  }
376  }
377 
378  m_spiceItems.push_back( spiceItem );
379  }
380  }
381 
382  return true;
383 }
384 
385 
387 {
388  const SCH_SHEET_LIST& sheetList = g_RootSheet;
389  wxRegEx couplingK( "^[kK][[:digit:]]*[[:space:]]+[[:alnum:]]+[[:space:]]+[[:alnum:]]+",
390  wxRE_ADVANCED );
391 
392  m_directives.clear();
393  bool controlBlock = false;
394 
395  for( unsigned i = 0; i < sheetList.size(); i++ )
396  {
397  for( EDA_ITEM* item = sheetList[i].LastDrawList(); item; item = item->Next() )
398  {
399  if( item->Type() != SCH_TEXT_T )
400  continue;
401 
402  wxString text = static_cast<SCH_TEXT*>( item )->GetText();
403 
404  if( text.IsEmpty() )
405  continue;
406 
407  // Analyze each line of a text field
408  wxStringTokenizer tokenizer( text, "\r\n" );
409 
410  // Flag to follow multiline directives
411  bool directiveStarted = false;
412 
413  while( tokenizer.HasMoreTokens() )
414  {
415  wxString line( tokenizer.GetNextToken() );
416 
417  // Cleanup: remove preceding and trailing white-space characters
418  line.Trim( true ).Trim( false );
419  // Convert to lower-case for parsing purposes only
420  wxString lowercaseline = line;
421  lowercaseline.MakeLower();
422 
423  // 'Include' directive stores the library file name, so it
424  // can be later resolved using a list of paths
425  if( lowercaseline.StartsWith( ".inc" ) )
426  {
427  wxString lib = line.AfterFirst( ' ' );
428 
429  if( lib.IsEmpty() )
430  continue;
431 
432  // Strip quotes if present
433  if( ( lib.StartsWith( "\"" ) && lib.EndsWith( "\"" ) )
434  || ( lib.StartsWith( "'" ) && lib.EndsWith( "'" ) ) )
435  {
436  lib = lib.Mid( 1, lib.Length() - 2 );
437  }
438 
439  m_libraries.insert( lib );
440  }
441 
442  // Store the title to be sure it appears
443  // in the first line of output
444  else if( lowercaseline.StartsWith( ".title " ) )
445  {
446  m_title = line.AfterFirst( ' ' );
447  }
448 
449  // Handle .control .. .endc blocks
450  else if( lowercaseline.IsSameAs( ".control" ) && ( !controlBlock ) )
451  {
452  controlBlock = true;
453  m_directives.push_back( line );
454  }
455  else if( lowercaseline.IsSameAs( ".endc" ) && controlBlock )
456  {
457  controlBlock = false;
458  m_directives.push_back( line );
459  }
460 
461  else if( line.StartsWith( '.' ) // one-line directives
462  || controlBlock // .control .. .endc block
463  || couplingK.Matches( line ) // K## L## L## coupling constant
464  || ( directiveStarted && line.StartsWith( '+' ) ) ) // multiline directives
465  {
466  m_directives.push_back( line );
467  }
468 
469  // Mark directive as started or continued in case it is a multi-line one
470  directiveStarted = line.StartsWith( '.' )
471  || ( directiveStarted && line.StartsWith( '+' ) );
472  }
473  }
474  }
475 }
476 
477 
478 void NETLIST_EXPORTER_PSPICE::writeDirectives( OUTPUTFORMATTER* aFormatter, unsigned aCtl ) const
479 {
480  for( auto& dir : m_directives )
481  {
482  aFormatter->Print( 0, "%s\n", (const char*) dir.c_str() );
483  }
484 }
485 
486 
487 // Entries in the vector below have to follow the order in SPICE_FIELD enum
488 const std::vector<wxString> NETLIST_EXPORTER_PSPICE::m_spiceFields = {
489  "Spice_Primitive",
490  "Spice_Model",
491  "Spice_Netlist_Enabled",
492  "Spice_Node_Sequence",
493  "Spice_Lib_File"
494 };
Class SCH_SHEET_LIST.
Class SCH_FIELD instances are attached to a component and provide a place for the component's value,...
Definition: sch_field.h:52
bool Format(OUTPUTFORMATTER *aFormatter, unsigned aCtl)
std::vector< NETLIST_OBJECT * > m_pins
Array containing Standard Pin Name
SCH_FIELD * FindField(const wxString &aFieldName, bool aIncludeDefaultFields=true)
Search for a SCH_FIELD with aFieldName.
const SPICE_ITEM_LIST & GetSpiceItems() const
Returns list of items representing schematic components in the Spice world.
wxString ResolveFile(const wxString &aFileName, const ENV_VAR_MAP *aEnvVars, const PROJECT *aProject)
Searches the default paths trying to find one with the requested file.
Definition: env_paths.cpp:138
PART_REF & GetPartRef()
UNIQUE_STRINGS m_ReferencesAlreadyFound
Used for "multi parts per package" components, avoids processing a lib component more than once.
std::set< wxString > m_libraries
Libraries used by the simulated circuit
This file is part of the common library.
SCH_COMPONENT * m_parent
Schematic component represented by this SPICE_ITEM.
const wxString GetText() const override
Function GetText returns the string associated with the text object.
Definition: sch_field.cpp:105
Structure to represent a schematic component in the Spice simulation.
static void sprintPinNetName(wxString &aResult, const wxString &aNetNameFormat, NETLIST_OBJECT *aPin, bool aUseNetcodeAsNetName=false)
Function sprintPinNetName formats the net name for aPin using aNetNameFormat into aResult.
static const wxString & GetSpiceFieldName(SPICE_FIELD aField)
Returns a string used for a particular component field related to Spice simulation.
Class OUTPUTFORMATTER is an important interface (abstract class) used to output 8 bit text in a conve...
Definition: richio.h:327
bool m_enabled
Flag to indicate whether the component should be used in simulation.
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:66
void Clear()
Function Clear erases the record.
std::vector< wxString > m_directives
Spice directives found in the processed schematic sheet
static bool StringToBool(const wxString &aStr)
Convertes typical boolean string values (no/yes, true/false, 1/0) to a boolean value.
wxString m_model
Library model (for semiconductors and subcircuits), component value (for passive components) or volta...
NETLIST_OBJECT_LIST * m_masterList
Field Reference of part, i.e. "IC21".
SPICE_ITEM_LIST m_spiceItems
List of items representing schematic components in the Spice world
SCH_FIELD * GetField(int aFieldNdx) const
Returns a field in this symbol.
static wxString GetSpiceFieldDefVal(SPICE_FIELD aField, SCH_COMPONENT *aComponent, unsigned aCtl)
Retrieves the default value for a given field.
#define TO_UTF8(wxstring)
Macro TO_UTF8 converts a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: macros.h:47
wxString m_title
Spice simulation title found in the processed schematic sheet
#define VALUE
NET_INDEX_MAP m_netMap
Maps circuit nodes to net names
SCH_SHEET * g_RootSheet
Definition: eeschema.cpp:56
virtual void writeDirectives(OUTPUTFORMATTER *aFormatter, unsigned aCtl) const
Saves the Spice directives.
void UpdateDirectives(unsigned aCtl)
Updates the vector of Spice directives placed in the schematics.
SCH_COMPONENT * findNextComponentAndCreatePinList(EDA_ITEM *aItem, SCH_SHEET_PATH *aSheetPath)
Function findNextComponentAndCreatePinList finds a component from the DrawList and builds its pin lis...
bool ProcessNetlist(unsigned aCtl)
Processes the netlist to create net mapping and a list of SPICE_ITEMs.
static void ReplaceForbiddenChars(wxString &aNetName)
some chars are not accepted in netnames in spice netlists.
const wxString GetRef(const SCH_SHEET_PATH *aSheet)
Return the reference for the given sheet path.
PROJECT * m_project
Project object to fetch its settings (e.g. paths)
const wxString & GetPinNumText() const
Function GetPinNum returns a pin number in wxString form.
bool WriteNetlist(const wxString &aOutFileName, unsigned aNetlistOptions) override
Function WriteNetlist writes to specified output file.
NETLIST_OBJECTS m_SortedComponentPinList
yes ownership, connected items flat list
NETLIST_OBJECT * GetItem(unsigned aIdx) const
Acces to an item in list.
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, CPTREE &aTree)
Function Format outputs a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:205
wxString GetNetName(bool adoptTimestamp=false) const
Function GetNetName.
size_t i
Definition: json11.cpp:597
static wxString GetSpiceField(SPICE_FIELD aField, SCH_COMPONENT *aComponent, unsigned aCtl)
Retrieves either the requested field value or the default value.
Class SCH_COMPONENT describes a real schematic component.
Definition: sch_component.h:73
Class EDA_ITEM is a base class for most all the KiCad significant classes, used in schematics and boa...
Definition: base_struct.h:157
static const std::vector< wxString > m_spiceFields
wxChar m_primitive
Spice primitive type (
wxString GetSpiceDevice(const wxString &aComponent) const
Returns name of Spice device corresponding to a schematic component.
Class FILE_OUTPUTFORMATTER may be used for text file output.
Definition: richio.h:492
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Function Print formats and writes text to the output stream.
Definition: richio.cpp:404
std::vector< int > m_pinSequence
Numeric indices into m_SortedComponentPinList
void DisplayError(wxWindow *parent, const wxString &text, int displaytime)
Function DisplayError displays an error or warning message box with aMessage.
Definition: confirm.cpp:244