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 auto getOrCreateField =
208 [&aSymbol, &fields]( const wxString& name ) -> SCH_FIELD*
209 {
210 for( SCH_FIELD& field : fields )
211 {
212 if( field.GetName().IsSameAs( name ) )
213 return &field;
214 }
215
216 fields.emplace_back( &aSymbol, -1, name );
217 return &fields.back();
218 };
219
220 wxString deviceType;
221 wxString modelType;
222 wxString modelParams;
223 wxString pinMap;
224 bool storeInValue = false;
225
226 // Infer RLC and VI models if they aren't specified
228 &deviceType, &modelType, &modelParams, &pinMap ) )
229 {
230 getOrCreateField( SIM_DEVICE_FIELD )->SetText( deviceType );
231
232 if( !modelType.IsEmpty() )
233 getOrCreateField( SIM_DEVICE_SUBTYPE_FIELD )->SetText( modelType );
234
235 getOrCreateField( SIM_PARAMS_FIELD )->SetText( modelParams );
236 getOrCreateField( SIM_PINS_FIELD )->SetText( pinMap );
237
238 storeInValue = true;
239 }
240
241 std::vector<SCH_PIN*> sourcePins = aSymbol.GetAllLibPins();
242
243 std::sort( sourcePins.begin(), sourcePins.end(),
244 []( const SCH_PIN* lhs, const SCH_PIN* rhs )
245 {
246 return StrNumCmp( lhs->GetNumber(), rhs->GetNumber(), true ) < 0;
247 } );
248
249 SIM_LIBRARY::MODEL model = CreateModel( fields, sourcePins, true, aReporter );
250
251 model.model.SetIsStoredInValue( storeInValue );
252
253 return model;
254}
255
256
257SIM_LIBRARY::MODEL SIM_LIB_MGR::CreateModel( const std::vector<SCH_FIELD>& aFields,
258 const std::vector<SCH_PIN*>& aPins, bool aResolved,
259 REPORTER& aReporter )
260{
261 std::string libraryPath = SIM_MODEL::GetFieldValue( &aFields, SIM_LIBRARY::LIBRARY_FIELD );
262 std::string baseModelName = SIM_MODEL::GetFieldValue( &aFields, SIM_LIBRARY::NAME_FIELD );
263
264 if( libraryPath != "" )
265 {
266 return CreateModel( libraryPath, baseModelName, aFields, aPins, aReporter );
267 }
268 else
269 {
270 m_models.push_back( SIM_MODEL::Create( aFields, aPins, aResolved, aReporter ) );
271 return { baseModelName, *m_models.back() };
272 }
273}
274
275
276SIM_LIBRARY::MODEL SIM_LIB_MGR::CreateModel( const wxString& aLibraryPath,
277 const std::string& aBaseModelName,
278 const std::vector<SCH_FIELD>& aFields,
279 const std::vector<SCH_PIN*>& aPins,
280 REPORTER& aReporter )
281{
282 wxString path;
283 wxString msg;
284 SIM_LIBRARY* library = nullptr;
285 SIM_MODEL* baseModel = nullptr;
286 std::string modelName;
287
288 try
289 {
290 path = ResolveLibraryPath( aLibraryPath, m_project );
291
292 auto it = m_libraries.find( path );
293
294 if( it == m_libraries.end() )
295 {
296 std::function<wxString( const wxString&, const wxString& )> f2 =
297 std::bind( &SIM_LIB_MGR::ResolveEmbeddedLibraryPath, this, _1, _2 );
298
300 aReporter, &f2 ) ).first;
301 }
302
303 library = &*it->second;
304 }
305 catch( const IO_ERROR& e )
306 {
307 msg.Printf( _( "Error loading simulation model library '%s': %s" ),
308 path,
309 e.What() );
310
311 aReporter.Report( msg, RPT_SEVERITY_ERROR );
312 }
313
314 if( aBaseModelName == "" )
315 {
316 msg.Printf( _( "Error loading simulation model: no '%s' field" ),
318
319 aReporter.Report( msg, RPT_SEVERITY_ERROR );
320
321 modelName = _( "unknown" ).ToStdString();
322 }
323 else if( library )
324 {
325 baseModel = library->FindModel( aBaseModelName );
326 modelName = aBaseModelName;
327
328 if( !baseModel )
329 {
330 msg.Printf( _( "Error loading simulation model: could not find base model '%s' "
331 "in library '%s'" ),
332 aBaseModelName,
333 path );
334
335 aReporter.Report( msg, RPT_SEVERITY_ERROR );
336 }
337 }
338
339 m_models.push_back( SIM_MODEL::Create( baseModel, aPins, aFields, aReporter ) );
340
341 return { modelName, *m_models.back() };
342}
343
344
345void SIM_LIB_MGR::SetModel( int aIndex, std::unique_ptr<SIM_MODEL> aModel )
346{
347 m_models.at( aIndex ) = std::move( aModel );
348}
349
350
351std::map<wxString, std::reference_wrapper<const SIM_LIBRARY>> SIM_LIB_MGR::GetLibraries() const
352{
353 std::map<wxString, std::reference_wrapper<const SIM_LIBRARY>> libraries;
354
355 for( auto& [path, library] : m_libraries )
356 libraries.try_emplace( path, *library );
357
358 return libraries;
359}
360
361
362std::vector<std::reference_wrapper<SIM_MODEL>> SIM_LIB_MGR::GetModels() const
363{
364 std::vector<std::reference_wrapper<SIM_MODEL>> models;
365
366 for( const std::unique_ptr<SIM_MODEL>& model : m_models )
367 models.emplace_back( *model );
368
369 return models;
370}
const char * name
Definition: DXF_plotter.cpp:57
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
void SetText(const wxString &aText) override
Definition: sch_field.cpp:1150
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:105
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:898
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
Definition: sch_symbol.cpp:651
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:1064
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:506
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< int32_t > VECTOR2I
Definition: vector2d.h:638