KiCad PCB EDA Suite
NETLIST_EXPORTER_PSPICE_SIM Class Reference

Special netlist exporter flavor that allows one to override simulation commands. More...

#include <netlist_exporter_pspice_sim.h>

Inheritance diagram for NETLIST_EXPORTER_PSPICE_SIM:
NETLIST_EXPORTER_PSPICE NETLIST_EXPORTER

Public Types

typedef std::list< SPICE_ITEMSPICE_ITEM_LIST
 
typedef std::map< wxString, int > NET_INDEX_MAP
 

Net name to circuit node number mapping

More...
 

Public Member Functions

 NETLIST_EXPORTER_PSPICE_SIM (SCHEMATIC *aSchematic)
 
wxString ComponentToVector (const wxString &aName, SIM_PLOT_TYPE aType, const wxString &aParam=wxEmptyString) const
 Returns name of Spice dataset for a specific plot. More...
 
SIM_PLOT_TYPE VectorToSignal (const std::string &aVector, wxString &aSignal) const
 Returns name of Spice dataset for a specific plot. More...
 
void SetSimCommand (const wxString &aCmd)
 Overrides the simulation command directive. More...
 
const wxString & GetSimCommand () const
 Returns the simulation command directive. More...
 
void ClearSimCommand ()
 Clears the simulation command directive. More...
 
