KiCad PCB EDA Suite
Loading...
Searching...
No Matches
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 The 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
39{
40public:
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 // Detach the reporter before m_reporter destructs. SetReporter blocks
79 // until any in-flight bg callback that holds the reporter has returned.
80 if( m_simulator )
81 m_simulator->SetReporter( nullptr );
82
83 test_case::id_t id = framework::current_test_case().p_id;
84 test_results results = results_collector.results( id );
85
86 // Output a log if the test has failed.
87 // Don't use BOOST_CHECK_MESSAGE because it triggers a checkpoint which affects debugging
88 if( !results.passed() )
89 {
90 BOOST_TEST_MESSAGE( "\nNGSPICE LOG\n===========\n" << *m_log );
91 }
92 }
93
94 wxFileName SchematicQAPath( const wxString& aBaseName ) override
95 {
96 wxFileName fn( KI_TEST::GetEeschemaTestDataDir() );
97 fn.AppendDir( "spice_netlists" );
98 fn.AppendDir( aBaseName );
99 fn.SetName( aBaseName );
101
102 return fn;
103 }
104
105 wxString GetNetlistPath( bool aTest = false ) override
106 {
107 wxFileName netFile = m_schematic->Project().GetProjectFullName();
108
109 if( aTest )
110 netFile.SetName( netFile.GetName() + "_test" );
111
112 netFile.SetExt( "spice" );
113 return netFile.GetFullPath();
114 }
115
116 void CompareNetlists() override
117 {
118 wxString netlistPath = GetNetlistPath( true );
119 BOOST_TEST_CHECKPOINT( "Comparing netlist " << netlistPath );
120
121 m_abort = false;
122
123 // Our simulator is actually Ngspice.
124 NGSPICE* ngspice = dynamic_cast<NGSPICE*>( m_simulator.get() );
125 BOOST_REQUIRE( ngspice );
126
127 ngspice->SetReporter( m_reporter.get() );
128
129 wxFFile file( netlistPath, "rt" );
130 wxString netlist;
131
132 BOOST_REQUIRE( file.IsOpened() );
133 file.ReadAll( &netlist );
134
135 //ngspice->Init();
136 ngspice->Command( "set ngbehavior=ps" );
137 ngspice->Command( "setseed 1" );
138 BOOST_REQUIRE( ngspice->LoadNetlist( std::string( netlist.ToUTF8() ) ) );
139
140 if( ngspice->Run() )
141 {
142 // wait for end of simulation.
143 // calling wxYield() allows printing activity, and stopping ngspice from GUI
144 // Also note: do not user wxSafeYield, because when using it we cannot stop
145 // ngspice from the GUI
146 do
147 {
148 wxMilliSleep( 50 );
149 wxYield();
150 } while( ngspice->IsRunning() );
151 }
152
153 // Detach the reporter while we read m_log on the main thread. m_ngSpice_Running
154 // can return false while a cbSendChar callback is still in flight, and that
155 // callback writes to *m_log. SetReporter(nullptr) blocks until the in-flight
156 // call returns.
157 ngspice->SetReporter( nullptr );
158
159 // Test if ngspice cannot run a simulation (missing code models).
160 // in this case the log contains "MIF-ERROR" and/or "Error: circuit not parsed"
161 // when the simulation is not run the spice command "linearize" crashes.
162 bool mif_error = m_log->Find( wxT( "MIF-ERROR" ) ) != wxNOT_FOUND;
163
164 BOOST_TEST_INFO( "Cannot run ngspice. test skipped. Missing code model files?" );
165 BOOST_CHECK( !mif_error );
166
167 bool err_found = m_log->Find( wxT( "Error: circuit not parsed" ) ) != wxNOT_FOUND;
168
169 // Re-attach so the rest of the foreground ngspice->Command calls below feed
170 // their output back into the log. These run on the main thread, so the
171 // cbSendChar callback fires synchronously and there's no concurrent reader.
172 ngspice->SetReporter( m_reporter.get() );
173
174 BOOST_TEST_INFO( "Cannot run ngspice. test skipped. Install error?" );
175 BOOST_CHECK( !err_found );
176
177 if( mif_error || err_found )
178 {
179 m_abort = true;
180
181 // Still display the original netlist in this case.
182 *m_log << "Original Netlist\n";
183 *m_log << "----------------\n";
184 *m_log << netlist << "\n";
185
186 return;
187 }
188
189 // We need to make sure that the number of points always the same.
190 ngspice->Command( "linearize" );
191
192
193 // Debug info.
194
195 // Display all vectors.
196 *m_log << "\n";
197 ngspice->Command( "echo Available Vectors" );
198 ngspice->Command( "echo -----------------" );
199 ngspice->Command( "display" );
200
201 // Display the original netlist.
202 *m_log << "\n";
203 *m_log << "Original Netlist\n";
204 *m_log << "----------------\n";
205 *m_log << netlist << "\n";
206
207 // Display the expanded netlist.
208 ngspice->Command( "echo Expanded Netlist" );
209 ngspice->Command( "echo ----------------" );
210 ngspice->Command( "listing runnable" );
211 }
212
213 void TestOpPoint( double aRefValue, const std::string& aVectorName,
214 double aMaxRelError = MAX_DEFAULT_REL_ERROR )
215 {
216 BOOST_TEST_CONTEXT( "Vector name: " << aVectorName )
217 {
218 NGSPICE* ngspice = static_cast<NGSPICE*>( m_simulator.get() );
219
220 std::vector<double> vector = ngspice->GetRealVector( aVectorName );
221
222 BOOST_REQUIRE_EQUAL( vector.size(), 1 );
223
224 double maxError = abs( aRefValue * aMaxRelError );
225 BOOST_CHECK_LE( abs( vector[0] - aRefValue ), aMaxRelError );
226 }
227 }
228
229 void TestPoint( const std::string& aXVectorName, double aXValue,
230 const std::map<const std::string, double> aTestVectorsAndValues,
231 double aMaxRelError = MAX_DEFAULT_REL_ERROR )
232 {
233 // The default aMaxRelError is fairly large because we have some problems with determinism
234 // in QA pipeline. We don't need to fix this for now because, if this has to be fixed in
235 // the first place, this has to be done from Ngspice's side.
236
237 BOOST_TEST_CONTEXT( "X vector name: " << aXVectorName << ", X value: " << aXValue )
238 {
239 NGSPICE* ngspice = static_cast<NGSPICE*>( m_simulator.get() );
240
241 std::vector<double> xVector = ngspice->GetRealVector( aXVectorName );
242 std::size_t i = 0;
243
244 for(; i < xVector.size(); ++i )
245 {
246 double inf = std::numeric_limits<double>::infinity();
247
248 double leftDelta = ( aXValue - ( i >= 1 ? xVector[i - 1] : -inf ) );
249 double middleDelta = ( aXValue - xVector[i] );
250 double rightDelta = ( aXValue - ( i < xVector.size() - 1 ? xVector[i + 1] : inf ) );
251
252 // Check if this point is the closest one.
253 if( abs( middleDelta ) <= abs( leftDelta )
254 && abs( middleDelta ) <= abs( rightDelta ) )
255 {
256 break;
257 }
258 }
259
260 BOOST_REQUIRE_LT( i, xVector.size() );
261
262 for( auto& [vectorName, refValue] : aTestVectorsAndValues )
263 {
264 std::vector<double> yVector = ngspice->GetGainVector( vectorName );
265
266 BOOST_REQUIRE_GE( yVector.size(), i + 1 );
267
268 BOOST_TEST_CONTEXT( "Y vector name: " << vectorName
269 << ", Ref value: " << refValue
270 << ", Actual value: " << yVector[i] )
271 {
272 double maxError = abs( refValue * aMaxRelError );
273
274 if( maxError == 0 )
275 {
276 // If refValue is 0, we need a obtain the max. error differently.
277 maxError = aMaxRelError;
278 }
279
280 BOOST_CHECK_LE( abs( yVector[i] - refValue ), maxError );
281 }
282 }
283 }
284 }
285
286 void TestTranPoint( double aTime,
287 const std::map<const std::string, double> aTestVectorsAndValues,
288 double aMaxRelError = MAX_DEFAULT_REL_ERROR )
289 {
290 TestPoint( "time", aTime, aTestVectorsAndValues, aMaxRelError );
291 }
292
293 void TestACPoint( double aFrequency,
294 const std::map<const std::string, double> aTestVectorsAndValues,
295 double aMaxRelError = MAX_DEFAULT_REL_ERROR )
296 {
297 TestPoint( "frequency", aFrequency, aTestVectorsAndValues, aMaxRelError );
298 }
299
300 wxString GetResultsPath( bool aTest = false )
301 {
302 wxFileName netlistPath( GetNetlistPath( aTest ) );
303 netlistPath.SetExt( "csv" );
304
305 return netlistPath.GetFullPath();
306 }
307
317
318 std::shared_ptr<SPICE_SIMULATOR> m_simulator;
319 std::shared_ptr<wxString> m_log;
320 std::unique_ptr<SPICE_TEST_REPORTER> m_reporter;
321 bool m_abort; // set to true to force abort durint a test
322};
bool Command(const std::string &aCmd) override final
Definition ngspice.cpp:417
bool IsRunning() override final
Execute a Spice command as if it was typed into console.
Definition ngspice.cpp:374
bool Run() override final
Halt the simulation.
Definition ngspice.cpp:351
bool LoadNetlist(const std::string &aNetlist) override final
Execute the simulation with currently loaded netlist.
Definition ngspice.cpp:315
std::vector< double > GetGainVector(const std::string &aName, int aMaxLen=-1) override final
Return a requested vector with phase values.
Definition ngspice.cpp:225
std::vector< double > GetRealVector(const std::string &aName, int aMaxLen=-1) override final
Return a requested vector with imaginary values.
Definition ngspice.cpp:170
REPORTER()
Definition reporter.h:77
Interface to receive simulation updates from SPICE_SIMULATOR class.
virtual void SetReporter(SIMULATOR_REPORTER *aReporter)
Set a SIMULATOR_REPORTER object to receive the simulation log.
bool HasMessage() const override
Returns true if any messages were reported.
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::shared_ptr< SPICE_SIMULATOR > m_simulator
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 SchematicQAPath(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
std::unique_ptr< SPICE_TEST_REPORTER > m_reporter
static const std::string KiCadSchematicFileExtension
std::string GetEeschemaTestDataDir()
Get the configured location of Eeschema test data.
STL namespace.
SEVERITY
@ RPT_SEVERITY_UNDEFINED
BOOST_REQUIRE(intersection.has_value()==c.ExpectedIntersection.has_value())
BOOST_TEST_INFO("Parsed: "<< path)
#define MAX_DEFAULT_REL_ERROR
BOOST_TEST_MESSAGE("\n=== Real-World Polygon PIP Benchmark ===\n"<< formatTable(table))
BOOST_TEST_CONTEXT("Test Clearance")