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) 2021 KiCad Developers, see AUTHORS.txt for contributors.
6  *
7  * @author Tomasz Wlostowski <tomasz.wlostowski@cern.ch>
8  * @author Maciej Suminski <maciej.suminski@cern.ch>
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 3
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, you may find one here:
22  * https://www.gnu.org/licenses/gpl-3.0.html
23  * or you may search the http://www.gnu.org website for the version 3 license,
24  * or you may write to the Free Software Foundation, Inc.,
25  * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
26  */
27 
28 #include "sim_plot_colors.h"
29 #include "sim_plot_panel.h"
30 #include "sim_plot_frame.h"
31 
32 #include <algorithm>
33 #include <limits>
34 
35 
formatFloat(double x,int nDigits)36 static wxString formatFloat( double x, int nDigits )
37 {
38     wxString rv, fmt;
39 
40     if( nDigits )
41     {
42         fmt.Printf( "%%.0%df", nDigits );
43     }
44     else
45     {
46         fmt = wxT( "%.0f" );
47     }
48 
49     rv.Printf( fmt, x );
50 
51     return rv;
52 }
53 
54 
getSISuffix(double x,const wxString & unit,int & power,wxString & suffix)55 static void getSISuffix( double x, const wxString& unit, int& power, wxString& suffix )
56 {
57     const int n_powers = 11;
58 
59     const struct
60     {
61         double exponent;
62         char suffix;
63     } powers[] =
64     {
65         { -18, 'a' },
66         { -15, 'f' },
67         { -12, 'p' },
68         { -9,  'n' },
69         { -6,  'u' },
70         { -3,  'm' },
71         { 0,   0   },
72         { 3,   'k' },
73         { 6,   'M' },
74         { 9,   'G' },
75         { 12,  'T' },
76         { 14,  'P' }
77     };
78 
79     power = 0;
80     suffix = unit;
81 
82     if( x == 0.0 )
83         return;
84 
85     for( int i = 0; i < n_powers - 1; i++ )
86     {
87         double r_cur = pow( 10, powers[i].exponent );
88 
89         if( fabs( x ) >= r_cur && fabs( x ) < r_cur * 1000.0 )
90         {
91             power = powers[i].exponent;
92 
93             if( powers[i].suffix )
94                 suffix = wxString( powers[i].suffix ) + unit;
95             else
96                 suffix = unit;
97 
98             return;
99         }
100     }
101 }
102 
103 
countDecimalDigits(double x,int maxDigits)104 static int countDecimalDigits( double x, int maxDigits )
105 {
106     if( std::isnan( x ) )
107     {
108         // avoid trying to count the decimals of NaN
109         return 0;
110     }
111 
112     int64_t k = (int)( ( x - floor( x ) ) * pow( 10.0, (double) maxDigits ) );
113     int n = 0;
114 
115     while( k && ( ( k % 10LL ) == 0LL || ( k % 10LL ) == 9LL ) )
116     {
117         k /= 10LL;
118     }
119 
120     n = 0;
121 
122     while( k != 0LL )
123     {
124         n++;
125         k /= 10LL;
126     }
127 
128     return n;
129 }
130 
131 
132 template <typename parent>
133 class LIN_SCALE : public parent
134 {
135 public:
LIN_SCALE(wxString name,wxString unit,int flags)136     LIN_SCALE( wxString name, wxString unit, int flags ) : parent( name, flags ), m_unit( unit ){};
137 
formatLabels()138     void formatLabels() override
139     {
140         double maxVis = parent::AbsVisibleMaxValue();
141 
142         wxString suffix;
143         int power, digits = 0;
144         int constexpr DIGITS = 3;
145 
146         getSISuffix( maxVis, m_unit, power, suffix );
147 
148         double sf = pow( 10.0, power );
149 
150         for( auto& l : parent::TickLabels() )
151         {
152             int k = countDecimalDigits( l.pos / sf, DIGITS );
153 
154             digits = std::max( digits, k );
155         }
156 
157         for( auto& l : parent::TickLabels() )
158         {
159             l.label = formatFloat( l.pos / sf, digits ) + suffix;
160             l.visible = true;
161         }
162     }
163 
164 private:
165     const wxString m_unit;
166 };
167 
168 
169 template <typename parent>
170 class LOG_SCALE : public parent
171 {
172 public:
LOG_SCALE(wxString name,wxString unit,int flags)173     LOG_SCALE( wxString name, wxString unit, int flags ) : parent( name, flags ), m_unit( unit ){};
174 
formatLabels()175     void formatLabels() override
176     {
177         wxString suffix;
178         int      power;
179 
180         for( auto& l : parent::TickLabels() )
181         {
182             getSISuffix( l.pos, m_unit, power, suffix );
183             double sf = pow( 10.0, power );
184             int    k = countDecimalDigits( l.pos / sf, 3 );
185 
186             l.label = formatFloat( l.pos / sf, k ) + suffix;
187             l.visible = true;
188         }
189     }
190 
191 private:
192     const wxString m_unit;
193 };
194 
195 
Plot(wxDC & aDC,mpWindow & aWindow)196 void CURSOR::Plot( wxDC& aDC, mpWindow& aWindow )
197 {
198     if( !m_window )
199         m_window = &aWindow;
200 
201     if( !m_visible )
202         return;
203 
204     const auto& dataX = m_trace->GetDataX();
205     const auto& dataY = m_trace->GetDataY();
206 
207     if( dataX.size() <= 1 )
208         return;
209 
210     if( m_updateRequired )
211     {
212         m_coords.x = m_trace->s2x( aWindow.p2x( m_dim.x ) );
213 
214         // Find the closest point coordinates
215         auto maxXIt = std::upper_bound( dataX.begin(), dataX.end(), m_coords.x );
216         int maxIdx = maxXIt - dataX.begin();
217         int minIdx = maxIdx - 1;
218 
219         // Out of bounds checks
220         if( minIdx < 0 )
221         {
222             minIdx = 0;
223             maxIdx = 1;
224             m_coords.x = dataX[0];
225         }
226         else if( maxIdx >= (int) dataX.size() )
227         {
228             maxIdx = dataX.size() - 1;
229             minIdx = maxIdx - 1;
230             m_coords.x = dataX[maxIdx];
231         }
232 
233         const double leftX = dataX[minIdx];
234         const double rightX = dataX[maxIdx];
235         const double leftY = dataY[minIdx];
236         const double rightY = dataY[maxIdx];
237 
238         // Linear interpolation
239         m_coords.y = leftY + ( rightY - leftY ) / ( rightX - leftX ) * ( m_coords.x - leftX );
240         m_updateRequired = false;
241 
242         // Notify the parent window about the changes
243         wxQueueEvent( aWindow.GetParent(), new wxCommandEvent( EVT_SIM_CURSOR_UPDATE ) );
244     }
245     else
246     {
247         m_updateRef = true;
248     }
249 
250     if( m_updateRef )
251     {
252         UpdateReference();
253         m_updateRef = false;
254     }
255 
256     // Line length in horizontal and vertical dimensions
257     const wxPoint cursorPos( aWindow.x2p( m_trace->x2s( m_coords.x ) ),
258                              aWindow.y2p( m_trace->y2s( m_coords.y ) ) );
259 
260     wxCoord leftPx   = m_drawOutsideMargins ? 0 : aWindow.GetMarginLeft();
261     wxCoord rightPx  = m_drawOutsideMargins ? aWindow.GetScrX() :
262                                               aWindow.GetScrX() - aWindow.GetMarginRight();
263     wxCoord topPx    = m_drawOutsideMargins ? 0 : aWindow.GetMarginTop();
264     wxCoord bottomPx = m_drawOutsideMargins ? aWindow.GetScrY() :
265                                               aWindow.GetScrY() - aWindow.GetMarginBottom();
266 
267     wxPen pen = GetPen();
268     pen.SetStyle( m_continuous ? wxPENSTYLE_SOLID : wxPENSTYLE_LONG_DASH );
269     aDC.SetPen( pen );
270 
271     if( topPx < cursorPos.y && cursorPos.y < bottomPx )
272         aDC.DrawLine( leftPx, cursorPos.y, rightPx, cursorPos.y );
273 
274     if( leftPx < cursorPos.x && cursorPos.x < rightPx )
275         aDC.DrawLine( cursorPos.x, topPx, cursorPos.x, bottomPx );
276 }
277 
278 
Inside(wxPoint & aPoint)279 bool CURSOR::Inside( wxPoint& aPoint )
280 {
281     if( !m_window )
282         return false;
283 
284     return ( std::abs( (double) aPoint.x -
285                        m_window->x2p( m_trace->x2s( m_coords.x ) ) ) <= DRAG_MARGIN )
286         || ( std::abs( (double) aPoint.y -
287                        m_window->y2p( m_trace->y2s( m_coords.y ) ) ) <= DRAG_MARGIN );
288 }
289 
290 
UpdateReference()291 void CURSOR::UpdateReference()
292 {
293     if( !m_window )
294         return;
295 
296     m_reference.x = m_window->x2p( m_trace->x2s( m_coords.x ) );
297     m_reference.y = m_window->y2p( m_trace->y2s( m_coords.y ) );
298 }
299 
300 
SIM_PLOT_PANEL(const wxString & aCommand,wxWindow * parent,SIM_PLOT_FRAME * aMainFrame,wxWindowID id,const wxPoint & pos,const wxSize & size,long style,const wxString & name)301 SIM_PLOT_PANEL::SIM_PLOT_PANEL( const wxString& aCommand, wxWindow* parent,
302                                 SIM_PLOT_FRAME* aMainFrame, wxWindowID id, const wxPoint& pos,
303                                 const wxSize& size, long style, const wxString& name )
304     : SIM_PANEL_BASE( aCommand, parent, id, pos, size, style, name ),
305       m_axis_x( nullptr ),
306       m_axis_y1( nullptr ),
307       m_axis_y2( nullptr ),
308       m_dotted_cp( false ),
309       m_masterFrame( aMainFrame )
310 {
311     m_sizer   = new wxBoxSizer( wxVERTICAL );
312     m_plotWin = new mpWindow( this, wxID_ANY, pos, size, style );
313 
314     m_plotWin->LimitView( true );
315     m_plotWin->SetMargins( 50, 80, 50, 80 );
316 
317     UpdatePlotColors();
318 
319     updateAxes();
320 
321     // a mpInfoLegend displays le name of traces on the left top panel corner:
322     m_legend = new mpInfoLegend( wxRect( 0, 40, 200, 40 ), wxTRANSPARENT_BRUSH );
323     m_legend->SetVisible( false );
324     m_plotWin->AddLayer( m_legend );
325 
326     m_plotWin->EnableDoubleBuffer( true );
327     m_plotWin->UpdateAll();
328 
329     m_sizer->Add( m_plotWin, 1, wxALL | wxEXPAND, 1 );
330     SetSizer( m_sizer );
331 }
332 
333 
~SIM_PLOT_PANEL()334 SIM_PLOT_PANEL::~SIM_PLOT_PANEL()
335 {
336     // ~mpWindow destroys all the added layers, so there is no need to destroy m_traces contents
337 }
338 
339 
updateAxes()340 void SIM_PLOT_PANEL::updateAxes()
341 {
342     if( m_axis_x )
343         return;
344 
345     switch( GetType() )
346     {
347         case ST_AC:
348             m_axis_x = new LOG_SCALE<mpScaleXLog>( _( "Frequency" ), wxT( "Hz" ), mpALIGN_BOTTOM );
349             m_axis_y1 = new LIN_SCALE<mpScaleY>( _( "Gain" ), wxT( "dBV" ), mpALIGN_LEFT );
350             m_axis_y2 = new LIN_SCALE<mpScaleY>( _( "Phase" ), wxT( "\u00B0" ),
351                                                  mpALIGN_RIGHT ); // degree sign
352             m_axis_y2->SetMasterScale( m_axis_y1 );
353             break;
354 
355         case ST_DC:
356             prepareDCAxes();
357             break;
358 
359         case ST_NOISE:
360             m_axis_x = new LOG_SCALE<mpScaleXLog>( _( "Frequency" ), wxT( "Hz" ), mpALIGN_BOTTOM );
361             m_axis_y1 = new mpScaleY( _( "noise [(V or A)^2/Hz]" ), mpALIGN_LEFT );
362             break;
363 
364         case ST_TRANSIENT:
365             m_axis_x = new LIN_SCALE<mpScaleX>( _( "Time" ), wxT( "s" ), mpALIGN_BOTTOM );
366             m_axis_y1 = new LIN_SCALE<mpScaleY>( _( "Voltage" ), wxT( "V" ), mpALIGN_LEFT );
367             m_axis_y2 = new LIN_SCALE<mpScaleY>( _( "Current" ), wxT( "A" ), mpALIGN_RIGHT );
368             m_axis_y2->SetMasterScale( m_axis_y1 );
369             break;
370 
371         default:
372             // suppress warnings
373             break;
374     }
375 
376     if( m_axis_x )
377     {
378         m_axis_x->SetTicks( false );
379         m_axis_x->SetNameAlign ( mpALIGN_BOTTOM );
380 
381         m_plotWin->AddLayer( m_axis_x );
382     }
383 
384     if( m_axis_y1 )
385     {
386         m_axis_y1->SetTicks( false );
387         m_axis_y1->SetNameAlign ( mpALIGN_LEFT );
388         m_plotWin->AddLayer( m_axis_y1 );
389     }
390 
391     if( m_axis_y2 )
392     {
393         m_axis_y2->SetTicks( false );
394         m_axis_y2->SetNameAlign ( mpALIGN_RIGHT );
395         m_plotWin->AddLayer( m_axis_y2 );
396     }
397 }
398 
prepareDCAxes()399 void SIM_PLOT_PANEL::prepareDCAxes()
400 {
401     wxString sim_cmd = getSimCommand().Lower();
402     wxString rem;
403 
404     if( sim_cmd.StartsWith( ".dc", &rem ) )
405     {
406         wxChar ch;
407 
408         rem.Trim( false );
409 
410         try
411         {
412             ch = rem.GetChar( 0 );
413         }
414         catch( ... )
415         {;}
416 
417         switch( ch )
418         {
419         // Make sure that we have a reliable default (even if incorrectly labeled)
420         default:
421         case 'v':
422             m_axis_x =
423                     new LIN_SCALE<mpScaleX>( _( "Voltage (swept)" ), wxT( "V" ), mpALIGN_BOTTOM );
424             break;
425         case 'i':
426             m_axis_x =
427                     new LIN_SCALE<mpScaleX>( _( "Current (swept)" ), wxT( "A" ), mpALIGN_BOTTOM );
428             break;
429         case 'r':
430             m_axis_x = new LIN_SCALE<mpScaleX>( _( "Resistance (swept)" ), wxT( "\u03A9" ),
431                                                 mpALIGN_BOTTOM );
432             break;
433         case 't':
434             m_axis_x = new LIN_SCALE<mpScaleX>( _( "Temperature (swept)" ), wxT( "\u00B0C" ),
435                                                 mpALIGN_BOTTOM );
436             break;
437         }
438 
439         m_axis_y1 = new LIN_SCALE<mpScaleY>( _( "Voltage (measured)" ), wxT( "V" ), mpALIGN_LEFT );
440         m_axis_y2 = new LIN_SCALE<mpScaleY>( _( "Current" ), wxT( "A" ), mpALIGN_RIGHT );
441     }
442 }
443 
444 
UpdatePlotColors()445 void SIM_PLOT_PANEL::UpdatePlotColors()
446 {
447     // Update bg and fg colors:
448     m_plotWin->SetColourTheme( m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::BACKGROUND ),
449                                m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::FOREGROUND ),
450                                m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::AXIS ) );
451 
452     // Update color of all traces
453     for( auto& t : m_traces )
454         if( t.second->GetCursor() )
455             t.second->GetCursor()->SetPen(
456                     wxPen( m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::CURSOR ) ) );
457 
458     m_plotWin->UpdateAll();
459 }
460 
461 
UpdateTraceStyle(TRACE * trace)462 void SIM_PLOT_PANEL::UpdateTraceStyle( TRACE* trace )
463 {
464     int        type = trace->GetType();
465     wxPenStyle penStyle = ( ( ( type & SPT_AC_PHASE ) || ( type & SPT_CURRENT ) ) && m_dotted_cp )
466                                   ? wxPENSTYLE_DOT
467                                   : wxPENSTYLE_SOLID;
468     trace->SetPen( wxPen( trace->GetTraceColour(), 2, penStyle ) );
469 }
470 
471 
addTrace(const wxString & aTitle,const wxString & aName,int aPoints,const double * aX,const double * aY,SIM_PLOT_TYPE aType,const wxString & aParam)472 bool SIM_PLOT_PANEL::addTrace( const wxString& aTitle, const wxString& aName, int aPoints,
473                                const double* aX, const double* aY, SIM_PLOT_TYPE aType,
474                                const wxString& aParam )
475 {
476     TRACE* trace = nullptr;
477     wxString name = aTitle;
478 
479     updateAxes();
480 
481     // Find previous entry, if there is one
482     auto prev = m_traces.find( name );
483     bool addedNewEntry = ( prev == m_traces.end() );
484 
485     if( addedNewEntry )
486     {
487         if( GetType() == ST_TRANSIENT )
488         {
489             bool hasVoltageTraces = false;
490 
491             for( const auto& tr : m_traces )
492             {
493                 if( !( tr.second->GetType() & SPT_CURRENT ) )
494                 {
495                     hasVoltageTraces = true;
496                     break;
497                 }
498             }
499 
500             if( !hasVoltageTraces )
501                 m_axis_y2->SetMasterScale( nullptr );
502             else
503                 m_axis_y2->SetMasterScale( m_axis_y1 );
504         }
505 
506         // New entry
507         trace = new TRACE( aName, aType, aParam );
508         trace->SetTraceColour( m_colors.GenerateColor( m_traces ) );
509         UpdateTraceStyle( trace );
510         m_traces[name] = trace;
511 
512         // It is a trick to keep legend & coords always on the top
513         for( mpLayer* l : m_topLevel )
514             m_plotWin->DelLayer( l );
515 
516         m_plotWin->AddLayer( (mpLayer*) trace );
517 
518         for( mpLayer* l : m_topLevel )
519             m_plotWin->AddLayer( l );
520     }
521     else
522     {
523         trace = prev->second;
524     }
525 
526     std::vector<double> tmp( aY, aY + aPoints );
527 
528     if( GetType() == ST_AC )
529     {
530         if( aType & SPT_AC_PHASE )
531         {
532             for( int i = 0; i < aPoints; i++ )
533                 tmp[i] = tmp[i] * 180.0 / M_PI;                 // convert to degrees
534         }
535         else
536         {
537             for( int i = 0; i < aPoints; i++ )
538             {
539                 // log( 0 ) is not valid.
540                 if( tmp[i] != 0 )
541                     tmp[i] = 20 * log( tmp[i] ) / log( 10.0 );  // convert to dB
542             }
543         }
544     }
545 
546     trace->SetData( std::vector<double>( aX, aX + aPoints ), tmp );
547 
548     if( ( aType & SPT_AC_PHASE ) || ( aType & SPT_CURRENT ) )
549         trace->SetScale( m_axis_x, m_axis_y2 );
550     else
551         trace->SetScale( m_axis_x, m_axis_y1 );
552 
553     m_plotWin->UpdateAll();
554 
555     return addedNewEntry;
556 }
557 
558 
deleteTrace(const wxString & aName)559 bool SIM_PLOT_PANEL::deleteTrace( const wxString& aName )
560 {
561     auto it = m_traces.find( aName );
562 
563     if( it != m_traces.end() )
564     {
565         TRACE* trace = it->second;
566         m_traces.erase( it );
567 
568         if( CURSOR* cursor = trace->GetCursor() )
569             m_plotWin->DelLayer( cursor, true );
570 
571         m_plotWin->DelLayer( trace, true, true );
572         ResetScales();
573 
574         return true;
575     }
576 
577     return false;
578 }
579 
580 
deleteAllTraces()581 void SIM_PLOT_PANEL::deleteAllTraces()
582 {
583     for( auto& t : m_traces )
584     {
585         deleteTrace( t.first );
586     }
587 
588     m_traces.clear();
589 }
590 
591 
HasCursorEnabled(const wxString & aName) const592 bool SIM_PLOT_PANEL::HasCursorEnabled( const wxString& aName ) const
593 {
594     TRACE* t = GetTrace( aName );
595 
596     return t ? t->HasCursor() : false;
597 }
598 
599 
EnableCursor(const wxString & aName,bool aEnable)600 void SIM_PLOT_PANEL::EnableCursor( const wxString& aName, bool aEnable )
601 {
602     TRACE* t = GetTrace( aName );
603 
604     if( t == nullptr || t->HasCursor() == aEnable )
605         return;
606 
607     if( aEnable )
608     {
609         CURSOR* c = new CURSOR( t, this );
610         int     plotCenter = GetPlotWin()->GetMarginLeft()
611                          + ( GetPlotWin()->GetXScreen() - GetPlotWin()->GetMarginLeft()
612                                    - GetPlotWin()->GetMarginRight() )
613                                    / 2;
614         c->SetX( plotCenter );
615         c->SetPen( wxPen( m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::CURSOR ) ) );
616         t->SetCursor( c );
617         m_plotWin->AddLayer( c );
618     }
619     else
620     {
621         CURSOR* c = t->GetCursor();
622         t->SetCursor( nullptr );
623         m_plotWin->DelLayer( c, true );
624     }
625 
626     // Notify the parent window about the changes
627     wxQueueEvent( GetParent(), new wxCommandEvent( EVT_SIM_CURSOR_UPDATE ) );
628 }
629 
630 
ResetScales()631 void SIM_PLOT_PANEL::ResetScales()
632 {
633     if( m_axis_x )
634         m_axis_x->ResetDataRange();
635 
636     if( m_axis_y1 )
637         m_axis_y1->ResetDataRange();
638 
639     if( m_axis_y2 )
640         m_axis_y2->ResetDataRange();
641 
642     for( auto t : m_traces )
643         t.second->UpdateScales();
644 }
645 
646 
647 wxDEFINE_EVENT( EVT_SIM_CURSOR_UPDATE, wxCommandEvent );
648