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 The 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, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <filename_resolver.h>
22#include <pgm_base.h>
23#include <string>
24#include <string_utils.h>
25#include <common.h>
26#include <functional>
27#include <sch_symbol.h>
28#include <schematic.h>
29
30// Include simulator headers after wxWidgets headers to avoid conflicts with Windows headers
31// (especially on msys2 + wxWidgets 3.0.x)
32#include <sim/sim_lib_mgr.h>
33#include <sim/sim_library.h>
34#include <sim/sim_model.h>
35#include <sim/sim_model_ideal.h>
36
37using namespace std::placeholders;
38
39
41 m_project( aPrj ),
42 m_forceFullParse( false )
43{
44}
45
46
48{
49 m_libraries.clear();
50 m_models.clear();
51}
52
53
54wxString SIM_LIB_MGR::ResolveLibraryPath( const wxString& aLibraryPath, REPORTER& aReporter )
55{
56 FILENAME_RESOLVER resolver;
57
58 resolver.SetProject( m_project );
59
60 std::vector<const EMBEDDED_FILES*> embeddedFilesStack;
61
62 for( const EMBEDDED_FILES* embeddedFiles : m_embeddedFilesStack )
63 embeddedFilesStack.push_back( embeddedFiles );
64
65 wxString resolvedPath = resolver.ResolvePath( aLibraryPath, wxEmptyString, std::move( embeddedFilesStack ) );
66
67 // If FILENAME_RESOLVER found the file, use that result
68 if( !resolvedPath.IsEmpty() )
69 {
70 wxFileName fn( resolvedPath );
71
72 if( fn.IsAbsolute() )
73 return fn.GetFullPath();
74 }
75
76 // Fall back to the original behavior for paths not found by FILENAME_RESOLVER.
77 // First expand any environment variables in the path.
78 wxString expandedPath = ExpandEnvVarSubstitutions( aLibraryPath, m_project );
79
80 // Convert to UNIX format
81 expandedPath.Replace( '\\', '/' );
82
83 wxFileName fn( expandedPath );
84
85 if( fn.IsAbsolute() && fn.Exists() )
86 return fn.GetFullPath();
87
88 wxFileName projectFn( m_project ? m_project->AbsolutePath( expandedPath ) : expandedPath );
89
90 if( projectFn.Exists() )
91 return projectFn.GetFullPath();
92
93 // Check relative to SPICE_LIB_DIR environment variable
94 wxFileName spiceLibFn( expandedPath );
95 wxString spiceLibDir;
96
97 wxGetEnv( wxT( "SPICE_LIB_DIR" ), &spiceLibDir );
98
99 if( !spiceLibDir.IsEmpty() && spiceLibFn.MakeAbsolute( spiceLibDir ) && spiceLibFn.Exists() )
100 return spiceLibFn.GetFullPath();
101
102 if( spiceLibDir.IsEmpty() || spiceLibFn.GetFullPath() == projectFn.GetFullPath() )
103 {
104 aReporter.Report( wxString::Format( _( "Simulation model library not found at '%s'" ),
105 projectFn.GetFullPath() ) );
106 }
107 else
108 {
109 aReporter.Report( wxString::Format( _( "Simulation model library not found at '%s' or '%s'" ),
110 projectFn.GetFullPath(),
111 spiceLibFn.GetFullPath() ) );
112 }
113
114 return aLibraryPath;
115}
116
117
118wxString SIM_LIB_MGR::ResolveEmbeddedLibraryPath( const wxString& aLibPath,
119 const wxString& aRelativeLib,
120 REPORTER& aReporter )
121{
122 wxFileName testPath( aLibPath );
123 wxString fullPath( aLibPath );
124
125 if( !testPath.IsAbsolute() && !aRelativeLib.empty() )
126 {
127 wxString relLib( aRelativeLib );
128
129 relLib = ResolveLibraryPath( relLib, aReporter );
130
131 wxFileName fn( relLib );
132
133 testPath.MakeAbsolute( fn.GetPath( true ) );
134 fullPath = testPath.GetFullPath();
135 }
136
137 wxFileName fn( fullPath );
138
139 if( !fn.Exists() )
140 fullPath = aLibPath;
141
142 fullPath = ResolveLibraryPath( fullPath, aReporter );
143
144 return fullPath;
145}
146
147
148void SIM_LIB_MGR::SetLibrary( const wxString& aLibraryPath, REPORTER& aReporter )
149{
150 wxString path = ResolveLibraryPath( aLibraryPath, aReporter );
151
153 return;
154
155 if( !wxFileName::Exists( path ) )
156 {
157 aReporter.Report( wxString::Format( _( "Simulation model library not found at '%s'" ),
158 path ) );
159 return;
160 }
161
162 std::unique_ptr<SIM_LIBRARY> library = SIM_LIBRARY::Create( path, m_forceFullParse, aReporter,
163 [&]( const wxString& libPath, const wxString& relativeLib ) -> wxString
164 {
165 return ResolveEmbeddedLibraryPath( libPath, relativeLib, aReporter );
166 } );
167
168 Clear();
169 m_libraries[path] = std::move( library );
170}
171
172
173SIM_MODEL& SIM_LIB_MGR::CreateModel( SIM_MODEL::TYPE aType, std::span<const wxString> aPins,
174 REPORTER& aReporter )
175{
176 m_models.push_back( SIM_MODEL::Create( aType, aPins, aReporter ) );
177 return *m_models.back();
178}
179
180
182 std::span<const wxString> aPins, REPORTER& aReporter )
183{
184 m_models.push_back( SIM_MODEL::Create( aBaseModel, aPins, aReporter ) );
185 return *m_models.back();
186}
187
188
189SIM_MODEL& SIM_LIB_MGR::CreateModel( const SIM_MODEL* aBaseModel, std::span<const wxString> aPins,
190 const std::vector<SCH_FIELD>& aFields, bool aResolve, int aDepth,
191 REPORTER& aReporter )
192{
193 m_models.push_back( SIM_MODEL::Create( aBaseModel, aPins, aFields, aResolve, aDepth, aReporter ) );
194 return *m_models.back();
195}
196
197
199 int aDepth, const wxString& aVariantName,
200 const wxString& aMergedSimPins )
201{
202 SIM_MODEL_INPUT input;
203 input.prefix = aSymbol.GetPrefix();
204
205 for( const SCH_FIELD& field : aSymbol.GetFields() )
206 {
207 if( field.GetId() == FIELD_T::REFERENCE )
208 {
209 input.fields.emplace_back( field.GetName(), aSymbol.GetRef( aSheetPath ) );
210 }
211 else if( field.GetId() == FIELD_T::VALUE || field.GetName().StartsWith( wxS( "Sim." ) ) )
212 {
213 const wxString value = !aMergedSimPins.IsEmpty() && field.GetName() == SIM_PINS_FIELD
214 ? aMergedSimPins
215 : field.GetShownText( aSheetPath, FOR_NETNAME, aVariantName, aDepth );
216 input.fields.emplace_back( field.GetName(), value );
217 }
218 }
219
220 input.inferencePins = SIM_MODEL::PinNumbers( aSymbol.GetPins( aSheetPath ) );
221 std::sort( input.inferencePins.begin(), input.inferencePins.end() );
222 input.modelPins = SIM_MODEL::PinNumbers( aSymbol.GetAllLibPins() );
223 std::sort( input.modelPins.begin(), input.modelPins.end(),
224 []( const wxString& lhs, const wxString& rhs )
225 {
226 return StrNumCmp( lhs, rhs, CMP_T::IGNORE_CASE ) < 0;
227 } );
228 return input;
229}
230
231
233 bool aResolve, int aDepth, const wxString& aVariantName,
234 REPORTER& aReporter, const wxString& aMergedSimPins )
235{
236 return CreateModel( CaptureModelInput( aSheetPath, aSymbol, aDepth, aVariantName, aMergedSimPins ),
237 aResolve, aReporter );
238}
239
240
241SIM_LIBRARY::MODEL SIM_LIB_MGR::CreateModel( const SIM_MODEL_INPUT& aInput, bool aAllowRawFallback,
242 REPORTER& aReporter )
243{
244 std::vector<SCH_FIELD> fields;
245
246 for( const auto& [name, value] : aInput.fields )
247 {
248 fields.emplace_back( nullptr, FIELD_T::USER, name );
249 fields.back().SetText( value );
250 }
251
252 auto getOrCreateField =
253 [&fields]( const wxString& name ) -> SCH_FIELD*
254 {
255 if( SCH_FIELD* field = FindField( fields, name ) )
256 return field;
257
258 fields.emplace_back( nullptr, FIELD_T::USER, name );
259 return &fields.back();
260 };
261
262 wxString deviceType;
263 wxString modelType;
264 wxString modelParams;
265 wxString pinMap;
266 bool storeInValue = false;
267
268 // Infer RLC and VI models if they aren't specified
269 if( SIM_MODEL::InferSimModel( aInput.prefix, aInput.inferencePins, &fields, false, 0,
270 SIM_VALUE_GRAMMAR::NOTATION::SI, &deviceType, &modelType, &modelParams, &pinMap ) )
271 {
272 getOrCreateField( SIM_DEVICE_FIELD )->SetText( deviceType );
273
274 if( !modelType.IsEmpty() )
275 getOrCreateField( SIM_DEVICE_SUBTYPE_FIELD )->SetText( modelType );
276
277 getOrCreateField( SIM_PARAMS_FIELD )->SetText( modelParams );
278 getOrCreateField( SIM_PINS_FIELD )->SetText( pinMap );
279
280 storeInValue = true;
281 }
282
283 SIM_LIBRARY::MODEL model = createModel( fields, false, 0, aInput.modelPins, aReporter, aAllowRawFallback );
284
285 model.model.SetIsStoredInValue( storeInValue );
286
287 return model;
288}
289
290
291SIM_LIBRARY::MODEL SIM_LIB_MGR::CreateModel( const std::vector<SCH_FIELD>& aFields,
292 bool aResolve, int aDepth,
293 std::span<const wxString> aPins,
294 REPORTER& aReporter )
295{
296 return createModel( aFields, aResolve, aDepth, aPins, aReporter, aResolve );
297}
298
299
300SIM_LIBRARY::MODEL SIM_LIB_MGR::createModel( const std::vector<SCH_FIELD>& aFields, bool aResolve, int aDepth,
301 std::span<const wxString> aPins, REPORTER& aReporter,
302 bool aAllowRawFallback )
303{
304 std::string libraryPath = GetFieldValue( &aFields, SIM_LIBRARY::LIBRARY_FIELD, aResolve, aDepth );
305 std::string baseModelName = GetFieldValue( &aFields, SIM_LIBRARY::NAME_FIELD, aResolve, aDepth );
306
307 if( libraryPath != "" )
308 {
309 return CreateModel( libraryPath, baseModelName, aFields, aResolve, aDepth, aPins, aReporter );
310 }
311 else
312 {
313 m_models.push_back( SIM_MODEL::Create( aFields, aResolve, aDepth, aPins, aReporter, aAllowRawFallback ) );
314 return { baseModelName, *m_models.back() };
315 }
316}
317
318
319SIM_LIBRARY::MODEL SIM_LIB_MGR::CreateModel( const wxString& aLibraryPath,
320 const std::string& aBaseModelName,
321 const std::vector<SCH_FIELD>& aFields,
322 bool aResolve, int aDepth,
323 std::span<const wxString> aPins,
324 REPORTER& aReporter )
325{
326 wxString msg;
327 SIM_LIBRARY* library = nullptr;
328 SIM_MODEL* baseModel = nullptr;
329 std::string modelName;
330 wxString path = ResolveLibraryPath( aLibraryPath, aReporter );
331
332 auto it = m_libraries.find( path );
333
334 if( it == m_libraries.end() )
335 {
336 it = m_libraries.emplace( path, SIM_LIBRARY::Create( path, m_forceFullParse, aReporter,
337 [&]( const wxString& libPath, const wxString& relativeLib ) -> wxString
338 {
339 return ResolveEmbeddedLibraryPath( libPath, relativeLib, aReporter );
340 } ) ).first;
341 }
342
343 library = &*it->second;
344
345 if( aBaseModelName == "" )
346 {
347 msg.Printf( _( "Error loading simulation model: no '%s' field" ),
349
350 aReporter.Report( msg, RPT_SEVERITY_ERROR );
351
352 modelName = _( "unknown" ).ToStdString();
353 }
354 else if( library )
355 {
356 baseModel = library->FindModel( aBaseModelName );
357 modelName = aBaseModelName;
358
359 if( !baseModel )
360 {
361 msg.Printf( _( "Error loading simulation model: could not find base model '%s' "
362 "in library '%s'" ),
363 aBaseModelName,
364 path );
365
366 aReporter.Report( msg, RPT_SEVERITY_ERROR );
367 }
368 }
369
370 m_models.push_back( SIM_MODEL::Create( baseModel, aPins, aFields, aResolve, aDepth, aReporter ) );
371
372 return { modelName, *m_models.back() };
373}
374
375
376void SIM_LIB_MGR::SetModel( int aIndex, std::unique_ptr<SIM_MODEL> aModel )
377{
378 m_models.at( aIndex ) = std::move( aModel );
379}
380
381
382std::map<wxString, std::reference_wrapper<const SIM_LIBRARY>> SIM_LIB_MGR::GetLibraries() const
383{
384 std::map<wxString, std::reference_wrapper<const SIM_LIBRARY>> libraries;
385
386 for( auto& [path, library] : m_libraries )
387 libraries.try_emplace( path, *library );
388
389 return libraries;
390}
391
392
393std::vector<std::reference_wrapper<SIM_MODEL>> SIM_LIB_MGR::GetModels() const
394{
395 std::vector<std::reference_wrapper<SIM_MODEL>> models;
396
397 for( const std::unique_ptr<SIM_MODEL>& model : m_models )
398 models.emplace_back( *model );
399
400 return models;
401}
const char * name
Provide an extensible class to resolve 3D model paths.
wxString ResolvePath(const wxString &aFileName, const wxString &aWorkingPath, std::vector< const EMBEDDED_FILES * > aEmbeddedFilesStack)
Determine the full path of the given file name.
bool SetProject(const PROJECT *aProject, bool *flgChanged=nullptr)
Set the current KiCad project directory as the first entry in the model path list.
Container for project specific data.
Definition project.h:63
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:102
virtual bool HasMessageOfSeverity(int aSeverityMask) const
Returns true if the reporter has one or more messages matching the specified severity mask.
Definition reporter.h:152
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:76
std::vector< const SCH_PIN * > GetPins(const SCH_SHEET_PATH *aSheet) const
Retrieve a list of the SCH_PINs for the given sheet path.
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
std::vector< SCH_PIN * > GetAllLibPins() const
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
wxString GetPrefix() const
Definition sch_symbol.h:241
static std::unique_ptr< SIM_LIBRARY > Create(const wxString &aFilePath, bool aForceFullParse, REPORTER &aReporter, const std::function< wxString(const wxString &, const wxString &)> &aResolver)
Read library from a source file (e.g.
static constexpr auto LIBRARY_FIELD
Definition sim_library.h:31
static constexpr auto NAME_FIELD
Definition sim_library.h:32
void SetModel(int aIndex, std::unique_ptr< SIM_MODEL > aModel)
SIM_LIBRARY::MODEL createModel(const std::vector< SCH_FIELD > &aFields, bool aResolve, int aDepth, std::span< const wxString > aPins, REPORTER &aReporter, bool aAllowRawFallback)
wxString ResolveLibraryPath(const wxString &aLibraryPath, REPORTER &aReporter)
const PROJECT * m_project
Definition sim_lib_mgr.h:99
std::vector< EMBEDDED_FILES * > m_embeddedFilesStack
Definition sim_lib_mgr.h:98
bool m_forceFullParse
SIM_LIB_MGR(const PROJECT *aPrj)
std::vector< std::unique_ptr< SIM_MODEL > > m_models
SIM_MODEL & CreateModel(SIM_MODEL::TYPE aType, std::span< const wxString > aPins, REPORTER &aReporter)
std::map< wxString, std::reference_wrapper< const SIM_LIBRARY > > GetLibraries() const
wxString ResolveEmbeddedLibraryPath(const wxString &aLibPath, const wxString &aRelativeLib, REPORTER &aReporter)
std::vector< std::reference_wrapper< SIM_MODEL > > GetModels() const
static SIM_MODEL_INPUT CaptureModelInput(const SCH_SHEET_PATH *aSheetPath, const SCH_SYMBOL &aSymbol, int aDepth, const wxString &aVariantName, const wxString &aMergedSimPins=wxEmptyString)
Resolve instance fields once; editors use the field-based overloads for unresolved input.
void SetLibrary(const wxString &aLibraryPath, REPORTER &aReporter)
std::map< wxString, std::unique_ptr< SIM_LIBRARY > > m_libraries
static std::unique_ptr< SIM_MODEL > Create(TYPE aType, std::span< const wxString > aPins, REPORTER &aReporter)
static bool InferSimModel(const wxString &aPrefix, std::span< const wxString > aPins, std::vector< SCH_FIELD > *aFields, bool aResolve, int aDepth, SIM_VALUE_GRAMMAR::NOTATION aNotation, wxString *aDeviceType, wxString *aModelType, wxString *aModelParams, wxString *aPinMap)
aPins follows lexical symbol-pin number order, including duplicate numbers.
static std::vector< wxString > PinNumbers(std::span< const SCH_PIN *const > aPins)
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject, bool aAllowEscapes)
Replace any environment variable & text variable references with their values.
Definition common.cpp:777
@ FOR_NETNAME
Definition common.h:94
#define _(s)
see class PGM_BASE
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_UNDEFINED
wxString GetFieldValue(const std::vector< SCH_FIELD > *aFields, FIELD_T aFieldType)
Definition sch_field.h:428
const SCH_FIELD * FindField(const std::vector< SCH_FIELD > &aFields, FIELD_T aFieldId)
Definition sch_field.h:390
#define SIM_PINS_FIELD
Definition sim_model.h:51
#define SIM_DEVICE_FIELD
Definition sim_model.h:49
#define SIM_PARAMS_FIELD
Definition sim_model.h:53
#define SIM_DEVICE_SUBTYPE_FIELD
Definition sim_model.h:50
std::vector< wxString > inferencePins
Selected-unit pin numbers in lexical order, including duplicates.
std::vector< std::pair< wxString, wxString > > fields
Resolved shown values in symbol order, adapted to USER fields without further expansion.
std::vector< wxString > modelPins
All library pin numbers in natural (StrNumCmp) order, including duplicates.
@ USER
The field ID hasn't been set yet; field is invalid.
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
std::string path
KIBIS_MODEL * model