KiCad PCB EDA Suite
Loading...
Searching...
No Matches
simulator_frame_ui.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) 2016-2023 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 * @author Tomasz Wlostowski <[email protected]>
7 * @author Maciej Suminski <[email protected]>
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 3
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, you may find one here:
21 * https://www.gnu.org/licenses/gpl-3.0.html
22 * or you may search the http://www.gnu.org website for the version 3 license,
23 * or you may write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
25 */
26
27#include <memory>
28#include <type_traits>
29
30#include <wx/event.h>
31#include <fmt/format.h>
32#include <wx/wfstream.h>
33#include <wx/stdstream.h>
34#include <wx/debug.h>
35#include <wx/clipbrd.h>
36#include <wx/log.h>
37
39#include <sch_edit_frame.h>
40#include <confirm.h>
44#include <widgets/wx_grid.h>
45#include <grid_tricks.h>
46#include <eda_pattern_match.h>
47#include <string_utils.h>
48#include <pgm_base.h>
50#include <sim/simulator_frame.h>
51#include <sim/sim_plot_tab.h>
52#include <sim/spice_simulator.h>
55#include <eeschema_settings.h>
56#include <magic_enum.hpp>
57
58
60{
61 int res = static_cast<int>( aFirst ) | static_cast<int>( aSecond);
62
63 return static_cast<SIM_TRACE_TYPE>( res );
64}
65
66
75
76
84
85
92
93
94enum
95{
105
108};
109
110
112{
113public:
115 GRID_TRICKS( aGrid ),
116 m_parent( aParent ),
117 m_menuRow( 0 ),
118 m_menuCol( 0 )
119 {}
120
121protected:
122 void showPopupMenu( wxMenu& menu, wxGridEvent& aEvent ) override;
123 void doPopupSelection( wxCommandEvent& event ) override;
124
125protected:
129};
130
131
132void SIGNALS_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
133{
134 SIM_TAB* panel = m_parent->GetCurrentSimTab();
135
136 if( !panel )
137 return;
138
139 m_menuRow = aEvent.GetRow();
140 m_menuCol = aEvent.GetCol();
141
143 {
144 if( !( m_grid->IsInSelection( m_menuRow, m_menuCol ) ) )
145 m_grid->ClearSelection();
146
147 m_grid->SetGridCursor( m_menuRow, m_menuCol );
148
149 if( panel->GetSimType() == ST_TRAN || panel->GetSimType() == ST_AC
150 || panel->GetSimType() == ST_DC || panel->GetSimType() == ST_SP )
151 {
152 menu.Append( MYID_MEASURE_MIN, _( "Measure Min" ) );
153 menu.Append( MYID_MEASURE_MAX, _( "Measure Max" ) );
154 menu.Append( MYID_MEASURE_AVG, _( "Measure Average" ) );
155 menu.Append( MYID_MEASURE_RMS, _( "Measure RMS" ) );
156 menu.Append( MYID_MEASURE_PP, _( "Measure Peak-to-peak" ) );
157
158 if( panel->GetSimType() == ST_AC || panel->GetSimType() == ST_SP )
159 {
160 menu.Append( MYID_MEASURE_MIN_AT, _( "Measure Frequency of Min" ) );
161 menu.Append( MYID_MEASURE_MAX_AT, _( "Measure Frequency of Max" ) );
162 }
163 else
164 {
165 menu.Append( MYID_MEASURE_MIN_AT, _( "Measure Time of Min" ) );
166 menu.Append( MYID_MEASURE_MAX_AT, _( "Measure Time of Max" ) );
167 }
168
169 menu.Append( MYID_MEASURE_INTEGRAL, _( "Measure Integral" ) );
170
171 if( panel->GetSimType() == ST_TRAN )
172 {
173 menu.AppendSeparator();
174 menu.Append( MYID_FOURIER, _( "Perform Fourier Analysis..." ) );
175 }
176
177 menu.AppendSeparator();
178 menu.Append( GRIDTRICKS_ID_COPY, _( "Copy Signal Name" ) + "\tCtrl+C" );
179
180 menu.AppendSeparator();
181 menu.Append( GRIDTRICKS_ID_SELECT, _( "Create new cursor..." ) );
182
183 m_grid->PopupMenu( &menu );
184 }
185 }
186 else if( m_menuCol > static_cast<int>( COL_CURSOR_2 ) )
187 {
188 menu.Append( GRIDTRICKS_ID_SELECT, _( "Create new cursor..." ) );
189
190 menu.AppendSeparator();
191
192 wxString msg = m_grid->GetColLabelValue( m_grid->GetNumberCols() - 1 );
193
194 menu.AppendSeparator();
195 menu.Append( GRIDTRICKS_ID_DELETE, wxString::Format( _( "Delete %s..." ), msg ) );
196
197 m_grid->PopupMenu( &menu );
198 }
199 else
200 {
201 menu.Append( GRIDTRICKS_ID_SELECT, _( "Create new cursor..." ) );
202
203 m_grid->PopupMenu( &menu );
204 }
205}
206
207
208void SIGNALS_GRID_TRICKS::doPopupSelection( wxCommandEvent& event )
209{
210 std::vector<wxString> signals;
211
212 wxGridCellCoordsArray cells1 = m_grid->GetSelectionBlockTopLeft();
213 wxGridCellCoordsArray cells2 = m_grid->GetSelectionBlockBottomRight();
214
215 for( size_t i = 0; i < cells1.Count(); i++ )
216 {
217 if( cells1[i].GetCol() == COL_SIGNAL_NAME )
218 {
219 for( int j = cells1[i].GetRow(); j < cells2[i].GetRow() + 1; j++ )
220 {
221 signals.push_back( m_grid->GetCellValue( j, cells1[i].GetCol() ) );
222 }
223 }
224 }
225
226 wxGridCellCoordsArray cells3 = m_grid->GetSelectedCells();
227
228 for( size_t i = 0; i < cells3.Count(); i++ )
229 {
230 if( cells3[i].GetCol() == COL_SIGNAL_NAME )
231 signals.push_back( m_grid->GetCellValue( cells3[i].GetRow(), cells3[i].GetCol() ) );
232 }
233
234 if( signals.size() < 1 )
235 signals.push_back( m_grid->GetCellValue( m_menuRow, m_menuCol ) );
236
237 auto addMeasurement =
238 [this]( const wxString& cmd, wxString signal )
239 {
240 if( signal.EndsWith( _( " (phase)" ) ) )
241 return;
242
243 if( signal.EndsWith( _( " (gain)" ) ) || signal.EndsWith( _( " (amplitude)" ) ) )
244 {
245 signal = signal.Left( signal.length() - 7 );
246
247 if( signal.Upper().StartsWith( wxS( "V(" ) ) )
248 signal = wxS( "vdb" ) + signal.Mid( 1 );
249 }
250
251 m_parent->AddMeasurement( cmd + wxS( " " ) + signal );
252 };
253
254 if( event.GetId() == MYID_MEASURE_MIN )
255 {
256 for( const wxString& signal : signals )
257 addMeasurement( wxS( "MIN" ), signal );
258 }
259 else if( event.GetId() == MYID_MEASURE_MAX )
260 {
261 for( const wxString& signal : signals )
262 addMeasurement( wxS( "MAX" ), signal );
263 }
264 else if( event.GetId() == MYID_MEASURE_AVG )
265 {
266 for( const wxString& signal : signals )
267 addMeasurement( wxS( "AVG" ), signal );
268 }
269 else if( event.GetId() == MYID_MEASURE_RMS )
270 {
271 for( const wxString& signal : signals )
272 addMeasurement( wxS( "RMS" ), signal );
273 }
274 else if( event.GetId() == MYID_MEASURE_PP )
275 {
276 for( const wxString& signal : signals )
277 addMeasurement( wxS( "PP" ), signal );
278 }
279 else if( event.GetId() == MYID_MEASURE_MIN_AT )
280 {
281 for( const wxString& signal : signals )
282 addMeasurement( wxS( "MIN_AT" ), signal );
283 }
284 else if( event.GetId() == MYID_MEASURE_MAX_AT )
285 {
286 for( const wxString& signal : signals )
287 addMeasurement( wxS( "MAX_AT" ), signal );
288 }
289 else if( event.GetId() == MYID_MEASURE_INTEGRAL )
290 {
291 for( const wxString& signal : signals )
292 addMeasurement( wxS( "INTEG" ), signal );
293 }
294 else if( event.GetId() == MYID_FOURIER )
295 {
296 wxString title;
297 wxString fundamental = wxT( "1K" );
298
299 if( signals.size() == 1 )
300 title.Printf( _( "Fourier Analysis of %s" ), signals[0] );
301 else
302 title = _( "Fourier Analyses of Multiple Signals" );
303
304 WX_TEXT_ENTRY_DIALOG dlg( m_parent, _( "Fundamental frequency:" ), title, fundamental );
305
306 if( dlg.ShowModal() != wxID_OK )
307 return;
308
309 if( !dlg.GetValue().IsEmpty() )
310 fundamental = dlg.GetValue();
311
312 for( const wxString& signal : signals )
313 m_parent->DoFourier( signal, fundamental );
314 }
315 else if( event.GetId() == GRIDTRICKS_ID_COPY )
316 {
317 wxLogNull doNotLog; // disable logging of failed clipboard actions
318 wxString txt;
319
320 for( const wxString& signal : signals )
321 {
322 if( !txt.IsEmpty() )
323 txt += '\r';
324
325 txt += signal;
326 }
327
328 if( wxTheClipboard->Open() )
329 {
330 wxTheClipboard->SetData( new wxTextDataObject( txt ) );
331 wxTheClipboard->Flush(); // Allow data to be available after closing KiCad
332 wxTheClipboard->Close();
333 }
334 }
335 else if( event.GetId() == GRIDTRICKS_ID_SELECT )
336 {
337 m_parent->CreateNewCursor();
338 }
339 else if( event.GetId() == GRIDTRICKS_ID_DELETE )
340 {
341 m_parent->DeleteCursor();
342 }
343}
344
345
347{
348public:
350 GRID_TRICKS( aGrid ),
351 m_parent( aParent ),
352 m_menuRow( 0 ),
353 m_menuCol( 0 )
354 {}
355
356protected:
357 void showPopupMenu( wxMenu& menu, wxGridEvent& aEvent ) override;
358 void doPopupSelection( wxCommandEvent& event ) override;
359
360protected:
364};
365
366
367void CURSORS_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
368{
369 m_menuRow = aEvent.GetRow();
370 m_menuCol = aEvent.GetCol();
371
373 {
374 wxString msg = m_grid->GetColLabelValue( m_menuCol );
375
376 menu.Append( MYID_FORMAT_VALUE, wxString::Format( _( "Format %s..." ), msg ) );
377 menu.AppendSeparator();
378 }
379
380 GRID_TRICKS::showPopupMenu( menu, aEvent );
381}
382
383
384void CURSORS_GRID_TRICKS::doPopupSelection( wxCommandEvent& event )
385{
386 auto getSignalName =
387 [this]( int row ) -> wxString
388 {
389 wxString signal = m_grid->GetCellValue( row, COL_CURSOR_SIGNAL );
390
391 if( signal.EndsWith( "[2 - 1]" ) )
392 signal = signal.Left( signal.length() - 7 );
393
394 return signal;
395 };
396
397 if( event.GetId() == MYID_FORMAT_VALUE )
398 {
399 int axis = m_menuCol - COL_CURSOR_X;
400 SPICE_VALUE_FORMAT format = m_parent->GetCursorFormat( m_menuRow, axis );
401 DIALOG_SIM_FORMAT_VALUE formatDialog( m_parent, &format );
402
403 if( formatDialog.ShowModal() == wxID_OK )
404 {
405 for( int row = 0; row < m_grid->GetNumberRows(); ++row )
406 {
407 if( getSignalName( row ) == getSignalName( m_menuRow ) )
408 m_parent->SetCursorFormat( row, axis, format );
409 }
410 }
411 }
412 else
413 {
415 }
416}
417
418
420{
421public:
423 GRID_TRICKS( aGrid ),
424 m_parent( aParent ),
425 m_menuRow( 0 ),
426 m_menuCol( 0 )
427 {}
428
429protected:
430 void showPopupMenu( wxMenu& menu, wxGridEvent& aEvent ) override;
431 void doPopupSelection( wxCommandEvent& event ) override;
432
433protected:
437};
438
439
440void MEASUREMENTS_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
441{
442 m_menuRow = aEvent.GetRow();
443 m_menuCol = aEvent.GetCol();
444
445 if( !( m_grid->IsInSelection( m_menuRow, m_menuCol ) ) )
446 m_grid->ClearSelection();
447
448 m_grid->SetGridCursor( m_menuRow, m_menuCol );
449
451 menu.Append( MYID_FORMAT_VALUE, _( "Format Value..." ) );
452
453 if( m_menuRow < ( m_grid->GetNumberRows() - 1 ) )
454 menu.Append( MYID_DELETE_MEASUREMENT, _( "Delete Measurement" ) );
455
456 menu.AppendSeparator();
457
458 GRID_TRICKS::showPopupMenu( menu, aEvent );
459}
460
461
463{
464 if( event.GetId() == MYID_FORMAT_VALUE )
465 {
466 SPICE_VALUE_FORMAT format = m_parent->GetMeasureFormat( m_menuRow );
467 DIALOG_SIM_FORMAT_VALUE formatDialog( m_parent, &format );
468
469 if( formatDialog.ShowModal() == wxID_OK )
470 {
471 m_parent->SetMeasureFormat( m_menuRow, format );
472 m_parent->UpdateMeasurement( m_menuRow );
473 m_parent->OnModify();
474 }
475 }
476 else if( event.GetId() == MYID_DELETE_MEASUREMENT )
477 {
478 std::vector<int> measurements;
479
480 wxGridCellCoordsArray cells1 = m_grid->GetSelectionBlockTopLeft();
481 wxGridCellCoordsArray cells2 = m_grid->GetSelectionBlockBottomRight();
482
483 for( size_t i = 0; i < cells1.Count(); i++ )
484 {
485 if( cells1[i].GetCol() == COL_MEASUREMENT )
486 {
487 for( int j = cells1[i].GetRow(); j < cells2[i].GetRow() + 1; j++ )
488 measurements.push_back( j );
489 }
490 }
491
492 wxGridCellCoordsArray cells3 = m_grid->GetSelectedCells();
493
494 for( size_t i = 0; i < cells3.Count(); i++ )
495 {
496 if( cells3[i].GetCol() == COL_MEASUREMENT )
497 measurements.push_back( cells3[i].GetRow() );
498 }
499
500 if( measurements.size() < 1 )
501 measurements.push_back( m_menuRow );
502
503 // When deleting a row, we'll change the indexes.
504 // To avoid problems, we can start with the highest indexes.
505 sort( measurements.begin(), measurements.end(), std::greater<>() );
506
507 for( int row : measurements )
508 m_parent->DeleteMeasurement( row );
509
510 m_grid->ClearSelection();
511
512 m_parent->OnModify();
513 }
514 else
515 {
517 }
518}
519
520
522{
523public:
525 m_frame( aFrame )
526 {
527 m_frame->m_SuppressGridEvents++;
528 }
529
531 {
532 m_frame->m_SuppressGridEvents--;
533 }
534
535private:
537};
538
539
540#define ID_SIM_REFRESH 10207
541#define REFRESH_INTERVAL 50 // 20 frames/second.
542
543
545 SCH_EDIT_FRAME* aSchematicFrame ) :
546 SIMULATOR_FRAME_UI_BASE( aSimulatorFrame ),
548 m_simulatorFrame( aSimulatorFrame ),
549 m_schematicFrame( aSchematicFrame ),
550 m_darkMode( true ),
551 m_plotNumber( 0 ),
553{
554 // Get the previous size and position of windows:
555 LoadSettings( m_schematicFrame->eeconfig() );
556
557 m_filter->SetHint( _( "Filter" ) );
558
559 m_signalsGrid->wxGrid::SetLabelFont( KIUI::GetStatusFont( this ) );
560 m_cursorsGrid->wxGrid::SetLabelFont( KIUI::GetStatusFont( this ) );
561 m_measurementsGrid->wxGrid::SetLabelFont( KIUI::GetStatusFont( this ) );
562
563 m_signalsGrid->PushEventHandler( new SIGNALS_GRID_TRICKS( this, m_signalsGrid ) );
564 m_cursorsGrid->PushEventHandler( new CURSORS_GRID_TRICKS( this, m_cursorsGrid ) );
565 m_measurementsGrid->PushEventHandler( new MEASUREMENTS_GRID_TRICKS( this, m_measurementsGrid ) );
566
567 wxGridCellAttr* attr = new wxGridCellAttr;
568 attr->SetReadOnly();
569 m_signalsGrid->SetColAttr( COL_SIGNAL_NAME, attr );
570
571 attr = new wxGridCellAttr;
572 attr->SetReadOnly();
573 m_cursorsGrid->SetColAttr( COL_CURSOR_NAME, attr );
574
575 attr = new wxGridCellAttr;
576 attr->SetReadOnly();
577 m_cursorsGrid->SetColAttr( COL_CURSOR_SIGNAL, attr );
578
579 attr = new wxGridCellAttr;
580 attr->SetReadOnly();
581 m_cursorsGrid->SetColAttr( COL_CURSOR_Y, attr );
582
584
585 attr = new wxGridCellAttr;
586 attr->SetReadOnly();
587 m_measurementsGrid->SetColAttr( COL_MEASUREMENT_VALUE, attr );
588
589 // Prepare the color list to plot traces
591
592 Bind( EVT_SIM_CURSOR_UPDATE, &SIMULATOR_FRAME_UI::onPlotCursorUpdate, this );
593
594 Bind( wxEVT_TIMER,
595 [&]( wxTimerEvent& aEvent )
596 {
597 OnSimRefresh( false );
598
599 if( m_simulatorFrame->GetSimulator()->IsRunning() )
600 m_refreshTimer.Start( REFRESH_INTERVAL, wxTIMER_ONE_SHOT );
601 },
602 m_refreshTimer.GetId() );
603
604#ifndef wxHAS_NATIVE_TABART
605 // Default non-native tab art has ugly gradients we don't want
606 m_plotNotebook->SetArtProvider( new wxAuiSimpleTabArt() );
607#endif
608}
609
610
612{
613 // Delete the GRID_TRICKS.
614 m_signalsGrid->PopEventHandler( true );
615 m_cursorsGrid->PopEventHandler( true );
616 m_measurementsGrid->PopEventHandler( true );
617}
618
619
621{
622 for( auto& m_cursorFormat : m_cursorFormats )
623 {
624 m_cursorFormat[0] = { 3, wxS( "~s" ) };
625 m_cursorFormat[1] = { 3, wxS( "~V" ) };
626 }
627
628 // proper init and transfer/copy m_cursorFormats
629 // we work on m_cursorFormatsDyn from now on.
630 // TODO: rework +- LOC when m_cursorFormatsDyn and m_cursorFormats get merged.
631 m_cursorFormatsDyn.clear();
632 m_cursorFormatsDyn.resize( std::size( m_cursorFormats ) );
633
634 for( size_t index = 0; index < std::size( m_cursorFormats ); index++ )
635 {
636 for( size_t index2 = 0; index2 < std::size( m_cursorFormats[0] ); index2++ )
637 {
638 m_cursorFormatsDyn[index].push_back( m_cursorFormats[index][index2] );
639 }
640 }
641
642 // Dump string helper, tries to get the current higher cursor name to form the next one.
643 // Based on the column labeling
644 // TODO: "Cursor n" may translate as "n Cursor" in other languages
645 // TBD how to handle; just forbid for now.
646 int nameMax = 0;
647
648 for( int i = 0; i < m_signalsGrid->GetNumberCols(); i++ )
649 {
650 wxString maxCursor = m_signalsGrid->GetColLabelValue( i );
651
652 maxCursor.Replace( _( "Cursor " ), "" );
653
654 int tmpMax = wxAtoi( maxCursor );
655
656 if( nameMax < tmpMax )
657 nameMax = tmpMax;
658 }
659
660 m_customCursorsCnt = nameMax + 1; // Init with a +1 on top of current cursor 2, defaults to 3
661}
662
663
665{
666 std::vector<SPICE_VALUE_FORMAT> tmp;
667 // m_cursorFormatsDyn should be equal with m_cursorFormats on first entry here.
668 m_cursorFormatsDyn.emplace_back( tmp );
669
670 m_cursorFormatsDyn[m_customCursorsCnt].push_back( { 3, wxS( "~s" ) } );
671 m_cursorFormatsDyn[m_customCursorsCnt].push_back( { 3, wxS( "~V" ) } );
672
673 wxString cursor_name = wxString( _( "Cursor " ) ) << m_customCursorsCnt;
674
675 m_signalsGrid->InsertCols( m_signalsGrid->GetNumberCols() , 1, true );
676 m_signalsGrid->SetColLabelValue( m_signalsGrid->GetNumberCols() - 1, cursor_name );
677
678 wxGridCellAttr* attr = new wxGridCellAttr;
679 m_signalsGrid->SetColAttr( COL_CURSOR_2 + m_customCursorsCnt, attr );
680
682
685 OnModify();
686}
687
688
690{
691 int col = m_signalsGrid->GetNumberCols();
692 int rows = m_signalsGrid->GetNumberRows();
693
694 if( col > COL_CURSOR_2 )
695 {
696 // Now we need to find the active cursor and deactivate before removing the column,
697 // Send the dummy event to update the UI
698 for( int i = 0; i < rows; i++ )
699 {
700 if( m_signalsGrid->GetCellValue( i, col - 1 ) == wxS( "1" ) )
701 {
702 m_signalsGrid->SetCellValue( i, col - 1, wxEmptyString );
703 wxGridEvent aDummy( wxID_ANY, wxEVT_GRID_CELL_CHANGED, m_signalsGrid, i, col - 1 );
704 onSignalsGridCellChanged( aDummy );
705 break;
706 }
707
708 }
709
710 m_signalsGrid->DeleteCols( col - 1, 1, false );
711 m_cursorFormatsDyn.pop_back();
713 m_plotNotebook->Refresh();
716 OnModify();
717 }
718}
719
720
722{
723 for( int ii = 0; ii < static_cast<int>( m_plotNotebook->GetPageCount() ); ++ii )
724 {
725 if( SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( ii ) ) )
726 {
727 simTab->OnLanguageChanged();
728
729 wxString pageTitle( simulator()->TypeToName( simTab->GetSimType(), true ) );
730 pageTitle.Prepend( wxString::Format( _( "Analysis %u - " ), ii+1 /* 1-based */ ) );
731
732 m_plotNotebook->SetPageText( ii, pageTitle );
733 }
734 }
735
736 m_filter->SetHint( _( "Filter" ) );
737
738 m_signalsGrid->SetColLabelValue( COL_SIGNAL_NAME, _( "Signal" ) );
739 m_signalsGrid->SetColLabelValue( COL_SIGNAL_SHOW, _( "Plot" ) );
740 m_signalsGrid->SetColLabelValue( COL_SIGNAL_COLOR, _( "Color" ) );
741 m_signalsGrid->SetColLabelValue( COL_CURSOR_1, _( "Cursor 1" ) );
742 m_signalsGrid->SetColLabelValue( COL_CURSOR_2, _( "Cursor 2" ) );
743
744 m_cursorsGrid->SetColLabelValue( COL_CURSOR_NAME, _( "Cursor" ) );
745 m_cursorsGrid->SetColLabelValue( COL_CURSOR_SIGNAL, _( "Signal" ) );
746 m_cursorsGrid->SetColLabelValue( COL_CURSOR_X, _( "Time" ) );
747 m_cursorsGrid->SetColLabelValue( COL_CURSOR_Y, _( "Value" ) );
749
750 for( TUNER_SLIDER* tuner : m_tuners )
751 tuner->ShowChangedLanguage();
752}
753
754
769
770
772{
774
775 settings.view.plot_panel_width = m_splitterLeftRight->GetSashPosition();
776 settings.view.plot_panel_height = m_splitterPlotAndConsole->GetSashPosition();
777 settings.view.signal_panel_height = m_splitterSignals->GetSashPosition();
778 settings.view.cursors_panel_height = m_splitterCursors->GetSashPosition();
779 settings.view.measurements_panel_height = m_splitterMeasurements->GetSashPosition();
780 settings.view.white_background = !m_darkMode;
781}
782
783
785{
786 m_preferences = aPrefs;
787
788 for( std::size_t i = 0; i < m_plotNotebook->GetPageCount(); ++i )
789 {
790 if( SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( i ) ) )
791 simTab->ApplyPreferences( aPrefs );
792 }
793}
794
795
797{
798 if( !simulator()->Settings()->GetWorkbookFilename().IsEmpty() )
799 {
800 wxFileName filename = simulator()->Settings()->GetWorkbookFilename();
801 filename.SetPath( m_schematicFrame->Prj().GetProjectPath() );
802
803 if( !LoadWorkbook( filename.GetFullPath() ) )
805 }
806 else if( m_simulatorFrame->LoadSimulator( wxEmptyString, 0 ) )
807 {
808 wxString schTextSimCommand = circuitModel()->GetSchTextSimCommand();
809
810 if( !schTextSimCommand.IsEmpty() )
811 {
812 SIM_TAB* simTab = NewSimTab( schTextSimCommand );
814 }
815
817 rebuildSignalsGrid( m_filter->GetValue() );
818 }
819}
820
821
839
840
841void sortSignals( std::vector<wxString>& signals )
842{
843 std::sort( signals.begin(), signals.end(),
844 []( const wxString& lhs, const wxString& rhs )
845 {
846 // Sort voltages first
847 if( lhs.Upper().StartsWith( 'V' ) && !rhs.Upper().StartsWith( 'V' ) )
848 return true;
849 else if( !lhs.Upper().StartsWith( 'V' ) && rhs.Upper().StartsWith( 'V' ) )
850 return false;
851
852 return StrNumCmp( lhs, rhs, true /* ignore case */ ) < 0;
853 } );
854}
855
856
858{
859 SUPPRESS_GRID_CELL_EVENTS raii( this );
860
861 m_signalsGrid->ClearRows();
862
863 SIM_PLOT_TAB* plotPanel = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
864
865 if( !plotPanel )
866 return;
867
868 SIM_TYPE simType = plotPanel->GetSimType();
869 std::vector<wxString> signals;
870
871 if( plotPanel->GetSimType() == ST_FFT )
872 {
873 wxStringTokenizer tokenizer( plotPanel->GetSimCommand(), " \t\r\n", wxTOKEN_STRTOK );
874
875 while( tokenizer.HasMoreTokens() && tokenizer.GetNextToken().Lower() != wxT( "fft" ) )
876 {};
877
878 while( tokenizer.HasMoreTokens() )
879 signals.emplace_back( tokenizer.GetNextToken() );
880 }
881 else
882 {
883 // NB: m_signals are already broken out into gain/phase, but m_userDefinedSignals are
884 // as the user typed them
885
886 for( const wxString& signal : m_signals )
887 signals.push_back( signal );
888
889 for( const auto& [ id, signal ] : m_userDefinedSignals )
890 {
891 if( simType == ST_AC )
892 {
893 signals.push_back( signal + _( " (gain)" ) );
894 signals.push_back( signal + _( " (phase)" ) );
895 }
896 else if( simType == ST_SP )
897 {
898 signals.push_back( signal + _( " (amplitude)" ) );
899 signals.push_back( signal + _( " (phase)" ) );
900 }
901 else
902 {
903 signals.push_back( signal );
904 }
905 }
906
907 sortSignals( signals );
908 }
909
910 if( aFilter.IsEmpty() )
911 aFilter = wxS( "*" );
912
913 EDA_COMBINED_MATCHER matcher( aFilter.Upper(), CTX_SIGNAL );
914 int row = 0;
915
916 for( const wxString& signal : signals )
917 {
918 if( matcher.Find( signal.Upper() ) )
919 {
920 int traceType = SPT_UNKNOWN;
921 wxString vectorName = vectorNameFromSignalName( plotPanel, signal, &traceType );
922 TRACE* trace = plotPanel->GetTrace( vectorName, traceType );
923
924 m_signalsGrid->AppendRows( 1 );
925 m_signalsGrid->SetCellValue( row, COL_SIGNAL_NAME, signal );
926
927 wxGridCellAttr* attr = new wxGridCellAttr;
928 attr->SetRenderer( new wxGridCellBoolRenderer() );
929 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
930 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
931 m_signalsGrid->SetAttr( row, COL_SIGNAL_SHOW, attr );
932
933 if( !trace )
934 {
935 attr = new wxGridCellAttr;
936 attr->SetReadOnly();
937 m_signalsGrid->SetAttr( row, COL_SIGNAL_COLOR, attr );
938 m_signalsGrid->SetCellValue( row, COL_SIGNAL_COLOR, wxEmptyString );
939
940 attr = new wxGridCellAttr;
941 attr->SetReadOnly();
942 m_signalsGrid->SetAttr( row, COL_CURSOR_1, attr );
943
944 attr = new wxGridCellAttr;
945 attr->SetReadOnly();
946 m_signalsGrid->SetAttr( row, COL_CURSOR_2, attr );
947
948 if( m_customCursorsCnt > 3 )
949 {
950 for( int i = 1; i <= m_customCursorsCnt - 3; i++ )
951 {
952 attr = new wxGridCellAttr;
953 attr->SetReadOnly();
954 m_signalsGrid->SetAttr( row, COL_CURSOR_2 + i, attr );
955 }
956 }
957 }
958 else
959 {
960 m_signalsGrid->SetCellValue( row, COL_SIGNAL_SHOW, wxS( "1" ) );
961
962 attr = new wxGridCellAttr;
963 attr->SetRenderer( new GRID_CELL_COLOR_RENDERER( this ) );
964 attr->SetEditor( new GRID_CELL_COLOR_SELECTOR( this, m_signalsGrid ) );
965 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
966 m_signalsGrid->SetAttr( row, COL_SIGNAL_COLOR, attr );
967 KIGFX::COLOR4D color( trace->GetPen().GetColour() );
968 m_signalsGrid->SetCellValue( row, COL_SIGNAL_COLOR, color.ToCSSString() );
969
970 attr = new wxGridCellAttr;
971 attr->SetRenderer( new wxGridCellBoolRenderer() );
972 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
973 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
974 m_signalsGrid->SetAttr( row, COL_CURSOR_1, attr );
975 m_signalsGrid->SetCellValue( row, COL_CURSOR_1, trace->GetCursor( 1 ) ? "1" : "0" );
976
977 attr = new wxGridCellAttr;
978 attr->SetRenderer( new wxGridCellBoolRenderer() );
979 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
980 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
981 m_signalsGrid->SetAttr( row, COL_CURSOR_2, attr );
982 m_signalsGrid->SetCellValue( row, COL_CURSOR_2, trace->GetCursor( 2 ) ? "1" : "0" );
983
984 if( m_customCursorsCnt > 3 )
985 {
986 for( int i = 1; i <= m_customCursorsCnt - 3; i++ )
987 {
988 attr = new wxGridCellAttr;
989 attr->SetRenderer( new wxGridCellBoolRenderer() );
990 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
991 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
992 m_signalsGrid->SetAttr( row, COL_CURSOR_2 + i, attr );
993 m_signalsGrid->SetCellValue( row, COL_CURSOR_2 + i,
994 trace->GetCursor( i ) ? "1" : "0" );
995 }
996 }
997 }
998 row++;
999 }
1000 }
1001}
1002
1003
1005{
1006 m_signals.clear();
1007
1008 int options = m_simulatorFrame->GetCurrentOptions();
1009 SIM_TYPE simType = m_simulatorFrame->GetCurrentSimType();
1010 wxString unconnected = wxString( wxS( "unconnected-(" ) );
1011
1012 if( simType == ST_UNKNOWN )
1013 simType = ST_TRAN;
1014
1015 unconnected.Replace( '(', '_' ); // Convert to SPICE markup
1016
1017 auto addSignal =
1018 [&]( const wxString& aSignalName )
1019 {
1020 if( simType == ST_AC )
1021 {
1022 m_signals.push_back( aSignalName + _( " (gain)" ) );
1023 m_signals.push_back( aSignalName + _( " (phase)" ) );
1024 }
1025 else if( simType == ST_SP )
1026 {
1027 m_signals.push_back( aSignalName + _( " (amplitude)" ) );
1028 m_signals.push_back( aSignalName + _( " (phase)" ) );
1029 }
1030 else
1031 {
1032 m_signals.push_back( aSignalName );
1033 }
1034 };
1035
1037 && ( simType == ST_TRAN || simType == ST_DC || simType == ST_AC || simType == ST_FFT) )
1038 {
1039 for( const wxString& net : circuitModel()->GetNets() )
1040 {
1041 // netnames are escaped (can contain "{slash}" for '/') Unscape them:
1042 wxString netname = UnescapeString( net );
1044
1045 if( netname == "GND" || netname == "0" || netname.StartsWith( unconnected ) )
1046 continue;
1047
1048 m_netnames.emplace_back( netname );
1049 addSignal( wxString::Format( wxS( "V(%s)" ), netname ) );
1050 }
1051 }
1052
1054 && ( simType == ST_TRAN || simType == ST_DC || simType == ST_AC ) )
1055 {
1056 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
1057 {
1058 // Add all possible currents for the device.
1059 for( const std::string& name : item.model->SpiceGenerator().CurrentNames( item ) )
1060 addSignal( name );
1061 }
1062 }
1063
1065 && ( simType == ST_TRAN || simType == ST_DC ) )
1066 {
1067 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
1068 {
1069 if( item.model->GetPinCount() >= 2 )
1070 {
1071 wxString name = item.model->SpiceGenerator().ItemName( item );
1072 addSignal( wxString::Format( wxS( "P(%s)" ), name ) );
1073 }
1074 }
1075 }
1076
1077 if( simType == ST_NOISE )
1078 {
1079 addSignal( wxS( "inoise_spectrum" ) );
1080 addSignal( wxS( "onoise_spectrum" ) );
1081 }
1082
1083 if( simType == ST_SP )
1084 {
1085 std::vector<std::string> portnums;
1086
1087 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
1088 {
1089 wxString name = item.model->SpiceGenerator().ItemName( item );
1090
1091 // We are only looking for voltage sources in .SP mode
1092 if( !name.StartsWith( "V" ) )
1093 continue;
1094
1095 std::string portnum = "";
1096
1097 if( const SIM_MODEL::PARAM* portnum_param = item.model->FindParam( "portnum" ) )
1098 portnum = SIM_VALUE::ToSpice( portnum_param->value );
1099
1100 if( portnum != "" )
1101 portnums.push_back( portnum );
1102 }
1103
1104 for( const std::string& portnum1 : portnums )
1105 {
1106 for( const std::string& portnum2 : portnums )
1107 {
1108 addSignal( wxString::Format( wxS( "S_%s_%s" ), portnum1, portnum2 ) );
1109 }
1110 }
1111 }
1112
1113 // Add .SAVE and .PROBE directives
1114 for( const wxString& directive : circuitModel()->GetDirectives() )
1115 {
1116 wxStringTokenizer directivesTokenizer( directive, "\r\n", wxTOKEN_STRTOK );
1117
1118 while( directivesTokenizer.HasMoreTokens() )
1119 {
1120 wxString line = directivesTokenizer.GetNextToken().Upper();
1121 wxString directiveParams;
1122
1123 if( line.StartsWith( wxS( ".SAVE" ), &directiveParams )
1124 || line.StartsWith( wxS( ".PROBE" ), &directiveParams ) )
1125 {
1126 wxStringTokenizer paramsTokenizer( directiveParams, " \t", wxTOKEN_STRTOK );
1127
1128 while( paramsTokenizer.HasMoreTokens() )
1129 addSignal( paramsTokenizer.GetNextToken() );
1130 }
1131 }
1132 }
1133}
1134
1135
1136SIM_TAB* SIMULATOR_FRAME_UI::NewSimTab( const wxString& aSimCommand )
1137{
1138 SIM_TAB* simTab = nullptr;
1139 SIM_TYPE simType = SPICE_CIRCUIT_MODEL::CommandToSimType( aSimCommand );
1140
1141 if( SIM_TAB::IsPlottable( simType ) )
1142 {
1143 SIM_PLOT_TAB* panel = new SIM_PLOT_TAB( aSimCommand, m_plotNotebook );
1144 simTab = panel;
1146 }
1147 else
1148 {
1149 simTab = new SIM_NOPLOT_TAB( aSimCommand, m_plotNotebook );
1150 }
1151
1152 wxString pageTitle( simulator()->TypeToName( simType, true ) );
1153 pageTitle.Prepend( wxString::Format( _( "Analysis %u - " ), static_cast<unsigned int>( ++m_plotNumber ) ) );
1154
1155 m_plotNotebook->AddPage( simTab, pageTitle, true );
1156
1157 return simTab;
1158}
1159
1160
1161void SIMULATOR_FRAME_UI::OnFilterText( wxCommandEvent& aEvent )
1162{
1163 rebuildSignalsGrid( m_filter->GetValue() );
1164}
1165
1166
1167void SIMULATOR_FRAME_UI::OnFilterMouseMoved( wxMouseEvent& aEvent )
1168{
1169#if defined( __WXOSX__ ) || wxCHECK_VERSION( 3, 3, 0 ) // Doesn't work properly on other ports
1170 wxPoint pos = aEvent.GetPosition();
1171 wxRect ctrlRect = m_filter->GetScreenRect();
1172 int buttonWidth = ctrlRect.GetHeight(); // Presume buttons are square
1173
1174 if( m_filter->IsSearchButtonVisible() && pos.x < buttonWidth )
1175 SetCursor( wxCURSOR_ARROW );
1176 else if( m_filter->IsCancelButtonVisible() && pos.x > ctrlRect.GetWidth() - buttonWidth )
1177 SetCursor( wxCURSOR_ARROW );
1178 else
1179 SetCursor( wxCURSOR_IBEAM );
1180#endif
1181}
1182
1183
1184wxString vectorNameFromSignalId( int aUserDefinedSignalId )
1185{
1186 return wxString::Format( wxS( "user%d" ), aUserDefinedSignalId );
1187}
1188
1189
1195 const wxString& aSignalName,
1196 int* aTraceType )
1197{
1198 std::map<wxString, int> suffixes;
1199 suffixes[ _( " (amplitude)" ) ] = SPT_SP_AMP;
1200 suffixes[ _( " (gain)" ) ] = SPT_AC_GAIN;
1201 suffixes[ _( " (phase)" ) ] = SPT_AC_PHASE;
1202
1203 if( aTraceType )
1204 {
1205 if( aPlotTab && aPlotTab->GetSimType() == ST_NOISE )
1206 {
1207 if( getNoiseSource().Upper().StartsWith( 'I' ) )
1208 *aTraceType = SPT_CURRENT;
1209 else
1210 *aTraceType = SPT_VOLTAGE;
1211 }
1212 else
1213 {
1214 wxUniChar firstChar = aSignalName.Upper()[0];
1215
1216 if( firstChar == 'V' )
1217 *aTraceType = SPT_VOLTAGE;
1218 else if( firstChar == 'I' )
1219 *aTraceType = SPT_CURRENT;
1220 else if( firstChar == 'P' )
1221 *aTraceType = SPT_POWER;
1222 }
1223 }
1224
1225 wxString name = aSignalName;
1226
1227 for( const auto& [ candidate, type ] : suffixes )
1228 {
1229 if( name.EndsWith( candidate ) )
1230 {
1231 name = name.Left( name.Length() - candidate.Length() );
1232
1233 if( aTraceType )
1234 *aTraceType |= type;
1235
1236 break;
1237 }
1238 }
1239
1240 for( const auto& [ id, signal ] : m_userDefinedSignals )
1241 {
1242 if( name == signal )
1243 return vectorNameFromSignalId( id );
1244 }
1245
1246 return name;
1247};
1248
1249
1251{
1252 if( m_SuppressGridEvents > 0 )
1253 return;
1254
1255 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1256
1257 if( !plotTab )
1258 return;
1259
1260 int row = aEvent.GetRow();
1261 int col = aEvent.GetCol();
1262 wxString text = m_signalsGrid->GetCellValue( row, col );
1263 wxString signalName = m_signalsGrid->GetCellValue( row, COL_SIGNAL_NAME );
1264 int traceType = SPT_UNKNOWN;
1265 wxString vectorName = vectorNameFromSignalName( plotTab, signalName, &traceType );
1266
1267 if( col == COL_SIGNAL_SHOW )
1268 {
1269 if( text == wxS( "1" ) )
1270 updateTrace( vectorName, traceType, plotTab );
1271 else
1272 plotTab->DeleteTrace( vectorName, traceType );
1273
1274 plotTab->GetPlotWin()->UpdateAll();
1275
1276 // Update enabled/visible states of other controls
1279 OnModify();
1280 }
1281 else if( col == COL_SIGNAL_COLOR )
1282 {
1283 KIGFX::COLOR4D color( m_signalsGrid->GetCellValue( row, COL_SIGNAL_COLOR ) );
1284 TRACE* trace = plotTab->GetTrace( vectorName, traceType );
1285
1286 if( trace )
1287 {
1288 trace->SetTraceColour( color.ToColour() );
1289 plotTab->UpdateTraceStyle( trace );
1290 plotTab->UpdatePlotColors();
1291 OnModify();
1292 }
1293 }
1294 else if( col == COL_CURSOR_1 || col == COL_CURSOR_2
1295 || ( ( std::size( m_cursorFormatsDyn ) > std::size( m_cursorFormats ) )
1296 && col > COL_CURSOR_2 ) )
1297 {
1298 int id = col == COL_CURSOR_1 ? 1 : 2;
1299
1300 if( col > COL_CURSOR_2 ) // TODO: clean up logic
1301 {
1302 id = col - 2; // enum SIGNALS_GRID_COLUMNS offset for Cursor n
1303 }
1304
1305 TRACE* activeTrace = nullptr;
1306
1307 if( text == wxS( "1" ) )
1308 {
1309 signalName = m_signalsGrid->GetCellValue( row, COL_SIGNAL_NAME );
1310 vectorName = vectorNameFromSignalName( plotTab, signalName, &traceType );
1311 activeTrace = plotTab->GetTrace( vectorName, traceType );
1312
1313 if( activeTrace )
1314 plotTab->EnableCursor( activeTrace, id, signalName );
1315
1316 OnModify();
1317 }
1318
1319 // Turn off cursor on other signals.
1320 for( const auto& [name, trace] : plotTab->GetTraces() )
1321 {
1322 if( trace != activeTrace && trace->HasCursor( id ) )
1323 {
1324 plotTab->DisableCursor( trace, id );
1325 OnModify();
1326 }
1327 }
1328
1329 // Update cursor checkboxes (which are really radio buttons)
1331 }
1332}
1333
1334
1336{
1337 if( m_SuppressGridEvents > 0 )
1338 return;
1339
1340 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1341
1342 if( !plotTab )
1343 return;
1344
1345 int row = aEvent.GetRow();
1346 int col = aEvent.GetCol();
1347 wxString text = m_cursorsGrid->GetCellValue( row, col );
1348 wxString cursorName = m_cursorsGrid->GetCellValue( row, COL_CURSOR_NAME );
1349
1350 double value = SPICE_VALUE( text ).ToDouble();
1351
1352 if( col == COL_CURSOR_X )
1353 {
1354 CURSOR* cursor1 = nullptr;
1355 CURSOR* cursor2 = nullptr;
1356
1357 std::vector<CURSOR*> cursorsVec;
1358 cursorsVec.clear();
1359
1360 for( const auto& [name, trace] : plotTab->GetTraces() )
1361 {
1362 if( CURSOR* cursor = trace->GetCursor( 1 ) )
1363 cursor1 = cursor;
1364
1365 if( CURSOR* cursor = trace->GetCursor( 2 ) )
1366 cursor2 = cursor;
1367
1368 int tmp = 3;
1369
1370 if( !cursor1 )
1371 tmp--;
1372 if( !cursor2 )
1373 tmp--;
1374
1375 for( int i = tmp; i < m_customCursorsCnt; i++ )
1376 {
1377 if( CURSOR* cursor = trace->GetCursor( i ) )
1378 {
1379 cursorsVec.emplace_back( cursor );
1380
1381 if( cursorName == ( wxString( "" ) << i ) && cursor )
1382 cursor->SetCoordX( value );
1383 }
1384 }
1385 }
1386
1387 //double value = SPICE_VALUE( text ).ToDouble();
1388
1389 if( cursorName == wxS( "1" ) && cursor1 )
1390 cursor1->SetCoordX( value );
1391 else if( cursorName == wxS( "2" ) && cursor2 )
1392 cursor2->SetCoordX( value );
1393 else if( cursorName == _( "Diff" ) && cursor1 && cursor2 )
1394 cursor2->SetCoordX( cursor1->GetCoords().x + value );
1395
1397 OnModify();
1398 }
1399 else
1400 {
1401 wxFAIL_MSG( wxT( "All other columns are supposed to be read-only!" ) );
1402 }
1403}
1404
1405
1407{
1409 result.FromString( m_measurementsGrid->GetCellValue( aRow, COL_MEASUREMENT_FORMAT ) );
1410 return result;
1411}
1412
1413
1415{
1416 m_measurementsGrid->SetCellValue( aRow, COL_MEASUREMENT_FORMAT, aFormat.ToString() );
1417}
1418
1419
1421{
1422 if( aRow < ( m_measurementsGrid->GetNumberRows() - 1 ) )
1423 m_measurementsGrid->DeleteRows( aRow, 1 );
1424}
1425
1426
1428{
1429 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1430
1431 if( !plotTab )
1432 return;
1433
1434 int row = aEvent.GetRow();
1435 int col = aEvent.GetCol();
1436
1437 if( col == COL_MEASUREMENT )
1438 {
1439 UpdateMeasurement( row );
1441 OnModify();
1442 }
1443 else
1444 {
1445 wxFAIL_MSG( wxT( "All other columns are supposed to be read-only!" ) );
1446 }
1447
1448 // Always leave a single empty row for type-in
1449
1450 int rowCount = static_cast<int>( m_measurementsGrid->GetNumberRows() );
1451 int emptyRows = 0;
1452
1453 for( row = rowCount - 1; row >= 0; row-- )
1454 {
1455 if( m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1456 emptyRows++;
1457 else
1458 break;
1459 }
1460
1461 if( emptyRows > 1 )
1462 {
1463 int killRows = emptyRows - 1;
1464 m_measurementsGrid->DeleteRows( rowCount - killRows, killRows );
1465 }
1466 else if( emptyRows == 0 )
1467 {
1468 m_measurementsGrid->AppendRows( 1 );
1469 }
1470}
1471
1472
1473void SIMULATOR_FRAME_UI::OnUpdateUI( wxUpdateUIEvent& event )
1474{
1475 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
1476 {
1477 if( plotTab->GetLegendPosition() != plotTab->m_LastLegendPosition )
1478 {
1479 plotTab->m_LastLegendPosition = plotTab->GetLegendPosition();
1480 OnModify();
1481 }
1482 }
1483}
1484
1485
1501{
1502 static wxRegEx measureParamsRegEx( wxT( "^"
1503 " *"
1504 "([a-zA-Z_]+)"
1505 " +"
1506 "([a-zA-Z]*)\\(([^\\)]+)\\)" ) );
1507
1508 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1509
1510 if( !plotTab )
1511 return;
1512
1513 wxString text = m_measurementsGrid->GetCellValue( aRow, COL_MEASUREMENT );
1514
1515 if( text.IsEmpty() )
1516 {
1517 m_measurementsGrid->SetCellValue( aRow, COL_MEASUREMENT_VALUE, wxEmptyString );
1518 return;
1519 }
1520
1521 wxString simType = simulator()->TypeToName( plotTab->GetSimType(), true );
1522 wxString resultName = wxString::Format( wxS( "meas_result_%u" ), aRow );
1523 wxString result = wxS( "?" );
1524
1525 if( measureParamsRegEx.Matches( text ) )
1526 {
1527 wxString func = measureParamsRegEx.GetMatch( text, 1 ).Upper();
1528 wxString signalType = measureParamsRegEx.GetMatch( text, 2 ).Upper();
1529 wxString deviceName = measureParamsRegEx.GetMatch( text, 3 );
1530 wxString units;
1532
1533 if( signalType.EndsWith( wxS( "DB" ) ) )
1534 {
1535 units = wxS( "dB" );
1536 }
1537 else if( signalType.StartsWith( 'I' ) )
1538 {
1539 units = wxS( "A" );
1540 }
1541 else if( signalType.StartsWith( 'P' ) )
1542 {
1543 units = wxS( "W" );
1544 // Our syntax is different from ngspice for power signals
1545 text = func + " " + deviceName + ":power";
1546 }
1547 else
1548 {
1549 units = wxS( "V" );
1550 }
1551
1552 if( func.EndsWith( wxS( "_AT" ) ) )
1553 {
1554 if( plotTab->GetSimType() == ST_AC || plotTab->GetSimType() == ST_SP )
1555 units = wxS( "Hz" );
1556 else
1557 units = wxS( "s" );
1558 }
1559 else if( func.StartsWith( wxS( "INTEG" ) ) )
1560 {
1561 switch( plotTab->GetSimType() )
1562 {
1563 case ST_TRAN:
1564 if ( signalType.StartsWith( 'P' ) )
1565 units = wxS( "J" );
1566 else
1567 units += wxS( ".s" );
1568
1569 break;
1570
1571 case ST_AC:
1572 case ST_SP:
1573 case ST_DISTO:
1574 case ST_NOISE:
1575 case ST_FFT:
1576 case ST_SENS: // If there is a vector, it is frequency
1577 units += wxS( "·Hz" );
1578 break;
1579
1580 case ST_DC: // Could be a lot of things : V, A, deg C, ohm, ...
1581 case ST_OP: // There is no vector for integration
1582 case ST_PZ: // There is no vector for integration
1583 case ST_TF: // There is no vector for integration
1584 default:
1585 units += wxS( "·?" );
1586 break;
1587 }
1588 }
1589
1590 fmt.UpdateUnits( units );
1591 SetMeasureFormat( aRow, fmt );
1592
1594 }
1595
1596 if( m_simulatorFrame->SimFinished() )
1597 {
1598 wxString cmd = wxString::Format( wxS( "meas %s %s %s" ), simType, resultName, text );
1599 simulator()->Command( "echo " + cmd.ToStdString() );
1600 simulator()->Command( cmd.ToStdString() );
1601
1602 std::vector<double> resultVec = simulator()->GetGainVector( resultName.ToStdString() );
1603
1604 if( resultVec.size() > 0 )
1605 result = SPICE_VALUE( resultVec[0] ).ToString( GetMeasureFormat( aRow ) );
1606 }
1607
1608 m_measurementsGrid->SetCellValue( aRow, COL_MEASUREMENT_VALUE, result );
1609}
1610
1611
1612void SIMULATOR_FRAME_UI::AddTuner( const SCH_SHEET_PATH& aSheetPath, SCH_SYMBOL* aSymbol )
1613{
1614 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1615
1616 if( !plotTab )
1617 {
1618 DisplayErrorMessage( nullptr, _( "The current analysis must have a plot in order to tune "
1619 "the value of a passive R, L, C model or voltage or "
1620 "current source." ) );
1621 return;
1622 }
1623
1624 wxString ref = aSymbol->GetRef( &aSheetPath );
1625
1626 // Do not add multiple instances for the same component.
1627 for( TUNER_SLIDER* tuner : m_tuners )
1628 {
1629 if( tuner->GetSymbolRef() == ref )
1630 return;
1631 }
1632
1633 if( [[maybe_unused]] const SPICE_ITEM* item = GetExporter()->FindItem( ref ) )
1634 {
1635 try
1636 {
1637 TUNER_SLIDER* tuner = new TUNER_SLIDER( this, m_panelTuners, aSheetPath, aSymbol );
1638 m_sizerTuners->Add( tuner );
1639 m_tuners.push_back( tuner );
1640 m_panelTuners->Layout();
1641 OnModify();
1642 }
1643 catch( const KI_PARAM_ERROR& e )
1644 {
1645 DisplayErrorMessage( nullptr, e.What() );
1646 }
1647 }
1648}
1649
1650
1651void SIMULATOR_FRAME_UI::UpdateTunerValue( const SCH_SHEET_PATH& aSheetPath, const KIID& aSymbol,
1652 const wxString& aRef, const wxString& aValue )
1653{
1654 SCH_ITEM* item = aSheetPath.ResolveItem( aSymbol );
1655 SCH_SYMBOL* symbol = dynamic_cast<SCH_SYMBOL*>( item );
1656
1657 if( !symbol )
1658 {
1659 DisplayErrorMessage( this, _( "Could not apply tuned value(s):" ) + wxS( " " )
1660 + wxString::Format( _( "%s not found" ), aRef ) );
1661 return;
1662 }
1663
1664 NULL_REPORTER devnull;
1665 SIM_LIB_MGR mgr( &m_schematicFrame->Prj() );
1666
1667 std::vector<EMBEDDED_FILES*> embeddedFilesStack;
1668 embeddedFilesStack.push_back( m_schematicFrame->Schematic().GetEmbeddedFiles() );
1669
1670 if( EMBEDDED_FILES* symbolEmbeddedFiles = symbol->GetEmbeddedFiles() )
1671 embeddedFilesStack.push_back( symbolEmbeddedFiles );
1672
1673 mgr.SetFilesStack( std::move( embeddedFilesStack ) );
1674
1675 SIM_MODEL& model = mgr.CreateModel( &aSheetPath, *symbol, true, 0, devnull ).model;
1676
1677 const SIM_MODEL::PARAM* tunerParam = model.GetTunerParam();
1678
1679 if( !tunerParam )
1680 {
1681 DisplayErrorMessage( this, _( "Could not apply tuned value(s):" ) + wxS( " " )
1682 + wxString::Format( _( "%s is not tunable" ), aRef ) );
1683 return;
1684 }
1685
1686 model.SetParamValue( tunerParam->info.name, std::string( aValue.ToUTF8() ) );
1687 model.WriteFields( symbol->GetFields() );
1688
1689 m_schematicFrame->UpdateItem( symbol, false, true );
1690 m_schematicFrame->OnModify();
1691}
1692
1693
1695{
1696 m_tuners.remove( aTuner );
1697 aTuner->Destroy();
1698 m_panelTuners->Layout();
1699 OnModify();
1700}
1701
1702
1703void SIMULATOR_FRAME_UI::AddMeasurement( const wxString& aCmd )
1704{
1705 // -1 because the last one is for user input
1706 for( int i = 0; i < m_measurementsGrid->GetNumberRows(); i++ )
1707 {
1708 if ( m_measurementsGrid->GetCellValue( i, COL_MEASUREMENT ) == aCmd )
1709 return; // Don't create duplicates
1710 }
1711
1712 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1713
1714 if( !plotTab )
1715 return;
1716
1717 int row;
1718
1719 for( row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
1720 {
1721 if( m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1722 break;
1723 }
1724
1725 if( !m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1726 {
1727 m_measurementsGrid->AppendRows( 1 );
1728 row = m_measurementsGrid->GetNumberRows() - 1;
1729 }
1730
1731 m_measurementsGrid->SetCellValue( row, COL_MEASUREMENT, aCmd );
1732
1733 UpdateMeasurement( row );
1735 OnModify();
1736
1737 // Always leave at least one empty row for type-in:
1738 row = m_measurementsGrid->GetNumberRows() - 1;
1739
1740 if( !m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1741 m_measurementsGrid->AppendRows( 1 );
1742}
1743
1744
1745void SIMULATOR_FRAME_UI::DoFourier( const wxString& aSignal, const wxString& aFundamental )
1746{
1747 wxString cmd = wxString::Format( wxS( "fourier %s %s" ),
1748 SPICE_VALUE( aFundamental ).ToSpiceString(),
1749 aSignal );
1750
1751 simulator()->Command( cmd.ToStdString() );
1752}
1753
1754
1756{
1757 return circuitModel().get();
1758}
1759
1760
1761void SIMULATOR_FRAME_UI::AddTrace( const wxString& aName, SIM_TRACE_TYPE aType )
1762{
1763 if( !GetCurrentSimTab() )
1764 {
1765 m_simConsole->AppendText( _( "Error: no current simulation.\n" ) );
1766 m_simConsole->SetInsertionPointEnd();
1767 return;
1768 }
1769
1770 SIM_TYPE simType = SPICE_CIRCUIT_MODEL::CommandToSimType( GetCurrentSimTab()->GetSimCommand() );
1771
1772 if( simType == ST_UNKNOWN )
1773 {
1774 m_simConsole->AppendText( _( "Error: simulation type not defined.\n" ) );
1775 m_simConsole->SetInsertionPointEnd();
1776 return;
1777 }
1778 else if( !SIM_TAB::IsPlottable( simType ) )
1779 {
1780 m_simConsole->AppendText( _( "Error: simulation type doesn't support plotting.\n" ) );
1781 m_simConsole->SetInsertionPointEnd();
1782 return;
1783 }
1784
1785 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
1786 {
1787 if( simType == ST_AC )
1788 {
1789 updateTrace( aName, aType | SPT_AC_GAIN, plotTab );
1790 updateTrace( aName, aType | SPT_AC_PHASE, plotTab );
1791 }
1792 else if( simType == ST_SP )
1793 {
1794 updateTrace( aName, aType | SPT_AC_GAIN, plotTab );
1795 updateTrace( aName, aType | SPT_AC_PHASE, plotTab );
1796 }
1797 else
1798 {
1799 updateTrace( aName, aType, plotTab );
1800 }
1801
1802 plotTab->GetPlotWin()->UpdateAll();
1803 }
1804
1806 OnModify();
1807}
1808
1809
1810void SIMULATOR_FRAME_UI::SetUserDefinedSignals( const std::map<int, wxString>& aNewSignals )
1811{
1812 for( size_t ii = 0; ii < m_plotNotebook->GetPageCount(); ++ii )
1813 {
1814 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( m_plotNotebook->GetPage( ii ) );
1815
1816 if( !plotTab )
1817 continue;
1818
1819 for( const auto& [ id, existingSignal ] : m_userDefinedSignals )
1820 {
1821 int traceType = SPT_UNKNOWN;
1822 wxString vectorName = vectorNameFromSignalName( plotTab, existingSignal, &traceType );
1823
1824 if( aNewSignals.count( id ) == 0 )
1825 {
1826 if( plotTab->GetSimType() == ST_AC )
1827 {
1828 for( int subType : { SPT_AC_GAIN, SPT_AC_PHASE } )
1829 plotTab->DeleteTrace( vectorName, traceType | subType );
1830 }
1831 else if( plotTab->GetSimType() == ST_SP )
1832 {
1833 for( int subType : { SPT_SP_AMP, SPT_AC_PHASE } )
1834 plotTab->DeleteTrace( vectorName, traceType | subType );
1835 }
1836 else
1837 {
1838 plotTab->DeleteTrace( vectorName, traceType );
1839 }
1840 }
1841 else
1842 {
1843 if( plotTab->GetSimType() == ST_AC )
1844 {
1845 for( int subType : { SPT_AC_GAIN, SPT_AC_PHASE } )
1846 {
1847 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType | subType ) )
1848 trace->SetName( aNewSignals.at( id ) );
1849 }
1850 }
1851 else if( plotTab->GetSimType() == ST_SP )
1852 {
1853 for( int subType : { SPT_SP_AMP, SPT_AC_PHASE } )
1854 {
1855 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType | subType ) )
1856 trace->SetName( aNewSignals.at( id ) );
1857 }
1858 }
1859 else
1860 {
1861 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType ) )
1862 trace->SetName( aNewSignals.at( id ) );
1863 }
1864 }
1865 }
1866 }
1867
1868 m_userDefinedSignals = aNewSignals;
1869
1870 if( m_simulatorFrame->SimFinished() )
1872
1874 rebuildSignalsGrid( m_filter->GetValue() );
1877 OnModify();
1878}
1879
1880
1881void SIMULATOR_FRAME_UI::updateTrace( const wxString& aVectorName, int aTraceType,
1882 SIM_PLOT_TAB* aPlotTab, std::vector<double>* aDataX,
1883 bool aClearData )
1884{
1885 if( !m_simulatorFrame->SimFinished() && !simulator()->IsRunning())
1886 {
1887 aPlotTab->GetOrAddTrace( aVectorName, aTraceType );
1888 return;
1889 }
1890
1892
1893 aTraceType &= aTraceType & SPT_Y_AXIS_MASK;
1894 aTraceType |= getXAxisType( simType );
1895
1896 wxString simVectorName = aVectorName;
1897
1898 if( aTraceType & SPT_POWER )
1899 simVectorName = simVectorName.AfterFirst( '(' ).BeforeLast( ')' ) + wxS( ":power" );
1900
1901 if( !SIM_TAB::IsPlottable( simType ) )
1902 {
1903 // There is no plot to be shown
1904 simulator()->Command( wxString::Format( wxT( "print %s" ), aVectorName ).ToStdString() );
1905
1906 return;
1907 }
1908
1909 std::vector<double> data_x;
1910 std::vector<double> data_y;
1911
1912 if( !aDataX || aClearData )
1913 aDataX = &data_x;
1914
1915 // First, handle the x axis
1916 if( aDataX->empty() && !aClearData )
1917 {
1918 wxString xAxisName( simulator()->GetXAxis( simType ) );
1919
1920 if( xAxisName.IsEmpty() )
1921 return;
1922
1923 *aDataX = simulator()->GetGainVector( (const char*) xAxisName.c_str() );
1924 }
1925
1926 unsigned int size = aDataX->size();
1927
1928 switch( simType )
1929 {
1930 case ST_AC:
1931 if( aTraceType & SPT_AC_GAIN )
1932 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), size );
1933 else if( aTraceType & SPT_AC_PHASE )
1934 data_y = simulator()->GetPhaseVector( (const char*) simVectorName.c_str(), size );
1935 else
1936 wxFAIL_MSG( wxT( "Plot type missing AC_PHASE or AC_MAG bit" ) );
1937
1938 break;
1939 case ST_SP:
1940 if( aTraceType & SPT_SP_AMP )
1941 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), size );
1942 else if( aTraceType & SPT_AC_PHASE )
1943 data_y = simulator()->GetPhaseVector( (const char*) simVectorName.c_str(), size );
1944 else
1945 wxFAIL_MSG( wxT( "Plot type missing AC_PHASE or SPT_SP_AMP bit" ) );
1946
1947 break;
1948
1949 case ST_DC:
1950 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), -1 );
1951 break;
1952
1953 case ST_NOISE:
1954 case ST_TRAN:
1955 case ST_FFT:
1956 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), size );
1957 break;
1958
1959 default:
1960 wxFAIL_MSG( wxT( "Unhandled plot type" ) );
1961 }
1962
1963 SPICE_DC_PARAMS source1, source2;
1964 int sweepCount = 1;
1965 size_t sweepSize = std::numeric_limits<size_t>::max();
1966
1967 if( simType == ST_DC
1968 && circuitModel()->ParseDCCommand( aPlotTab->GetSimCommand(), &source1, &source2 )
1969 && !source2.m_source.IsEmpty() )
1970 {
1971 SPICE_VALUE v = ( source2.m_vend - source2.m_vstart ) / source2.m_vincrement;
1972
1973 sweepCount = KiROUND( v.ToDouble() ) + 1;
1974 sweepSize = aDataX->size() / sweepCount;
1975 }
1976
1977 if( TRACE* trace = aPlotTab->GetOrAddTrace( aVectorName, aTraceType ) )
1978 {
1979 if( data_y.size() >= size )
1980 aPlotTab->SetTraceData( trace, *aDataX, data_y, sweepCount, sweepSize );
1981 }
1982}
1983
1984
1985// TODO make sure where to instantiate and how to style correct
1986// Better ask someone..
1988 SIGNALS_GRID_COLUMNS, int, int );
1989
1990template <typename T, typename U, typename R>
1991void SIMULATOR_FRAME_UI::signalsGridCursorUpdate( T t, U u, R r ) // t=cursor type/signals' grid col, u=cursor number/cursor "id", r=table's row
1992{
1993 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1994
1995 wxString signalName = m_signalsGrid->GetCellValue( r, COL_SIGNAL_NAME );
1996 int traceType = SPT_UNKNOWN;
1997 wxString vectorName = vectorNameFromSignalName( plotTab, signalName, &traceType );
1998
1999 wxGridCellAttrPtr attr = m_signalsGrid->GetOrCreateCellAttrPtr( r, static_cast<int>( t ) );
2000
2001 if( TRACE* trace = plotTab ? plotTab->GetTrace( vectorName, traceType ) : nullptr )
2002 {
2003 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
2004
2006 {
2007 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
2008 }
2009
2010 if constexpr ( std::is_enum<T>::value )
2011 {
2013 {
2014 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), wxS( "1" ) );
2015 }
2017 {
2018 if( !attr->HasRenderer() )
2019 attr->SetRenderer( new GRID_CELL_COLOR_RENDERER( this ) );
2020
2021 if( !attr->HasEditor() )
2022 attr->SetEditor( new GRID_CELL_COLOR_SELECTOR( this, m_signalsGrid ) );
2023
2024 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
2025 attr->SetReadOnly( false );
2026
2027 KIGFX::COLOR4D color( trace->GetPen().GetColour() );
2028 m_signalsGrid->SetCellValue( r, COL_SIGNAL_COLOR, color.ToCSSString() );
2029 }
2033 {
2034 if( !attr->HasRenderer() )
2035 attr->SetRenderer( new wxGridCellBoolRenderer() );
2036
2037 if( u > 0 && trace->HasCursor( u ) )
2038 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), wxS( "1" ) );
2039 else
2040 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), wxEmptyString );
2041 }
2042 }
2043 }
2044 else
2045 {
2046 if constexpr ( std::is_enum<T>::value )
2047 {
2049 {
2050 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), wxEmptyString );
2051 }
2056 {
2057 attr->SetEditor( nullptr );
2058 attr->SetRenderer( nullptr );
2059 attr->SetReadOnly();
2060 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), wxEmptyString );
2061 }
2062 }
2063 }
2064}
2065
2066
2068{
2069 for( int row = 0; row < m_signalsGrid->GetNumberRows(); ++row )
2070 {
2075
2076 if( ( m_signalsGrid->GetNumberCols() - 1 ) > COL_CURSOR_2 )
2077 {
2078 for( int i = 3; i < m_customCursorsCnt; i++ )
2079 {
2080 int tm = i + 2;
2082 static_cast<SIGNALS_GRID_COLUMNS>( tm ),
2083 i,
2084 row );
2085 }
2086 }
2087 }
2088 m_signalsGrid->Refresh();
2089}
2090
2091
2093{
2094 auto quoteNetNames = [&]( wxString aExpression ) -> wxString
2095 {
2096 std::vector<bool> mask( aExpression.length(), false );
2097
2098 for( const auto& netname : m_netnames )
2099 {
2100 size_t pos = aExpression.find( netname );
2101
2102 while( pos != wxString::npos )
2103 {
2104 for( size_t i = 0; i < netname.length(); ++i )
2105 {
2106 mask[pos + i] = true; // Mark the positions of the netname
2107 }
2108 pos = aExpression.find( netname, pos + 1 ); // Find the next occurrence
2109 }
2110 }
2111
2112 wxString quotedNetnames = "";
2113 bool startQuote = true;
2114
2115 // put quotes around all the positions that were found above
2116 for( size_t i = 0; i < aExpression.length(); i++ )
2117 {
2118 if( mask[i] && startQuote )
2119 {
2120 quotedNetnames = quotedNetnames + "\"";
2121 startQuote = false;
2122 }
2123 else if( !mask[i] && !startQuote )
2124 {
2125 quotedNetnames = quotedNetnames + "\"";
2126 startQuote = true;
2127 }
2128 wxString ch = aExpression[i];
2129 quotedNetnames = quotedNetnames + ch;
2130 }
2131
2132 if( !startQuote )
2133 {
2134 quotedNetnames = quotedNetnames + "\"";
2135 }
2136 return quotedNetnames;
2137 };
2138
2139 for( const auto& [ id, signal ] : m_userDefinedSignals )
2140 {
2141 constexpr const char* cmd = "let user{} = {}";
2142
2143 simulator()->Command( "echo " + fmt::format( cmd, id, signal.ToStdString() ) );
2144 simulator()->Command( fmt::format( cmd, id, quoteNetNames( signal ).ToStdString() ) );
2145 }
2146}
2147
2148
2150{
2151 WX_STRING_REPORTER reporter;
2152
2153 for( const TUNER_SLIDER* tuner : m_tuners )
2154 {
2155 SCH_SHEET_PATH sheetPath;
2156 wxString ref = tuner->GetSymbolRef();
2157 KIID symbolId = tuner->GetSymbol( &sheetPath );
2158 SCH_ITEM* schItem = sheetPath.ResolveItem( symbolId );
2159 SCH_SYMBOL* symbol = dynamic_cast<SCH_SYMBOL*>( schItem );
2160
2161 if( !symbol )
2162 {
2163 reporter.Report( wxString::Format( _( "%s not found" ), ref ) );
2164 continue;
2165 }
2166
2167 const SPICE_ITEM* item = GetExporter()->FindItem( tuner->GetSymbolRef() );
2168
2169 if( !item || !item->model->GetTunerParam() )
2170 {
2171 reporter.Report( wxString::Format( _( "%s is not tunable" ), ref ) );
2172 continue;
2173 }
2174
2175 double floatVal = tuner->GetValue().ToDouble();
2176
2177 simulator()->Command( item->model->SpiceGenerator().TunerCommand( *item, floatVal ) );
2178 }
2179
2180 if( reporter.HasMessage() )
2181 DisplayErrorMessage( this, _( "Could not apply tuned value(s):" ) + wxS( "\n" )
2182 + reporter.GetMessages() );
2183}
2184
2185bool SIMULATOR_FRAME_UI::LoadWorkbook( const wxString& aPath )
2186{
2187 wxTextFile file( aPath );
2188
2189 if( !file.Open() )
2190 return false;
2191
2192 wxString firstLine = file.GetFirstLine();
2193 long dummy;
2194 bool legacy = firstLine.StartsWith( wxT( "version " ) ) || firstLine.ToLong( &dummy );
2195
2196 file.Close();
2197
2198 m_plotNotebook->DeleteAllPages();
2199 m_userDefinedSignals.clear();
2200
2201 if( legacy )
2202 {
2203 if( !loadLegacyWorkbook( aPath ) )
2204 return false;
2205 }
2206 else
2207 {
2208 if( !loadJsonWorkbook( aPath ) )
2209 return false;
2210 }
2211
2213
2214 rebuildSignalsGrid( m_filter->GetValue() );
2218
2219 wxFileName filename( aPath );
2220 filename.MakeRelativeTo( m_schematicFrame->Prj().GetProjectPath() );
2221
2222 // Remember the loaded workbook filename.
2223 simulator()->Settings()->SetWorkbookFilename( filename.GetFullPath() );
2224
2225 return true;
2226}
2227
2228
2229bool SIMULATOR_FRAME_UI::loadJsonWorkbook( const wxString& aPath )
2230{
2231 wxFFileInputStream fp( aPath, wxT( "rt" ) );
2232 wxStdInputStream fstream( fp );
2233
2234 if( !fp.IsOk() )
2235 return false;
2236
2237 try
2238 {
2239 nlohmann::json js = nlohmann::json::parse( fstream, nullptr, true, true );
2240
2241 std::map<SIM_PLOT_TAB*, nlohmann::json> traceInfo;
2242
2243 for( const nlohmann::json& tab_js : js[ "tabs" ] )
2244 {
2245 wxString simCommand;
2248
2249 for( const nlohmann::json& cmd : tab_js[ "commands" ] )
2250 {
2251 if( cmd == ".kicad adjustpaths" )
2253 else if( cmd == ".save all" )
2255 else if( cmd == ".probe alli" )
2257 else if( cmd == ".probe allp" )
2259 else if( cmd == ".kicad esavenone" )
2260 simOptions &= ~NETLIST_EXPORTER_SPICE::OPTION_SAVE_ALL_EVENTS;
2261 else
2262 simCommand += wxString( cmd.get<wxString>() ).Trim();
2263 }
2264
2265 SIM_TAB* simTab = NewSimTab( simCommand );
2266 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( simTab );
2267
2268 simTab->SetSimOptions( simOptions );
2269
2270 if( plotTab )
2271 {
2272 if( tab_js.contains( "traces" ) )
2273 traceInfo[plotTab] = tab_js[ "traces" ];
2274
2275 if( tab_js.contains( "measurements" ) )
2276 {
2277 for( const nlohmann::json& m_js : tab_js[ "measurements" ] )
2278 plotTab->Measurements().emplace_back( m_js[ "expr" ], m_js[ "format" ] );
2279 }
2280
2281 plotTab->SetDottedSecondary( tab_js[ "dottedSecondary" ] );
2282 plotTab->ShowGrid( tab_js[ "showGrid" ] );
2283
2284 if( tab_js.contains( "fixedY1scale" ) )
2285 {
2286 const nlohmann::json& scale_js = tab_js[ "fixedY1scale" ];
2287 plotTab->SetY1Scale( true, scale_js[ "min" ], scale_js[ "max" ] );
2288 plotTab->GetPlotWin()->LockY( true );
2289 }
2290
2291 if( tab_js.contains( "fixedY2scale" ) )
2292 {
2293 const nlohmann::json& scale_js = tab_js[ "fixedY2scale" ];
2294 plotTab->SetY2Scale( true, scale_js[ "min" ], scale_js[ "max" ] );
2295 plotTab->GetPlotWin()->LockY( true );
2296 }
2297
2298 if( tab_js.contains( "fixedY3scale" ) )
2299 {
2300 plotTab->EnsureThirdYAxisExists();
2301 const nlohmann::json& scale_js = tab_js[ "fixedY3scale" ];
2302 plotTab->SetY3Scale( true, scale_js[ "min" ], scale_js[ "max" ] );
2303 plotTab->GetPlotWin()->LockY( true );
2304 }
2305
2306 if( tab_js.contains( "legend" ) )
2307 {
2308 const nlohmann::json& legend_js = tab_js[ "legend" ];
2309 plotTab->SetLegendPosition( wxPoint( legend_js[ "x" ], legend_js[ "y" ] ) );
2310 plotTab->ShowLegend( true );
2311 }
2312
2313 if( tab_js.contains( "margins" ) )
2314 {
2315 const nlohmann::json& margins_js = tab_js[ "margins" ];
2316 plotTab->GetPlotWin()->SetMargins( margins_js[ "top" ],
2317 margins_js[ "right" ],
2318 margins_js[ "bottom" ],
2319 margins_js[ "left" ] );
2320 }
2321 }
2322 }
2323
2324 int ii = 0;
2325
2326 if( js.contains( "user_defined_signals" ) )
2327 {
2328 for( const nlohmann::json& signal_js : js[ "user_defined_signals" ] )
2329 m_userDefinedSignals[ii++] = wxString( signal_js.get<wxString>() );
2330 }
2331
2332 if( SIM_TAB* simTab = GetCurrentSimTab() )
2333 {
2334 m_simulatorFrame->LoadSimulator( simTab->GetSimCommand(), simTab->GetSimOptions() );
2335
2336 if( SIM_TAB* firstTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( 0 ) ) )
2337 firstTab->SetLastSchTextSimCommand( js["last_sch_text_sim_command"] );
2338 }
2339
2340 int tempCustomCursorsCnt = 0;
2341
2342 if( js.contains( "custom_cursors" ) )
2343 tempCustomCursorsCnt = js["custom_cursors"];
2344 else
2345 tempCustomCursorsCnt = 2; // Kind of virtual, for the initial loading of the new setting
2346
2347 if( ( tempCustomCursorsCnt > m_customCursorsCnt ) && m_customCursorsCnt > 2 )
2348 tempCustomCursorsCnt = 2 * tempCustomCursorsCnt - m_customCursorsCnt;
2349
2350 for( int yy = 0; yy <= ( tempCustomCursorsCnt - m_customCursorsCnt ); yy++ )
2352
2353 auto addCursor =
2354 [=,this]( SIM_PLOT_TAB* aPlotTab, TRACE* aTrace, const wxString& aSignalName,
2355 int aCursorId, const nlohmann::json& aCursor_js )
2356 {
2357 if( aCursorId >= 1 )
2358 {
2359 CURSOR* cursor = new CURSOR( aTrace, aPlotTab );
2360
2361 cursor->SetName( aSignalName );
2362 cursor->SetCoordX( aCursor_js[ "position" ] );
2363
2364 aTrace->SetCursor( aCursorId, cursor );
2365 aPlotTab->GetPlotWin()->AddLayer( cursor );
2366 }
2367
2368 if( aCursorId == -1 )
2369 {
2370 // We are a "cursorD"
2371 m_cursorFormatsDyn[2][0].FromString( aCursor_js["x_format"] );
2372 m_cursorFormatsDyn[2][1].FromString( aCursor_js["y_format"] );
2373 }
2374 else
2375 {
2376 if( aCursorId < 3 )
2377 {
2378 m_cursorFormatsDyn[aCursorId - 1][0].FromString(
2379 aCursor_js["x_format"] );
2380 m_cursorFormatsDyn[aCursorId - 1][1].FromString(
2381 aCursor_js["y_format"] );
2382 }
2383 else
2384 {
2385 m_cursorFormatsDyn[aCursorId][0].FromString( aCursor_js["x_format"] );
2386 m_cursorFormatsDyn[aCursorId][1].FromString( aCursor_js["y_format"] );
2387 }
2388 }
2389 };
2390
2391 for( const auto& [ plotTab, traces_js ] : traceInfo )
2392 {
2393 for( const nlohmann::json& trace_js : traces_js )
2394 {
2395 wxString signalName = trace_js[ "signal" ];
2396 wxString vectorName = vectorNameFromSignalName( plotTab, signalName, nullptr );
2397 TRACE* trace = plotTab->GetOrAddTrace( vectorName, trace_js[ "trace_type" ] );
2398
2399 if( trace )
2400 {
2401 if( trace_js.contains( "cursorD" ) )
2402 addCursor( plotTab, trace, signalName, -1, trace_js[ "cursorD" ] );
2403
2404 std::vector<const char*> aVec;
2405 aVec.clear();
2406
2407 for( int i = 1; i <= tempCustomCursorsCnt; i++ )
2408 {
2409 wxString str = "cursor" + std::to_string( i );
2410 aVec.emplace_back( str.c_str() );
2411
2412 if( trace_js.contains( aVec[i - 1] ) )
2413 addCursor( plotTab, trace, signalName, i, trace_js[aVec[i - 1]] );
2414 }
2415
2416 if( trace_js.contains( "color" ) )
2417 {
2418 wxColour color;
2419 color.Set( wxString( trace_js["color"].get<wxString>() ) );
2420 trace->SetTraceColour( color );
2421 plotTab->UpdateTraceStyle( trace );
2422 }
2423 }
2424 }
2425
2426 plotTab->UpdatePlotColors();
2427 }
2428 }
2429 catch( nlohmann::json::parse_error& error )
2430 {
2431 wxLogTrace( traceSettings, wxT( "Json parse error reading %s: %s" ), aPath, error.what() );
2432
2433 return false;
2434 }
2435 catch( nlohmann::json::type_error& error )
2436 {
2437 wxLogTrace( traceSettings, wxT( "Json type error reading %s: %s" ), aPath, error.what() );
2438
2439 return false;
2440 }
2441 catch( nlohmann::json::invalid_iterator& error )
2442 {
2443 wxLogTrace( traceSettings, wxT( "Json invalid_iterator error reading %s: %s" ), aPath, error.what() );
2444
2445 return false;
2446 }
2447 catch( nlohmann::json::out_of_range& error )
2448 {
2449 wxLogTrace( traceSettings, wxT( "Json out_of_range error reading %s: %s" ), aPath, error.what() );
2450
2451 return false;
2452 }
2453 catch( ... )
2454 {
2455 wxLogTrace( traceSettings, wxT( "Error reading %s" ), aPath );
2456 return false;
2457 }
2458
2459 return true;
2460}
2461
2462void SIMULATOR_FRAME_UI::SaveCursorToWorkbook( nlohmann::json& aTraceJs, TRACE* aTrace, int aCursorId )
2463{
2464 int cursorIdAfterD = aCursorId;
2465
2466 if( aCursorId > 3 )
2467 cursorIdAfterD = cursorIdAfterD - 1;
2468
2469
2470 if( CURSOR* cursor = aTrace->GetCursor( aCursorId ) )
2471 {
2472 aTraceJs["cursor" + wxString( "" ) << aCursorId] =
2473 nlohmann::json( { { "position", cursor->GetCoords().x },
2474 { "x_format", m_cursorFormatsDyn[cursorIdAfterD][0].ToString() },
2475 { "y_format", m_cursorFormatsDyn[cursorIdAfterD][1].ToString() } } );
2476 }
2477
2478 if( cursorIdAfterD < 3 && ( aTrace->GetCursor( 1 ) || aTrace->GetCursor( 2 ) ) )
2479 {
2480 aTraceJs["cursorD"] =
2481 nlohmann::json( { { "x_format", m_cursorFormatsDyn[2][0].ToString() },
2482 { "y_format", m_cursorFormatsDyn[2][1].ToString() } } );
2483 }
2484}
2485
2486
2487bool SIMULATOR_FRAME_UI::SaveWorkbook( const wxString& aPath )
2488{
2490
2491 wxFileName filename = aPath;
2492 filename.SetExt( FILEEXT::WorkbookFileExtension );
2493
2494 wxFile file;
2495
2496 file.Create( filename.GetFullPath(), true /* overwrite */ );
2497
2498 if( !file.IsOpened() )
2499 return false;
2500
2501 nlohmann::json tabs_js = nlohmann::json::array();
2502
2503 for( size_t i = 0; i < m_plotNotebook->GetPageCount(); i++ )
2504 {
2505 SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( i ) );
2506
2507 if( !simTab )
2508 continue;
2509
2510 SIM_TYPE simType = simTab->GetSimType();
2511
2512 nlohmann::json commands_js = nlohmann::json::array();
2513
2514 commands_js.push_back( simTab->GetSimCommand() );
2515
2516 int options = simTab->GetSimOptions();
2517
2519 commands_js.push_back( ".kicad adjustpaths" );
2520
2522 commands_js.push_back( ".save all" );
2523
2525 commands_js.push_back( ".probe alli" );
2526
2528 commands_js.push_back( ".probe allp" );
2529
2531 commands_js.push_back( ".kicad esavenone" );
2532
2533 nlohmann::json tab_js = nlohmann::json(
2534 { { "analysis", SPICE_SIMULATOR::TypeToName( simType, true ) },
2535 { "commands", commands_js } } );
2536
2537 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( simTab ) )
2538 {
2539 nlohmann::json traces_js = nlohmann::json::array();
2540
2541 auto findSignalName =
2542 [&]( const wxString& aVectorName ) -> wxString
2543 {
2544 wxString vectorName;
2545 wxString suffix;
2546
2547 if( aVectorName.EndsWith( _( " (phase)" ) ) )
2548 suffix = _( " (phase)" );
2549 else if( aVectorName.EndsWith( _( " (gain)" ) ) )
2550 suffix = _( " (gain)" );
2551
2552 vectorName = aVectorName.Left( aVectorName.Length() - suffix.Length() );
2553
2554 for( const auto& [ id, signal ] : m_userDefinedSignals )
2555 {
2556 if( vectorName == vectorNameFromSignalId( id ) )
2557 return signal + suffix;
2558 }
2559
2560 return aVectorName;
2561 };
2562
2563 for( const auto& [name, trace] : plotTab->GetTraces() )
2564 {
2565 nlohmann::json trace_js = nlohmann::json(
2566 { { "trace_type", (int) trace->GetType() },
2567 { "signal", findSignalName( trace->GetDisplayName() ) },
2568 { "color", COLOR4D( trace->GetTraceColour() ).ToCSSString() } } );
2569
2570 for( int ii = 1; ii <= m_customCursorsCnt; ii++ )
2571 SaveCursorToWorkbook( trace_js, trace, ii );
2572
2573 if( trace->GetCursor( 1 ) || trace->GetCursor( 2 ) )
2574 {
2575 trace_js["cursorD"] = nlohmann::json(
2576 { { "x_format", m_cursorFormatsDyn[2][0].ToString() },
2577 { "y_format", m_cursorFormatsDyn[2][1].ToString() } } );
2578 }
2579
2580 traces_js.push_back( trace_js );
2581 }
2582
2583 nlohmann::json measurements_js = nlohmann::json::array();
2584
2585 for( const auto& [ measurement, format ] : plotTab->Measurements() )
2586 {
2587 measurements_js.push_back( nlohmann::json( { { "expr", measurement },
2588 { "format", format } } ) );
2589 }
2590
2591 tab_js[ "traces" ] = traces_js;
2592 tab_js[ "measurements" ] = measurements_js;
2593 tab_js[ "dottedSecondary" ] = plotTab->GetDottedSecondary();
2594 tab_js[ "showGrid" ] = plotTab->IsGridShown();
2595
2596 double min, max;
2597
2598 if( plotTab->GetY1Scale( &min, &max ) )
2599 tab_js[ "fixedY1scale" ] = nlohmann::json( { { "min", min }, { "max", max } } );
2600
2601 if( plotTab->GetY2Scale( &min, &max ) )
2602 tab_js[ "fixedY2scale" ] = nlohmann::json( { { "min", min }, { "max", max } } );
2603
2604 if( plotTab->GetY3Scale( &min, &max ) )
2605 tab_js[ "fixedY3scale" ] = nlohmann::json( { { "min", min }, { "max", max } } );
2606
2607 if( plotTab->IsLegendShown() )
2608 {
2609 tab_js[ "legend" ] = nlohmann::json( { { "x", plotTab->GetLegendPosition().x },
2610 { "y", plotTab->GetLegendPosition().y } } );
2611 }
2612
2613 mpWindow* plotWin = plotTab->GetPlotWin();
2614
2615 tab_js[ "margins" ] = nlohmann::json( { { "left", plotWin->GetMarginLeft() },
2616 { "right", plotWin->GetMarginRight() },
2617 { "top", plotWin->GetMarginTop() },
2618 { "bottom", plotWin->GetMarginBottom() } } );
2619 }
2620
2621 tabs_js.push_back( tab_js );
2622 }
2623
2624 nlohmann::json userDefinedSignals_js = nlohmann::json::array();
2625
2626 for( const auto& [ id, signal ] : m_userDefinedSignals )
2627 userDefinedSignals_js.push_back( signal );
2628
2629 // clang-format off
2630 nlohmann::json js = nlohmann::json( { { "version", 7 },
2631 { "tabs", tabs_js },
2632 { "user_defined_signals", userDefinedSignals_js },
2633 { "custom_cursors", m_customCursorsCnt - 1 } } ); // Since we start +1 on init
2634 // clang-format on
2635
2636 // Store the value of any simulation command found on the schematic sheet in a SCH_TEXT
2637 // object. If this changes we want to warn the user and ask them if they want to update
2638 // the corresponding panel's sim command.
2639 if( m_plotNotebook->GetPageCount() > 0 )
2640 {
2641 SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( 0 ) );
2642 js[ "last_sch_text_sim_command" ] = simTab->GetLastSchTextSimCommand();
2643 }
2644
2645 std::stringstream buffer;
2646 buffer << std::setw( 2 ) << js << std::endl;
2647
2648 bool res = file.Write( buffer.str() );
2649 file.Close();
2650
2651 // Store the filename of the last saved workbook.
2652 if( res )
2653 {
2654 filename.MakeRelativeTo( m_schematicFrame->Prj().GetProjectPath() );
2655 simulator()->Settings()->SetWorkbookFilename( filename.GetFullPath() );
2656 }
2657
2658 return res;
2659}
2660
2661
2663{
2664 switch( aType )
2665 {
2667 case ST_AC: return SPT_LIN_FREQUENCY;
2668 case ST_SP: return SPT_LIN_FREQUENCY;
2669 case ST_FFT: return SPT_LIN_FREQUENCY;
2670 case ST_DC: return SPT_SWEEP;
2671 case ST_TRAN: return SPT_TIME;
2672 case ST_NOISE: return SPT_LIN_FREQUENCY;
2673
2674 default:
2675 wxFAIL_MSG( wxString::Format( wxS( "Unhandled simulation type: %d" ), (int) aType ) );
2676 return SPT_UNKNOWN;
2677 }
2678}
2679
2680
2682{
2683 wxString output;
2684 wxString ref;
2685 wxString source;
2686 wxString scale;
2687 SPICE_VALUE pts;
2688 SPICE_VALUE fStart;
2689 SPICE_VALUE fStop;
2690 bool saveAll;
2691
2692 if( GetCurrentSimTab() )
2693 {
2694 circuitModel()->ParseNoiseCommand( GetCurrentSimTab()->GetSimCommand(), &output, &ref,
2695 &source, &scale, &pts, &fStart, &fStop, &saveAll );
2696 }
2697
2698 return source;
2699}
2700
2701
2702void SIMULATOR_FRAME_UI::TogglePanel( wxPanel* aPanel, wxSplitterWindow* aSplitterWindow,
2703 int& aSashPosition )
2704{
2705 bool isShown = aPanel->IsShown();
2706
2707 if( isShown )
2708 aSashPosition = aSplitterWindow->GetSashPosition();
2709
2710 aPanel->Show( !isShown );
2711
2712 aSplitterWindow->SetSashInvisible( isShown );
2713 aSplitterWindow->SetSashPosition( isShown ? -1 : aSashPosition, true );
2714
2715 aSplitterWindow->UpdateSize();
2716 m_parent->Refresh();
2717 m_parent->Layout();
2718}
2719
2720
2722{
2723 return m_panelConsole->IsShown();
2724}
2725
2726
2731
2732
2734{
2735 return m_sidePanel->IsShown();
2736}
2737
2738
2743
2744
2746{
2748
2749 // Rebuild the color list to plot traces
2751
2752 // Now send changes to all SIM_PLOT_TAB
2753 for( size_t page = 0; page < m_plotNotebook->GetPageCount(); page++ )
2754 {
2755 wxWindow* curPage = m_plotNotebook->GetPage( page );
2756
2757 // ensure it is truly a plot plotTab and not the (zero plots) placeholder
2758 // which is only SIM_TAB
2759 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( curPage );
2760
2761 if( plotTab )
2762 plotTab->UpdatePlotColors();
2763 }
2764}
2765
2766
2767void SIMULATOR_FRAME_UI::onPlotClose( wxAuiNotebookEvent& event )
2768{
2769 OnModify();
2770}
2771
2772
2773void SIMULATOR_FRAME_UI::onPlotClosed( wxAuiNotebookEvent& event )
2774{
2775 CallAfter( [this]()
2776 {
2778 rebuildSignalsGrid( m_filter->GetValue() );
2780
2781 SIM_TAB* panel = GetCurrentSimTab();
2782
2783 if( !panel || panel->GetSimType() != ST_OP )
2784 {
2785 SCHEMATIC& schematic = m_schematicFrame->Schematic();
2786 schematic.ClearOperatingPoints();
2787 m_schematicFrame->RefreshOperatingPointDisplay();
2788 m_schematicFrame->GetCanvas()->Refresh();
2789 }
2790 } );
2791}
2792
2793
2795{
2796 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
2797 {
2798 std::vector<std::pair<wxString, wxString>>& measurements = plotTab->Measurements();
2799
2800 measurements.clear();
2801
2802 for( int row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
2803 {
2804 if( !m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
2805 {
2806 measurements.emplace_back( m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ),
2807 m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT_FORMAT ) );
2808 }
2809 }
2810 }
2811}
2812
2813
2814void SIMULATOR_FRAME_UI::onPlotChanging( wxAuiNotebookEvent& event )
2815{
2816 m_measurementsGrid->ClearRows();
2817
2818 event.Skip();
2819}
2820
2821
2823{
2825 rebuildSignalsGrid( m_filter->GetValue() );
2827
2829
2830 for( int row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
2831 UpdateMeasurement( row );
2832}
2833
2834
2835void SIMULATOR_FRAME_UI::onPlotChanged( wxAuiNotebookEvent& event )
2836{
2837 if( SIM_TAB* simTab = GetCurrentSimTab() )
2838 simulator()->Command( "setplot " + simTab->GetSpicePlotName().ToStdString() );
2839
2841
2842 event.Skip();
2843}
2844
2845
2847{
2848 m_measurementsGrid->ClearRows();
2849
2850 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
2851 {
2852 for( const auto& [ measurement, format ] : plotTab->Measurements() )
2853 {
2854 int row = m_measurementsGrid->GetNumberRows();
2855 m_measurementsGrid->AppendRows();
2856 m_measurementsGrid->SetCellValue( row, COL_MEASUREMENT, measurement );
2857 m_measurementsGrid->SetCellValue( row, COL_MEASUREMENT_FORMAT, format );
2858 }
2859
2860 if( plotTab->GetSimType() == ST_TRAN || plotTab->GetSimType() == ST_AC
2861 || plotTab->GetSimType() == ST_DC || plotTab->GetSimType() == ST_SP )
2862 {
2863 m_measurementsGrid->AppendRows(); // Empty row at end
2864 }
2865 }
2866}
2867
2868
2869void SIMULATOR_FRAME_UI::onPlotDragged( wxAuiNotebookEvent& event )
2870{
2871}
2872
2873
2874std::shared_ptr<SPICE_SIMULATOR> SIMULATOR_FRAME_UI::simulator() const
2875{
2876 return m_simulatorFrame->GetSimulator();
2877}
2878
2879
2880std::shared_ptr<SPICE_CIRCUIT_MODEL> SIMULATOR_FRAME_UI::circuitModel() const
2881{
2882 return m_simulatorFrame->GetCircuitModel();
2883}
2884
2885
2887{
2888 SUPPRESS_GRID_CELL_EVENTS raii( this );
2889
2890 m_cursorsGrid->ClearRows();
2891
2892 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
2893
2894 if( !plotTab )
2895 return;
2896
2897 // Update cursor values
2898 CURSOR* cursor1 = nullptr;
2899 wxString cursor1Name;
2900 wxString cursor1Units;
2901 CURSOR* cursor2 = nullptr;
2902 wxString cursor2Name;
2903 wxString cursor2Units;
2904
2905 auto getUnitsY =
2906 [&]( TRACE* aTrace ) -> wxString
2907 {
2908 if( plotTab->GetSimType() == ST_AC )
2909 {
2910 if( aTrace->GetType() & SPT_AC_PHASE )
2911 return plotTab->GetUnitsY2();
2912 else
2913 return plotTab->GetUnitsY1();
2914 }
2915 else
2916 {
2917 if( aTrace->GetType() & SPT_POWER )
2918 return plotTab->GetUnitsY3();
2919 else if( aTrace->GetType() & SPT_CURRENT )
2920 return plotTab->GetUnitsY2();
2921 else
2922 return plotTab->GetUnitsY1();
2923 }
2924 };
2925
2926 auto getNameY =
2927 [&]( TRACE* aTrace ) -> wxString
2928 {
2929 if( plotTab->GetSimType() == ST_AC )
2930 {
2931 if( aTrace->GetType() & SPT_AC_PHASE )
2932 return plotTab->GetLabelY2();
2933 else
2934 return plotTab->GetLabelY1();
2935 }
2936 else
2937 {
2938 if( aTrace->GetType() & SPT_POWER )
2939 return plotTab->GetLabelY3();
2940 else if( aTrace->GetType() & SPT_CURRENT )
2941 return plotTab->GetLabelY2();
2942 else
2943 return plotTab->GetLabelY1();
2944 }
2945 };
2946
2947 auto formatValue =
2948 [this]( double aValue, int aCursorId, int aCol ) -> wxString
2949 {
2950 if( ( !m_simulatorFrame->SimFinished() && aCol == 1 ) || std::isnan( aValue ) )
2951 return wxS( "--" );
2952 else
2953 return SPICE_VALUE( aValue ).ToString( m_cursorFormatsDyn[ aCursorId ][ aCol ] );
2954 };
2955
2956 for( const auto& [name, trace] : plotTab->GetTraces() )
2957 {
2958 if( CURSOR* cursor = trace->GetCursor( 1 ) )
2959 {
2960 cursor1 = cursor;
2961 cursor1Name = getNameY( trace );
2962 cursor1Units = getUnitsY( trace );
2963
2964 wxRealPoint coords = cursor->GetCoords();
2965 int row = m_cursorsGrid->GetNumberRows();
2966
2967 m_cursorFormatsDyn[0][0].UpdateUnits( plotTab->GetUnitsX() );
2968 m_cursorFormatsDyn[0][1].UpdateUnits( cursor1Units );
2969
2970 m_cursorsGrid->AppendRows( 1 );
2971 m_cursorsGrid->SetCellValue( row, COL_CURSOR_NAME, wxS( "1" ) );
2972 m_cursorsGrid->SetCellValue( row, COL_CURSOR_SIGNAL, cursor->GetName() );
2973 m_cursorsGrid->SetCellValue( row, COL_CURSOR_X, formatValue( coords.x, 0, 0 ) );
2974 m_cursorsGrid->SetCellValue( row, COL_CURSOR_Y, formatValue( coords.y, 0, 1 ) );
2975 break;
2976 }
2977 }
2978
2979 for( const auto& [name, trace] : plotTab->GetTraces() )
2980 {
2981 if( CURSOR* cursor = trace->GetCursor( 2 ) )
2982 {
2983 cursor2 = cursor;
2984 cursor2Name = getNameY( trace );
2985 cursor2Units = getUnitsY( trace );
2986
2987 wxRealPoint coords = cursor->GetCoords();
2988 int row = m_cursorsGrid->GetNumberRows();
2989
2990 m_cursorFormatsDyn[1][0].UpdateUnits( plotTab->GetUnitsX() );
2991 m_cursorFormatsDyn[1][1].UpdateUnits( cursor2Units );
2992
2993 m_cursorsGrid->AppendRows( 1 );
2994 m_cursorsGrid->SetCellValue( row, COL_CURSOR_NAME, wxS( "2" ) );
2995 m_cursorsGrid->SetCellValue( row, COL_CURSOR_SIGNAL, cursor->GetName() );
2996 m_cursorsGrid->SetCellValue( row, COL_CURSOR_X, formatValue( coords.x, 1, 0 ) );
2997 m_cursorsGrid->SetCellValue( row, COL_CURSOR_Y, formatValue( coords.y, 1, 1 ) );
2998 break;
2999 }
3000 }
3001
3002 if( cursor1 && cursor2 && cursor1Units == cursor2Units )
3003 {
3004 wxRealPoint coords = cursor2->GetCoords() - cursor1->GetCoords();
3005 wxString signal;
3006
3007 m_cursorFormatsDyn[2][0].UpdateUnits( plotTab->GetUnitsX() );
3008 m_cursorFormatsDyn[2][1].UpdateUnits( cursor1Units );
3009
3010 if( cursor1->GetName() == cursor2->GetName() )
3011 signal = wxString::Format( wxS( "%s[2 - 1]" ), cursor2->GetName() );
3012 else
3013 signal = wxString::Format( wxS( "%s - %s" ), cursor2->GetName(), cursor1->GetName() );
3014
3015 m_cursorsGrid->AppendRows( 1 );
3016 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_NAME, _( "Diff" ) );
3017 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_SIGNAL, signal );
3018 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_X, formatValue( coords.x, 2, 0 ) );
3019 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_Y, formatValue( coords.y, 2, 1 ) );
3020 }
3021 // Set up the labels
3022 m_cursorsGrid->SetColLabelValue( COL_CURSOR_X, plotTab->GetLabelX() );
3023
3024 wxString valColName = _( "Value" );
3025
3026 if( !cursor1Name.IsEmpty() )
3027 {
3028 if( cursor2Name.IsEmpty() || cursor1Name == cursor2Name )
3029 valColName = cursor1Name;
3030 }
3031 else if( !cursor2Name.IsEmpty() )
3032 {
3033 valColName = cursor2Name;
3034 }
3035
3036 m_cursorsGrid->SetColLabelValue( COL_CURSOR_Y, valColName );
3037
3038 if( m_customCursorsCnt > 3 ) // 2 for the default hardocded cursors plus the initial + 1
3039 {
3040 for( int i = 3; i < m_customCursorsCnt; i++ )
3041 {
3042 for( const auto& [name, trace] : plotTab->GetTraces() )
3043 {
3044 if( CURSOR* cursor = trace->GetCursor( i ) )
3045 {
3046 CURSOR* curs = cursor;
3047 wxString cursName = getNameY( trace );
3048 wxString cursUnits = getUnitsY( trace );
3049
3050 wxRealPoint coords = cursor->GetCoords();
3051 int row = m_cursorsGrid->GetNumberRows();
3052
3053 m_cursorFormatsDyn[i][0].UpdateUnits( plotTab->GetUnitsX() );
3054 m_cursorFormatsDyn[i][1].UpdateUnits( cursUnits );
3055
3056 m_cursorsGrid->AppendRows( 1 );
3057 m_cursorsGrid->SetCellValue( row, COL_CURSOR_NAME, wxS( "" ) + wxString( "" ) << i );
3058 m_cursorsGrid->SetCellValue( row, COL_CURSOR_SIGNAL, curs->GetName() );
3059 m_cursorsGrid->SetCellValue( row, COL_CURSOR_X, formatValue( coords.x, i, 0 ) );
3060 m_cursorsGrid->SetCellValue( row, COL_CURSOR_Y, formatValue( coords.y, i, 1 ) );
3061
3062 // Set up the labels
3063 m_cursorsGrid->SetColLabelValue( COL_CURSOR_X, plotTab->GetLabelX() );
3064
3065 valColName = _( "Value" );
3066
3067 if( !cursName.IsEmpty()
3068 && ( m_cursorsGrid->GetColLabelValue( COL_CURSOR_Y ) == cursName ) )
3069 {
3070 valColName = cursName;
3071 }
3072 m_cursorsGrid->SetColLabelValue( COL_CURSOR_Y, valColName );
3073 break;
3074 }
3075 }
3076 }
3077 }
3078}
3079
3080
3081void SIMULATOR_FRAME_UI::onPlotCursorUpdate( wxCommandEvent& aEvent )
3082{
3084 OnModify();
3085}
3086
3087
3089{
3090 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
3091 plotTab->ResetScales( true );
3092
3093 m_simConsole->Clear();
3094
3095 // Do not export netlist, it is already stored in the simulator
3096 applyTuners();
3097
3098 m_refreshTimer.Start( REFRESH_INTERVAL, wxTIMER_ONE_SHOT );
3099}
3100
3101
3102void SIMULATOR_FRAME_UI::OnSimReport( const wxString& aMsg )
3103{
3104 m_simConsole->AppendText( aMsg + "\n" );
3105 m_simConsole->SetInsertionPointEnd();
3106}
3107
3108
3109std::vector<wxString> SIMULATOR_FRAME_UI::SimPlotVectors() const
3110{
3111 std::vector<wxString> signals;
3112
3113 for( const std::string& vec : simulator()->AllVectors() )
3114 signals.emplace_back( vec );
3115
3116 return signals;
3117}
3118
3119
3120std::vector<wxString> SIMULATOR_FRAME_UI::Signals() const
3121{
3122 std::vector<wxString> signals;
3123
3124 for( const wxString& signal : m_signals )
3125 signals.emplace_back( signal );
3126
3127 for( const auto& [ id, signal ] : m_userDefinedSignals )
3128 signals.emplace_back( signal );
3129
3130 sortSignals( signals );
3131
3132 return signals;
3133}
3134
3135
3137{
3138 if( aFinal )
3139 m_refreshTimer.Stop();
3140
3141 SIM_TAB* simTab = GetCurrentSimTab();
3142
3143 if( !simTab )
3144 return;
3145
3146 SIM_TYPE simType = simTab->GetSimType();
3147 wxString msg;
3148
3149 if( aFinal )
3150 {
3153 }
3154
3155 // If there are any signals plotted, update them
3156 if( SIM_TAB::IsPlottable( simType ) )
3157 {
3158 simTab->SetSpicePlotName( simulator()->CurrentPlotName() );
3159
3160 if( simType == ST_NOISE && aFinal )
3161 {
3162 m_simConsole->AppendText( _( "\n\nSimulation results:\n\n" ) );
3163 m_simConsole->SetInsertionPointEnd();
3164
3165 // The simulator will create noise1 & noise2 on the first run, noise3 and noise4
3166 // on the second, etc. The first plot for each run contains the spectral density
3167 // noise vectors and second contains the integrated noise.
3168 long number;
3169 simulator()->CurrentPlotName().Mid( 5 ).ToLong( &number );
3170
3171 for( const std::string& vec : simulator()->AllVectors() )
3172 {
3173 std::vector<double> val_list = simulator()->GetRealVector( vec, 1 );
3174 wxString value = SPICE_VALUE( val_list[ 0 ] ).ToSpiceString();
3175
3176 msg.Printf( wxS( "%s: %sV\n" ), vec, value );
3177
3178 m_simConsole->AppendText( msg );
3179 m_simConsole->SetInsertionPointEnd();
3180 }
3181
3182 simulator()->Command( fmt::format( "setplot noise{}", number - 1 ) );
3183 simTab->SetSpicePlotName( simulator()->CurrentPlotName() );
3184 }
3185
3186 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( simTab );
3187 wxCHECK_RET( plotTab, wxString::Format( wxT( "No SIM_PLOT_TAB for: %s" ),
3188 magic_enum::enum_name( simType ) ) );
3189
3190 struct TRACE_INFO
3191 {
3192 wxString Vector;
3193 int TraceType;
3194 bool ClearData;
3195 };
3196
3197 std::map<TRACE*, TRACE_INFO> traceMap;
3198
3199 for( const auto& [ name, trace ] : plotTab->GetTraces() )
3200 traceMap[ trace ] = { wxEmptyString, SPT_UNKNOWN, false };
3201
3202 // NB: m_signals are already broken out into gain/phase, but m_userDefinedSignals are
3203 // as the user typed them
3204
3205 for( const wxString& signal : m_signals )
3206 {
3207 int traceType = SPT_UNKNOWN;
3208 wxString vectorName = vectorNameFromSignalName( plotTab, signal, &traceType );
3209
3210 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType ) )
3211 traceMap[ trace ] = { vectorName, traceType, false };
3212 }
3213
3214 for( const auto& [ id, signal ] : m_userDefinedSignals )
3215 {
3216 int traceType = SPT_UNKNOWN;
3217 wxString vectorName = vectorNameFromSignalName( plotTab, signal, &traceType );
3218
3219 if( simType == ST_AC )
3220 {
3221 int baseType = traceType &= ~( SPT_AC_GAIN | SPT_AC_PHASE );
3222
3223 for( int subType : { baseType | SPT_AC_GAIN, baseType | SPT_AC_PHASE } )
3224 {
3225 if( TRACE* trace = plotTab->GetTrace( vectorName, subType ) )
3226 traceMap[ trace ] = { vectorName, subType, !aFinal };
3227 }
3228 }
3229 else if( simType == ST_SP )
3230 {
3231 int baseType = traceType &= ~( SPT_SP_AMP | SPT_AC_PHASE );
3232
3233 for( int subType : { baseType | SPT_SP_AMP, baseType | SPT_AC_PHASE } )
3234 {
3235 if( TRACE* trace = plotTab->GetTrace( vectorName, subType ) )
3236 traceMap[trace] = { vectorName, subType, !aFinal };
3237 }
3238 }
3239 else
3240 {
3241 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType ) )
3242 traceMap[ trace ] = { vectorName, traceType, !aFinal };
3243 }
3244 }
3245
3246 // Two passes so that DC-sweep sub-traces get deleted and re-created:
3247
3248 for( const auto& [ trace, traceInfo ] : traceMap )
3249 {
3250 if( traceInfo.Vector.IsEmpty() )
3251 plotTab->DeleteTrace( trace );
3252 }
3253
3254 for( const auto& [ trace, info ] : traceMap )
3255 {
3256 std::vector<double> data_x;
3257
3258 if( !info.Vector.IsEmpty() )
3259 updateTrace( info.Vector, info.TraceType, plotTab, &data_x, info.ClearData );
3260 }
3261
3262 plotTab->GetPlotWin()->UpdateAll();
3263
3264 if( aFinal )
3265 {
3266 for( int row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
3267 UpdateMeasurement( row );
3268
3269 plotTab->ResetScales( true );
3270 }
3271
3272 plotTab->GetPlotWin()->Fit();
3273
3275 }
3276 else if( simType == ST_OP && aFinal )
3277 {
3278 m_simConsole->AppendText( _( "\n\nSimulation results:\n\n" ) );
3279 m_simConsole->SetInsertionPointEnd();
3280
3281 for( const std::string& vec : simulator()->AllVectors() )
3282 {
3283 std::vector<double> val_list = simulator()->GetRealVector( vec, 1 );
3284
3285 if( val_list.empty() )
3286 continue;
3287
3288 wxString value = SPICE_VALUE( val_list[ 0 ] ).ToSpiceString();
3289 wxString signal;
3290 SIM_TRACE_TYPE type = circuitModel()->VectorToSignal( vec, signal );
3291
3292 const size_t tab = 25; //characters
3293 size_t padding = ( signal.length() < tab ) ? ( tab - signal.length() ) : 1;
3294
3295 switch( type )
3296 {
3297 case SPT_VOLTAGE: value.Append( wxS( "V" ) ); break;
3298 case SPT_CURRENT: value.Append( wxS( "A" ) ); break;
3299 case SPT_POWER: value.Append( wxS( "W" ) ); break;
3300 default: value.Append( wxS( "?" ) ); break;
3301 }
3302
3303 msg.Printf( wxT( "%s%s\n" ),
3304 ( signal + wxT( ":" ) ).Pad( padding, wxUniChar( ' ' ) ),
3305 value );
3306
3307 m_simConsole->AppendText( msg );
3308 m_simConsole->SetInsertionPointEnd();
3309
3310 if( type == SPT_VOLTAGE || type == SPT_CURRENT || type == SPT_POWER )
3311 signal = signal.SubString( 2, signal.Length() - 2 );
3312
3313 if( type == SPT_POWER )
3314 signal += wxS( ":power" );
3315
3316 m_schematicFrame->Schematic().SetOperatingPoint( signal, val_list.at( 0 ) );
3317 }
3318 }
3319 else if( simType == ST_PZ && aFinal )
3320 {
3321 m_simConsole->AppendText( _( "\n\nSimulation results:\n\n" ) );
3322 m_simConsole->SetInsertionPointEnd();
3323 simulator()->Command( "print all" );
3324 }
3325}
3326
3327
3329{
3330 m_simulatorFrame->OnModify();
3331}
int color
const char * name
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:990
void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent) override
void doPopupSelection(wxCommandEvent &event) override
SIMULATOR_FRAME_UI * m_parent
CURSORS_GRID_TRICKS(SIMULATOR_FRAME_UI *aParent, WX_GRID *aGrid)
The SIMULATOR_FRAME holds the main user-interface for running simulations.
const wxRealPoint & GetCoords() const
void SetCoordX(double aValue)
int ShowModal() override
bool Find(const wxString &aTerm, int &aMatchersTriggered, int &aPosition)
Look in all existing matchers, return the earliest match of any of the existing.
GRID_TRICKS(WX_GRID *aGrid)
virtual void doPopupSelection(wxCommandEvent &event)
virtual void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent)
WX_GRID * m_grid
I don't own the grid, but he owns me.
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:104
wxString ToCSSString() const
Definition color4d.cpp:147
Definition kiid.h:49
Hold a translatable error message and may be used when throwing exceptions containing a translated er...
const wxString What() const
void doPopupSelection(wxCommandEvent &event) override
void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent) override
SIMULATOR_FRAME_UI * m_parent
MEASUREMENTS_GRID_TRICKS(SIMULATOR_FRAME_UI *aParent, WX_GRID *aGrid)
static void ConvertToSpiceMarkup(wxString *aNetName)
Remove formatting wrappers and replace illegal spice net name characters with underscores.
const SPICE_ITEM * FindItem(const wxString &aRefName) const
Find and return the item corresponding to aRefName.
A singleton reporter that reports to nowhere.
Definition reporter.h:216
virtual bool HasMessage() const
Returns true if any messages were reported.
Definition reporter.h:134
Holds all the data relating to one schematic.
Definition schematic.h:88
void ClearOperatingPoints()
Clear operating points from a .op simulation.
Definition schematic.h:265
Schematic editor (Eeschema) main window.
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:167
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
SCH_ITEM * ResolveItem(const KIID &aID) const
Fetch a SCH_ITEM by ID.
Schematic symbol object.
Definition sch_symbol.h:75
EMBEDDED_FILES * GetEmbeddedFiles() override
SCH_SYMBOLs don't currently support embedded files, but their LIB_SYMBOL counterparts do.
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
void doPopupSelection(wxCommandEvent &event) override
void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent) override
SIMULATOR_FRAME_UI * m_parent
SIGNALS_GRID_TRICKS(SIMULATOR_FRAME_UI *aParent, WX_GRID *aGrid)
wxSplitterWindow * m_splitterLeftRight
wxSplitterWindow * m_splitterMeasurements
wxSplitterWindow * m_splitterCursors
wxSplitterWindow * m_splitterPlotAndConsole
SIMULATOR_FRAME_UI_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(-1,-1), long style=wxTAB_TRAVERSAL, const wxString &name=wxEmptyString)
wxSplitterWindow * m_splitterSignals
The SIMULATOR_FRAME_UI holds the main user-interface for running simulations.
SIM_TAB * NewSimTab(const wxString &aSimCommand)
Create a new simulation tab for a given simulation type.
void SetUserDefinedSignals(const std::map< int, wxString > &aSignals)
void updatePlotCursors()
Update the cursor values (in the grid) and graphics (in the plot window).
void OnSimRefresh(bool aFinal)
void onPlotClose(wxAuiNotebookEvent &event) override
void CustomCursorsInit()
Init handler for custom cursors.
void TogglePanel(wxPanel *aPanel, wxSplitterWindow *aSplitterWindow, int &aSashPosition)
A common toggler for the two main wxSplitterWindow s.
void onPlotChanged(wxAuiNotebookEvent &event) override
void rebuildSignalsGrid(wxString aFilter)
Rebuild the filtered list of signals in the signals grid.
std::vector< std::vector< SPICE_VALUE_FORMAT > > m_cursorFormatsDyn
void DoFourier(const wxString &aSignal, const wxString &aFundamental)
void rebuildMeasurementsGrid()
Rebuild the measurements grid for the current plot.
std::list< TUNER_SLIDER * > m_tuners
SPICE expressions need quoted versions of the netnames since KiCad allows '-' and '/' in netnames.
void rebuildSignalsList()
Rebuild the list of signals available from the netlist.
bool loadLegacyWorkbook(const wxString &aPath)
void UpdateMeasurement(int aRow)
Update a measurement in the measurements grid.
wxString getNoiseSource() const
std::vector< wxString > SimPlotVectors() const
void SetSubWindowsSashSize()
Adjust the sash dimension of splitter windows after reading the config settings must be called after ...
void applyUserDefinedSignals()
Apply user-defined signals to the SPICE session.
SIM_PREFERENCES m_preferences
void DeleteMeasurement(int aRow)
Delete a row from the measurements grid.
SCH_EDIT_FRAME * m_schematicFrame
wxString vectorNameFromSignalName(SIM_PLOT_TAB *aPlotTab, const wxString &aSignalName, int *aTraceType)
Get the simulator output vector name for a given signal name and type.
void updateSignalsGrid()
Update the values in the signals grid.
void onCursorsGridCellChanged(wxGridEvent &aEvent) override
void onPlotDragged(wxAuiNotebookEvent &event) override
std::vector< wxString > Signals() const
bool SaveWorkbook(const wxString &aPath)
Save plot, signal, cursor, measurement, etc.
std::vector< wxString > m_signals
SIM_TAB * GetCurrentSimTab() const
Return the currently opened plot panel (or NULL if there is none).
void SaveCursorToWorkbook(nlohmann::json &aTraceJs, TRACE *aTrace, int aCursorId)
bool LoadWorkbook(const wxString &aPath)
Load plot, signal, cursor, measurement, etc.
SPICE_VALUE_FORMAT GetMeasureFormat(int aRow) const
Get/Set the format of a value in the measurements grid.
std::map< int, wxString > m_userDefinedSignals
void UpdateTunerValue(const SCH_SHEET_PATH &aSheetPath, const KIID &aSymbol, const wxString &aRef, const wxString &aValue)
Safely update a field of the associated symbol without dereferencing the symbol.
std::vector< wxString > m_netnames
void AddTrace(const wxString &aName, SIM_TRACE_TYPE aType)
Add a new trace to the current plot.
void onPlotClosed(wxAuiNotebookEvent &event) override
void RemoveTuner(TUNER_SLIDER *aTuner)
Remove an existing tuner.
void SaveSettings(EESCHEMA_SETTINGS *aCfg)
std::shared_ptr< SPICE_CIRCUIT_MODEL > circuitModel() const
void OnFilterText(wxCommandEvent &aEvent) override
void onMeasurementsGridCellChanged(wxGridEvent &aEvent) override
void DeleteCursor()
Deletes last m_signalsGrid "Cursor n" column, removes vector's m_cursorFormatsDyn last entry,...
void CreateNewCursor()
Creates a column at the end of m_signalsGrid named "Cursor n" ( n = m_customCursorsCnt ),...
void applyTuners()
Apply component values specified using tuner sliders to the current netlist.
bool loadJsonWorkbook(const wxString &aPath)
void OnFilterMouseMoved(wxMouseEvent &aEvent) override
void AddMeasurement(const wxString &aCmd)
Add a measurement to the measurements grid.
void onPlotChanging(wxAuiNotebookEvent &event) override
std::shared_ptr< SPICE_SIMULATOR > simulator() const
void onPlotCursorUpdate(wxCommandEvent &aEvent)
void onSignalsGridCellChanged(wxGridEvent &aEvent) override
void InitWorkbook()
Load the currently active workbook stored in the project settings.
SIM_TRACE_TYPE getXAxisType(SIM_TYPE aType) const
Return X axis for a given simulation type.
void signalsGridCursorUpdate(T t, U u, R r)
Updates m_signalsGrid cursor widget, column rendering and attributes.
void SetMeasureFormat(int aRow, const SPICE_VALUE_FORMAT &aFormat)
void OnSimReport(const wxString &aMsg)
void ApplyPreferences(const SIM_PREFERENCES &aPrefs)
Called when settings are changed via the common Preferences dialog.
const SPICE_CIRCUIT_MODEL * GetExporter() const
Return the netlist exporter object used for simulations.
SIMULATOR_FRAME * m_simulatorFrame
void AddTuner(const SCH_SHEET_PATH &aSheetPath, SCH_SYMBOL *aSymbol)
Add a tuner for a symbol.
void OnUpdateUI(wxUpdateUIEvent &event) override
void updateTrace(const wxString &aVectorName, int aTraceType, SIM_PLOT_TAB *aPlotTab, std::vector< double > *aDataX=nullptr, bool aClearData=false)
Update a trace in a particular SIM_PLOT_TAB.
SIMULATOR_FRAME_UI(SIMULATOR_FRAME *aSimulatorFrame, SCH_EDIT_FRAME *aSchematicFrame)
SPICE_VALUE_FORMAT m_cursorFormats[3][2]
void LoadSettings(EESCHEMA_SETTINGS *aCfg)
The SIMULATOR_FRAME holds the main user-interface for running simulations.
SIM_MODEL & CreateModel(SIM_MODEL::TYPE aType, const std::vector< SCH_PIN * > &aPins, REPORTER &aReporter)
void SetFilesStack(std::vector< EMBEDDED_FILES * > aFilesStack)
Definition sim_lib_mgr.h:48
virtual const PARAM * GetTunerParam() const
Definition sim_model.h:480
const SPICE_GENERATOR & SpiceGenerator() const
Definition sim_model.h:431
void WriteFields(std::vector< SCH_FIELD > &aFields) const
void SetParamValue(int aParamIndex, const std::string &aValue, SIM_VALUE::NOTATION aNotation=SIM_VALUE::NOTATION::SI)
static void FillDefaultColorList(bool aWhiteBg)
Fills m_colorList by a default set of colors.
bool DeleteTrace(const wxString &aVectorName, int aTraceType)
wxString GetLabelY1() const
mpWindow * GetPlotWin() const
void ShowGrid(bool aEnable)
wxString GetUnitsY2() const
void SetY2Scale(bool aLock, double aMin, double aMax)
TRACE * GetTrace(const wxString &aVecName, int aType) const
wxString GetLabelX() const
const std::map< wxString, TRACE * > & GetTraces() const
wxString GetLabelY3() const
void SetY1Scale(bool aLock, double aMin, double aMax)
void SetY3Scale(bool aLock, double aMin, double aMax)
std::vector< std::pair< wxString, wxString > > & Measurements()
void UpdateTraceStyle(TRACE *trace)
Update plot colors.
void SetLegendPosition(const wxPoint &aPosition)
void ResetScales(bool aIncludeX)
Update trace line style.
void UpdatePlotColors()
void ShowLegend(bool aEnable)
wxString GetLabelY2() const
void SetTraceData(TRACE *aTrace, std::vector< double > &aX, std::vector< double > &aY, int aSweepCount, size_t aSweepSize)
void EnableCursor(TRACE *aTrace, int aCursorId, const wxString &aSignalName)
wxString GetUnitsX() const
void EnsureThirdYAxisExists()
TRACE * GetOrAddTrace(const wxString &aVectorName, int aType)
void SetDottedSecondary(bool aEnable)
Draw secondary signal traces (current or phase) with dotted lines.
void ApplyPreferences(const SIM_PREFERENCES &aPrefs) override
wxString GetUnitsY1() const
void DisableCursor(TRACE *aTrace, int aCursorId)
Reset scale ranges to fit the current traces.
wxString GetUnitsY3() const
int GetSimOptions() const
Definition sim_tab.h:55
SIM_TYPE GetSimType() const
Definition sim_tab.cpp:75
const wxString & GetSimCommand() const
Definition sim_tab.h:52
static bool IsPlottable(SIM_TYPE aSimType)
Definition sim_tab.cpp:53
void SetSimOptions(int aOptions)
Definition sim_tab.h:56
wxString GetLastSchTextSimCommand() const
Definition sim_tab.h:58
void SetSpicePlotName(const wxString &aPlotName)
Definition sim_tab.h:62
static std::string ToSpice(const std::string &aString)
Special netlist exporter flavor that allows one to override simulation commands.
static SIM_TYPE CommandToSimType(const wxString &aCmd)
Return simulation type basing on a simulation command directive.
bool ParseNoiseCommand(const wxString &aCmd, wxString *aOutput, wxString *aRef, wxString *aSource, wxString *aScale, SPICE_VALUE *aPts, SPICE_VALUE *aFStart, SPICE_VALUE *aFStop, bool *aSaveAll)
wxString GetSchTextSimCommand()
Return simulation command directives placed in schematic sheets (if any).
SIM_TRACE_TYPE VectorToSignal(const std::string &aVector, wxString &aSignal) const
Return name of Spice dataset for a specific trace.
virtual std::string TunerCommand(const SPICE_ITEM &aItem, double aValue) const
wxString GetWorkbookFilename() const
void SetWorkbookFilename(const wxString &aFilename)
virtual bool Command(const std::string &aCmd)=0
Execute a Spice command as if it was typed into console.
static wxString TypeToName(SIM_TYPE aType, bool aShortName)
Return a string with simulation name based on enum.
std::shared_ptr< SPICE_SETTINGS > & Settings()
Return the simulator configuration settings.
virtual wxString CurrentPlotName() const =0
virtual std::vector< double > GetRealVector(const std::string &aName, int aMaxLen=-1)=0
Return a requested vector with real values.
virtual std::vector< double > GetGainVector(const std::string &aName, int aMaxLen=-1)=0
Return a requested vector with magnitude values.
virtual std::vector< double > GetPhaseVector(const std::string &aName, int aMaxLen=-1)=0
Return a requested vector with phase values.
Helper class to recognize Spice formatted values.
Definition spice_value.h:56
wxString ToString() const
Return string value as when converting double to string (e.g.
wxString ToSpiceString() const
Return string value in Spice format (e.g.
double ToDouble() const
SUPPRESS_GRID_CELL_EVENTS(SIMULATOR_FRAME_UI *aFrame)
void SetTraceColour(const wxColour &aColour)
bool HasCursor(int aCursorId)
CURSOR * GetCursor(int aCursorId)
Custom widget to handle quick component values modification and simulation on the fly.
A wrapper for reporting to a wxString object.
Definition reporter.h:191
REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED) override
Report a string with a given severity.
Definition reporter.cpp:68
const wxString & GetMessages() const
Definition reporter.cpp:77
A KICAD version of wxTextEntryDialog which supports the various improvements/work-arounds from DIALOG...
wxString GetValue() const
const wxString & GetName() const
Get layer name.
Definition mathplot.h:239
const wxPen & GetPen() const
Get pen set for this layer.
Definition mathplot.h:254
Canvas for plotting mpLayer implementations.
Definition mathplot.h:908
int GetMarginLeft() const
Definition mathplot.h:1219
void SetMargins(int top, int right, int bottom, int left)
Set window margins, creating a blank area where some kinds of layers cannot draw.
int GetMarginTop() const
Definition mathplot.h:1213
void UpdateAll()
Refresh display.
int GetMarginRight() const
Definition mathplot.h:1215
int GetMarginBottom() const
Definition mathplot.h:1217
void LockY(bool aLock)
Definition mathplot.h:1263
bool AddLayer(mpLayer *layer, bool refreshDisplay=true)
Add a plot layer to the canvas.
void Fit() override
Set view to fit global bounding box of all plot layers and refresh display.
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:194
This file is part of the common library.
#define _(s)
Abstract pattern-matching tool and implementations.
@ CTX_SIGNAL
@ GRIDTRICKS_ID_SELECT
Definition grid_tricks.h:46
@ GRIDTRICKS_ID_COPY
Definition grid_tricks.h:43
@ GRIDTRICKS_ID_DELETE
Definition grid_tricks.h:44
@ GRIDTRICKS_FIRST_CLIENT_ID
Definition grid_tricks.h:48
static const std::string WorkbookFileExtension
#define traceSettings
KICOMMON_API wxFont GetStatusFont(wxWindow *aWindow)
see class PGM_BASE
SIM_TRACE_TYPE
Definition sim_types.h:50
@ SPT_TIME
Definition sim_types.h:61
@ SPT_AC_PHASE
Definition sim_types.h:54
@ SPT_SWEEP
Definition sim_types.h:64
@ SPT_UNKNOWN
Definition sim_types.h:67
@ SPT_AC_GAIN
Definition sim_types.h:55
@ SPT_Y_AXIS_MASK
Definition sim_types.h:58
@ SPT_SP_AMP
Definition sim_types.h:57
@ SPT_VOLTAGE
Definition sim_types.h:52
@ SPT_POWER
Definition sim_types.h:56
@ SPT_CURRENT
Definition sim_types.h:53
@ SPT_LIN_FREQUENCY
Definition sim_types.h:62
SIM_TYPE
< Possible simulation types
Definition sim_types.h:32
@ ST_SP
Definition sim_types.h:43
@ ST_TRAN
Definition sim_types.h:42
@ ST_UNKNOWN
Definition sim_types.h:33
@ ST_NOISE
Definition sim_types.h:37
@ ST_AC
Definition sim_types.h:34
@ ST_DISTO
Definition sim_types.h:36
@ ST_TF
Definition sim_types.h:41
@ ST_SENS
Definition sim_types.h:40
@ ST_DC
Definition sim_types.h:35
@ ST_OP
Definition sim_types.h:38
@ ST_FFT
Definition sim_types.h:44
@ ST_PZ
Definition sim_types.h:39
void sortSignals(std::vector< wxString > &signals)
wxString vectorNameFromSignalId(int aUserDefinedSignalId)
MEASUREMENTS_GIRD_COLUMNS
@ COL_MEASUREMENT_FORMAT
@ COL_MEASUREMENT_VALUE
@ COL_MEASUREMENT
CURSORS_GRID_COLUMNS
@ COL_CURSOR_NAME
@ COL_CURSOR_SIGNAL
@ COL_CURSOR_X
@ COL_CURSOR_Y
SIGNALS_GRID_COLUMNS
@ COL_SIGNAL_SHOW
@ COL_SIGNAL_NAME
@ COL_CURSOR_1
@ COL_SIGNAL_COLOR
@ COL_CURSOR_2
#define ID_SIM_REFRESH
@ MYID_MEASURE_INTEGRAL
@ MYID_MEASURE_MAX_AT
@ MYID_MEASURE_AVG
@ MYID_MEASURE_MAX
@ MYID_FORMAT_VALUE
@ MYID_MEASURE_RMS
@ MYID_DELETE_MEASUREMENT
@ MYID_MEASURE_MIN
@ MYID_MEASURE_MIN_AT
@ MYID_MEASURE_PP
SIM_TRACE_TYPE operator|(SIM_TRACE_TYPE aFirst, SIM_TRACE_TYPE aSecond)
#define REFRESH_INTERVAL
const int scale
std::vector< FAB_LAYER_COLOR > dummy
wxString UnescapeString(const wxString &aSource)
const INFO & info
Definition sim_model.h:401
Contains preferences pertaining to the simulator.
const SIM_MODEL * model
A SPICE_VALUE_FORMAT holds precision and range info for formatting values.Helper class to handle Spic...
Definition spice_value.h:43
wxString ToString() const
void UpdateUnits(const wxString &aUnits)
VECTOR3I res
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.