wxString GetUsedSimCommand ()
 Returns the command directive that is in use (either from the sheet or from m_simCommand. More...
 
SIM_TYPE GetSimType ()
 Returns simulation type basing on the simulation command directives. More...
 
wxString GetSheetSimCommand ()
 Returns simulation command directives placed in schematic sheets (if any). More...
 
bool ParseDCCommand (const wxString &aCmd, SPICE_DC_PARAMS *aSource1, SPICE_DC_PARAMS *aSource2)
 Parses a two-source .dc command directive into its components. More...
 
const SPICE_ITEM_LISTGetSpiceItems () const
 Returns list of items representing schematic components in the Spice world. More...
 
wxString GetSpiceDevice (const wxString &aComponent) const
 Returns name of Spice device corresponding to a schematic component. More...
 
bool WriteNetlist (const wxString &aOutFileName, unsigned aNetlistOptions) override
 Function WriteNetlist writes to specified output file. More...
 
bool Format (OUTPUTFORMATTER *aFormatter, unsigned aCtl)
 

More...
 
bool ProcessNetlist (unsigned aCtl)
 Processes the netlist to create net mapping and a list of SPICE_ITEMs. More...
 
const NET_INDEX_MAPGetNetIndexMap () const
 Returns a map of circuit nodes to net names. More...
 
void UpdateDirectives (unsigned aCtl)
 Updates the vector of Spice directives placed in the schematics. More...
 
const std::vector< wxString > GetDirectives () const
 Returnss a vector of Spice directives found in the schematics. More...
 

Static Public Member Functions

static const std::vector< wxString > & GetCurrents (SPICE_PRIMITIVE aPrimitive)
 Returns a list of currents that can be probed in a Spice primitive. More...
 
static bool IsSimCommand (const wxString &aCmd)
 Determines if a directive is a simulation command. More...
 
static SIM_TYPE CommandToSimType (const wxString &aCmd)
 Returns simulation type basing on a simulation command directive. More...
 
static void ReplaceForbiddenChars (wxString &aNetName)
 some chars are not accepted in netnames in spice netlists. More...
 
static const std::vector< wxString > & GetSpiceFields ()
 Returns a vector of component field names related to Spice simulation. More...
 
static const wxString & GetSpiceFieldName (SPICE_FIELD aField)
 Returns a string used for a particular component field related to Spice simulation. More...
 
static wxString GetSpiceField (SPICE_FIELD aField, SCH_COMPONENT *aComponent, unsigned aCtl)
 Retrieves either the requested field value or the default value. More...
 
static wxString GetSpiceFieldDefVal (SPICE_FIELD aField, SCH_COMPONENT *aComponent, unsigned aCtl)
 Retrieves the default value for a given field. More...
 
static bool StringToBool (const wxString &aStr)
 Convertes typical boolean string values (no/yes, true/false, 1/0) to a boolean value. More...
 
static wxString MakeCommandLine (const wxString &aFormatString, const wxString &aNetlistFile, const wxString &aFinalFile, const wxString &aProjectDirectory)
 Function MakeCommandLine builds up a string that describes a command line for executing a child process. More...
 

Protected Member Functions

void writeDirectives (OUTPUTFORMATTER *aFormatter, unsigned aCtl) const override
 Saves the Spice directives. More...
 
void CreatePinList (SCH_COMPONENT *aItem, SCH_SHEET_PATH *aSheetPath)
 Function findNextComponentAndCreatePinList finds a component from the DrawList and builds its pin list in m_SortedComponentPinList. More...
 
SCH_COMPONENTfindNextComponent (EDA_ITEM *aItem, SCH_SHEET_PATH *aSheetPath)
 Checks if the given component should be processed for netlisting. More...
 
void eraseDuplicatePins ()
 Function eraseDuplicatePins erase duplicate Pins from m_SortedComponentPinList (i.e. More...
 
void findAllUnitsOfComponent (SCH_COMPONENT *aComponent, LIB_PART *aEntry, SCH_SHEET_PATH *aSheetPath)
 Function findAllUnitsOfComponent is used for "multiple parts per package" components. More...
 

Protected Attributes

std::vector< PIN_INFOm_SortedComponentPinList
 Used to temporarily store and filter the list of pins of a schematic component when generating schematic component data in netlist (comp section). More...
 
UNIQUE_STRINGS m_ReferencesAlreadyFound
 Used for "multi parts per package" components, avoids processing a lib component more than once. More...
 
std::set< LIB_PART *, LIB_PART_LESS_THANm_LibParts
 unique library parts used. More...
 
SCHEMATICm_schematic
 The schematic we're generating a netlist for. More...
 

Private Attributes

wxString m_simCommand
 

Custom simulation command (has priority over the schematic sheet simulation commands)

More...
 

Detailed Description

Special netlist exporter flavor that allows one to override simulation commands.

Definition at line 46 of file netlist_exporter_pspice_sim.h.

Member Typedef Documentation

◆ NET_INDEX_MAP

typedef std::map<wxString, int> NETLIST_EXPORTER_PSPICE::NET_INDEX_MAP
inherited

Net name to circuit node number mapping

Definition at line 116 of file netlist_exporter_pspice.h.

◆ SPICE_ITEM_LIST

Definition at line 113 of file netlist_exporter_pspice.h.

Constructor & Destructor Documentation

◆ NETLIST_EXPORTER_PSPICE_SIM()

NETLIST_EXPORTER_PSPICE_SIM::NETLIST_EXPORTER_PSPICE_SIM ( SCHEMATIC aSchematic)
inline

Definition at line 49 of file netlist_exporter_pspice_sim.h.

49  :
50  NETLIST_EXPORTER_PSPICE( aSchematic )
51  {
52  }
NETLIST_EXPORTER_PSPICE(SCHEMATIC *aSchematic)

Member Function Documentation

◆ ClearSimCommand()

void NETLIST_EXPORTER_PSPICE_SIM::ClearSimCommand ( )
inline

Clears the simulation command directive.

Definition at line 99 of file netlist_exporter_pspice_sim.h.

100  {
101  m_simCommand.Clear();
102  }
wxString m_simCommand
Custom simulation command (has priority over the schematic sheet simulation commands)

References m_simCommand.

◆ CommandToSimType()

SIM_TYPE NETLIST_EXPORTER_PSPICE_SIM::CommandToSimType ( const wxString &  aCmd)
static

Returns simulation type basing on a simulation command directive.

Definition at line 166 of file netlist_exporter_pspice_sim.cpp.

167 {
168  const std::vector<std::pair<wxString, SIM_TYPE>> simCmds = {
169  { "^.ac\\M.*", ST_AC },
170  { "^.dc\\M.*", ST_DC },
171  { "^.tran\\M.*", ST_TRANSIENT },
172  { "^.op\\M.*", ST_OP },
173  { "^.disto\\M.*", ST_DISTORTION },
174  { "^.noise\\M.*", ST_NOISE },
175  { "^.pz\\M.*", ST_POLE_ZERO },
176  { "^.sens\\M.*", ST_SENSITIVITY },
177  { "^.tf\\M.*", ST_TRANS_FUNC } };
178  wxRegEx simCmd;
179 
180  for( const auto& c : simCmds )
181  {
182  simCmd.Compile( c.first, wxRE_ADVANCED | wxRE_NOSUB | wxRE_ICASE );
183 
184  if( simCmd.Matches( aCmd ) )
185  return c.second;
186  }
187 
188  return ST_UNKNOWN;
189 }

References ST_AC, ST_DC, ST_DISTORTION, ST_NOISE, ST_OP, ST_POLE_ZERO, ST_SENSITIVITY, ST_TRANS_FUNC, ST_TRANSIENT, and ST_UNKNOWN.

Referenced by BOOST_AUTO_TEST_CASE(), GetSimType(), IsSimCommand(), and SIM_PLOT_FRAME::onSettings().

◆ ComponentToVector()

wxString NETLIST_EXPORTER_PSPICE_SIM::ComponentToVector ( const wxString &  aName,
SIM_PLOT_TYPE  aType,
const wxString &  aParam = wxEmptyString 
) const

Returns name of Spice dataset for a specific plot.

Parameters
aNameis name of the measured net or device
aTypedescribes the type of expected plot
aParamis an optional parameter for devices, if absent it will return current (only for passive devices).
Returns
Empty string if query is invalid, otherwise a plot name that can be requested from the simulator.

Definition at line 29 of file netlist_exporter_pspice_sim.cpp.

31 {
32  wxString res;
33 
34  // Some of the flags should exclude mutually
35  assert( ( ( aType & SPT_VOLTAGE ) == 0 ) != ( ( aType & SPT_CURRENT ) == 0 ) );
36  assert( ( ( aType & SPT_AC_PHASE ) == 0 ) || ( ( aType & SPT_AC_MAG ) == 0 ) );
37 
38  if( aType & SPT_VOLTAGE )
39  {
40  // netnames are escaped (can contain "{slash}" for '/') Unscape them:
41  wxString spicenet = UnescapeString( aName );
42 
43  // Spice netlist netnames does not accept some chars, which are replaced
44  // by eeschema netlist generator.
45  // Replace these forbidden chars to find the actual spice net name
47 
48  return wxString::Format( "V(%s)", spicenet );
49  }
50 
51  else if( aType & SPT_CURRENT )
52  {
53  wxString device = GetSpiceDevice( aName ).Lower();
54  wxString param = aParam.Lower();
55 
56  if( device[0] == 'x' )
57  {
58  return "current probe of .subckt not yet implemented";
59  }
60  else
61  {
62  return wxString::Format( "@%s[%s]",
63  device,
64  param.IsEmpty() ? "i" : param );
65  }
66  }
67 
68  return res;
69 }
static void ReplaceForbiddenChars(wxString &aNetName)
some chars are not accepted in netnames in spice netlists.
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 UnescapeString(const wxString &aSource)
Definition: string.cpp:125
wxString GetSpiceDevice(const wxString &aComponent) const
Returns name of Spice device corresponding to a schematic component.

References Format(), NETLIST_EXPORTER_PSPICE::GetSpiceDevice(), NETLIST_EXPORTER_PSPICE::ReplaceForbiddenChars(), SPT_AC_MAG, SPT_AC_PHASE, SPT_CURRENT, SPT_VOLTAGE, and UnescapeString().

Referenced by writeDirectives().

◆ CreatePinList()

void NETLIST_EXPORTER::CreatePinList ( SCH_COMPONENT aItem,
SCH_SHEET_PATH aSheetPath 
)
protectedinherited

Function findNextComponentAndCreatePinList finds a component from the DrawList and builds its pin list in m_SortedComponentPinList.

This list is sorted by pin num. the component is the next actual component after aItem (power symbols and virtual components that have their reference starting by '#'are skipped).

Definition at line 124 of file netlist_exporter.cpp.

125 {
126  wxString ref( comp->GetRef( aSheetPath ) );
127 
128  // Power symbols and other components which have the reference starting
129  // with "#" are not included in netlist (pseudo or virtual components)
130 
131  if( ref[0] == wxChar( '#' ) )
132  return;
133 
134  // if( Component->m_FlagControlMulti == 1 )
135  // continue; /* yes */
136  // removed because with multiple instances of one schematic
137  // (several sheets pointing to 1 screen), this will be erroneously be
138  // toggled.
139 
140  if( !comp->GetPartRef() )
141  return;
142 
143  m_SortedComponentPinList.clear();
144 
145  // If component is a "multi parts per package" type
146  if( comp->GetPartRef()->GetUnitCount() > 1 )
147  {
148  // Collect all pins for this reference designator by searching
149  // the entire design for other parts with the same reference designator.
150  // This is only done once, it would be too expensive otherwise.
151  findAllUnitsOfComponent( comp, comp->GetPartRef().get(), aSheetPath );
152  }
153 
154  else // entry->GetUnitCount() <= 1 means one part per package
155  {
156  for( const auto& pin : comp->GetSchPins( aSheetPath ) )
157  {
158  if( auto conn = pin->Connection( *aSheetPath ) )
159  {
160  const wxString& netName = conn->Name();
161 
162  // Skip unconnected pins
163  CONNECTION_SUBGRAPH* sg =
164  m_schematic->ConnectionGraph()->FindSubgraphByName( netName, *aSheetPath );
165 
166  if( !sg || sg->m_no_connect || sg->m_items.size() < 2 )
167  continue;
168 
169  m_SortedComponentPinList.emplace_back( pin->GetNumber(), netName );
170  }
171  }
172  }
173 
174  // Sort pins in m_SortedComponentPinList by pin number
176 
177  // Remove duplicate Pins in m_SortedComponentPinList
179 
180  // record the usage of this library component entry.
181  m_LibParts.insert( comp->GetPartRef().get() ); // rejects non-unique pointers
182 }
CONNECTION_SUBGRAPH * FindSubgraphByName(const wxString &aNetName, const SCH_SHEET_PATH &aPath)
Returns the subgraph for a given net name on a given sheet.
SCHEMATIC * m_schematic
The schematic we're generating a netlist for.
CONNECTION_GRAPH * ConnectionGraph() const
Definition: schematic.h:132
void findAllUnitsOfComponent(SCH_COMPONENT *aComponent, LIB_PART *aEntry, SCH_SHEET_PATH *aSheetPath)
Function findAllUnitsOfComponent is used for "multiple parts per package" components.
A subgraph is a set of items that are electrically connected on a single sheet.
std::set< LIB_PART *, LIB_PART_LESS_THAN > m_LibParts
unique library parts used.
std::vector< SCH_ITEM * > m_items
std::vector< PIN_INFO > m_SortedComponentPinList
Used to temporarily store and filter the list of pins of a schematic component when generating schema...
static bool sortPinsByNum(PIN_INFO &aPin1, PIN_INFO &aPin2)
Comparison routine for sorting by pin numbers.
SCH_ITEM * m_no_connect
No-connect item in graph, if any.
void eraseDuplicatePins()
Function eraseDuplicatePins erase duplicate Pins from m_SortedComponentPinList (i....

References SCHEMATIC::ConnectionGraph(), NETLIST_EXPORTER::eraseDuplicatePins(), NETLIST_EXPORTER::findAllUnitsOfComponent(), CONNECTION_GRAPH::FindSubgraphByName(), SCH_COMPONENT::GetPartRef(), SCH_COMPONENT::GetRef(), SCH_COMPONENT::GetSchPins(), CONNECTION_SUBGRAPH::m_items, NETLIST_EXPORTER::m_LibParts, CONNECTION_SUBGRAPH::m_no_connect, NETLIST_EXPORTER::m_schematic, NETLIST_EXPORTER::m_SortedComponentPinList, and sortPinsByNum().

Referenced by NETLIST_EXPORTER_PSPICE::ProcessNetlist(), and NETLIST_EXPORTER_ORCADPCB2::WriteNetlist().

◆ eraseDuplicatePins()

void NETLIST_EXPORTER::eraseDuplicatePins ( )
protectedinherited

Function eraseDuplicatePins erase duplicate Pins from m_SortedComponentPinList (i.e.

set pointer in this list to NULL). (This is a list of pins found in the whole schematic, for a single component.) These duplicate pins were put in list because some pins (powers... ) are found more than one time when we have a multiple parts per package component. For instance, a 74ls00 has 4 parts, and therefore the VCC pin and GND pin appears 4 times in the list. Note: this list MUST be sorted by pin number (.m_PinNum member value) Also set the m_Flag member of "removed" NETLIST_OBJECT pin item to 1

Definition at line 185 of file netlist_exporter.cpp.

186 {
187  for( unsigned ii = 0; ii < m_SortedComponentPinList.size(); ii++ )
188  {
189  if( m_SortedComponentPinList[ii].num.empty() ) /* already deleted */
190  continue;
191 
192  /* Search for duplicated pins
193  * If found, remove duplicates. The priority is to keep connected pins
194  * and remove unconnected
195  * - So this allows (for instance when using multi op amps per package
196  * - to connect only one op amp to power
197  * Because the pin list is sorted by m_PinNum value, duplicated pins
198  * are necessary successive in list
199  */
200  int idxref = ii;
201 
202  for( unsigned jj = ii + 1; jj < m_SortedComponentPinList.size(); jj++ )
203  {
204  if( m_SortedComponentPinList[jj].num.empty() ) // Already removed
205  continue;
206 
207  // if other pin num, stop search,
208  // because all pins having the same number are consecutive in list.
209  if( m_SortedComponentPinList[idxref].num != m_SortedComponentPinList[jj].num )
210  break;
211 
212  m_SortedComponentPinList[jj].num.clear();
213  }
214  }
215 }
std::vector< PIN_INFO > m_SortedComponentPinList
Used to temporarily store and filter the list of pins of a schematic component when generating schema...

References NETLIST_EXPORTER::m_SortedComponentPinList.

Referenced by NETLIST_EXPORTER::CreatePinList().

◆ findAllUnitsOfComponent()

void NETLIST_EXPORTER::findAllUnitsOfComponent ( SCH_COMPONENT aComponent,
LIB_PART aEntry,
SCH_SHEET_PATH aSheetPath 
)
protectedinherited

Function findAllUnitsOfComponent is used for "multiple parts per package" components.

Search the entire design for all units of aComponent based on matching reference designator, and for each unit, add all its pins to the temporary sorted pin list, m_SortedComponentPinList.

Definition at line 218 of file netlist_exporter.cpp.

220 {
221  wxString ref = aComponent->GetRef( aSheetPath );
222  wxString ref2;
223 
224  SCH_SHEET_LIST sheetList = m_schematic->GetSheets();
225 
226  for( unsigned i = 0; i < sheetList.size(); i++ )
227  {
228  for( auto item : sheetList[i].LastScreen()->Items().OfType( SCH_COMPONENT_T ) )
229  {
230  SCH_COMPONENT* comp2 = static_cast<SCH_COMPONENT*>( item );
231 
232  ref2 = comp2->GetRef( &sheetList[i] );
233 
234  if( ref2.CmpNoCase( ref ) != 0 )
235  continue;
236 
237  for( const auto& pin : comp2->GetSchPins( aSheetPath ) )
238  {
239  if( auto conn = pin->Connection( *aSheetPath ) )
240  {
241  const wxString& netName = conn->Name();
242 
243  // Skip unconnected pins
245  netName, *aSheetPath );
246 
247  if( !sg || sg->m_no_connect || sg->m_items.size() < 2 )
248  continue;
249 
250  m_SortedComponentPinList.emplace_back( pin->GetNumber(), netName );
251  }
252  }
253  }
254  }
255 }
CONNECTION_SUBGRAPH * FindSubgraphByName(const wxString &aNetName, const SCH_SHEET_PATH &aPath)
Returns the subgraph for a given net name on a given sheet.
SCH_SHEET_LIST.
SCH_SHEET_LIST GetSheets() const
Builds and returns an updated schematic hierarchy TODO: can this be cached?
Definition: schematic.h:92
SCHEMATIC * m_schematic
The schematic we're generating a netlist for.
CONNECTION_GRAPH * ConnectionGraph() const
Definition: schematic.h:132
A subgraph is a set of items that are electrically connected on a single sheet.
std::vector< SCH_ITEM * > m_items
std::vector< PIN_INFO > m_SortedComponentPinList
Used to temporarily store and filter the list of pins of a schematic component when generating schema...
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false)
Return the reference for the given sheet path.
Schematic symbol object.
Definition: sch_component.h:88
SCH_ITEM * m_no_connect
No-connect item in graph, if any.
SCH_PIN_PTRS GetSchPins(const SCH_SHEET_PATH *aSheet=nullptr) const
Retrieves a list of the SCH_PINs for the given sheet path.

References SCHEMATIC::ConnectionGraph(), CONNECTION_GRAPH::FindSubgraphByName(), SCH_COMPONENT::GetRef(), SCH_COMPONENT::GetSchPins(), SCHEMATIC::GetSheets(), CONNECTION_SUBGRAPH::m_items, CONNECTION_SUBGRAPH::m_no_connect, NETLIST_EXPORTER::m_schematic, NETLIST_EXPORTER::m_SortedComponentPinList, and SCH_COMPONENT_T.

Referenced by NETLIST_EXPORTER::CreatePinList().

◆ findNextComponent()

SCH_COMPONENT * NETLIST_EXPORTER::findNextComponent ( EDA_ITEM aItem,
SCH_SHEET_PATH aSheetPath 
)
protectedinherited

Checks if the given component should be processed for netlisting.

Prevents processing multi-unit components more than once, etc.

Parameters
aItemis a component to check
aSheetPathis the sheet to check the component for
Returns
the component if it should be processed, or nullptr

Definition at line 75 of file netlist_exporter.cpp.

76 {
77  wxString ref;
78 
79  if( aItem->Type() != SCH_COMPONENT_T )
80  return nullptr;
81 
82  // found next component
83  SCH_COMPONENT* comp = (SCH_COMPONENT*) aItem;
84 
85  // Power symbols and other components which have the reference starting
86  // with "#" are not included in netlist (pseudo or virtual components)
87  ref = comp->GetRef( aSheetPath );
88 
89  if( ref[0] == wxChar( '#' ) )
90  return nullptr;
91 
92  // if( Component->m_FlagControlMulti == 1 )
93  // continue; /* yes */
94  // removed because with multiple instances of one schematic
95  // (several sheets pointing to 1 screen), this will be erroneously be
96  // toggled.
97 
98  if( !comp->GetPartRef() )
99  return nullptr;
100 
101  // If component is a "multi parts per package" type
102  if( comp->GetPartRef()->GetUnitCount() > 1 )
103  {
104  // test if this reference has already been processed, and if so skip
105  if( m_ReferencesAlreadyFound.Lookup( ref ) )
106  return nullptr;
107  }
108 
109  // record the usage of this library component entry.
110  m_LibParts.insert( comp->GetPartRef().get() ); // rejects non-unique pointers
111 
112  return comp;
113 }
bool Lookup(const wxString &aString)
Function Lookup returns true if aString already exists in the set, otherwise returns false and adds a...
UNIQUE_STRINGS m_ReferencesAlreadyFound
Used for "multi parts per package" components, avoids processing a lib component more than once.
std::set< LIB_PART *, LIB_PART_LESS_THAN > m_LibParts
unique library parts used.
std::unique_ptr< LIB_PART > & GetPartRef()
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false)
Return the reference for the given sheet path.
Schematic symbol object.
Definition: sch_component.h:88
KICAD_T Type() const
Function Type()
Definition: base_struct.h:193

