KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sim_lib_mgr.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2022 Mikolaj Wielgus
5 * Copyright (C) 2022-2024 KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 3
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, you may find one here:
19 * https://www.gnu.org/licenses/gpl-3.0.html
20 * or you may search the http://www.gnu.org website for the version 3 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
25#include <pgm_base.h>
26#include <string>
27#include <string_utils.h>
28#include <common.h>
29#include <functional>
30#include <sch_symbol.h>
31
32// Include simulator headers after wxWidgets headers to avoid conflicts with Windows headers
33// (especially on msys2 + wxWidgets 3.0.x)
34#include <sim/sim_lib_mgr.h>
35#include <sim/sim_library.h>
36#include <sim/sim_model.h>
37#include <sim/sim_model_ideal.h>
38
39using namespace std::placeholders;
40
41
43 m_project( aPrj ),
44 m_forceFullParse( false )
45{
46}
47
48
50{
51 m_libraries.clear();
52 m_models.clear();
53}
54
55
56wxString SIM_LIB_MGR::ResolveLibraryPath( const wxString& aLibraryPath, const PROJECT* aProject )
57{
58 wxString expandedPath = ExpandEnvVarSubstitutions( aLibraryPath, aProject );
59
60 // Convert it to UNIX format
61 expandedPath.Replace( '\\', '/' );
62
63 wxFileName fn( expandedPath );
64
65 if( fn.IsAbsolute() )
66 return fn.GetFullPath();
67
68 wxFileName projectFn( aProject ? aProject->AbsolutePath( expandedPath ) : expandedPath );
69
70 if( projectFn.Exists() )
71 return projectFn.GetFullPath();
72
73 wxFileName spiceLibFn( expandedPath );
74 wxString spiceLibDir;
75
76 wxGetEnv( wxT( "SPICE_LIB_DIR" ), &spiceLibDir );
77
78 if( !spiceLibDir.IsEmpty() && spiceLibFn.MakeAbsolute( spiceLibDir ) && spiceLibFn.Exists() )
79 return spiceLibFn.GetFullPath();
80
81 if( spiceLibDir.IsEmpty() || spiceLibFn.GetFullPath() == projectFn.GetFullPath() )
82 {
83 THROW_IO_ERROR( wxString::Format( _( "Simulation model library not found at '%s'" ),
84 projectFn.GetFullPath() ) );
85 }
86 else
87 {
88 THROW_IO_ERROR( wxString::Format( _( "Simulation model library not found at '%s' or '%s'" ),
89 projectFn.GetFullPath(),
90 spiceLibFn.GetFullPath() ) );
91 }
92}
93
94
95wxString SIM_LIB_MGR::ResolveEmbeddedLibraryPath( const wxString& aLibPath,
96 const wxString& aRelativeLib )
97{
98 wxFileName testPath( aLibPath );
99 wxString fullPath( aLibPath );
100
101 if( !testPath.IsAbsolute() && !aRelativeLib.empty() )
102 {
103 wxString relLib( aRelativeLib );
104
105 try
106 {
107 relLib = ResolveLibraryPath( relLib, m_project );
108 }
109 catch( ... )
110 {}
111
112 wxFileName fn( relLib );
113
114 testPath.MakeAbsolute( fn.GetPath( true ) );
115 fullPath = testPath.GetFullPath();
116 }
117
118 try
119 {
120 wxFileName fn( fullPath );
121
122 if( !fn.Exists() )
123 fullPath = aLibPath;
124
125 fullPath = ResolveLibraryPath( fullPath, m_project );
126 }
127 catch( ... )
128 {}
129
130 return fullPath;
131}
132
133
134void SIM_LIB_MGR::SetLibrary( const wxString& aLibraryPath, REPORTER& aReporter )
135{
136 try
137 {
138 wxString path = ResolveLibraryPath( aLibraryPath, m_project );
139
140 std::function<wxString(const wxString&, const wxString&)> f2 =
141 std::bind( &SIM_LIB_MGR::ResolveEmbeddedLibraryPath, this, _1, _2 );
142
143 std::unique_ptr<SIM_LIBRARY> library = SIM_LIBRARY::Create( path, m_forceFullParse,
144 aReporter, &f2 );
145
146 Clear();
147 m_libraries[path] = std::move( library );
148 }
149 catch( const IO_ERROR& e )
150 {
151 aReporter.Report( e.What() );
152 }
153}
154
155
156SIM_MODEL& SIM_LIB_MGR::CreateModel( SIM_MODEL::TYPE aType, const std::vector<SCH_PIN*>& aPins,
157 REPORTER& aReporter )
158{
159 m_models.push_back( SIM_MODEL::Create( aType, aPins, aReporter ) );
160 return *m_models.back();
161}
162
163
165 const std::vector<SCH_PIN*>& aPins, REPORTER& aReporter )
166{
167 m_models.push_back( SIM_MODEL::Create( aBaseModel, aPins, aReporter ) );
168 return *m_models.back();
169}
170
171
173 const std::vector<SCH_PIN*>& aPins,
174 const std::vector<SCH_FIELD>& aFields, REPORTER& aReporter )
175{
176 m_models.push_back( SIM_MODEL::Create( aBaseModel, aPins, aFields, aReporter ) );
177 return *m_models.back();
178}
179
181 REPORTER& aReporter )
182{
183 // Note: currently this creates a resolved model (all Kicad variables references are resolved
184 // before building the model).
185 //
186 // That's not what we want if this is ever called from the Simulation Model Editor (or other
187 // editors, but it is what we want if called to generate a netlist or other exported items.
188
189
190 std::vector<SCH_FIELD> fields;
191
192 for( const SCH_FIELD& field : aSymbol.GetFields() )
193 {
194 if( field.GetId() == REFERENCE_FIELD )
195 {
196 fields.emplace_back( VECTOR2I(), -1, &aSymbol, field.GetName() );
197 fields.back().SetText( aSymbol.GetRef( aSheetPath ) );
198 }
199 else if( field.GetId() == VALUE_FIELD
200 || field.GetName().StartsWith( wxS( "Sim." ) ) )
201 {
202 fields.emplace_back( VECTOR2I(), -1, &aSymbol, field.GetName() );
203 fields.back().SetText( field.GetShownText( aSheetPath, false ) );
204 }
205 }
206
207 wxString deviceType;
208 wxString modelType;
209 wxString modelParams;
210 wxString pinMap;
211 bool storeInValue = false;
212
213 // Infer RLC and VI models if they aren't specified
215 &deviceType, &modelType, &modelParams, &pinMap ) )
216 {
217 fields.emplace_back( &aSymbol, -1, SIM_DEVICE_FIELD );
218 fields.back().SetText( deviceType );
219
220 if( !modelType.IsEmpty() )
221 {
222 fields.emplace_back( &aSymbol, -1, SIM_DEVICE_SUBTYPE_FIELD );
223 fields.back().SetText( modelType );
224 }
225
226 fields.emplace_back( &aSymbol, -1, SIM_PARAMS_FIELD );
227 fields.back().SetText( modelParams );
228
229 fields.emplace_back( &aSymbol, -1, SIM_PINS_FIELD );
230 fields.back().SetText( pinMap );
231
232 storeInValue = true;
233 }
234
235 std::vector<SCH_PIN*> sourcePins = aSymbol.GetAllLibPins();
236
237 std::sort( sourcePins.begin(), sourcePins.end(),
238 []( const SCH_PIN* lhs, const SCH_PIN* rhs )
239 {
240 return StrNumCmp( lhs->GetNumber(), rhs->GetNumber(), true ) < 0;
241 } );
242
243 SIM_LIBRARY::MODEL model = CreateModel( fields, sourcePins, true, aReporter );
244
245 model.model.SetIsStoredInValue( storeInValue );
246
247 return model;
248}
249
250
251SIM_LIBRARY::MODEL SIM_LIB_MGR::CreateModel( const std::vector<SCH_FIELD>& aFields,
252 const std::vector<SCH_PIN*>& aPins, bool aResolved,
253 REPORTER& aReporter )
254{
255 std::string libraryPath = SIM_MODEL::GetFieldValue( &aFields, SIM_LIBRARY::LIBRARY_FIELD );
256 std::string baseModelName = SIM_MODEL::GetFieldValue( &aFields, SIM_LIBRARY::NAME_FIELD );
257
258 if( libraryPath != "" )
259 {
260 return CreateModel( libraryPath, baseModelName, aFields, aPins, aReporter );
261 }
262 else
263 {
264 m_models.push_back( SIM_MODEL::Create( aFields, aPins, aResolved, aReporter ) );
265 return { baseModelName, *m_models.back() };
266 }
267}
268
269
270SIM_LIBRARY::MODEL SIM_LIB_MGR::CreateModel( const wxString& aLibraryPath,
271 const std::string& aBaseModelName,
272 const std::vector<SCH_FIELD>& aFields,
273 const std::vector<SCH_PIN*>& aPins,
274 REPORTER& aReporter )
275{
276 wxString path;
277 wxString msg;
278 SIM_LIBRARY* library = nullptr;
279 SIM_MODEL* baseModel = nullptr;
280 std::string modelName;
281
282 try
283 {
284 path = ResolveLibraryPath( aLibraryPath, m_project );
285
286 auto it = m_libraries.find( path );
287
288 if( it == m_libraries.end() )
289 {
290 std::function<wxString( const wxString&, const wxString& )> f2 =
291 std::bind( &SIM_LIB_MGR::ResolveEmbeddedLibraryPath, this, _1, _2 );
292
294 aReporter, &f2 ) ).first;
295 }
296
297 library = &*it->second;
298 }
299 catch( const IO_ERROR& e )
300 {
301 msg.Printf( _( "Error loading simulation model library '%s': %s" ),
302 path,
303 e.What() );
304
305 aReporter.Report( msg, RPT_SEVERITY_ERROR );
306 }
307
308 if( aBaseModelName == "" )
309 {
310 msg.Printf( _( "Error loading simulation model: no '%s' field" ),
312
313 aReporter.Report( msg, RPT_SEVERITY_ERROR );
314
315 modelName = _( "unknown" ).ToStdString();
316 }
317 else if( library )
318 {
319 baseModel = library->FindModel( aBaseModelName );
320 modelName = aBaseModelName;
321
322 if( !baseModel )
323 {
324 msg.Printf( _( "Error loading simulation model: could not find base model '%s' "
325 "in library '%s'" ),
326 aBaseModelName,
327 path );
328
329 aReporter.Report( msg, RPT_SEVERITY_ERROR );
330 }
331 }
332
333 m_models.push_back( SIM_MODEL::Create( baseModel, aPins, aFields, aReporter ) );
334
335 return { modelName, *m_models.back() };
336}
337
338
339void SIM_LIB_MGR::SetModel( int aIndex, std::unique_ptr<SIM_MODEL> aModel )
340{
341 m_models.at( aIndex ) = std::move( aModel );
342}
343
344
345std::map<wxString, std::reference_wrapper<const SIM_LIBRARY>> SIM_LIB_MGR::GetLibraries() const
346{
347 std::map<wxString, std::reference_wrapper<const SIM_LIBRARY>> libraries;
348
349 for( auto& [path, library] : m_libraries )
350 libraries.try_emplace( path, *library );
351
352 return libraries;
353}
354
355
356std::vector<std::reference_wrapper<SIM_MODEL>> SIM_LIB_MGR::GetModels() const
357{
358 std::vector<std::reference_wrapper<SIM_MODEL>> models;
359
360 for( const std::unique_ptr<SIM_MODEL>& model : m_models )
361 models.emplace_back( *model );
362
363 return models;
364}
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
Definition: ki_exception.h:77
virtual const wxString What() const
A composite of Problem() and Where()
Definition: exceptions.cpp:30
Container for project specific data.
Definition: project.h:62
virtual const wxString AbsolutePath(const wxString &aFileName) const
Fix up aFileName if it is relative to the project's directory to be an absolute path and filename.
Definition: project.cpp:320
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:71
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Report a string with a given severity.
Instances are attached to a symbol or sheet and provide a place for the symbol's value,...
Definition: sch_field.h:51
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
Schematic symbol object.
Definition: sch_symbol.h:108
std::vector< SCH_PIN * > GetAllLibPins() const
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly)
Populate a std::vector with SCH_FIELDs.
Definition: sch_symbol.cpp:958
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
Definition: sch_symbol.cpp:711
static std::unique_ptr< SIM_LIBRARY > Create(const wxString &aFilePath, bool aForceFullParse, REPORTER &aReporter, std::function< wxString(const wxString &, const wxString &)> *aResolver)
Read library from a source file (e.g.
Definition: sim_library.cpp:33
static constexpr auto LIBRARY_FIELD
Definition: sim_library.h:35
static constexpr auto NAME_FIELD
Definition: sim_library.h:36
void SetModel(int aIndex, std::unique_ptr< SIM_MODEL > aModel)
wxString ResolveEmbeddedLibraryPath(const wxString &aLibPath, const wxString &aRelativeLib)
Definition: sim_lib_mgr.cpp:95
const PROJECT * m_project
Definition: sim_lib_mgr.h:81
bool m_forceFullParse
Definition: sim_lib_mgr.h:82
SIM_MODEL & CreateModel(SIM_MODEL::TYPE aType, const std::vector< SCH_PIN * > &aPins, REPORTER &aReporter)
SIM_LIB_MGR(const PROJECT *aPrj)
Definition: sim_lib_mgr.cpp:42
std::vector< std::unique_ptr< SIM_MODEL > > m_models
Definition: sim_lib_mgr.h:84
static wxString ResolveLibraryPath(const wxString &aLibraryPath, const PROJECT *aProject)
Definition: sim_lib_mgr.cpp:56
std::map< wxString, std::reference_wrapper< const SIM_LIBRARY > > GetLibraries() const
std::vector< std::reference_wrapper< SIM_MODEL > > GetModels() const
void Clear()
Definition: sim_lib_mgr.cpp:49
void SetLibrary(const wxString &aLibraryPath, REPORTER &aReporter)
std::map< wxString, std::unique_ptr< SIM_LIBRARY > > m_libraries
Definition: sim_lib_mgr.h:83
static bool InferSimModel(T &aSymbol, std::vector< SCH_FIELD > *aFields, bool aResolve, SIM_VALUE_GRAMMAR::NOTATION aNotation, wxString *aDeviceType, wxString *aModelType, wxString *aModelParams, wxString *aPinMap)
Definition: sim_model.cpp:1063
static std::string GetFieldValue(const std::vector< SCH_FIELD > *aFields, const wxString &aFieldName, bool aResolve=true)
Definition: sim_model.cpp:645
static std::unique_ptr< SIM_MODEL > Create(TYPE aType, const std::vector< SCH_PIN * > &aPins, REPORTER &aReporter)
Definition: sim_model.cpp:492
void SetIsStoredInValue(bool aIsStoredInValue)
Definition: sim_model.h:507
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:334
The common library.
#define _(s)
#define THROW_IO_ERROR(msg)
Definition: ki_exception.h:39
see class PGM_BASE
@ RPT_SEVERITY_ERROR
#define SIM_PINS_FIELD
Definition: sim_model.h:54
#define SIM_DEVICE_FIELD
Definition: sim_model.h:52
#define SIM_PARAMS_FIELD
Definition: sim_model.h:55
#define SIM_DEVICE_SUBTYPE_FIELD
Definition: sim_model.h:53
SIM_MODEL & model
Definition: sim_library.h:41
@ VALUE_FIELD
Field Value of part, i.e. "3.3K".
@ REFERENCE_FIELD
Field Reference of part, i.e. "IC21".
VECTOR2< int > VECTOR2I
Definition: vector2d.h:588