KiCad PCB EDA Suite
Loading...
Searching...
No Matches
simulator_frame_ui.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2016-2023 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 * @author Tomasz Wlostowski <[email protected]>
7 * @author Maciej Suminski <[email protected]>
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 3
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23#include <algorithm>
24#include <memory>
25#include <type_traits>
26
27#include <wx/event.h>
28#include <wx/settings.h>
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#include <wx/tokenzr.h>
36
38#include <sch_edit_frame.h>
39#include <confirm.h>
45#include <bitmaps.h>
46#include <widgets/wx_grid.h>
47#include <grid_tricks.h>
48#include <eda_pattern_match.h>
49#include <string_utils.h>
50#include <pgm_base.h>
52#include <sim/simulator_frame.h>
53#include <sim/sim_plot_tab.h>
54#include <sim/spice_simulator.h>
57#include <eeschema_settings.h>
58#include <advanced_config.h>
59#include <magic_enum.hpp>
60#include <widgets/wx_infobar.h>
61
62
64{
65 int res = static_cast<int>( aFirst ) | static_cast<int>( aSecond );
66
67 return static_cast<SIM_TRACE_TYPE>( res );
68}
69
70
80
81
99
100
102
103
104static bool smithColumnsShown( const WX_GRID* aGrid )
105{
106 return aGrid->GetNumberCols() > COL_CURSOR_SMITH_FIRST;
107}
108
109
116
117
118enum
119{
129
132};
133
134
136{
137public:
139 GRID_TRICKS( aGrid ),
140 m_parent( aParent ),
141 m_menuRow( 0 ),
142 m_menuCol( 0 )
143 {
144 }
145
146protected:
147 void showPopupMenu( wxMenu& menu, wxGridEvent& aEvent ) override;
148 void doPopupSelection( wxCommandEvent& event ) override;
149
150protected:
154};
155
156
157void SIGNALS_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
158{
159 SIM_TAB* panel = m_parent->GetCurrentSimTab();
160
161 if( !panel )
162 return;
163
164 m_menuRow = aEvent.GetRow();
165 m_menuCol = aEvent.GetCol();
166
168 {
169 if( !( m_grid->IsInSelection( m_menuRow, m_menuCol ) ) )
170 m_grid->ClearSelection();
171
172 m_grid->SetGridCursor( m_menuRow, m_menuCol );
173
174 if( panel->GetSimType() == ST_TRAN || panel->GetSimType() == ST_AC || panel->GetSimType() == ST_DC
175 || panel->GetSimType() == ST_SP )
176 {
177 menu.Append( MYID_MEASURE_MIN, _( "Measure Min" ) );
178 menu.Append( MYID_MEASURE_MAX, _( "Measure Max" ) );
179 menu.Append( MYID_MEASURE_AVG, _( "Measure Average" ) );
180 menu.Append( MYID_MEASURE_RMS, _( "Measure RMS" ) );
181 menu.Append( MYID_MEASURE_PP, _( "Measure Peak-to-peak" ) );
182
183 if( panel->GetSimType() == ST_AC || panel->GetSimType() == ST_SP )
184 {
185 menu.Append( MYID_MEASURE_MIN_AT, _( "Measure Frequency of Min" ) );
186 menu.Append( MYID_MEASURE_MAX_AT, _( "Measure Frequency of Max" ) );
187 }
188 else
189 {
190 menu.Append( MYID_MEASURE_MIN_AT, _( "Measure Time of Min" ) );
191 menu.Append( MYID_MEASURE_MAX_AT, _( "Measure Time of Max" ) );
192 }
193
194 menu.Append( MYID_MEASURE_INTEGRAL, _( "Measure Integral" ) );
195
196 if( panel->GetSimType() == ST_TRAN )
197 {
198 menu.AppendSeparator();
199 menu.Append( MYID_FOURIER, _( "Perform Fourier Analysis..." ) );
200 }
201
202 menu.AppendSeparator();
203 menu.Append( GRIDTRICKS_ID_COPY, _( "Copy Signal Name" ) + "\tCtrl+C" );
204
205 menu.AppendSeparator();
206 menu.Append( GRIDTRICKS_ID_SELECT, _( "Create new cursor..." ) );
207
208 m_grid->PopupMenu( &menu );
209 }
210 }
211 else if( m_menuCol > static_cast<int>( COL_CURSOR_2 ) )
212 {
213 menu.Append( GRIDTRICKS_ID_SELECT, _( "Create new cursor..." ) );
214
215 menu.AppendSeparator();
216
217 wxString msg = m_grid->GetColLabelValue( m_grid->GetNumberCols() - 1 );
218
219 menu.AppendSeparator();
220 menu.Append( GRIDTRICKS_ID_DELETE, wxString::Format( _( "Delete %s..." ), msg ) );
221
222 m_grid->PopupMenu( &menu );
223 }
224 else
225 {
226 menu.Append( GRIDTRICKS_ID_SELECT, _( "Create new cursor..." ) );
227
228 m_grid->PopupMenu( &menu );
229 }
230}
231
232
233void SIGNALS_GRID_TRICKS::doPopupSelection( wxCommandEvent& event )
234{
235 std::vector<wxString> signals;
236
237 wxGridCellCoordsArray cells1 = m_grid->GetSelectionBlockTopLeft();
238 wxGridCellCoordsArray cells2 = m_grid->GetSelectionBlockBottomRight();
239
240 for( size_t i = 0; i < cells1.Count(); i++ )
241 {
242 if( cells1[i].GetCol() == COL_SIGNAL_NAME )
243 {
244 for( int j = cells1[i].GetRow(); j < cells2[i].GetRow() + 1; j++ )
245 {
246 signals.push_back( m_grid->GetCellValue( j, cells1[i].GetCol() ) );
247 }
248 }
249 }
250
251 wxGridCellCoordsArray cells3 = m_grid->GetSelectedCells();
252
253 for( size_t i = 0; i < cells3.Count(); i++ )
254 {
255 if( cells3[i].GetCol() == COL_SIGNAL_NAME )
256 signals.push_back( m_grid->GetCellValue( cells3[i].GetRow(), cells3[i].GetCol() ) );
257 }
258
259 if( signals.size() < 1 )
260 signals.push_back( m_grid->GetCellValue( m_menuRow, m_menuCol ) );
261
262 auto addMeasurement =
263 [this]( const wxString& cmd, wxString signal )
264 {
265 if( signal.EndsWith( _( " (phase)" ) ) )
266 return;
267
268 if( signal.EndsWith( _( " (gain)" ) ) || signal.EndsWith( _( " (amplitude)" ) ) )
269 {
270 signal = signal.Left( signal.length() - 7 );
271
272 if( signal.Upper().StartsWith( wxS( "V(" ) ) )
273 signal = wxS( "vdb" ) + signal.Mid( 1 );
274 }
275
276 m_parent->AddMeasurement( cmd + wxS( " " ) + signal );
277 };
278
279 if( event.GetId() == MYID_MEASURE_MIN )
280 {
281 for( const wxString& signal : signals )
282 addMeasurement( wxS( "MIN" ), signal );
283 }
284 else if( event.GetId() == MYID_MEASURE_MAX )
285 {
286 for( const wxString& signal : signals )
287 addMeasurement( wxS( "MAX" ), signal );
288 }
289 else if( event.GetId() == MYID_MEASURE_AVG )
290 {
291 for( const wxString& signal : signals )
292 addMeasurement( wxS( "AVG" ), signal );
293 }
294 else if( event.GetId() == MYID_MEASURE_RMS )
295 {
296 for( const wxString& signal : signals )
297 addMeasurement( wxS( "RMS" ), signal );
298 }
299 else if( event.GetId() == MYID_MEASURE_PP )
300 {
301 for( const wxString& signal : signals )
302 addMeasurement( wxS( "PP" ), signal );
303 }
304 else if( event.GetId() == MYID_MEASURE_MIN_AT )
305 {
306 for( const wxString& signal : signals )
307 addMeasurement( wxS( "MIN_AT" ), signal );
308 }
309 else if( event.GetId() == MYID_MEASURE_MAX_AT )
310 {
311 for( const wxString& signal : signals )
312 addMeasurement( wxS( "MAX_AT" ), signal );
313 }
314 else if( event.GetId() == MYID_MEASURE_INTEGRAL )
315 {
316 for( const wxString& signal : signals )
317 addMeasurement( wxS( "INTEG" ), signal );
318 }
319 else if( event.GetId() == MYID_FOURIER )
320 {
321 wxString title;
322 wxString fundamental = wxT( "1K" );
323
324 if( signals.size() == 1 )
325 title.Printf( _( "Fourier Analysis of %s" ), signals[0] );
326 else
327 title = _( "Fourier Analyses of Multiple Signals" );
328
329 WX_TEXT_ENTRY_DIALOG dlg( m_parent, _( "Fundamental frequency:" ), title, fundamental );
330
331 if( dlg.ShowModal() != wxID_OK )
332 return;
333
334 if( !dlg.GetValue().IsEmpty() )
335 fundamental = dlg.GetValue();
336
337 for( const wxString& signal : signals )
338 m_parent->DoFourier( signal, fundamental );
339 }
340 else if( event.GetId() == GRIDTRICKS_ID_COPY )
341 {
342 wxLogNull doNotLog; // disable logging of failed clipboard actions
343 wxString txt;
344
345 for( const wxString& signal : signals )
346 {
347 if( !txt.IsEmpty() )
348 txt += '\r';
349
350 txt += signal;
351 }
352
353 if( wxTheClipboard->Open() )
354 {
355 wxTheClipboard->SetData( new wxTextDataObject( txt ) );
356 wxTheClipboard->Flush(); // Allow data to be available after closing KiCad
357 wxTheClipboard->Close();
358 }
359 }
360 else if( event.GetId() == GRIDTRICKS_ID_SELECT )
361 {
362 m_parent->CreateNewCursor();
363 }
364 else if( event.GetId() == GRIDTRICKS_ID_DELETE )
365 {
366 m_parent->DeleteCursor();
367 }
368}
369
370
372{
373public:
375 GRID_TRICKS( aGrid ),
376 m_parent( aParent ),
377 m_menuRow( 0 ),
378 m_menuCol( 0 )
379 {
380 }
381
382protected:
383 void showPopupMenu( wxMenu& menu, wxGridEvent& aEvent ) override;
384 void doPopupSelection( wxCommandEvent& event ) override;
385
386protected:
390};
391
392
393void CURSORS_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
394{
395 m_menuRow = aEvent.GetRow();
396 m_menuCol = aEvent.GetCol();
397
399 {
400 wxString msg = m_grid->GetColLabelValue( m_menuCol );
401
402 menu.Append( MYID_FORMAT_VALUE, wxString::Format( _( "Format %s..." ), msg ) );
403 menu.AppendSeparator();
404 }
405
406 GRID_TRICKS::showPopupMenu( menu, aEvent );
407}
408
409
410void CURSORS_GRID_TRICKS::doPopupSelection( wxCommandEvent& event )
411{
412 auto getSignalName =
413 [this]( int row ) -> wxString
414 {
415 wxString signal = m_grid->GetCellValue( row, COL_CURSOR_SIGNAL );
416
417 if( signal.EndsWith( "[2 - 1]" ) )
418 signal = signal.Left( signal.length() - 7 );
419
420 return signal;
421 };
422
423 if( event.GetId() == MYID_FORMAT_VALUE )
424 {
425 int axis = m_menuCol - COL_CURSOR_X;
426 SPICE_VALUE_FORMAT format = m_parent->GetCursorFormat( m_menuRow, axis );
427 DIALOG_SIM_FORMAT_VALUE formatDialog( m_parent, &format );
428
429 if( formatDialog.ShowModal() == wxID_OK )
430 {
431 for( int row = 0; row < m_grid->GetNumberRows(); ++row )
432 {
433 if( getSignalName( row ) == getSignalName( m_menuRow ) )
434 m_parent->SetCursorFormat( row, axis, format );
435 }
436 }
437 }
438 else
439 {
441 }
442}
443
444
446{
447public:
449 GRID_TRICKS( aGrid ),
450 m_parent( aParent ),
451 m_menuRow( 0 ),
452 m_menuCol( 0 )
453 {
454 }
455
456protected:
457 void showPopupMenu( wxMenu& menu, wxGridEvent& aEvent ) override;
458 void doPopupSelection( wxCommandEvent& event ) override;
459
460protected:
464};
465
466
467void MEASUREMENTS_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
468{
469 m_menuRow = aEvent.GetRow();
470 m_menuCol = aEvent.GetCol();
471
472 if( !( m_grid->IsInSelection( m_menuRow, m_menuCol ) ) )
473 m_grid->ClearSelection();
474
475 m_grid->SetGridCursor( m_menuRow, m_menuCol );
476
478 menu.Append( MYID_FORMAT_VALUE, _( "Format Value..." ) );
479
480 if( m_menuRow < ( m_grid->GetNumberRows() - 1 ) )
481 menu.Append( MYID_DELETE_MEASUREMENT, _( "Delete Measurement" ) );
482
483 menu.AppendSeparator();
484
485 GRID_TRICKS::showPopupMenu( menu, aEvent );
486}
487
488
490{
491 if( event.GetId() == MYID_FORMAT_VALUE )
492 {
493 SPICE_VALUE_FORMAT format = m_parent->GetMeasureFormat( m_menuRow );
494 DIALOG_SIM_FORMAT_VALUE formatDialog( m_parent, &format );
495
496 if( formatDialog.ShowModal() == wxID_OK )
497 {
498 m_parent->SetMeasureFormat( m_menuRow, format );
499 m_parent->UpdateMeasurement( m_menuRow );
500 m_parent->OnModify();
501 }
502 }
503 else if( event.GetId() == MYID_DELETE_MEASUREMENT )
504 {
505 std::vector<int> measurements;
506
507 wxGridCellCoordsArray cells1 = m_grid->GetSelectionBlockTopLeft();
508 wxGridCellCoordsArray cells2 = m_grid->GetSelectionBlockBottomRight();
509
510 for( size_t i = 0; i < cells1.Count(); i++ )
511 {
512 if( cells1[i].GetCol() == COL_MEASUREMENT )
513 {
514 for( int j = cells1[i].GetRow(); j < cells2[i].GetRow() + 1; j++ )
515 measurements.push_back( j );
516 }
517 }
518
519 wxGridCellCoordsArray cells3 = m_grid->GetSelectedCells();
520
521 for( size_t i = 0; i < cells3.Count(); i++ )
522 {
523 if( cells3[i].GetCol() == COL_MEASUREMENT )
524 measurements.push_back( cells3[i].GetRow() );
525 }
526
527 if( measurements.size() < 1 )
528 measurements.push_back( m_menuRow );
529
530 // When deleting a row, we'll change the indexes.
531 // To avoid problems, we can start with the highest indexes.
532 sort( measurements.begin(), measurements.end(), std::greater<>() );
533
534 for( int row : measurements )
535 m_parent->DeleteMeasurement( row );
536
537 m_grid->ClearSelection();
538
539 m_parent->OnModify();
540 }
541 else
542 {
544 }
545}
546
547
549{
550public:
552 m_frame( aFrame )
553 {
554 m_frame->m_SuppressGridEvents++;
555 }
556
558 {
559 m_frame->m_SuppressGridEvents--;
560 }
561
562private:
564};
565
566
567#define ID_SIM_REFRESH 10207
568#define REFRESH_INTERVAL 50 // 20 frames/second.
569
570
572 SIMULATOR_FRAME_UI_BASE( aSimulatorFrame ),
574 m_simulatorFrame( aSimulatorFrame ),
575 m_schematicFrame( aSchematicFrame ),
576 m_darkMode( true ),
577 m_plotNumber( 0 ),
579{
580 // Get the previous size and position of windows:
581 LoadSettings( m_schematicFrame->eeconfig() );
582
583 m_filter->SetHint( _( "Filter" ) );
584
585 Bind( EVT_SIM_VIEWS_CHANGED,
586 [&]( wxCommandEvent& aEvent )
587 {
588 rebuildSignalsGrid( m_filter->GetValue() );
590 OnModify();
591 } );
592
593 m_signalsGrid->wxGrid::SetLabelFont( KIUI::GetStatusFont( this ) );
594 m_cursorsGrid->wxGrid::SetLabelFont( KIUI::GetStatusFont( this ) );
595 m_measurementsGrid->wxGrid::SetLabelFont( KIUI::GetStatusFont( this ) );
596
597 m_signalsGrid->PushEventHandler( new SIGNALS_GRID_TRICKS( this, m_signalsGrid ) );
598 m_cursorsGrid->PushEventHandler( new CURSORS_GRID_TRICKS( this, m_cursorsGrid ) );
599 m_measurementsGrid->PushEventHandler( new MEASUREMENTS_GRID_TRICKS( this, m_measurementsGrid ) );
600
601 wxGridCellAttr* attr = new wxGridCellAttr;
602 attr->SetReadOnly();
603 m_signalsGrid->SetColAttr( COL_SIGNAL_NAME, attr );
604
605 attr = new wxGridCellAttr;
606 attr->SetReadOnly();
607 m_cursorsGrid->SetColAttr( COL_CURSOR_NAME, attr );
608
609 attr = new wxGridCellAttr;
610 attr->SetReadOnly();
611 m_cursorsGrid->SetColAttr( COL_CURSOR_SIGNAL, attr );
612
613 attr = new wxGridCellAttr;
614 attr->SetReadOnly();
615 m_cursorsGrid->SetColAttr( COL_CURSOR_Y, attr );
616
618
619 attr = new wxGridCellAttr;
620 attr->SetReadOnly();
621 m_measurementsGrid->SetColAttr( COL_MEASUREMENT_VALUE, attr );
622
623 // Prepare the color list to plot traces
625
626 Bind( EVT_SIM_CURSOR_UPDATE, &SIMULATOR_FRAME_UI::onPlotCursorUpdate, this );
627
628 Bind( wxEVT_TIMER,
629 [&]( wxTimerEvent& aEvent )
630 {
631 OnSimRefresh( false );
632
633 if( m_simulatorFrame->GetSimulator()->IsRunning() )
634 m_refreshTimer.Start( REFRESH_INTERVAL, wxTIMER_ONE_SHOT );
635 },
636 m_refreshTimer.GetId() );
637
638#ifndef wxHAS_NATIVE_TABART
639 // Default non-native tab art has ugly gradients we don't want
640 m_plotNotebook->SetArtProvider( new wxAuiSimpleTabArt() );
641#endif
642}
643
644
646{
647 // Delete the GRID_TRICKS.
648 m_signalsGrid->PopEventHandler( true );
649 m_cursorsGrid->PopEventHandler( true );
650 m_measurementsGrid->PopEventHandler( true );
651}
652
653
655{
656 for( auto& m_cursorFormat : m_cursorFormats )
657 {
658 m_cursorFormat[0] = { 3, wxS( "~s" ) };
659 m_cursorFormat[1] = { 3, wxS( "~V" ) };
660 }
661
662 // proper init and transfer/copy m_cursorFormats
663 // we work on m_cursorFormatsDyn from now on.
664 // TODO: rework +- LOC when m_cursorFormatsDyn and m_cursorFormats get merged.
665 m_cursorFormatsDyn.clear();
666 m_cursorFormatsDyn.resize( std::size( m_cursorFormats ) );
667
668 for( size_t index = 0; index < std::size( m_cursorFormats ); index++ )
669 {
670 for( size_t index2 = 0; index2 < std::size( m_cursorFormats[0] ); index2++ )
671 m_cursorFormatsDyn[index].push_back( m_cursorFormats[index][index2] );
672 }
673
674 // Dump string helper, tries to get the current higher cursor name to form the next one.
675 // Based on the column labeling
676 // TODO: "Cursor n" may translate as "n Cursor" in other languages
677 // TBD how to handle; just forbid for now.
678 int nameMax = 0;
679
680 for( int i = 0; i < m_signalsGrid->GetNumberCols(); i++ )
681 {
682 wxString maxCursor = m_signalsGrid->GetColLabelValue( i );
683
684 maxCursor.Replace( _( "Cursor " ), "" );
685
686 int tmpMax = wxAtoi( maxCursor );
687
688 if( nameMax < tmpMax )
689 nameMax = tmpMax;
690 }
691
692 m_customCursorsCnt = nameMax + 1; // Init with a +1 on top of current cursor 2, defaults to 3
693}
694
695
697{
698 std::vector<SPICE_VALUE_FORMAT> tmp;
699 // m_cursorFormatsDyn should be equal with m_cursorFormats on first entry here.
700 m_cursorFormatsDyn.emplace_back( tmp );
701
702 m_cursorFormatsDyn[m_customCursorsCnt].push_back( { 3, wxS( "~s" ) } );
703 m_cursorFormatsDyn[m_customCursorsCnt].push_back( { 3, wxS( "~V" ) } );
704
705 wxString cursor_name = wxString( _( "Cursor " ) ) << m_customCursorsCnt;
706
707 m_signalsGrid->InsertCols( m_signalsGrid->GetNumberCols(), 1, true );
708 m_signalsGrid->SetColLabelValue( m_signalsGrid->GetNumberCols() - 1, cursor_name );
709
710 wxGridCellAttr* attr = new wxGridCellAttr;
711 m_signalsGrid->SetColAttr( COL_CURSOR_2 + m_customCursorsCnt, attr );
712
714
717 OnModify();
718}
719
720
722{
723 int col = m_signalsGrid->GetNumberCols();
724 int rows = m_signalsGrid->GetNumberRows();
725
726 if( col > COL_CURSOR_2 )
727 {
728 // Now we need to find the active cursor and deactivate before removing the column,
729 // Send the dummy event to update the UI
730 for( int i = 0; i < rows; i++ )
731 {
732 if( m_signalsGrid->GetCellValue( i, col - 1 ) == wxS( "1" ) )
733 {
734 m_signalsGrid->SetCellValue( i, col - 1, wxEmptyString );
735 wxGridEvent aDummy( wxID_ANY, wxEVT_GRID_CELL_CHANGED, m_signalsGrid, i, col - 1 );
736 onSignalsGridCellChanged( aDummy );
737 break;
738 }
739 }
740
741 m_signalsGrid->DeleteCols( col - 1, 1, false );
742 m_cursorFormatsDyn.pop_back();
744 m_plotNotebook->Refresh();
747 OnModify();
748 }
749}
750
751
753{
754 for( int ii = 0; ii < static_cast<int>( m_plotNotebook->GetPageCount() ); ++ii )
755 {
756 if( SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( ii ) ) )
757 {
758 simTab->OnLanguageChanged();
759
760 wxString pageTitle( simulator()->TypeToName( simTab->GetSimType(), true ) );
761 pageTitle.Prepend( wxString::Format( _( "Analysis %u - " ), ii + 1 /* 1-based */ ) );
762
763 m_plotNotebook->SetPageText( ii, pageTitle );
764 }
765 }
766
767 m_filter->SetHint( _( "Filter" ) );
768
769 m_signalsGrid->SetColLabelValue( COL_SIGNAL_NAME, _( "Signal" ) );
770 m_signalsGrid->SetColLabelValue( COL_SIGNAL_SHOW, _( "Plot" ) );
771 m_signalsGrid->SetColLabelValue( COL_Y_SCALE, _( "Y Scale" ) );
772 m_signalsGrid->SetColLabelValue( COL_SIGNAL_COLOR, _( "Color" ) );
773 m_signalsGrid->SetColLabelValue( COL_CURSOR_1, _( "Cursor 1" ) );
774 m_signalsGrid->SetColLabelValue( COL_CURSOR_2, _( "Cursor 2" ) );
775
776 m_cursorsGrid->SetColLabelValue( COL_CURSOR_NAME, _( "Cursor" ) );
777 m_cursorsGrid->SetColLabelValue( COL_CURSOR_SIGNAL, _( "Signal" ) );
778 m_cursorsGrid->SetColLabelValue( COL_CURSOR_X, _( "Time" ) );
779 m_cursorsGrid->SetColLabelValue( COL_CURSOR_Y, _( "Value" ) );
782
783 for( TUNER_SLIDER* tuner : m_tuners )
784 tuner->ShowChangedLanguage();
785}
786
787
803
804
806{
808
809 settings.view.plot_panel_width = m_splitterLeftRight->GetSashPosition();
810 settings.view.plot_panel_height = m_splitterPlotAndConsole->GetSashPosition();
811 settings.view.signal_panel_height = m_splitterSignals->GetSashPosition();
812 settings.view.cursors_panel_height = m_splitterCursors->GetSashPosition();
813 settings.view.measurements_panel_height = m_splitterMeasurements->GetSashPosition();
814 settings.view.white_background = !m_darkMode;
815
818
820}
821
822
824{
825 m_preferences = aPrefs;
826
827 for( std::size_t i = 0; i < m_plotNotebook->GetPageCount(); ++i )
828 {
829 if( SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( i ) ) )
830 simTab->ApplyPreferences( aPrefs );
831 }
832}
833
834
836{
837 wxString workbookFilename = simulator()->Settings()->GetWorkbookFilename();
838 bool loadFromSchematic = false;
839
840 if( !workbookFilename.IsEmpty() )
841 {
842 wxFileName filename = workbookFilename;
843 filename.SetPath( m_schematicFrame->Prj().GetProjectPath() );
844
845 if( !filename.FileExists() )
846 {
847 WX_INFOBAR* infobar = m_simulatorFrame->GetInfoBar();
848 wxString msg = wxString::Format( _( "Workbook file '%s' not found. Loading simulation settings from "
849 "schematic." ),
850 filename.GetFullPath() );
851 infobar->ShowMessageFor( msg, 8000, wxICON_WARNING );
852
853 simulator()->Settings()->SetWorkbookFilename( wxEmptyString );
854 loadFromSchematic = true;
855 }
856 else if( !LoadWorkbook( filename.GetFullPath() ) )
857 {
858 simulator()->Settings()->SetWorkbookFilename( wxEmptyString );
859 }
860 }
861 else
862 {
863 loadFromSchematic = true;
864 }
865
866 if( loadFromSchematic && m_simulatorFrame->LoadSimulator( wxEmptyString, 0 ) )
867 {
868 wxString schTextSimCommand = circuitModel()->GetSchTextSimCommand();
869
870 if( !schTextSimCommand.IsEmpty() )
871 {
872 SIM_TAB* simTab = NewSimTab( schTextSimCommand );
874 }
875
877 rebuildSignalsGrid( m_filter->GetValue() );
878 }
879}
880
881
899
900
901void sortSignals( std::vector<wxString>& signals )
902{
903 std::sort( signals.begin(), signals.end(),
904 []( const wxString& lhs, const wxString& rhs )
905 {
906 // Sort voltages first
907 if( lhs.Upper().StartsWith( 'V' ) && !rhs.Upper().StartsWith( 'V' ) )
908 return true;
909 else if( !lhs.Upper().StartsWith( 'V' ) && rhs.Upper().StartsWith( 'V' ) )
910 return false;
911
912 return StrNumCmp( lhs, rhs, CMP_T::IGNORE_CASE ) < 0;
913 } );
914}
915
916
918{
919 SUPPRESS_GRID_CELL_EVENTS raii( this );
920
921 m_signalsGrid->ClearRows();
922
923 SIM_PLOT_TAB* plotPanel = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
924
925 if( !plotPanel )
926 return;
927
928 SIM_TYPE simType = plotPanel->GetSimType();
929 std::vector<wxString> signals;
930
931 if( plotPanel->GetSimType() == ST_FFT )
932 {
933 wxStringTokenizer tokenizer( plotPanel->GetSimCommand(), " \t\r\n", wxTOKEN_STRTOK );
934
935 while( tokenizer.HasMoreTokens() && tokenizer.GetNextToken().Lower() != wxT( "fft" ) )
936 {
937 };
938
939 while( tokenizer.HasMoreTokens() )
940 signals.emplace_back( tokenizer.GetNextToken() );
941 }
942 else
943 {
944 // NB: m_signals are already broken out into gain/phase, but m_userDefinedSignals are
945 // as the user typed them
946
947 for( const wxString& signal : m_signals )
948 signals.push_back( signal );
949
950 for( const auto& [id, signal] : m_userDefinedSignals )
951 {
952 if( simType == ST_AC )
953 {
954 signals.push_back( signal + _( " (gain)" ) );
955 signals.push_back( signal + _( " (phase)" ) );
956 }
957 else if( simType == ST_SP )
958 {
959 if( plotPanel->IsSmithMode() )
960 {
961 signals.push_back( signal );
962 }
963 else
964 {
965 signals.push_back( signal + _( " (amplitude)" ) );
966 signals.push_back( signal + _( " (phase)" ) );
967 }
968 }
969 else
970 {
971 signals.push_back( signal );
972 }
973 }
974
975 sortSignals( signals );
976 }
977
978 if( aFilter.IsEmpty() )
979 aFilter = wxS( "*" );
980
981 EDA_COMBINED_MATCHER matcher( aFilter.Upper(), CTX_SIGNAL );
982 int row = 0;
983
984 for( const wxString& signal : signals )
985 {
986 if( matcher.Find( signal.Upper() ) )
987 {
988 int traceType = SPT_UNKNOWN;
989 wxString vectorName = vectorNameFromSignalName( plotPanel, signal, &traceType );
990 TRACE* trace = plotPanel->GetTrace( vectorName, traceType );
991
992 // A trace can exist but not be plotted on any view (e.g. after its view was removed);
993 // such an orphan is shown the same as a never-plotted signal.
994 bool plotted = trace && trace->GetView();
995
996 m_signalsGrid->AppendRows( 1 );
997 m_signalsGrid->SetCellValue( row, COL_SIGNAL_NAME, signal );
998
999 wxGridCellAttr* attr = new wxGridCellAttr;
1000 attr->SetEditor( new GRID_CELL_COMBOBOX( getViewChoices( plotPanel ) ) );
1001 attr->SetRenderer( new GRID_CELL_COMBOBOX_RENDERER() );
1002 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
1003
1004 if( !plotted )
1005 attr->SetTextColour( *wxLIGHT_GREY );
1006
1007 m_signalsGrid->SetAttr( row, COL_SIGNAL_SHOW, attr );
1008 m_signalsGrid->SetCellValue( row, COL_SIGNAL_SHOW, getViewLabel( plotPanel, trace ? trace->GetView()
1009 : nullptr ) );
1010
1011 if( !plotted )
1012 {
1013 attr = new wxGridCellAttr;
1014 attr->SetReadOnly();
1015 m_signalsGrid->SetAttr( row, COL_Y_SCALE, attr );
1016 m_signalsGrid->SetCellValue( row, COL_Y_SCALE, wxEmptyString );
1017
1018 attr = new wxGridCellAttr;
1019 attr->SetReadOnly();
1020 m_signalsGrid->SetAttr( row, COL_SIGNAL_COLOR, attr );
1021 m_signalsGrid->SetCellValue( row, COL_SIGNAL_COLOR, wxEmptyString );
1022
1023 attr = new wxGridCellAttr;
1024 attr->SetReadOnly();
1025 m_signalsGrid->SetAttr( row, COL_CURSOR_1, attr );
1026
1027 attr = new wxGridCellAttr;
1028 attr->SetReadOnly();
1029 m_signalsGrid->SetAttr( row, COL_CURSOR_2, attr );
1030
1031 if( m_customCursorsCnt > 3 )
1032 {
1033 for( int i = 1; i <= m_customCursorsCnt - 3; i++ )
1034 {
1035 attr = new wxGridCellAttr;
1036 attr->SetReadOnly();
1037 m_signalsGrid->SetAttr( row, COL_CURSOR_2 + i, attr );
1038 }
1039 }
1040 }
1041 else
1042 {
1043 attr = new wxGridCellAttr;
1044 attr->SetEditor( new GRID_CELL_COMBOBOX( getYScaleChoices( plotPanel, trace->GetView() ) ) );
1045 attr->SetRenderer( new GRID_CELL_COMBOBOX_RENDERER() );
1046 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
1047 m_signalsGrid->SetAttr( row, COL_Y_SCALE, attr );
1048 m_signalsGrid->SetCellValue( row, COL_Y_SCALE, getYScaleLabel( plotPanel, trace ) );
1049
1050 attr = new wxGridCellAttr;
1051 attr->SetRenderer( new GRID_CELL_COLOR_RENDERER( this ) );
1052 attr->SetEditor( new GRID_CELL_COLOR_SELECTOR( this, m_signalsGrid ) );
1053 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
1054 m_signalsGrid->SetAttr( row, COL_SIGNAL_COLOR, attr );
1055 KIGFX::COLOR4D color( trace->GetPen().GetColour() );
1056 m_signalsGrid->SetCellValue( row, COL_SIGNAL_COLOR, color.ToCSSString() );
1057
1058 attr = new wxGridCellAttr;
1059 attr->SetRenderer( new wxGridCellBoolRenderer() );
1060 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
1061 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
1062 m_signalsGrid->SetAttr( row, COL_CURSOR_1, attr );
1063 m_signalsGrid->SetCellValue( row, COL_CURSOR_1, trace->GetCursor( 1 ) ? "1" : "0" );
1064
1065 attr = new wxGridCellAttr;
1066 attr->SetRenderer( new wxGridCellBoolRenderer() );
1067 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
1068 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
1069 m_signalsGrid->SetAttr( row, COL_CURSOR_2, attr );
1070 m_signalsGrid->SetCellValue( row, COL_CURSOR_2, trace->GetCursor( 2 ) ? "1" : "0" );
1071
1072 if( m_customCursorsCnt > 3 )
1073 {
1074 for( int i = 1; i <= m_customCursorsCnt - 3; i++ )
1075 {
1076 attr = new wxGridCellAttr;
1077 attr->SetRenderer( new wxGridCellBoolRenderer() );
1078 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
1079 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
1080 m_signalsGrid->SetAttr( row, COL_CURSOR_2 + i, attr );
1081 m_signalsGrid->SetCellValue( row, COL_CURSOR_2 + i, trace->GetCursor( i ) ? "1" : "0" );
1082 }
1083 }
1084 }
1085 row++;
1086 }
1087 }
1088
1093
1094 for( int col = COL_CURSOR_1; col < m_signalsGrid->GetNumberCols(); ++col )
1096}
1097
1098
1099void SIMULATOR_FRAME_UI::autoSizeGridColumn( WX_GRID* aGrid, int aCol, int aMinWidth, int aExtraPadding )
1100{
1101 wxGridUpdateLocker deferRepaintsTillLeavingScope( aGrid );
1102
1103 aGrid->AutoSizeColumn( aCol );
1104 aGrid->AutoSizeColLabelSize( aCol ); // Also grow (never shrink) to fit the header label
1105
1106 if( aExtraPadding > 0 )
1107 aGrid->SetColSize( aCol, aGrid->GetColSize( aCol ) + aExtraPadding );
1108
1109 if( aGrid->GetColSize( aCol ) < aMinWidth )
1110 aGrid->SetColSize( aCol, aMinWidth );
1111}
1112
1113
1114#define UNPLOTTED _( "none" )
1115
1116wxArrayString SIMULATOR_FRAME_UI::getViewChoices( SIM_PLOT_TAB* aPlotTab ) const
1117{
1118 wxArrayString choices;
1119 choices.Add( UNPLOTTED );
1120
1121 if( aPlotTab )
1122 {
1123 for( int ii = 0; ii < aPlotTab->GetViewCount(); ++ii )
1124 choices.Add( wxString::Format( _( "View %d" ), ii + 1 ) );
1125 }
1126
1127 return choices;
1128}
1129
1130
1131wxString SIMULATOR_FRAME_UI::getViewLabel( SIM_PLOT_TAB* aPlotTab, SIM_VIEW* aView ) const
1132{
1133 if( !aView || !aPlotTab )
1134 return UNPLOTTED;
1135
1136 int index = aPlotTab->GetViewIndex( aView );
1137
1138 return index >= 0 ? wxString::Format( _( "View %d" ), index + 1 ) : UNPLOTTED;
1139}
1140
1141
1142std::vector<SIM_VIEW*> SIMULATOR_FRAME_UI::getYScaleTargetViews( SIM_PLOT_TAB* aPlotTab, SIM_VIEW* aOwnView ) const
1143{
1144 std::vector<SIM_VIEW*> views;
1145
1146 if( aPlotTab )
1147 {
1148 for( SIM_VIEW* view : aPlotTab->GetViews() )
1149 {
1150 if( view != aOwnView )
1151 views.push_back( view );
1152 }
1153 }
1154
1155 return views;
1156}
1157
1158
1159wxArrayString SIMULATOR_FRAME_UI::getYScaleChoices( SIM_PLOT_TAB* aPlotTab, SIM_VIEW* aOwnView ) const
1160{
1161 wxArrayString choices;
1162 choices.Add( _( "Default" ) );
1163
1164 for( SIM_VIEW* view : getYScaleTargetViews( aPlotTab, aOwnView ) )
1165 choices.Add( getViewLabel( aPlotTab, view ) );
1166
1167 return choices;
1168}
1169
1170
1171wxString SIMULATOR_FRAME_UI::getYScaleLabel( SIM_PLOT_TAB* aPlotTab, TRACE* aTrace ) const
1172{
1173 if( !aTrace || aTrace->IsYScaleDefault() )
1174 return _( "Default" );
1175
1176 return getViewLabel( aPlotTab, aTrace->GetYScaleView() );
1177}
1178
1179
1181{
1182 m_signals.clear();
1183
1184 int options = m_simulatorFrame->GetCurrentOptions();
1185 SIM_TYPE simType = m_simulatorFrame->GetCurrentSimType();
1186 wxString unconnected = wxString( wxS( "unconnected-(" ) );
1187
1188 if( simType == ST_UNKNOWN )
1189 simType = ST_TRAN;
1190
1191 unconnected.Replace( '(', '_' ); // Convert to SPICE markup
1192
1193 SIM_PLOT_TAB* curPlotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1194 bool smithMode = curPlotTab && curPlotTab->GetSimType() == ST_SP && curPlotTab->IsSmithMode();
1195
1196 auto addSignal =
1197 [&]( const wxString& aSignalName )
1198 {
1199 if( simType == ST_AC )
1200 {
1201 m_signals.push_back( aSignalName + _( " (gain)" ) );
1202 m_signals.push_back( aSignalName + _( " (phase)" ) );
1203 }
1204 else if( simType == ST_SP )
1205 {
1206 if( smithMode )
1207 {
1208 m_signals.push_back( aSignalName );
1209 }
1210 else
1211 {
1212 m_signals.push_back( aSignalName + _( " (amplitude)" ) );
1213 m_signals.push_back( aSignalName + _( " (phase)" ) );
1214 }
1215 }
1216 else
1217 {
1218 m_signals.push_back( aSignalName );
1219 }
1220 };
1221
1223 && ( simType == ST_TRAN || simType == ST_DC || simType == ST_AC || simType == ST_FFT ) )
1224 {
1225 for( const wxString& netname : circuitModel()->GetNets() )
1226 {
1227 if( netname.IsSameAs( wxS( "GND" ), false ) || netname == "0" || netname.StartsWith( unconnected ) )
1228 continue;
1229
1230 m_netnames.emplace_back( netname );
1231 addSignal( wxString::Format( wxS( "V(%s)" ), netname ) );
1232 }
1233 }
1234
1236 && ( simType == ST_TRAN || simType == ST_DC || simType == ST_AC ) )
1237 {
1238 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
1239 {
1240 // Add all possible currents for the device.
1241 for( const std::string& name : item.model->SpiceGenerator().CurrentNames( item ) )
1242 addSignal( name );
1243 }
1244 }
1245
1247 && ( simType == ST_TRAN || simType == ST_DC ) )
1248 {
1249 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
1250 {
1251 if( item.model->GetPinCount() >= 2 )
1252 {
1253 wxString name = item.model->SpiceGenerator().ItemName( item );
1254 addSignal( wxString::Format( wxS( "P(%s)" ), name ) );
1255 }
1256 }
1257 }
1258
1259 if( simType == ST_NOISE )
1260 {
1261 addSignal( wxS( "inoise_spectrum" ) );
1262 addSignal( wxS( "onoise_spectrum" ) );
1263 }
1264
1265 if( simType == ST_SP )
1266 {
1267 std::vector<std::string> portnums;
1268
1269 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
1270 {
1271 wxString name = item.model->SpiceGenerator().ItemName( item );
1272
1273 // We are only looking for voltage sources in .SP mode
1274 if( !name.StartsWith( "V" ) )
1275 continue;
1276
1277 std::string portnum = "";
1278
1279 if( const SIM_MODEL::PARAM* portnum_param = item.model->FindParam( "portnum" ) )
1280 portnum = SIM_VALUE::ToSpice( portnum_param->value );
1281
1282 if( portnum != "" )
1283 portnums.push_back( portnum );
1284 }
1285
1286 for( const std::string& portnum1 : portnums )
1287 {
1288 for( const std::string& portnum2 : portnums )
1289 {
1290 // the Smith chart only makes sense for reflection parameters (S_i_i), the
1291 // transmission ones are not impedances
1292 if( smithMode && portnum1 != portnum2 )
1293 continue;
1294
1295 addSignal( wxString::Format( wxS( "S_%s_%s" ), portnum1, portnum2 ) );
1296 }
1297 }
1298 }
1299
1300 // Add .SAVE and .PROBE directives
1301 for( const wxString& directive : circuitModel()->GetDirectives() )
1302 {
1303 wxStringTokenizer directivesTokenizer( directive, "\r\n", wxTOKEN_STRTOK );
1304
1305 while( directivesTokenizer.HasMoreTokens() )
1306 {
1307 wxString line = directivesTokenizer.GetNextToken().Upper();
1308 wxString directiveParams;
1309
1310 if( line.StartsWith( wxS( ".SAVE" ), &directiveParams )
1311 || line.StartsWith( wxS( ".PROBE" ), &directiveParams ) )
1312 {
1313 wxStringTokenizer paramsTokenizer( directiveParams, " \t", wxTOKEN_STRTOK );
1314
1315 while( paramsTokenizer.HasMoreTokens() )
1316 addSignal( paramsTokenizer.GetNextToken() );
1317 }
1318 }
1319 }
1320}
1321
1322
1323SIM_TAB* SIMULATOR_FRAME_UI::NewSimTab( const wxString& aSimCommand )
1324{
1325 SIM_TAB* simTab = nullptr;
1326 SIM_TYPE simType = SPICE_CIRCUIT_MODEL::CommandToSimType( aSimCommand );
1327
1328 if( SIM_TAB::IsPlottable( simType ) )
1329 {
1330 SIM_PLOT_TAB* panel = new SIM_PLOT_TAB( aSimCommand, m_plotNotebook );
1331 simTab = panel;
1333 }
1334 else
1335 {
1336 simTab = new SIM_NOPLOT_TAB( aSimCommand, m_plotNotebook );
1337 }
1338
1339 wxString pageTitle( simulator()->TypeToName( simType, true ) );
1340 pageTitle.Prepend( wxString::Format( _( "Analysis %u - " ), static_cast<unsigned int>( ++m_plotNumber ) ) );
1341
1342 m_plotNotebook->AddPage( simTab, pageTitle, true );
1343
1344 return simTab;
1345}
1346
1347
1348void SIMULATOR_FRAME_UI::OnFilterText( wxCommandEvent& aEvent )
1349{
1350 rebuildSignalsGrid( m_filter->GetValue() );
1351}
1352
1353
1354void SIMULATOR_FRAME_UI::OnFilterMouseMoved( wxMouseEvent& aEvent )
1355{
1356#if defined( __WXOSX__ ) // Doesn't work properly on other ports
1357 wxPoint pos = aEvent.GetPosition();
1358 wxRect ctrlRect = m_filter->GetScreenRect();
1359 int buttonWidth = ctrlRect.GetHeight(); // Presume buttons are square
1360
1361 if( m_filter->IsSearchButtonVisible() && pos.x < buttonWidth )
1362 SetCursor( wxCURSOR_ARROW );
1363 else if( m_filter->IsCancelButtonVisible() && pos.x > ctrlRect.GetWidth() - buttonWidth )
1364 SetCursor( wxCURSOR_ARROW );
1365 else
1366 SetCursor( wxCURSOR_IBEAM );
1367#endif
1368}
1369
1370
1371wxString vectorNameFromSignalId( int aUserDefinedSignalId )
1372{
1373 return wxString::Format( wxS( "user%d" ), aUserDefinedSignalId );
1374}
1375
1376
1381wxString SIMULATOR_FRAME_UI::vectorNameFromSignalName( SIM_PLOT_TAB* aPlotTab, const wxString& aSignalName,
1382 int* aTraceType )
1383{
1384 auto looksLikePower = []( const wxString& aExpression ) -> bool
1385 {
1386 wxString exprUpper = aExpression.Upper();
1387
1388 if( exprUpper.Contains( wxS( ":POWER" ) ) )
1389 return true;
1390
1391 if( exprUpper.Find( '*' ) == wxNOT_FOUND )
1392 return false;
1393
1394 if( !exprUpper.Contains( wxS( "V(" ) ) )
1395 return false;
1396
1397 if( !exprUpper.Contains( wxS( "I(" ) ) )
1398 return false;
1399
1400 return true;
1401 };
1402
1403 std::map<wxString, int> suffixes;
1404 suffixes[_( " (amplitude)" )] = SPT_SP_AMP;
1405 suffixes[_( " (gain)" )] = SPT_AC_GAIN;
1406 suffixes[_( " (phase)" )] = SPT_AC_PHASE;
1407
1408 if( aTraceType )
1409 {
1410 if( aPlotTab && aPlotTab->GetSimType() == ST_NOISE )
1411 {
1412 if( getNoiseSource().Upper().StartsWith( 'I' ) )
1413 *aTraceType = SPT_CURRENT;
1414 else
1415 *aTraceType = SPT_VOLTAGE;
1416 }
1417 else
1418 {
1419 wxUniChar firstChar = aSignalName.Upper()[0];
1420
1421 if( firstChar == 'V' )
1422 *aTraceType = SPT_VOLTAGE;
1423 else if( firstChar == 'I' )
1424 *aTraceType = SPT_CURRENT;
1425 else if( firstChar == 'P' )
1426 *aTraceType = SPT_POWER;
1427 }
1428 }
1429
1430 wxString name = aSignalName;
1431
1432 for( const auto& [candidate, type] : suffixes )
1433 {
1434 if( name.EndsWith( candidate ) )
1435 {
1436 name = name.Left( name.Length() - candidate.Length() );
1437
1438 if( aTraceType )
1439 *aTraceType |= type;
1440
1441 break;
1442 }
1443 }
1444
1445 // smith mode rows carry no suffix, the trace holds the complex reflection coefficient
1446 if( aTraceType && aPlotTab && aPlotTab->GetSimType() == ST_SP && aPlotTab->IsSmithMode()
1447 && !( *aTraceType & ( SPT_SP_AMP | SPT_AC_GAIN | SPT_AC_PHASE ) ) )
1448 {
1449 *aTraceType |= SPT_SP_SMITH;
1450 }
1451
1452 for( const auto& [ id, signal ] : m_userDefinedSignals )
1453 {
1454 if( name == signal )
1455 {
1456 if( aTraceType && looksLikePower( signal ) )
1457 {
1458 int suffixBits = *aTraceType & ( SPT_SP_MASK | SPT_AC_GAIN );
1459 *aTraceType = suffixBits | SPT_POWER;
1460 }
1461
1462 return vectorNameFromSignalId( id );
1463 }
1464 }
1465
1466 return name;
1467};
1468
1469
1471{
1472 if( m_SuppressGridEvents > 0 )
1473 return;
1474
1475 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1476
1477 if( !plotTab )
1478 return;
1479
1480 int row = aEvent.GetRow();
1481 int col = aEvent.GetCol();
1482 wxString text = m_signalsGrid->GetCellValue( row, col );
1483 wxString signalName = m_signalsGrid->GetCellValue( row, COL_SIGNAL_NAME );
1484 int traceType = SPT_UNKNOWN;
1485 wxString vectorName = vectorNameFromSignalName( plotTab, signalName, &traceType );
1486
1487 if( col == COL_SIGNAL_SHOW )
1488 {
1489 wxArrayString choices = getViewChoices( plotTab );
1490 int choiceIndex = choices.Index( text );
1491
1492 if( choiceIndex <= 0 )
1493 {
1494 plotTab->DeleteTrace( vectorName, traceType );
1495 }
1496 else if( SIM_VIEW* targetView = plotTab->GetView( choiceIndex - 1 ) )
1497 {
1498 TRACE* existing = plotTab->GetTrace( vectorName, traceType );
1499
1500 if( existing && existing->GetView() != targetView )
1501 plotTab->DeleteTrace( existing );
1502
1503 updateTrace( vectorName, traceType, plotTab, nullptr, false, targetView );
1504 }
1505
1506 for( SIM_VIEW* view : plotTab->GetViews() )
1507 view->UpdateAll();
1508
1509 // Update enabled/visible states of other controls
1512 OnModify();
1513 }
1514 else if( col == COL_Y_SCALE )
1515 {
1516 TRACE* trace = plotTab->GetTrace( vectorName, traceType );
1517
1518 if( trace )
1519 {
1520 std::vector<SIM_VIEW*> targetViews = getYScaleTargetViews( plotTab, trace->GetView() );
1521 wxArrayString choices = getYScaleChoices( plotTab, trace->GetView() );
1522 int choiceIndex = choices.Index( text );
1523
1524 if( choiceIndex == 0 )
1525 {
1526 trace->SetYScaleView( trace->GetView() );
1527 }
1528 else if( choiceIndex > 0 && choiceIndex - 1 < (int) targetViews.size() )
1529 {
1530 trace->SetYScaleView( targetViews[choiceIndex - 1] );
1531 }
1532
1533 plotTab->ResetScales( false );
1534
1535 for( SIM_VIEW* view : plotTab->GetViews() )
1536 view->UpdateAll();
1537
1538 OnModify();
1539 }
1540 }
1541 else if( col == COL_SIGNAL_COLOR )
1542 {
1543 KIGFX::COLOR4D color( m_signalsGrid->GetCellValue( row, COL_SIGNAL_COLOR ) );
1544 TRACE* trace = plotTab->GetTrace( vectorName, traceType );
1545
1546 if( trace )
1547 {
1548 trace->SetTraceColour( color.ToColour() );
1549 plotTab->UpdateTraceStyle( trace );
1550 plotTab->UpdatePlotColors();
1551 OnModify();
1552 }
1553 }
1554 else if( col == COL_CURSOR_1 || col == COL_CURSOR_2
1555 || ( std::size( m_cursorFormatsDyn ) > std::size( m_cursorFormats ) && col > COL_CURSOR_2 ) )
1556 {
1557 int id = col == COL_CURSOR_1 ? 1 : 2;
1558
1559 if( col > COL_CURSOR_2 ) // TODO: clean up logic
1560 {
1561 id = col - 3; // enum SIGNALS_GRID_COLUMNS offset for Cursor n (COL_CURSOR_1 - 1)
1562 }
1563
1564 TRACE* activeTrace = nullptr;
1565
1566 if( text == wxS( "1" ) )
1567 {
1568 signalName = m_signalsGrid->GetCellValue( row, COL_SIGNAL_NAME );
1569 vectorName = vectorNameFromSignalName( plotTab, signalName, &traceType );
1570 activeTrace = plotTab->GetTrace( vectorName, traceType );
1571
1572 if( activeTrace )
1573 plotTab->EnableCursor( activeTrace, id, signalName );
1574
1575 OnModify();
1576 }
1577
1578 // Turn off cursor on other signals.
1579 for( const auto& [name, trace] : plotTab->GetTraces() )
1580 {
1581 if( trace != activeTrace && trace->HasCursor( id ) )
1582 {
1583 plotTab->DisableCursor( trace, id );
1584 OnModify();
1585 }
1586 }
1587
1588 // Update cursor checkboxes (which are really radio buttons)
1590 }
1591}
1592
1593
1595{
1596 if( m_SuppressGridEvents > 0 )
1597 return;
1598
1599 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1600
1601 if( !plotTab )
1602 return;
1603
1604 int row = aEvent.GetRow();
1605 int col = aEvent.GetCol();
1606 wxString text = m_cursorsGrid->GetCellValue( row, col );
1607 wxString cursorName = m_cursorsGrid->GetCellValue( row, COL_CURSOR_NAME );
1608
1609 double value = SPICE_VALUE( text ).ToDouble();
1610
1611 if( col == COL_CURSOR_X )
1612 {
1613 CURSOR* cursor1 = nullptr;
1614 CURSOR* cursor2 = nullptr;
1615
1616 std::vector<CURSOR*> cursorsVec;
1617 cursorsVec.clear();
1618
1619 for( const auto& [name, trace] : plotTab->GetTraces() )
1620 {
1621 if( CURSOR* cursor = trace->GetCursor( 1 ) )
1622 cursor1 = cursor;
1623
1624 if( CURSOR* cursor = trace->GetCursor( 2 ) )
1625 cursor2 = cursor;
1626
1627 int tmp = 3;
1628
1629 if( !cursor1 )
1630 tmp--;
1631 if( !cursor2 )
1632 tmp--;
1633
1634 for( int i = tmp; i < m_customCursorsCnt; i++ )
1635 {
1636 if( CURSOR* cursor = trace->GetCursor( i ) )
1637 {
1638 cursorsVec.emplace_back( cursor );
1639
1640 if( cursorName == ( wxString( "" ) << i ) && cursor )
1641 cursor->SetCoordX( value );
1642 }
1643 }
1644 }
1645
1646 //double value = SPICE_VALUE( text ).ToDouble();
1647
1648 if( cursorName == wxS( "1" ) && cursor1 )
1649 cursor1->SetCoordX( value );
1650 else if( cursorName == wxS( "2" ) && cursor2 )
1651 cursor2->SetCoordX( value );
1652 else if( cursorName == _( "Diff" ) && cursor1 && cursor2 )
1653 cursor2->SetCoordX( cursor1->GetCoords().x + value );
1654
1656 OnModify();
1657 }
1658 else
1659 {
1660 wxFAIL_MSG( wxT( "All other columns are supposed to be read-only!" ) );
1661 }
1662}
1663
1664
1666{
1668 result.FromString( m_measurementsGrid->GetCellValue( aRow, COL_MEASUREMENT_FORMAT ) );
1669 return result;
1670}
1671
1672
1674{
1675 m_measurementsGrid->SetCellValue( aRow, COL_MEASUREMENT_FORMAT, aFormat.ToString() );
1676}
1677
1678
1680{
1681 if( aRow < ( m_measurementsGrid->GetNumberRows() - 1 ) )
1682 m_measurementsGrid->DeleteRows( aRow, 1 );
1683}
1684
1685
1687{
1688 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1689
1690 if( !plotTab )
1691 return;
1692
1693 int row = aEvent.GetRow();
1694 int col = aEvent.GetCol();
1695
1696 if( col == COL_MEASUREMENT )
1697 {
1698 UpdateMeasurement( row );
1700 OnModify();
1701 }
1702 else
1703 {
1704 wxFAIL_MSG( wxT( "All other columns are supposed to be read-only!" ) );
1705 }
1706
1707 // Always leave a single empty row for type-in
1708
1709 int rowCount = static_cast<int>( m_measurementsGrid->GetNumberRows() );
1710 int emptyRows = 0;
1711
1712 for( row = rowCount - 1; row >= 0; row-- )
1713 {
1714 if( m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1715 emptyRows++;
1716 else
1717 break;
1718 }
1719
1720 if( emptyRows > 1 )
1721 {
1722 int killRows = emptyRows - 1;
1723 m_measurementsGrid->DeleteRows( rowCount - killRows, killRows );
1724 }
1725 else if( emptyRows == 0 )
1726 {
1727 m_measurementsGrid->AppendRows( 1 );
1728 }
1729}
1730
1731
1732void SIMULATOR_FRAME_UI::OnUpdateUI( wxUpdateUIEvent& event )
1733{
1734 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
1735 {
1736 if( plotTab->GetLegendPosition() != plotTab->m_LastLegendPosition )
1737 {
1738 plotTab->m_LastLegendPosition = plotTab->GetLegendPosition();
1739 OnModify();
1740 }
1741 }
1742}
1743
1744
1760{
1761 static wxRegEx measureParamsRegEx( wxT( "^"
1762 " *"
1763 "([a-zA-Z_]+)"
1764 " +"
1765 "([a-zA-Z]*)\\(([^\\)]+)\\)" ) );
1766
1767 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1768
1769 if( !plotTab )
1770 return;
1771
1772 wxString text = m_measurementsGrid->GetCellValue( aRow, COL_MEASUREMENT );
1773
1774 if( text.IsEmpty() )
1775 {
1776 m_measurementsGrid->SetCellValue( aRow, COL_MEASUREMENT_VALUE, wxEmptyString );
1777 return;
1778 }
1779
1780 wxString simType = simulator()->TypeToName( plotTab->GetSimType(), true );
1781 wxString resultName = wxString::Format( wxS( "meas_result_%u" ), aRow );
1782 wxString result = wxS( "?" );
1783
1784 if( measureParamsRegEx.Matches( text ) )
1785 {
1786 wxString func = measureParamsRegEx.GetMatch( text, 1 ).Upper();
1787 wxString signalType = measureParamsRegEx.GetMatch( text, 2 ).Upper();
1788 wxString deviceName = measureParamsRegEx.GetMatch( text, 3 );
1789 wxString units;
1791
1792 if( signalType.EndsWith( wxS( "DB" ) ) )
1793 {
1794 units = wxS( "dB" );
1795 }
1796 else if( signalType.StartsWith( 'I' ) )
1797 {
1798 units = wxS( "A" );
1799 }
1800 else if( signalType.StartsWith( 'P' ) )
1801 {
1802 units = wxS( "W" );
1803 // Our syntax is different from ngspice for power signals
1804 text = func + " " + deviceName + ":power";
1805 }
1806 else
1807 {
1808 units = wxS( "V" );
1809 }
1810
1811 if( func.EndsWith( wxS( "_AT" ) ) )
1812 {
1813 if( plotTab->GetSimType() == ST_AC || plotTab->GetSimType() == ST_SP )
1814 units = wxS( "Hz" );
1815 else
1816 units = wxS( "s" );
1817 }
1818 else if( func.StartsWith( wxS( "INTEG" ) ) )
1819 {
1820 switch( plotTab->GetSimType() )
1821 {
1822 case ST_TRAN:
1823 if ( signalType.StartsWith( 'P' ) )
1824 units = wxS( "J" );
1825 else
1826 units += wxS( ".s" );
1827
1828 break;
1829
1830 case ST_AC:
1831 case ST_SP:
1832 case ST_DISTO:
1833 case ST_NOISE:
1834 case ST_FFT:
1835 case ST_SENS: // If there is a vector, it is frequency
1836 units += wxS( "·Hz" );
1837 break;
1838
1839 case ST_DC: // Could be a lot of things : V, A, deg C, ohm, ...
1840 case ST_OP: // There is no vector for integration
1841 case ST_PZ: // There is no vector for integration
1842 case ST_TF: // There is no vector for integration
1843 default:
1844 units += wxS( "·?" );
1845 break;
1846 }
1847 }
1848
1849 fmt.UpdateUnits( units );
1850 SetMeasureFormat( aRow, fmt );
1851
1853 }
1854
1855 if( m_simulatorFrame->SimFinished() )
1856 {
1857 wxString cmd = wxString::Format( wxS( "meas %s %s %s" ), simType, resultName, text );
1858 simulator()->Command( "echo " + cmd.ToStdString() );
1859 simulator()->Command( cmd.ToStdString() );
1860
1861 std::vector<double> resultVec = simulator()->GetGainVector( resultName.ToStdString() );
1862
1863 if( resultVec.size() > 0 )
1864 result = SPICE_VALUE( resultVec[0] ).ToString( GetMeasureFormat( aRow ) );
1865 }
1866
1867 m_measurementsGrid->SetCellValue( aRow, COL_MEASUREMENT_VALUE, result );
1868}
1869
1870
1871void SIMULATOR_FRAME_UI::AddTuner( const SCH_SHEET_PATH& aSheetPath, SCH_SYMBOL* aSymbol )
1872{
1873 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1874
1875 if( !plotTab )
1876 {
1877 DisplayErrorMessage( nullptr, _( "The current analysis must have a plot in order to tune "
1878 "the value of a passive R, L, C model or voltage or "
1879 "current source." ) );
1880 return;
1881 }
1882
1883 wxString ref = aSymbol->GetRef( &aSheetPath );
1884
1885 // Do not add multiple instances for the same component.
1886 for( TUNER_SLIDER* tuner : m_tuners )
1887 {
1888 if( tuner->GetSymbolRef() == ref )
1889 return;
1890 }
1891
1892 if( [[maybe_unused]] const SPICE_ITEM* item = GetExporter()->FindItem( ref ) )
1893 {
1894 try
1895 {
1896 TUNER_SLIDER* tuner = new TUNER_SLIDER( this, m_panelTuners, aSheetPath, aSymbol );
1897 m_sizerTuners->Add( tuner );
1898 m_tuners.push_back( tuner );
1899 m_panelTuners->Layout();
1900 OnModify();
1901 }
1902 catch( const KI_PARAM_ERROR& e )
1903 {
1904 DisplayErrorMessage( nullptr, e.What() );
1905 }
1906 }
1907}
1908
1909
1910void SIMULATOR_FRAME_UI::UpdateTunerValue( const SCH_SHEET_PATH& aSheetPath, const KIID& aSymbol, const wxString& aRef,
1911 const wxString& aValue )
1912{
1913 SCHEMATIC& schematic = m_schematicFrame->Schematic();
1914 wxString variant = schematic.GetCurrentVariant();
1915 SCH_ITEM* item = aSheetPath.ResolveItem( aSymbol );
1916 SCH_SYMBOL* symbol = dynamic_cast<SCH_SYMBOL*>( item );
1917
1918 if( !symbol )
1919 {
1920 DisplayErrorMessage( this, _( "Could not apply tuned value(s):" ) + wxS( " " )
1921 + wxString::Format( _( "%s not found" ), aRef ) );
1922 return;
1923 }
1924
1925 NULL_REPORTER devnull;
1926 SIM_LIB_MGR mgr( &m_schematicFrame->Prj() );
1927
1928 std::vector<EMBEDDED_FILES*> embeddedFilesStack;
1929 embeddedFilesStack.push_back( m_schematicFrame->Schematic().GetEmbeddedFiles() );
1930
1931 if( symbol->GetLibSymbolRef() )
1932 symbol->GetLibSymbolRef()->AppendParentEmbeddedFiles( embeddedFilesStack );
1933
1934 if( EMBEDDED_FILES* symbolEmbeddedFiles = symbol->GetEmbeddedFiles() )
1935 embeddedFilesStack.push_back( symbolEmbeddedFiles );
1936
1937 mgr.SetFilesStack( std::move( embeddedFilesStack ) );
1938
1939 SIM_MODEL& model = mgr.CreateModel( &aSheetPath, *symbol, true, 0, variant, devnull ).model;
1940
1941 const SIM_MODEL::PARAM* tunerParam = model.GetTunerParam();
1942
1943 if( !tunerParam )
1944 {
1945 DisplayErrorMessage( this, _( "Could not apply tuned value(s):" ) + wxS( " " )
1946 + wxString::Format( _( "%s is not tunable" ), aRef ) );
1947 return;
1948 }
1949
1950 model.SetParamValue( tunerParam->info.name, std::string( aValue.ToUTF8() ) );
1951 model.WriteFields( symbol->GetFields(), &aSheetPath, variant );
1952
1953 m_schematicFrame->UpdateItem( symbol, false, true );
1954 m_schematicFrame->OnModify();
1955}
1956
1957
1959{
1960 m_tuners.remove( aTuner );
1961
1962 if( std::find( m_multiRunState.tuners.begin(), m_multiRunState.tuners.end(), aTuner )
1963 != m_multiRunState.tuners.end() )
1964 {
1965 clearMultiRunState( true );
1966 }
1967
1968 m_tunerOverrides.erase( aTuner );
1969
1970 aTuner->Destroy();
1971 m_panelTuners->Layout();
1972 OnModify();
1973}
1974
1975
1976void SIMULATOR_FRAME_UI::AddMeasurement( const wxString& aCmd )
1977{
1978 // -1 because the last one is for user input
1979 for( int i = 0; i < m_measurementsGrid->GetNumberRows(); i++ )
1980 {
1981 if( m_measurementsGrid->GetCellValue( i, COL_MEASUREMENT ) == aCmd )
1982 return; // Don't create duplicates
1983 }
1984
1985 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
1986
1987 if( !plotTab )
1988 return;
1989
1990 int row;
1991
1992 for( row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
1993 {
1994 if( m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1995 break;
1996 }
1997
1998 if( !m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
1999 {
2000 m_measurementsGrid->AppendRows( 1 );
2001 row = m_measurementsGrid->GetNumberRows() - 1;
2002 }
2003
2004 m_measurementsGrid->SetCellValue( row, COL_MEASUREMENT, aCmd );
2005
2006 UpdateMeasurement( row );
2008 OnModify();
2009
2010 // Always leave at least one empty row for type-in:
2011 row = m_measurementsGrid->GetNumberRows() - 1;
2012
2013 if( !m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
2014 m_measurementsGrid->AppendRows( 1 );
2015}
2016
2017
2018void SIMULATOR_FRAME_UI::DoFourier( const wxString& aSignal, const wxString& aFundamental )
2019{
2020 wxString cmd = wxString::Format( wxS( "fourier %s %s" ),
2021 SPICE_VALUE( aFundamental ).ToSpiceString(),
2022 aSignal );
2023
2024 simulator()->Command( cmd.ToStdString() );
2025}
2026
2027
2029{
2030 return circuitModel().get();
2031}
2032
2033
2034void SIMULATOR_FRAME_UI::AddTrace( const wxString& aName, SIM_TRACE_TYPE aType )
2035{
2036 if( !GetCurrentSimTab() )
2037 {
2038 m_simConsole->AppendText( _( "Error: no current simulation.\n" ) );
2039 m_simConsole->SetInsertionPointEnd();
2040 return;
2041 }
2042
2043 SIM_TYPE simType = SPICE_CIRCUIT_MODEL::CommandToSimType( GetCurrentSimTab()->GetSimCommand() );
2044
2045 if( simType == ST_UNKNOWN )
2046 {
2047 m_simConsole->AppendText( _( "Error: simulation type not defined.\n" ) );
2048 m_simConsole->SetInsertionPointEnd();
2049 return;
2050 }
2051 else if( !SIM_TAB::IsPlottable( simType ) )
2052 {
2053 m_simConsole->AppendText( _( "Error: simulation type doesn't support plotting.\n" ) );
2054 m_simConsole->SetInsertionPointEnd();
2055 return;
2056 }
2057
2058 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
2059 {
2060 if( simType == ST_AC )
2061 {
2062 updateTrace( aName, aType | SPT_AC_GAIN, plotTab );
2063 updateTrace( aName, aType | SPT_AC_PHASE, plotTab );
2064 }
2065 else if( simType == ST_SP )
2066 {
2067 if( plotTab->IsSmithMode() )
2068 {
2069 updateTrace( aName, aType | SPT_SP_SMITH, plotTab );
2070 }
2071 else
2072 {
2073 updateTrace( aName, aType | SPT_SP_AMP, plotTab );
2074 updateTrace( aName, aType | SPT_AC_PHASE, plotTab );
2075 }
2076 }
2077 else
2078 {
2079 updateTrace( aName, aType, plotTab );
2080 }
2081
2082 for( SIM_VIEW* view : plotTab->GetViews() )
2083 view->UpdateAll();
2084 }
2085
2087 OnModify();
2088}
2089
2090
2091void SIMULATOR_FRAME_UI::SetUserDefinedSignals( const std::map<int, wxString>& aNewSignals )
2092{
2093 for( size_t ii = 0; ii < m_plotNotebook->GetPageCount(); ++ii )
2094 {
2095 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( m_plotNotebook->GetPage( ii ) );
2096
2097 if( !plotTab )
2098 continue;
2099
2100 for( const auto& [id, existingSignal] : m_userDefinedSignals )
2101 {
2102 int traceType = SPT_UNKNOWN;
2103 wxString vectorName = vectorNameFromSignalName( plotTab, existingSignal, &traceType );
2104
2105 if( aNewSignals.count( id ) == 0 )
2106 {
2107 if( plotTab->GetSimType() == ST_AC )
2108 {
2109 for( int subType : { SPT_AC_GAIN, SPT_AC_PHASE } )
2110 plotTab->DeleteTrace( vectorName, traceType | subType );
2111 }
2112 else if( plotTab->GetSimType() == ST_SP )
2113 {
2114 for( int subType : { SPT_SP_AMP, SPT_AC_PHASE, SPT_SP_SMITH } )
2115 plotTab->DeleteTrace( vectorName, traceType | subType );
2116 }
2117 else
2118 {
2119 plotTab->DeleteTrace( vectorName, traceType );
2120 }
2121 }
2122 else
2123 {
2124 if( plotTab->GetSimType() == ST_AC )
2125 {
2126 for( int subType : { SPT_AC_GAIN, SPT_AC_PHASE } )
2127 {
2128 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType | subType ) )
2129 trace->SetName( aNewSignals.at( id ) );
2130 }
2131 }
2132 else if( plotTab->GetSimType() == ST_SP )
2133 {
2134 for( int subType : { SPT_SP_AMP, SPT_AC_PHASE, SPT_SP_SMITH } )
2135 {
2136 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType | subType ) )
2137 trace->SetName( aNewSignals.at( id ) );
2138 }
2139 }
2140 else
2141 {
2142 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType ) )
2143 trace->SetName( aNewSignals.at( id ) );
2144 }
2145 }
2146 }
2147 }
2148
2149 m_userDefinedSignals = aNewSignals;
2150
2151 if( m_simulatorFrame->SimFinished() )
2153
2155 rebuildSignalsGrid( m_filter->GetValue() );
2158 OnModify();
2159}
2160
2161
2162double SIMULATOR_FRAME_UI::getSmithPortImpedance( const wxString& aVectorName )
2163{
2164 long responsePort, drivePort;
2165
2166 // normalize to the response port z0
2167 if( !SMITH_MATH::ParseSParamPorts( aVectorName, &responsePort, &drivePort ) )
2168 return 0.0;
2169
2170 for( const SPICE_ITEM& item : circuitModel()->GetItems() )
2171 {
2172 if( !item.model )
2173 continue;
2174
2175 const SIM_MODEL::PARAM* portnumParam = item.model->FindParam( "portnum" );
2176 long portnum = 0;
2177
2178 if( !portnumParam
2179 || !wxString( SIM_VALUE::ToSpice( portnumParam->value ) ).ToLong( &portnum )
2180 || portnum != responsePort )
2181 {
2182 continue;
2183 }
2184
2185 if( const SIM_MODEL::PARAM* z0Param = item.model->FindParam( "z0" ) )
2186 {
2187 double z0 = SIM_VALUE::ToDouble( z0Param->value, 50.0 );
2188
2189 if( z0 > 0 )
2190 return z0;
2191 }
2192
2193 // this item has no usable z0, another item may still carry it for this port
2194 }
2195
2196 return 0.0;
2197}
2198
2199
2200void SIMULATOR_FRAME_UI::updateTrace( const wxString& aVectorName, int aTraceType, SIM_PLOT_TAB* aPlotTab,
2201 std::vector<double>* aDataX, bool aClearData, SIM_VIEW* aView )
2202{
2203 if( !aView )
2204 {
2205 TRACE* existing = aPlotTab->GetTrace( aVectorName, aTraceType );
2206 aView = existing && existing->GetView() ? existing->GetView() : aPlotTab->GetDefaultView();
2207 }
2208
2209 if( !m_simulatorFrame->SimFinished() && !simulator()->IsRunning() )
2210 {
2211 aPlotTab->GetOrAddTrace( aVectorName, aTraceType, aView );
2212 return;
2213 }
2214
2216
2217 aTraceType &= aTraceType & SPT_Y_AXIS_MASK;
2218 aTraceType |= getXAxisType( simType );
2219
2220 wxString simVectorName = aVectorName;
2221
2222 if( aTraceType & SPT_POWER )
2223 simVectorName = simVectorName.AfterFirst( '(' ).BeforeLast( ')' ) + wxS( ":power" );
2224
2225 if( !SIM_TAB::IsPlottable( simType ) )
2226 {
2227 // There is no plot to be shown
2228 simulator()->Command( wxString::Format( wxT( "print %s" ), aVectorName ).ToStdString() );
2229
2230 return;
2231 }
2232
2233 std::vector<double> data_x;
2234 std::vector<double> data_y;
2235 std::vector<double> frequencies;
2236
2237 if( !aDataX || aClearData )
2238 aDataX = &data_x;
2239
2240 // First, handle the x axis
2241 if( aDataX->empty() && !aClearData )
2242 {
2243 wxString xAxisName( simulator()->GetXAxis( simType ) );
2244
2245 if( xAxisName.IsEmpty() )
2246 return;
2247
2248 *aDataX = simulator()->GetGainVector( (const char*) xAxisName.c_str() );
2249 }
2250
2251 unsigned int size = aDataX->size();
2252
2253 switch( simType )
2254 {
2255 case ST_AC:
2256 if( aTraceType & SPT_AC_GAIN )
2257 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), size );
2258 else if( aTraceType & SPT_AC_PHASE )
2259 data_y = simulator()->GetPhaseVector( (const char*) simVectorName.c_str(), size );
2260 else
2261 wxFAIL_MSG( wxT( "Plot type missing AC_PHASE or AC_MAG bit" ) );
2262
2263 break;
2264 case ST_SP:
2265 if( aTraceType & SPT_SP_SMITH )
2266 {
2267 // reflection coefficient locus, Re on X and Im on Y, frequency kept aside
2268 frequencies = *aDataX;
2269 data_y = simulator()->GetImaginaryVector( (const char*) simVectorName.c_str(), size );
2270 *aDataX = simulator()->GetRealVector( (const char*) simVectorName.c_str(), size );
2271 }
2272 else if( aTraceType & SPT_SP_AMP )
2273 {
2274 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), size );
2275 }
2276 else if( aTraceType & SPT_AC_PHASE )
2277 {
2278 data_y = simulator()->GetPhaseVector( (const char*) simVectorName.c_str(), size );
2279 }
2280 else
2281 {
2282 wxFAIL_MSG( wxT( "Plot type missing AC_PHASE, SPT_SP_AMP or SPT_SP_SMITH bit" ) );
2283 }
2284
2285 break;
2286
2287 case ST_DC:
2288 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), -1 );
2289 break;
2290
2291 case ST_NOISE:
2292 case ST_TRAN:
2293 case ST_FFT:
2294 data_y = simulator()->GetGainVector( (const char*) simVectorName.c_str(), size );
2295 break;
2296
2297 default:
2298 wxFAIL_MSG( wxT( "Unhandled plot type" ) );
2299 }
2300
2301 SPICE_DC_PARAMS source1, source2;
2302 int sweepCount = 1;
2303 size_t sweepSize = std::numeric_limits<size_t>::max();
2304
2305 if( simType == ST_DC
2306 && circuitModel()->ParseDCCommand( aPlotTab->GetSimCommand(), &source1, &source2 )
2307 && !source2.m_source.IsEmpty() )
2308 {
2309 SPICE_VALUE v = ( source2.m_vend - source2.m_vstart ) / source2.m_vincrement;
2310
2311 sweepCount = KiROUND( v.ToDouble() ) + 1;
2312 sweepSize = aDataX->size() / sweepCount;
2313 }
2314
2315 bool smithTrace = ( aTraceType & SPT_SP_SMITH ) > 0;
2316
2317 if( m_multiRunState.storePending )
2318 recordMultiRunData( aVectorName, aTraceType, *aDataX, data_y );
2319
2320 if( hasMultiRunTrace( aVectorName, aTraceType ) )
2321 {
2322 const std::string key = multiRunTraceKey( aVectorName, aTraceType );
2323 const auto traceIt = m_multiRunState.traces.find( key );
2324
2325 if( traceIt != m_multiRunState.traces.end() )
2326 {
2327 const MULTI_RUN_TRACE& traceData = traceIt->second;
2328
2329 if( !traceData.xValues.empty() && !traceData.yValues.empty() )
2330 {
2331 size_t sweepSizeMulti = traceData.xValues.size();
2332 size_t runCount = traceData.yValues.size();
2333
2334 if( sweepSizeMulti > 0 && runCount > 0 )
2335 {
2336 std::vector<double> combinedX;
2337 std::vector<double> combinedY;
2338 std::vector<double> combinedFreq;
2339
2340 combinedX.reserve( sweepSizeMulti * runCount );
2341 combinedY.reserve( sweepSizeMulti * runCount );
2342
2343 for( size_t run = 0; run < traceData.yValues.size(); run++ )
2344 {
2345 const std::vector<double>& runY = traceData.yValues[run];
2346
2347 if( runY.size() != sweepSizeMulti )
2348 continue;
2349
2350 if( smithTrace )
2351 {
2352 // per-run x, Re(gamma) differs between runs
2353 if( run >= traceData.xRuns.size() || traceData.xRuns[run].size() != sweepSizeMulti )
2354 continue;
2355
2356 combinedX.insert( combinedX.end(), traceData.xRuns[run].begin(),
2357 traceData.xRuns[run].end() );
2358 }
2359 else
2360 {
2361 combinedX.insert( combinedX.end(), traceData.xValues.begin(), traceData.xValues.end() );
2362 }
2363
2364 combinedY.insert( combinedY.end(), runY.begin(), runY.end() );
2365
2366 // the sweep frequencies are the same every run, repeat them per run
2367 if( frequencies.size() == sweepSizeMulti )
2368 combinedFreq.insert( combinedFreq.end(), frequencies.begin(), frequencies.end() );
2369 }
2370
2371 if( TRACE* trace = aPlotTab->GetOrAddTrace( aVectorName, aTraceType, aView ) )
2372 {
2373 if( SMITH_TRACE* smith = dynamic_cast<SMITH_TRACE*>( trace ) )
2374 {
2375 smith->SetReferenceImpedance( getSmithPortImpedance( aVectorName ) );
2377
2378 if( combinedFreq.size() == combinedX.size() )
2379 smith->SetFrequencies( combinedFreq );
2380 }
2381
2382 if( combinedY.size() >= combinedX.size() && sweepSizeMulti > 0 )
2383 {
2384 int sweepCountCombined =
2385 combinedX.empty() ? 0 : static_cast<int>( combinedY.size() / sweepSizeMulti );
2386
2387 if( sweepCountCombined > 0 )
2388 {
2389 // Generate labels for each run based on tuner values
2390 std::vector<wxString> labels;
2391 labels.reserve( sweepCountCombined );
2392
2393 for( int i = 0; i < sweepCountCombined && i < (int) m_multiRunState.steps.size(); ++i )
2394 {
2395 const MULTI_RUN_STEP& step = m_multiRunState.steps[i];
2396 wxString label;
2397
2398 for( auto it = step.overrides.begin(); it != step.overrides.end(); ++it )
2399 {
2400 if( it != step.overrides.begin() )
2401 label += wxS( ", " );
2402
2403 const TUNER_SLIDER* tuner = it->first;
2404 double value = it->second;
2405
2406 SPICE_VALUE spiceVal( value );
2407 label += tuner->GetSymbolRef() + wxS( "=" ) + spiceVal.ToSpiceString();
2408 }
2409
2410 labels.push_back( label );
2411 }
2412
2413 aPlotTab->SetTraceData( trace, combinedX, combinedY, sweepCountCombined, sweepSizeMulti,
2414 true, labels );
2415 }
2416 }
2417 }
2418
2419 return;
2420 }
2421 }
2422 }
2423 }
2424
2425 if( TRACE* trace = aPlotTab->GetOrAddTrace( aVectorName, aTraceType, aView ) )
2426 {
2427 if( data_y.size() >= size )
2428 {
2429 if( SMITH_TRACE* smith = dynamic_cast<SMITH_TRACE*>( trace ) )
2430 {
2431 smith->SetFrequencies( frequencies );
2432 smith->SetReferenceImpedance( getSmithPortImpedance( aVectorName ) );
2434 }
2435
2436 aPlotTab->SetTraceData( trace, *aDataX, data_y, sweepCount, sweepSize );
2437 }
2438 }
2439}
2440
2441
2442// TODO make sure where to instantiate and how to style correct
2443// Better ask someone..
2444template
2446
2447template <typename T, typename U, typename R>
2449 T t, U u, R r ) // t=cursor type/signals' grid col, u=cursor number/cursor "id", r=table's row
2450{
2451 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
2452 wxString signalName = m_signalsGrid->GetCellValue( r, COL_SIGNAL_NAME );
2453 int traceType = SPT_UNKNOWN;
2454 wxString vectorName = vectorNameFromSignalName( plotTab, signalName, &traceType );
2455
2456 wxGridCellAttrPtr attr = m_signalsGrid->GetOrCreateCellAttrPtr( r, static_cast<int>( t ) );
2457
2458 TRACE* trace = plotTab ? plotTab->GetTrace( vectorName, traceType ) : nullptr;
2459
2460 // A trace with no view is an orphan (its view was removed); treat it as not plotted so it
2461 // shows the same disabled styling as a never-plotted signal.
2462 bool plotted = trace && trace->GetView();
2463
2464 if( plotted )
2465 {
2466 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
2467
2469 {
2470 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
2471 }
2472
2473 if constexpr( std::is_enum<T>::value )
2474 {
2476 {
2477 if( !attr->HasEditor() )
2478 attr->SetEditor( new GRID_CELL_COMBOBOX( getViewChoices( plotTab ) ) );
2479
2480 if( !attr->HasRenderer() )
2481 attr->SetRenderer( new GRID_CELL_COMBOBOX_RENDERER() );
2482
2483 attr->SetReadOnly( false );
2484 attr->SetTextColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) );
2485 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), getViewLabel( plotTab, trace->GetView() ) );
2486 }
2487 else if( t == SIGNALS_GRID_COLUMNS::COL_Y_SCALE )
2488 {
2489 if( !attr->HasEditor() )
2490 attr->SetEditor( new GRID_CELL_COMBOBOX( getYScaleChoices( plotTab, trace->GetView() ) ) );
2491
2492 if( !attr->HasRenderer() )
2493 attr->SetRenderer( new GRID_CELL_COMBOBOX_RENDERER() );
2494
2495 attr->SetReadOnly( false );
2496 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), getYScaleLabel( plotTab, trace ) );
2497 }
2499 {
2500 if( !attr->HasRenderer() )
2501 attr->SetRenderer( new GRID_CELL_COLOR_RENDERER( this ) );
2502
2503 if( !attr->HasEditor() )
2504 attr->SetEditor( new GRID_CELL_COLOR_SELECTOR( this, m_signalsGrid ) );
2505
2506 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
2507 attr->SetReadOnly( false );
2508
2509 KIGFX::COLOR4D color( trace->GetPen().GetColour() );
2510 m_signalsGrid->SetCellValue( r, COL_SIGNAL_COLOR, color.ToCSSString() );
2511 }
2515 {
2516 if( !attr->HasRenderer() )
2517 attr->SetRenderer( new wxGridCellBoolRenderer() );
2518
2519 if( u > 0 && trace->HasCursor( u ) )
2520 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), wxS( "1" ) );
2521 else
2522 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), wxEmptyString );
2523 }
2524 }
2525 }
2526 else
2527 {
2528 if constexpr( std::is_enum<T>::value )
2529 {
2531 {
2532 if( !attr->HasEditor() )
2533 attr->SetEditor( new GRID_CELL_COMBOBOX( getViewChoices( plotTab ) ) );
2534
2535 if( !attr->HasRenderer() )
2536 attr->SetRenderer( new GRID_CELL_COMBOBOX_RENDERER() );
2537
2538 attr->SetReadOnly( false );
2539 attr->SetTextColour( *wxLIGHT_GREY );
2540 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), getViewLabel( plotTab, nullptr ) );
2541 }
2547 {
2548 attr->SetEditor( nullptr );
2549 attr->SetRenderer( nullptr );
2550 attr->SetReadOnly();
2551 m_signalsGrid->SetCellValue( r, static_cast<int>( t ), wxEmptyString );
2552 }
2553 }
2554 }
2555}
2556
2557
2559{
2560 for( int row = 0; row < m_signalsGrid->GetNumberRows(); ++row )
2561 {
2567
2568 if( ( m_signalsGrid->GetNumberCols() - 1 ) > COL_CURSOR_2 )
2569 {
2570 for( int i = 3; i < m_customCursorsCnt; i++ )
2571 {
2572 int tm = i + 3;
2573 signalsGridCursorUpdate( static_cast<SIGNALS_GRID_COLUMNS>( tm ), i, row );
2574 }
2575 }
2576 }
2577 m_signalsGrid->Refresh();
2578}
2579
2580
2582{
2583 auto quoteNetNames =
2584 [&]( wxString aExpression ) -> wxString
2585 {
2586 std::vector<bool> mask( aExpression.length(), false );
2587
2588 auto isNetnameChar =
2589 []( wxUniChar aChar ) -> bool
2590 {
2591 wxUint32 value = aChar.GetValue();
2592
2593 if( ( value >= '0' && value <= '9' ) || ( value >= 'A' && value <= 'Z' )
2594 || ( value >= 'a' && value <= 'z' ) )
2595 {
2596 return true;
2597 }
2598
2599 switch( value )
2600 {
2601 case '_':
2602 case '/':
2603 case '+':
2604 case '-':
2605 case '~':
2606 case '.':
2607 return true;
2608 default:
2609 break;
2610 }
2611
2612 return false;
2613 };
2614
2615 for( const wxString& netname : m_netnames )
2616 {
2617 size_t pos = aExpression.find( netname );
2618
2619 while( pos != wxString::npos )
2620 {
2621 for( size_t i = 0; i < netname.length(); ++i )
2622 mask[pos + i] = true; // Mark the positions of the netname
2623
2624 pos = aExpression.find( netname, pos + 1 ); // Find the next occurrence
2625 }
2626 }
2627
2628 for( size_t i = 0; i < aExpression.length(); ++i )
2629 {
2630 if( !mask[i] || ( i > 0 && mask[i - 1] ) )
2631 continue;
2632
2633 size_t j = i + 1;
2634
2635 while( j < aExpression.length() )
2636 {
2637 if( mask[j] )
2638 {
2639 ++j;
2640 continue;
2641 }
2642
2643 if( isNetnameChar( aExpression[j] ) )
2644 {
2645 mask[j] = true;
2646 ++j;
2647 }
2648 else
2649 {
2650 break;
2651 }
2652 }
2653 }
2654
2655 wxString quotedNetnames = "";
2656 bool startQuote = true;
2657
2658 // put quotes around all the positions that were found above
2659 for( size_t i = 0; i < aExpression.length(); i++ )
2660 {
2661 if( mask[i] && startQuote )
2662 {
2663 quotedNetnames = quotedNetnames + "\"";
2664 startQuote = false;
2665 }
2666 else if( !mask[i] && !startQuote )
2667 {
2668 quotedNetnames = quotedNetnames + "\"";
2669 startQuote = true;
2670 }
2671
2672 wxString ch = aExpression[i];
2673 quotedNetnames = quotedNetnames + ch;
2674 }
2675
2676 if( !startQuote )
2677 quotedNetnames = quotedNetnames + "\"";
2678
2679 return quotedNetnames;
2680 };
2681
2682 for( const auto& [id, signal] : m_userDefinedSignals )
2683 {
2684 constexpr const char* cmd = "let user{} = {}";
2685
2686 simulator()->Command( "echo " + fmt::format( cmd, id, signal.ToStdString() ) );
2687 simulator()->Command( fmt::format( cmd, id, quoteNetNames( signal ).ToStdString() ) );
2688 }
2689}
2690
2691
2693{
2695
2696 for( const TUNER_SLIDER* tuner : m_tuners )
2697 {
2698 SCH_SHEET_PATH sheetPath;
2699 wxString ref = tuner->GetSymbolRef();
2700 KIID symbolId = tuner->GetSymbol( &sheetPath );
2701 SCH_ITEM* schItem = sheetPath.ResolveItem( symbolId );
2702 SCH_SYMBOL* symbol = dynamic_cast<SCH_SYMBOL*>( schItem );
2703
2704 if( !symbol )
2705 {
2706 reporter.Report( wxString::Format( _( "%s not found" ), ref ) );
2707 continue;
2708 }
2709
2710 const SPICE_ITEM* item = GetExporter()->FindItem( tuner->GetSymbolRef() );
2711
2712 if( !item || !item->model->GetTunerParam() )
2713 {
2714 reporter.Report( wxString::Format( _( "%s is not tunable" ), ref ) );
2715 continue;
2716 }
2717
2718 double floatVal;
2719
2720 auto overrideIt = m_tunerOverrides.find( tuner );
2721
2722 if( overrideIt != m_tunerOverrides.end() )
2723 floatVal = overrideIt->second;
2724 else
2725 floatVal = tuner->GetValue().ToDouble();
2726
2727 simulator()->Command( item->model->SpiceGenerator().TunerCommand( *item, floatVal ) );
2728 }
2729
2730 if( reporter.HasMessage() )
2731 DisplayErrorMessage( this, _( "Could not apply tuned value(s):" ) + wxS( "\n" ) + reporter.GetMessages() );
2732}
2733
2734bool SIMULATOR_FRAME_UI::LoadWorkbook( const wxString& aPath )
2735{
2736 wxTextFile file( aPath );
2737
2738 if( !file.Open() )
2739 return false;
2740
2741 wxString firstLine = file.GetFirstLine();
2742 long dummy;
2743 bool legacy = firstLine.StartsWith( wxT( "version " ) ) || firstLine.ToLong( &dummy );
2744
2745 file.Close();
2746
2747 m_plotNotebook->DeleteAllPages();
2748 m_userDefinedSignals.clear();
2749
2750 if( legacy )
2751 {
2752 if( !loadLegacyWorkbook( aPath ) )
2753 return false;
2754 }
2755 else
2756 {
2757 if( !loadJsonWorkbook( aPath ) )
2758 return false;
2759 }
2760
2762
2763 rebuildSignalsGrid( m_filter->GetValue() );
2767
2768 wxFileName filename( aPath );
2769 filename.MakeRelativeTo( m_schematicFrame->Prj().GetProjectPath() );
2770
2771 // Remember the loaded workbook filename.
2772 simulator()->Settings()->SetWorkbookFilename( filename.GetFullPath() );
2773
2774 return true;
2775}
2776
2777
2778bool SIMULATOR_FRAME_UI::loadJsonWorkbook( const wxString& aPath )
2779{
2780 wxFFileInputStream fp( aPath, wxT( "rt" ) );
2781 wxStdInputStream fstream( fp );
2782
2783 if( !fp.IsOk() )
2784 return false;
2785
2786 try
2787 {
2788 nlohmann::json js = nlohmann::json::parse( fstream, nullptr, true, true );
2789
2790 std::map<SIM_PLOT_TAB*, nlohmann::json> traceInfo;
2791
2792 for( const nlohmann::json& tab_js : js["tabs"] )
2793 {
2794 wxString simCommand;
2797
2798 if( !tab_js.contains( "commands" ) || !tab_js["commands"].is_array() )
2799 continue;
2800
2801 for( const nlohmann::json& cmd : tab_js[ "commands" ] )
2802 {
2803 if( cmd == ".kicad adjustpaths" )
2805 else if( cmd == ".save all" )
2807 else if( cmd == ".probe alli" )
2809 else if( cmd == ".probe allp" )
2811 else if( cmd == ".kicad esavenone" )
2812 simOptions &= ~NETLIST_EXPORTER_SPICE::OPTION_SAVE_ALL_EVENTS;
2813 else
2814 simCommand += wxString( cmd.get<wxString>() ).Trim();
2815 }
2816
2817 SIM_TAB* simTab = NewSimTab( simCommand );
2818 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( simTab );
2819
2820 simTab->SetSimOptions( simOptions );
2821
2822 if( plotTab )
2823 {
2824 int viewCount = tab_js.contains( "viewCount" ) ? (int) tab_js["viewCount"] : 1;
2825
2826 for( int ii = 1; ii < viewCount; ++ii )
2827 plotTab->AddView();
2828
2829 if( tab_js.contains( "traces" ) )
2830 traceInfo[plotTab] = tab_js["traces"];
2831
2832 if( tab_js.contains( "measurements" ) && tab_js["measurements"].is_array() )
2833 {
2834 for( const nlohmann::json& m_js : tab_js[ "measurements" ] )
2835 {
2836 plotTab->Measurements().emplace_back( wxString( m_js.value( "expr", "" ) ),
2837 wxString( m_js.value( "format", "" ) ) );
2838 }
2839 }
2840
2841 plotTab->SetDottedSecondary( tab_js.value( "dottedSecondary", false ) );
2842 plotTab->ShowGrid( tab_js.value( "showGrid", true ) );
2843 plotTab->EnableTrackCursor( tab_js.value( "showTrackCursor", false ) );
2844
2845 if( tab_js.value( "smithMode", false ) )
2846 {
2847 plotTab->SetSmithMode( true );
2848 plotTab->SetSmithView( tab_js.value( "smithZoom", 1.0 ),
2849 tab_js.value( "smithPanX", 0.0 ),
2850 tab_js.value( "smithPanY", 0.0 ) );
2851
2852 if( tab_js.contains( "smithStashedTraces" ) && tab_js["smithStashedTraces"].is_array() )
2853 {
2854 for( const nlohmann::json& stash_js : tab_js["smithStashedTraces"] )
2855 {
2856 wxString vector( stash_js.value( "vector", "" ) );
2857 wxString name( stash_js.value( "name", "" ) );
2858
2859 if( vector.IsEmpty() )
2860 continue;
2861
2862 plotTab->SmithStashedTraces().push_back( { vector,
2863 name.IsEmpty() ? vector : name,
2864 stash_js.value( "base_type", 0 ) } );
2865 }
2866 }
2867
2868 if( tab_js.contains( "smithStashedCursors" ) && tab_js["smithStashedCursors"].is_array() )
2869 {
2870 for( const nlohmann::json& stash_js : tab_js["smithStashedCursors"] )
2871 {
2872 wxString vector( stash_js.value( "vector", "" ) );
2873 int id = stash_js.value( "id", 0 );
2874
2875 if( vector.IsEmpty() || ( id < 1 && id != -1 ) )
2876 continue;
2877
2878 plotTab->SmithStashedCursors().push_back( { id,
2879 vector,
2880 stash_js.value( "base_type", 0 ),
2881 stash_js.value( "sub_type", 0 ),
2882 stash_js.value( "frequency",
2883 std::nan( "" ) ) } );
2884 }
2885 }
2886 }
2887
2888 auto loadScale =
2889 [&]( const char* aKey, auto&& aSetter )
2890 {
2891 if( !tab_js.contains( aKey ) )
2892 return;
2893
2894 // older workbooks can hold null here (non-finite bounds saved as json null)
2895 nlohmann::json min_js = tab_js[aKey].value( "min", nlohmann::json() );
2896 nlohmann::json max_js = tab_js[aKey].value( "max", nlohmann::json() );
2897
2898 if( !min_js.is_number() || !max_js.is_number() )
2899 return;
2900
2901 double min = min_js.get<double>();
2902 double max = max_js.get<double>();
2903
2904 if( min < max )
2905 aSetter( min, max );
2906 };
2907
2908 loadScale( "fixedY1scale",
2909 [&]( double min, double max )
2910 {
2911 plotTab->SetY1Scale( true, min, max );
2912 } );
2913
2914 loadScale( "fixedY2scale",
2915 [&]( double min, double max )
2916 {
2917 plotTab->SetY2Scale( true, min, max );
2918 } );
2919
2920 loadScale( "fixedY3scale",
2921 [&]( double min, double max )
2922 {
2923 plotTab->EnsureThirdYAxisExists();
2924 plotTab->SetY3Scale( true, min, max );
2925 } );
2926
2927 if( tab_js.contains( "legend" ) )
2928 {
2929 const nlohmann::json& legend_js = tab_js[ "legend" ];
2930 plotTab->SetLegendPosition( wxPoint( legend_js.value( "x", 0 ), legend_js.value( "y", 0 ) ) );
2931 plotTab->ShowLegend( true );
2932 }
2933
2934 if( tab_js.contains( "margins" ) )
2935 {
2936 const nlohmann::json& margins_js = tab_js[ "margins" ];
2937 plotTab->GetPlotWin()->SetMargins( margins_js.value( "top", 30 ),
2938 margins_js.value( "right", 70 ),
2939 margins_js.value( "bottom", 45 ),
2940 margins_js.value( "left", 70 ) );
2941 }
2942 }
2943 }
2944
2945 int ii = 0;
2946
2947 if( js.contains( "user_defined_signals" ) )
2948 {
2949 for( const nlohmann::json& signal_js : js["user_defined_signals"] )
2950 m_userDefinedSignals[ii++] = wxString( signal_js.get<wxString>() );
2951 }
2952
2953 if( SIM_TAB* simTab = GetCurrentSimTab() )
2954 {
2955 m_simulatorFrame->LoadSimulator( simTab->GetSimCommand(), simTab->GetSimOptions() );
2956
2957 if( SIM_TAB* firstTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( 0 ) ) )
2958 firstTab->SetLastSchTextSimCommand( wxString( js.value( "last_sch_text_sim_command", "" ) ) );
2959 }
2960
2961 // 2 is kind of virtual, for the initial loading of the new setting
2962 int tempCustomCursorsCnt = js.value( "custom_cursors", 2 );
2963
2964 if( ( tempCustomCursorsCnt > m_customCursorsCnt ) && m_customCursorsCnt > 2 )
2965 tempCustomCursorsCnt = 2 * tempCustomCursorsCnt - m_customCursorsCnt;
2966
2967 for( int yy = 0; yy <= ( tempCustomCursorsCnt - m_customCursorsCnt ); yy++ )
2969
2970 auto addCursor =
2971 [=, this]( SIM_PLOT_TAB* aPlotTab, TRACE* aTrace, const wxString& aSignalName,
2972 int aCursorId, const nlohmann::json& aCursor_js )
2973 {
2974 if( aCursorId >= 1 )
2975 {
2976 aPlotTab->EnableCursor( aTrace, aCursorId, aSignalName );
2977
2978 // tolerate a missing or null position from an older workbook saved
2979 // with a non-finite cursor coordinate
2980 nlohmann::json position = aCursor_js.value( "position", nlohmann::json() );
2981
2982 if( position.is_number() )
2983 {
2984 if( CURSOR* cursor = aTrace->GetCursor( aCursorId ) )
2985 cursor->SetCoordX( position.get<double>() );
2986 }
2987 }
2988
2989 wxString xFormat( aCursor_js.value( "x_format", "" ) );
2990 wxString yFormat( aCursor_js.value( "y_format", "" ) );
2991 int formatSlot;
2992
2993 if( aCursorId == -1 )
2994 formatSlot = 2; // we are a "cursorD"
2995 else if( aCursorId < 3 )
2996 formatSlot = aCursorId - 1;
2997 else
2998 formatSlot = aCursorId;
2999
3000 if( !xFormat.IsEmpty() )
3001 m_cursorFormatsDyn[formatSlot][0].FromString( xFormat );
3002
3003 if( !yFormat.IsEmpty() )
3004 m_cursorFormatsDyn[formatSlot][1].FromString( yFormat );
3005 };
3006
3007 for( const auto& [plotTab, traces_js] : traceInfo )
3008 {
3009 for( const nlohmann::json& trace_js : traces_js )
3010 {
3011 int traceType = trace_js.value( "trace_type", (int) SPT_UNKNOWN );
3012 wxString signalName( trace_js.value( "signal", "" ) );
3013
3014 if( signalName.IsEmpty() || traceType == SPT_UNKNOWN )
3015 continue;
3016
3017 wxString vectorName = vectorNameFromSignalName( plotTab, signalName, nullptr );
3018
3019 int viewIndex = trace_js.contains( "view" ) ? (int) trace_js["view"] : 0;
3020 SIM_VIEW* view = plotTab->GetView( viewIndex );
3021
3022 if( !view )
3023 view = plotTab->GetDefaultView();
3024
3025 TRACE* trace = plotTab->GetOrAddTrace( vectorName, traceType, view );
3026
3027 if( trace )
3028 {
3029 int yScaleIndex = trace_js.contains( "yScaleView" ) ? (int) trace_js["yScaleView"]
3030 : viewIndex;
3031
3032 if( SIM_VIEW* yScaleView = plotTab->GetView( yScaleIndex ) )
3033 trace->SetYScaleView( yScaleView );
3034
3035 if( trace_js.contains( "cursorD" ) )
3036 addCursor( plotTab, trace, signalName, -1, trace_js["cursorD"] );
3037
3038 std::vector<const char*> aVec;
3039 aVec.clear();
3040
3041 for( int i = 1; i <= tempCustomCursorsCnt; i++ )
3042 {
3043 wxString str = "cursor" + std::to_string( i );
3044 aVec.emplace_back( str.c_str() );
3045
3046 if( trace_js.contains( aVec[i - 1] ) )
3047 addCursor( plotTab, trace, signalName, i, trace_js[aVec[i - 1]] );
3048 }
3049
3050 if( trace_js.contains( "color" ) )
3051 {
3052 wxColour color;
3053 color.Set( wxString( trace_js["color"].get<wxString>() ) );
3054 trace->SetTraceColour( color );
3055 plotTab->UpdateTraceStyle( trace );
3056 }
3057 }
3058 }
3059
3060 plotTab->UpdatePlotColors();
3061 }
3062 }
3063 catch( nlohmann::json::parse_error& error )
3064 {
3065 wxLogTrace( traceSettings, wxT( "Json parse error reading %s: %s" ), aPath, error.what() );
3066
3067 return false;
3068 }
3069 catch( nlohmann::json::type_error& error )
3070 {
3071 wxLogTrace( traceSettings, wxT( "Json type error reading %s: %s" ), aPath, error.what() );
3072
3073 return false;
3074 }
3075 catch( nlohmann::json::invalid_iterator& error )
3076 {
3077 wxLogTrace( traceSettings, wxT( "Json invalid_iterator error reading %s: %s" ), aPath, error.what() );
3078
3079 return false;
3080 }
3081 catch( nlohmann::json::out_of_range& error )
3082 {
3083 wxLogTrace( traceSettings, wxT( "Json out_of_range error reading %s: %s" ), aPath, error.what() );
3084
3085 return false;
3086 }
3087 catch( ... )
3088 {
3089 wxLogTrace( traceSettings, wxT( "Error reading %s" ), aPath );
3090 return false;
3091 }
3092
3093 return true;
3094}
3095
3096void SIMULATOR_FRAME_UI::SaveCursorToWorkbook( nlohmann::json& aTraceJs, TRACE* aTrace, int aCursorId )
3097{
3098 int cursorIdAfterD = aCursorId;
3099
3100 if( aCursorId > 3 )
3101 cursorIdAfterD = cursorIdAfterD - 1;
3102
3103
3104 if( CURSOR* cursor = aTrace->GetCursor( aCursorId ) )
3105 {
3106 nlohmann::json cursor_js =
3107 nlohmann::json( { { "x_format", m_cursorFormatsDyn[cursorIdAfterD][0].ToString() },
3108 { "y_format", m_cursorFormatsDyn[cursorIdAfterD][1].ToString() } } );
3109
3110 // json serializes a non-finite double as null, which would poison the load,
3111 // leave the position out instead and the loader keeps its default placement
3112 double position = cursor->GetCoords().x;
3113
3114 if( std::isfinite( position ) )
3115 cursor_js["position"] = position;
3116
3117 aTraceJs["cursor" + wxString( "" ) << aCursorId] = cursor_js;
3118 }
3119
3120 if( cursorIdAfterD < 3 && ( aTrace->GetCursor( 1 ) || aTrace->GetCursor( 2 ) ) )
3121 {
3122 aTraceJs["cursorD"] = nlohmann::json( { { "x_format", m_cursorFormatsDyn[2][0].ToString() },
3123 { "y_format", m_cursorFormatsDyn[2][1].ToString() } } );
3124 }
3125}
3126
3127
3128bool SIMULATOR_FRAME_UI::SaveWorkbook( const wxString& aPath )
3129{
3131
3132 wxFileName filename = aPath;
3133 filename.SetExt( FILEEXT::WorkbookFileExtension );
3134
3135 wxFile file;
3136
3137 file.Create( filename.GetFullPath(), true /* overwrite */ );
3138
3139 if( !file.IsOpened() )
3140 return false;
3141
3142 nlohmann::json tabs_js = nlohmann::json::array();
3143
3144 for( size_t i = 0; i < m_plotNotebook->GetPageCount(); i++ )
3145 {
3146 SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( i ) );
3147
3148 if( !simTab )
3149 continue;
3150
3151 SIM_TYPE simType = simTab->GetSimType();
3152
3153 nlohmann::json commands_js = nlohmann::json::array();
3154
3155 commands_js.push_back( simTab->GetSimCommand() );
3156
3157 int options = simTab->GetSimOptions();
3158
3160 commands_js.push_back( ".kicad adjustpaths" );
3161
3163 commands_js.push_back( ".save all" );
3164
3166 commands_js.push_back( ".probe alli" );
3167
3169 commands_js.push_back( ".probe allp" );
3170
3172 commands_js.push_back( ".kicad esavenone" );
3173
3174 nlohmann::json tab_js = nlohmann::json( { { "analysis", SPICE_SIMULATOR::TypeToName( simType, true ) },
3175 { "commands", commands_js } } );
3176
3177 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( simTab ) )
3178 {
3179 nlohmann::json traces_js = nlohmann::json::array();
3180
3181 auto findSignalName =
3182 [&]( const wxString& aVectorName ) -> wxString
3183 {
3184 wxString vectorName;
3185 wxString suffix;
3186
3187 if( aVectorName.EndsWith( _( " (phase)" ) ) )
3188 suffix = _( " (phase)" );
3189 else if( aVectorName.EndsWith( _( " (gain)" ) ) )
3190 suffix = _( " (gain)" );
3191
3192 vectorName = aVectorName.Left( aVectorName.Length() - suffix.Length() );
3193
3194 for( const auto& [id, signal] : m_userDefinedSignals )
3195 {
3196 if( vectorName == vectorNameFromSignalId( id ) )
3197 return signal + suffix;
3198 }
3199
3200 return aVectorName;
3201 };
3202
3203 for( const auto& [name, trace] : plotTab->GetTraces() )
3204 {
3205 nlohmann::json trace_js =
3206 nlohmann::json( { { "trace_type", (int) trace->GetType() },
3207 { "signal", findSignalName( trace->GetDisplayName() ) },
3208 { "color", COLOR4D( trace->GetTraceColour() ).ToCSSString() },
3209 { "view", plotTab->GetViewIndex( trace->GetView() ) },
3210 { "yScaleView", plotTab->GetViewIndex( trace->GetYScaleView() ) } } );
3211
3212 for( int ii = 1; ii <= m_customCursorsCnt; ii++ )
3213 SaveCursorToWorkbook( trace_js, trace, ii );
3214
3215 if( trace->GetCursor( 1 ) || trace->GetCursor( 2 ) )
3216 {
3217 trace_js["cursorD"] = nlohmann::json( { { "x_format", m_cursorFormatsDyn[2][0].ToString() },
3218 { "y_format", m_cursorFormatsDyn[2][1].ToString() } } );
3219 }
3220
3221 traces_js.push_back( trace_js );
3222 }
3223
3224 nlohmann::json measurements_js = nlohmann::json::array();
3225
3226 for( const auto& [measurement, format] : plotTab->Measurements() )
3227 {
3228 measurements_js.push_back( nlohmann::json( { { "expr", measurement },
3229 { "format", format } } ) );
3230 }
3231
3232 tab_js[ "traces" ] = traces_js;
3233 tab_js[ "measurements" ] = measurements_js;
3234 tab_js[ "dottedSecondary" ] = plotTab->GetDottedSecondary();
3235 tab_js[ "showGrid" ] = plotTab->IsGridShown();
3236 tab_js[ "smithMode" ] = plotTab->IsSmithMode();
3237
3238 if( plotTab->IsSmithMode() )
3239 {
3240 tab_js["smithZoom"] = plotTab->GetSmithZoom();
3241 tab_js["smithPanX"] = plotTab->GetSmithPan().x;
3242 tab_js["smithPanY"] = plotTab->GetSmithPan().y;
3243
3244 // traces and cursors the smith toggle set aside, saved so a workbook
3245 // written in smith mode does not lose them across a reload
3246 nlohmann::json stashedTraces_js = nlohmann::json::array();
3247
3248 for( const SMITH_STASHED_TRACE& stashed : plotTab->SmithStashedTraces() )
3249 {
3250 stashedTraces_js.push_back( nlohmann::json( { { "vector", stashed.vectorName },
3251 { "name", stashed.displayName },
3252 { "base_type", stashed.baseType } } ) );
3253 }
3254
3255 if( !stashedTraces_js.empty() )
3256 tab_js["smithStashedTraces"] = stashedTraces_js;
3257
3258 nlohmann::json stashedCursors_js = nlohmann::json::array();
3259
3260 for( const SMITH_STASHED_CURSOR& stashed : plotTab->SmithStashedCursors() )
3261 {
3262 nlohmann::json cursor_js = nlohmann::json( { { "id", stashed.id },
3263 { "vector", stashed.vectorName },
3264 { "base_type", stashed.baseType },
3265 { "sub_type", stashed.subType } } );
3266
3267 if( std::isfinite( stashed.frequency ) )
3268 cursor_js["frequency"] = stashed.frequency;
3269
3270 stashedCursors_js.push_back( cursor_js );
3271 }
3272
3273 if( !stashedCursors_js.empty() )
3274 tab_js["smithStashedCursors"] = stashedCursors_js;
3275 }
3276
3277 tab_js["viewCount"] = plotTab->GetViewCount();
3278 tab_js["showTrackCursor"] = plotTab->IsTrackCursorEnabled();
3279
3280 double min, max;
3281
3282 // json serializes a non-finite double as null, which would poison the load
3283 auto saveScale =
3284 [&]( const char* aKey, double aMin, double aMax )
3285 {
3286 if( std::isfinite( aMin ) && std::isfinite( aMax ) )
3287 tab_js[aKey] = nlohmann::json( { { "min", aMin }, { "max", aMax } } );
3288 };
3289
3290 if( plotTab->GetY1Scale( &min, &max ) )
3291 saveScale( "fixedY1scale", min, max );
3292
3293 if( plotTab->GetY2Scale( &min, &max ) )
3294 saveScale( "fixedY2scale", min, max );
3295
3296 if( plotTab->GetY3Scale( &min, &max ) )
3297 saveScale( "fixedY3scale", min, max );
3298
3299 if( plotTab->IsLegendShown() )
3300 {
3301 tab_js["legend"] = nlohmann::json( { { "x", plotTab->GetLegendPosition().x },
3302 { "y", plotTab->GetLegendPosition().y } } );
3303 }
3304
3305 mpWindow* plotWin = plotTab->GetPlotWin();
3306
3307 tab_js["margins"] = nlohmann::json( { { "left", plotWin->GetMarginLeft() },
3308 { "right", plotWin->GetMarginRight() },
3309 { "top", plotWin->GetMarginTop() },
3310 { "bottom", plotWin->GetMarginBottom() } } );
3311 }
3312
3313 tabs_js.push_back( tab_js );
3314 }
3315
3316 nlohmann::json userDefinedSignals_js = nlohmann::json::array();
3317
3318 for( const auto& [id, signal] : m_userDefinedSignals )
3319 userDefinedSignals_js.push_back( signal );
3320
3321 // clang-format off
3322 nlohmann::json js = nlohmann::json( { { "version", 8 },
3323 { "tabs", tabs_js },
3324 { "user_defined_signals", userDefinedSignals_js },
3325 { "custom_cursors", m_customCursorsCnt - 1 } } ); // Since we start +1 on init
3326 // clang-format on
3327
3328 // Store the value of any simulation command found on the schematic sheet in a SCH_TEXT
3329 // object. If this changes we want to warn the user and ask them if they want to update
3330 // the corresponding panel's sim command.
3331 if( m_plotNotebook->GetPageCount() > 0 )
3332 {
3333 SIM_TAB* simTab = dynamic_cast<SIM_TAB*>( m_plotNotebook->GetPage( 0 ) );
3334 js["last_sch_text_sim_command"] = simTab->GetLastSchTextSimCommand();
3335 }
3336
3337 std::stringstream buffer;
3338 buffer << std::setw( 2 ) << js << std::endl;
3339
3340 bool res = file.Write( buffer.str() );
3341 file.Close();
3342
3343 // Store the filename of the last saved workbook.
3344 if( res )
3345 {
3346 filename.MakeRelativeTo( m_schematicFrame->Prj().GetProjectPath() );
3347 simulator()->Settings()->SetWorkbookFilename( filename.GetFullPath() );
3348 }
3349
3350 return res;
3351}
3352
3353
3355{
3356 switch( aType )
3357 {
3359 case ST_AC: return SPT_LIN_FREQUENCY;
3360 case ST_SP: return SPT_LIN_FREQUENCY;
3361 case ST_FFT: return SPT_LIN_FREQUENCY;
3362 case ST_DC: return SPT_SWEEP;
3363 case ST_TRAN: return SPT_TIME;
3364 case ST_NOISE: return SPT_LIN_FREQUENCY;
3365
3366 default:
3367 wxFAIL_MSG( wxString::Format( wxS( "Unhandled simulation type: %d" ), (int) aType ) );
3368 return SPT_UNKNOWN;
3369 }
3370}
3371
3372
3374{
3375 wxString output;
3376 wxString ref;
3377 wxString source;
3378 wxString scale;
3379 SPICE_VALUE pts;
3380 SPICE_VALUE fStart;
3381 SPICE_VALUE fStop;
3382 bool saveAll;
3383
3384 if( GetCurrentSimTab() )
3385 {
3386 circuitModel()->ParseNoiseCommand( GetCurrentSimTab()->GetSimCommand(), &output, &ref, &source, &scale, &pts,
3387 &fStart, &fStop, &saveAll );
3388 }
3389
3390 return source;
3391}
3392
3393
3394void SIMULATOR_FRAME_UI::TogglePanel( wxPanel* aPanel, wxSplitterWindow* aSplitterWindow, int& aSashPosition )
3395{
3396 bool isShown = aPanel->IsShown();
3397
3398 if( isShown )
3399 aSashPosition = aSplitterWindow->GetSashPosition();
3400
3401 aPanel->Show( !isShown );
3402
3403 aSplitterWindow->SetSashInvisible( isShown );
3404 aSplitterWindow->SetSashPosition( isShown ? -1 : aSashPosition, true );
3405
3406 aSplitterWindow->UpdateSize();
3407 m_parent->Refresh();
3408 m_parent->Layout();
3409}
3410
3411
3413{
3414 return m_panelConsole->IsShown();
3415}
3416
3417
3422
3423
3425{
3426 return m_sidePanel->IsShown();
3427}
3428
3429
3434
3435
3437{
3439
3440 // Rebuild the color list to plot traces
3442
3443 // Now send changes to all SIM_PLOT_TAB
3444 for( size_t page = 0; page < m_plotNotebook->GetPageCount(); page++ )
3445 {
3446 wxWindow* curPage = m_plotNotebook->GetPage( page );
3447
3448 // ensure it is truly a plot plotTab and not the (zero plots) placeholder
3449 // which is only SIM_TAB
3450 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( curPage );
3451
3452 if( plotTab )
3453 plotTab->UpdatePlotColors();
3454 }
3455}
3456
3457
3459{
3460 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
3461
3462 if( !plotTab || plotTab->GetSimType() != ST_SP )
3463 return;
3464
3465 bool smithMode = !plotTab->IsSmithMode();
3466
3467 // collect the shown signals, then rebuild their traces in the new coordinate system,
3468 // keyed by vector name since user-defined traces are renamed to their display text
3469 struct SHOWN_VECTOR
3470 {
3471 wxString vectorName;
3472 wxString displayName;
3473 int baseType;
3474 SIM_VIEW* view; // the view it was plotted on, so the rebuild stays where it was
3475 };
3476
3477 std::vector<SHOWN_VECTOR> shownVectors;
3478
3479 // remember cursors so they survive the rebuild
3480 struct SAVED_CURSOR
3481 {
3482 int id;
3483 wxString vectorName;
3484 int baseType;
3485 int subType; // the SP subtype the cursor lived on
3486 double coordX;
3487 };
3488
3489 std::vector<SAVED_CURSOR> savedCursors;
3490
3491 for( const auto& [id, trace] : plotTab->GetTraces() )
3492 {
3493 int baseType = SPT_UNKNOWN;
3494 wxString vectorName = vectorNameFromSignalName( plotTab, trace->GetName(), &baseType );
3495 bool seen = false;
3496 int subType = trace->GetType() & ( SPT_SP_AMP | SPT_AC_PHASE | SPT_SP_SMITH );
3497
3498 baseType &= ~( SPT_SP_MASK | SPT_AC_GAIN );
3499
3500 for( const SHOWN_VECTOR& sv : shownVectors )
3501 seen |= sv.vectorName == vectorName;
3502
3503 if( !seen )
3504 shownVectors.push_back( { vectorName, trace->GetName(), baseType, trace->GetView() } );
3505
3506 for( const auto& [cursorId, cursor] : trace->GetCursors() )
3507 {
3508 if( cursor )
3509 savedCursors.push_back( { cursorId, vectorName, baseType, subType, cursor->GetCoords().x } );
3510 }
3511 }
3512
3513 // a transmission S-parameter (S_i_j, i != j) is not an impedance, drop it from the chart
3514 auto isReflection =
3515 []( const wxString& aName ) -> bool
3516 {
3517 long response, drive;
3518
3519 if( SMITH_MATH::ParseSParamPorts( aName, &response, &drive ) )
3520 return response == drive;
3521
3522 return true;
3523 };
3524
3525 std::vector<SMITH_STASHED_TRACE>& stashedTraces = plotTab->SmithStashedTraces();
3526 std::vector<SMITH_STASHED_CURSOR>& stashedCursors = plotTab->SmithStashedCursors();
3527
3528 if( smithMode )
3529 {
3530 // set aside what the Smith view cannot show, so leaving the mode restores it
3531 stashedTraces.clear();
3532 stashedCursors.clear();
3533
3534 for( const SHOWN_VECTOR& sv : shownVectors )
3535 {
3536 if( !isReflection( sv.vectorName ) )
3537 stashedTraces.push_back( { sv.vectorName, sv.displayName, sv.baseType } );
3538 }
3539
3540 for( const SAVED_CURSOR& saved : savedCursors )
3541 stashedCursors.push_back( { saved.id, saved.vectorName, saved.baseType, saved.subType, saved.coordX } );
3542 }
3543 else
3544 {
3545 // bring the stashed transmission traces back into the rebuild list
3546 for( const SMITH_STASHED_TRACE& stashed : stashedTraces )
3547 {
3548 bool seen = false;
3549
3550 for( const SHOWN_VECTOR& sv : shownVectors )
3551 seen |= sv.vectorName == stashed.vectorName;
3552
3553 if( !seen )
3554 {
3555 shownVectors.push_back( { stashed.vectorName, stashed.displayName, stashed.baseType,
3556 plotTab->GetDefaultView() } );
3557 }
3558 }
3559 }
3560
3561 for( const SHOWN_VECTOR& sv : shownVectors )
3562 {
3563 for( int subType : { SPT_SP_AMP, SPT_AC_PHASE, SPT_SP_SMITH } )
3564 plotTab->DeleteTrace( sv.vectorName, sv.baseType | subType );
3565 }
3566
3567 plotTab->SetSmithMode( smithMode );
3568
3569 for( const SHOWN_VECTOR& sv : shownVectors )
3570 {
3571 std::vector<int> subTypes;
3572
3573 if( smithMode )
3574 {
3575 if( !isReflection( sv.vectorName ) )
3576 continue;
3577
3578 subTypes = { SPT_SP_SMITH };
3579 }
3580 else
3581 {
3582 subTypes = { SPT_SP_AMP, SPT_AC_PHASE };
3583 }
3584
3585 for( int subType : subTypes )
3586 {
3587 updateTrace( sv.vectorName, sv.baseType | subType, plotTab, nullptr, false, sv.view );
3588
3589 if( TRACE* trace = plotTab->GetTrace( sv.vectorName, sv.baseType | subType ) )
3590 trace->SetName( sv.displayName );
3591 }
3592 }
3593
3594 // restore cursors on the rebuilt traces at the same frequency
3595 if( smithMode )
3596 {
3597 for( const SAVED_CURSOR& saved : savedCursors )
3598 {
3599 TRACE* trace = plotTab->GetTrace( saved.vectorName, saved.baseType | SPT_SP_SMITH );
3600
3601 // amplitude and phase cursors with the same id collapse onto one locus marker,
3602 // keep the first, the stash remembers both for the way back
3603 if( !trace || trace->GetCursor( saved.id ) )
3604 continue;
3605
3606 plotTab->EnableCursor( trace, saved.id, trace->GetName() );
3607
3608 if( CURSOR* cursor = trace->GetCursor( saved.id ) )
3609 {
3610 if( std::isfinite( saved.coordX ) )
3611 cursor->SetCoordX( saved.coordX );
3612 }
3613 }
3614 }
3615 else
3616 {
3617 auto findStashed =
3618 [&]( int aId, const wxString& aVectorName ) -> const SMITH_STASHED_CURSOR*
3619 {
3620 for( const SMITH_STASHED_CURSOR& stashed : stashedCursors )
3621 {
3622 if( stashed.id == aId && stashed.vectorName == aVectorName )
3623 return &stashed;
3624 }
3625
3626 return nullptr;
3627 };
3628
3629 auto restoreCursor =
3630 [&]( int aId, const wxString& aVectorName, int aBaseType, int aSubType, double aFreq ) -> bool
3631 {
3632 int wantSubType = aSubType == SPT_AC_PHASE ? SPT_AC_PHASE : SPT_SP_AMP;
3633
3634 if( TRACE* trace = plotTab->GetTrace( aVectorName, aBaseType | wantSubType ) )
3635 {
3636 plotTab->EnableCursor( trace, aId, trace->GetName() );
3637
3638 // a stash entry without a usable frequency keeps the default placement
3639 if( std::isfinite( aFreq ) )
3640 {
3641 if( CURSOR* cursor = trace->GetCursor( aId ) )
3642 cursor->SetCoordX( aFreq );
3643 }
3644
3645 return true;
3646 }
3647
3648 return false;
3649 };
3650
3651 std::vector<int> restoredIds;
3652
3653 // live smith cursors go back to the subtype they came from, at their current frequency
3654 for( const SAVED_CURSOR& saved : savedCursors )
3655 {
3656 const SMITH_STASHED_CURSOR* stashed = findStashed( saved.id, saved.vectorName );
3657
3658 if( restoreCursor( saved.id, saved.vectorName, saved.baseType,
3659 stashed ? stashed->subType : SPT_SP_AMP, saved.coordX ) )
3660 {
3661 restoredIds.push_back( saved.id );
3662 }
3663 }
3664
3665 // cursors whose trace could not exist in Smith mode come back from the stash alone,
3666 // unless the same cursor id was moved to another trace while in smith mode
3667 for( const SMITH_STASHED_CURSOR& stashed : stashedCursors )
3668 {
3669 if( isReflection( stashed.vectorName ) )
3670 continue;
3671
3672 if( std::find( restoredIds.begin(), restoredIds.end(), stashed.id ) != restoredIds.end() )
3673 continue;
3674
3675 restoreCursor( stashed.id, stashed.vectorName, stashed.baseType, stashed.subType, stashed.frequency );
3676 }
3677
3678 stashedTraces.clear();
3679 stashedCursors.clear();
3680 }
3681
3682 for( SIM_VIEW* view : plotTab->GetViews() )
3683 view->UpdateAll();
3684
3686 rebuildSignalsGrid( m_filter->GetValue() );
3689 OnModify();
3690}
3691
3692
3693void SIMULATOR_FRAME_UI::onPlotClose( wxAuiNotebookEvent& event )
3694{
3695 OnModify();
3696}
3697
3698
3699void SIMULATOR_FRAME_UI::onPlotClosed( wxAuiNotebookEvent& event )
3700{
3701 CallAfter( [this]()
3702 {
3704 rebuildSignalsGrid( m_filter->GetValue() );
3706
3707 //To avoid a current side effect in dynamic cursors while closing one out of many sim tabs
3709
3710 SIM_TAB* panel = GetCurrentSimTab();
3711
3712 if( !panel || panel->GetSimType() != ST_OP )
3713 {
3714 SCHEMATIC& schematic = m_schematicFrame->Schematic();
3715 schematic.ClearOperatingPoints();
3716 m_schematicFrame->RefreshOperatingPointDisplay();
3717 m_schematicFrame->GetCanvas()->Refresh();
3718 }
3719 } );
3720}
3721
3722
3724{
3725 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
3726 {
3727 std::vector<std::pair<wxString, wxString>>& measurements = plotTab->Measurements();
3728
3729 measurements.clear();
3730
3731 for( int row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
3732 {
3733 if( !m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ).IsEmpty() )
3734 {
3735 measurements.emplace_back( m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT ),
3736 m_measurementsGrid->GetCellValue( row, COL_MEASUREMENT_FORMAT ) );
3737 }
3738 }
3739 }
3740}
3741
3742
3743void SIMULATOR_FRAME_UI::onPlotChanging( wxAuiNotebookEvent& event )
3744{
3745 m_measurementsGrid->ClearRows();
3746
3747 event.Skip();
3748}
3749
3750
3752{
3754 rebuildSignalsGrid( m_filter->GetValue() );
3756
3758
3759 for( int row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
3760 UpdateMeasurement( row );
3761}
3762
3763
3764void SIMULATOR_FRAME_UI::onPlotChanged( wxAuiNotebookEvent& event )
3765{
3766 if( SIM_TAB* simTab = GetCurrentSimTab() )
3767 simulator()->Command( "setplot " + simTab->GetSpicePlotName().ToStdString() );
3768
3770
3771 //To avoid a current side effect in dynamic cursors while switching sim tabs
3773
3774 event.Skip();
3775}
3776
3777
3779{
3780 m_measurementsGrid->ClearRows();
3781
3782 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
3783 {
3784 for( const auto& [measurement, format] : plotTab->Measurements() )
3785 {
3786 int row = m_measurementsGrid->GetNumberRows();
3787 m_measurementsGrid->AppendRows();
3788 m_measurementsGrid->SetCellValue( row, COL_MEASUREMENT, measurement );
3789 m_measurementsGrid->SetCellValue( row, COL_MEASUREMENT_FORMAT, format );
3790 }
3791
3792 if( plotTab->GetSimType() == ST_TRAN || plotTab->GetSimType() == ST_AC || plotTab->GetSimType() == ST_DC
3793 || plotTab->GetSimType() == ST_SP )
3794 {
3795 m_measurementsGrid->AppendRows(); // Empty row at end
3796 }
3797 }
3798
3801}
3802
3803
3804void SIMULATOR_FRAME_UI::onPlotDragged( wxAuiNotebookEvent& event )
3805{
3806}
3807
3808
3809std::shared_ptr<SPICE_SIMULATOR> SIMULATOR_FRAME_UI::simulator() const
3810{
3811 return m_simulatorFrame->GetSimulator();
3812}
3813
3814
3815std::shared_ptr<SPICE_CIRCUIT_MODEL> SIMULATOR_FRAME_UI::circuitModel() const
3816{
3817 return m_simulatorFrame->GetCircuitModel();
3818}
3819
3820
3822{
3823 if( aSmithMode == smithColumnsShown( m_cursorsGrid ) )
3824 return;
3825
3826 if( aSmithMode )
3827 {
3828 m_cursorsGrid->AppendCols( SMITH_CURSOR_COLS );
3829
3830 for( int col = COL_CURSOR_SMITH_FIRST; col < COL_CURSOR_SMITH_END; ++col )
3831 {
3832 wxGridCellAttr* attr = new wxGridCellAttr;
3833 attr->SetReadOnly();
3834 m_cursorsGrid->SetColAttr( col, attr );
3835 }
3836
3837 // the panel is narrow, so keep the added columns off the horizontal scrollbar
3838 m_cursorsGrid->SetColSize( COL_CURSOR_R, 80 );
3839 m_cursorsGrid->SetColSize( COL_CURSOR_REACTANCE, 80 );
3840 m_cursorsGrid->SetColSize( COL_CURSOR_RL, 85 );
3841 m_cursorsGrid->SetColSize( COL_CURSOR_VSWR, 55 );
3842
3843 // a hidden column reports zero, so only a width the user really dragged overrides
3844 for( size_t ii = 0; ii < m_smithCursorWidths.size(); ++ii )
3845 {
3846 if( m_smithCursorWidths[ii] > 0 )
3847 m_cursorsGrid->SetColSize( COL_CURSOR_SMITH_FIRST + (int) ii, m_smithCursorWidths[ii] );
3848 }
3849
3852 }
3853 else
3854 {
3856
3857 // DeleteCols would otherwise throw away anything the user dragged
3858 m_smithCursorWidths.clear();
3859
3860 for( int col = COL_CURSOR_SMITH_FIRST; col < COL_CURSOR_SMITH_END; ++col )
3861 m_smithCursorWidths.push_back( m_cursorsGrid->GetColSize( col ) );
3862
3864 }
3865}
3866
3867
3869{
3871 return;
3872
3873 m_cursorsGrid->SetColLabelValue( COL_CURSOR_R, wxS( "R" ) );
3874 m_cursorsGrid->SetColLabelValue( COL_CURSOR_REACTANCE, wxS( "X" ) );
3875 m_cursorsGrid->SetColLabelValue( COL_CURSOR_RL, _( "Return loss" ) );
3876 m_cursorsGrid->SetColLabelValue( COL_CURSOR_VSWR, wxS( "VSWR" ) );
3877}
3878
3879
3881{
3882 // only the Smith columns, so hiding one cannot follow the user onto a non-Smith tab
3883 m_smithCursorColumns.Empty();
3884
3885 for( int col = COL_CURSOR_SMITH_FIRST; col < COL_CURSOR_SMITH_END; ++col )
3886 {
3887 if( !m_cursorsGrid->IsColShown( col ) )
3889 }
3890}
3891
3892
3894{
3895 wxStringTokenizer tokens( m_smithCursorColumns, wxS( " " ), wxTOKEN_STRTOK );
3896
3897 while( tokens.HasMoreTokens() )
3898 {
3899 long offset;
3900
3901 if( tokens.GetNextToken().ToLong( &offset ) && offset >= 0 && offset < SMITH_CURSOR_COLS )
3902 m_cursorsGrid->HideCol( COL_CURSOR_SMITH_FIRST + (int) offset );
3903 }
3904}
3905
3906
3907void SIMULATOR_FRAME_UI::fillSmithCursorRow( int aRow, CURSOR* aCursor, TRACE* aTrace )
3908{
3909 SMITH_CURSOR* smithCursor = dynamic_cast<SMITH_CURSOR*>( aCursor );
3910 SMITH_TRACE* smithTrace = dynamic_cast<SMITH_TRACE*>( aTrace );
3911
3912 if( !smithCursor || !smithTrace )
3913 return;
3914
3915 for( int col = COL_CURSOR_SMITH_FIRST; col < COL_CURSOR_SMITH_END; ++col )
3916 m_cursorsGrid->SetCellValue( aRow, col, wxS( "--" ) );
3917
3918 // gamma sits at the origin until the trace has a locus to snap to, which would read as a
3919 // perfect match rather than as no answer
3920 if( smithTrace->GetDataX().empty() )
3921 return;
3922
3923 const wxRealPoint& gamma = smithCursor->GetGamma();
3924 double z0 = smithTrace->GetReferenceImpedance();
3925 double zr, zi;
3926 const SPICE_VALUE_FORMAT ohms = { 3, wxS( "~Ω" ) };
3927
3928 // ohms need the port impedance, the match figures only need the magnitude
3929 if( z0 > 0.0 && SMITH_MATH::GammaToImpedance( gamma.x, gamma.y, z0, zr, zi ) )
3930 {
3931 m_cursorsGrid->SetCellValue( aRow, COL_CURSOR_R, SPICE_VALUE( zr ).ToString( ohms ) );
3932 m_cursorsGrid->SetCellValue( aRow, COL_CURSOR_REACTANCE, SPICE_VALUE( zi ).ToString( ohms ) );
3933 }
3934
3935 double gm = std::hypot( gamma.x, gamma.y );
3936 double rl = SMITH_MATH::ReturnLoss( gm );
3937 double vswr = SMITH_MATH::VSWR( gm );
3938
3939 if( std::isfinite( rl ) )
3940 m_cursorsGrid->SetCellValue( aRow, COL_CURSOR_RL, wxString::Format( wxS( "%.1f dB" ), rl ) );
3941 else if( std::isinf( rl ) )
3942 m_cursorsGrid->SetCellValue( aRow, COL_CURSOR_RL, wxS( "inf dB" ) );
3943
3944 if( std::isfinite( vswr ) )
3945 m_cursorsGrid->SetCellValue( aRow, COL_CURSOR_VSWR, wxString::Format( wxS( "%.2f" ), vswr ) );
3946 else if( std::isinf( vswr ) )
3947 m_cursorsGrid->SetCellValue( aRow, COL_CURSOR_VSWR, wxS( "inf" ) );
3948}
3949
3950
3952{
3953 SUPPRESS_GRID_CELL_EVENTS raii( this );
3954
3955 m_cursorsGrid->ClearRows();
3956
3957 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() );
3958
3959 if( !plotTab )
3960 {
3961 updateSmithCursorColumns( false );
3962 return;
3963 }
3964
3965 updateSmithCursorColumns( plotTab->GetSimType() == ST_SP && plotTab->IsSmithMode() );
3966
3967 // Update cursor values
3968 CURSOR* cursor1 = nullptr;
3969 wxString cursor1Name;
3970 wxString cursor1Units;
3971 CURSOR* cursor2 = nullptr;
3972 wxString cursor2Name;
3973 wxString cursor2Units;
3974
3975 auto getUnitsY =
3976 [&]( TRACE* aTrace ) -> wxString
3977 {
3978 // a smith cursor's y is the reflection coefficient magnitude, unitless
3979 if( aTrace->GetType() & SPT_SP_SMITH )
3980 return wxString();
3981
3982 if( plotTab->GetSimType() == ST_AC )
3983 {
3984 if( aTrace->GetType() & SPT_AC_PHASE )
3985 return plotTab->GetUnitsY2();
3986 else
3987 return plotTab->GetUnitsY1();
3988 }
3989 else
3990 {
3991 if( aTrace->GetType() & SPT_POWER )
3992 return plotTab->GetUnitsY3();
3993 else if( aTrace->GetType() & SPT_CURRENT )
3994 return plotTab->GetUnitsY2();
3995 else
3996 return plotTab->GetUnitsY1();
3997 }
3998 };
3999
4000 auto getNameY =
4001 [&]( TRACE* aTrace ) -> wxString
4002 {
4003 if( aTrace->GetType() & SPT_SP_SMITH )
4004 return _( "Refl. Coeff." );
4005
4006 if( plotTab->GetSimType() == ST_AC )
4007 {
4008 if( aTrace->GetType() & SPT_AC_PHASE )
4009 return plotTab->GetLabelY2();
4010 else
4011 return plotTab->GetLabelY1();
4012 }
4013 else
4014 {
4015 if( aTrace->GetType() & SPT_POWER )
4016 return plotTab->GetLabelY3();
4017 else if( aTrace->GetType() & SPT_CURRENT )
4018 return plotTab->GetLabelY2();
4019 else
4020 return plotTab->GetLabelY1();
4021 }
4022 };
4023
4024 auto formatValue =
4025 [this]( double aValue, int aCursorId, int aCol ) -> wxString
4026 {
4027 if( ( !m_simulatorFrame->SimFinished() && aCol == 1 ) || std::isnan( aValue ) )
4028 return wxS( "--" );
4029 else
4030 return SPICE_VALUE( aValue ).ToString( m_cursorFormatsDyn[aCursorId][aCol] );
4031 };
4032
4033 for( const auto& [name, trace] : plotTab->GetTraces() )
4034 {
4035 if( CURSOR* cursor = trace->GetCursor( 1 ) )
4036 {
4037 cursor1 = cursor;
4038 cursor1Name = getNameY( trace );
4039 cursor1Units = getUnitsY( trace );
4040
4041 wxRealPoint coords = cursor->GetCoords();
4042 int row = m_cursorsGrid->GetNumberRows();
4043
4044 m_cursorFormatsDyn[0][0].UpdateUnits( plotTab->GetUnitsX() );
4045 m_cursorFormatsDyn[0][1].UpdateUnits( cursor1Units );
4046
4047 m_cursorsGrid->AppendRows( 1 );
4048 m_cursorsGrid->SetCellValue( row, COL_CURSOR_NAME, wxS( "1" ) );
4049 m_cursorsGrid->SetCellValue( row, COL_CURSOR_SIGNAL, cursor->GetName() );
4050 m_cursorsGrid->SetCellValue( row, COL_CURSOR_X, formatValue( coords.x, 0, 0 ) );
4051 m_cursorsGrid->SetCellValue( row, COL_CURSOR_Y, formatValue( coords.y, 0, 1 ) );
4052 fillSmithCursorRow( row, cursor, trace );
4053 break;
4054 }
4055 }
4056
4057 for( const auto& [name, trace] : plotTab->GetTraces() )
4058 {
4059 if( CURSOR* cursor = trace->GetCursor( 2 ) )
4060 {
4061 cursor2 = cursor;
4062 cursor2Name = getNameY( trace );
4063 cursor2Units = getUnitsY( trace );
4064
4065 wxRealPoint coords = cursor->GetCoords();
4066 int row = m_cursorsGrid->GetNumberRows();
4067
4068 m_cursorFormatsDyn[1][0].UpdateUnits( plotTab->GetUnitsX() );
4069 m_cursorFormatsDyn[1][1].UpdateUnits( cursor2Units );
4070
4071 m_cursorsGrid->AppendRows( 1 );
4072 m_cursorsGrid->SetCellValue( row, COL_CURSOR_NAME, wxS( "2" ) );
4073 m_cursorsGrid->SetCellValue( row, COL_CURSOR_SIGNAL, cursor->GetName() );
4074 m_cursorsGrid->SetCellValue( row, COL_CURSOR_X, formatValue( coords.x, 1, 0 ) );
4075 m_cursorsGrid->SetCellValue( row, COL_CURSOR_Y, formatValue( coords.y, 1, 1 ) );
4076 fillSmithCursorRow( row, cursor, trace );
4077 break;
4078 }
4079 }
4080
4081 if( cursor1 && cursor2 && cursor1Units == cursor2Units )
4082 {
4083 wxRealPoint coords = cursor2->GetCoords() - cursor1->GetCoords();
4084 wxString signal;
4085
4086 m_cursorFormatsDyn[2][0].UpdateUnits( plotTab->GetUnitsX() );
4087 m_cursorFormatsDyn[2][1].UpdateUnits( cursor1Units );
4088
4089 if( cursor1->GetName() == cursor2->GetName() )
4090 signal = wxString::Format( wxS( "%s[2 - 1]" ), cursor2->GetName() );
4091 else
4092 signal = wxString::Format( wxS( "%s - %s" ), cursor2->GetName(), cursor1->GetName() );
4093
4094 m_cursorsGrid->AppendRows( 1 );
4095 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_NAME, _( "Diff" ) );
4096 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_SIGNAL, signal );
4097 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_X, formatValue( coords.x, 2, 0 ) );
4098 m_cursorsGrid->SetCellValue( 2, COL_CURSOR_Y, formatValue( coords.y, 2, 1 ) );
4099 }
4100 // Set up the labels
4101 m_cursorsGrid->SetColLabelValue( COL_CURSOR_X, plotTab->GetLabelX() );
4102
4103 wxString valColName = _( "Value" );
4104
4105 if( !cursor1Name.IsEmpty() )
4106 {
4107 if( cursor2Name.IsEmpty() || cursor1Name == cursor2Name )
4108 valColName = cursor1Name;
4109 }
4110 else if( !cursor2Name.IsEmpty() )
4111 {
4112 valColName = cursor2Name;
4113 }
4114
4115 m_cursorsGrid->SetColLabelValue( COL_CURSOR_Y, valColName );
4116
4117 if( m_customCursorsCnt > 3 ) // 2 for the default hardocded cursors plus the initial + 1
4118 {
4119 for( int i = 3; i < m_customCursorsCnt; i++ )
4120 {
4121 for( const auto& [name, trace] : plotTab->GetTraces() )
4122 {
4123 if( CURSOR* cursor = trace->GetCursor( i ) )
4124 {
4125 CURSOR* curs = cursor;
4126 wxString cursName = getNameY( trace );
4127 wxString cursUnits = getUnitsY( trace );
4128
4129 wxRealPoint coords = cursor->GetCoords();
4130 int row = m_cursorsGrid->GetNumberRows();
4131
4132 m_cursorFormatsDyn[i][0].UpdateUnits( plotTab->GetUnitsX() );
4133 m_cursorFormatsDyn[i][1].UpdateUnits( cursUnits );
4134
4135 m_cursorsGrid->AppendRows( 1 );
4136 m_cursorsGrid->SetCellValue( row, COL_CURSOR_NAME, wxS( "" ) + wxString( "" ) << i );
4137 m_cursorsGrid->SetCellValue( row, COL_CURSOR_SIGNAL, curs->GetName() );
4138 m_cursorsGrid->SetCellValue( row, COL_CURSOR_X, formatValue( coords.x, i, 0 ) );
4139 m_cursorsGrid->SetCellValue( row, COL_CURSOR_Y, formatValue( coords.y, i, 1 ) );
4140 fillSmithCursorRow( row, curs, trace );
4141
4142 // Set up the labels
4143 m_cursorsGrid->SetColLabelValue( COL_CURSOR_X, plotTab->GetLabelX() );
4144
4145 valColName = _( "Value" );
4146
4147 if( !cursName.IsEmpty() && m_cursorsGrid->GetColLabelValue( COL_CURSOR_Y ) == cursName )
4148 valColName = cursName;
4149
4150 m_cursorsGrid->SetColLabelValue( COL_CURSOR_Y, valColName );
4151 break;
4152 }
4153 }
4154 }
4155 }
4156
4161}
4162
4163
4164void SIMULATOR_FRAME_UI::onPlotCursorUpdate( wxCommandEvent& aEvent )
4165{
4167 OnModify();
4168}
4169
4170
4172{
4173 if( SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( GetCurrentSimTab() ) )
4174 plotTab->ResetScales( true );
4175
4176 // Drop any buffered output from the previous run and clear the console widget.
4177 m_simulatorFrame->TakeSimReportMessages();
4178 m_simConsole->Clear();
4179
4181
4182 // Do not export netlist, it is already stored in the simulator
4183 applyTuners();
4184
4185 m_refreshTimer.Start( REFRESH_INTERVAL, wxTIMER_ONE_SHOT );
4186}
4187
4188
4190{
4191 // AppendText is slow on MSW, so we use the buffered report lines
4192 wxString messages = m_simulatorFrame->TakeSimReportMessages();
4193
4194 if( messages.IsEmpty() )
4195 return;
4196
4197 m_simConsole->AppendText( messages );
4198 m_simConsole->SetInsertionPointEnd();
4199}
4200
4201
4202std::vector<wxString> SIMULATOR_FRAME_UI::SimPlotVectors() const
4203{
4204 std::vector<wxString> signals;
4205
4206 for( const std::string& vec : simulator()->AllVectors() )
4207 signals.emplace_back( vec );
4208
4209 return signals;
4210}
4211
4212
4213std::vector<wxString> SIMULATOR_FRAME_UI::Signals() const
4214{
4215 std::vector<wxString> signals;
4216
4217 for( const wxString& signal : m_signals )
4218 signals.emplace_back( signal );
4219
4220 for( const auto& [id, signal] : m_userDefinedSignals )
4221 signals.emplace_back( signal );
4222
4223 sortSignals( signals );
4224
4225 return signals;
4226}
4227
4228
4230{
4232
4233 if( aFinal )
4234 m_refreshTimer.Stop();
4235
4236 SIM_TAB* simTab = GetCurrentSimTab();
4237
4238 if( !simTab )
4239 return;
4240
4241 bool storeMultiRun = false;
4242
4243 if( aFinal && m_multiRunState.active )
4244 {
4245 if( m_multiRunState.currentStep < m_multiRunState.steps.size() )
4246 {
4247 storeMultiRun = true;
4248 m_multiRunState.storePending = true;
4249 }
4250 }
4251 else
4252 {
4253 m_multiRunState.storePending = false;
4254 }
4255
4256 SIM_TYPE simType = simTab->GetSimType();
4257 wxString msg;
4258
4259 // FFT is run synchronously in StartSimulation(), which stores the new FFT plot name before
4260 // refreshing. Ensure ngspice is on that plot before accessing its vectors. Other simulation
4261 // refreshes must not run setplot here, or a rerun would switch ngspice back to a stale plot.
4262 if( aFinal && simType == ST_FFT )
4263 {
4264 const wxString spicePlotName = simTab->GetSpicePlotName();
4265
4266 if( !spicePlotName.IsEmpty() )
4267 simulator()->Command( "setplot " + spicePlotName.ToStdString() );
4268 }
4269
4270 if( aFinal )
4271 {
4274 }
4275
4276 // If there are any signals plotted, update them
4277 if( SIM_TAB::IsPlottable( simType ) )
4278 {
4279 simTab->SetSpicePlotName( simulator()->CurrentPlotName() );
4280
4281 if( simType == ST_NOISE && aFinal )
4282 {
4283 m_simConsole->AppendText( _( "\n\nSimulation results:\n\n" ) );
4284 m_simConsole->SetInsertionPointEnd();
4285
4286 // The simulator will create noise1 & noise2 on the first run, noise3 and noise4
4287 // on the second, etc. The first plot for each run contains the spectral density
4288 // noise vectors and second contains the integrated noise.
4289 long number;
4290 simulator()->CurrentPlotName().Mid( 5 ).ToLong( &number );
4291
4292 for( const std::string& vec : simulator()->AllVectors() )
4293 {
4294 std::vector<double> val_list = simulator()->GetRealVector( vec, 1 );
4295 wxString value = SPICE_VALUE( val_list[0] ).ToSpiceString();
4296
4297 msg.Printf( wxS( "%s: %sV\n" ), vec, value );
4298
4299 m_simConsole->AppendText( msg );
4300 m_simConsole->SetInsertionPointEnd();
4301 }
4302
4303 simulator()->Command( fmt::format( "setplot noise{}", number - 1 ) );
4304 simTab->SetSpicePlotName( simulator()->CurrentPlotName() );
4305 }
4306
4307 SIM_PLOT_TAB* plotTab = dynamic_cast<SIM_PLOT_TAB*>( simTab );
4308 wxCHECK_RET( plotTab, wxString::Format( wxT( "No SIM_PLOT_TAB for: %s" ), magic_enum::enum_name( simType ) ) );
4309
4310 struct TRACE_INFO
4311 {
4312 wxString Vector;
4313 int TraceType;
4314 bool ClearData;
4315 };
4316
4317 std::map<TRACE*, TRACE_INFO> traceMap;
4318
4319 for( const auto& [name, trace] : plotTab->GetTraces() )
4320 traceMap[trace] = { wxEmptyString, SPT_UNKNOWN, false };
4321
4322 // NB: m_signals are already broken out into gain/phase, but m_userDefinedSignals are
4323 // as the user typed them
4324
4325 for( const wxString& signal : m_signals )
4326 {
4327 int traceType = SPT_UNKNOWN;
4328 wxString vectorName = vectorNameFromSignalName( plotTab, signal, &traceType );
4329
4330 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType ) )
4331 traceMap[trace] = { vectorName, traceType, false };
4332 }
4333
4334 for( const auto& [id, signal] : m_userDefinedSignals )
4335 {
4336 int traceType = SPT_UNKNOWN;
4337 wxString vectorName = vectorNameFromSignalName( plotTab, signal, &traceType );
4338
4339 if( simType == ST_AC )
4340 {
4341 int baseType = traceType &= ~( SPT_AC_GAIN | SPT_AC_PHASE );
4342
4343 for( int subType : { baseType | SPT_AC_GAIN, baseType | SPT_AC_PHASE } )
4344 {
4345 if( TRACE* trace = plotTab->GetTrace( vectorName, subType ) )
4346 traceMap[trace] = { vectorName, subType, !aFinal };
4347 }
4348 }
4349 else if( simType == ST_SP )
4350 {
4351 int baseType = traceType &= ~SPT_SP_MASK;
4352
4353 for( int subType : { baseType | SPT_SP_AMP, baseType | SPT_AC_PHASE, baseType | SPT_SP_SMITH } )
4354 {
4355 if( TRACE* trace = plotTab->GetTrace( vectorName, subType ) )
4356 traceMap[trace] = { vectorName, subType, !aFinal };
4357 }
4358 }
4359 else
4360 {
4361 if( TRACE* trace = plotTab->GetTrace( vectorName, traceType ) )
4362 traceMap[trace] = { vectorName, traceType, !aFinal };
4363 }
4364 }
4365
4366 // Two passes so that DC-sweep sub-traces get deleted and re-created:
4367
4368 for( const auto& [trace, traceInfo] : traceMap )
4369 {
4370 if( traceInfo.Vector.IsEmpty() )
4371 plotTab->DeleteTrace( trace );
4372 }
4373
4374 for( const auto& [trace, info] : traceMap )
4375 {
4376 std::vector<double> data_x;
4377
4378 if( !info.Vector.IsEmpty() )
4379 updateTrace( info.Vector, info.TraceType, plotTab, &data_x, info.ClearData );
4380 }
4381
4382 for( SIM_VIEW* view : plotTab->GetViews() )
4383 view->UpdateAll();
4384
4385 if( aFinal )
4386 {
4387 for( int row = 0; row < m_measurementsGrid->GetNumberRows(); ++row )
4388 UpdateMeasurement( row );
4389
4390 plotTab->ResetScales( true );
4391 }
4392
4393 for( SIM_VIEW* view : plotTab->GetViews() )
4394 view->Fit();
4395
4397 }
4398 else if( simType == ST_OP && aFinal )
4399 {
4400 m_simConsole->AppendText( _( "\n\nSimulation results:\n\n" ) );
4401 m_simConsole->SetInsertionPointEnd();
4402
4403 for( const std::string& vec : simulator()->AllVectors() )
4404 {
4405 std::vector<double> val_list = simulator()->GetRealVector( vec, 1 );
4406
4407 if( val_list.empty() )
4408 continue;
4409
4410 wxString value = SPICE_VALUE( val_list[0] ).ToSpiceString();
4411 wxString signal;
4412 SIM_TRACE_TYPE type = circuitModel()->VectorToSignal( vec, signal );
4413
4414 const size_t tab = 25; //characters
4415 size_t padding = ( signal.length() < tab ) ? ( tab - signal.length() ) : 1;
4416
4417 switch( type )
4418 {
4419 case SPT_VOLTAGE: value.Append( wxS( "V" ) ); break;
4420 case SPT_CURRENT: value.Append( wxS( "A" ) ); break;
4421 case SPT_POWER: value.Append( wxS( "W" ) ); break;
4422 default: value.Append( wxS( "?" ) ); break;
4423 }
4424
4425 msg.Printf( wxT( "%s%s\n" ),
4426 ( signal + wxT( ":" ) ).Pad( padding, wxUniChar( ' ' ) ),
4427 value );
4428
4429 m_simConsole->AppendText( msg );
4430 m_simConsole->SetInsertionPointEnd();
4431
4432 if( type == SPT_VOLTAGE || type == SPT_CURRENT || type == SPT_POWER )
4433 signal = signal.SubString( 2, signal.Length() - 2 );
4434
4435 if( type == SPT_POWER )
4436 signal += wxS( ":power" );
4437
4438 m_schematicFrame->Schematic().SetOperatingPoint( signal, val_list.at( 0 ) );
4439 }
4440 }
4441 else if( simType == ST_PZ && aFinal )
4442 {
4443 m_simConsole->AppendText( _( "\n\nSimulation results:\n\n" ) );
4444 m_simConsole->SetInsertionPointEnd();
4445 simulator()->Command( "print all" );
4446 }
4447
4448 // Non-plottable analyses (op, pz, tf, sens, disto) still create an ngspice plot; record its
4449 // name so a rerun can destroy it instead of leaking the vectors. Plottable tabs already
4450 // stored their (possibly noise-adjusted) plot name above. A shared/stale plot name is caught
4451 // when destroying, not here.
4452 if( aFinal && !SIM_TAB::IsPlottable( simType ) )
4453 simTab->SetSpicePlotName( simulator()->CurrentPlotName() );
4454
4455 if( storeMultiRun )
4456 {
4457 m_multiRunState.storePending = false;
4458 m_multiRunState.storedSteps = m_multiRunState.currentStep + 1;
4459 }
4460
4461 if( aFinal && m_multiRunState.active )
4462 {
4463 if( m_multiRunState.currentStep + 1 < m_multiRunState.steps.size() )
4464 {
4465 m_multiRunState.currentStep++;
4466
4467 wxQueueEvent( m_simulatorFrame, new wxCommandEvent( EVT_SIM_UPDATE ) );
4468 }
4469 else
4470 {
4471 m_multiRunState.active = false;
4472 m_multiRunState.steps.clear();
4473 m_multiRunState.currentStep = 0;
4474 m_multiRunState.storePending = false;
4475 m_tunerOverrides.clear();
4476
4477 if( !m_multiRunState.traces.empty() )
4478 {
4479 auto iter = m_multiRunState.traces.begin();
4480
4481 if( iter != m_multiRunState.traces.end() )
4482 m_multiRunState.storedSteps = iter->second.yValues.size();
4483 }
4484 }
4485 }
4486}
4487
4488
4490{
4491 m_multiRunState.active = false;
4492 m_multiRunState.tuners.clear();
4493 m_multiRunState.steps.clear();
4494 m_multiRunState.currentStep = 0;
4495 m_multiRunState.storePending = false;
4496
4497 if( aClearTraces )
4498 {
4499 m_multiRunState.traces.clear();
4500 m_multiRunState.storedSteps = 0;
4501 }
4502
4503 m_tunerOverrides.clear();
4504}
4505
4506
4508{
4509 m_tunerOverrides.clear();
4510
4511 std::vector<TUNER_SLIDER*> multiTuners;
4512
4513 for( TUNER_SLIDER* tuner : m_tuners )
4514 {
4515 if( tuner->GetRunMode() == TUNER_SLIDER::RUN_MODE::MULTI )
4516 multiTuners.push_back( tuner );
4517 }
4518
4519 if( multiTuners.empty() )
4520 {
4521 clearMultiRunState( true );
4522 return;
4523 }
4524
4525 bool tunersChanged = multiTuners != m_multiRunState.tuners;
4526
4527 if( m_multiRunState.active && tunersChanged )
4528 clearMultiRunState( true );
4529
4530 if( !m_multiRunState.active )
4531 {
4532 if( tunersChanged || m_multiRunState.storedSteps > 0 || !m_multiRunState.traces.empty() )
4533 clearMultiRunState( true );
4534
4535 m_multiRunState.tuners = multiTuners;
4536 m_multiRunState.steps = calculateMultiRunSteps( multiTuners );
4537 m_multiRunState.currentStep = 0;
4538 m_multiRunState.storePending = false;
4539
4540 if( m_multiRunState.steps.size() >= 2 )
4541 {
4542 m_multiRunState.active = true;
4543 m_multiRunState.storedSteps = 0;
4544 }
4545 else
4546 {
4547 m_multiRunState.steps.clear();
4548 return;
4549 }
4550 }
4551 else if( tunersChanged )
4552 {
4553 m_multiRunState.tuners = multiTuners;
4554 }
4555
4556 if( m_multiRunState.active && m_multiRunState.currentStep < m_multiRunState.steps.size() )
4557 {
4558 const MULTI_RUN_STEP& step = m_multiRunState.steps[m_multiRunState.currentStep];
4559
4560 for( const auto& entry : step.overrides )
4561 m_tunerOverrides[entry.first] = entry.second;
4562 }
4563}
4564
4565
4566std::vector<SIMULATOR_FRAME_UI::MULTI_RUN_STEP>
4567SIMULATOR_FRAME_UI::calculateMultiRunSteps( const std::vector<TUNER_SLIDER*>& aTuners ) const
4568{
4569 std::vector<MULTI_RUN_STEP> steps;
4570
4571 if( aTuners.empty() )
4572 return steps;
4573
4574 std::vector<std::vector<double>> tunerValues;
4575 tunerValues.reserve( aTuners.size() );
4576
4577 for( TUNER_SLIDER* tuner : aTuners )
4578 {
4579 if( !tuner )
4580 return steps;
4581
4582 double startValue = tuner->GetMin().ToDouble();
4583 double endValue = tuner->GetMax().ToDouble();
4584 int stepCount = std::max( 2, tuner->GetStepCount() );
4585
4586 if( stepCount < 2 )
4587 stepCount = 2;
4588
4589 double increment = ( endValue - startValue ) / static_cast<double>( stepCount - 1 );
4590
4591 std::vector<double> values;
4592 values.reserve( stepCount );
4593
4594 for( int ii = 0; ii < stepCount; ++ii )
4595 values.push_back( startValue + increment * ii );
4596
4597 tunerValues.push_back( std::move( values ) );
4598 }
4599
4601
4602 if( limit < 1 )
4603 limit = 1;
4604
4605 std::vector<double> currentValues( aTuners.size(), 0.0 );
4606
4607 auto generate =
4608 [&]( auto&& self, size_t depth ) -> void
4609 {
4610 if( steps.size() >= static_cast<size_t>( limit ) )
4611 return;
4612
4613 if( depth == aTuners.size() )
4614 {
4615 MULTI_RUN_STEP step;
4616
4617 for( size_t ii = 0; ii < aTuners.size(); ++ii )
4618 step.overrides.emplace( aTuners[ii], currentValues[ii] );
4619
4620 steps.push_back( std::move( step ) );
4621 return;
4622 }
4623
4624 for( double value : tunerValues[depth] )
4625 {
4626 currentValues[depth] = value;
4627 self( self, depth + 1 );
4628
4629 if( steps.size() >= static_cast<size_t>( limit ) )
4630 return;
4631 }
4632 };
4633
4634 generate( generate, 0 );
4635
4636 return steps;
4637}
4638
4639
4640std::string SIMULATOR_FRAME_UI::multiRunTraceKey( const wxString& aVectorName, int aTraceType ) const
4641{
4642 return fmt::format( "{}|{}", aVectorName.ToStdString(), aTraceType );
4643}
4644
4645
4646void SIMULATOR_FRAME_UI::recordMultiRunData( const wxString& aVectorName, int aTraceType, const std::vector<double>& aX,
4647 const std::vector<double>& aY )
4648{
4649 if( aX.empty() || aY.empty() )
4650 return;
4651
4652 std::string key = multiRunTraceKey( aVectorName, aTraceType );
4653 MULTI_RUN_TRACE& trace = m_multiRunState.traces[key];
4654
4655 trace.traceType = aTraceType;
4656
4657 if( trace.xValues.empty() )
4658 trace.xValues = aX;
4659
4660 if( trace.xValues.size() != aX.size() )
4661 return;
4662
4663 size_t index = m_multiRunState.currentStep;
4664
4665 if( trace.yValues.size() <= index )
4666 trace.yValues.resize( index + 1 );
4667
4668 trace.yValues[index] = aY;
4669
4670 if( aTraceType & SPT_SP_SMITH )
4671 {
4672 if( trace.xRuns.size() <= index )
4673 trace.xRuns.resize( index + 1 );
4674
4675 trace.xRuns[index] = aX;
4676 }
4677}
4678
4679
4680bool SIMULATOR_FRAME_UI::hasMultiRunTrace( const wxString& aVectorName, int aTraceType ) const
4681{
4682 std::string key = multiRunTraceKey( aVectorName, aTraceType );
4683 auto it = m_multiRunState.traces.find( key );
4684
4685 if( it == m_multiRunState.traces.end() )
4686 return false;
4687
4688 const MULTI_RUN_TRACE& trace = it->second;
4689
4690 return !trace.xValues.empty() && !trace.yValues.empty();
4691}
4692
4693
4695{
4696 m_simulatorFrame->OnModify();
4697}
int index
const char * name
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent) override
void doPopupSelection(wxCommandEvent &event) override
SIMULATOR_FRAME_UI * m_parent
CURSORS_GRID_TRICKS(SIMULATOR_FRAME_UI *aParent, WX_GRID *aGrid)
The SIMULATOR_FRAME holds the main user-interface for running simulations.
const wxRealPoint & GetCoords() const
virtual void SetCoordX(double aValue)
int ShowModal() override
bool Find(const wxString &aTerm, int &aMatchersTriggered, int &aPosition)
Look in all existing matchers, return the earliest match of any of the existing.
Renders a combobox cell's text with an always-visible dropdown arrow, so it reads as a dropdown even ...
GRID_TRICKS(WX_GRID *aGrid)
virtual void doPopupSelection(wxCommandEvent &event)
virtual void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent)
WX_GRID * m_grid
I don't own the grid, but he owns me.
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
wxString ToCSSString() const
Definition color4d.cpp:146
wxColour ToColour() const
Definition color4d.cpp:221
Definition kiid.h:46
Hold a translatable error message and may be used when throwing exceptions containing a translated er...
const wxString What() const
void AppendParentEmbeddedFiles(std::vector< EMBEDDED_FILES * > &aStack) const
void doPopupSelection(wxCommandEvent &event) override
void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent) override
SIMULATOR_FRAME_UI * m_parent
MEASUREMENTS_GRID_TRICKS(SIMULATOR_FRAME_UI *aParent, WX_GRID *aGrid)
const SPICE_ITEM * FindItem(const wxString &aRefName) const
Find and return the item corresponding to aRefName.
A singleton reporter that reports to nowhere.
Definition reporter.h:267
Holds all the data relating to one schematic.
Definition schematic.h:155
void ClearOperatingPoints()
Clear operating points from a .op simulation.
Definition schematic.h:526
wxString GetCurrentVariant() const
Return the current variant being edited.
Schematic editor (Eeschema) main window.
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
SCH_ITEM * ResolveItem(const KIID &aID) const
Fetch a SCH_ITEM by ID.
Schematic symbol object.
Definition sch_symbol.h:76
EMBEDDED_FILES * GetEmbeddedFiles() override
SCH_SYMBOLs don't currently support embedded files, but their LIB_SYMBOL counterparts do.
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:185
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
void doPopupSelection(wxCommandEvent &event) override
void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent) override
SIMULATOR_FRAME_UI * m_parent
SIGNALS_GRID_TRICKS(SIMULATOR_FRAME_UI *aParent, WX_GRID *aGrid)
wxSplitterWindow * m_splitterLeftRight
wxSplitterWindow * m_splitterMeasurements
wxSplitterWindow * m_splitterCursors
wxSplitterWindow * m_splitterPlotAndConsole
SIMULATOR_FRAME_UI_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(-1,-1), long style=wxTAB_TRAVERSAL, const wxString &name=wxEmptyString)
wxSplitterWindow * m_splitterSignals
The SIMULATOR_FRAME_UI holds the main user-interface for running simulations.
SIM_TAB * NewSimTab(const wxString &aSimCommand)
Create a new simulation tab for a given simulation type.
std::string multiRunTraceKey(const wxString &aVectorName, int aTraceType) const
std::vector< int > m_smithCursorWidths
void SetUserDefinedSignals(const std::map< int, wxString > &aSignals)
void updatePlotCursors()
Update the cursor values (in the grid) and graphics (in the plot window).
void OnSimRefresh(bool aFinal)
void onPlotClose(wxAuiNotebookEvent &event) override
void CustomCursorsInit()
Init handler for custom cursors.
void recordMultiRunData(const wxString &aVectorName, int aTraceType, const std::vector< double > &aX, const std::vector< double > &aY)
std::vector< MULTI_RUN_STEP > calculateMultiRunSteps(const std::vector< TUNER_SLIDER * > &aTuners) const
void autoSizeGridColumn(WX_GRID *aGrid, int aCol, int aMinWidth, int aExtraPadding=0)
Grow (but never shrink below aMinWidth) a grid column to fit its current contents.
void TogglePanel(wxPanel *aPanel, wxSplitterWindow *aSplitterWindow, int &aSashPosition)
A common toggler for the two main wxSplitterWindow s.
void onPlotChanged(wxAuiNotebookEvent &event) override
void rebuildSignalsGrid(wxString aFilter)
Rebuild the filtered list of signals in the signals grid.
std::vector< std::vector< SPICE_VALUE_FORMAT > > m_cursorFormatsDyn
void DoFourier(const wxString &aSignal, const wxString &aFundamental)
void rebuildMeasurementsGrid()
Rebuild the measurements grid for the current plot.
std::list< TUNER_SLIDER * > m_tuners
void rebuildSignalsList()
Rebuild the list of signals available from the netlist.
bool loadLegacyWorkbook(const wxString &aPath)
MULTI_RUN_STATE m_multiRunState
wxArrayString getYScaleChoices(SIM_PLOT_TAB *aPlotTab, SIM_VIEW *aOwnView) const
The Signals grid's "Y Scale" column choices: "Default" plus one entry per eligible view.
void ToggleSmithChart()
Toggle the current S-parameter tab between Smith chart and amplitude/phase views.
void UpdateMeasurement(int aRow)
Update a measurement in the measurements grid.
wxString getNoiseSource() const
std::vector< wxString > SimPlotVectors() const
void SetSubWindowsSashSize()
Adjust the sash dimension of splitter windows after reading the config settings must be called after ...
void applyUserDefinedSignals()
Apply user-defined signals to the SPICE session.
SIM_PREFERENCES m_preferences
void DeleteMeasurement(int aRow)
Delete a row from the measurements grid.
SCH_EDIT_FRAME * m_schematicFrame
wxString vectorNameFromSignalName(SIM_PLOT_TAB *aPlotTab, const wxString &aSignalName, int *aTraceType)
Get the simulator output vector name for a given signal name and type.
void updateSignalsGrid()
Update the values in the signals grid.
void onCursorsGridCellChanged(wxGridEvent &aEvent) override
void onPlotDragged(wxAuiNotebookEvent &event) override
std::vector< wxString > Signals() const
bool SaveWorkbook(const wxString &aPath)
Save plot, signal, cursor, measurement, etc.
bool hasMultiRunTrace(const wxString &aVectorName, int aTraceType) const
std::vector< wxString > m_signals
SIM_TAB * GetCurrentSimTab() const
Return the currently opened plot panel (or NULL if there is none).
wxString getViewLabel(SIM_PLOT_TAB *aPlotTab, SIM_VIEW *aView) const
The Signals grid's "Plot" column label for a given view ("Disabled" if null).
void updateSmithCursorColumns(bool aSmithMode)
Add or remove the Smith-only cursor columns, carrying their shown/hidden state across.
void SaveCursorToWorkbook(nlohmann::json &aTraceJs, TRACE *aTrace, int aCursorId)
bool LoadWorkbook(const wxString &aPath)
Load plot, signal, cursor, measurement, etc.
wxString getYScaleLabel(SIM_PLOT_TAB *aPlotTab, TRACE *aTrace) const
The Signals grid's "Y Scale" column label for a trace ("Default" if not explicitly linked).
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 updateTrace(const wxString &aVectorName, int aTraceType, SIM_PLOT_TAB *aPlotTab, std::vector< double > *aDataX=nullptr, bool aClearData=false, SIM_VIEW *aView=nullptr)
Update a trace in a particular SIM_PLOT_TAB.
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 fillSmithCursorRow(int aRow, CURSOR *aCursor, TRACE *aTrace)
std::vector< wxString > m_netnames
SPICE expressions need quoted versions of the netnames since KiCad allows '-' and '/' in netnames.
void AddTrace(const wxString &aName, SIM_TRACE_TYPE aType)
Add a new trace to the current plot.
void onPlotClosed(wxAuiNotebookEvent &event) override
void RemoveTuner(TUNER_SLIDER *aTuner)
Remove an existing tuner.
void SaveSettings(EESCHEMA_SETTINGS *aCfg)
std::shared_ptr< SPICE_CIRCUIT_MODEL > circuitModel() const
void OnFilterText(wxCommandEvent &aEvent) override
void onMeasurementsGridCellChanged(wxGridEvent &aEvent) override
void DeleteCursor()
Deletes last m_signalsGrid "Cursor n" column, removes vector's m_cursorFormatsDyn last entry,...
void CreateNewCursor()
Creates a column at the end of m_signalsGrid named "Cursor n" ( n = m_customCursorsCnt ),...
void applyTuners()
Apply component values specified using tuner sliders to the current netlist.
bool loadJsonWorkbook(const wxString &aPath)
wxArrayString getViewChoices(SIM_PLOT_TAB *aPlotTab) const
The Signals grid's "Plot" column choices: "Disabled" plus one entry per current view.
void clearMultiRunState(bool aClearTraces)
void OnFilterMouseMoved(wxMouseEvent &aEvent) override
void AddMeasurement(const wxString &aCmd)
Add a measurement to the measurements grid.
void onPlotChanging(wxAuiNotebookEvent &event) override
std::vector< SIM_VIEW * > getYScaleTargetViews(SIM_PLOT_TAB *aPlotTab, SIM_VIEW *aOwnView) const
The views a trace's Y-axis scale could be linked to: every view except its own (since linking to its ...
std::map< const TUNER_SLIDER *, double > m_tunerOverrides
std::shared_ptr< SPICE_SIMULATOR > simulator() const
void onPlotCursorUpdate(wxCommandEvent &aEvent)
void onSignalsGridCellChanged(wxGridEvent &aEvent) override
void InitWorkbook()
Load the currently active workbook stored in the project settings.
SIM_TRACE_TYPE getXAxisType(SIM_TYPE aType) const
Return X axis for a given simulation type.
void signalsGridCursorUpdate(T t, U u, R r)
Updates m_signalsGrid cursor widget, column rendering and attributes.
void SetMeasureFormat(int aRow, const SPICE_VALUE_FORMAT &aFormat)
double getSmithPortImpedance(const wxString &aVectorName)
Reference impedance of the response port for an S-parameter vector, zero when unresolved.
void ApplyPreferences(const SIM_PREFERENCES &aPrefs)
Called when settings are changed via the common Preferences dialog.
const SPICE_CIRCUIT_MODEL * GetExporter() const
Return the netlist exporter object used for simulations.
SIMULATOR_FRAME * m_simulatorFrame
void AddTuner(const SCH_SHEET_PATH &aSheetPath, SCH_SYMBOL *aSymbol)
Add a tuner for a symbol.
void OnUpdateUI(wxUpdateUIEvent &event) override
SIMULATOR_FRAME_UI(SIMULATOR_FRAME *aSimulatorFrame, SCH_EDIT_FRAME *aSchematicFrame)
SPICE_VALUE_FORMAT m_cursorFormats[3][2]
void LoadSettings(EESCHEMA_SETTINGS *aCfg)
The SIMULATOR_FRAME holds the main user-interface for running simulations.
SIM_MODEL & CreateModel(SIM_MODEL::TYPE aType, std::span< const wxString > aPins, REPORTER &aReporter)
void SetFilesStack(std::vector< EMBEDDED_FILES * > aFilesStack)
Definition sim_lib_mgr.h:45
virtual const PARAM * GetTunerParam() const
Definition sim_model.h:491
const SPICE_GENERATOR & SpiceGenerator() const
Definition sim_model.h:429
static void FillDefaultColorList(bool aWhiteBg)
Fills m_colorList by a default set of colors.
bool DeleteTrace(const wxString &aVectorName, int aTraceType)
int GetViewCount() const
void UpdateSmithReferenceImpedance()
Refresh the grid z0 from the shown Smith traces, on every view.
wxString GetLabelY1() const
mpWindow * GetPlotWin() const
Getter for the default view's math plot window (back-compat for zoom undo/redo, export).
void SetSmithView(double aZoom, double aPanX, double aPanY)
Restore a saved view, values are validated and clamped.
void EnableTrackCursor(bool aEnable)
Turn on/off the crosshair that follows the mouse and reads out every trace's value.
SIM_VIEW * GetView(int aIndex) const
void ShowGrid(bool aEnable)
void SetTraceData(TRACE *aTrace, std::vector< double > &aX, std::vector< double > &aY, int aSweepCount, size_t aSweepSize, bool aIsMultiRun=false, const std::vector< wxString > &aMultiRunLabels={})
const std::vector< SIM_VIEW * > & GetViews() const
wxString GetUnitsY2() const
void SetY2Scale(bool aLock, double aMin, double aMax)
TRACE * GetTrace(const wxString &aVecName, int aType) const
void SetSmithMode(bool aEnable)
Smith mode is tab-wide: every view of the tab shows a Smith chart while it is on.
wxString GetLabelX() const
const std::map< wxString, TRACE * > & GetTraces() const
wxString GetLabelY3() const
void SetY1Scale(bool aLock, double aMin, double aMax)
void SetY3Scale(bool aLock, double aMin, double aMax)
SIM_VIEW * GetDefaultView() const
The view new traces default to, and legacy (single-view) settings apply to.
SIM_VIEW * AddView()
Add a new (empty) view, stacked below the existing ones.
std::vector< std::pair< wxString, wxString > > & Measurements()
void UpdateTraceStyle(TRACE *trace)
Update trace line style.
void SetLegendPosition(const wxPoint &aPosition)
TRACE * GetOrAddTrace(const wxString &aVectorName, int aType, SIM_VIEW *aView)
Get (or create, on aView) the TRACE for a signal.
void ResetScales(bool aIncludeX)
Reset scale ranges to fit the current traces, on every view.
void UpdatePlotColors()
Update plot colors.
std::vector< SMITH_STASHED_TRACE > & SmithStashedTraces()
Traces and cursors set aside while in Smith mode, restored when leaving it.
void ShowLegend(bool aEnable)
wxString GetLabelY2() const
void EnableCursor(TRACE *aTrace, int aCursorId, const wxString &aSignalName)
Turn on/off the cursor for a particular trace.
int GetViewIndex(SIM_VIEW *aView) const
bool IsSmithMode() const
wxString GetUnitsX() const
void EnsureThirdYAxisExists()
std::vector< SMITH_STASHED_CURSOR > & SmithStashedCursors()
void SetDottedSecondary(bool aEnable)
Draw secondary signal traces (current or phase) with dotted lines.
void ApplyPreferences(const SIM_PREFERENCES &aPrefs) override
wxString GetUnitsY1() const
void DisableCursor(TRACE *aTrace, int aCursorId)
wxString GetUnitsY3() const
int GetSimOptions() const
Definition sim_tab.h:51
const wxString & GetSpicePlotName() const
Definition sim_tab.h:57
SIM_TYPE GetSimType() const
Definition sim_tab.cpp:71
const wxString & GetSimCommand() const
Definition sim_tab.h:48
static bool IsPlottable(SIM_TYPE aSimType)
Definition sim_tab.cpp:49
void SetSimOptions(int aOptions)
Definition sim_tab.h:52
wxString GetLastSchTextSimCommand() const
Definition sim_tab.h:54
void SetSpicePlotName(const wxString &aPlotName)
Definition sim_tab.h:58
static double ToDouble(const std::string &aString, double aDefault=NAN)
static std::string ToSpice(const std::string &aString)
A single stacked plot area within a SIM_PLOT_TAB.
Cursor that snaps along a Smith chart locus, keyed by frequency.
const wxRealPoint & GetGamma() const
Reflection coefficient locus, Re in X and Im in Y, drawn on the Smith chart.
double GetReferenceImpedance() const
Special netlist exporter flavor that allows one to override simulation commands.
static SIM_TYPE CommandToSimType(const wxString &aCmd)
Return simulation type basing on a simulation command directive.
bool ParseNoiseCommand(const wxString &aCmd, wxString *aOutput, wxString *aRef, wxString *aSource, wxString *aScale, SPICE_VALUE *aPts, SPICE_VALUE *aFStart, SPICE_VALUE *aFStop, bool *aSaveAll)
wxString GetSchTextSimCommand()
Return simulation command directives placed in schematic sheets (if any).
SIM_TRACE_TYPE VectorToSignal(const std::string &aVector, wxString &aSignal) const
Return name of Spice dataset for a specific trace.
virtual std::string TunerCommand(const SPICE_ITEM &aItem, double aValue) const
wxString GetWorkbookFilename() const
void SetWorkbookFilename(const wxString &aFilename)
virtual std::vector< double > GetImaginaryVector(const std::string &aName, int aMaxLen=-1)=0
Return a requested vector with imaginary values.
virtual bool Command(const std::string &aCmd)=0
Execute a Spice command as if it was typed into console.
static wxString TypeToName(SIM_TYPE aType, bool aShortName)
Return a string with simulation name based on enum.
std::shared_ptr< SPICE_SETTINGS > & Settings()
Return the simulator configuration settings.
virtual wxString CurrentPlotName() const =0
virtual std::vector< double > GetRealVector(const std::string &aName, int aMaxLen=-1)=0
Return a requested vector with real values.
virtual std::vector< double > GetGainVector(const std::string &aName, int aMaxLen=-1)=0
Return a requested vector with magnitude values.
virtual std::vector< double > GetPhaseVector(const std::string &aName, int aMaxLen=-1)=0
Return a requested vector with phase values.
Helper class to handle Spice way of expressing values (e.g. 10.5 Meg)
Definition spice_value.h:51
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)
bool IsYScaleDefault() const
True if this trace's Y-axis scale hasn't been explicitly linked to another view (i....
void SetTraceColour(const wxColour &aColour)
SIM_VIEW * GetView() const
The SIM_VIEW this trace is currently plotted on (nullptr if not plotted anywhere).
bool HasCursor(int aCursorId)
SIM_VIEW * GetYScaleView() const
The view whose Y-axis scale this trace's axis should match (defaults to its own view).
const std::vector< double > & GetDataX() const
CURSOR * GetCursor(int aCursorId)
void SetYScaleView(SIM_VIEW *aView)
Custom widget to handle quick component values modification and simulation on the fly.
wxString GetSymbolRef() const
A modified version of the wxInfoBar class that allows us to:
Definition wx_infobar.h:77
void ShowMessageFor(const wxString &aMessage, int aTime, int aFlags=wxICON_INFORMATION, MESSAGE_TYPE aType=WX_INFOBAR::MESSAGE_TYPE::GENERIC)
Show the infobar with the provided message and icon for a specific period of time.
A wrapper for reporting to a wxString object.
Definition reporter.h:242
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:256
const wxPen & GetPen() const
Get pen set for this layer.
Definition mathplot.h:287
Canvas for plotting mpLayer implementations.
Definition mathplot.h:970
int GetMarginLeft() const
Definition mathplot.h:1285
void SetMargins(int top, int right, int bottom, int left)
Set window margins, creating a blank area where some kinds of layers cannot draw.
int GetMarginTop() const
Definition mathplot.h:1279
int GetMarginRight() const
Definition mathplot.h:1281
int GetMarginBottom() const
Definition mathplot.h:1283
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
static wxString displayName(const DATABASE_LIB_TABLE &aTable)
static std::string ToStdString(const wxString &aStr)
#define _(s)
Abstract pattern-matching tool and implementations.
@ CTX_SIGNAL
@ GRIDTRICKS_ID_SELECT
Definition grid_tricks.h:44
@ GRIDTRICKS_ID_COPY
Definition grid_tricks.h:41
@ GRIDTRICKS_ID_DELETE
Definition grid_tricks.h:42
@ GRIDTRICKS_FIRST_CLIENT_ID
Definition grid_tricks.h:46
int m_SimulatorMultiRunCombinationLimit
Maximum number of tuner combinations simulated when using multi-run mode.
static const std::string WorkbookFileExtension
std::string source
#define traceSettings
KICOMMON_API wxFont GetStatusFont(wxWindow *aWindow)
double VSWR(double aGammaMag)
Definition smith_math.h:78
bool ParseSParamPorts(const wxString &aVectorName, long *aResponsePort, long *aDrivePort)
S-parameter vectors are named S_<responsePort>_<drivePort>.
Definition smith_math.h:117
bool GammaToImpedance(double aRe, double aIm, double aZ0, double &aResistance, double &aReactance)
Impedance of a reflection coefficient, z = z0 ( 1 + gamma ) / ( 1 - gamma ), false at the gamma = 1 s...
Definition smith_math.h:65
double ReturnLoss(double aGammaMag)
Definition smith_math.h:86
see class PGM_BASE
SIM_TRACE_TYPE
Possible trace types.
Definition sim_types.h:49
@ SPT_TIME
Definition sim_types.h:62
@ SPT_AC_PHASE
Definition sim_types.h:53
@ SPT_SWEEP
Definition sim_types.h:65
@ SPT_UNKNOWN
Definition sim_types.h:68
@ SPT_AC_GAIN
Definition sim_types.h:54
@ SPT_Y_AXIS_MASK
Definition sim_types.h:59
@ SPT_SP_AMP
Definition sim_types.h:56
@ SPT_VOLTAGE
Definition sim_types.h:51
@ SPT_POWER
Definition sim_types.h:55
@ SPT_CURRENT
Definition sim_types.h:52
@ SPT_SP_MASK
Definition sim_types.h:58
@ SPT_LIN_FREQUENCY
Definition sim_types.h:63
@ SPT_SP_SMITH
Definition sim_types.h:57
SIM_TYPE
Possible simulation types.
Definition sim_types.h:31
@ ST_SP
Definition sim_types.h:42
@ ST_TRAN
Definition sim_types.h:41
@ ST_UNKNOWN
Definition sim_types.h:32
@ ST_NOISE
Definition sim_types.h:36
@ ST_AC
Definition sim_types.h:33
@ ST_DISTO
Definition sim_types.h:35
@ ST_TF
Definition sim_types.h:40
@ ST_SENS
Definition sim_types.h:39
@ ST_DC
Definition sim_types.h:34
@ ST_OP
Definition sim_types.h:37
@ ST_FFT
Definition sim_types.h:43
@ ST_PZ
Definition sim_types.h:38
void sortSignals(std::vector< wxString > &signals)
static bool smithColumnsShown(const WX_GRID *aGrid)
wxString vectorNameFromSignalId(int aUserDefinedSignalId)
MEASUREMENTS_GIRD_COLUMNS
@ COL_MEASUREMENT_FORMAT
@ COL_MEASUREMENT_VALUE
@ COL_MEASUREMENT
CURSORS_GRID_COLUMNS
@ COL_CURSOR_SMITH_END
@ COL_CURSOR_REACTANCE
@ COL_CURSOR_NAME
@ COL_CURSOR_RL
@ COL_CURSOR_SIGNAL
@ COL_CURSOR_R
@ COL_CURSOR_X
@ COL_CURSOR_Y
@ COL_CURSOR_SMITH_FIRST
@ COL_CURSOR_VSWR
SIGNALS_GRID_COLUMNS
@ COL_SIGNAL_SHOW
@ COL_SIGNAL_NAME
@ COL_Y_SCALE
@ COL_CURSOR_1
@ COL_SIGNAL_COLOR
@ COL_CURSOR_2
#define ID_SIM_REFRESH
@ MYID_MEASURE_INTEGRAL
@ MYID_MEASURE_MAX_AT
@ MYID_MEASURE_AVG
@ MYID_MEASURE_MAX
@ MYID_FORMAT_VALUE
@ MYID_MEASURE_RMS
@ MYID_DELETE_MEASUREMENT
@ MYID_MEASURE_MIN
@ MYID_MEASURE_MIN_AT
@ MYID_MEASURE_PP
#define UNPLOTTED
static constexpr int SMITH_CURSOR_COLS
SIM_TRACE_TYPE operator|(SIM_TRACE_TYPE aFirst, SIM_TRACE_TYPE aSecond)
#define REFRESH_INTERVAL
const int scale
std::vector< FAB_LAYER_COLOR > dummy
std::map< const TUNER_SLIDER *, double > overrides
std::vector< std::vector< double > > xRuns
std::vector< std::vector< double > > yValues
std::string value
Definition sim_model.h:398
const INFO & info
Definition sim_model.h:399
Contains preferences pertaining to the simulator.
Cursor recorded when entering Smith mode, so leaving restores it to its original trace.
Trace hidden while the tab is in Smith mode, kept so leaving the mode restores it.
const SIM_MODEL * model
A SPICE_VALUE_FORMAT holds precision and range info for formatting values.
Definition spice_value.h:38
wxString ToString() const
void UpdateUnits(const wxString &aUnits)
nanodbc::result res
std::vector< DATABASE_CONNECTION::ROW > rows
IbisParser parser & reporter
KIBIS_MODEL * model
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.