36#include <wx/stdpaths.h>
90 wxLogTrace(
traceNgspice,
"Sending Ngspice configuration command '%s'.", command );
116 std::vector<std::string> retVal;
118 if( allVectors !=
nullptr )
120 for(
char**
plot = allVectors; *
plot !=
nullptr;
plot++ )
123 retVal.reserve( noOfVectors );
125 for(
int i = 0; i < noOfVectors; i++, allVectors++ )
127 std::string vec = *allVectors;
128 retVal.push_back( std::move( vec ) );
140 std::vector<COMPLEX> data;
148 int length = aMaxLen < 0 ? vi->v_length : std::min( aMaxLen, vi->v_length );
149 data.reserve( length );
153 for(
int i = 0; i < length; i++ )
154 data.emplace_back( vi->v_realdata[i], 0.0 );
156 else if( vi->v_compdata )
158 for(
int i = 0; i < length; i++ )
159 data.emplace_back( vi->v_compdata[i].cx_real, vi->v_compdata[i].cx_imag );
170 std::vector<double> data;
178 int length = aMaxLen < 0 ? vi->v_length : std::min( aMaxLen, vi->v_length );
179 data.reserve( length );
183 for(
int i = 0; i < length; i++ )
184 data.push_back( vi->v_realdata[i] );
186 else if( vi->v_compdata )
188 for(
int i = 0; i < length; i++ )
189 data.push_back( vi->v_compdata[i].cx_real );
200 std::vector<double> data;
208 int length = aMaxLen < 0 ? vi->v_length : std::min( aMaxLen, vi->v_length );
209 data.reserve( length );
213 for(
int i = 0; i < length; i++ )
214 data.push_back( vi->v_compdata[i].cx_imag );
225 std::vector<double> data;
233 int length = aMaxLen < 0 ? vi->v_length : std::min( aMaxLen, vi->v_length );
234 data.reserve( length );
238 for(
int i = 0; i < length; i++ )
239 data.push_back( vi->v_realdata[i] );
241 else if( vi->v_compdata )
243 for(
int i = 0; i < length; i++ )
244 data.push_back( hypot( vi->v_compdata[i].cx_real, vi->v_compdata[i].cx_imag ) );
255 std::vector<double> data;
263 int length = aMaxLen < 0 ? vi->v_length : std::min( aMaxLen, vi->v_length );
264 data.reserve( length );
268 for(
int i = 0; i < length; i++ )
269 data.push_back( 0.0 );
271 else if( vi->v_compdata )
273 for(
int i = 0; i < length; i++ )
274 data.push_back( atan2( vi->v_compdata[i].cx_imag, vi->v_compdata[i].cx_real ) );
282bool NGSPICE::Attach(
const std::shared_ptr<SIMULATION_MODEL>& aModel,
const wxString& aSimCommand,
283 unsigned aSimOptions,
const wxString& aInputPath,
REPORTER& aReporter )
290 if(
model &&
model->GetNetlist( aSimCommand, aSimOptions, &formatter, aReporter ) )
298 Command(
"echo Command: esave none" );
315 std::stringstream ss( aNetlist );
320 std::vector<std::string> ownedLines;
323 for( std::string line; std::getline( ss, line ); )
327 ownedLines.push_back( std::move( line ) );
330 std::vector<char*> lines;
331 lines.reserve( ownedLines.size() + 1 );
333 for( std::string& line : ownedLines )
334 lines.push_back( line.data() );
336 lines.push_back(
nullptr );
391 case SIGSEGV: signalName = wxT(
"SIGSEGV (segmentation fault)" );
break;
392 case SIGABRT: signalName = wxT(
"SIGABRT (abort)" );
break;
393 case SIGFPE: signalName = wxT(
"SIGFPE (floating point exception)" );
break;
394 case SIGILL: signalName = wxT(
"SIGILL (illegal instruction)" );
break;
395 default: signalName = wxString::Format( wxT(
"signal %d" ), signal );
break;
399 _(
"Simulation crashed (%s). This is usually caused by a bug in ngspice "
400 "or an invalid netlist. The simulator will be reset." ),
428 return wxS(
"frequency" );
434 if( vector.Lower().EndsWith( wxS(
"-sweep" ) ) )
438 return wxS(
"sweep" );
441 return wxS(
"time" );
444 return wxEmptyString;
453 std::vector<std::string> commands;
455 wxCHECK( settings, commands );
465 default: wxFAIL_MSG( wxString::Format(
"Undefined NGSPICE_COMPATIBILITY_MODE %d.",
485 const wxStandardPaths& stdPaths = wxStandardPaths::Get();
487 if(
m_dll.IsLoaded() )
492 wxFileName dllFile(
"", NGSPICE_DLL_FILE );
493#if defined(__WINDOWS__)
494 #if defined( _MSC_VER )
495 std::vector<std::string> dllPaths = {
"" };
497 std::vector<std::string> dllPaths = {
"",
"/mingw64/bin",
"/mingw32/bin" };
499#elif defined(__WXMAC__)
500 std::vector<std::string> dllPaths = {
501 PATHS::GetOSXKicadUserDataDir().ToStdString() +
"/PlugIns/ngspice",
502 PATHS::GetOSXKicadMachineDataDir().ToStdString() +
"/PlugIns/ngspice",
505 stdPaths.GetPluginsDir().ToStdString() +
"/sim",
508 wxFileName( stdPaths.GetExecutablePath() ).GetPath().ToStdString() +
509 "/../../../../../Contents/PlugIns/sim"
512 std::vector<std::string> dllPaths = {
"/usr/local/lib" };
515 if( wxGetEnv( wxT(
"KICAD_RUN_FROM_BUILD_DIR" ),
nullptr ) )
516 dllPaths.emplace_back( NGSPICE_DLL_DIR );
518#if defined(__WINDOWS__) || (__WXMAC__)
519 for(
const auto&
path : dllPaths )
521 dllFile.SetPath(
path );
522 wxLogTrace(
traceNgspice,
"libngspice search path: %s", dllFile.GetFullPath() );
523 m_dll.Load( dllFile.GetFullPath(), wxDL_VERBATIM | wxDL_QUIET | wxDL_NOW );
525 if(
m_dll.IsLoaded() )
527 wxLogTrace(
traceNgspice,
"libngspice path found in: %s", dllFile.GetFullPath() );
532 if( !
m_dll.IsLoaded() )
533 m_dll.Load( wxDynamicLibrary::CanonicalizeName(
"ngspice" ) );
536 m_dll.Load( NGSPICE_DLL_FILE, wxDL_VERBATIM | wxDL_QUIET | wxDL_NOW );
539 if( !
m_dll.IsLoaded() )
541 for(
const auto&
path : dllPaths )
543 dllFile.SetPath(
path );
544 wxLogTrace(
traceNgspice,
"libngspice search path: %s", dllFile.GetFullPath() );
545 m_dll.Load( dllFile.GetFullPath(), wxDL_VERBATIM | wxDL_QUIET | wxDL_NOW );
547 if(
m_dll.IsLoaded() )
549 wxLogTrace(
traceNgspice,
"libngspice path found in: %s", dllFile.GetFullPath() );
556 if( !
m_dll.IsLoaded() )
557 throw std::runtime_error(
_(
"Unable to load ngspice shared library. Please check your install." ).ToStdString() );
572 if(
m_dll.HasSymbol(
"ngSpice_LockRealloc" ) )
583 wxString cwd( wxGetCwd() );
584 wxFileName exeDir( stdPaths.GetExecutablePath() );
585 wxSetWorkingDirectory( exeDir.GetPath() );
591 if( !cmPath.empty() )
592 Command(
"set __CMPATH=\"" + cmPath +
"\"" );
595 const std::vector<std::string> spiceinitPaths =
599 stdPaths.GetPluginsDir().ToStdString() +
"/sim/ngspice/scripts",
600 wxFileName( stdPaths.GetExecutablePath() ).GetPath().ToStdString() +
601 "/../../../../../Contents/PlugIns/sim/ngspice/scripts"
609 bool foundSpiceinit =
false;
611 for(
const auto&
path : spiceinitPaths )
618 foundSpiceinit =
true;
625 if( !foundSpiceinit && !cmPath.empty() )
629 wxSetWorkingDirectory( cwd );
642 std::vector<char*> lines;
643 lines.push_back( strdup(
"*" ) );
644 lines.push_back( strdup(
".end" ) );
645 lines.push_back(
nullptr );
649 for(
auto line : lines )
658 if( !wxFileName::FileExists( aFileName ) )
663 if( !file.Open( aFileName ) )
666 for( wxString& cmd = file.GetFirstLine(); !file.Eof(); cmd = file.GetNextLine() )
675 const std::vector<std::string> cmPaths =
678 "/Applications/ngspice/lib/ngspice",
679 "Contents/Frameworks",
680 wxStandardPaths::Get().GetPluginsDir().ToStdString() +
"/sim/ngspice",
681 wxFileName( wxStandardPaths::Get().GetExecutablePath() ).GetPath().ToStdString() +
682 "/../../../../../Contents/PlugIns/sim/ngspice",
683 "../Plugins/sim/ngspice",
685 "../eeschema/ngspice",
692 for(
const auto&
path : cmPaths )
696 if( wxFileName::FileExists(
path +
"/spice2poly.cm" ) )
703 return std::string();
722 wxArrayString cmFiles;
723 size_t count = wxDir::GetAllFiles( aPath, &cmFiles );
725 for(
const auto& cm : cmFiles )
726 Command( fmt::format(
"codemodel '{}'", cm.ToStdString() ) );
736 std::lock_guard<std::mutex> lock(
sim->m_reporterMutex );
742 if( ( strncasecmp( aWhat,
"stdout ", 7 ) == 0 )
743 || ( strncasecmp( aWhat,
"stderr ", 7 ) == 0 ) )
767 sim->restoreSignalHandlers();
771 std::lock_guard<std::mutex> lock(
sim->m_reporterMutex );
789 std::lock_guard<std::mutex> lock(
sim->m_reporterMutex );
795 _(
"Simulation terminated by ngspice. This may be caused by insufficient "
796 "memory or an internal error. The simulator will be reset." ) );
842 struct sigaction* oldAction =
nullptr;
852 if( oldAction && oldAction->sa_handler != SIG_DFL && oldAction->sa_handler != SIG_IGN )
854 oldAction->sa_handler( aSignal );
859 signal( aSignal, SIG_DFL );
878 pthread_exit(
nullptr );
892 struct sigaction newAction;
894 sigemptyset( &newAction.sa_mask );
895 newAction.sa_flags = 0;
918static bool s_exceptionHandlersInstalled =
false;
919static PVOID s_vectoredHandler =
nullptr;
920static DWORD s_mainThreadId = 0;
922long __stdcall NGSPICE::sehHandler( _EXCEPTION_POINTERS* aException )
924 if( !aException || !aException->ExceptionRecord )
925 return EXCEPTION_CONTINUE_SEARCH;
927 if( GetCurrentThreadId() == s_mainThreadId )
928 return EXCEPTION_CONTINUE_SEARCH;
932 switch( aException->ExceptionRecord->ExceptionCode )
934 case EXCEPTION_ACCESS_VIOLATION:
935 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
936 case EXCEPTION_DATATYPE_MISALIGNMENT:
937 case EXCEPTION_STACK_OVERFLOW:
940 case EXCEPTION_ILLEGAL_INSTRUCTION:
941 case EXCEPTION_PRIV_INSTRUCTION:
944 case EXCEPTION_INT_DIVIDE_BY_ZERO:
945 case EXCEPTION_INT_OVERFLOW:
946 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
947 case EXCEPTION_FLT_INVALID_OPERATION:
948 case EXCEPTION_FLT_OVERFLOW:
949 case EXCEPTION_FLT_UNDERFLOW:
950 case EXCEPTION_FLT_INEXACT_RESULT:
951 case EXCEPTION_FLT_STACK_CHECK:
955 return EXCEPTION_CONTINUE_SEARCH;
965 if( aException->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW )
966 TerminateThread( GetCurrentThread(), 1 );
970 return EXCEPTION_CONTINUE_EXECUTION;
976 wxUnusedVar( aSignal );
982 if( s_exceptionHandlersInstalled )
985 s_mainThreadId = GetCurrentThreadId();
990 s_vectoredHandler = AddVectoredExceptionHandler( 1, &NGSPICE::sehHandler );
991 s_exceptionHandlersInstalled = ( s_vectoredHandler != nullptr );
997 if( s_exceptionHandlersInstalled )
999 RemoveVectoredExceptionHandler( s_vectoredHandler );
1000 s_vectoredHandler =
nullptr;
1001 s_exceptionHandlersInstalled =
false;
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Execute commands from a file.
Container for Ngspice simulator settings.
NGSPICE_COMPATIBILITY_MODE GetCompatibilityMode() const
std::vector< std::string > AllVectors() const override final
Return a requested vector with complex values.
static std::atomic< bool > s_crashed
Set by signal handler when ngspice crashes.
ngSpice_Circ m_ngSpice_Circ
bool Command(const std::string &aCmd) override final
char **(* ngSpice_AllVecs)(char *plotname)
ngSpice_AllPlots m_ngSpice_AllPlots
static int cbControlledExit(int aStatus, NG_BOOL aImmediate, NG_BOOL aExitOnQuit, int aId, void *aUser)
void restoreSignalHandlers()
int(* ngSpice_Circ)(char **circarray)
ngSpice_UnlockRealloc m_ngSpice_UnlockRealloc
char **(* ngSpice_AllPlots)(void)
bool IsRunning() override final
Execute a Spice command as if it was typed into console.
std::vector< double > GetImaginaryVector(const std::string &aName, int aMaxLen=-1) override final
Return a requested vector with magnitude values.
virtual const std::string GetNetlist() const override final
Cleans simulation data (i.e.
char *(* ngSpice_CurPlot)(void)
ngSpice_Init m_ngSpice_Init
void updateNgspiceSettings()
Check a few different locations for codemodel files and returns one if it exists.
ngSpice_Command m_ngSpice_Command
int(* ngSpice_LockRealloc)(void)
void(* ngSpice_Init)(SendChar *, SendStat *, ControlledExit *, SendData *, SendInitData *, BGThreadRunning *, void *)
bool setCodemodelsInputPath(const std::string &aPath)
Load codemodel files from a directory.
wxString GetXAxis(SIM_TYPE aType) const override final
wxString CurrentPlotName() const override final
ngGet_Vec_Info m_ngGet_Vec_Info
bool m_error
Error flag indicating that ngspice needs to be reloaded.
ngCM_Input_Path m_ngCM_Input_Path
std::vector< double > GetPhaseVector(const std::string &aName, int aMaxLen=-1) override final
Return a requested vector with phase values.
ngSpice_LockRealloc m_ngSpice_LockRealloc
ngSpice_CurPlot m_ngSpice_CurPlot
bool loadSpinit(const std::string &aFileName)
bool Run() override final
Halt the simulation.
bool LoadNetlist(const std::string &aNetlist) override final
Execute the simulation with currently loaded netlist.
static int cbBGThreadRunning(NG_BOOL aFinished, int aId, void *aUser)
std::vector< double > GetGainVector(const std::string &aName, int aMaxLen=-1) override final
Return a requested vector with phase values.
bool Stop() override final
Check if simulation is running at the moment.
int(* ngSpice_Command)(char *command)
static bool m_initialized
Ngspice should be initialized only once.
static int cbSendStat(char *what, int aId, void *aUser)
static int cbSendChar(char *what, int aId, void *aUser)
std::vector< double > GetRealVector(const std::string &aName, int aMaxLen=-1) override final
Return a requested vector with imaginary values.
char *(* ngCM_Input_Path)(const char *path)
std::vector< std::string > GetSettingCommands() const override final
Return current SPICE netlist used by the simulator.
std::string m_netlist
Current netlist.
static void signalHandler(int aSignal)
ngSpice_AllVecs m_ngSpice_AllVecs
int(* ngSpice_UnlockRealloc)(void)
Handle to DLL functions.
pvector_info(* ngGet_Vec_Info)(char *vecname)
static std::atomic< int > s_crashSignal
Signal that caused the crash.
ngSpice_Running m_ngSpice_Running
void Clean() override final
Cleans simulation data (i.e.
bool(* ngSpice_Running)(void)
static NGSPICE * s_currentInstance
Instance that is currently running ngspice.
void Init(const SPICE_SETTINGS *aSettings=nullptr) override final
Point out the model that will be used in future simulations.
bool Attach(const std::shared_ptr< SIMULATION_MODEL > &aModel, const wxString &aSimCommand, unsigned aSimOptions, const wxString &aInputPath, REPORTER &aReporter) override final
Load a netlist for the simulation.
std::string findCmPath() const
Send additional search path for codemodels to ngspice.
void installSignalHandlers()
bool loadCodemodels(const std::string &aPath)
std::vector< COMPLEX > GetComplexVector(const std::string &aName, int aMaxLen=-1) override final
Return a requested vector with real values.
A pure virtual class used to derive REPORTER objects from.
Interface to receive simulation updates from SPICE_SIMULATOR class.
virtual bool Attach(const std::shared_ptr< SIMULATION_MODEL > &aModel, const wxString &aSimCommand, unsigned aSimOptions, const wxString &aInputPath, REPORTER &aReporter)
Point out the model that will be used in future simulations.
Special netlist exporter flavor that allows one to override simulation commands.
Storage for simulator specific settings.
std::shared_ptr< SPICE_SETTINGS > & Settings()
Return the simulator configuration settings.
std::atomic< SIMULATOR_REPORTER * > m_reporter
< Reporter object to receive simulation log (not owned, accessed from BG threads).
std::mutex m_reporterMutex
We don't own this. We are just borrowing it from the SCHEMATIC_SETTINGS.
static const wxChar *const traceNgspice
Flag to enable debug output of Ngspice simulator.
static struct sigaction s_oldSigSegv
static bool s_signalHandlersInstalled
static struct sigaction s_oldSigFpe
static pthread_t s_mainThread
static struct sigaction s_oldSigAbrt
SIM_TYPE
< Possible simulation types
IbisParser parser & reporter
wxString result
Test unit parsing edge cases and error handling.