KiCad PCB EDA Suite
sim_plot_frame.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 CERN
5  * Copyright (C) 2016-2018 KiCad Developers, see AUTHORS.txt for contributors.
6  * @author Tomasz Wlostowski <tomasz.wlostowski@cern.ch>
7  * @author Maciej Suminski <maciej.suminski@cern.ch>
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 3
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, you may find one here:
21  * https://www.gnu.org/licenses/gpl-3.0.html
22  * or you may search the http://www.gnu.org website for the version 3 license,
23  * or you may write to the Free Software Foundation, Inc.,
24  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
25  */
26 
27 #include <wx/stc/stc.h>
28 
29 #include <sch_edit_frame.h>
30 #include <eeschema_id.h>
31 #include <kiway.h>
32 #include <confirm.h>
33 #include <bitmaps.h>
35 #include <widgets/tuner_slider.h>
38 #include <pgm_base.h>
39 #include "sim_plot_frame.h"
40 #include "sim_plot_panel.h"
41 #include "spice_simulator.h"
42 #include "spice_reporter.h"
43 #include <menus_helpers.h>
44 #include <tool/tool_manager.h>
45 #include <tools/ee_actions.h>
46 
48 {
49  int res = (int) aFirst | (int) aSecond;
50 
51  return (SIM_PLOT_TYPE) res;
52 }
53 
54 
56 {
57 public:
59  : m_parent( aParent )
60  {
61  }
62 
63  REPORTER& Report( const wxString& aText, SEVERITY aSeverity = RPT_UNDEFINED ) override
64  {
65  wxCommandEvent* event = new wxCommandEvent( EVT_SIM_REPORT );
66  event->SetString( aText );
67  wxQueueEvent( m_parent, event );
68  return *this;
69  }
70 
71  bool HasMessage() const override
72  {
73  return false; // Technically "indeterminate" rather than false.
74  }
75 
76  void OnSimStateChange( SPICE_SIMULATOR* aObject, SIM_STATE aNewState ) override
77  {
78  wxCommandEvent* event = NULL;
79 
80  switch( aNewState )
81  {
82  case SIM_IDLE:
83  event = new wxCommandEvent( EVT_SIM_FINISHED );
84  break;
85 
86  case SIM_RUNNING:
87  event = new wxCommandEvent( EVT_SIM_STARTED );
88  break;
89 
90  default:
91  wxFAIL;
92  return;
93  }
94 
95  wxQueueEvent( m_parent, event );
96  }
97 
98 private:
100 };
101 
102 
103 TRACE_DESC::TRACE_DESC( const NETLIST_EXPORTER_PSPICE_SIM& aExporter, const wxString& aName,
104  SIM_PLOT_TYPE aType, const wxString& aParam )
105  : m_name( aName ), m_type( aType ), m_param( aParam )
106 {
107  // Title generation
108  m_title = wxString::Format( "%s(%s)", aParam, aName );
109 
110  if( aType & SPT_AC_MAG )
111  m_title += " (mag)";
112  else if( aType & SPT_AC_PHASE )
113  m_title += " (phase)";
114 }
115 
116 // Store the path of saved workbooks during the session
118 
119 SIM_PLOT_FRAME::SIM_PLOT_FRAME( KIWAY* aKiway, wxWindow* aParent )
120  : SIM_PLOT_FRAME_BASE( aParent ), m_lastSimPlot( nullptr )
121 {
122  SetKiway( this, aKiway );
123  m_signalsIconColorList = NULL;
124 
126 
127  if( m_schematicFrame == NULL )
128  throw std::runtime_error( "There is no schematic window" );
129 
130  // Give an icon
131  wxIcon icon;
132  icon.CopyFromBitmap( KiBitmap( simulator_xpm ) );
133  SetIcon( icon );
134 
135  // Gives a minimal size
136  SetSizeHints( 500, 400, -1, -1, -1, -1 );
137 
138  // Get the previous size and position of windows:
139  LoadSettings( config() );
140 
141  // Give icons to menuitems
143 
145 
146  if( !m_simulator )
147  {
148  throw std::runtime_error( "Could not create simulator instance" );
149  return;
150  }
151 
152  m_simulator->Init();
153 
154  if( m_savedWorkbooksPath.IsEmpty() )
155  {
157  }
158 
159  m_reporter = new SIM_THREAD_REPORTER( this );
160  m_simulator->SetReporter( m_reporter );
161 
163 
164  Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( SIM_PLOT_FRAME::onClose ), NULL, this );
165  Connect( EVT_SIM_UPDATE, wxCommandEventHandler( SIM_PLOT_FRAME::onSimUpdate ), NULL, this );
166  Connect( EVT_SIM_REPORT, wxCommandEventHandler( SIM_PLOT_FRAME::onSimReport ), NULL, this );
167  Connect( EVT_SIM_STARTED, wxCommandEventHandler( SIM_PLOT_FRAME::onSimStarted ), NULL, this );
168  Connect( EVT_SIM_FINISHED, wxCommandEventHandler( SIM_PLOT_FRAME::onSimFinished ), NULL, this );
169  Connect( EVT_SIM_CURSOR_UPDATE, wxCommandEventHandler( SIM_PLOT_FRAME::onCursorUpdate ), NULL, this );
170 
171  // Toolbar buttons
172  m_toolSimulate = m_toolBar->AddTool( ID_SIM_RUN, _( "Run/Stop Simulation" ),
173  KiBitmap( sim_run_xpm ), _( "Run Simulation" ), wxITEM_NORMAL );
174  m_toolAddSignals = m_toolBar->AddTool( ID_SIM_ADD_SIGNALS, _( "Add Signals" ),
175  KiBitmap( sim_add_signal_xpm ), _( "Add signals to plot" ), wxITEM_NORMAL );
176  m_toolProbe = m_toolBar->AddTool( ID_SIM_PROBE, _( "Probe" ),
177  KiBitmap( sim_probe_xpm ), _( "Probe signals on the schematic" ), wxITEM_NORMAL );
178  m_toolTune = m_toolBar->AddTool( ID_SIM_TUNE, _( "Tune" ),
179  KiBitmap( sim_tune_xpm ), _( "Tune component values" ), wxITEM_NORMAL );
180  m_toolSettings = m_toolBar->AddTool( wxID_ANY, _( "Settings" ),
181  KiBitmap( sim_settings_xpm ), _( "Simulation settings" ), wxITEM_NORMAL );
182 
183  Connect( m_toolSimulate->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
184  wxCommandEventHandler( SIM_PLOT_FRAME::onSimulate ), NULL, this );
185  Connect( m_toolAddSignals->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
186  wxCommandEventHandler( SIM_PLOT_FRAME::onAddSignal ), NULL, this );
187  Connect( m_toolProbe->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
188  wxCommandEventHandler( SIM_PLOT_FRAME::onProbe ), NULL, this );
189  Connect( m_toolTune->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
190  wxCommandEventHandler( SIM_PLOT_FRAME::onTune ), NULL, this );
191  Connect( m_toolSettings->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
192  wxCommandEventHandler( SIM_PLOT_FRAME::onSettings ), NULL, this );
193 
194  // Bind toolbar buttons event to existing menu event handlers, so they behave the same
195  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onSimulate, this, m_runSimulation->GetId() );
196  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onAddSignal, this, m_addSignals->GetId() );
197  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onProbe, this, m_probeSignals->GetId() );
198  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onTune, this, m_tuneValue->GetId() );
199  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onShowNetlist, this, m_showNetlist->GetId() );
200  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onSettings, this, m_settings->GetId() );
201 
202  m_toolBar->Realize();
203  m_plotNotebook->SetPageText( 0, _( "Welcome!" ) );
204 
205  // the settings dialog will be created later, on demand.
206  // if created in the ctor, for some obscure reason, there is an issue
207  // on Windows: when open it, the simulator frame is sent to the background.
208  // instead of being behind the dialog frame (as it does)
209  m_settingsDlg = NULL;
210 
211  // resize the subwindows size. At least on Windows, calling wxSafeYield before
212  // resizing the subwindows forces the wxSplitWindows size events automatically generated
213  // by wxWidgets to be executed before our resize code.
214  // Otherwise, the changes made by setSubWindowsSashSize are overwritten by one these
215  // events
216  wxSafeYield();
218 }
219 
220 
222 {
223  m_simulator->SetReporter( nullptr );
224  delete m_reporter;
225  delete m_signalsIconColorList;
226 
227  if( m_settingsDlg )
228  m_settingsDlg->Destroy();
229 }
230 
231 #define PLOT_PANEL_WIDTH_ENTRY "SimPlotPanelWidth"
232 #define PLOT_PANEL_HEIGHT_ENTRY "SimPlotPanelHeight"
233 #define SIGNALS_PANEL_HEIGHT_ENTRY "SimSignalPanelHeight"
234 #define CURSORS_PANEL_HEIGHT_ENTRY "SimCursorsPanelHeight"
235 
236 void SIM_PLOT_FRAME::SaveSettings( wxConfigBase* aCfg )
237 {
238  // Save main frame size and position:
240 
241  // Save subwindows sizes
242  aCfg->Write( PLOT_PANEL_WIDTH_ENTRY, m_splitterLeftRight->GetSashPosition() );
243  aCfg->Write( PLOT_PANEL_HEIGHT_ENTRY, m_splitterPlotAndConsole->GetSashPosition() );
244  aCfg->Write( SIGNALS_PANEL_HEIGHT_ENTRY, m_splitterSignals->GetSashPosition() );
245  aCfg->Write( CURSORS_PANEL_HEIGHT_ENTRY, m_splitterTuneValues->GetSashPosition() );
246 }
247 
248 
249 void SIM_PLOT_FRAME::LoadSettings( wxConfigBase* aCfg )
250 {
251  // Read main frame size and position:
253  SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y );
254 
255  // Read subwindows sizes (should be > 0 )
260 }
261 
262 
263 // A small helper struct to handle bitmaps initialisation in menus
265 {
266  int m_MenuId;
267  BITMAP_DEF m_Bitmap;
268 };
269 
270 
272 {
273  // Give icons to menuitems of the main menubar
274  BM_MENU_INIT_ITEM bm_list[]
275  {
276  // File menu:
277  { wxID_NEW, simulator_xpm },
278  { wxID_OPEN,directory_browser_xpm },
279  { wxID_SAVE, directory_xpm},
280  { ID_SAVE_AS_IMAGE, export_xpm},
281  { ID_SAVE_AS_CSV, export_xpm},
282  { wxID_CLOSE, exit_xpm},
283 
284  // simulator menu:
285  { ID_MENU_RUN_SIM, sim_run_xpm},
286  { ID_MENU_ADD_SIGNAL, sim_add_signal_xpm},
287  { ID_MENU_PROBE_SIGNALS, sim_probe_xpm},
288  { ID_MENU_TUNE_SIGNALS, sim_tune_xpm},
289  { ID_MENU_SHOW_NETLIST, netlist_xpm},
290  { ID_MENU_SET_SIMUL, sim_settings_xpm},
291 
292  // View menu
293  { wxID_ZOOM_IN, zoom_in_xpm},
294  { wxID_ZOOM_OUT, zoom_out_xpm},
295  { wxID_ZOOM_FIT, zoom_fit_in_page_xpm},
296  { ID_MENU_SHOW_GRID, grid_xpm},
298 
299  { 0, nullptr } // Sentinel
300  };
301 
302  // wxMenuItems are already created and attached to the m_mainMenu wxMenuBar.
303  // A problem is the fact setting bitmaps in wxMenuItems after they are attached
304  // to a wxMenu do not work in all cases.
305  // So the trick is:
306  // Remove the wxMenuItem from its wxMenu
307  // Set the bitmap
308  // Insert the modified wxMenuItem to its previous place
309  for( int ii = 0; bm_list[ii].m_MenuId; ++ii )
310  {
311  wxMenuItem* item = m_mainMenu->FindItem( bm_list[ii].m_MenuId );
312 
313  if( !item || !bm_list[ii].m_Bitmap)
314  continue;
315 
316  wxMenu* menu = item->GetMenu();
317  // Calculate the initial index of item inside the wxMenu parent
318  wxMenuItemList& mlist = menu->GetMenuItems();
319  int mpos = mlist.IndexOf( item );
320 
321  if( mpos >= 0 ) // Should be always the case
322  {
323  // Modify the bitmap
324  menu->Remove( item );
325  AddBitmapToMenuItem( item, KiBitmap( bm_list[ii].m_Bitmap ) );
326  // Insert item to its the initial index
327  menu->Insert( mpos, item );
328  }
329  }
330 }
331 
332 
334 {
337 
340 
343 
346 }
347 
348 
350 {
351  STRING_FORMATTER formatter;
352  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
353 
354  if( !m_settingsDlg )
355  m_settingsDlg = new DIALOG_SIM_SETTINGS( this );
356 
357  m_simConsole->Clear();
359 
360  if( plotPanel )
361  m_exporter->SetSimCommand( m_plots[plotPanel].m_simCommand );
362 
363  if( !m_exporter->Format( &formatter, m_settingsDlg->GetNetlistOptions() ) )
364  {
365  DisplayError( this, _( "There were errors during netlist export, aborted." ) );
366  return;
367  }
368 
369  if( m_exporter->GetSimType() == ST_UNKNOWN )
370  {
371  DisplayInfoMessage( this, _( "You need to select the simulation settings first." ) );
372  return;
373  }
374 
375  m_simulator->LoadNetlist( formatter.GetString() );
376  updateTuners();
377  applyTuners();
378  m_simulator->Run();
379 }
380 
381 
383 {
384  m_simulator->Stop();
385 }
386 
387 
389 {
390  return m_simulator ? m_simulator->IsRunning() : false;
391 }
392 
393 
395 {
396  SIM_PLOT_PANEL* plotPanel = new SIM_PLOT_PANEL( aSimType, m_plotNotebook, wxID_ANY );
397 
398  if( m_welcomePanel )
399  {
400  m_plotNotebook->DeletePage( 0 );
401  m_welcomePanel = nullptr;
402  }
403 
404  m_plotNotebook->AddPage( plotPanel, wxString::Format( _( "Plot%u" ),
405  (unsigned int) m_plotNotebook->GetPageCount() + 1 ), true );
406 
407  m_plots[plotPanel] = PLOT_INFO();
408 
409  return plotPanel;
410 }
411 
412 
413 void SIM_PLOT_FRAME::AddVoltagePlot( const wxString& aNetName )
414 {
415  addPlot( aNetName, SPT_VOLTAGE, "V" );
416 }
417 
418 
419 void SIM_PLOT_FRAME::AddCurrentPlot( const wxString& aDeviceName, const wxString& aParam )
420 {
421  addPlot( aDeviceName, SPT_CURRENT, aParam );
422 }
423 
424 
426 {
427  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
428 
429  if( !plotPanel )
430  return;
431 
432  // For now limit the tuner tool to RLC components
433  char primitiveType = NETLIST_EXPORTER_PSPICE::GetSpiceField( SF_PRIMITIVE, aComponent, 0 )[0];
434 
435  if( primitiveType != SP_RESISTOR && primitiveType != SP_CAPACITOR && primitiveType != SP_INDUCTOR )
436  return;
437 
438  const wxString componentName = aComponent->GetField( REFERENCE )->GetText();
439 
440  // Do not add multiple instances for the same component
441  auto tunerIt = std::find_if( m_tuners.begin(), m_tuners.end(), [&]( const TUNER_SLIDER* t )
442  {
443  return t->GetComponentName() == componentName;
444  }
445  );
446 
447  if( tunerIt != m_tuners.end() )
448  return; // We already have it
449 
450  try
451  {
452  TUNER_SLIDER* tuner = new TUNER_SLIDER( this, m_tunePanel, aComponent );
453  m_tuneSizer->Add( tuner );
454  m_tuners.push_back( tuner );
455  m_tunePanel->Layout();
456  }
457  catch( const KI_PARAM_ERROR& e )
458  {
459  // Sorry, no bonus
460  DisplayError( nullptr, e.What() );
461  }
462 }
463 
464 
465 void SIM_PLOT_FRAME::RemoveTuner( TUNER_SLIDER* aTuner, bool aErase )
466 {
467  if( aErase )
468  m_tuners.remove( aTuner );
469 
470  aTuner->Destroy();
471  m_tunePanel->Layout();
472 }
473 
474 
476 {
477  wxWindow* curPage = m_plotNotebook->GetCurrentPage();
478 
479  return ( curPage == m_welcomePanel ) ? nullptr : static_cast<SIM_PLOT_PANEL*>( curPage );
480 }
481 
482 
484 {
485  return m_exporter.get();
486 }
487 
488 
489 void SIM_PLOT_FRAME::addPlot( const wxString& aName, SIM_PLOT_TYPE aType, const wxString& aParam )
490 {
491  SIM_TYPE simType = m_exporter->GetSimType();
492 
493  if( simType == ST_UNKNOWN )
494  {
495  m_simConsole->AppendText( _( "Error: simulation type not defined!\n" ) );
496  m_simConsole->SetInsertionPointEnd();
497  return;
498  }
499  else if( !SIM_PLOT_PANEL::IsPlottable( simType ) )
500  {
501  m_simConsole->AppendText( _( "Error: simulation type doesn't support plotting!\n" ) );
502  m_simConsole->SetInsertionPointEnd();
503  return;
504  }
505 
506  // Create a new plot if the current one displays a different type
507  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
508 
509  if( !plotPanel || plotPanel->GetType() != simType )
510  plotPanel = NewPlotPanel( simType );
511 
512  TRACE_DESC descriptor( *m_exporter, aName, aType, aParam );
513 
514  bool updated = false;
515  SIM_PLOT_TYPE xAxisType = GetXAxisType( simType );
516 
517  if( xAxisType == SPT_LIN_FREQUENCY || xAxisType == SPT_LOG_FREQUENCY )
518  {
519  int baseType = descriptor.GetType() & ~( SPT_AC_MAG | SPT_AC_PHASE );
520 
521  // Add two plots: magnitude & phase
522  TRACE_DESC mag_desc( *m_exporter, descriptor, (SIM_PLOT_TYPE)( baseType | SPT_AC_MAG ) );
523  TRACE_DESC phase_desc( *m_exporter, descriptor, (SIM_PLOT_TYPE)( baseType | SPT_AC_PHASE ) );
524 
525  updated |= updatePlot( mag_desc, plotPanel );
526  updated |= updatePlot( phase_desc, plotPanel );
527  }
528  else
529  {
530  updated = updatePlot( descriptor, plotPanel );
531  }
532 
533  if( updated )
534  {
536  }
537 }
538 
539 
540 void SIM_PLOT_FRAME::removePlot( const wxString& aPlotName, bool aErase )
541 {
542  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
543 
544  if( !plotPanel )
545  return;
546 
547  if( aErase )
548  {
549  auto& traceMap = m_plots[plotPanel].m_traces;
550  auto traceIt = traceMap.find( aPlotName );
551  wxASSERT( traceIt != traceMap.end() );
552  traceMap.erase( traceIt );
553  }
554 
555  wxASSERT( plotPanel->TraceShown( aPlotName ) );
556  plotPanel->DeleteTrace( aPlotName );
557  plotPanel->Fit();
558 
560  updateCursors();
561 }
562 
563 
565 {
567 }
568 
569 
570 bool SIM_PLOT_FRAME::updatePlot( const TRACE_DESC& aDescriptor, SIM_PLOT_PANEL* aPanel )
571 {
572  SIM_TYPE simType = m_exporter->GetSimType();
573  wxString spiceVector = m_exporter->GetSpiceVector( aDescriptor.GetName(),
574  aDescriptor.GetType(), aDescriptor.GetParam() );
575 
576  if( !SIM_PLOT_PANEL::IsPlottable( simType ) )
577  {
578  // There is no plot to be shown
579  m_simulator->Command( wxString::Format( "print %s", spiceVector ).ToStdString() );
580 
581  return false;
582  }
583 
584  // First, handle the x axis
585  wxString xAxisName( m_simulator->GetXAxis( simType ) );
586 
587  if( xAxisName.IsEmpty() )
588  return false;
589 
590  auto data_x = m_simulator->GetMagPlot( (const char*) xAxisName.c_str() );
591  unsigned int size = data_x.size();
592 
593  if( data_x.empty() )
594  return false;
595 
596  SIM_PLOT_TYPE plotType = aDescriptor.GetType();
597  std::vector<double> data_y;
598 
599  // Now, Y axis data
600  switch( m_exporter->GetSimType() )
601  {
602  case ST_AC:
603  {
604  wxASSERT_MSG( !( ( plotType & SPT_AC_MAG ) && ( plotType & SPT_AC_PHASE ) ),
605  "Cannot set both AC_PHASE and AC_MAG bits" );
606 
607  if( plotType & SPT_AC_MAG )
608  data_y = m_simulator->GetMagPlot( (const char*) spiceVector.c_str() );
609  else if( plotType & SPT_AC_PHASE )
610  data_y = m_simulator->GetPhasePlot( (const char*) spiceVector.c_str() );
611  else
612  wxASSERT_MSG( false, "Plot type missing AC_PHASE or AC_MAG bit" );
613  }
614  break;
615 
616  case ST_NOISE:
617  case ST_DC:
618  case ST_TRANSIENT:
619  {
620  data_y = m_simulator->GetMagPlot( (const char*) spiceVector.c_str() );
621  }
622  break;
623 
624  default:
625  wxASSERT_MSG( false, "Unhandled plot type" );
626  return false;
627  }
628 
629  if( data_y.size() != size )
630  return false;
631 
632  // If we did a two-source DC analysis, we need to split the resulting vector and add traces
633  // for each input step
634  SPICE_DC_PARAMS source1, source2;
635 
636  if( m_exporter->GetSimType() == ST_DC &&
637  m_exporter->ParseDCCommand( m_exporter->GetUsedSimCommand(), &source1, &source2 ) )
638  {
639  if( !source2.m_source.IsEmpty() )
640  {
641  // Source 1 is the inner loop, so lets add traces for each Source 2 (outer loop) step
642  SPICE_VALUE v = source2.m_vstart;
643  wxString name;
644 
645  size_t offset = 0;
646  size_t outer = ( size_t )( ( source2.m_vend - v ) / source2.m_vincrement ).ToDouble();
647  size_t inner = data_x.size() / ( outer + 1 );
648 
649  wxASSERT( data_x.size() % ( outer + 1 ) == 0 );
650 
651  for( size_t idx = 0; idx <= outer; idx++ )
652  {
653  name = wxString::Format( "%s (%s = %s V)", aDescriptor.GetTitle(),
654  source2.m_source, v.ToString() );
655 
656  std::vector<double> sub_x( data_x.begin() + offset,
657  data_x.begin() + offset + inner );
658  std::vector<double> sub_y( data_y.begin() + offset,
659  data_y.begin() + offset + inner );
660 
661  if( aPanel->AddTrace( name, inner,
662  sub_x.data(), sub_y.data(), aDescriptor.GetType() ) )
663  {
664  m_plots[aPanel].m_traces.insert( std::make_pair( name, aDescriptor ) );
665  }
666 
667  v = v + source2.m_vincrement;
668  offset += inner;
669  }
670 
671  return true;
672  }
673  }
674 
675  if( aPanel->AddTrace( aDescriptor.GetTitle(), size,
676  data_x.data(), data_y.data(), aDescriptor.GetType() ) )
677  {
678  m_plots[aPanel].m_traces.insert( std::make_pair( aDescriptor.GetTitle(), aDescriptor ) );
679  }
680 
681  return true;
682 }
683 
684 
686 {
687  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
688 
689  if( !plotPanel )
690  return;
691 
692  m_signals->ClearAll();
693 
694  wxSize size = m_signals->GetClientSize();
695  m_signals->AppendColumn( _( "Signal" ), wxLIST_FORMAT_LEFT, size.x );
696 
697  // Build an image list, to show the color of the corresponding trace
698  // in the plot panel
699  // This image list is used for trace and cursor lists
700  wxMemoryDC bmDC;
701  const int isize = bmDC.GetCharHeight();
702 
703  if( m_signalsIconColorList == NULL )
704  m_signalsIconColorList = new wxImageList( isize, isize, false );
705  else
706  m_signalsIconColorList->RemoveAll();
707 
708  for( const auto& trace : CurrentPlot()->GetTraces() )
709  {
710  wxBitmap bitmap( isize, isize );
711  bmDC.SelectObject( bitmap );
712  wxColour tcolor = trace.second->GetTraceColour();
713 
714  wxColour bgColor = m_signals->wxWindow::GetBackgroundColour();
715  bmDC.SetPen( wxPen( bgColor ) );
716  bmDC.SetBrush( wxBrush( bgColor ) );
717  bmDC.DrawRectangle( 0, 0, isize, isize ); // because bmDC.Clear() does not work in wxGTK
718 
719  bmDC.SetPen( wxPen( tcolor ) );
720  bmDC.SetBrush( wxBrush( tcolor ) );
721  bmDC.DrawRectangle( 0, isize / 4 + 1, isize, isize / 2 );
722 
723  bmDC.SelectObject( wxNullBitmap ); // Needed to initialize bitmap
724 
725  bitmap.SetMask( new wxMask( bitmap, *wxBLACK ) );
726  m_signalsIconColorList->Add( bitmap );
727  }
728 
729  if( bmDC.IsOk() )
730  {
731  bmDC.SetBrush( wxNullBrush );
732  bmDC.SetPen( wxNullPen );
733  }
734 
735  m_signals->SetImageList( m_signalsIconColorList, wxIMAGE_LIST_SMALL );
736 
737  // Fill the signals listctrl. Keep the order of names and
738  // the order of icon color identical, because the icons
739  // are also used in cursor list, and the color index is
740  // calculated from the trace name index
741  int imgidx = 0;
742 
743  for( const auto& trace : m_plots[plotPanel].m_traces )
744  {
745  m_signals->InsertItem( imgidx, trace.first, imgidx );
746  imgidx++;
747  }
748 }
749 
750 
752 {
753  wxQueueEvent( this, new wxCommandEvent( EVT_SIM_CURSOR_UPDATE ) );
754 }
755 
756 
758 {
759  const auto& spiceItems = m_exporter->GetSpiceItems();
760 
761  for( auto it = m_tuners.begin(); it != m_tuners.end(); /* iteration inside the loop */ )
762  {
763  const wxString& ref = (*it)->GetComponentName();
764 
765  if( std::find_if( spiceItems.begin(), spiceItems.end(), [&]( const SPICE_ITEM& item )
766  {
767  return item.m_refName == ref;
768  }) == spiceItems.end() )
769  {
770  // The component does not exist anymore, remove the associated tuner
771  TUNER_SLIDER* tuner = *it;
772  it = m_tuners.erase( it );
773  RemoveTuner( tuner, false );
774  }
775  else
776  {
777  ++it;
778  }
779  }
780 }
781 
782 
784 {
785  for( auto& tuner : m_tuners )
786  {
788  std::string command( "alter @" + tuner->GetSpiceName()
789  + "=" + tuner->GetValue().ToSpiceString() );
790 
791  m_simulator->Command( command );
792  }
793 }
794 
795 
796 bool SIM_PLOT_FRAME::loadWorkbook( const wxString& aPath )
797 {
798  m_plots.clear();
799  m_plotNotebook->DeleteAllPages();
800 
801  wxTextFile file( aPath );
802 
803  if( !file.Open() )
804  return false;
805 
806  long plotsCount;
807 
808  if( !file.GetFirstLine().ToLong( &plotsCount ) ) // GetFirstLine instead of GetNextLine
809  return false;
810 
811  for( long i = 0; i < plotsCount; ++i )
812  {
813  long plotType, tracesCount;
814 
815  if( !file.GetNextLine().ToLong( &plotType ) )
816  return false;
817 
818  SIM_PLOT_PANEL* plotPanel = NewPlotPanel( (SIM_TYPE) plotType );
819  m_plots[plotPanel].m_simCommand = file.GetNextLine();
820  StartSimulation();
821 
822  // Perform simulation, so plots can be added with values
823  do
824  {
825  wxThread::This()->Sleep( 50 );
826  }
827  while( IsSimulationRunning() );
828 
829  if( !file.GetNextLine().ToLong( &tracesCount ) )
830  return false;
831 
832  for( long j = 0; j < tracesCount; ++j )
833  {
834  long traceType;
835  wxString name, param;
836 
837  if( !file.GetNextLine().ToLong( &traceType ) )
838  return false;
839 
840  name = file.GetNextLine();
841  param = file.GetNextLine();
842 
843  if( name.IsEmpty() || param.IsEmpty() )
844  return false;
845 
846  addPlot( name, (SIM_PLOT_TYPE) traceType, param );
847  }
848  }
849 
850  return true;
851 }
852 
853 
854 bool SIM_PLOT_FRAME::saveWorkbook( const wxString& aPath )
855 {
856 
857  wxString savePath = aPath;
858 
859  if( !savePath.Lower().EndsWith(".wbk"))
860  {
861  savePath += ".wbk";
862  };
863 
864 
865  wxTextFile file( savePath );
866 
867  if( file.Exists() )
868  {
869  if( !file.Open() )
870  return false;
871 
872  file.Clear();
873  }
874  else
875  {
876  file.Create();
877  }
878 
879  file.AddLine( wxString::Format( "%lu", m_plots.size() ) );
880 
881  for( const auto& plot : m_plots )
882  {
883  file.AddLine( wxString::Format( "%d", plot.first->GetType() ) );
884  file.AddLine( plot.second.m_simCommand );
885  file.AddLine( wxString::Format( "%lu", plot.second.m_traces.size() ) );
886 
887  for( const auto& trace : plot.second.m_traces )
888  {
889  file.AddLine( wxString::Format( "%d", trace.second.GetType() ) );
890  file.AddLine( trace.second.GetName() );
891  file.AddLine( trace.second.GetParam() );
892  }
893  }
894 
895  bool res = file.Write();
896  file.Close();
897 
898  return res;
899 }
900 
901 
903 {
904  switch( aType )
905  {
906  case ST_AC:
907  return SPT_LIN_FREQUENCY;
909 
910  case ST_DC:
911  return SPT_SWEEP;
912 
913  case ST_TRANSIENT:
914  return SPT_TIME;
915 
916  default:
917  wxASSERT_MSG( false, "Unhandled simulation type" );
918  return (SIM_PLOT_TYPE) 0;
919  }
920 }
921 
922 
923 void SIM_PLOT_FRAME::menuNewPlot( wxCommandEvent& aEvent )
924 {
925  SIM_TYPE type = m_exporter->GetSimType();
926 
927  if( SIM_PLOT_PANEL::IsPlottable( type ) )
928  {
929  SIM_PLOT_PANEL* prevPlot = CurrentPlot();
930  SIM_PLOT_PANEL* newPlot = NewPlotPanel( type );
931 
932  // If the previous plot had the same type, copy the simulation command
933  if( prevPlot )
934  m_plots[newPlot].m_simCommand = m_plots[prevPlot].m_simCommand;
935  }
936 }
937 
938 
939 void SIM_PLOT_FRAME::menuOpenWorkbook( wxCommandEvent& event )
940 {
941  wxFileDialog openDlg( this, _( "Open simulation workbook" ), m_savedWorkbooksPath, "",
942  WorkbookFileWildcard(), wxFD_OPEN | wxFD_FILE_MUST_EXIST );
943 
944  if( openDlg.ShowModal() == wxID_CANCEL )
945  return;
946 
947  m_savedWorkbooksPath = openDlg.GetDirectory();
948 
949  if( !loadWorkbook( openDlg.GetPath() ) )
950  DisplayError( this, _( "There was an error while opening the workbook file" ) );
951 }
952 
953 
954 void SIM_PLOT_FRAME::menuSaveWorkbook( wxCommandEvent& event )
955 {
956  if( !CurrentPlot() )
957  return;
958 
959  wxFileDialog saveDlg( this, _( "Save Simulation Workbook" ), m_savedWorkbooksPath, "",
960  WorkbookFileWildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
961 
962  if( saveDlg.ShowModal() == wxID_CANCEL )
963  return;
964 
965  m_savedWorkbooksPath = saveDlg.GetDirectory();
966 
967  if( !saveWorkbook( saveDlg.GetPath() ) )
968  DisplayError( this, _( "There was an error while saving the workbook file" ) );
969 }
970 
971 
972 void SIM_PLOT_FRAME::menuSaveImage( wxCommandEvent& event )
973 {
974  if( !CurrentPlot() )
975  return;
976 
977  wxFileDialog saveDlg( this, _( "Save Plot as Image" ), "", "",
978  PngFileWildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
979 
980  if( saveDlg.ShowModal() == wxID_CANCEL )
981  return;
982 
983  CurrentPlot()->SaveScreenshot( saveDlg.GetPath(), wxBITMAP_TYPE_PNG );
984 }
985 
986 
987 void SIM_PLOT_FRAME::menuSaveCsv( wxCommandEvent& event )
988 {
989  if( !CurrentPlot() )
990  return;
991 
992  const wxChar SEPARATOR = ';';
993 
994  wxFileDialog saveDlg( this, _( "Save Plot Data" ), "", "",
995  CsvFileWildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
996 
997  if( saveDlg.ShowModal() == wxID_CANCEL )
998  return;
999 
1000  wxFile out( saveDlg.GetPath(), wxFile::write );
1001  bool timeWritten = false;
1002 
1003  for( const auto& t : CurrentPlot()->GetTraces() )
1004  {
1005  const TRACE* trace = t.second;
1006 
1007  if( !timeWritten )
1008  {
1009  out.Write( wxString::Format( "Time%c", SEPARATOR ) );
1010 
1011  for( double v : trace->GetDataX() )
1012  out.Write( wxString::Format( "%f%c", v, SEPARATOR ) );
1013 
1014  out.Write( "\r\n" );
1015  timeWritten = true;
1016  }
1017 
1018  out.Write( wxString::Format( "%s%c", t.first, SEPARATOR ) );
1019 
1020  for( double v : trace->GetDataY() )
1021  out.Write( wxString::Format( "%f%c", v, SEPARATOR ) );
1022 
1023  out.Write( "\r\n" );
1024  }
1025 
1026  out.Close();
1027 }
1028 
1029 
1030 void SIM_PLOT_FRAME::menuZoomIn( wxCommandEvent& event )
1031 {
1032  if( CurrentPlot() )
1033  CurrentPlot()->ZoomIn();
1034 }
1035 
1036 
1037 void SIM_PLOT_FRAME::menuZoomOut( wxCommandEvent& event )
1038 {
1039  if( CurrentPlot() )
1040  CurrentPlot()->ZoomOut();
1041 }
1042 
1043 
1044 void SIM_PLOT_FRAME::menuZoomFit( wxCommandEvent& event )
1045 {
1046  if( CurrentPlot() )
1047  CurrentPlot()->Fit();
1048 }
1049 
1050 
1051 void SIM_PLOT_FRAME::menuShowGrid( wxCommandEvent& event )
1052 {
1053  SIM_PLOT_PANEL* plot = CurrentPlot();
1054 
1055  if( plot )
1056  plot->ShowGrid( !plot->IsGridShown() );
1057 }
1058 
1059 
1060 void SIM_PLOT_FRAME::menuShowGridUpdate( wxUpdateUIEvent& event )
1061 {
1062  SIM_PLOT_PANEL* plot = CurrentPlot();
1063 
1064  event.Check( plot ? plot->IsGridShown() : false );
1065 }
1066 
1067 
1068 void SIM_PLOT_FRAME::menuShowLegend( wxCommandEvent& event )
1069 {
1070  SIM_PLOT_PANEL* plot = CurrentPlot();
1071 
1072  if( plot )
1073  plot->ShowLegend( !plot->IsLegendShown() );
1074 }
1075 
1076 
1077 void SIM_PLOT_FRAME::menuShowLegendUpdate( wxUpdateUIEvent& event )
1078 {
1079  SIM_PLOT_PANEL* plot = CurrentPlot();
1080  event.Check( plot ? plot->IsLegendShown() : false );
1081 }
1082 
1083 
1084 void SIM_PLOT_FRAME::onPlotClose( wxAuiNotebookEvent& event )
1085 {
1086  int idx = event.GetSelection();
1087 
1088  if( idx == wxNOT_FOUND )
1089  return;
1090 
1091  SIM_PLOT_PANEL* plotPanel = dynamic_cast<SIM_PLOT_PANEL*>( m_plotNotebook->GetPage( idx ) );
1092 
1093  if( !plotPanel )
1094  return;
1095 
1096  m_plots.erase( plotPanel );
1097  updateSignalList();
1098  updateCursors();
1099 }
1100 
1101 
1102 void SIM_PLOT_FRAME::onPlotChanged( wxAuiNotebookEvent& event )
1103 {
1104  updateSignalList();
1105  updateCursors();
1106 }
1107 
1108 
1109 void SIM_PLOT_FRAME::onSignalDblClick( wxMouseEvent& event )
1110 {
1111  // Remove signal from the plot panel when double clicked
1112  long idx = m_signals->GetFocusedItem();
1113 
1114  if( idx != wxNOT_FOUND )
1115  removePlot( m_signals->GetItemText( idx, 0 ) );
1116 }
1117 
1118 
1119 void SIM_PLOT_FRAME::onSignalRClick( wxListEvent& event )
1120 {
1121  int idx = event.GetIndex();
1122 
1123  if( idx != wxNOT_FOUND )
1124  m_signals->Select( idx );
1125 
1126  idx = m_signals->GetFirstSelected();
1127 
1128  if( idx != wxNOT_FOUND )
1129  {
1130  const wxString& netName = m_signals->GetItemText( idx, 0 );
1131  SIGNAL_CONTEXT_MENU ctxMenu( netName, this );
1132  m_signals->PopupMenu( &ctxMenu );
1133  }
1134 }
1135 
1136 
1137 void SIM_PLOT_FRAME::onSimulate( wxCommandEvent& event )
1138 {
1139  if( IsSimulationRunning() )
1140  StopSimulation();
1141  else
1142  StartSimulation();
1143 }
1144 
1145 
1146 void SIM_PLOT_FRAME::onSettings( wxCommandEvent& event )
1147 {
1148  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
1149 
1150  // Initial processing is required to e.g. display a list of power sources
1152 
1153  if( !m_exporter->ProcessNetlist( NET_ALL_FLAGS ) )
1154  {
1155  DisplayError( this, _( "There were errors during netlist export, aborted." ) );
1156  return;
1157  }
1158 
1159  if( !m_settingsDlg )
1160  m_settingsDlg = new DIALOG_SIM_SETTINGS( this );
1161 
1162  if( plotPanel )
1163  m_settingsDlg->SetSimCommand( m_plots[plotPanel].m_simCommand );
1164 
1166 
1167  if( m_settingsDlg->ShowModal() == wxID_OK )
1168  {
1169  wxString newCommand = m_settingsDlg->GetSimCommand();
1170  SIM_TYPE newSimType = NETLIST_EXPORTER_PSPICE_SIM::CommandToSimType( newCommand );
1171 
1172  // If it is a new simulation type, open a new plot
1173  if( !plotPanel || ( plotPanel && plotPanel->GetType() != newSimType ) )
1174  {
1175  plotPanel = NewPlotPanel( newSimType );
1176  }
1177 
1178  m_plots[plotPanel].m_simCommand = newCommand;
1179  }
1180 }
1181 
1182 
1183 void SIM_PLOT_FRAME::onAddSignal( wxCommandEvent& event )
1184 {
1185  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
1186 
1187  if( !plotPanel || !m_exporter || plotPanel->GetType() != m_exporter->GetSimType() )
1188  {
1189  DisplayInfoMessage( this, _( "You need to run simulation first." ) );
1190  return;
1191  }
1192 
1193  DIALOG_SIGNAL_LIST dialog( this, m_exporter.get() );
1194  dialog.ShowModal();
1195 }
1196 
1197 
1198 void SIM_PLOT_FRAME::onProbe( wxCommandEvent& event )
1199 {
1200  if( m_schematicFrame == NULL )
1201  return;
1202 
1204  m_schematicFrame->Raise();
1205 }
1206 
1207 
1208 void SIM_PLOT_FRAME::onTune( wxCommandEvent& event )
1209 {
1210  if( m_schematicFrame == NULL )
1211  return;
1212 
1214  m_schematicFrame->Raise();
1215 }
1216 
1217 void SIM_PLOT_FRAME::onShowNetlist( wxCommandEvent& event )
1218 {
1219  class NETLIST_VIEW_DIALOG : public wxDialog
1220  {
1221  public:
1222  enum
1223  {
1224  MARGIN_LINE_NUMBERS
1225  };
1226 
1227  void onClose( wxCloseEvent& evt )
1228  {
1229  EndModal( GetReturnCode() );
1230  }
1231 
1232  NETLIST_VIEW_DIALOG(wxWindow* parent, wxString source) :
1233  wxDialog(parent, wxID_ANY, "SPICE Netlist",
1234  wxDefaultPosition, wxSize(1500,900),
1235  wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
1236  {
1237  wxStyledTextCtrl* text = new wxStyledTextCtrl( this, wxID_ANY );
1238 
1239  text->SetMarginWidth( MARGIN_LINE_NUMBERS, 50 );
1240  text->StyleSetForeground( wxSTC_STYLE_LINENUMBER, wxColour( 75, 75, 75 ) );
1241  text->StyleSetBackground( wxSTC_STYLE_LINENUMBER, wxColour( 220, 220, 220 ) );
1242  text->SetMarginType( MARGIN_LINE_NUMBERS, wxSTC_MARGIN_NUMBER );
1243 
1244  text->SetWrapMode( wxSTC_WRAP_WORD );
1245 
1246  text->SetText( source );
1247 
1248  text->StyleClearAll();
1249  text->SetLexer( wxSTC_LEX_SPICE );
1250 
1251  wxBoxSizer* sizer = new wxBoxSizer( wxVERTICAL );
1252  sizer->Add( text, 1, wxEXPAND );
1253  SetSizer( sizer );
1254 
1255  Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( NETLIST_VIEW_DIALOG::onClose ), NULL,
1256  this );
1257  }
1258  };
1259 
1260  if( m_schematicFrame == NULL || m_simulator == NULL )
1261  return;
1262 
1263  NETLIST_VIEW_DIALOG dlg( this, m_simulator->GetNetlist() );
1264  dlg.ShowModal();
1265 }
1266 
1267 
1268 void SIM_PLOT_FRAME::onClose( wxCloseEvent& aEvent )
1269 {
1270  SaveSettings( config() );
1271 
1272  if( IsSimulationRunning() )
1273  m_simulator->Stop();
1274 
1275  // Cancel a running simProbe or simTune tool
1277 
1278  Destroy();
1279 }
1280 
1281 
1282 void SIM_PLOT_FRAME::onCursorUpdate( wxCommandEvent& event )
1283 {
1284  wxSize size = m_cursors->GetClientSize();
1285  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
1286  m_cursors->ClearAll();
1287 
1288  if( !plotPanel )
1289  return;
1290 
1292  m_cursors->SetImageList(m_signalsIconColorList, wxIMAGE_LIST_SMALL);
1293 
1294  // Fill the signals listctrl
1295  m_cursors->AppendColumn( _( "Signal" ), wxLIST_FORMAT_LEFT, size.x / 2 );
1296  const long X_COL = m_cursors->AppendColumn( plotPanel->GetLabelX(), wxLIST_FORMAT_LEFT, size.x / 4 );
1297 
1298  wxString labelY1 = plotPanel->GetLabelY1();
1299  wxString labelY2 = plotPanel->GetLabelY2();
1300  wxString labelY;
1301 
1302  if( !labelY2.IsEmpty() )
1303  labelY = labelY1 + " / " + labelY2;
1304  else
1305  labelY = labelY1;
1306 
1307  const long Y_COL = m_cursors->AppendColumn( labelY, wxLIST_FORMAT_LEFT, size.x / 4 );
1308 
1309  // Update cursor values
1310  int itemidx = 0;
1311  for( const auto& trace : plotPanel->GetTraces() )
1312  {
1313  if( CURSOR* cursor = trace.second->GetCursor() )
1314  {
1315  // Find the right icon color in list.
1316  // It is the icon used in m_signals list for the same trace
1317  long iconColor = m_signals->FindItem( -1, trace.first );
1318 
1319  const wxRealPoint coords = cursor->GetCoords();
1320  long idx = m_cursors->InsertItem( itemidx++, trace.first, iconColor );
1321  m_cursors->SetItem( idx, X_COL, SPICE_VALUE( coords.x ).ToSpiceString() );
1322  m_cursors->SetItem( idx, Y_COL, SPICE_VALUE( coords.y ).ToSpiceString() );
1323  }
1324  }
1325 }
1326 
1327 
1328 void SIM_PLOT_FRAME::onSimStarted( wxCommandEvent& aEvent )
1329 {
1330  m_toolBar->SetToolNormalBitmap( ID_SIM_RUN, KiBitmap( sim_stop_xpm ) );
1331  SetCursor( wxCURSOR_ARROWWAIT );
1332 }
1333 
1334 
1335 void SIM_PLOT_FRAME::onSimFinished( wxCommandEvent& aEvent )
1336 {
1337  m_toolBar->SetToolNormalBitmap( ID_SIM_RUN, KiBitmap( sim_run_xpm ) );
1338  SetCursor( wxCURSOR_ARROW );
1339 
1340  SIM_TYPE simType = m_exporter->GetSimType();
1341 
1342  if( simType == ST_UNKNOWN )
1343  return;
1344 
1345  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
1346 
1347  if( !plotPanel || plotPanel->GetType() != simType )
1348  plotPanel = NewPlotPanel( simType );
1349 
1350  if( IsSimulationRunning() )
1351  return;
1352 
1353  // If there are any signals plotted, update them
1354  if( SIM_PLOT_PANEL::IsPlottable( simType ) )
1355  {
1356  TRACE_MAP& traceMap = m_plots[plotPanel].m_traces;
1357 
1358  for( auto it = traceMap.begin(); it != traceMap.end(); /* iteration occurs in the loop */)
1359  {
1360  if( !updatePlot( it->second, plotPanel ) )
1361  {
1362  removePlot( it->first, false );
1363  it = traceMap.erase( it ); // remove a plot that does not exist anymore
1364  }
1365  else
1366  {
1367  ++it;
1368  }
1369  }
1370 
1371  updateSignalList();
1372  plotPanel->UpdateAll();
1373  plotPanel->ResetScales();
1374  }
1375  else
1376  {
1378  for( const auto& net : m_exporter->GetNetIndexMap() )
1379  {
1380  int node = net.second;
1381 
1382  if( node > 0 )
1383  m_simulator->Command( wxString::Format( "print v(%d)", node ).ToStdString() );
1384  }
1385  }
1386 }
1387 
1388 
1389 void SIM_PLOT_FRAME::onSimUpdate( wxCommandEvent& aEvent )
1390 {
1391  if( IsSimulationRunning() )
1392  StopSimulation();
1393 
1394  if( CurrentPlot() != m_lastSimPlot )
1395  {
1396  // We need to rerun simulation, as the simulator currently stores
1397  // results for another plot
1398  StartSimulation();
1399  }
1400  else
1401  {
1402  // Incremental update
1403  m_simConsole->Clear();
1404  // Do not export netlist, it is already stored in the simulator
1405  applyTuners();
1406  m_simulator->Run();
1407  }
1408 }
1409 
1410 
1411 void SIM_PLOT_FRAME::onSimReport( wxCommandEvent& aEvent )
1412 {
1413  m_simConsole->AppendText( aEvent.GetString() + "\n" );
1414  m_simConsole->SetInsertionPointEnd();
1415 }
1416 
1417 
1419  SIM_PLOT_FRAME* aPlotFrame )
1420  : m_signal( aSignal ), m_plotFrame( aPlotFrame )
1421 {
1423 
1424  AddMenuItem( this, HIDE_SIGNAL, _( "Hide Signal" ),
1425  _( "Erase the signal from plot screen" ),
1426  KiBitmap( delete_xpm ) );
1427 
1428  TRACE* trace = plot->GetTrace( m_signal );
1429 
1430  if( trace->HasCursor() )
1431  AddMenuItem( this, HIDE_CURSOR, _( "Hide Cursor" ), KiBitmap( pcb_target_xpm ) );
1432  else
1433  AddMenuItem( this, SHOW_CURSOR, _( "Show Cursor" ), KiBitmap( pcb_target_xpm ) );
1434 
1435  Connect( wxEVT_COMMAND_MENU_SELECTED, wxMenuEventHandler( SIGNAL_CONTEXT_MENU::onMenuEvent ), NULL, this );
1436 }
1437 
1438 
1440 {
1441  SIM_PLOT_PANEL* plot = m_plotFrame->CurrentPlot();
1442 
1443  switch( aEvent.GetId() )
1444  {
1445  case HIDE_SIGNAL:
1446  m_plotFrame->removePlot( m_signal );
1447  break;
1448 
1449  case SHOW_CURSOR:
1450  plot->EnableCursor( m_signal, true );
1451  break;
1452 
1453  case HIDE_CURSOR:
1454  plot->EnableCursor( m_signal, false );
1455  break;
1456  }
1457 }
1458 
1459 wxDEFINE_EVENT( EVT_SIM_UPDATE, wxCommandEvent );
1460 wxDEFINE_EVENT( EVT_SIM_REPORT, wxCommandEvent );
1461 
1462 wxDEFINE_EVENT( EVT_SIM_STARTED, wxCommandEvent );
1463 wxDEFINE_EVENT( EVT_SIM_FINISHED, wxCommandEvent );
void onAddSignal(wxCommandEvent &event)
#define ID_MENU_PROBE_SIGNALS
#define ID_SAVE_AS_IMAGE
void ZoomOut(const wxPoint &centerPoint=wxDefaultPosition)
Zoom out current view and refresh display.
Definition: mathplot.cpp:2295
bool IsLegendShown() const
bool saveWorkbook(const wxString &aPath)
Saves plot settings to a file.
wxString ToSpiceString() const
Returns string value in Spice format (e.g.
void SetKiway(wxWindow *aDest, KIWAY *aKiway)
Function SetKiway.
wxToolBarToolBase * m_toolProbe
void LoadSettings(wxConfigBase *aCfg) override
Load common frame parameters from a configuration file.
void setIconsForMenuItems()
Give icons to menuitems of the main menubar.
void onSimStarted(wxCommandEvent &aEvent)
KIWAY & Kiway() const
Function Kiway returns a reference to the KIWAY that this object has an opportunity to participate in...
Definition: kiway_holder.h:56
TOOL_MANAGER * GetToolManager() const
Return the MVC controller.
NETLIST_OBJECT_LIST * BuildNetListBase(bool updateStatusText=true)
Create a flat list which stores all connected objects.
void RemoveTuner(TUNER_SLIDER *aTuner, bool aErase=true)
Removes an existing tuner.
wxImageList * m_signalsIconColorList
imagelists uset to add a small coloured icon to signal names and cursors name, the same color as the ...
SIM_PLOT_TYPE operator|(SIM_PLOT_TYPE aFirst, SIM_PLOT_TYPE aSecond)
void onPlotChanged(wxAuiNotebookEvent &event) override
SIM_PLOT_FRAME * m_parent
void onSignalDblClick(wxMouseEvent &event) override
bool SetSimCommand(const wxString &aCommand)
This file is part of the common library.
wxSplitterWindow * m_splitterSignals
const wxString & GetTitle() const
bool HasCursor() const
wxMenuItem * AddMenuItem(wxMenu *aMenu, int aId, const wxString &aText, const wxBitmap &aImage, wxItemKind aType=wxITEM_NORMAL)
Function AddMenuItem is an inline helper function to create and insert a menu item with an icon into ...
Definition: bitmap.cpp:251
#define SIGNALS_PANEL_HEIGHT_ENTRY
void ShowLegend(bool aEnable)
int m_splitterPlotAndConsoleSashPosition
void menuZoomFit(wxCommandEvent &event) override
Structure to represent a schematic component in the Spice simulation.
virtual void SaveSettings(wxConfigBase *aCfg)
Saves common frame parameters to a configuration data file.
const std::vector< double > & GetDataX() const
static bool IsPlottable(SIM_TYPE aSimType)
std::list< TUNER_SLIDER * > m_tuners
List of currently displayed tuners
static TOOL_ACTION cancelInteractive
Definition: actions.h:65
SIM_PLOT_TYPE GetType() const
wxString m_title
Title displayed in the signal list/plot legend
Class SIM_PLOT_FRAME_BASE.
bool IsGridShown() const
bool RunAction(const std::string &aActionName, bool aNow=false, T aParam=NULL)
Function RunAction() Runs the specified action.
Definition: tool_manager.h:109
void menuNewPlot(wxCommandEvent &aEvent) override
void applyTuners()
Applies component values specified using tunder sliders to the current netlist.
void AddVoltagePlot(const wxString &aNetName)
Adds a voltage plot for a given net name.
virtual wxConfigBase * config()
Returns the wxConfigBase used in SaveSettings(), and is overloaded in KICAD_MANAGER_FRAME.
void AddCurrentPlot(const wxString &aDeviceName, const wxString &aParam)
Adds a current plot for a particular device.
Trace descriptor class
Schematic editor (Eeschema) main window.
wxString CsvFileWildcard()
void onSimUpdate(wxCommandEvent &aEvent)
void menuOpenWorkbook(wxCommandEvent &event) override
void menuShowGrid(wxCommandEvent &event) override
void menuZoomIn(wxCommandEvent &event) override
Class REPORTER is a pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:61
void menuZoomOut(wxCommandEvent &event) override
SIM_THREAD_REPORTER * m_reporter
void OnSimStateChange(SPICE_SIMULATOR *aObject, SIM_STATE aNewState) override
std::shared_ptr< SPICE_SIMULATOR > m_simulator
bool updatePlot(const TRACE_DESC &aDescriptor, SIM_PLOT_PANEL *aPanel)
Updates plot in a particular SIM_PLOT_PANEL.
TRACE * GetTrace(const wxString &aName) const
#define ID_SAVE_AS_CSV
VTBL_ENTRY const wxString GetProjectPath() const
Function GetProjectPath returns the full path of the project.
Definition: project.cpp:102
Field Reference of part, i.e. "IC21".
wxString GetLabelY1() const
void updateCursors()
Updates the cursor values list.
wxSplitterWindow * m_splitterTuneValues
static SIM_TYPE CommandToSimType(const wxString &aCmd)
Returns simulation type basing on a simulation command directive.
SIM_PLOT_TYPE GetXAxisType(SIM_TYPE aType) const
Returns X axis for a given simulation type.
void menuSaveCsv(wxCommandEvent &event) override
void onPlotClose(wxAuiNotebookEvent &event) override
const wxString & GetParam() const
wxAuiNotebook * m_plotNotebook
SCH_EDIT_FRAME * m_schematicFrame
SCH_FIELD * GetField(int aFieldNdx) const
Returns a field in this symbol.
bool DeleteTrace(const wxString &aName)
void UpdateAll()
Refresh display.
Definition: mathplot.cpp:2803
void EnableCursor(const wxString &aName, bool aEnable)
Toggles cursor for a particular trace.
SIM_STATE
const wxString & GetSimCommand() const
void setSubWindowsSashSize()
wxBitmap KiBitmap(BITMAP_DEF aBitmap)
Construct a wxBitmap from a memory record, held in a BITMAP_DEF.
Definition: bitmap.cpp:79
#define PLOT_PANEL_WIDTH_ENTRY
wxString ToString() const
Returns string value as when converting double to string (e.g.
SEVERITY
Severity of the reported messages.
Definition: reporter.h:74
std::map< SIM_PLOT_PANEL *, PLOT_INFO > m_plots
Map of plot panels and associated data
SIM_PLOT_PANEL * m_lastSimPlot
Panel that was used as the most recent one for simulations
wxString GetLabelX() const
void AddBitmapToMenuItem(wxMenuItem *aMenu, const wxBitmap &aImage)
Add a bitmap to a menuitem.
Definition: bitmap.cpp:223
VTBL_ENTRY KIWAY_PLAYER * Player(FRAME_T aFrameType, bool doCreate=true, wxTopLevelWindow *aParent=NULL)
Function Player returns the KIWAY_PLAYER* given a FRAME_T.
Definition: kiway.cpp:321
#define ID_MENU_SHOW_NETLIST
wxString GetLabelY2() const
static TOOL_ACTION simTune
Definition: ee_actions.h:199
Helper class to handle Spice way of expressing values (e.g. 10.5 Meg)
Definition: spice_value.h:32
wxSplitterWindow * m_splitterLeftRight
void ZoomIn(const wxPoint &centerPoint=wxDefaultPosition)
Zoom into current view and refresh display.
Definition: mathplot.cpp:2238
#define CURSORS_PANEL_HEIGHT_ENTRY
wxMenuItem * m_runSimulation
#define ID_MENU_TUNE_SIGNALS
void onSimReport(wxCommandEvent &aEvent)
PROJECT & Prj() const
Function Prj returns a reference to the PROJECT "associated with" this KIWAY.
SIM_TYPE
Possible simulation types
Definition: sim_types.h:29
virtual void LoadSettings(wxConfigBase *aCfg)
Load common frame parameters from a configuration file.
void onSimFinished(wxCommandEvent &aEvent)
Interface to receive simulation updates from SPICE_SIMULATOR class.
bool AddTrace(const wxString &aName, int aPoints, const double *aX, const double *aY, SIM_PLOT_TYPE aFlags)
Definition of file extensions used in Kicad.
void onShowNetlist(wxCommandEvent &event)
SIM_THREAD_REPORTER(SIM_PLOT_FRAME *aParent)
void menuShowLegendUpdate(wxUpdateUIEvent &event) override
Class KIWAY is a minimalistic software bus for communications between various DLLs/DSOs (DSOs) within...
Definition: kiway.h:258
wxToolBarToolBase * m_toolAddSignals
Subclass of SIM_PLOT_FRAME_BASE, which is generated by wxFormBuilder.
int m_splitterTuneValuesSashPosition
static std::shared_ptr< SPICE_SIMULATOR > CreateInstance(const std::string &aName)
Creates a simulator instance of particular type (currently only ngspice is handled)
TRACE_DESC(const NETLIST_EXPORTER_PSPICE_SIM &aExporter, const wxString &aName, SIM_PLOT_TYPE aType, const wxString &aParam)
const std::string & GetString()
Definition: richio.h:475
void onSignalRClick(wxListEvent &event) override
void ResetScales()
Resets scale ranges to fit the current traces
bool IsSimulationRunning()
#define ID_MENU_SHOW_LEGEND
void menuShowLegend(wxCommandEvent &event) override
#define PLOT_PANEL_HEIGHT_ENTRY
void ShowGrid(bool aEnable)
#define _(s)
void onTune(wxCommandEvent &event)
wxToolBarToolBase * m_toolSimulate
void menuSaveImage(wxCommandEvent &event) override
#define ID_MENU_SET_SIMUL
wxString PngFileWildcard()
Implementing SIM_PLOT_FRAME_BASE.
bool loadWorkbook(const wxString &aPath)
Loads plot settings from a file.
void SetNetlistExporter(NETLIST_EXPORTER_PSPICE_SIM *aExporter)
static wxString m_savedWorkbooksPath
A string to store the path of saved workbooks during a session
void onCursorUpdate(wxCommandEvent &aEvent)
DIALOG_SIM_SETTINGS * m_settingsDlg
void Fit() override
Set view to fit global bounding box of all plot layers and refresh display.
Definition: mathplot.cpp:1995
const wxString & GetName() const
const wxString What() const
Definition: ki_exception.h:58
#define ID_MENU_ADD_SIGNAL
std::unique_ptr< NETLIST_EXPORTER_PSPICE_SIM > m_exporter
void updateNetlistExporter()
Reloads the current schematic for the netlist exporter.
see class PGM_BASE
void onSimulate(wxCommandEvent &event)
const char * name
Definition: DXF_plotter.cpp:61
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, CPTREE &aTree)
Function Format outputs a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:205
SIGNAL_CONTEXT_MENU(const wxString &aSignal, SIM_PLOT_FRAME *aPlotFrame)
void onProbe(wxCommandEvent &event)
#define ID_MENU_SHOW_GRID
void updateSignalList()
Updates the list of currently plotted signals.
size_t i
Definition: json11.cpp:597
static wxString GetSpiceField(SPICE_FIELD aField, SCH_COMPONENT *aComponent, unsigned aCtl)
Retrieves either the requested field value or the default value.
Class SCH_COMPONENT describes a real schematic component.
Definition: sch_component.h:73
int m_splitterSignalsSashPosition
SIM_PLOT_PANEL * CurrentPlot() const
Returns the currently opened plot panel (or NULL if there is none).
std::map< wxString, TRACE_DESC > TRACE_MAP
wxDEFINE_EVENT(EVT_SIM_UPDATE, wxCommandEvent)
bool Destroy() override
Our version of Destroy() which is virtual from wxWidgets.
SIM_TYPE GetType() const
const std::vector< double > & GetDataY() const
int m_splitterLeftRightSashPosition
static TOOL_ACTION simProbe
Definition: ee_actions.h:198
const NETLIST_EXPORTER_PSPICE_SIM * GetExporter() const
Returns the netlist exporter object used for simulations.
void removePlot(const wxString &aPlotName, bool aErase=true)
Removes a plot with a specific title.
void SaveSettings(wxConfigBase *aCfg) override
Saves common frame parameters to a configuration data file.
Custom widget to handle quick component values modification and simulation on the fly.
Definition: tuner_slider.h:40
void AddTuner(SCH_COMPONENT *aComponent)
Adds a tuner for a component.
wxString WorkbookFileWildcard()
bool SaveScreenshot(const wxString &filename, wxBitmapType type=wxBITMAP_TYPE_BMP, wxSize imageSize=wxDefaultSize, bool fit=false)
Draw the window on a wxBitmap, then save it to a file.
Definition: mathplot.cpp:3033
const std::map< wxString, TRACE * > & GetTraces() const
wxSplitterWindow * m_splitterPlotAndConsole
void menuShowGridUpdate(wxUpdateUIEvent &event) override
bool HasMessage() const override
Function HasMessage Returns true if the reporter client is non-empty.
static const char * text_xpm[]
void menuSaveWorkbook(wxCommandEvent &event) override
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition: confirm.cpp:276
Class STRING_FORMATTER implements OUTPUTFORMATTER to a memory buffer.
Definition: richio.h:445
SIM_PLOT_TYPE
Possible plot types
Definition: sim_types.h:35
REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_UNDEFINED) override
Function Report is a pure virtual function to override in the derived object.
#define ID_MENU_RUN_SIM
void DisplayError(wxWindow *parent, const wxString &text, int displaytime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:243
void addPlot(const wxString &aName, SIM_PLOT_TYPE aType, const wxString &aParam)
Adds a new plot to the current panel.
virtual const wxString & GetText() const
Function GetText returns the string associated with the text object.
Definition: eda_text.h:124
void onSettings(wxCommandEvent &event)
void onClose(wxCloseEvent &aEvent)
wxToolBarToolBase * m_toolTune
void onMenuEvent(wxMenuEvent &aEvent)
SIM_PLOT_PANEL * NewPlotPanel(SIM_TYPE aSimType)
Creates a new plot panel for a given simulation type and adds it to the main notebook.
bool TraceShown(const wxString &aName) const
Cursor attached to a trace to follow its values:
Special netlist exporter flavor that allows one to override simulation commands.
void updateTuners()
Filters out tuners for components that do not exist anymore.
class KI_PARAM_ERROR is a class used to hold a translatable error message and may be used when throwi...
Definition: ki_exception.h:45
wxToolBarToolBase * m_toolSettings
SIM_PLOT_FRAME(KIWAY *aKiway, wxWindow *aParent)
Constructor.