You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

646 lines
17 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  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. #include "sim_plot_colors.h"
  28. #include "sim_plot_panel.h"
  29. #include "sim_plot_frame.h"
  30. #include <algorithm>
  31. #include <limits>
  32. static wxString formatFloat( double x, int nDigits )
  33. {
  34. wxString rv, fmt;
  35. if( nDigits )
  36. {
  37. fmt.Printf( "%%.0%df", nDigits );
  38. }
  39. else
  40. {
  41. fmt = wxT( "%.0f" );
  42. }
  43. rv.Printf( fmt, x );
  44. return rv;
  45. }
  46. static void getSISuffix( double x, const wxString& unit, int& power, wxString& suffix )
  47. {
  48. const int n_powers = 11;
  49. const struct
  50. {
  51. double exponent;
  52. char suffix;
  53. } powers[] =
  54. {
  55. { -18, 'a' },
  56. { -15, 'f' },
  57. { -12, 'p' },
  58. { -9, 'n' },
  59. { -6, 'u' },
  60. { -3, 'm' },
  61. { 0, 0 },
  62. { 3, 'k' },
  63. { 6, 'M' },
  64. { 9, 'G' },
  65. { 12, 'T' },
  66. { 14, 'P' }
  67. };
  68. power = 0;
  69. suffix = unit;
  70. if( x == 0.0 )
  71. return;
  72. for( int i = 0; i < n_powers - 1; i++ )
  73. {
  74. double r_cur = pow( 10, powers[i].exponent );
  75. if( fabs( x ) >= r_cur && fabs( x ) < r_cur * 1000.0 )
  76. {
  77. power = powers[i].exponent;
  78. if( powers[i].suffix )
  79. suffix = wxString( powers[i].suffix ) + unit;
  80. else
  81. suffix = unit;
  82. return;
  83. }
  84. }
  85. }
  86. static int countDecimalDigits( double x, int maxDigits )
  87. {
  88. if( std::isnan( x ) )
  89. {
  90. // avoid trying to count the decimals of NaN
  91. return 0;
  92. }
  93. int64_t k = (int)( ( x - floor( x ) ) * pow( 10.0, (double) maxDigits ) );
  94. int n = 0;
  95. while( k && ( ( k % 10LL ) == 0LL || ( k % 10LL ) == 9LL ) )
  96. {
  97. k /= 10LL;
  98. }
  99. n = 0;
  100. while( k != 0LL )
  101. {
  102. n++;
  103. k /= 10LL;
  104. }
  105. return n;
  106. }
  107. template <typename parent>
  108. class LIN_SCALE : public parent
  109. {
  110. public:
  111. LIN_SCALE( wxString name, wxString unit, int flags ) : parent( name, flags ), m_unit( unit ){};
  112. void formatLabels() override
  113. {
  114. double maxVis = parent::AbsVisibleMaxValue();
  115. wxString suffix;
  116. int power, digits = 0;
  117. int constexpr DIGITS = 3;
  118. getSISuffix( maxVis, m_unit, power, suffix );
  119. double sf = pow( 10.0, power );
  120. for( auto& l : parent::TickLabels() )
  121. {
  122. int k = countDecimalDigits( l.pos / sf, DIGITS );
  123. digits = std::max( digits, k );
  124. }
  125. for( auto& l : parent::TickLabels() )
  126. {
  127. l.label = formatFloat( l.pos / sf, digits ) + suffix;
  128. l.visible = true;
  129. }
  130. }
  131. private:
  132. const wxString m_unit;
  133. };
  134. template <typename parent>
  135. class LOG_SCALE : public parent
  136. {
  137. public:
  138. LOG_SCALE( wxString name, wxString unit, int flags ) : parent( name, flags ), m_unit( unit ){};
  139. void formatLabels() override
  140. {
  141. wxString suffix;
  142. int power;
  143. for( auto& l : parent::TickLabels() )
  144. {
  145. getSISuffix( l.pos, m_unit, power, suffix );
  146. double sf = pow( 10.0, power );
  147. int k = countDecimalDigits( l.pos / sf, 3 );
  148. l.label = formatFloat( l.pos / sf, k ) + suffix;
  149. l.visible = true;
  150. }
  151. }
  152. private:
  153. const wxString m_unit;
  154. };
  155. void CURSOR::Plot( wxDC& aDC, mpWindow& aWindow )
  156. {
  157. if( !m_window )
  158. m_window = &aWindow;
  159. if( !m_visible )
  160. return;
  161. const auto& dataX = m_trace->GetDataX();
  162. const auto& dataY = m_trace->GetDataY();
  163. if( dataX.size() <= 1 )
  164. return;
  165. if( m_updateRequired )
  166. {
  167. m_coords.x = m_trace->s2x( aWindow.p2x( m_dim.x ) );
  168. // Find the closest point coordinates
  169. auto maxXIt = std::upper_bound( dataX.begin(), dataX.end(), m_coords.x );
  170. int maxIdx = maxXIt - dataX.begin();
  171. int minIdx = maxIdx - 1;
  172. // Out of bounds checks
  173. if( minIdx < 0 )
  174. {
  175. minIdx = 0;
  176. maxIdx = 1;
  177. m_coords.x = dataX[0];
  178. }
  179. else if( maxIdx >= (int) dataX.size() )
  180. {
  181. maxIdx = dataX.size() - 1;
  182. minIdx = maxIdx - 1;
  183. m_coords.x = dataX[maxIdx];
  184. }
  185. const double leftX = dataX[minIdx];
  186. const double rightX = dataX[maxIdx];
  187. const double leftY = dataY[minIdx];
  188. const double rightY = dataY[maxIdx];
  189. // Linear interpolation
  190. m_coords.y = leftY + ( rightY - leftY ) / ( rightX - leftX ) * ( m_coords.x - leftX );
  191. m_updateRequired = false;
  192. // Notify the parent window about the changes
  193. wxQueueEvent( aWindow.GetParent(), new wxCommandEvent( EVT_SIM_CURSOR_UPDATE ) );
  194. }
  195. else
  196. {
  197. m_updateRef = true;
  198. }
  199. if( m_updateRef )
  200. {
  201. UpdateReference();
  202. m_updateRef = false;
  203. }
  204. // Line length in horizontal and vertical dimensions
  205. const wxPoint cursorPos( aWindow.x2p( m_trace->x2s( m_coords.x ) ),
  206. aWindow.y2p( m_trace->y2s( m_coords.y ) ) );
  207. wxCoord leftPx = m_drawOutsideMargins ? 0 : aWindow.GetMarginLeft();
  208. wxCoord rightPx = m_drawOutsideMargins ? aWindow.GetScrX() :
  209. aWindow.GetScrX() - aWindow.GetMarginRight();
  210. wxCoord topPx = m_drawOutsideMargins ? 0 : aWindow.GetMarginTop();
  211. wxCoord bottomPx = m_drawOutsideMargins ? aWindow.GetScrY() :
  212. aWindow.GetScrY() - aWindow.GetMarginBottom();
  213. wxPen pen = GetPen();
  214. pen.SetStyle( m_continuous ? wxPENSTYLE_SOLID : wxPENSTYLE_LONG_DASH );
  215. aDC.SetPen( pen );
  216. if( topPx < cursorPos.y && cursorPos.y < bottomPx )
  217. aDC.DrawLine( leftPx, cursorPos.y, rightPx, cursorPos.y );
  218. if( leftPx < cursorPos.x && cursorPos.x < rightPx )
  219. aDC.DrawLine( cursorPos.x, topPx, cursorPos.x, bottomPx );
  220. }
  221. bool CURSOR::Inside( wxPoint& aPoint )
  222. {
  223. if( !m_window )
  224. return false;
  225. return ( std::abs( (double) aPoint.x -
  226. m_window->x2p( m_trace->x2s( m_coords.x ) ) ) <= DRAG_MARGIN )
  227. || ( std::abs( (double) aPoint.y -
  228. m_window->y2p( m_trace->y2s( m_coords.y ) ) ) <= DRAG_MARGIN );
  229. }
  230. void CURSOR::UpdateReference()
  231. {
  232. if( !m_window )
  233. return;
  234. m_reference.x = m_window->x2p( m_trace->x2s( m_coords.x ) );
  235. m_reference.y = m_window->y2p( m_trace->y2s( m_coords.y ) );
  236. }
  237. SIM_PLOT_PANEL::SIM_PLOT_PANEL( const wxString& aCommand, wxWindow* parent,
  238. SIM_PLOT_FRAME* aMainFrame, wxWindowID id, const wxPoint& pos,
  239. const wxSize& size, long style, const wxString& name )
  240. : SIM_PANEL_BASE( aCommand, parent, id, pos, size, style, name ),
  241. m_axis_x( nullptr ),
  242. m_axis_y1( nullptr ),
  243. m_axis_y2( nullptr ),
  244. m_dotted_cp( false ),
  245. m_masterFrame( aMainFrame )
  246. {
  247. m_sizer = new wxBoxSizer( wxVERTICAL );
  248. m_plotWin = new mpWindow( this, wxID_ANY, pos, size, style );
  249. m_plotWin->LimitView( true );
  250. m_plotWin->SetMargins( 50, 80, 50, 80 );
  251. UpdatePlotColors();
  252. updateAxes();
  253. // a mpInfoLegend displays le name of traces on the left top panel corner:
  254. m_legend = new mpInfoLegend( wxRect( 0, 40, 200, 40 ), wxTRANSPARENT_BRUSH );
  255. m_legend->SetVisible( false );
  256. m_plotWin->AddLayer( m_legend );
  257. m_plotWin->EnableDoubleBuffer( true );
  258. m_plotWin->UpdateAll();
  259. m_sizer->Add( m_plotWin, 1, wxALL | wxEXPAND, 1 );
  260. SetSizer( m_sizer );
  261. }
  262. SIM_PLOT_PANEL::~SIM_PLOT_PANEL()
  263. {
  264. // ~mpWindow destroys all the added layers, so there is no need to destroy m_traces contents
  265. }
  266. void SIM_PLOT_PANEL::updateAxes()
  267. {
  268. if( m_axis_x )
  269. return;
  270. switch( GetType() )
  271. {
  272. case ST_AC:
  273. m_axis_x = new LOG_SCALE<mpScaleXLog>( _( "Frequency" ), wxT( "Hz" ), mpALIGN_BOTTOM );
  274. m_axis_y1 = new LIN_SCALE<mpScaleY>( _( "Gain" ), wxT( "dBV" ), mpALIGN_LEFT );
  275. m_axis_y2 = new LIN_SCALE<mpScaleY>( _( "Phase" ), wxT( "\u00B0" ),
  276. mpALIGN_RIGHT ); // degree sign
  277. m_axis_y2->SetMasterScale( m_axis_y1 );
  278. break;
  279. case ST_DC:
  280. prepareDCAxes();
  281. break;
  282. case ST_NOISE:
  283. m_axis_x = new LOG_SCALE<mpScaleXLog>( _( "Frequency" ), wxT( "Hz" ), mpALIGN_BOTTOM );
  284. m_axis_y1 = new mpScaleY( _( "noise [(V or A)^2/Hz]" ), mpALIGN_LEFT );
  285. break;
  286. case ST_TRANSIENT:
  287. m_axis_x = new LIN_SCALE<mpScaleX>( _( "Time" ), wxT( "s" ), mpALIGN_BOTTOM );
  288. m_axis_y1 = new LIN_SCALE<mpScaleY>( _( "Voltage" ), wxT( "V" ), mpALIGN_LEFT );
  289. m_axis_y2 = new LIN_SCALE<mpScaleY>( _( "Current" ), wxT( "A" ), mpALIGN_RIGHT );
  290. m_axis_y2->SetMasterScale( m_axis_y1 );
  291. break;
  292. default:
  293. // suppress warnings
  294. break;
  295. }
  296. if( m_axis_x )
  297. {
  298. m_axis_x->SetTicks( false );
  299. m_axis_x->SetNameAlign ( mpALIGN_BOTTOM );
  300. m_plotWin->AddLayer( m_axis_x );
  301. }
  302. if( m_axis_y1 )
  303. {
  304. m_axis_y1->SetTicks( false );
  305. m_axis_y1->SetNameAlign ( mpALIGN_LEFT );
  306. m_plotWin->AddLayer( m_axis_y1 );
  307. }
  308. if( m_axis_y2 )
  309. {
  310. m_axis_y2->SetTicks( false );
  311. m_axis_y2->SetNameAlign ( mpALIGN_RIGHT );
  312. m_plotWin->AddLayer( m_axis_y2 );
  313. }
  314. }
  315. void SIM_PLOT_PANEL::prepareDCAxes()
  316. {
  317. wxString sim_cmd = getSimCommand().Lower();
  318. wxString rem;
  319. if( sim_cmd.StartsWith( ".dc", &rem ) )
  320. {
  321. wxChar ch;
  322. rem.Trim( false );
  323. try
  324. {
  325. ch = rem.GetChar( 0 );
  326. }
  327. catch( ... )
  328. {;}
  329. switch( ch )
  330. {
  331. // Make sure that we have a reliable default (even if incorrectly labeled)
  332. default:
  333. case 'v':
  334. m_axis_x =
  335. new LIN_SCALE<mpScaleX>( _( "Voltage (swept)" ), wxT( "V" ), mpALIGN_BOTTOM );
  336. break;
  337. case 'i':
  338. m_axis_x =
  339. new LIN_SCALE<mpScaleX>( _( "Current (swept)" ), wxT( "A" ), mpALIGN_BOTTOM );
  340. break;
  341. case 'r':
  342. m_axis_x = new LIN_SCALE<mpScaleX>( _( "Resistance (swept)" ), wxT( "\u03A9" ),
  343. mpALIGN_BOTTOM );
  344. break;
  345. case 't':
  346. m_axis_x = new LIN_SCALE<mpScaleX>( _( "Temperature (swept)" ), wxT( "\u00B0C" ),
  347. mpALIGN_BOTTOM );
  348. break;
  349. }
  350. m_axis_y1 = new LIN_SCALE<mpScaleY>( _( "Voltage (measured)" ), wxT( "V" ), mpALIGN_LEFT );
  351. m_axis_y2 = new LIN_SCALE<mpScaleY>( _( "Current" ), wxT( "A" ), mpALIGN_RIGHT );
  352. }
  353. }
  354. void SIM_PLOT_PANEL::UpdatePlotColors()
  355. {
  356. // Update bg and fg colors:
  357. m_plotWin->SetColourTheme( m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::BACKGROUND ),
  358. m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::FOREGROUND ),
  359. m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::AXIS ) );
  360. // Update color of all traces
  361. for( auto& t : m_traces )
  362. if( t.second->GetCursor() )
  363. t.second->GetCursor()->SetPen(
  364. wxPen( m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::CURSOR ) ) );
  365. m_plotWin->UpdateAll();
  366. }
  367. void SIM_PLOT_PANEL::UpdateTraceStyle( TRACE* trace )
  368. {
  369. int type = trace->GetType();
  370. wxPenStyle penStyle = ( ( ( type & SPT_AC_PHASE ) || ( type & SPT_CURRENT ) ) && m_dotted_cp )
  371. ? wxPENSTYLE_DOT
  372. : wxPENSTYLE_SOLID;
  373. trace->SetPen( wxPen( trace->GetTraceColour(), 2, penStyle ) );
  374. }
  375. bool SIM_PLOT_PANEL::addTrace( const wxString& aTitle, const wxString& aName, int aPoints,
  376. const double* aX, const double* aY, SIM_PLOT_TYPE aType )
  377. {
  378. TRACE* trace = nullptr;
  379. wxString name = aTitle;
  380. updateAxes();
  381. // Find previous entry, if there is one
  382. auto prev = m_traces.find( name );
  383. bool addedNewEntry = ( prev == m_traces.end() );
  384. if( addedNewEntry )
  385. {
  386. if( GetType() == ST_TRANSIENT )
  387. {
  388. bool hasVoltageTraces = false;
  389. for( const auto& tr : m_traces )
  390. {
  391. if( !( tr.second->GetType() & SPT_CURRENT ) )
  392. {
  393. hasVoltageTraces = true;
  394. break;
  395. }
  396. }
  397. if( !hasVoltageTraces )
  398. m_axis_y2->SetMasterScale( nullptr );
  399. else
  400. m_axis_y2->SetMasterScale( m_axis_y1 );
  401. }
  402. // New entry
  403. trace = new TRACE( aName, aType );
  404. trace->SetTraceColour( m_colors.GenerateColor( m_traces ) );
  405. UpdateTraceStyle( trace );
  406. m_traces[name] = trace;
  407. // It is a trick to keep legend & coords always on the top
  408. for( mpLayer* l : m_topLevel )
  409. m_plotWin->DelLayer( l );
  410. m_plotWin->AddLayer( (mpLayer*) trace );
  411. for( mpLayer* l : m_topLevel )
  412. m_plotWin->AddLayer( l );
  413. }
  414. else
  415. {
  416. trace = prev->second;
  417. }
  418. std::vector<double> tmp( aY, aY + aPoints );
  419. if( GetType() == ST_AC )
  420. {
  421. if( aType & SPT_AC_PHASE )
  422. {
  423. for( int i = 0; i < aPoints; i++ )
  424. tmp[i] = tmp[i] * 180.0 / M_PI; // convert to degrees
  425. }
  426. else
  427. {
  428. for( int i = 0; i < aPoints; i++ )
  429. {
  430. // log( 0 ) is not valid.
  431. if( tmp[i] != 0 )
  432. tmp[i] = 20 * log( tmp[i] ) / log( 10.0 ); // convert to dB
  433. }
  434. }
  435. }
  436. trace->SetData( std::vector<double>( aX, aX + aPoints ), tmp );
  437. if( ( aType & SPT_AC_PHASE ) || ( aType & SPT_CURRENT ) )
  438. trace->SetScale( m_axis_x, m_axis_y2 );
  439. else
  440. trace->SetScale( m_axis_x, m_axis_y1 );
  441. m_plotWin->UpdateAll();
  442. return addedNewEntry;
  443. }
  444. bool SIM_PLOT_PANEL::deleteTrace( const wxString& aName )
  445. {
  446. auto it = m_traces.find( aName );
  447. if( it != m_traces.end() )
  448. {
  449. TRACE* trace = it->second;
  450. m_traces.erase( it );
  451. if( CURSOR* cursor = trace->GetCursor() )
  452. m_plotWin->DelLayer( cursor, true );
  453. m_plotWin->DelLayer( trace, true, true );
  454. ResetScales();
  455. return true;
  456. }
  457. return false;
  458. }
  459. void SIM_PLOT_PANEL::deleteAllTraces()
  460. {
  461. for( auto& t : m_traces )
  462. {
  463. deleteTrace( t.first );
  464. }
  465. m_traces.clear();
  466. }
  467. bool SIM_PLOT_PANEL::HasCursorEnabled( const wxString& aName ) const
  468. {
  469. TRACE* t = GetTrace( aName );
  470. return t ? t->HasCursor() : false;
  471. }
  472. void SIM_PLOT_PANEL::EnableCursor( const wxString& aName, bool aEnable )
  473. {
  474. TRACE* t = GetTrace( aName );
  475. if( t == nullptr || t->HasCursor() == aEnable )
  476. return;
  477. if( aEnable )
  478. {
  479. CURSOR* c = new CURSOR( t, this );
  480. int plotCenter = GetPlotWin()->GetMarginLeft()
  481. + ( GetPlotWin()->GetXScreen() - GetPlotWin()->GetMarginLeft()
  482. - GetPlotWin()->GetMarginRight() )
  483. / 2;
  484. c->SetX( plotCenter );
  485. c->SetPen( wxPen( m_colors.GetPlotColor( SIM_PLOT_COLORS::COLOR_SET::CURSOR ) ) );
  486. t->SetCursor( c );
  487. m_plotWin->AddLayer( c );
  488. }
  489. else
  490. {
  491. CURSOR* c = t->GetCursor();
  492. t->SetCursor( nullptr );
  493. m_plotWin->DelLayer( c, true );
  494. }
  495. // Notify the parent window about the changes
  496. wxQueueEvent( GetParent(), new wxCommandEvent( EVT_SIM_CURSOR_UPDATE ) );
  497. }
  498. void SIM_PLOT_PANEL::ResetScales()
  499. {
  500. if( m_axis_x )
  501. m_axis_x->ResetDataRange();
  502. if( m_axis_y1 )
  503. m_axis_y1->ResetDataRange();
  504. if( m_axis_y2 )
  505. m_axis_y2->ResetDataRange();
  506. for( auto& t : m_traces )
  507. t.second->UpdateScales();
  508. }
  509. wxDEFINE_EVENT( EVT_SIM_CURSOR_UPDATE, wxCommandEvent );