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 (C) 2016-2024 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
29#include <fmt/format.h>
30#include <wx/wfstream.h>
31#include <wx/stdstream.h>
32#include <wx/debug.h>
33#include <wx/clipbrd.h>
34#include <wx/log.h>
35
37#include <sch_edit_frame.h>
38#include <confirm.h>
42#include <widgets/wx_grid.h>
43#include <grid_tricks.h>
44#include <eda_pattern_match.h>
45#include <string_utils.h>
46#include <pgm_base.h>
48#include <sim/simulator_frame.h>
49#include <sim/sim_plot_tab.h>
50#include <sim/spice_simulator.h>
53#include <eeschema_settings.h>
54#include "kiplatform/app.h"
55
56
58{
59 int res = (int) aFirst | (int) aSecond;
60
61 return (SIM_TRACE_TYPE) res;
62}
63
64
66{
72};
73
74
76{
81};
82
83
85{
89};
90
91
92enum
93{
103
107
108
110{
111public:
113 GRID_TRICKS( aGrid ),
114 m_parent( aParent ),
115 m_menuRow( 0 ),
116 m_menuCol( 0 )
117 {}
118
119protected:
120 void showPopupMenu( wxMenu& menu, wxGridEvent& aEvent ) override;
121 void doPopupSelection( wxCommandEvent& event ) override;
122
123protected:
127};
128
129
130void SIGNALS_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
131{
132 m_menuRow = aEvent.GetRow();
133 m_menuCol = aEvent.GetCol();
134
136 {
137 if( !( m_grid->IsInSelection( m_menuRow, m_menuCol ) ) )
138 m_grid->ClearSelection();
139
140 m_grid->SetGridCursor( m_menuRow, m_menuCol );
141
142 if( SIM_TAB* panel = m_parent->GetCurrentSimTab() )
143 {
144 if( panel->GetSimType() == ST_TRAN || panel->GetSimType() == ST_AC
145 || panel->GetSimType() == ST_DC || panel->GetSimType() == ST_SP )
146 {
147 menu.Append( MYID_MEASURE_MIN, _( "Measure Min" ) );
148 menu.Append( MYID_MEASURE_MAX, _( "Measure Max" ) );
149 menu.Append( MYID_MEASURE_AVG, _( "Measure Average" ) );
150 menu.Append( MYID_MEASURE_RMS, _( "Measure RMS" ) );
151 menu.Append( MYID_MEASURE_PP, _( "Measure Peak-to-peak" ) );
152
153 if( panel->GetSimType() == ST_AC || panel->GetSimType() == ST_SP )
154 {
155 menu.Append( MYID_MEASURE_MIN_AT, _( "Measure Frequency of Min" ) );
156 menu.Append( MYID_MEASURE_MAX_AT, _( "Measure Frequency of Max" ) );
157 }
158 else
159 {
160 menu.Append( MYID_MEASURE_MIN_AT, _( "Measure Time of Min" ) );
161 menu.Append( MYID_MEASURE_MAX_AT, _( "Measure Time of Max" ) );
162 }
163
164 menu.Append( MYID_MEASURE_INTEGRAL, _( "Measure Integral" ) );
165
166 if( panel->GetSimType() == ST_TRAN )
167 {
168 menu.AppendSeparator();
169 menu.Append( MYID_FOURIER, _( "Perform Fourier Analysis..." ) );
170 }
171
172 menu.AppendSeparator();
173 menu.Append( GRIDTRICKS_ID_COPY, _( "Copy Signal Name" ) + "\tCtrl+C" );
174
175 m_grid->PopupMenu( &menu );
176 }
177 }
178 }
179}
180
181
182void SIGNALS_GRID_TRICKS::doPopupSelection( wxCommandEvent& event )
183{
184 std::vector<wxString> signals;
185
186 wxGridCellCoordsArray cells1 = m_grid->GetSelectionBlockTopLeft();
187 wxGridCellCoordsArray cells2 = m_grid->GetSelectionBlockBottomRight();
188
189 for( size_t i = 0; i < cells1.Count(); i++ )
190 {
191 if( cells1[i].GetCol() == COL_SIGNAL_NAME )
192 {
193 for( int j = cells1[i].GetRow(); j < cells2[i].GetRow() + 1; j++ )
194 {
195 signals.push_back( m_grid->GetCellValue( j, cells1[i].GetCol() ) );
196 }
197 }
198 }
199
200 wxGridCellCoordsArray cells3 = m_grid->GetSelectedCells();
201
202 for( size_t i = 0; i < cells3.Count(); i++ )
203 {
204 if( cells3[i].GetCol() == COL_SIGNAL_NAME )
205 signals.push_back( m_grid->GetCellValue( cells3[i].GetRow(), cells3[i].GetCol() ) );
206 }
207
208 if( signals.size() < 1 )
209 signals.push_back( m_grid->GetCellValue( m_menuRow, m_menuCol ) );
210
211 auto addMeasurement =
212 [this]( const wxString& cmd, wxString signal )
213 {
214 if( signal.EndsWith( _( " (phase)" ) ) )
215 return;
216
217 if( signal.EndsWith( _( " (gain)" ) ) || signal.EndsWith( _( " (amplitude)" ) ) )
218 {
219 signal = signal.Left( signal.length() - 7 );
220
221 if( signal.Upper().StartsWith( wxS( "V(" ) ) )
222 signal = wxS( "vdb" ) + signal.Mid( 1 );
223 }
224
225 m_parent->AddMeasurement( cmd + wxS( " " ) + signal );
226 };
227
228 if( event.GetId() == MYID_MEASURE_MIN )
229 {
230 for( const wxString& signal : signals )
231 addMeasurement( wxS( "MIN" ), signal );
232 }
233 else if( event.GetId() == MYID_MEASURE_MAX )
234 {
235 for( const wxString& signal : signals )
236 addMeasurement( wxS( "MAX" ), signal );
237 }
238 else if( event.GetId() == MYID_MEASURE_AVG )
239 {
240 for( const wxString& signal : signals )
241 addMeasurement( wxS( "AVG" ), signal );
242 }
243 else if( event.GetId() == MYID_MEASURE_RMS )
244 {
245 for( const wxString& signal : signals )
246 addMeasurement( wxS( "RMS" ), signal );
247 }
248 else if( event.GetId() == MYID_MEASURE_PP )
249 {
250 for( const wxString& signal : signals )
251 addMeasurement( wxS( "PP" ), signal );
252 }
253 else if( event.GetId() == MYID_MEASURE_MIN_AT )
254 {
255 for( const wxString& signal : signals )
256 addMeasurement( wxS( "MIN_AT" ), signal );
257 }
258 else if( event.GetId() == MYID_MEASURE_MAX_AT )
259 {
260 for( const wxString& signal : signals )
261 addMeasurement( wxS( "MAX_AT" ), signal );
262 }
263 else if( event.GetId() == MYID_MEASURE_INTEGRAL )
264 {
265 for( const wxString& signal : signals )
266 addMeasurement( wxS( "INTEG" ), signal );
267 }
268 else if( event.GetId() == MYID_FOURIER )
269 {
270 wxString title;
271 wxString fundamental = wxT( "1K" );
272
273 if( signals.size() == 1 )
274 title.Printf( _( "Fourier Analysis of %s" ), signals[0] );
275 else
276 title = _( "Fourier Analyses of Multiple Signals" );
277
278 WX_TEXT_ENTRY_DIALOG dlg( m_parent, _( "Fundamental frequency:" ), title, fundamental );
279
280 if( dlg.ShowModal() != wxID_OK )
281 return;
282
283 if( !dlg.GetValue().IsEmpty() )
284 fundamental = dlg.GetValue();
285
286 for( const wxString& signal : signals )
287 m_parent->DoFourier( signal, fundamental );
288 }
289 else if( event.GetId() == GRIDTRICKS_ID_COPY )
290 {
291 wxLogNull doNotLog; // disable logging of failed clipboard actions
292 wxString txt;
293
294 for( const wxString& signal : signals )
295 {
296 if( !txt.IsEmpty() )
297 txt += '\r';
298
299 txt += signal;
300 }
301
302 if( wxTheClipboard->Open() )
303 {
304 wxTheClipboard->SetData( new wxTextDataObject( txt ) );
305 wxTheClipboard->Flush(); // Allow data to be available after closing KiCad
306 wxTheClipboard->Close();
307 }
308 }
309}
310
311
313{
314public:
316 GRID_TRICKS( aGrid ),
317 m_parent( aParent ),
318 m_menuRow( 0 ),
319 m_menuCol( 0 )
320 {}
321
322protected:
323 void showPopupMenu( wxMenu& menu, wxGridEvent& aEvent ) override;
324 void doPopupSelection( wxCommandEvent& event ) override;
325
326protected:
330};
331
332
333void CURSORS_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
334{
335 m_menuRow = aEvent.GetRow();
336 m_menuCol = aEvent.GetCol();
337
339 {
340 wxString msg = m_grid->GetColLabelValue( m_menuCol );
341
342 menu.Append( MYID_FORMAT_VALUE, wxString::Format( _( "Format %s..." ), msg ) );
343 menu.AppendSeparator();
344 }
345
346 GRID_TRICKS::showPopupMenu( menu, aEvent );
347}
348
349
350void CURSORS_GRID_TRICKS::doPopupSelection( wxCommandEvent& event )
351{
352 auto getSignalName =
353 [this]( int row ) -> wxString
354 {
355 wxString signal = m_grid->GetCellValue( row, COL_CURSOR_SIGNAL );
356
357 if( signal.EndsWith( "[2 - 1]" ) )
358 signal = signal.Left( signal.length() - 7 );
359
360 return signal;
361 };
362
363 if( event.GetId() == MYID_FORMAT_VALUE )
364 {
365 int axis = m_menuCol - COL_CURSOR_X;
367 DIALOG_SIM_FORMAT_VALUE formatDialog( m_parent, &format );
368
369 if( formatDialog.ShowModal() == wxID_OK )
370 {
371 for( int row = 0; row < m_grid->GetNumberRows(); ++row )
372 {
373 if( getSignalName( row ) == getSignalName( m_menuRow ) )
374 m_parent->SetCursorFormat( row, axis, format );
375 }
376 }
377 }
378 else
379 {
381 }
382}
383
384
386{
387public:
389 GRID_TRICKS( aGrid ),
390 m_parent( aParent ),
391 m_menuRow( 0 ),
392 m_menuCol( 0 )
393 {}
394
395protected:
396 void showPopupMenu( wxMenu& menu, wxGridEvent& aEvent ) override;
397 void doPopupSelection( wxCommandEvent& event ) override;
398
399protected:
403};
404
405
406void MEASUREMENTS_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
407{
408 m_menuRow = aEvent.GetRow();
409 m_menuCol = aEvent.GetCol();
410
411 if( !( m_grid->IsInSelection( m_menuRow, m_menuCol ) ) )
412 m_grid->ClearSelection();
413
414 m_grid->SetGridCursor( m_menuRow, m_menuCol );
415
417 menu.Append( MYID_FORMAT_VALUE, _( "Format Value..." ) );
418
419 if( m_menuRow < ( m_grid->GetNumberRows() - 1 ) )
420 menu.Append( MYID_DELETE_MEASUREMENT, _( "Delete Measurement" ) );
421
422 menu.AppendSeparator();
423
424 GRID_TRICKS::showPopupMenu( menu, aEvent );
425}
426
427
429{
430 if( event.GetId() == MYID_FORMAT_VALUE )
431 {
433 DIALOG_SIM_FORMAT_VALUE formatDialog( m_parent, &format );
434
435 if( formatDialog.ShowModal() == wxID_OK )
436 {
440 }
441 }
442 else if( event.GetId() == MYID_DELETE_MEASUREMENT )
443 {
444 std::vector<int> measurements;
445
446 wxGridCellCoordsArray cells1 = m_grid->GetSelectionBlockTopLeft();
447 wxGridCellCoordsArray cells2 = m_grid->GetSelectionBlockBottomRight();
448
449 for( size_t i = 0; i < cells1.Count(); i++ )
450 {
451 if( cells1[i].GetCol() == COL_MEASUREMENT )
452 {
453 for( int j = cells1[i].GetRow(); j < cells2[i].GetRow() + 1; j++ )
454 measurements.push_back( j );
455 }
456 }
457
458 wxGridCellCoordsArray cells3 = m_grid->GetSelectedCells();
459
460 for( size_t i = 0; i < cells3.Count(); i++ )
461 {
462 if( cells3[i].GetCol() == COL_MEASUREMENT )
463 measurements.push_back( cells3[i].GetRow() );
464 }
465
466 if( measurements.size() < 1 )
467 measurements.push_back( m_menuRow );
468
469 // When deleting a row, we'll change the indexes.
470 // To avoid problems, we can start with the highest indexes.
471 sort( measurements.begin(), measurements.end(), std::greater<>() );
472
473 for( int row : measurements )
475
476 m_grid->ClearSelection();
477
479 }
480 else
481 {
483 }
484}
485
486
488{
489public:
491 m_frame( aFrame )
492 {
494 }
495
497 {
499 }
500
501private:
503};
504
505
506#define ID_SIM_REFRESH 10207
507#define REFRESH_INTERVAL 50 // 20 frames/second.
508
509
511 SCH_EDIT_FRAME* aSchematicFrame ) :
512 SIMULATOR_FRAME_UI_BASE( aSimulatorFrame ),
513 m_SuppressGridEvents( 0 ),
514 m_simulatorFrame( aSimulatorFrame ),
515 m_schematicFrame( aSchematicFrame ),
516 m_darkMode( true ),
517 m_plotNumber( 0 ),
518 m_refreshTimer( this, ID_SIM_REFRESH )
519{
520 // Get the previous size and position of windows:
522
523 m_filter->SetHint( _( "Filter" ) );
524
525 m_signalsGrid->wxGrid::SetLabelFont( KIUI::GetStatusFont( this ) );
526 m_cursorsGrid->wxGrid::SetLabelFont( KIUI::GetStatusFont( this ) );
527 m_measurementsGrid->wxGrid::SetLabelFont( KIUI::GetStatusFont( this ) );
528
529 m_signalsGrid->PushEventHandler( new SIGNALS_GRID_TRICKS( this, m_signalsGrid ) );
530 m_cursorsGrid->PushEventHandler( new CURSORS_GRID_TRICKS( this, m_cursorsGrid ) );
531 m_measurementsGrid->PushEventHandler( new MEASUREMENTS_GRID_TRICKS( this, m_measurementsGrid ) );
532
533 wxGridCellAttr* attr = new wxGridCellAttr;
534 attr->SetReadOnly();
535 m_signalsGrid->SetColAttr( COL_SIGNAL_NAME, attr );
536
537 attr = new wxGridCellAttr;
538 attr->SetReadOnly();
539 m_cursorsGrid->SetColAttr( COL_CURSOR_NAME, attr );
540
541 attr = new wxGridCellAttr;
542 attr->SetReadOnly();
543 m_cursorsGrid->SetColAttr( COL_CURSOR_SIGNAL, attr );
544
545 attr = new wxGridCellAttr;
546 attr->SetReadOnly();
547 m_cursorsGrid->SetColAttr( COL_CURSOR_Y, attr );
548
549 for( int cursorId = 0; cursorId < 3; ++cursorId )
550 {
551 m_cursorFormats[ cursorId ][ 0 ] = { 3, wxS( "~s" ) };
552 m_cursorFormats[ cursorId ][ 1 ] = { 3, wxS( "~V" ) };
553 }
554
555 attr = new wxGridCellAttr;
556 attr->SetReadOnly();
557 m_measurementsGrid->SetColAttr( COL_MEASUREMENT_VALUE, attr );
558
559 // Prepare the color list to plot traces
561
562 Bind( EVT_SIM_CURSOR_UPDATE, &SIMULATOR_FRAME_UI::onPlotCursorUpdate, this );
563
564 Bind( wxEVT_TIMER,
565 [&]( wxTimerEvent& aEvent )
566 {
567 OnSimRefresh( false );
568
569 if( m_simulatorFrame->GetSimulator()->IsRunning() )
570 m_refreshTimer.Start( REFRESH_INTERVAL, wxTIMER_ONE_SHOT );
571 },
572 m_refreshTimer.GetId() );
573
574#ifndef wxHAS_NATIVE_TABART
575 // Default non-native tab art has ugly gradients we don't want
576 m_plotNotebook->SetArtProvider( new wxAuiSimpleTabArt() );
577#endif
578}
579
580
582{
583 // Delete the GRID_TRICKS.
584 m_signalsGrid->PopEventHandler( true );
585 m_cursorsGrid->PopEventHandler( true );
586 m_measurementsGrid->PopEventHandler( true );
587}
588
589
591{
592 for( int ii = 0; ii < (int) m_plotNotebook->GetPageCount(); ++ii )
593 {
594 SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( ii ) );
595
596 wxCHECK( simTab, /* void */ );
597
598 simTab->OnLanguageChanged();
599
600 wxString pageTitle( simulator()->TypeToName( simTab->GetSimType(), true ) );
601 pageTitle.Prepend( wxString::Format( _( "Analysis %u - " ), ii+1 /* 1-based */ ) );
602
603 m_plotNotebook->SetPageText( ii, pageTitle );
604 }
605
606 m_filter->SetHint( _( "Filter" ) );
607
608 m_signalsGrid->SetColLabelValue( COL_SIGNAL_NAME, _( "Signal" ) );
609 m_signalsGrid->SetColLabelValue( COL_SIGNAL_SHOW, _( "Plot" ) );
610 m_signalsGrid->SetColLabelValue( COL_SIGNAL_COLOR, _( "Color" ) );
611 m_signalsGrid->SetColLabelValue( COL_CURSOR_1, _( "Cursor 1" ) );
612 m_signalsGrid->SetColLabelValue( COL_CURSOR_2, _( "Cursor 2" ) );
613
614 m_cursorsGrid->SetColLabelValue( COL_CURSOR_NAME, _( "Cursor" ) );
615 m_cursorsGrid->SetColLabelValue( COL_CURSOR_SIGNAL, _( "Signal" ) );
616 m_cursorsGrid->SetColLabelValue( COL_CURSOR_X, _( "Time" ) );
617 m_cursorsGrid->SetColLabelValue( COL_CURSOR_Y, _( "Value" ) );
619
620 for( TUNER_SLIDER* tuner : m_tuners )
621 tuner->ShowChangedLanguage();
622}
623
624
626{
627 const EESCHEMA_SETTINGS::SIMULATOR& settings = aCfg->m_Simulator;
628
629 // Read subwindows sizes (should be > 0 )
635 m_darkMode = !settings.view.white_background;
636
637 m_preferences = settings.preferences;
638}
639
640
642{
644
645 settings.view.plot_panel_width = m_splitterLeftRight->GetSashPosition();
646 settings.view.plot_panel_height = m_splitterPlotAndConsole->GetSashPosition();
647 settings.view.signal_panel_height = m_splitterSignals->GetSashPosition();
648 settings.view.cursors_panel_height = m_splitterCursors->GetSashPosition();
649 settings.view.measurements_panel_height = m_splitterMeasurements->GetSashPosition();
650 settings.view.white_background = !m_darkMode;
651}
652
653
655{
656 m_preferences = aPrefs;
657
658 const std::size_t pageCount = m_plotNotebook->GetPageCount();
659 for( std::size_t i = 0; i < pageCount; ++i )
660 {
661 wxWindow* page = m_plotNotebook->GetPage( i );
662 auto simTab = dynamic_cast<SIM_TAB*>( page );
663 wxASSERT( simTab != nullptr );
664 simTab->ApplyPreferences( aPrefs );
665 }
666}
667
668
670{
671 if( !simulator()->Settings()->GetWorkbookFilename().IsEmpty() )
672 {
673 wxFileName filename = simulator()->Settings()->GetWorkbookFilename();
674 filename.SetPath( m_schematicFrame->Prj().GetProjectPath() );
675
676 if( !LoadWorkbook( filename.GetFullPath() ) )
677 simulator()->Settings()->SetWorkbookFilename( "" );
678 }
679 else if( m_simulatorFrame->LoadSimulator( wxEmptyString, 0 ) )
680 {
681 wxString schTextSimCommand = circuitModel()->GetSchTextSimCommand();
682
683 if( !schTextSimCommand.IsEmpty() )
684 {
685 SIM_TAB* simTab = NewSimTab( schTextSimCommand );
687 }
688
690 rebuildSignalsGrid( m_filter->GetValue() );
691 }
692}
693
694
696{
699
702
705
708
711}
712
713
714void sortSignals( std::vector<wxString>& signals )
715{
716 std::sort( signals.begin(), signals.end(),
717 []( const wxString& lhs, const wxString& rhs )
718 {
719 // Sort voltages first
720 if( lhs.Upper().StartsWith( 'V' ) && !rhs.Upper().StartsWith( 'V' ) )
721 return true;
722 else if( !lhs.Upper().StartsWith( 'V' ) && rhs.Upper().StartsWith( 'V' ) )
723 return false;
724
725 return StrNumCmp( lhs, rhs, true /* ignore case */ ) < 0;
726 } );
727}
728
729
731{
732 SUPPRESS_GRID_CELL_EVENTS raii( this );
733
735
736 SIM_PLOT_TAB* plotPanel = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
737
738 if( !plotPanel )
739 return;
740
741 SIM_TYPE simType = plotPanel->GetSimType();
742 std::vector<wxString> signals;
743
744 if( plotPanel->GetSimType() == ST_FFT )
745 {
746 wxStringTokenizer tokenizer( plotPanel->GetSimCommand(), wxT( " \t\r\n" ), wxTOKEN_STRTOK );
747
748 while( tokenizer.HasMoreTokens() && tokenizer.GetNextToken().Lower() != wxT( "fft" ) )
749 {};
750
751 while( tokenizer.HasMoreTokens() )
752 signals.emplace_back( tokenizer.GetNextToken() );
753 }
754 else
755 {
756 // NB: m_signals are already broken out into gain/phase, but m_userDefinedSignals are
757 // as the user typed them
758
759 for( const wxString& signal : m_signals )
760 signals.push_back( signal );
761
762 for( const auto& [ id, signal ] : m_userDefinedSignals )
763 {
764 if( simType == ST_AC )
765 {
766 signals.push_back( signal + _( " (gain)" ) );
767 signals.push_back( signal + _( " (phase)" ) );
768 }
769 else if( simType == ST_SP )
770 {
771 signals.push_back( signal + _( " (amplitude)" ) );
772 signals.push_back( signal + _( " (phase)" ) );
773 }
774 else
775 {
776 signals.push_back( signal );
777 }
778 }
779
780 sortSignals( signals );
781 }
782
783 if( aFilter.IsEmpty() )
784 aFilter = wxS( "*" );
785
786 EDA_COMBINED_MATCHER matcher( aFilter.Upper(), CTX_SIGNAL );
787 int row = 0;
788
789 for( const wxString& signal : signals )
790 {
791 if( matcher.Find( signal.Upper() ) )
792 {
793 int traceType = SPT_UNKNOWN;
794 wxString vectorName = vectorNameFromSignalName( plotPanel, signal, &traceType );
795 TRACE* trace = plotPanel->GetTrace( vectorName, traceType );
796
797 m_signalsGrid->AppendRows( 1 );
798 m_signalsGrid->SetCellValue( row, COL_SIGNAL_NAME, signal );
799
800 wxGridCellAttr* attr = new wxGridCellAttr;
801 attr->SetRenderer( new wxGridCellBoolRenderer() );
802 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
803 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
804 m_signalsGrid->SetAttr( row, COL_SIGNAL_SHOW, attr );
805
806 if( !trace )
807 {
808 attr = new wxGridCellAttr;
809 attr->SetReadOnly();
810 m_signalsGrid->SetAttr( row, COL_SIGNAL_COLOR, attr );
811 m_signalsGrid->SetCellValue( row, COL_SIGNAL_COLOR, wxEmptyString );
812
813 attr = new wxGridCellAttr;
814 attr->SetReadOnly();
815 m_signalsGrid->SetAttr( row, COL_CURSOR_1, attr );
816
817 attr = new wxGridCellAttr;
818 attr->SetReadOnly();
819 m_signalsGrid->SetAttr( row, COL_CURSOR_2, attr );
820 }
821 else
822 {
823 m_signalsGrid->SetCellValue( row, COL_SIGNAL_SHOW, wxS( "1" ) );
824
825 attr = new wxGridCellAttr;
826 attr->SetRenderer( new GRID_CELL_COLOR_RENDERER( this ) );
827 attr->SetEditor( new GRID_CELL_COLOR_SELECTOR( this, m_signalsGrid ) );
828 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
829 m_signalsGrid->SetAttr( row, COL_SIGNAL_COLOR, attr );
830 KIGFX::COLOR4D color( trace->GetPen().GetColour() );
831 m_signalsGrid->SetCellValue( row, COL_SIGNAL_COLOR, color.ToCSSString() );
832
833 attr = new wxGridCellAttr;
834 attr->SetRenderer( new wxGridCellBoolRenderer() );
835 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
836 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
837 m_signalsGrid->SetAttr( row, COL_CURSOR_1, attr );
838
839 attr = new wxGridCellAttr;
840 attr->SetRenderer( new wxGridCellBoolRenderer() );
841 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
842 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
843 m_signalsGrid->SetAttr( row, COL_CURSOR_2, attr );
844 }
845
846 row++;
847 }
848 }
849}
850
851
853{
854 m_signals.clear();
855
856 int options = m_simulatorFrame->GetCurrentOptions();
858 wxString unconnected = wxString( wxS( "unconnected-(" ) );
859
860 if( simType == ST_UNKNOWN )
861 simType = ST_TRAN;
862
863 unconnected.Replace( '(', '_' ); // Convert to SPICE markup
864
865 auto addSignal =
866 [&]( const wxString& aSignalName )
867 {
868 if( simType == ST_AC )
869 {
870 m_signals.push_back( aSignalName + _( " (gain)" ) );
871 m_signals.push_back( aSignalName + _( " (phase)" ) );
872 }
873 else if( simType == ST_SP )
874 {
875 m_signals.push_back( aSignalName + _( " (amplitude)" ) );
876 m_signals.push_back( aSignalName + _( " (phase)" ) );
877 }
878 else
879 {
880 m_signals.push_back( aSignalName );
881 }
882 };
883
885 && ( simType == ST_TRAN || simType == ST_DC || simType == ST_AC || simType == ST_FFT) )
886 {
887 for( const std::string& net : circuitModel()->GetNets() )
888 {
889 // netnames are escaped (can contain "{slash}" for '/') Unscape them:
890 wxString netname = UnescapeString( net );
891
892 if( netname == "GND" || netname == "0" || netname.StartsWith( unconnected ) )
893 continue;
894
895 m_quotedNetnames[ netname ] = wxString::Format( wxS( "\"%s\"" ), netname );
896 addSignal( wxString::Format( wxS( "V(%s)" ), netname ) );
897 }
898 }
899
901 && ( simType == ST_TRAN || simType == ST_DC || simType == ST_AC ) )
902 {
903 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
904 {
905 // Add all possible currents for the device.
906 for( const std::string& name : item.model->SpiceGenerator().CurrentNames( item ) )
907 addSignal( name );
908 }
909 }
910
912 && ( simType == ST_TRAN || simType == ST_DC ) )
913 {
914 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
915 {
916 if( item.model->GetPinCount() >= 2 )
917 {
918 wxString name = item.model->SpiceGenerator().ItemName( item );
919 addSignal( wxString::Format( wxS( "P(%s)" ), name ) );
920 }
921 }
922 }
923
924 if( simType == ST_NOISE )
925 {
926 addSignal( wxS( "inoise_spectrum" ) );
927 addSignal( wxS( "onoise_spectrum" ) );
928 }
929
930 if( simType == ST_SP )
931 {
932 std::vector<std::string> portnums;
933
934 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
935 {
936 wxString name = item.model->SpiceGenerator().ItemName( item );
937
938 // We are only looking for voltage sources in .SP mode
939 if( !name.StartsWith( "V" ) )
940 continue;
941
942 std::string portnum = "";
943
944 if( const SIM_MODEL::PARAM* portnum_param = item.model->FindParam( "portnum" ) )
945 portnum = SIM_VALUE::ToSpice( portnum_param->value );
946
947 if( portnum != "" )
948 portnums.push_back( portnum );
949 }
950
951 for( const std::string& portnum1 : portnums )
952 {
953 for( const std::string& portnum2 : portnums )
954 {
955 addSignal( wxString::Format( wxS( "S_%s_%s" ), portnum1, portnum2 ) );
956 }
957 }
958 }
959
960 // Add .PROBE directives
961 for( const wxString& directive : circuitModel()->GetDirectives() )
962 {
963 wxStringTokenizer tokenizer( directive, wxT( "\r\n" ), wxTOKEN_STRTOK );
964
965 while( tokenizer.HasMoreTokens() )
966 {
967 wxString line = tokenizer.GetNextToken();
968 wxString directiveParams;
969
970 if( line.Upper().StartsWith( wxS( ".PROBE" ), &directiveParams ) )
971 addSignal( directiveParams.Trim( true ).Trim( false ) );
972 }
973 }
974}
975
976
977SIM_TAB* SIMULATOR_FRAME_UI::NewSimTab( const wxString& aSimCommand )
978{
979 SIM_TAB* simTab = nullptr;
980 SIM_TYPE simType = SPICE_CIRCUIT_MODEL::CommandToSimType( aSimCommand );
981
982 if( SIM_TAB::IsPlottable( simType ) )
983 {
984 SIM_PLOT_TAB* panel = new SIM_PLOT_TAB( aSimCommand, m_plotNotebook );
985 simTab = panel;
987 }
988 else
989 {
990 simTab = new SIM_NOPLOT_TAB( aSimCommand, m_plotNotebook );
991 }
992
993 wxString pageTitle( simulator()->TypeToName( simType, true ) );
994 pageTitle.Prepend( wxString::Format( _( "Analysis %u - " ), (unsigned int) ++m_plotNumber ) );
995
996 m_plotNotebook->AddPage( simTab, pageTitle, true );
997
998 return simTab;
999}
1000
1001
1002void SIMULATOR_FRAME_UI::OnFilterText( wxCommandEvent& aEvent )
1003{
1004 rebuildSignalsGrid( m_filter->GetValue() );
1005}
1006
1007
1008void SIMULATOR_FRAME_UI::OnFilterMouseMoved( wxMouseEvent& aEvent )
1009{
1010 wxPoint pos = aEvent.GetPosition();
1011 wxRect ctrlRect = m_filter->GetScreenRect();
1012 int buttonWidth = ctrlRect.GetHeight(); // Presume buttons are square
1013
1014 if( m_filter->IsSearchButtonVisible() && pos.x < buttonWidth )
1015 SetCursor( wxCURSOR_ARROW );
1016 else if( m_filter->IsCancelButtonVisible() && pos.x > ctrlRect.GetWidth() - buttonWidth )
1017 SetCursor( wxCURSOR_ARROW );
1018 else
1019 SetCursor( wxCURSOR_IBEAM );
1020}
1021
1022
1023wxString vectorNameFromSignalId( int aUserDefinedSignalId )
1024{
1025 return wxString::Format( wxS( "user%d" ), aUserDefinedSignalId );
1026}
1027
1028
1034 const wxString& aSignalName,
1035 int* aTraceType )
1036{
1037 std::map<wxString, int> suffixes;
1038 suffixes[ _( " (amplitude)" ) ] = SPT_SP_AMP;
1039 suffixes[ _( " (gain)" ) ] = SPT_AC_GAIN;
1040 suffixes[ _( " (phase)" ) ] = SPT_AC_PHASE;
1041
1042 if( aTraceType )
1043 {
1044 if( aPlotTab && aPlotTab->GetSimType() == ST_NOISE )
1045 {
1046 if( getNoiseSource().Upper().StartsWith( 'I' ) )
1047 *aTraceType = SPT_CURRENT;
1048 else
1049 *aTraceType = SPT_VOLTAGE;
1050 }
1051 else
1052 {
1053 wxUniChar firstChar = aSignalName.Upper()[0];
1054
1055 if( firstChar == 'V' )
1056 *aTraceType = SPT_VOLTAGE;
1057 else if( firstChar == 'I' )
1058 *aTraceType = SPT_CURRENT;
1059 else if( firstChar == 'P' )
1060 *aTraceType = SPT_POWER;
1061 }
1062 }
1063
1064 wxString suffix;
1065 wxString name = aSignalName;
1066
1067 for( const auto& [ candidate, type ] : suffixes )
1068 {
1069 if( name.EndsWith( candidate ) )
1070 {
1071 name = name.Left( name.Length() - candidate.Length() );
1072
1073 if( aTraceType )
1074 *aTraceType |= type;
1075
1076 break;
1077 }
1078 }
1079
1080 for( const auto& [ id, signal ] : m_userDefinedSignals )
1081 {
1082 if( name == signal )
1083 return vectorNameFromSignalId( id );
1084 }
1085
1086 return name;
1087};
1088
1089
1091{
1092 if( m_SuppressGridEvents > 0 )
1093 return;
1094
1095 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1096
1097 if( !plotTab )
1098 return;
1099
1100 int row = aEvent.GetRow();
1101 int col = aEvent.GetCol();
1102 wxString text = m_signalsGrid->GetCellValue( row, col );
1103 wxString signalName = m_signalsGrid->GetCellValue( row, COL_SIGNAL_NAME );
1104 int traceType = SPT_UNKNOWN;
1105 wxString vectorName = vectorNameFromSignalName( plotTab, signalName, &traceType );
1106
1107 if( col == COL_SIGNAL_SHOW )
1108 {
1109 if( text == wxS( "1" ) )
1110 updateTrace( vectorName, traceType, plotTab );
1111 else
1112 plotTab->DeleteTrace( vectorName, traceType );
1113
1114 plotTab->GetPlotWin()->UpdateAll();
1115
1116 // Update enabled/visible states of other controls
1119 OnModify();
1120 }
1121 else if( col == COL_SIGNAL_COLOR )
1122 {
1123 KIGFX::COLOR4D color( m_signalsGrid->GetCellValue( row, COL_SIGNAL_COLOR ) );
1124 TRACE* trace = plotTab->GetTrace( vectorName, traceType );
1125
1126 if( trace )
1127 {
1128 trace->SetTraceColour( color.ToColour() );
1129 plotTab->UpdateTraceStyle( trace );
1130 plotTab->UpdatePlotColors();
1131 OnModify();
1132 }
1133 }
1134 else if( col == COL_CURSOR_1 || col == COL_CURSOR_2 )
1135 {
1136 for( int ii = 0; ii < m_signalsGrid->GetNumberRows(); ++ii )
1137 {
1138 signalName = m_signalsGrid->GetCellValue( ii, COL_SIGNAL_NAME );
1139 vectorName = vectorNameFromSignalName( plotTab, signalName, &traceType );
1140
1141 int id = col == COL_CURSOR_1 ? 1 : 2;
1142 bool enable = ii == row && text == wxS( "1" );
1143
1144 plotTab->EnableCursor( vectorName, traceType, id, enable, signalName );
1145 OnModify();
1146 }
1147
1148 // Update cursor checkboxes (which are really radio buttons)
1150 }
1151}
1152
1153
1155{
1156 if( m_SuppressGridEvents > 0 )
1157 return;
1158
1159 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1160
1161 if( !plotTab )
1162 return;
1163
1164 int row = aEvent.GetRow();
1165 int col = aEvent.GetCol();
1166 wxString text = m_cursorsGrid->GetCellValue( row, col );
1167 wxString cursorName = m_cursorsGrid->GetCellValue( row, COL_CURSOR_NAME );
1168
1169 if( col == COL_CURSOR_X )
1170 {
1171 CURSOR* cursor1 = nullptr;
1172 CURSOR* cursor2 = nullptr;
1173
1174 for( const auto& [name, trace] : plotTab->GetTraces() )
1175 {
1176 if( CURSOR* cursor = trace->GetCursor( 1 ) )
1177 cursor1 = cursor;
1178
1179 if( CURSOR* cursor = trace->GetCursor( 2 ) )
1180 cursor2 = cursor;
1181 }
1182
1183 double value = SPICE_VALUE( text ).ToDouble();
1184
1185 if( cursorName == wxS( "1" ) && cursor1 )
1186 cursor1->SetCoordX( value );
1187 else if( cursorName == wxS( "2" ) && cursor2 )
1188 cursor2->SetCoordX( value );
1189 else if( cursorName == _( "Diff" ) && cursor1 && cursor2 )
1190 cursor2->SetCoordX( cursor1->GetCoords().x + value );
1191
1193 OnModify();
1194 }
1195 else
1196 {
1197 wxFAIL_MSG( wxT( "All other columns are supposed to be read-only!" ) );
1198 }
1199}
1200
1201
1203{
1204 SPICE_VALUE_FORMAT result;
1205 result.FromString( m_measurementsGrid->GetCellValue( aRow, COL_MEASUREMENT_FORMAT ) );
1206 return result;
1207}
1208
1209
1211{
1212 m_measurementsGrid->SetCellValue( aRow, COL_MEASUREMENT_FORMAT, aFormat.ToString() );
1213}
1214
1215
1217{
1218 if( aRow < ( m_measurementsGrid->GetNumberRows() - 1 ) )
1219 m_measurementsGrid->DeleteRows( aRow, 1 );
1220}
1221
1222
1224{
1225 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1226
1227 if( !plotTab )
1228 return;
1229
1230 int row = aEvent.GetRow();
1231 int col = aEvent.GetCol();
1232 wxString text = m_measurementsGrid->GetCellValue( row, col );
1233
1234 if( col == COL_MEASUREMENT )
1235 {
1236 UpdateMeasurement( row );
1237 OnModify();
1238 }
1239 else
1240 {
1241 wxFAIL_MSG( wxT( "All other columns are supposed to be read-only!" ) );
1242 }
1243
1244 // Always leave a single empty row for type-in
1245
1246 int rowCount = (int) m_measurementsGrid->GetNumberRows();
1247 int emptyRows = 0;
1248
1249 for( row = rowCount - 1; row >= 0; row-- )
1250 {
1251 if( m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1252 emptyRows++;
1253 else
1254 break;
1255 }
1256
1257 if( emptyRows > 1 )
1258 {
1259 int killRows = emptyRows - 1;
1260 m_measurementsGrid->DeleteRows( rowCount - killRows, killRows );
1261 }
1262 else if( emptyRows == 0 )
1263 {
1264 m_measurementsGrid->AppendRows( 1 );
1265 }
1266}
1267
1268
1269void SIMULATOR_FRAME_UI::OnUpdateUI( wxUpdateUIEvent& event )
1270{
1271 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
1272 {
1273 if( plotTab->GetLegendPosition() != plotTab->m_LastLegendPosition )
1274 {
1275 plotTab->m_LastLegendPosition = plotTab->GetLegendPosition();
1276 OnModify();
1277 }
1278 }
1279}
1280
1281
1297{
1298 static wxRegEx measureParamsRegEx( wxT( "^"
1299 " *"
1300 "([a-zA-Z_]+)"
1301 " +"
1302 "([a-zA-Z]*)\\(([^\\)]+)\\)" ) );
1303
1304 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1305
1306 if( !plotTab )
1307 return;
1308
1309 wxString text = m_measurementsGrid->GetCellValue( aRow, COL_MEASUREMENT );
1310
1311 if( text.IsEmpty() )
1312 {
1313 m_measurementsGrid->SetCellValue( aRow, COL_MEASUREMENT_VALUE, wxEmptyString );
1314 return;
1315 }
1316
1317 wxString simType = simulator()->TypeToName( plotTab->GetSimType(), true );
1318 wxString resultName = wxString::Format( wxS( "meas_result_%u" ), aRow );
1319 wxString result = wxS( "?" );
1320
1321 if( measureParamsRegEx.Matches( text ) )
1322 {
1323 wxString func = measureParamsRegEx.GetMatch( text, 1 ).Upper();
1324 wxString signalType = measureParamsRegEx.GetMatch( text, 2 ).Upper();
1325 wxString deviceName = measureParamsRegEx.GetMatch( text, 3 );
1326 wxString units;
1328
1329 if( signalType.EndsWith( wxS( "DB" ) ) )
1330 {
1331 units = wxS( "dB" );
1332 }
1333 else if( signalType.StartsWith( 'I' ) )
1334 {
1335 units = wxS( "A" );
1336 }
1337 else if( signalType.StartsWith( 'P' ) )
1338 {
1339 units = wxS( "W" );
1340 // Our syntax is different from ngspice for power signals
1341 text = func + " " + deviceName + ":power";
1342 }
1343 else
1344 {
1345 units = wxS( "V" );
1346 }
1347
1348 if( func.EndsWith( wxS( "_AT" ) ) )
1349 {
1350 if( plotTab->GetSimType() == ST_AC || plotTab->GetSimType() == ST_SP )
1351 units = wxS( "Hz" );
1352 else
1353 units = wxS( "s" );
1354 }
1355 else if( func.StartsWith( wxS( "INTEG" ) ) )
1356 {
1357 switch( plotTab->GetSimType() )
1358 {
1359 case ST_TRAN:
1360 if ( signalType.StartsWith( 'P' ) )
1361 units = wxS( "J" );
1362 else
1363 units += wxS( ".s" );
1364
1365 break;
1366
1367 case ST_AC:
1368 case ST_SP:
1369 case ST_DISTO:
1370 case ST_NOISE:
1371 case ST_FFT:
1372 case ST_SENS: // If there is a vector, it is frequency
1373 units += wxS( "·Hz" );
1374 break;
1375
1376 case ST_DC: // Could be a lot of things : V, A, deg C, ohm, ...
1377 case ST_OP: // There is no vector for integration
1378 case ST_PZ: // There is no vector for integration
1379 case ST_TF: // There is no vector for integration
1380 default:
1381 units += wxS( "·?" );
1382 break;
1383 }
1384 }
1385
1386 fmt.UpdateUnits( units );
1387 SetMeasureFormat( aRow, fmt );
1388 }
1389
1391 {
1392 wxString cmd = wxString::Format( wxS( "meas %s %s %s" ), simType, resultName, text );
1393 simulator()->Command( "echo " + cmd.ToStdString() );
1394 simulator()->Command( cmd.ToStdString() );
1395
1396 std::vector<double> resultVec = simulator()->GetGainVector( resultName.ToStdString() );
1397
1398 if( resultVec.size() > 0 )
1399 result = SPICE_VALUE( resultVec[0] ).ToString( GetMeasureFormat( aRow ) );
1400 }
1401
1402 m_measurementsGrid->SetCellValue( aRow, COL_MEASUREMENT_VALUE, result );
1403}
1404
1405
1406void SIMULATOR_FRAME_UI::AddTuner( const SCH_SHEET_PATH& aSheetPath, SCH_SYMBOL* aSymbol )
1407{
1408 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1409
1410 if( !plotTab )
1411 return;
1412
1413 wxString ref = aSymbol->GetRef( &aSheetPath );
1414
1415 // Do not add multiple instances for the same component.
1416 for( TUNER_SLIDER* tuner : m_tuners )
1417 {
1418 if( tuner->GetSymbolRef() == ref )
1419 return;
1420 }
1421
1422 const SPICE_ITEM* item = GetExporter()->FindItem( std::string( ref.ToUTF8() ) );
1423
1424 // Do nothing if the symbol is not tunable.
1425 if( !item || !item->model->GetTunerParam() )
1426 return;
1427
1428 try
1429 {
1430 TUNER_SLIDER* tuner = new TUNER_SLIDER( this, m_panelTuners, aSheetPath, aSymbol );
1431 m_sizerTuners->Add( tuner );
1432 m_tuners.push_back( tuner );
1433 m_panelTuners->Layout();
1434 OnModify();
1435 }
1436 catch( const KI_PARAM_ERROR& e )
1437 {
1438 DisplayErrorMessage( nullptr, e.What() );
1439 }
1440}
1441
1442
1443void SIMULATOR_FRAME_UI::UpdateTunerValue( const SCH_SHEET_PATH& aSheetPath, const KIID& aSymbol,
1444 const wxString& aRef, const wxString& aValue )
1445{
1446 SCH_ITEM* item = aSheetPath.GetItem( aSymbol );
1447 SCH_SYMBOL* symbol = dynamic_cast<SCH_SYMBOL*>( item );
1448
1449 if( !symbol )
1450 {
1451 DisplayErrorMessage( this, _( "Could not apply tuned value(s):" ) + wxS( " " )
1452 + wxString::Format( _( "%s not found" ), aRef ) );
1453 return;
1454 }
1455
1456 NULL_REPORTER devnull;
1457 SIM_LIB_MGR mgr( &m_schematicFrame->Prj() );
1458 SIM_MODEL& model = mgr.CreateModel( &aSheetPath, *symbol, devnull ).model;
1459
1460 const SIM_MODEL::PARAM* tunerParam = model.GetTunerParam();
1461
1462 if( !tunerParam )
1463 {
1464 DisplayErrorMessage( this, _( "Could not apply tuned value(s):" ) + wxS( " " )
1465 + wxString::Format( _( "%s is not tunable" ), aRef ) );
1466 return;
1467 }
1468
1469 model.SetParamValue( tunerParam->info.name, std::string( aValue.ToUTF8() ) );
1470 model.WriteFields( symbol->GetFields() );
1471
1472 m_schematicFrame->UpdateItem( symbol, false, true );
1474}
1475
1476
1478{
1479 m_tuners.remove( aTuner );
1480 aTuner->Destroy();
1481 m_panelTuners->Layout();
1482 OnModify();
1483}
1484
1485
1486void SIMULATOR_FRAME_UI::AddMeasurement( const wxString& aCmd )
1487{
1488 // -1 because the last one is for user input
1489 for( int i = 0; i < m_measurementsGrid->GetNumberRows(); i++ )
1490 {
1491 if ( m_measurementsGrid->GetCellValue( i, COL_MEASUREMENT ) == aCmd )
1492 return; // Don't create duplicates
1493 }
1494
1495 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1496
1497 if( !plotTab )
1498 return;
1499
1500 wxString simType = simulator()->TypeToName( plotTab->GetSimType(), true );
1501 int row;
1502
1503 for( row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
1504 {
1505 if( m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1506 break;
1507 }
1508
1509 if( !m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1510 {
1511 m_measurementsGrid->AppendRows( 1 );
1512 row = m_measurementsGrid->GetNumberRows() - 1;
1513 }
1514
1515 m_measurementsGrid->SetCellValue( row, COL_MEASUREMENT, aCmd );
1516 SetMeasureFormat( row, { 2, wxS( "~V" ) } );
1517
1518 UpdateMeasurement( row );
1519 OnModify();
1520
1521 // Always leave at least one empty row for type-in:
1522 row = m_measurementsGrid->GetNumberRows() - 1;
1523
1524 if( !m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1525 m_measurementsGrid->AppendRows( 1 );
1526}
1527
1528
1529void SIMULATOR_FRAME_UI::DoFourier( const wxString& aSignal, const wxString& aFundamental )
1530{
1531 wxString cmd = wxString::Format( wxS( "fourier %s %s" ),
1532 SPICE_VALUE( aFundamental ).ToSpiceString(),
1533 aSignal );
1534
1535 simulator()->Command( cmd.ToStdString() );
1536}
1537
1538
1540{
1541 return circuitModel().get();
1542}
1543
1544
1545void SIMULATOR_FRAME_UI::AddTrace( const wxString& aName, SIM_TRACE_TYPE aType )
1546{
1547 if( !GetCurrentSimTab() )
1548 {
1549 m_simConsole->AppendText( _( "Error: no current simulation.\n" ) );
1550 m_simConsole->SetInsertionPointEnd();
1551 return;
1552 }
1553
1554 SIM_TYPE simType = SPICE_CIRCUIT_MODEL::CommandToSimType( GetCurrentSimTab()->GetSimCommand() );
1555
1556 if( simType == ST_UNKNOWN )
1557 {
1558 m_simConsole->AppendText( _( "Error: simulation type not defined.\n" ) );
1559 m_simConsole->SetInsertionPointEnd();
1560 return;
1561 }
1562 else if( !SIM_TAB::IsPlottable( simType ) )
1563 {
1564 m_simConsole->AppendText( _( "Error: simulation type doesn't support plotting.\n" ) );
1565 m_simConsole->SetInsertionPointEnd();
1566 return;
1567 }
1568
1569 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1570 wxCHECK( plotTab, /* void */ );
1571
1572 if( simType == ST_AC )
1573 {
1574 updateTrace( aName, aType | SPT_AC_GAIN, plotTab );
1575 updateTrace( aName, aType | SPT_AC_PHASE, plotTab );
1576 }
1577 else if( simType == ST_SP )
1578 {
1579 updateTrace( aName, aType | SPT_AC_GAIN, plotTab );
1580 updateTrace( aName, aType | SPT_AC_PHASE, plotTab );
1581 }
1582 else
1583 {
1584 updateTrace( aName, aType, plotTab );
1585 }
1586
1587 plotTab->GetPlotWin()->UpdateAll();
1588
1590 OnModify();
1591}
1592
1593
1594void SIMULATOR_FRAME_UI::SetUserDefinedSignals( const std::map<int, wxString>& aNewSignals )
1595{
1596 for( size_t ii = 0; ii < m_plotNotebook->GetPageCount(); ++ii )
1597 {
1598 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( m_plotNotebook->GetPage( ii ) );
1599
1600 if( !plotTab )
1601 continue;
1602
1603 for( const auto& [ id, existingSignal ] : m_userDefinedSignals )
1604 {
1605 int traceType = SPT_UNKNOWN;
1606 wxString vectorName = vectorNameFromSignalName( plotTab, existingSignal, &traceType );
1607
1608 if( aNewSignals.count( id ) == 0 )
1609 {
1610 if( plotTab->GetSimType() == ST_AC )
1611 {
1612 for( int subType : { SPT_AC_GAIN, SPT_AC_PHASE } )
1613 plotTab->DeleteTrace( vectorName, traceType | subType );
1614 }
1615 else if( plotTab->GetSimType() == ST_SP )
1616 {
1617 for( int subType : { SPT_SP_AMP, SPT_AC_PHASE } )
1618 plotTab->DeleteTrace( vectorName, traceType | subType );
1619 }
1620 else
1621 {
1622 plotTab->DeleteTrace( vectorName, traceType );
1623 }
1624 }
1625 else
1626 {
1627 if( plotTab->GetSimType() == ST_AC )
1628 {
1629 for( int subType : { SPT_AC_GAIN, SPT_AC_PHASE } )
1630 {
1631 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType | subType ) )
1632 trace->SetName( aNewSignals.at( id ) );
1633 }
1634 }
1635 else if( plotTab->GetSimType() == ST_SP )
1636 {
1637 for( int subType : { SPT_SP_AMP, SPT_AC_PHASE } )
1638 {
1639 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType | subType ) )
1640 trace->SetName( aNewSignals.at( id ) );
1641 }
1642 }
1643 else
1644 {
1645 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType ) )
1646 trace->SetName( aNewSignals.at( id ) );
1647 }
1648 }
1649 }
1650 }
1651
1652 m_userDefinedSignals = aNewSignals;
1653
1656
1658 rebuildSignalsGrid( m_filter->GetValue() );
1661 OnModify();
1662}
1663
1664
1665void SIMULATOR_FRAME_UI::updateTrace( const wxString& aVectorName, int aTraceType,
1666 SIM_PLOT_TAB* aPlotTab, std::vector<double>* aDataX,
1667 bool aClearData )
1668{
1670
1671 aTraceType &= aTraceType & SPT_Y_AXIS_MASK;
1672 aTraceType |= getXAxisType( simType );
1673
1674 wxString simVectorName = aVectorName;
1675
1676 if( aTraceType & SPT_POWER )
1677 simVectorName = simVectorName.AfterFirst( '(' ).BeforeLast( ')' ) + wxS( ":power" );
1678
1679 if( !SIM_TAB::IsPlottable( simType ) )
1680 {
1681 // There is no plot to be shown
1682 simulator()->Command( wxString::Format( wxT( "print %s" ), aVectorName ).ToStdString() );
1683
1684 return;
1685 }
1686
1687 std::vector<double> data_x;
1688 std::vector<double> data_y;
1689
1690 if( !aDataX || aClearData )
1691 aDataX = &data_x;
1692
1693 // First, handle the x axis
1694 if( aDataX->empty() && !aClearData )
1695 {
1696 wxString xAxisName( simulator()->GetXAxis( simType ) );
1697
1698 if( xAxisName.IsEmpty() )
1699 return;
1700
1701 *aDataX = simulator()->GetGainVector( (const char*) xAxisName.c_str() );
1702 }
1703
1704 unsigned int size = aDataX->size();
1705
1706 switch( simType )
1707 {
1708 case ST_AC:
1709 if( aTraceType & SPT_AC_GAIN )
1710 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), size );
1711 else if( aTraceType & SPT_AC_PHASE )
1712 data_y = simulator()->GetPhaseVector( (const char*) simVectorName.c_str(), size );
1713 else
1714 wxFAIL_MSG( wxT( "Plot type missing AC_PHASE or AC_MAG bit" ) );
1715
1716 break;
1717 case ST_SP:
1718 if( aTraceType & SPT_SP_AMP )
1719 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), size );
1720 else if( aTraceType & SPT_AC_PHASE )
1721 data_y = simulator()->GetPhaseVector( (const char*) simVectorName.c_str(), size );
1722 else
1723 wxFAIL_MSG( wxT( "Plot type missing AC_PHASE or SPT_SP_AMP bit" ) );
1724
1725 break;
1726
1727 case ST_DC:
1728 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), -1 );
1729 break;
1730
1731 case ST_NOISE:
1732 case ST_TRAN:
1733 case ST_FFT:
1734 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), size );
1735 break;
1736
1737 default:
1738 wxFAIL_MSG( wxT( "Unhandled plot type" ) );
1739 }
1740
1741 // If we did a two-source DC analysis, we need to split the resulting vector and add traces
1742 // for each input step
1743 SPICE_DC_PARAMS source1, source2;
1744
1745 if( simType == ST_DC
1746 && circuitModel()->ParseDCCommand( aPlotTab->GetSimCommand(), &source1, &source2 )
1747 && !source2.m_source.IsEmpty() )
1748 {
1749 // Source 1 is the inner loop, so lets add traces for each Source 2 (outer loop) step
1750 SPICE_VALUE v = source2.m_vstart;
1751
1752 size_t offset = 0;
1753 size_t outer = ( size_t )( ( source2.m_vend - v ) / source2.m_vincrement ).ToDouble();
1754 size_t inner = aDataX->size() / ( outer + 1 );
1755
1756 wxASSERT( aDataX->size() % ( outer + 1 ) == 0 );
1757
1758 for( size_t idx = 0; idx <= outer; idx++ )
1759 {
1760 if( TRACE* trace = aPlotTab->GetOrAddTrace( aVectorName, aTraceType ) )
1761 {
1762 if( data_y.size() >= size )
1763 {
1764 std::vector<double> sub_x( aDataX->begin() + offset,
1765 aDataX->begin() + offset + inner );
1766 std::vector<double> sub_y( data_y.begin() + offset,
1767 data_y.begin() + offset + inner );
1768
1769 aPlotTab->SetTraceData( trace, sub_x, sub_y );
1770 }
1771 }
1772
1773 v = v + source2.m_vincrement;
1774 offset += inner;
1775 }
1776 }
1777 else if( TRACE* trace = aPlotTab->GetOrAddTrace( aVectorName, aTraceType ) )
1778 {
1779 if( data_y.size() >= size )
1780 aPlotTab->SetTraceData( trace, *aDataX, data_y );
1781 }
1782}
1783
1784
1786{
1787 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1788
1789 for( int row = 0; row < m_signalsGrid->GetNumberRows(); ++row )
1790 {
1791 wxString signalName = m_signalsGrid->GetCellValue( row, COL_SIGNAL_NAME );
1792 int traceType = SPT_UNKNOWN;
1793 wxString vectorName = vectorNameFromSignalName( plotTab, signalName, &traceType );
1794
1795 if( TRACE* trace = plotTab ? plotTab->GetTrace( vectorName, traceType ) : nullptr )
1796 {
1797 m_signalsGrid->SetCellValue( row, COL_SIGNAL_SHOW, wxS( "1" ) );
1798
1799 wxGridCellAttr* attr = new wxGridCellAttr;
1800 attr->SetRenderer( new GRID_CELL_COLOR_RENDERER( this ) );
1801 attr->SetEditor( new GRID_CELL_COLOR_SELECTOR( this, m_signalsGrid ) );
1802 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
1803 m_signalsGrid->SetAttr( row, COL_SIGNAL_COLOR, attr );
1804
1805 KIGFX::COLOR4D color( trace->GetPen().GetColour() );
1806 m_signalsGrid->SetCellValue( row, COL_SIGNAL_COLOR, color.ToCSSString() );
1807
1808 attr = new wxGridCellAttr;
1809 attr->SetRenderer( new wxGridCellBoolRenderer() );
1810 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
1811 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
1812 m_signalsGrid->SetAttr( row, COL_CURSOR_1, attr );
1813
1814 attr = new wxGridCellAttr;
1815 attr->SetRenderer( new wxGridCellBoolRenderer() );
1816 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
1817 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
1818 m_signalsGrid->SetAttr( row, COL_CURSOR_2, attr );
1819
1820 if( trace->HasCursor( 1 ) )
1821 m_signalsGrid->SetCellValue( row, COL_CURSOR_1, wxS( "1" ) );
1822 else
1823 m_signalsGrid->SetCellValue( row, COL_CURSOR_1, wxEmptyString );
1824
1825 if( trace->HasCursor( 2 ) )
1826 m_signalsGrid->SetCellValue( row, COL_CURSOR_2, wxS( "1" ) );
1827 else
1828 m_signalsGrid->SetCellValue( row, COL_CURSOR_2, wxEmptyString );
1829 }
1830 else
1831 {
1832 m_signalsGrid->SetCellValue( row, COL_SIGNAL_SHOW, wxEmptyString );
1833
1834 wxGridCellAttr* attr = new wxGridCellAttr;
1835 attr->SetReadOnly();
1836 m_signalsGrid->SetAttr( row, COL_SIGNAL_COLOR, attr );
1837 m_signalsGrid->SetCellValue( row, COL_SIGNAL_COLOR, wxEmptyString );
1838
1839 attr = new wxGridCellAttr;
1840 attr->SetReadOnly();
1841 m_signalsGrid->SetAttr( row, COL_CURSOR_1, attr );
1842 m_signalsGrid->SetCellValue( row, COL_CURSOR_1, wxEmptyString );
1843
1844 attr = new wxGridCellAttr;
1845 attr->SetReadOnly();
1846 m_signalsGrid->SetAttr( row, COL_CURSOR_2, attr );
1847 m_signalsGrid->SetCellValue( row, COL_CURSOR_2, wxEmptyString );
1848 }
1849 }
1850}
1851
1852
1854{
1855 auto quoteNetNames =
1856 [&]( wxString aExpression ) -> wxString
1857 {
1858 for( const auto& [netname, quotedNetname] : m_quotedNetnames )
1859 aExpression.Replace( netname, quotedNetname );
1860
1861 return aExpression;
1862 };
1863
1864 for( const auto& [ id, signal ] : m_userDefinedSignals )
1865 {
1866 constexpr const char* cmd = "let user{} = {}";
1867
1868 simulator()->Command( "echo " + fmt::format( cmd, id, signal.ToStdString() ) );
1869 simulator()->Command( fmt::format( cmd, id, quoteNetNames( signal ).ToStdString() ) );
1870 }
1871}
1872
1873
1875{
1876 wxString errors;
1877 WX_STRING_REPORTER reporter( &errors );
1878
1879 for( const TUNER_SLIDER* tuner : m_tuners )
1880 {
1881 SCH_SHEET_PATH sheetPath;
1882 wxString ref = tuner->GetSymbolRef();
1883 KIID symbolId = tuner->GetSymbol( &sheetPath );
1884 SCH_ITEM* schItem = sheetPath.GetItem( symbolId );
1885 SCH_SYMBOL* symbol = dynamic_cast<SCH_SYMBOL*>( schItem );
1886
1887 if( !symbol )
1888 {
1889 reporter.Report( wxString::Format( _( "%s not found" ), ref ) );
1890 continue;
1891 }
1892
1893 const SPICE_ITEM* item = GetExporter()->FindItem( tuner->GetSymbolRef().ToStdString() );
1894
1895 if( !item || !item->model->GetTunerParam() )
1896 {
1897 reporter.Report( wxString::Format( _( "%s is not tunable" ), ref ) );
1898 continue;
1899 }
1900
1901 double floatVal = tuner->GetValue().ToDouble();
1902
1903 simulator()->Command( item->model->SpiceGenerator().TunerCommand( *item, floatVal ) );
1904 }
1905
1906 if( reporter.HasMessage() )
1907 DisplayErrorMessage( this, _( "Could not apply tuned value(s):" ) + wxS( "\n" ) + errors );
1908}
1909
1910
1911bool SIMULATOR_FRAME_UI::LoadWorkbook( const wxString& aPath )
1912{
1913 wxTextFile file( aPath );
1914
1915 if( !file.Open() )
1916 return false;
1917
1918 wxString firstLine = file.GetFirstLine();
1919 long dummy;
1920 bool legacy = firstLine.StartsWith( wxT( "version " ) ) || firstLine.ToLong( &dummy );
1921
1922 file.Close();
1923
1924 m_plotNotebook->DeleteAllPages();
1925 m_userDefinedSignals.clear();
1926
1927 if( legacy )
1928 {
1929 if( !loadLegacyWorkbook( aPath ) )
1930 return false;
1931 }
1932 else
1933 {
1934 if( !loadJsonWorkbook( aPath ) )
1935 return false;
1936 }
1937
1939
1940 rebuildSignalsGrid( m_filter->GetValue() );
1944
1945 wxFileName filename( aPath );
1946 filename.MakeRelativeTo( m_schematicFrame->Prj().GetProjectPath() );
1947
1948 // Remember the loaded workbook filename.
1949 simulator()->Settings()->SetWorkbookFilename( filename.GetFullPath() );
1950
1951 return true;
1952}
1953
1954
1955bool SIMULATOR_FRAME_UI::loadJsonWorkbook( const wxString& aPath )
1956{
1957 wxFFileInputStream fp( aPath, wxT( "rt" ) );
1958 wxStdInputStream fstream( fp );
1959
1960 if( !fp.IsOk() )
1961 return false;
1962
1963 try
1964 {
1965 nlohmann::json js = nlohmann::json::parse( fstream, nullptr, true, true );
1966
1967 std::map<SIM_PLOT_TAB*, nlohmann::json> traceInfo;
1968
1969 for( const nlohmann::json& tab_js : js[ "tabs" ] )
1970 {
1971 wxString simCommand;
1974
1975 for( const nlohmann::json& cmd : tab_js[ "commands" ] )
1976 {
1977 if( cmd == ".kicad adjustpaths" )
1979 else if( cmd == ".save all" )
1981 else if( cmd == ".probe alli" )
1983 else if( cmd == ".probe allp" )
1985 else if( cmd == ".kicad esavenone" )
1986 simOptions &= ~NETLIST_EXPORTER_SPICE::OPTION_SAVE_ALL_EVENTS;
1987 else
1988 simCommand += wxString( cmd.get<wxString>() ).Trim();
1989 }
1990
1991 SIM_TAB* simTab = NewSimTab( simCommand );
1992 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( simTab );
1993
1994 simTab->SetSimOptions( simOptions );
1995
1996 if( plotTab )
1997 {
1998 if( tab_js.contains( "traces" ) )
1999 traceInfo[plotTab] = tab_js[ "traces" ];
2000
2001 if( tab_js.contains( "measurements" ) )
2002 {
2003 for( const nlohmann::json& m_js : tab_js[ "measurements" ] )
2004 plotTab->Measurements().emplace_back( m_js[ "expr" ], m_js[ "format" ] );
2005 }
2006
2007 plotTab->SetDottedSecondary( tab_js[ "dottedSecondary" ] );
2008 plotTab->ShowGrid( tab_js[ "showGrid" ] );
2009
2010 if( tab_js.contains( "fixedY1scale" ) )
2011 {
2012 const nlohmann::json& scale_js = tab_js[ "fixedY1scale" ];
2013 plotTab->SetY1Scale( true, scale_js[ "min" ], scale_js[ "max" ] );
2014 plotTab->GetPlotWin()->LockY( true );
2015 }
2016
2017 if( tab_js.contains( "fixedY2scale" ) )
2018 {
2019 const nlohmann::json& scale_js = tab_js[ "fixedY2scale" ];
2020 plotTab->SetY2Scale( true, scale_js[ "min" ], scale_js[ "max" ] );
2021 plotTab->GetPlotWin()->LockY( true );
2022 }
2023
2024 if( tab_js.contains( "fixedY3scale" ) )
2025 {
2026 plotTab->EnsureThirdYAxisExists();
2027 const nlohmann::json& scale_js = tab_js[ "fixedY3scale" ];
2028 plotTab->SetY3Scale( true, scale_js[ "min" ], scale_js[ "max" ] );
2029 plotTab->GetPlotWin()->LockY( true );
2030 }
2031
2032 if( tab_js.contains( "legend" ) )
2033 {
2034 const nlohmann::json& legend_js = tab_js[ "legend" ];
2035 plotTab->SetLegendPosition( wxPoint( legend_js[ "x" ], legend_js[ "y" ] ) );
2036 plotTab->ShowLegend( true );
2037 }
2038
2039 if( tab_js.contains( "margins" ) )
2040 {
2041 const nlohmann::json& margins_js = tab_js[ "margins" ];
2042 plotTab->GetPlotWin()->SetMargins( margins_js[ "top" ],
2043 margins_js[ "right" ],
2044 margins_js[ "bottom" ],
2045 margins_js[ "left" ] );
2046 }
2047 }
2048 }
2049
2050 int ii = 0;
2051
2052 if( js.contains( "user_defined_signals" ) )
2053 {
2054 for( const nlohmann::json& signal_js : js[ "user_defined_signals" ] )
2055 m_userDefinedSignals[ii++] = wxString( signal_js.get<wxString>() );
2056 }
2057
2058 auto addCursor =
2059 [this]( SIM_PLOT_TAB* aPlotTab, TRACE* aTrace, const wxString& aSignalName,
2060 int aCursorId, const nlohmann::json& aCursor_js )
2061 {
2062 if( aCursorId == 1 || aCursorId == 2 )
2063 {
2064 CURSOR* cursor = new CURSOR( aTrace, aPlotTab );
2065
2066 cursor->SetName( aSignalName );
2067 cursor->SetPen( wxPen( aTrace->GetTraceColour() ) );
2068 cursor->SetCoordX( aCursor_js[ "position" ] );
2069
2070 aTrace->SetCursor( aCursorId, cursor );
2071 aPlotTab->GetPlotWin()->AddLayer( cursor );
2072 }
2073
2074 m_cursorFormats[aCursorId-1][0].FromString( aCursor_js[ "x_format" ] );
2075 m_cursorFormats[aCursorId-1][1].FromString( aCursor_js[ "y_format" ] );
2076 };
2077
2078 for( const auto& [ plotTab, traces_js ] : traceInfo )
2079 {
2080 for( const nlohmann::json& trace_js : traces_js )
2081 {
2082 wxString signalName = trace_js[ "signal" ];
2083 wxString vectorName = vectorNameFromSignalName( plotTab, signalName, nullptr );
2084 TRACE* trace = plotTab->GetOrAddTrace( vectorName, trace_js[ "trace_type" ] );
2085
2086 if( trace )
2087 {
2088 if( trace_js.contains( "cursor1" ) )
2089 addCursor( plotTab, trace, signalName, 1, trace_js[ "cursor1" ] );
2090
2091 if( trace_js.contains( "cursor2" ) )
2092 addCursor( plotTab, trace, signalName, 2, trace_js[ "cursor2" ] );
2093
2094 if( trace_js.contains( "cursorD" ) )
2095 addCursor( plotTab, trace, signalName, 3, trace_js[ "cursorD" ] );
2096
2097 if( trace_js.contains( "color" ) )
2098 {
2099 wxColour color;
2100 color.Set( wxString( trace_js["color"].get<wxString>() ) );
2101 trace->SetTraceColour( color );
2102 plotTab->UpdateTraceStyle( trace );
2103 }
2104 }
2105 }
2106
2107 plotTab->UpdatePlotColors();
2108 }
2109
2110 if( SIM_TAB* simTab = GetCurrentSimTab() )
2111 {
2112 m_simulatorFrame->LoadSimulator( simTab->GetSimCommand(), simTab->GetSimOptions() );
2113
2114 simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( 0 ) );
2115
2116 wxCHECK( simTab, false );
2117
2118 simTab->SetLastSchTextSimCommand( js[ "last_sch_text_sim_command" ] );
2119 }
2120 }
2121 catch( nlohmann::json::parse_error& error )
2122 {
2123 wxLogTrace( traceSettings, wxT( "Json parse error reading %s: %s" ), aPath, error.what() );
2124
2125 return false;
2126 }
2127
2128 return true;
2129}
2130
2131
2132bool SIMULATOR_FRAME_UI::SaveWorkbook( const wxString& aPath )
2133{
2135
2136 wxFileName filename = aPath;
2137 filename.SetExt( FILEEXT::WorkbookFileExtension );
2138
2139 wxFile file;
2140
2141 file.Create( filename.GetFullPath(), true /* overwrite */ );
2142
2143 if( !file.IsOpened() )
2144 return false;
2145
2146 nlohmann::json tabs_js = nlohmann::json::array();
2147
2148 for( size_t i = 0; i < m_plotNotebook->GetPageCount(); i++ )
2149 {
2150 SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( i ) );
2151
2152 if( !simTab )
2153 continue;
2154
2155 SIM_TYPE simType = simTab->GetSimType();
2156
2157 nlohmann::json commands_js = nlohmann::json::array();
2158
2159 commands_js.push_back( simTab->GetSimCommand() );
2160
2161 int options = simTab->GetSimOptions();
2162
2164 commands_js.push_back( ".kicad adjustpaths" );
2165
2167 commands_js.push_back( ".save all" );
2168
2170 commands_js.push_back( ".probe alli" );
2171
2173 commands_js.push_back( ".probe allp" );
2174
2176 commands_js.push_back( ".kicad esavenone" );
2177
2178 nlohmann::json tab_js = nlohmann::json(
2179 { { "analysis", SPICE_SIMULATOR::TypeToName( simType, true ) },
2180 { "commands", commands_js } } );
2181
2182 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( simTab ) )
2183 {
2184 nlohmann::json traces_js = nlohmann::json::array();
2185
2186 auto findSignalName =
2187 [&]( const wxString& aVectorName ) -> wxString
2188 {
2189 for( const auto& [ id, signal ] : m_userDefinedSignals )
2190 {
2191 if( aVectorName == vectorNameFromSignalId( id ) )
2192 return signal;
2193 }
2194
2195 return aVectorName;
2196 };
2197
2198 for( const auto& [name, trace] : plotTab->GetTraces() )
2199 {
2200 nlohmann::json trace_js = nlohmann::json(
2201 { { "trace_type", (int) trace->GetType() },
2202 { "signal", findSignalName( trace->GetName() ) },
2203 { "color", COLOR4D( trace->GetTraceColour() ).ToCSSString() } } );
2204
2205 if( CURSOR* cursor = trace->GetCursor( 1 ) )
2206 {
2207 trace_js["cursor1"] = nlohmann::json(
2208 { { "position", cursor->GetCoords().x },
2209 { "x_format", m_cursorFormats[0][0].ToString() },
2210 { "y_format", m_cursorFormats[0][1].ToString() } } );
2211 }
2212
2213 if( CURSOR* cursor = trace->GetCursor( 2 ) )
2214 {
2215 trace_js["cursor2"] = nlohmann::json(
2216 { { "position", cursor->GetCoords().x },
2217 { "x_format", m_cursorFormats[1][0].ToString() },
2218 { "y_format", m_cursorFormats[1][1].ToString() } } );
2219 }
2220
2221 if( trace->GetCursor( 1 ) || trace->GetCursor( 2 ) )
2222 {
2223 trace_js["cursorD"] = nlohmann::json(
2224 { { "x_format", m_cursorFormats[2][0].ToString() },
2225 { "y_format", m_cursorFormats[2][1].ToString() } } );
2226 }
2227
2228 traces_js.push_back( trace_js );
2229 }
2230
2231 nlohmann::json measurements_js = nlohmann::json::array();
2232
2233 for( const auto& [ measurement, format ] : plotTab->Measurements() )
2234 {
2235 measurements_js.push_back( nlohmann::json( { { "expr", measurement },
2236 { "format", format } } ) );
2237 }
2238
2239 tab_js[ "traces" ] = traces_js;
2240 tab_js[ "measurements" ] = measurements_js;
2241 tab_js[ "dottedSecondary" ] = plotTab->GetDottedSecondary();
2242 tab_js[ "showGrid" ] = plotTab->IsGridShown();
2243
2244 double min, max;
2245
2246 if( plotTab->GetY1Scale( &min, &max ) )
2247 tab_js[ "fixedY1scale" ] = nlohmann::json( { { "min", min }, { "max", max } } );
2248
2249 if( plotTab->GetY2Scale( &min, &max ) )
2250 tab_js[ "fixedY2scale" ] = nlohmann::json( { { "min", min }, { "max", max } } );
2251
2252 if( plotTab->GetY3Scale( &min, &max ) )
2253 tab_js[ "fixedY3scale" ] = nlohmann::json( { { "min", min }, { "max", max } } );
2254
2255 if( plotTab->IsLegendShown() )
2256 {
2257 tab_js[ "legend" ] = nlohmann::json( { { "x", plotTab->GetLegendPosition().x },
2258 { "y", plotTab->GetLegendPosition().y } } );
2259 }
2260
2261 mpWindow* plotWin = plotTab->GetPlotWin();
2262
2263 tab_js[ "margins" ] = nlohmann::json( { { "left", plotWin->GetMarginLeft() },
2264 { "right", plotWin->GetMarginRight() },
2265 { "top", plotWin->GetMarginTop() },
2266 { "bottom", plotWin->GetMarginBottom() } } );
2267 }
2268
2269 tabs_js.push_back( tab_js );
2270 }
2271
2272 nlohmann::json userDefinedSignals_js = nlohmann::json::array();
2273
2274 for( const auto& [ id, signal ] : m_userDefinedSignals )
2275 userDefinedSignals_js.push_back( signal );
2276
2277 nlohmann::json js = nlohmann::json( { { "version", 6 },
2278 { "tabs", tabs_js },
2279 { "user_defined_signals", userDefinedSignals_js } } );
2280
2281 // Store the value of any simulation command found on the schematic sheet in a SCH_TEXT
2282 // object. If this changes we want to warn the user and ask them if they want to update
2283 // the corresponding panel's sim command.
2284 if( m_plotNotebook->GetPageCount() > 0 )
2285 {
2286 SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( 0 ) );
2287 js[ "last_sch_text_sim_command" ] = simTab->GetLastSchTextSimCommand();
2288 }
2289
2290 std::stringstream buffer;
2291 buffer << std::setw( 2 ) << js << std::endl;
2292
2293 bool res = file.Write( buffer.str() );
2294 file.Close();
2295
2296 // Store the filename of the last saved workbook.
2297 if( res )
2298 {
2299 filename.MakeRelativeTo( m_schematicFrame->Prj().GetProjectPath() );
2300 simulator()->Settings()->SetWorkbookFilename( filename.GetFullPath() );
2301 }
2302
2303 return res;
2304}
2305
2306
2308{
2309 switch( aType )
2310 {
2312 case ST_AC: return SPT_LIN_FREQUENCY;
2313 case ST_SP: return SPT_LIN_FREQUENCY;
2314 case ST_FFT: return SPT_LIN_FREQUENCY;
2315 case ST_DC: return SPT_SWEEP;
2316 case ST_TRAN: return SPT_TIME;
2317 case ST_NOISE: return SPT_LIN_FREQUENCY;
2318 default: wxFAIL_MSG( wxS( "Unhandled simulation type" ) ); return SPT_UNKNOWN;
2319 }
2320}
2321
2322
2324{
2325 wxString output;
2326 wxString ref;
2327 wxString source;
2328 wxString scale;
2329 SPICE_VALUE pts;
2330 SPICE_VALUE fStart;
2331 SPICE_VALUE fStop;
2332 bool saveAll;
2333
2334 if( GetCurrentSimTab() )
2335 {
2336 circuitModel()->ParseNoiseCommand( GetCurrentSimTab()->GetSimCommand(), &output, &ref,
2337 &source, &scale, &pts, &fStart, &fStop, &saveAll );
2338 }
2339
2340 return source;
2341}
2342
2343
2345{
2347
2348 // Rebuild the color list to plot traces
2350
2351 // Now send changes to all SIM_PLOT_TAB
2352 for( size_t page = 0; page < m_plotNotebook->GetPageCount(); page++ )
2353 {
2354 wxWindow* curPage = m_plotNotebook->GetPage( page );
2355
2356 // ensure it is truly a plot plotTab and not the (zero plots) placeholder
2357 // which is only SIM_TAB
2358 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( curPage );
2359
2360 if( plotTab )
2361 plotTab->UpdatePlotColors();
2362 }
2363}
2364
2365
2366void SIMULATOR_FRAME_UI::onPlotClose( wxAuiNotebookEvent& event )
2367{
2368 OnModify();
2369}
2370
2371
2372void SIMULATOR_FRAME_UI::onPlotClosed( wxAuiNotebookEvent& event )
2373{
2374 CallAfter( [this]()
2375 {
2377 rebuildSignalsGrid( m_filter->GetValue() );
2379
2380 SIM_TAB* panel = GetCurrentSimTab();
2381
2382 if( !panel || panel->GetSimType() != ST_OP )
2383 {
2384 SCHEMATIC& schematic = m_schematicFrame->Schematic();
2385 schematic.ClearOperatingPoints();
2388 }
2389 } );
2390}
2391
2392
2394{
2395 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
2396 {
2397 std::vector<std::pair<wxString, wxString>>& measurements = plotTab->Measurements();
2398
2399 measurements.clear();
2400
2401 for( int row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
2402 {
2403 if( !m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
2404 {
2405 measurements.emplace_back( m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ),
2406 m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT_FORMAT ) );
2407 }
2408 }
2409 }
2410}
2411
2412
2413void SIMULATOR_FRAME_UI::onPlotChanging( wxAuiNotebookEvent& event )
2414{
2416
2417 event.Skip();
2418}
2419
2420
2422{
2424 rebuildSignalsGrid( m_filter->GetValue() );
2426
2428
2429 for( int row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
2430 UpdateMeasurement( row );
2431}
2432
2433
2434void SIMULATOR_FRAME_UI::onPlotChanged( wxAuiNotebookEvent& event )
2435{
2436 if( SIM_TAB* simTab = GetCurrentSimTab() )
2437 simulator()->Command( "setplot " + simTab->GetSpicePlotName().ToStdString() );
2438
2440
2441 event.Skip();
2442}
2443
2444
2446{
2448
2449 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
2450 {
2451 for( const auto& [ measurement, format ] : plotTab->Measurements() )
2452 {
2453 int row = m_measurementsGrid->GetNumberRows();
2454 m_measurementsGrid->AppendRows();
2455 m_measurementsGrid->SetCellValue( row, COL_MEASUREMENT, measurement );
2456 m_measurementsGrid->SetCellValue( row, COL_MEASUREMENT_FORMAT, format );
2457 }
2458
2459 if( plotTab->GetSimType() == ST_TRAN || plotTab->GetSimType() == ST_AC
2460 || plotTab->GetSimType() == ST_DC || plotTab->GetSimType() == ST_SP )
2461 {
2462 m_measurementsGrid->AppendRows(); // Empty row at end
2463 }
2464 }
2465}
2466
2467
2468void SIMULATOR_FRAME_UI::onPlotDragged( wxAuiNotebookEvent& event )
2469{
2470}
2471
2472
2473std::shared_ptr<SPICE_SIMULATOR> SIMULATOR_FRAME_UI::simulator() const
2474{
2476}
2477
2478
2479std::shared_ptr<SPICE_CIRCUIT_MODEL> SIMULATOR_FRAME_UI::circuitModel() const
2480{
2482}
2483
2484
2486{
2487 SUPPRESS_GRID_CELL_EVENTS raii( this );
2488
2490
2491 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
2492
2493 if( !plotTab )
2494 return;
2495
2496 // Update cursor values
2497 CURSOR* cursor1 = nullptr;
2498 wxString cursor1Name;
2499 wxString cursor1Units;
2500 CURSOR* cursor2 = nullptr;
2501 wxString cursor2Name;
2502 wxString cursor2Units;
2503
2504 auto getUnitsY =
2505 [&]( TRACE* aTrace ) -> wxString
2506 {
2507 if( ( aTrace->GetType() & SPT_AC_PHASE ) || ( aTrace->GetType() & SPT_CURRENT ) )
2508 return plotTab->GetUnitsY2();
2509 else if( aTrace->GetType() & SPT_POWER )
2510 return plotTab->GetUnitsY3();
2511 else
2512 return plotTab->GetUnitsY1();
2513 };
2514
2515 auto getNameY =
2516 [&]( TRACE* aTrace ) -> wxString
2517 {
2518 if( ( aTrace->GetType() & SPT_AC_PHASE ) || ( aTrace->GetType() & SPT_CURRENT ) )
2519 return plotTab->GetLabelY2();
2520 else if( aTrace->GetType() & SPT_POWER )
2521 return plotTab->GetLabelY3();
2522 else
2523 return plotTab->GetLabelY1();
2524 };
2525
2526 auto formatValue =
2527 [this]( double aValue, int aCursorId, int aCol ) -> wxString
2528 {
2529 if( ( !m_simulatorFrame->SimFinished() && aCol == 1 ) || std::isnan( aValue ) )
2530 return wxS( "--" );
2531 else
2532 return SPICE_VALUE( aValue ).ToString( m_cursorFormats[ aCursorId ][ aCol ] );
2533 };
2534
2535 for( const auto& [name, trace] : plotTab->GetTraces() )
2536 {
2537 if( CURSOR* cursor = trace->GetCursor( 1 ) )
2538 {
2539 cursor1 = cursor;
2540 cursor1Name = getNameY( trace );
2541 cursor1Units = getUnitsY( trace );
2542
2543 wxRealPoint coords = cursor->GetCoords();
2544 int row = m_cursorsGrid->GetNumberRows();
2545
2546 m_cursorFormats[0][0].UpdateUnits( plotTab->GetUnitsX() );
2547 m_cursorFormats[0][1].UpdateUnits( cursor1Units );
2548
2549 m_cursorsGrid->AppendRows( 1 );
2550 m_cursorsGrid->SetCellValue( row, COL_CURSOR_NAME, wxS( "1" ) );
2551 m_cursorsGrid->SetCellValue( row, COL_CURSOR_SIGNAL, cursor->GetName() );
2552 m_cursorsGrid->SetCellValue( row, COL_CURSOR_X, formatValue( coords.x, 0, 0 ) );
2553 m_cursorsGrid->SetCellValue( row, COL_CURSOR_Y, formatValue( coords.y, 0, 1 ) );
2554 break;
2555 }
2556 }
2557
2558 for( const auto& [name, trace] : plotTab->GetTraces() )
2559 {
2560 if( CURSOR* cursor = trace->GetCursor( 2 ) )
2561 {
2562 cursor2 = cursor;
2563 cursor2Name = getNameY( trace );
2564 cursor2Units = getUnitsY( trace );
2565
2566 wxRealPoint coords = cursor->GetCoords();
2567 int row = m_cursorsGrid->GetNumberRows();
2568
2569 m_cursorFormats[1][0].UpdateUnits( plotTab->GetUnitsX() );
2570 m_cursorFormats[1][1].UpdateUnits( cursor2Units );
2571
2572 m_cursorsGrid->AppendRows( 1 );
2573 m_cursorsGrid->SetCellValue( row, COL_CURSOR_NAME, wxS( "2" ) );
2574 m_cursorsGrid->SetCellValue( row, COL_CURSOR_SIGNAL, cursor->GetName() );
2575 m_cursorsGrid->SetCellValue( row, COL_CURSOR_X, formatValue( coords.x, 1, 0 ) );
2576 m_cursorsGrid->SetCellValue( row, COL_CURSOR_Y, formatValue( coords.y, 1, 1 ) );
2577 break;
2578 }
2579 }
2580
2581 if( cursor1 && cursor2 && cursor1Units == cursor2Units )
2582 {
2583 wxRealPoint coords = cursor2->GetCoords() - cursor1->GetCoords();
2584 wxString signal;
2585
2586 m_cursorFormats[2][0].UpdateUnits( plotTab->GetUnitsX() );
2587 m_cursorFormats[2][1].UpdateUnits( cursor1Units );
2588
2589 if( cursor1->GetName() == cursor2->GetName() )
2590 signal = wxString::Format( wxS( "%s[2 - 1]" ), cursor2->GetName() );
2591 else
2592 signal = wxString::Format( wxS( "%s - %s" ), cursor2->GetName(), cursor1->GetName() );
2593
2594 m_cursorsGrid->AppendRows( 1 );
2595 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_NAME, _( "Diff" ) );
2596 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_SIGNAL, signal );
2597 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_X, formatValue( coords.x, 2, 0 ) );
2598 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_Y, formatValue( coords.y, 2, 1 ) );
2599 }
2600
2601 // Set up the labels
2602 m_cursorsGrid->SetColLabelValue( COL_CURSOR_X, plotTab->GetLabelX() );
2603
2604 wxString valColName = _( "Value" );
2605
2606 if( !cursor1Name.IsEmpty() )
2607 {
2608 if( cursor2Name.IsEmpty() || cursor1Name == cursor2Name )
2609 valColName = cursor1Name;
2610 }
2611 else if( !cursor2Name.IsEmpty() )
2612 {
2613 valColName = cursor2Name;
2614 }
2615
2616 m_cursorsGrid->SetColLabelValue( COL_CURSOR_Y, valColName );
2617}
2618
2619
2620void SIMULATOR_FRAME_UI::onPlotCursorUpdate( wxCommandEvent& aEvent )
2621{
2623 OnModify();
2624}
2625
2626
2628{
2629 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
2630 plotTab->ResetScales( true );
2631
2632 m_simConsole->Clear();
2633
2634 // Do not export netlist, it is already stored in the simulator
2635 applyTuners();
2636
2637 m_refreshTimer.Start( REFRESH_INTERVAL, wxTIMER_ONE_SHOT );
2638}
2639
2640
2641void SIMULATOR_FRAME_UI::OnSimReport( const wxString& aMsg )
2642{
2643 m_simConsole->AppendText( aMsg + "\n" );
2644 m_simConsole->SetInsertionPointEnd();
2645}
2646
2647
2648std::vector<wxString> SIMULATOR_FRAME_UI::SimPlotVectors() const
2649{
2650 std::vector<wxString> signals;
2651
2652 for( const std::string& vec : simulator()->AllVectors() )
2653 signals.emplace_back( vec );
2654
2655 return signals;
2656}
2657
2658
2659std::vector<wxString> SIMULATOR_FRAME_UI::Signals() const
2660{
2661 std::vector<wxString> signals;
2662
2663 for( const wxString& signal : m_signals )
2664 signals.emplace_back( signal );
2665
2666 for( const auto& [ id, signal ] : m_userDefinedSignals )
2667 signals.emplace_back( signal );
2668
2669 sortSignals( signals );
2670
2671 return signals;
2672}
2673
2674
2676{
2677 if( aFinal )
2678 m_refreshTimer.Stop();
2679
2680 SIM_TAB* simTab = GetCurrentSimTab();
2681
2682 if( !simTab )
2683 return;
2684
2685 SIM_TYPE simType = simTab->GetSimType();
2686 wxString msg;
2687
2688 if( aFinal )
2690
2691 // If there are any signals plotted, update them
2692 if( SIM_TAB::IsPlottable( simType ) )
2693 {
2694 simTab->SetSpicePlotName( simulator()->CurrentPlotName() );
2695
2696 if( simType == ST_NOISE && aFinal )
2697 {
2698 m_simConsole->AppendText( _( "\n\nSimulation results:\n\n" ) );
2699 m_simConsole->SetInsertionPointEnd();
2700
2701 // The simulator will create noise1 & noise2 on the first run, noise3 and noise4
2702 // on the second, etc. The first plot for each run contains the spectral density
2703 // noise vectors and second contains the integrated noise.
2704 long number;
2705 simulator()->CurrentPlotName().Mid( 5 ).ToLong( &number );
2706
2707 for( const std::string& vec : simulator()->AllVectors() )
2708 {
2709 std::vector<double> val_list = simulator()->GetRealVector( vec, 1 );
2710 wxString value = SPICE_VALUE( val_list[ 0 ] ).ToSpiceString();
2711
2712 msg.Printf( wxS( "%s: %sV\n" ), vec, value );
2713
2714 m_simConsole->AppendText( msg );
2715 m_simConsole->SetInsertionPointEnd();
2716 }
2717
2718 simulator()->Command( fmt::format( "setplot noise{}", number - 1 ) );
2719 simTab->SetSpicePlotName( simulator()->CurrentPlotName() );
2720 }
2721
2722 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( simTab );
2723 wxCHECK_RET( plotTab, wxT( "not a SIM_PLOT_TAB" ) );
2724
2725 struct TRACE_INFO
2726 {
2727 wxString Vector;
2728 int TraceType;
2729 bool ClearData;
2730 };
2731
2732 std::map<TRACE*, TRACE_INFO> traceMap;
2733
2734 for( const auto& [ name, trace ] : plotTab->GetTraces() )
2735 traceMap[ trace ] = { wxEmptyString, SPT_UNKNOWN, false };
2736
2737 // NB: m_signals are already broken out into gain/phase, but m_userDefinedSignals are
2738 // as the user typed them
2739
2740 for( const wxString& signal : m_signals )
2741 {
2742 int traceType = SPT_UNKNOWN;
2743 wxString vectorName = vectorNameFromSignalName( plotTab, signal, &traceType );
2744
2745 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType ) )
2746 traceMap[ trace ] = { vectorName, traceType, false };
2747 }
2748
2749 for( const auto& [ id, signal ] : m_userDefinedSignals )
2750 {
2751 int traceType = SPT_UNKNOWN;
2752 wxString vectorName = vectorNameFromSignalName( plotTab, signal, &traceType );
2753
2754 if( simType == ST_AC )
2755 {
2756 int baseType = traceType &= ~( SPT_AC_GAIN | SPT_AC_PHASE );
2757
2758 for( int subType : { baseType | SPT_AC_GAIN, baseType | SPT_AC_PHASE } )
2759 {
2760 if( TRACE* trace = plotTab->GetTrace( vectorName, subType ) )
2761 traceMap[ trace ] = { vectorName, subType, !aFinal };
2762 }
2763 }
2764 else if( simType == ST_SP )
2765 {
2766 int baseType = traceType &= ~( SPT_SP_AMP | SPT_AC_PHASE );
2767
2768 for( int subType : { baseType | SPT_SP_AMP, baseType | SPT_AC_PHASE } )
2769 {
2770 if( TRACE* trace = plotTab->GetTrace( vectorName, subType ) )
2771 traceMap[trace] = { vectorName, subType, !aFinal };
2772 }
2773 }
2774 else
2775 {
2776 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType ) )
2777 traceMap[ trace ] = { vectorName, traceType, !aFinal };
2778 }
2779 }
2780
2781 // Two passes so that DC-sweep sub-traces get deleted and re-created:
2782
2783 for( const auto& [ trace, traceInfo ] : traceMap )
2784 {
2785 if( traceInfo.Vector.IsEmpty() )
2786 plotTab->DeleteTrace( trace );
2787 }
2788
2789 for( const auto& [ trace, info ] : traceMap )
2790 {
2791 std::vector<double> data_x;
2792
2793 if( !info.Vector.IsEmpty() )
2794 updateTrace( info.Vector, info.TraceType, plotTab, &data_x, info.ClearData );
2795 }
2796
2797 plotTab->GetPlotWin()->UpdateAll();
2798
2799 if( aFinal )
2800 {
2801 for( int row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
2802 UpdateMeasurement( row );
2803
2804 plotTab->ResetScales( true );
2805 }
2806
2807 plotTab->GetPlotWin()->Fit();
2808
2810 }
2811 else if( simType == ST_OP && aFinal )
2812 {
2813 m_simConsole->AppendText( _( "\n\nSimulation results:\n\n" ) );
2814 m_simConsole->SetInsertionPointEnd();
2815
2816 for( const std::string& vec : simulator()->AllVectors() )
2817 {
2818 std::vector<double> val_list = simulator()->GetRealVector( vec, 1 );
2819
2820 if( val_list.empty() )
2821 continue;
2822
2823 wxString value = SPICE_VALUE( val_list[ 0 ] ).ToSpiceString();
2824 wxString signal;
2825 SIM_TRACE_TYPE type = circuitModel()->VectorToSignal( vec, signal );
2826
2827 const size_t tab = 25; //characters
2828 size_t padding = ( signal.length() < tab ) ? ( tab - signal.length() ) : 1;
2829
2830 switch( type )
2831 {
2832 case SPT_VOLTAGE: value.Append( wxS( "V" ) ); break;
2833 case SPT_CURRENT: value.Append( wxS( "A" ) ); break;
2834 case SPT_POWER: value.Append( wxS( "W" ) ); break;
2835 default: value.Append( wxS( "?" ) ); break;
2836 }
2837
2838 msg.Printf( wxT( "%s%s\n" ),
2839 ( signal + wxT( ":" ) ).Pad( padding, wxUniChar( ' ' ) ),
2840 value );
2841
2842 m_simConsole->AppendText( msg );
2843 m_simConsole->SetInsertionPointEnd();
2844
2845 if( type == SPT_VOLTAGE || type == SPT_CURRENT || type == SPT_POWER )
2846 signal = signal.SubString( 2, signal.Length() - 2 );
2847
2848 if( type == SPT_POWER )
2849 signal += wxS( ":power" );
2850
2851 m_schematicFrame->Schematic().SetOperatingPoint( signal, val_list.at( 0 ) );
2852 }
2853 }
2854 else if( simType == ST_PZ && aFinal )
2855 {
2856 m_simConsole->AppendText( _( "\n\nSimulation results:\n\n" ) );
2857 m_simConsole->SetInsertionPointEnd();
2858 simulator()->Command( "print all" );
2859 }
2860}
2861
2862
2864{
2866}
int color
Definition: DXF_plotter.cpp:58
const char * name
Definition: DXF_plotter.cpp:57
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.
Definition: sim_plot_tab.h:64
const wxRealPoint & GetCoords() const
Definition: sim_plot_tab.h:100
void SetCoordX(double aValue)
bool Find(const wxString &aTerm, int &aMatchersTriggered, int &aPosition)
virtual void Refresh(bool aEraseBackground=true, const wxRect *aRect=nullptr) override
Add mouse and command handling (such as cut, copy, and paste) to a WX_GRID instance.
Definition: grid_tricks.h:61
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.
Definition: grid_tricks.h:125
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
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
Hold a translatable error message and may be used when throwing exceptions containing a translated er...
Definition: ki_exception.h:46
const wxString What() const
Definition: ki_exception.h:58
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)
const SPICE_ITEM * FindItem(const std::string &aRefName) const
Find and return the item corresponding to aRefName.
A singleton reporter that reports to nowhere.
Definition: reporter.h:223
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition: project.cpp:135
Holds all the data relating to one schematic.
Definition: schematic.h:75
void SetOperatingPoint(const wxString &aSignal, double aValue)
Set operating points from a .op simulation.
Definition: schematic.h:232
void ClearOperatingPoints()
Clear operating points from a .op simulation.
Definition: schematic.h:224
SCH_DRAW_PANEL * GetCanvas() const override
Return a pointer to GAL-based canvas of given EDA draw frame.
EESCHEMA_SETTINGS * eeconfig() const
Schematic editor (Eeschema) main window.
void RefreshOperatingPointDisplay()
Refresh the display of any operaintg points.
void OnModify() override
Must be called after a schematic change in order to set the "modify" flag and update other data struc...
SCHEMATIC & Schematic() const
void UpdateItem(EDA_ITEM *aItem, bool isAddOrDelete=false, bool aUpdateRtree=false) override
Mark an item for refresh.
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition: sch_item.h:174
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
SCH_ITEM * GetItem(const KIID &aID) const
Fetch a SCH_ITEM by ID.
Schematic symbol object.
Definition: sch_symbol.h:105
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly)
Populate a std::vector with SCH_FIELDs.
Definition: sch_symbol.cpp:959
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
Definition: sch_symbol.cpp:712
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)
Class SIMULATOR_FRAME_UI_BASE.
wxSplitterWindow * m_splitterLeftRight
wxSplitterWindow * m_splitterMeasurements
wxSplitterWindow * m_splitterCursors
wxSplitterWindow * m_splitterPlotAndConsole
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 onPlotChanged(wxAuiNotebookEvent &event) override
void rebuildSignalsGrid(wxString aFilter)
Rebuild the filtered list of signals in the signals grid.
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 applyUserDefinedSignals()
Apply user-defined signals to the SPICE session.
std::map< wxString, wxString > m_quotedNetnames
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).
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.
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 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 SetCursorFormat(int aCursorId, int aValueCol, const SPICE_VALUE_FORMAT &aFormat)
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 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.
SPICE_VALUE_FORMAT GetCursorFormat(int aCursorId, int aValueCol) const
Get/Set the number of significant digits and the range for formatting a cursor value.
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.
bool LoadSimulator(const wxString &aSimCommand, unsigned aSimOptions)
Check and load the current netlist into the simulator.
std::shared_ptr< SPICE_CIRCUIT_MODEL > GetCircuitModel() const
SIM_TYPE GetCurrentSimType() const
void OnModify() override
Must be called after a model change in order to set the "modify" flag and do other frame-specific pro...
bool SimFinished() const
int GetCurrentOptions() const
std::shared_ptr< SPICE_SIMULATOR > GetSimulator() const
SIM_MODEL & CreateModel(SIM_MODEL::TYPE aType, const std::vector< SCH_PIN * > &aPins, REPORTER &aReporter)
virtual const PARAM * GetTunerParam() const
Definition: sim_model.h:484
const SPICE_GENERATOR & SpiceGenerator() const
Definition: sim_model.h:435
void WriteFields(std::vector< SCH_FIELD > &aFields) const
Definition: sim_model.cpp:441
void SetParamValue(int aParamIndex, const std::string &aValue, SIM_VALUE::NOTATION aNotation=SIM_VALUE::NOTATION::SI)
Definition: sim_model.cpp:849
static void FillDefaultColorList(bool aWhiteBg)
Fills m_colorList by a default set of colors.
bool DeleteTrace(const wxString &aVectorName, int aTraceType)
void EnableCursor(const wxString &aVectorName, int aType, int aCursorId, bool aEnable, const wxString &aSignalName)
Reset scale ranges to fit the current traces.
wxString GetLabelY1() const
Definition: sim_plot_tab.h:208
mpWindow * GetPlotWin() const
Definition: sim_plot_tab.h:350
void ShowGrid(bool aEnable)
Definition: sim_plot_tab.h:268
wxString GetUnitsY2() const
void SetTraceData(TRACE *aTrace, std::vector< double > &aX, std::vector< double > &aY)
void SetY2Scale(bool aLock, double aMin, double aMax)
TRACE * GetTrace(const wxString &aVecName, int aType) const
Definition: sim_plot_tab.h:261
wxString GetLabelX() const
Definition: sim_plot_tab.h:203
const std::map< wxString, TRACE * > & GetTraces() const
Definition: sim_plot_tab.h:256
wxString GetLabelY3() const
Definition: sim_plot_tab.h:218
void SetY1Scale(bool aLock, double aMin, double aMax)
void SetY3Scale(bool aLock, double aMin, double aMax)
std::vector< std::pair< wxString, wxString > > & Measurements()
Definition: sim_plot_tab.h:359
void UpdateTraceStyle(TRACE *trace)
Update plot colors.
void SetLegendPosition(const wxPoint &aPosition)
Definition: sim_plot_tab.h:309
void ResetScales(bool aIncludeX)
Update trace line style.
void UpdatePlotColors()
void ShowLegend(bool aEnable)
Definition: sim_plot_tab.h:293
wxString GetLabelY2() const
Definition: sim_plot_tab.h:213
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.
Definition: sim_plot_tab.h:319
void ApplyPreferences(const SIM_PREFERENCES &aPrefs) override
Definition: sim_plot_tab.h:198
wxString GetUnitsY1() const
wxString GetUnitsY3() const
int GetSimOptions() const
Definition: sim_tab.h:55
virtual void OnLanguageChanged()=0
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)
Definition: sim_value.h:84
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.
virtual std::string TunerCommand(const SPICE_ITEM &aItem, double aValue) const
static wxString TypeToName(SIM_TYPE aType, bool aShortName)
Return a string with simulation name based on enum.
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)
SIMULATOR_FRAME_UI * m_frame
void SetTraceColour(const wxColour &aColour)
Definition: sim_plot_tab.h:181
Custom widget to handle quick component values modification and simulation on the fly.
Definition: tuner_slider.h:44
void ClearRows()
wxWidgets recently added an ASSERT which fires if the position is greater than or equal to the number...
Definition: wx_grid.h:165
A wrapper for reporting to a wxString object.
Definition: reporter.h:164
bool HasMessage() const override
Returns true if the reporter client is non-empty.
Definition: reporter.cpp:71
REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED) override
Report a string with a given severity.
Definition: reporter.cpp:61
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:906
int GetMarginLeft() const
Definition: mathplot.h:1217
void SetMargins(int top, int right, int bottom, int left)
Set window margins, creating a blank area where some kinds of layers cannot draw.
Definition: mathplot.cpp:2383
int GetMarginTop() const
Definition: mathplot.h:1211
void UpdateAll()
Refresh display.
Definition: mathplot.cpp:2284
int GetMarginRight() const
Definition: mathplot.h:1213
int GetMarginBottom() const
Definition: mathplot.h:1215
void LockY(bool aLock)
Definition: mathplot.h:1261
bool AddLayer(mpLayer *layer, bool refreshDisplay=true)
Add a plot layer to the canvas.
Definition: mathplot.cpp:1968
void Fit() override
Set view to fit global bounding box of all plot layers and refresh display.
Definition: mathplot.cpp:1612
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:186
This file is part of the common library.
#define _(s)
Abstract pattern-matching tool and implementations.
@ CTX_SIGNAL
@ GRIDTRICKS_ID_COPY
Definition: grid_tricks.h:43
@ GRIDTRICKS_FIRST_CLIENT_ID
Definition: grid_tricks.h:48
static const std::string WorkbookFileExtension
#define traceSettings
Definition: json_settings.h:52
KICOMMON_API wxFont GetStatusFont(wxWindow *aWindow)
Definition: ui_common.cpp:130
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
SIM_TRACE_TYPE operator|(SIM_TRACE_TYPE aFirst, SIM_TRACE_TYPE aSecond)
#define REFRESH_INTERVAL
@ MYID_MEASURE_INTEGRAL
@ MYID_MEASURE_MAX_AT
@ MYID_MEASURE_AVG
@ MYID_MEASURE_MAX
@ MYID_FOURIER
@ MYID_FORMAT_VALUE
@ MYID_MEASURE_RMS
@ MYID_DELETE_MEASUREMENT
@ MYID_MEASURE_MIN
@ MYID_MEASURE_MIN_AT
@ MYID_MEASURE_PP
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.
SPICE_VALUE m_vincrement
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
Definition: spice_value.cpp:49
void UpdateUnits(const wxString &aUnits)
Definition: spice_value.cpp:55
void FromString(const wxString &aString)
Definition: spice_value.cpp:40
VECTOR3I res
Definition of file extensions used in Kicad.