References SCH_COMPONENT::GetPartRef(), SCH_COMPONENT::GetRef(), UNIQUE_STRINGS::Lookup(), NETLIST_EXPORTER::m_LibParts, NETLIST_EXPORTER::m_ReferencesAlreadyFound, SCH_COMPONENT_T, and EDA_ITEM::Type().

Referenced by NETLIST_EXPORTER_GENERIC::makeComponents(), NETLIST_EXPORTER_PSPICE::ProcessNetlist(), NETLIST_EXPORTER_ORCADPCB2::WriteNetlist(), and NETLIST_EXPORTER_CADSTAR::WriteNetlist().

◆ Format()

bool NETLIST_EXPORTER_PSPICE::Format ( OUTPUTFORMATTER aFormatter,
unsigned  aCtl 
)
inherited

Definition at line 79 of file netlist_exporter_pspice.cpp.

80 {
81  // Netlist options
82  const bool useNetcodeAsNetName = false;//aCtl & NET_USE_NETCODES_AS_NETNAMES;
83 
84  // default title
85  m_title = "KiCad schematic";
86 
87  if( !ProcessNetlist( aCtl ) )
88  return false;
89 
90  aFormatter->Print( 0, ".title %s\n", (const char*) m_title.c_str() );
91 
92  // Write .include directives
93  for( const auto& lib : m_libraries )
94  {
95  wxString full_path;
96 
97  if( ( aCtl & NET_ADJUST_INCLUDE_PATHS ) )
98  {
99  // Look for the library in known search locations
100  full_path = ResolveFile( lib, &Pgm().GetLocalEnvVariables(), &m_schematic->Prj() );
101 
102  if( full_path.IsEmpty() )
103  {
104  DisplayError( NULL, wxString::Format( _( "Could not find library file %s" ), lib ) );
105  full_path = lib;
106  }
107  }
108  else
109  full_path = lib; // just use the unaltered path
110 
111  aFormatter->Print( 0, ".include \"%s\"\n", (const char*) full_path.c_str() );
112  }
113 
114  unsigned int NC_counter = 1;
115 
116  for( const auto& item : m_spiceItems )
117  {
118  if( !item.m_enabled )
119  continue;
120 
121  wxString device = GetSpiceDevice( item.m_refName );
122  aFormatter->Print( 0, "%s ", (const char*) device.c_str() );
123 
124  size_t pspiceNodes = item.m_pinSequence.empty() ? item.m_pins.size() : item.m_pinSequence.size();
125 
126  for( size_t ii = 0; ii < pspiceNodes; ii++ )
127  {
128  // Use the custom order if defined, otherwise use the standard pin order as defined in the compon
129  size_t activePinIndex = item.m_pinSequence.empty() ? ii : item.m_pinSequence[ii];
130  // Valid used Node Indexes are in the set
131  // {0,1,2,...m_item.m_pin.size()-1}
132  if( activePinIndex >= item.m_pins.size() )
133  {
134  wxASSERT_MSG( false, "Used an invalid pin number in node sequence" );
135  continue;
136  }
137 
138  wxString netName = item.m_pins[activePinIndex];
139 
140  wxASSERT( m_netMap.count( netName ) );
141 
142  if( useNetcodeAsNetName )
143  {
144  aFormatter->Print( 0, "%d ", m_netMap[netName] );
145  }
146  else
147  {
148  // Replace parenthesis with underscore to prevent parse issues with simulators
149  ReplaceForbiddenChars( netName );
150 
151  // unescape net names that contain a escaped sequence ("{slash}"):
152  netName = UnescapeString( netName );
153 
154  // Borrow LTSpice's nomenclature for unconnected nets
155  if( netName.IsEmpty() )
156  netName = wxString::Format( wxT( "NC_%.2u" ), NC_counter++ );
157 
158  aFormatter->Print( 0, "%s ", TO_UTF8( netName ) );
159  }
160  }
161 
162  aFormatter->Print( 0, "%s\n", (const char*) item.m_model.c_str() );
163  }
164 
165  // Print out all directives found in the text fields on the schematics
166  writeDirectives( aFormatter, aCtl );
167 
168  aFormatter->Print( 0, ".end\n" );
169 
170  return true;
171 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:239
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:151
KIWAY Kiway & Pgm(), KFCTL_STANDALONE
The global Program "get" accessor.
Definition: single_top.cpp:104
std::set< wxString > m_libraries
Libraries used by the simulated circuit
SCHEMATIC * m_schematic
The schematic we're generating a netlist for.
SPICE_ITEM_LIST m_spiceItems
List of items representing schematic components in the Spice world
wxString m_title
Spice simulation title found in the processed schematic sheet
NET_INDEX_MAP m_netMap
Maps circuit nodes to net names
#define NULL
virtual void writeDirectives(OUTPUTFORMATTER *aFormatter, unsigned aCtl) const
Saves the Spice directives.
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.
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
#define _(s)
Definition: 3d_actions.cpp:33
wxString UnescapeString(const wxString &aSource)
Definition: string.cpp:125
PROJECT & Prj() const
Return a reference to the project this schematic is part of.
Definition: schematic.h:77
#define TO_UTF8(wxstring)
wxString GetSpiceDevice(const wxString &aComponent) const
Returns name of Spice device corresponding to a schematic component.
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Function Print formats and writes text to the output stream.
Definition: richio.cpp:404

References _, DisplayError(), Format(), NETLIST_EXPORTER_PSPICE::GetSpiceDevice(), NETLIST_EXPORTER_PSPICE::m_libraries, NETLIST_EXPORTER_PSPICE::m_netMap, NETLIST_EXPORTER::m_schematic, NETLIST_EXPORTER_PSPICE::m_spiceItems, NETLIST_EXPORTER_PSPICE::m_title, NET_ADJUST_INCLUDE_PATHS, NULL, Pgm(), OUTPUTFORMATTER::Print(), SCHEMATIC::Prj(), NETLIST_EXPORTER_PSPICE::ProcessNetlist(), NETLIST_EXPORTER_PSPICE::ReplaceForbiddenChars(), ResolveFile(), TO_UTF8, UnescapeString(), and NETLIST_EXPORTER_PSPICE::writeDirectives().

Referenced by NETLIST_EXPORTER_PSPICE::WriteNetlist().

◆ GetCurrents()

const std::vector< wxString > & NETLIST_EXPORTER_PSPICE_SIM::GetCurrents ( SPICE_PRIMITIVE  aPrimitive)
static

Returns a list of currents that can be probed in a Spice primitive.

Definition at line 107 of file netlist_exporter_pspice_sim.cpp.

108 {
109  static const std::vector<wxString> passive = { "I" };
110  static const std::vector<wxString> diode = { "Id" };
111  static const std::vector<wxString> bjt = { "Ib", "Ic", "Ie" };
112  static const std::vector<wxString> mos = { "Ig", "Id", "Is" };
113  static const std::vector<wxString> empty;
114 
115  switch( aPrimitive )
116  {
117  case SP_RESISTOR:
118  case SP_CAPACITOR:
119  case SP_INDUCTOR:
120  case SP_VSOURCE:
121  return passive;
122 
123  case SP_DIODE:
124  return diode;
125 
126  case SP_BJT:
127  return bjt;
128 
129  case SP_MOSFET:
130  return mos;
131 
132  default:
133  return empty;
134  }
135 }
static bool empty(const wxTextEntryBase *aCtrl)

References empty(), SP_BJT, SP_CAPACITOR, SP_DIODE, SP_INDUCTOR, SP_MOSFET, SP_RESISTOR, and SP_VSOURCE.

Referenced by DIALOG_SIGNAL_LIST::TransferDataToWindow(), and writeDirectives().

◆ GetDirectives()

const std::vector<wxString> NETLIST_EXPORTER_PSPICE::GetDirectives ( ) const
inlineinherited

Returnss a vector of Spice directives found in the schematics.

Definition at line 205 of file netlist_exporter_pspice.h.

206  {
207  return m_directives;
208  }
std::vector< wxString > m_directives
Spice directives found in the processed schematic sheet

References NETLIST_EXPORTER_PSPICE::m_directives.

Referenced by GetSheetSimCommand(), and writeDirectives().

◆ GetNetIndexMap()

const NET_INDEX_MAP& NETLIST_EXPORTER_PSPICE::GetNetIndexMap ( ) const
inlineinherited

Returns a map of circuit nodes to net names.

Definition at line 166 of file netlist_exporter_pspice.h.

167  {
168  return m_netMap;
169  }
NET_INDEX_MAP m_netMap
Maps circuit nodes to net names

References NETLIST_EXPORTER_PSPICE::m_netMap.

Referenced by DIALOG_SIM_SETTINGS::ShowModal(), DIALOG_SIM_SETTINGS::TransferDataFromWindow(), DIALOG_SIGNAL_LIST::TransferDataToWindow(), and writeDirectives().

◆ GetSheetSimCommand()

wxString NETLIST_EXPORTER_PSPICE_SIM::GetSheetSimCommand ( )

Returns simulation command directives placed in schematic sheets (if any).

Definition at line 138 of file netlist_exporter_pspice_sim.cpp.

139 {
140  wxString simCmd;
141 
143 
144  for( const auto& dir : GetDirectives() )
145  {
146  if( IsSimCommand( dir ) )
147  simCmd += wxString::Format( "%s\r\n", dir );
148  }
149 
150  return simCmd;
151 }
const std::vector< wxString > GetDirectives() const
Returnss a vector of Spice directives found in the schematics.
static bool IsSimCommand(const wxString &aCmd)
Determines if a directive is a simulation command.
void UpdateDirectives(unsigned aCtl)
Updates the vector of Spice directives placed in the schematics.
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

References Format(), NETLIST_EXPORTER_PSPICE::GetDirectives(), IsSimCommand(), NET_ALL_FLAGS, and NETLIST_EXPORTER_PSPICE::UpdateDirectives().

Referenced by GetUsedSimCommand(), and DIALOG_SIM_SETTINGS::loadDirectives().

◆ GetSimCommand()

const wxString& NETLIST_EXPORTER_PSPICE_SIM::GetSimCommand ( ) const
inline

Returns the simulation command directive.

Definition at line 91 of file netlist_exporter_pspice_sim.h.

92  {
93  return m_simCommand;
94  }
wxString m_simCommand
Custom simulation command (has priority over the schematic sheet simulation commands)

References m_simCommand.

◆ GetSimType()

SIM_TYPE NETLIST_EXPORTER_PSPICE_SIM::GetSimType ( )

Returns simulation type basing on the simulation command directives.

Simulation directives set using SetSimCommand() have priority over the ones placed in schematic sheets.

Definition at line 160 of file netlist_exporter_pspice_sim.cpp.

161 {
163 }
wxString GetUsedSimCommand()
Returns the command directive that is in use (either from the sheet or from m_simCommand.
static SIM_TYPE CommandToSimType(const wxString &aCmd)
Returns simulation type basing on a simulation command directive.

References CommandToSimType(), and GetUsedSimCommand().

Referenced by DIALOG_SIGNAL_LIST::TransferDataToWindow().

◆ GetSpiceDevice()

wxString NETLIST_EXPORTER_PSPICE::GetSpiceDevice ( const wxString &  aComponent) const
inherited

Returns name of Spice device corresponding to a schematic component.

Parameters
aComponentis the component reference.
Returns
Spice device name or empty string if there is no such component in the netlist. The name is either plain reference if the first character of reference corresponds to the assigned device model type or it is the reference prefixed with a character defining the device model type.

Definition at line 43 of file netlist_exporter_pspice.cpp.

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 }
const SPICE_ITEM_LIST & GetSpiceItems() const
Returns list of items representing schematic components in the Spice world.
Structure to represent a schematic component in the Spice simulation.

References NETLIST_EXPORTER_PSPICE::GetSpiceItems().

Referenced by ComponentToVector(), NETLIST_EXPORTER_PSPICE::Format(), DIALOG_SIM_SETTINGS::TransferDataFromWindow(), and TUNER_SLIDER::TUNER_SLIDER().

◆ GetSpiceField()

wxString NETLIST_EXPORTER_PSPICE::GetSpiceField ( SPICE_FIELD  aField,
SCH_COMPONENT aComponent,
unsigned  aCtl 
)
staticinherited

Retrieves either the requested field value or the default value.

Definition at line 174 of file netlist_exporter_pspice.cpp.

176 {
177  SCH_FIELD* field = aComponent->FindField( GetSpiceFieldName( aField ) );
178  return field ? field->GetText() : GetSpiceFieldDefVal( aField, aComponent, aCtl );
179 }
SCH_FIELD instances are attached to a component and provide a place for the component's value,...
Definition: sch_field.h:52
SCH_FIELD * FindField(const wxString &aFieldName, bool aIncludeDefaultFields=true)
Search for a SCH_FIELD with aFieldName.
static const wxString & GetSpiceFieldName(SPICE_FIELD aField)
Returns a string used for a particular component field related to Spice simulation.
static wxString GetSpiceFieldDefVal(SPICE_FIELD aField, SCH_COMPONENT *aComponent, unsigned aCtl)
Retrieves the default value for a given field.
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition: eda_text.h:127

References SCH_COMPONENT::FindField(), NETLIST_EXPORTER_PSPICE::GetSpiceFieldDefVal(), NETLIST_EXPORTER_PSPICE::GetSpiceFieldName(), and EDA_TEXT::GetText().

Referenced by SIM_PLOT_FRAME::AddTuner(), and NETLIST_EXPORTER_PSPICE::ProcessNetlist().

◆ GetSpiceFieldDefVal()

wxString NETLIST_EXPORTER_PSPICE::GetSpiceFieldDefVal ( SPICE_FIELD  aField,
SCH_COMPONENT aComponent,
unsigned  aCtl 
)
staticinherited

Retrieves the default value for a given field.

Definition at line 182 of file netlist_exporter_pspice.cpp.

184 {
185  switch( aField )
186  {
187  case SF_PRIMITIVE:
188  {
189  const wxString refName = aComponent->GetField( REFERENCE )->GetText();
190  return refName.GetChar( 0 );
191  break;
192  }
193 
194  case SF_MODEL:
195  {
196  wxChar prim = aComponent->GetField( REFERENCE )->GetText().GetChar( 0 );
197  wxString value = aComponent->GetField( VALUE )->GetText();
198 
199  // Is it a passive component?
200  if( aCtl & NET_ADJUST_PASSIVE_VALS && ( prim == 'C' || prim == 'L' || prim == 'R' ) )
201  {
202  // Regular expression to match common formats used for passive parts description
203  // (e.g. 100k, 2k3, 1 uF)
204  wxRegEx passiveVal( "^([0-9\\. ]+)([fFpPnNuUmMkKgGtT]|M(e|E)(g|G))?([fFhH]|ohm)?([-1-9 ]*)$" );
205 
206  if( passiveVal.Matches( value ) )
207  {
208  wxString prefix( passiveVal.GetMatch( value, 1 ) );
209  wxString unit( passiveVal.GetMatch( value, 2 ) );
210  wxString suffix( passiveVal.GetMatch( value, 6 ) );
211 
212  prefix.Trim(); prefix.Trim( false );
213  unit.Trim(); unit.Trim( false );
214  suffix.Trim(); suffix.Trim( false );
215 
216  // Make 'mega' units comply with the Spice expectations
217  if( unit == "M" )
218  unit = "Meg";
219 
220  value = prefix + unit + suffix;
221  }
222  }
223 
224  return value;
225  break;
226  }
227 
228  case SF_ENABLED:
229  return wxString( "Y" );
230  break;
231 
232  case SF_NODE_SEQUENCE:
233  {
234  wxString nodeSeq;
235  std::vector<LIB_PIN*> pins;
236 
237  wxCHECK( aComponent->GetPartRef(), wxString() );
238  aComponent->GetPartRef()->GetPins( pins );
239 
240  for( auto pin : pins )
241  nodeSeq += pin->GetNumber() + " ";
242 
243  nodeSeq.Trim();
244 
245  return nodeSeq;
246  break;
247  }
248 
249  case SF_LIB_FILE:
250  // There is no default Spice library
251  return wxEmptyString;
252  break;
253 
254  default:
255  wxASSERT_MSG( false, "Missing default value definition for a Spice field" );
256  break;
257  }
258 
259 
260  return wxString( "<unknown>" );
261 }
Field Reference of part, i.e. "IC21".
std::unique_ptr< LIB_PART > & GetPartRef()
SCH_FIELD * GetField(int aFieldNdx)
Returns a field in this symbol.
Field Value of part, i.e. "3.3K".
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition: eda_text.h:127

References SCH_COMPONENT::GetField(), SCH_COMPONENT::GetPartRef(), EDA_TEXT::GetText(), NET_ADJUST_PASSIVE_VALS, REFERENCE, SF_ENABLED, SF_LIB_FILE, SF_MODEL, SF_NODE_SEQUENCE, SF_PRIMITIVE, and VALUE.

Referenced by NETLIST_EXPORTER_PSPICE::GetSpiceField(), and DIALOG_SPICE_MODEL::TransferDataToWindow().

◆ GetSpiceFieldName()

static const wxString& NETLIST_EXPORTER_PSPICE::GetSpiceFieldName ( SPICE_FIELD  aField)
inlinestaticinherited

Returns a string used for a particular component field related to Spice simulation.

Definition at line 182 of file netlist_exporter_pspice.h.

183  {
184  return m_spiceFields[(int) aField];
185  }
static const std::vector< wxString > m_spiceFields

References NETLIST_EXPORTER_PSPICE::m_spiceFields.

Referenced by DIALOG_SPICE_MODEL::getLibField(), DIALOG_SPICE_MODEL::getSchField(), NETLIST_EXPORTER_PSPICE::GetSpiceField(), NETLIST_EXPORTER_PSPICE::ProcessNetlist(), and DIALOG_SPICE_MODEL::TransferDataFromWindow().

◆ GetSpiceFields()

static const std::vector<wxString>& NETLIST_EXPORTER_PSPICE::GetSpiceFields ( )
inlinestaticinherited

Returns a vector of component field names related to Spice simulation.

Definition at line 174 of file netlist_exporter_pspice.h.

175  {
176  return m_spiceFields;
177  }
static const std::vector< wxString > m_spiceFields

References NETLIST_EXPORTER_PSPICE::m_spiceFields.

Referenced by DIALOG_SPICE_MODEL::TransferDataToWindow().

◆ GetSpiceItems()

const SPICE_ITEM_LIST& NETLIST_EXPORTER_PSPICE::GetSpiceItems ( ) const
inlineinherited

Returns list of items representing schematic components in the Spice world.

Definition at line 121 of file netlist_exporter_pspice.h.

122  {
123  return m_spiceItems;
124  }
SPICE_ITEM_LIST m_spiceItems
List of items representing schematic components in the Spice world

References NETLIST_EXPORTER_PSPICE::m_spiceItems.

Referenced by NETLIST_EXPORTER_PSPICE::GetSpiceDevice(), DIALOG_SIM_SETTINGS::ShowModal(), DIALOG_SIGNAL_LIST::TransferDataToWindow(), and writeDirectives().

◆ GetUsedSimCommand()

wxString NETLIST_EXPORTER_PSPICE_SIM::GetUsedSimCommand ( )

Returns the command directive that is in use (either from the sheet or from m_simCommand.

Returns

Definition at line 154 of file netlist_exporter_pspice_sim.cpp.

155 {
156  return m_simCommand.IsEmpty() ? GetSheetSimCommand() : m_simCommand;
157 }
wxString m_simCommand
Custom simulation command (has priority over the schematic sheet simulation commands)
wxString GetSheetSimCommand()
Returns simulation command directives placed in schematic sheets (if any).

References GetSheetSimCommand(), and m_simCommand.

Referenced by GetSimType().

◆ IsSimCommand()

static bool NETLIST_EXPORTER_PSPICE_SIM::IsSimCommand ( const wxString &  aCmd)
inlinestatic

Determines if a directive is a simulation command.

Definition at line 134 of file netlist_exporter_pspice_sim.h.

135  {
136  return CommandToSimType( aCmd ) != ST_UNKNOWN;
137  }
static SIM_TYPE CommandToSimType(const wxString &aCmd)
Returns simulation type basing on a simulation command directive.

References CommandToSimType(), and ST_UNKNOWN.

Referenced by GetSheetSimCommand(), and writeDirectives().

◆ MakeCommandLine()

wxString NETLIST_EXPORTER::MakeCommandLine ( const wxString &  aFormatString,
const wxString &  aNetlistFile,
const wxString &  aFinalFile,
const wxString &  aProjectDirectory 
)
staticinherited

Function MakeCommandLine builds up a string that describes a command line for executing a child process.

The input and output file names along with any options to the executable are all possibly in the returned string.

Parameters
aFormatStringholds:
  • the name of the external program
  • any options needed by that program
  • formatting sequences, see below.
aNetlistFileis the name of the input file for the external program, that is a intermediate netlist file in xml format.
aFinalFileis the name of the output file that the user expects.
aProjectDirectoryis used for P replacement, it should omit the trailing '/'.

Supported formatting sequences and their meaning:

  • B => base filename of selected output file, minus path and extension.
  • I => complete filename and path of the temporary input file.
  • O => complete filename and path of the user chosen output file.
  • P => project directory, without name and without trailing '/'

Definition at line 41 of file netlist_exporter.cpp.

43 {
44  // Expand format symbols in the command line:
45  // %B => base filename of selected output file, minus path and extension.
46  // %P => project directory name, without trailing '/' or '\'.
47  // %I => full filename of the input file (the intermediate net file).
48  // %O => complete filename and path (but without extension) of the user chosen output file.
49 
50  wxString ret = aFormatString;
51  wxFileName in = aNetlistFile;
52  wxFileName out = aFinalFile;
53  wxString str_out = out.GetFullPath();
54 
55  ret.Replace( "%P", aProjectPath, true );
56  ret.Replace( "%B", out.GetName(), true );
57  ret.Replace( "%I", in.GetFullPath(), true );
58 
59 #ifdef __WINDOWS__
60  // A ugly hack to run xsltproc that has a serious bug on Window since a long time:
61  // the filename given after -o option (output filename) cannot use '\' in filename
62  // so replace if by '/' if possible (I mean if the filename does not start by "\\"
63  // that is a filename on a Windows server)
64 
65  if( !str_out.StartsWith( "\\\\" ) )
66  str_out.Replace( "\\", "/" );
67 #endif
68 
69  ret.Replace( "%O", str_out, true );
70 
71  return ret;
72 }

Referenced by SCH_EDIT_FRAME::WriteNetListFile().

◆ ParseDCCommand()

bool NETLIST_EXPORTER_PSPICE_SIM::ParseDCCommand ( const wxString &  aCmd,
SPICE_DC_PARAMS aSource1,
SPICE_DC_PARAMS aSource2 
)

Parses a two-source .dc command directive into its components.

Parameters
aCmdis the input command string
Returns
true if the command was parsed successfully

Definition at line 192 of file netlist_exporter_pspice_sim.cpp.

194 {
195  if( !aCmd.Lower().StartsWith( ".dc" ) )
196  return false;
197 
198  wxString cmd = aCmd.Mid( 3 ).Trim().Trim( false );
199 
200  wxStringTokenizer tokens( cmd );
201 
202  size_t num = tokens.CountTokens();
203 
204  if( num != 4 && num != 8 )
205  return false;
206 
207  aSource1->m_source = tokens.GetNextToken();
208  aSource1->m_vstart = SPICE_VALUE( tokens.GetNextToken() );
209  aSource1->m_vend = SPICE_VALUE( tokens.GetNextToken() );
210  aSource1->m_vincrement = SPICE_VALUE( tokens.GetNextToken() );
211 
212  if( num == 8 )
213  {
214  aSource2->m_source = tokens.GetNextToken();
215  aSource2->m_vstart = SPICE_VALUE( tokens.GetNextToken() );
216  aSource2->m_vend = SPICE_VALUE( tokens.GetNextToken() );
217  aSource2->m_vincrement = SPICE_VALUE( tokens.GetNextToken() );
218  }
219 
220  return true;
221 }
Helper class to handle Spice way of expressing values (e.g. 10.5 Meg)
Definition: spice_value.h:32

References SPICE_DC_PARAMS::m_source, SPICE_DC_PARAMS::m_vend, SPICE_DC_PARAMS::m_vincrement, and SPICE_DC_PARAMS::m_vstart.

◆ ProcessNetlist()

bool NETLIST_EXPORTER_PSPICE::ProcessNetlist ( unsigned  aCtl)
inherited

Processes the netlist to create net mapping and a list of SPICE_ITEMs.

It is automatically called by WriteNetlist(), but might be used separately, if only net mapping and the list of SPICE_ITEMs are required.

Returns
True if successful.

Definition at line 264 of file netlist_exporter_pspice.cpp.

265 {
266  const wxString delimiters( "{:,; }" );
267 
268  SCH_SHEET_LIST sheetList = m_schematic->GetSheets();
269  // Set of reference names, to check for duplications
270  std::set<wxString> refNames;
271 
272  m_netMap.clear();
273  m_netMap["GND"] = 0; // 0 is reserved for "GND"
274  int netIdx = 1;
275 
276  m_libraries.clear();
278  m_LibParts.clear();
279 
280  UpdateDirectives( aCtl );
281 
282  for( unsigned sheet_idx = 0; sheet_idx < sheetList.size(); sheet_idx++ )
283  {
284  SCH_SHEET_PATH sheet = sheetList[sheet_idx];
285 
286  // Process component attributes to find Spice directives
287  for( auto item : sheet.LastScreen()->Items().OfType( SCH_COMPONENT_T ) )
288  {
289  SCH_COMPONENT* comp = findNextComponent( item, &sheet );
290 
291  if( !comp )
292  continue;
293 
294  CreatePinList( comp, &sheet );
295  SPICE_ITEM spiceItem;
296  spiceItem.m_parent = comp;
297 
298  // Obtain Spice fields
299  SCH_FIELD* fieldLibFile = comp->FindField( GetSpiceFieldName( SF_LIB_FILE ) );
300  SCH_FIELD* fieldSeq = comp->FindField( GetSpiceFieldName( SF_NODE_SEQUENCE ) );
301 
302  spiceItem.m_primitive = GetSpiceField( SF_PRIMITIVE, comp, aCtl )[0];
303  spiceItem.m_model = GetSpiceField( SF_MODEL, comp, aCtl );
304  spiceItem.m_refName = comp->GetRef( &sheet );
305 
306  // Duplicate references will result in simulation errors
307  if( refNames.count( spiceItem.m_refName ) )
308  {
309  DisplayError( NULL, wxT( "There are duplicate components. "
310  "You need to annotate schematics first." ) );
311  return false;
312  }
313 
314  refNames.insert( spiceItem.m_refName );
315 
316  // Check to see if component should be removed from Spice netlist
317  spiceItem.m_enabled = StringToBool( GetSpiceField( SF_ENABLED, comp, aCtl ) );
318 
319  if( fieldLibFile && !fieldLibFile->GetText().IsEmpty() )
320  m_libraries.insert( fieldLibFile->GetText() );
321 
322  wxArrayString pinNames;
323 
324  // Store pin information
325  for( const PIN_INFO& pin : m_SortedComponentPinList )
326  {
327  // Create net mapping
328  spiceItem.m_pins.push_back( pin.netName );
329  pinNames.Add( pin.num );
330 
331  if( m_netMap.count( pin.netName ) == 0 )
332  m_netMap[pin.netName] = netIdx++;
333  }
334 
335  // Check if an alternative pin sequence is available:
336  if( fieldSeq )
337  {
338  // Get the string containing the sequence of nodes:
339  const wxString& nodeSeqIndexLineStr = fieldSeq->GetText();
340 
341  // Verify field exists and is not empty:
342  if( !nodeSeqIndexLineStr.IsEmpty() )
343  {
344  // Get Alt Pin Name Array From User:
345  wxStringTokenizer tkz( nodeSeqIndexLineStr, delimiters );
346 
347  while( tkz.HasMoreTokens() )
348  {
349  wxString pinIndex = tkz.GetNextToken();
350  int seq;
351 
352  // Find PinName In Standard List assign Standard List Index to Name:
353  seq = pinNames.Index( pinIndex );
354 
355  if( seq != wxNOT_FOUND )
356  spiceItem.m_pinSequence.push_back( seq );
357  }
358  }
359  }
360 
361  m_spiceItems.push_back( spiceItem );
362  }
363  }
364 
365  return true;
366 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:239
SCH_SHEET_LIST.
SCH_FIELD instances are attached to a component and provide a place for the component's value,...
Definition: sch_field.h:52
SCH_FIELD * FindField(const wxString &aFieldName, bool aIncludeDefaultFields=true)
Search for a SCH_FIELD with aFieldName.
SCH_SHEET_LIST GetSheets() const
Builds and returns an updated schematic hierarchy TODO: can this be cached?
Definition: schematic.h:92
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
SCHEMATIC * m_schematic
The schematic we're generating a netlist for.
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
Array containing Standard Pin Name
static const wxString & GetSpiceFieldName(SPICE_FIELD aField)
Returns a string used for a particular component field related to Spice simulation.
EE_TYPE OfType(KICAD_T aType)
Definition: sch_rtree.h:219
bool m_enabled
Flag to indicate whether the component should be used in simulation.
void Clear()
Function Clear erases the record.
SCH_COMPONENT * findNextComponent(EDA_ITEM *aItem, SCH_SHEET_PATH *aSheetPath)
Checks if the given component should be processed for netlisting.
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...
SPICE_ITEM_LIST m_spiceItems
List of items representing schematic components in the Spice world
std::set< LIB_PART *, LIB_PART_LESS_THAN > m_LibParts
unique library parts used.
NET_INDEX_MAP m_netMap
Maps circuit nodes to net names
#define NULL
void UpdateDirectives(unsigned aCtl)
Updates the vector of Spice directives placed in the schematics.
void CreatePinList(SCH_COMPONENT *aItem, SCH_SHEET_PATH *aSheetPath)
Function findNextComponentAndCreatePinList finds a component from the DrawList and builds its pin lis...
std::vector< PIN_INFO > m_SortedComponentPinList
Used to temporarily store and filter the list of pins of a schematic component when generating schema...
SCH_SHEET_PATH.
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false)
Return the reference for the given sheet path.
SCH_SCREEN * LastScreen()
Function LastScreen.
EE_RTREE & Items()
Definition: sch_screen.h:158
static wxString GetSpiceField(SPICE_FIELD aField, SCH_COMPONENT *aComponent, unsigned aCtl)
Retrieves either the requested field value or the default value.
Schematic symbol object.
Definition: sch_component.h:88
wxChar m_primitive
Spice primitive type (
std::vector< int > m_pinSequence
Numeric indices into m_SortedComponentPinList
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition: eda_text.h:127

References UNIQUE_STRINGS::Clear(), NETLIST_EXPORTER::CreatePinList(), DisplayError(), SCH_COMPONENT::FindField(), NETLIST_EXPORTER::findNextComponent(), SCH_COMPONENT::GetRef(), SCHEMATIC::GetSheets(), NETLIST_EXPORTER_PSPICE::GetSpiceField(), NETLIST_EXPORTER_PSPICE::GetSpiceFieldName(), EDA_TEXT::GetText(), SCH_SCREEN::Items(), SCH_SHEET_PATH::LastScreen(), SPICE_ITEM::m_enabled, NETLIST_EXPORTER::m_LibParts, NETLIST_EXPORTER_PSPICE::m_libraries, SPICE_ITEM::m_model, NETLIST_EXPORTER_PSPICE::m_netMap, SPICE_ITEM::m_parent, SPICE_ITEM::m_pins, SPICE_ITEM::m_pinSequence, SPICE_ITEM::m_primitive, NETLIST_EXPORTER::m_ReferencesAlreadyFound, SPICE_ITEM::m_refName, NETLIST_EXPORTER::m_schematic, NETLIST_EXPORTER::m_SortedComponentPinList, NETLIST_EXPORTER_PSPICE::m_spiceItems, NULL, EE_RTREE::OfType(), SCH_COMPONENT_T, SF_ENABLED, SF_LIB_FILE, SF_MODEL, SF_NODE_SEQUENCE, SF_PRIMITIVE, NETLIST_EXPORTER_PSPICE::StringToBool(), and NETLIST_EXPORTER_PSPICE::UpdateDirectives().

Referenced by NETLIST_EXPORTER_PSPICE::Format().

◆ ReplaceForbiddenChars()

void NETLIST_EXPORTER_PSPICE::ReplaceForbiddenChars ( wxString &  aNetName)
staticinherited

some chars are not accepted in netnames in spice netlists.

for instance '(' and ')' ReplaceForbiddenChars replace these chars by an underscore.

Parameters
aNetName= the netname to modify.

Definition at line 67 of file netlist_exporter_pspice.cpp.

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  aNetName.Replace( " ", "_" );
76 }

Referenced by ComponentToVector(), and NETLIST_EXPORTER_PSPICE::Format().

◆ SetSimCommand()

void NETLIST_EXPORTER_PSPICE_SIM::SetSimCommand ( const wxString &  aCmd)
inline

Overrides the simulation command directive.

Definition at line 83 of file netlist_exporter_pspice_sim.h.

84  {
85  m_simCommand = aCmd;
86  }
wxString m_simCommand
Custom simulation command (has priority over the schematic sheet simulation commands)

References m_simCommand.

◆ StringToBool()

static bool NETLIST_EXPORTER_PSPICE::StringToBool ( const wxString &  aStr)
inlinestaticinherited

Convertes typical boolean string values (no/yes, true/false, 1/0) to a boolean value.

Definition at line 213 of file netlist_exporter_pspice.h.

214  {
215  if( aStr.IsEmpty() )
216  return false;
217 
218  char c = tolower( aStr[0] );
219 
220  // Different ways of saying false (no/false/0)
221  return !( c == 'n' || c == 'f' || c == '0' );
222  }

Referenced by NETLIST_EXPORTER_PSPICE::ProcessNetlist(), and DIALOG_SPICE_MODEL::TransferDataToWindow().

◆ UpdateDirectives()

void NETLIST_EXPORTER_PSPICE::UpdateDirectives ( unsigned  aCtl)
inherited

Updates the vector of Spice directives placed in the schematics.

Definition at line 369 of file netlist_exporter_pspice.cpp.

370 {
371  const SCH_SHEET_LIST& sheetList = m_schematic->GetSheets();
372  wxRegEx couplingK( "^[kK][[:digit:]]*[[:space:]]+[[:alnum:]]+[[:space:]]+[[:alnum:]]+",
373  wxRE_ADVANCED );
374 
375  m_directives.clear();
376  bool controlBlock = false;
377  bool circuitBlock = false;
378 
379  for( unsigned i = 0; i < sheetList.size(); i++ )
380  {
381  for( auto item : sheetList[i].LastScreen()->Items().OfType( SCH_TEXT_T ) )
382  {
383  wxString text = static_cast<SCH_TEXT*>( item )->GetText();
384 
385  if( text.IsEmpty() )
386  continue;
387 
388  // Analyze each line of a text field
389  wxStringTokenizer tokenizer( text, "\r\n" );
390 
391  // Flag to follow multiline directives
392  bool directiveStarted = false;
393 
394  while( tokenizer.HasMoreTokens() )
395  {
396  wxString line( tokenizer.GetNextToken() );
397 
398  // Cleanup: remove preceding and trailing white-space characters
399  line.Trim( true ).Trim( false );
400  // Convert to lower-case for parsing purposes only
401  wxString lowercaseline = line;
402  lowercaseline.MakeLower();
403 
404  // 'Include' directive stores the library file name, so it
405  // can be later resolved using a list of paths
406  if( lowercaseline.StartsWith( ".inc" ) )
407  {
408  wxString lib = line.AfterFirst( ' ' );
409 
410  if( lib.IsEmpty() )
411  continue;
412 
413  // Strip quotes if present
414  if( ( lib.StartsWith( "\"" ) && lib.EndsWith( "\"" ) )
415  || ( lib.StartsWith( "'" ) && lib.EndsWith( "'" ) ) )
416  {
417  lib = lib.Mid( 1, lib.Length() - 2 );
418  }
419 
420  m_libraries.insert( lib );
421  }
422 
423  // Store the title to be sure it appears
424  // in the first line of output
425  else if( lowercaseline.StartsWith( ".title " ) )
426  {
427  m_title = line.AfterFirst( ' ' );
428  }
429 
430  else if( line.StartsWith( '.' ) // one-line directives
431  || controlBlock // .control .. .endc block
432  || circuitBlock // .subckt .. .ends block
433  || couplingK.Matches( line ) // K## L## L## coupling constant
434  || ( directiveStarted && line.StartsWith( '+' ) ) ) // multiline directives
435  {
436  m_directives.push_back( line );
437  }
438 
439 
440  // Handle .control .. .endc blocks
441  if( lowercaseline.IsSameAs( ".control" ) && ( !controlBlock ) )
442  controlBlock = true;
443 
444  if( lowercaseline.IsSameAs( ".endc" ) && controlBlock )
445  controlBlock = false;
446 
447  // Handle .subckt .. .ends blocks
448  if( lowercaseline.StartsWith( ".subckt" ) && ( !circuitBlock ) )
449  circuitBlock = true;
450 
451  if( lowercaseline.IsSameAs( ".ends" ) && circuitBlock )
452  circuitBlock = false;
453 
454  // Mark directive as started or continued in case it is a multi-line one
455  directiveStarted = line.StartsWith( '.' )
456  || ( directiveStarted && line.StartsWith( '+' ) );
457  }
458  }
459  }
460 }
SCH_SHEET_LIST.
SCH_SHEET_LIST GetSheets() const
Builds and returns an updated schematic hierarchy TODO: can this be cached?
Definition: schematic.h:92
std::set< wxString > m_libraries
Libraries used by the simulated circuit
SCHEMATIC * m_schematic
The schematic we're generating a netlist for.
std::vector< wxString > m_directives
Spice directives found in the processed schematic sheet
wxString m_title
Spice simulation title found in the processed schematic sheet

References SCHEMATIC::GetSheets(), NETLIST_EXPORTER_PSPICE::m_directives, NETLIST_EXPORTER_PSPICE::m_libraries, NETLIST_EXPORTER::m_schematic, NETLIST_EXPORTER_PSPICE::m_title, and SCH_TEXT_T.

Referenced by GetSheetSimCommand(), and NETLIST_EXPORTER_PSPICE::ProcessNetlist().

◆ VectorToSignal()

SIM_PLOT_TYPE NETLIST_EXPORTER_PSPICE_SIM::VectorToSignal ( const std::string &  aVector,
wxString &  aSignal 
) const

Returns name of Spice dataset for a specific plot.

Parameters
aVectoris name of the vector produced by ngspice
[out]aSignalis output in form: V(R1), Ib(Q2), I(L8)
Returns
[SPT_VOLTAGE, SPT_CURRENT]. Otherwise SPT_UNKNOWN if vector is of different, unsupported type.

Definition at line 72 of file netlist_exporter_pspice_sim.cpp.

74 {
75  using namespace std;
76 
77  // See ngspice manual chapt. 31.1 "Accessing internal device parameters"
78  wxRegEx internalDevParameter( "^@(\\w*[\\.\\w+]*)\\[(\\w*)\\]$", wxRE_ADVANCED );
79  wxString vector( aVector );
80 
81  if( !internalDevParameter.Matches( vector ) )
82  {
83  // any text is a node name, which returns voltage
84  aSignal = "V(" + aVector + ")";
85  return SPT_VOLTAGE;
86  }
87  else
88  {
89  wxString paramType = internalDevParameter.GetMatch( vector, 2 );
90 
91  if( paramType.Lower()[0] == 'i' )
92  {
93  // this is a branch current
94  paramType[0] = 'I';
95  aSignal = paramType + "(";
96  aSignal += internalDevParameter.GetMatch( vector, 1 ).Upper() + ")";
97  return SPT_CURRENT;
98  }
99  else
100  {
101  return SPT_UNKNOWN;
102  }
103  }
104 }
Template specialization to enable wxStrings for certain containers (e.g. unordered_map)
Definition: bitmap.cpp:56

References SPT_CURRENT, SPT_UNKNOWN, and SPT_VOLTAGE.

◆ writeDirectives()

void NETLIST_EXPORTER_PSPICE_SIM::writeDirectives ( OUTPUTFORMATTER aFormatter,
unsigned  aCtl 
) const
overrideprotectedvirtual

Saves the Spice directives.

Todo:
is it required to switch to lowercase

Reimplemented from NETLIST_EXPORTER_PSPICE.

Definition at line 224 of file netlist_exporter_pspice_sim.cpp.

225 {
226  // Add a directive to obtain currents
227  //aFormatter->Print( 0, ".options savecurrents\n" ); // does not work :(
228 
229  for( const auto& item : GetSpiceItems() )
230  {
231  for( const auto& current :
233  {
234  if( !item.m_enabled )
235  continue;
236 
238  aFormatter->Print( 0, ".save %s\n",
239  (const char*) ComponentToVector( item.m_refName, SPT_CURRENT, current )
240  .c_str() );
241  }
242  }
243 
244  // If we print out .save directives for currents, then it needs to be done for voltages as well
245  for( const auto& netMap : GetNetIndexMap() )
246  {
247  // the "0" and the "GND" nets are automaticallly saved internally by ngspice.
248  // Skip them
249  wxString netname = ComponentToVector( netMap.first, SPT_VOLTAGE );
250 
251  if( netname == "V(0)" || netname == "V(GND)" )
252  continue;
253 
254  aFormatter->Print( 0, ".save %s\n", (const char*) netname.c_str() );
255  }
256 
257  if( m_simCommand.IsEmpty() )
258  {
259  // Fallback to the default behavior and just write all directives
260  NETLIST_EXPORTER_PSPICE::writeDirectives( aFormatter, aCtl );
261  }
262  else
263  {
264  // Dump all directives but simulation commands
265  for( const auto& dir : GetDirectives() )
266  {
267  if( !IsSimCommand( dir ) )
268  aFormatter->Print( 0, "%s\n", (const char*) dir.c_str() );
269  }
270 
271  // Finish with our custom simulation command
272  aFormatter->Print( 0, "%s\n", (const char*) m_simCommand.c_str() );
273  }
274 }
wxString m_simCommand
Custom simulation command (has priority over the schematic sheet simulation commands)
wxString ComponentToVector(const wxString &aName, SIM_PLOT_TYPE aType, const wxString &aParam=wxEmptyString) const
Returns name of Spice dataset for a specific plot.
const SPICE_ITEM_LIST & GetSpiceItems() const
Returns list of items representing schematic components in the Spice world.
const std::vector< wxString > GetDirectives() const
Returnss a vector of Spice directives found in the schematics.
static bool IsSimCommand(const wxString &aCmd)
Determines if a directive is a simulation command.
static const std::vector< wxString > & GetCurrents(SPICE_PRIMITIVE aPrimitive)
Returns a list of currents that can be probed in a Spice primitive.
virtual void writeDirectives(OUTPUTFORMATTER *aFormatter, unsigned aCtl) const
Saves the Spice directives.
const NET_INDEX_MAP & GetNetIndexMap() const
Returns a map of circuit nodes to net names.
SPICE_PRIMITIVE
Basic Spice component primitives
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Function Print formats and writes text to the output stream.
Definition: richio.cpp:404

References ComponentToVector(), GetCurrents(), NETLIST_EXPORTER_PSPICE::GetDirectives(), NETLIST_EXPORTER_PSPICE::GetNetIndexMap(), NETLIST_EXPORTER_PSPICE::GetSpiceItems(), IsSimCommand(), m_simCommand, OUTPUTFORMATTER::Print(), SPT_CURRENT, SPT_VOLTAGE, and NETLIST_EXPORTER_PSPICE::writeDirectives().

◆ WriteNetlist()

bool NETLIST_EXPORTER_PSPICE::WriteNetlist ( const wxString &  aOutFileName,
unsigned  aNetlistOptions 
)
overridevirtualinherited

Function WriteNetlist writes to specified output file.

Reimplemented from NETLIST_EXPORTER.

Definition at line 60 of file netlist_exporter_pspice.cpp.

61 {
62  FILE_OUTPUTFORMATTER outputFile( aOutFileName, wxT( "wt" ), '\'' );
63 
64  return Format( &outputFile, aNetlistOptions );
65 }
bool Format(OUTPUTFORMATTER *aFormatter, unsigned aCtl)
FILE_OUTPUTFORMATTER may be used for text file output.
Definition: richio.h:492

References NETLIST_EXPORTER_PSPICE::Format().

Member Data Documentation

◆ m_LibParts

std::set<LIB_PART*, LIB_PART_LESS_THAN> NETLIST_EXPORTER::m_LibParts
protectedinherited

◆ m_ReferencesAlreadyFound

UNIQUE_STRINGS NETLIST_EXPORTER::m_ReferencesAlreadyFound
protectedinherited

Used for "multi parts per package" components, avoids processing a lib component more than once.

Definition at line 110 of file netlist_exporter.h.

Referenced by NETLIST_EXPORTER::findNextComponent(), NETLIST_EXPORTER_GENERIC::makeComponents(), NETLIST_EXPORTER_PSPICE::ProcessNetlist(), NETLIST_EXPORTER_ORCADPCB2::WriteNetlist(), and NETLIST_EXPORTER_CADSTAR::WriteNetlist().

◆ m_schematic

◆ m_simCommand

wxString NETLIST_EXPORTER_PSPICE_SIM::m_simCommand
private

Custom simulation command (has priority over the schematic sheet simulation commands)

Definition at line 150 of file netlist_exporter_pspice_sim.h.

Referenced by ClearSimCommand(), GetSimCommand(), GetUsedSimCommand(), SetSimCommand(), and writeDirectives().

◆ m_SortedComponentPinList

std::vector<PIN_INFO> NETLIST_EXPORTER::m_SortedComponentPinList
protectedinherited

Used to temporarily store and filter the list of pins of a schematic component when generating schematic component data in netlist (comp section).

No ownership of members. TODO(snh): Descope this object

Definition at line 106 of file netlist_exporter.h.

Referenced by NETLIST_EXPORTER::CreatePinList(), NETLIST_EXPORTER::eraseDuplicatePins(), NETLIST_EXPORTER::findAllUnitsOfComponent(), NETLIST_EXPORTER_PSPICE::ProcessNetlist(), and NETLIST_EXPORTER_ORCADPCB2::WriteNetlist().


The documentation for this class was generated from the following files: