KiCad PCB EDA Suite
Loading...
Searching...
No Matches
spice/test_netlist_exporter_spice.h
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) 2023 KiCad Developers, see AUTHORS.TXT for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, you may find one here:
18 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19 * or you may search the http://www.gnu.org website for the version 2 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
25#include <boost/test/results_collector.hpp> // To check if the current test failed (to be moved?).
26#include <eeschema_test_utils.h>
28#include <sim/ngspice.h>
30#include <wx/ffile.h>
31#include <mock_pgm_base.h>
32#include <locale_io.h>
33
34// A relative max error accepted when comparing 2 values
35#define MAX_DEFAULT_REL_ERROR 2e-2
36
37
38class TEST_NETLIST_EXPORTER_SPICE_FIXTURE : public TEST_NETLIST_EXPORTER_FIXTURE<NETLIST_EXPORTER_SPICE>
39{
40public:
41 class SPICE_TEST_REPORTER : public SIMULATOR_REPORTER
42 {
43 public:
44 SPICE_TEST_REPORTER( std::shared_ptr<wxString> aLog ) :
45 m_log( std::move( aLog ) )
46 {}
47
48 REPORTER& Report( const wxString& aText,
49 SEVERITY aSeverity = RPT_SEVERITY_UNDEFINED ) override
50 {
51 *m_log << aText << "\n";
52
53 // You can add a debug trace here.
54 return *this;
55 }
56
57 bool HasMessage() const override { return false; }
58
59 void OnSimStateChange( SIMULATOR* aObject, SIM_STATE aNewState ) override { }
60
61 private:
62 std::shared_ptr<wxString> m_log;
63 };
64
67 m_simulator( SPICE_SIMULATOR::CreateInstance( "ngspice" ) ),
68 m_log( std::make_shared<wxString>() ),
69 m_reporter( std::make_unique<SPICE_TEST_REPORTER>( m_log ) ),
70 m_abort( false )
71 {
72 }
73
75 {
76 using namespace boost::unit_test;
77
78 test_case::id_t id = framework::current_test_case().p_id;
79 test_results results = results_collector.results( id );
80
81 // Output a log if the test has failed.
82 BOOST_CHECK_MESSAGE( results.passed(), "\nNGSPICE LOG\n===========\n" << *m_log );
83 }
84
85 wxFileName GetSchematicPath( const wxString& aBaseName ) override
86 {
87 wxFileName fn( KI_TEST::GetEeschemaTestDataDir() );
88 fn.AppendDir( "spice_netlists" );
89 fn.AppendDir( aBaseName );
90 fn.SetName( aBaseName );
92
93 return fn;
94 }
95
96 wxString GetNetlistPath( bool aTest = false ) override
97 {
98 wxFileName netFile = m_schematic.Prj().GetProjectFullName();
99
100 if( aTest )
101 netFile.SetName( netFile.GetName() + "_test" );
102
103 netFile.SetExt( "spice" );
104 return netFile.GetFullPath();
105 }
106
107 void CompareNetlists() override
108 {
109 m_abort = false;
110
111 // Our simulator is actually Ngspice.
112 NGSPICE* ngspice = dynamic_cast<NGSPICE*>( m_simulator.get() );
113 BOOST_REQUIRE( ngspice );
114
115 ngspice->SetReporter( m_reporter.get() );
116
117 wxFFile file( GetNetlistPath( true ), "rt" );
118 wxString netlist;
119
120 file.ReadAll( &netlist );
121
122 //ngspice->Init();
123 ngspice->Command( "set ngbehavior=ps" );
124 ngspice->Command( "setseed 1" );
125 BOOST_REQUIRE( ngspice->LoadNetlist( std::string( netlist.ToUTF8() ) ) );
126
127 if( ngspice->Run() )
128 {
129 // wait for end of simulation.
130 // calling wxYield() allows printing activity, and stopping ngspice from GUI
131 // Also note: do not user wxSafeYield, because when using it we cannot stop
132 // ngspice from the GUI
133 do
134 {
135 wxMilliSleep( 50 );
136 wxYield();
137 } while( ngspice->IsRunning() );
138 }
139
140 // Test if ngspice cannot run a simulation (missing code models).
141 // in this case the log contains "MIF-ERROR" and/or "Error: circuit not parsed"
142 // when the simulation is not run the spice command "linearize" crashes.
143 bool mif_error = m_log->Find( wxT( "MIF-ERROR" ) ) != wxNOT_FOUND;
144
145 BOOST_TEST_INFO( "Cannot run ngspice. test skipped. Missing code model files?" );
146 BOOST_CHECK( !mif_error );
147
148 bool err_found = m_log->Find( wxT( "Error: circuit not parsed" ) ) != wxNOT_FOUND;
149
150 BOOST_TEST_INFO( "Cannot run ngspice. test skipped. Install error?" );
151 BOOST_CHECK( !err_found );
152
153 if( mif_error || err_found )
154 {
155 m_abort = true;
156
157 // Still display the original netlist in this case.
158 *m_log << "Original Netlist\n";
159 *m_log << "----------------\n";
160 *m_log << netlist << "\n";
161
162 return;
163 }
164
165 // We need to make sure that the number of points always the same.
166 ngspice->Command( "linearize" );
167
168
169 // Debug info.
170
171 // Display all vectors.
172 *m_log << "\n";
173 ngspice->Command( "echo Available Vectors" );
174 ngspice->Command( "echo -----------------" );
175 ngspice->Command( "display" );
176
177 // Display the original netlist.
178 *m_log << "\n";
179 *m_log << "Original Netlist\n";
180 *m_log << "----------------\n";
181 *m_log << netlist << "\n";
182
183 // Display the expanded netlist.
184 ngspice->Command( "echo Expanded Netlist" );
185 ngspice->Command( "echo ----------------" );
186 ngspice->Command( "listing runnable" );
187 }
188
189 void TestOpPoint( double aRefValue, const std::string& aVectorName,
190 double aMaxRelError = MAX_DEFAULT_REL_ERROR )
191 {
192 BOOST_TEST_CONTEXT( "Vector name: " << aVectorName )
193 {
194 NGSPICE* ngspice = static_cast<NGSPICE*>( m_simulator.get() );
195
196 std::vector<double> vector = ngspice->GetRealVector( aVectorName );
197
198 BOOST_REQUIRE_EQUAL( vector.size(), 1 );
199
200 double maxError = abs( aRefValue * aMaxRelError );
201 BOOST_CHECK_LE( abs( vector[0] - aRefValue ), aMaxRelError );
202 }
203 }
204
205 void TestPoint( const std::string& aXVectorName, double aXValue,
206 const std::map<const std::string, double> aTestVectorsAndValues,
207 double aMaxRelError = MAX_DEFAULT_REL_ERROR )
208 {
209 // The default aMaxRelError is fairly large because we have some problems with determinism
210 // in QA pipeline. We don't need to fix this for now because, if this has to be fixed in
211 // the first place, this has to be done from Ngspice's side.
212
213 BOOST_TEST_CONTEXT( "X vector name: " << aXVectorName << ", X value: " << aXValue )
214 {
215 NGSPICE* ngspice = static_cast<NGSPICE*>( m_simulator.get() );
216
217 std::vector<double> xVector = ngspice->GetRealVector( aXVectorName );
218 std::size_t i = 0;
219
220 for(; i < xVector.size(); ++i )
221 {
222 double inf = std::numeric_limits<double>::infinity();
223
224 double leftDelta = ( aXValue - ( i >= 1 ? xVector[i - 1] : -inf ) );
225 double middleDelta = ( aXValue - xVector[i] );
226 double rightDelta = ( aXValue - ( i < xVector.size() - 1 ? xVector[i + 1] : inf ) );
227
228 // Check if this point is the closest one.
229 if( abs( middleDelta ) <= abs( leftDelta )
230 && abs( middleDelta ) <= abs( rightDelta ) )
231 {
232 break;
233 }
234 }
235
236 BOOST_REQUIRE_LT( i, xVector.size() );
237
238 for( auto& [vectorName, refValue] : aTestVectorsAndValues )
239 {
240 std::vector<double> yVector = ngspice->GetGainVector( vectorName );
241
242 BOOST_REQUIRE_GE( yVector.size(), i + 1 );
243
244 BOOST_TEST_CONTEXT( "Y vector name: " << vectorName
245 << ", Ref value: " << refValue
246 << ", Actual value: " << yVector[i] )
247 {
248 double maxError = abs( refValue * aMaxRelError );
249
250 if( maxError == 0 )
251 {
252 // If refValue is 0, we need a obtain the max. error differently.
253 maxError = aMaxRelError;
254 }
255
256 BOOST_CHECK_LE( abs( yVector[i] - refValue ), maxError );
257 }
258 }
259 }
260 }
261
262 void TestTranPoint( double aTime,
263 const std::map<const std::string, double> aTestVectorsAndValues,
264 double aMaxRelError = MAX_DEFAULT_REL_ERROR )
265 {
266 TestPoint( "time", aTime, aTestVectorsAndValues, aMaxRelError );
267 }
268
269 void TestACPoint( double aFrequency,
270 const std::map<const std::string, double> aTestVectorsAndValues,
271 double aMaxRelError = MAX_DEFAULT_REL_ERROR )
272 {
273 TestPoint( "frequency", aFrequency, aTestVectorsAndValues, aMaxRelError );
274 }
275
276 wxString GetResultsPath( bool aTest = false )
277 {
278 wxFileName netlistPath( GetNetlistPath( aTest ) );
279 netlistPath.SetExt( "csv" );
280
281 return netlistPath.GetFullPath();
282 }
283
284 unsigned GetNetlistOptions() override
285 {
291 }
292
293 std::shared_ptr<SPICE_SIMULATOR> m_simulator;
294 std::shared_ptr<wxString> m_log;
295 std::unique_ptr<SPICE_TEST_REPORTER> m_reporter;
296 bool m_abort; // set to true to force abort durint a test
297};
bool Command(const std::string &aCmd) override final
Set a SIMULATOR_REPORTER object to receive the simulation log.
Definition: ngspice.cpp:346
bool IsRunning() override final
Execute a Spice command as if it was typed into console.
Definition: ngspice.cpp:339
bool Run() override final
Halt the simulation.
Definition: ngspice.cpp:325
bool LoadNetlist(const std::string &aNetlist) override final
Execute the simulation with currently loaded netlist.
Definition: ngspice.cpp:297
std::vector< double > GetGainVector(const std::string &aName, int aMaxLen=-1) override final
Return a requested vector with phase values.
Definition: ngspice.cpp:216
std::vector< double > GetRealVector(const std::string &aName, int aMaxLen=-1) override final
Return a requested vector with imaginary values.
Definition: ngspice.cpp:158
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition: project.cpp:129
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:71
PROJECT & Prj() const override
Return a reference to the project this schematic is part of.
Definition: schematic.h:90
Interface to receive simulation updates from SPICE_SIMULATOR class.
virtual void SetReporter(SIMULATOR_REPORTER *aReporter)
bool HasMessage() const override
Returns true if the reporter client is non-empty.
void OnSimStateChange(SIMULATOR *aObject, SIM_STATE aNewState) override
REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED) override
Report a string with a given severity.
std::unique_ptr< SPICE_TEST_REPORTER > m_reporter
void TestOpPoint(double aRefValue, const std::string &aVectorName, double aMaxRelError=MAX_DEFAULT_REL_ERROR)
void TestPoint(const std::string &aXVectorName, double aXValue, const std::map< const std::string, double > aTestVectorsAndValues, double aMaxRelError=MAX_DEFAULT_REL_ERROR)
wxFileName GetSchematicPath(const wxString &aBaseName) override
void TestTranPoint(double aTime, const std::map< const std::string, double > aTestVectorsAndValues, double aMaxRelError=MAX_DEFAULT_REL_ERROR)
void TestACPoint(double aFrequency, const std::map< const std::string, double > aTestVectorsAndValues, double aMaxRelError=MAX_DEFAULT_REL_ERROR)
wxString GetNetlistPath(bool aTest=false) override
static const std::string KiCadSchematicFileExtension
std::string GetEeschemaTestDataDir()
Get the configured location of Eeschema test data.
STL namespace.
SEVERITY
@ RPT_SEVERITY_UNDEFINED
#define MAX_DEFAULT_REL_ERROR
BOOST_CHECK(box.ClosestPointTo(VECTOR2D(0, 0))==VECTOR2D(1, 2))
Test suite for KiCad math code.
#define BOOST_TEST_CONTEXT(A)
#define BOOST_TEST_INFO(A)
If HAVE_EXPECTED_FAILURES is defined, this means that boost::unit_test::expected_failures is availabl...