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-2016 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 <schframe.h>
35 #include <netlist.h>
36 #include <sch_reference_list.h>
37 #include <class_netlist_object.h>
38 #include <env_paths.h>
39 
40 #include <wx/tokenzr.h>
41 #include <wx/regex.h>
42 
43 bool NETLIST_EXPORTER_PSPICE::WriteNetlist( const wxString& aOutFileName, unsigned aNetlistOptions )
44 {
45  FILE_OUTPUTFORMATTER outputFile( aOutFileName, wxT( "wt" ), '\'' );
46 
47  return Format( &outputFile, aNetlistOptions );
48 }
49 
51 {
52  // some chars are not accepted in netnames in spice netlists, because they are separators
53  // they are replaced an underscore or some other allowed char.
54  // Note: this is a static function
55 
56  aNetName.Replace( "(", "_" );
57  aNetName.Replace( ")", "_" );
58 }
59 
60 
61 bool NETLIST_EXPORTER_PSPICE::Format( OUTPUTFORMATTER* aFormatter, unsigned aCtl )
62 {
63  // Netlist options
64  const bool useNetcodeAsNetName = false;//aCtl & NET_USE_NETCODES_AS_NETNAMES;
65 
66  if( !ProcessNetlist( aCtl ) )
67  return false;
68 
69  aFormatter->Print( 0, ".title KiCad schematic\n" );
70 
71  // Write .include directives
72  for( auto lib : m_libraries )
73  {
74  wxString full_path;
75 
76  if( ( aCtl & NET_ADJUST_INCLUDE_PATHS ) )
77  {
78  // Look for the library in known search locations
79  full_path = ResolveFile( lib, &Pgm().GetLocalEnvVariables(), m_project );
80 
81  if( full_path.IsEmpty() )
82  {
83  DisplayError( NULL, wxString::Format( _( "Could not find library file %s" ), lib ) );
84  full_path = lib;
85  }
86  }
87  else
88  full_path = lib; // just use the unaltered path
89 
90  aFormatter->Print( 0, ".include \"%s\"\n", (const char*) full_path.c_str() );
91  }
92 
93  for( const auto& item : m_spiceItems )
94  {
95  if( !item.m_enabled )
96  continue;
97 
98  // Save the node order
99  aFormatter->Print( 0, "%c%s ", item.m_primitive, (const char*) item.m_refName.c_str() );
100 
101  size_t pspiceNodes = item.m_pinSequence.empty() ? item.m_pins.size() : item.m_pinSequence.size();
102 
103  for( size_t ii = 0; ii < pspiceNodes; ii++ )
104  {
105  // Use the custom order if defined, otherwise use the standard pin order as defined in the compon
106  size_t activePinIndex = item.m_pinSequence.empty() ? ii : item.m_pinSequence[ii];
107  // Valid used Node Indexes are in the set
108  // {0,1,2,...m_item.m_pin.size()-1}
109  if( activePinIndex >= item.m_pins.size() )
110  {
111  wxASSERT_MSG( false, "Used an invalid pin number in node sequence" );
112  continue;
113  }
114 
115  NETLIST_OBJECT* pin = item.m_pins[activePinIndex];
116  assert( pin );
117  wxString netName = pin->GetNetName();
118 
119  if( useNetcodeAsNetName )
120  {
121  assert( m_netMap.count( netName ) );
122  aFormatter->Print( 0, "%d ", m_netMap[netName] );
123  }
124  else
125  {
126  sprintPinNetName( netName , wxT( "N-%.6d" ), pin, useNetcodeAsNetName );
127 
128  // Replace parenthesis with underscore to prevent parse issues with simulators
129  ReplaceForbiddenChars( netName );
130 
131  if( netName.IsEmpty() )
132  netName = wxT( "?" );
133 
134  aFormatter->Print( 0, "%s ", TO_UTF8( netName ) );
135  }
136  }
137 
138  aFormatter->Print( 0, "%s\n", (const char*) item.m_model.c_str() );
139  }
140 
141  // Print out all directives found in the text fields on the schematics
142  writeDirectives( aFormatter, aCtl );
143 
144  aFormatter->Print( 0, ".end\n" );
145 
146  return true;
147 }
148 
149 
151  SCH_COMPONENT* aComponent, unsigned aCtl )
152 {
153  SCH_FIELD* field = aComponent->FindField( GetSpiceFieldName( aField ) );
154  return field ? field->GetText() : GetSpiceFieldDefVal( aField, aComponent, aCtl );
155 }
156 
157 
159  SCH_COMPONENT* aComponent, unsigned aCtl )
160 {
161  switch( aField )
162  {
163  case SF_PRIMITIVE:
164  {
165  const wxString& refName = aComponent->GetField( REFERENCE )->GetText();
166  return refName.GetChar( 0 );
167  break;
168  }
169 
170  case SF_MODEL:
171  {
172  wxChar prim = aComponent->GetField( REFERENCE )->GetText().GetChar( 0 );
173  wxString value = aComponent->GetField( VALUE )->GetText();
174 
175  // Is it a passive component?
176  if( aCtl & NET_ADJUST_PASSIVE_VALS && ( prim == 'C' || prim == 'L' || prim == 'R' ) )
177  {
178  // Regular expression to match common formats used for passive parts description
179  // (e.g. 100k, 2k3, 1 uF)
180  wxRegEx passiveVal( "^([0-9\\. ]+)([fFpPnNuUmMkKgGtT]|M(e|E)(g|G))?([fFhH]|ohm)?([-1-9 ]*)$" );
181 
182  if( passiveVal.Matches( value ) )
183  {
184  wxString prefix( passiveVal.GetMatch( value, 1 ) );
185  wxString unit( passiveVal.GetMatch( value, 2 ) );
186  wxString suffix( passiveVal.GetMatch( value, 6 ) );
187 
188  prefix.Trim(); prefix.Trim( false );
189  unit.Trim(); unit.Trim( false );
190  suffix.Trim(); suffix.Trim( false );
191 
192  // Make 'mega' units comply with the Spice expectations
193  if( unit == "M" )
194  unit = "Meg";
195 
196  value = prefix + unit + suffix;
197  }
198  }
199 
200  return value;
201  break;
202  }
203 
204  case SF_ENABLED:
205  return wxString( "Y" );
206  break;
207 
208  case SF_NODE_SEQUENCE:
209  {
210  wxString nodeSeq;
211  std::vector<LIB_PIN*> pins;
212 
213  aComponent->GetPins( pins );
214 
215  for( auto pin : pins )
216  nodeSeq += pin->GetNumber() + " ";
217 
218  nodeSeq.Trim();
219 
220  return nodeSeq;
221  break;
222  }
223 
224  case SF_LIB_FILE:
225  // There is no default Spice library
226  return wxEmptyString;
227  break;
228 
229  default:
230  wxASSERT_MSG( false, "Missing default value definition for a Spice field" );
231  break;
232  }
233 
234 
235  return wxString( "<unknown>" );
236 }
237 
238 
240 {
241  const wxString delimiters( "{:,; }" );
242  SCH_SHEET_LIST sheetList( g_RootSheet );
243  // Set of reference names, to check for duplications
244  std::set<wxString> refNames;
245 
246  // Prepare list of nets generation (not used here, but...
247  for( unsigned ii = 0; ii < m_masterList->size(); ii++ )
248  m_masterList->GetItem( ii )->m_Flag = 0;
249 
250  m_netMap.clear();
251  m_netMap["GND"] = 0; // 0 is reserved for "GND"
252  int netIdx = 1;
253 
254  m_libraries.clear();
256 
257  UpdateDirectives( aCtl );
258 
259  for( unsigned sheet_idx = 0; sheet_idx < sheetList.size(); sheet_idx++ )
260  {
261  // Process component attributes to find Spice directives
262  for( EDA_ITEM* item = sheetList[sheet_idx].LastDrawList(); item; item = item->Next() )
263  {
264  SCH_COMPONENT* comp = findNextComponentAndCreatePinList( item, &sheetList[sheet_idx] );
265 
266  if( !comp )
267  break;
268 
269  item = comp;
270 
271  SPICE_ITEM spiceItem;
272  spiceItem.m_parent = comp;
273 
274  // Obtain Spice fields
275  SCH_FIELD* fieldLibFile = comp->FindField( GetSpiceFieldName( SF_LIB_FILE ) );
276  SCH_FIELD* fieldSeq = comp->FindField( GetSpiceFieldName( SF_NODE_SEQUENCE ) );
277 
278  spiceItem.m_primitive = GetSpiceField( SF_PRIMITIVE, comp, aCtl )[0];
279  spiceItem.m_model = GetSpiceField( SF_MODEL, comp, aCtl );
280  spiceItem.m_refName = comp->GetRef( &sheetList[sheet_idx] );
281 
282  // Duplicate references will result in simulation errors
283  if( refNames.count( spiceItem.m_refName ) )
284  {
285  DisplayError( NULL, wxT( "There are duplicate components. "
286  "You need to annotate schematics first." ) );
287  return false;
288  }
289 
290  refNames.insert( spiceItem.m_refName );
291 
292  // Check to see if component should be removed from Spice netlist
293  spiceItem.m_enabled = StringToBool( GetSpiceField( SF_ENABLED, comp, aCtl ) );
294 
295  if( fieldLibFile && !fieldLibFile->GetText().IsEmpty() )
296  m_libraries.insert( fieldLibFile->GetText() );
297 
298  wxArrayString pinNames;
299 
300  // Store pin information
301  for( unsigned ii = 0; ii < m_SortedComponentPinList.size(); ii++ )
302  {
304 
305  // NETLIST_EXPORTER marks removed pins by setting them to NULL
306  if( !pin )
307  continue;
308 
309  spiceItem.m_pins.push_back( pin );
310  pinNames.Add( pin->GetPinNumText() );
311 
312  // Create net mapping
313  const wxString& netName = pin->GetNetName();
314  if( m_netMap.count( netName ) == 0 )
315  m_netMap[netName] = netIdx++;
316  }
317 
318  // Check if an alternative pin sequence is available:
319  if( fieldSeq )
320  {
321  // Get the string containing the sequence of nodes:
322  wxString nodeSeqIndexLineStr = fieldSeq->GetText();
323 
324  // Verify field exists and is not empty:
325  if( !nodeSeqIndexLineStr.IsEmpty() )
326  {
327  // Get Alt Pin Name Array From User:
328  wxStringTokenizer tkz( nodeSeqIndexLineStr, delimiters );
329 
330  while( tkz.HasMoreTokens() )
331  {
332  wxString pinIndex = tkz.GetNextToken();
333  int seq;
334 
335  // Find PinName In Standard List assign Standard List Index to Name:
336  seq = pinNames.Index( pinIndex );
337 
338  if( seq != wxNOT_FOUND )
339  spiceItem.m_pinSequence.push_back( seq );
340  }
341  }
342  }
343 
344  m_spiceItems.push_back( spiceItem );
345  }
346  }
347 
348  return true;
349 }
350 
351 
353 {
354  const SCH_SHEET_LIST& sheetList = g_RootSheet;
355 
356  m_directives.clear();
357 
358  for( unsigned i = 0; i < sheetList.size(); i++ )
359  {
360  for( EDA_ITEM* item = sheetList[i].LastDrawList(); item; item = item->Next() )
361  {
362  if( item->Type() != SCH_TEXT_T )
363  continue;
364 
365  wxString text = static_cast<SCH_TEXT*>( item )->GetText();
366 
367  if( text.IsEmpty() )
368  continue;
369 
370  if( text.GetChar( 0 ) == '.' )
371  {
372  wxStringTokenizer tokenizer( text, "\r\n" );
373 
374  while( tokenizer.HasMoreTokens() )
375  {
376  wxString directive( tokenizer.GetNextToken() );
377 
378  if( directive.StartsWith( ".inc" ) )
379  {
380  wxString lib = directive.AfterFirst( ' ' );
381 
382  if( !lib.IsEmpty() )
383  m_libraries.insert( lib );
384  }
385  else
386  {
387  m_directives.push_back( directive );
388  }
389  }
390  }
391  }
392  }
393 }
394 
395 
396 void NETLIST_EXPORTER_PSPICE::writeDirectives( OUTPUTFORMATTER* aFormatter, unsigned aCtl ) const
397 {
398  for( auto& dir : m_directives )
399  {
400  aFormatter->Print( 0, "%s\n", (const char*) dir.c_str() );
401  }
402 }
403 
404 
405 // Entries in the vector below have to follow the order in SPICE_FIELD enum
406 const std::vector<wxString> NETLIST_EXPORTER_PSPICE::m_spiceFields = {
407  "Spice_Primitive",
408  "Spice_Model",
409  "Spice_Netlist_Enabled",
410  "Spice_Node_Sequence",
411  "Spice_Lib_File"
412 };
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:56
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.
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:129
wxString GetNetName(bool adoptTimestamp=false) const
Function GetNetName.
const wxString & GetPinNumText() const
Function GetPinNum returns a pin number in wxString form.
UNIQUE_STRINGS m_ReferencesAlreadyFound
Used for "multi parts per package" components, avoids processing a lib component more than once...
NETLIST_OBJECT * GetItem(unsigned aIdx) const
Acces to an item in list.
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.
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:65
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
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
NET_INDEX_MAP m_netMap
Maps circuit nodes to net names
SCH_SHEET * g_RootSheet
Definition: eeschema.cpp:55
SCH_FIELD * GetField(int aFieldNdx) const
Returns a field in this symbol.
const wxString & GetText() const
Function GetText returns the string associated with the text object.
Definition: eda_text.h:130
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.
wxString GetText(GRAPHIC_PINSHAPE shape)
Definition: pin_shape.cpp:33
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)
virtual void writeDirectives(OUTPUTFORMATTER *aFormatter, unsigned aCtl) const
Saves the Spice directives.
bool WriteNetlist(const wxString &aOutFileName, unsigned aNetlistOptions) override
Function WriteNetlist writes to specified output file.
Definition of the NETLIST_OBJECT class.
Field Value of part, i.e. "3.3K".
NETLIST_OBJECTS m_SortedComponentPinList
yes ownership, connected items flat list
void GetPins(std::vector< LIB_PIN * > &aPinsList)
Populate a vector with all the pins.
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
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:69
Class EDA_ITEM is a base class for most all the KiCad significant classes, used in schematics and boa...
Definition: base_struct.h:165
static const std::vector< wxString > m_spiceFields
wxChar m_primitive
Spice primitive type (
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:73