-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBodeZ.java
More file actions
1463 lines (1296 loc) · 48.7 KB
/
BodeZ.java
File metadata and controls
1463 lines (1296 loc) · 48.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//==========================================================\\
// BodeZ class, extends JApplet
// Originated 11/8/2014 by M. Williamsen
// Plots complex frequency response from Z-domain
// transfer function coefficients in entry fields.
// Will multiply lists of polynomials and collect terms.
// May be run in a browser, appletviewer, or standalone.
// Implements Java Swing user interface.
// Version 1.0.1, 12/23/2014
// Based on BodeNyquist Applet version 2.0
// http://www.williamsonic.com
//==========================================================\\
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
// units of measure for horizontal axis
enum FreqUnits {radSamp, cycSamp, radSec, cycSec};
// main class for this applet
//==========================================================\\
public class BodeZ extends JApplet
{
// information strings
private static final String versionStr =
"Z-Domain Bode/Nyquist Plot v. 1.0.1; M. Williamsen 12/23/2014";
private static final String infoStr[][] =
{
{"numerator", "String", "Polynomial coefficients or list of polynomials"},
{"denominator", "String", "Polynomial coefficients or list of polynomials"},
{"startFreq", "Real number", "Frequency at left edge of plot"},
{"decades", "Integer", "Number of decades to plot"},
{"units", "String", "Units of frequency"},
{"sampRate", "Real number", "Samples per second"},
};
// GUI components
PlotCanvas theCanvas;
PolarCanvas thePolar;
ImpulseCanvas theImpulse;
PlotPanel thePanel;
PlotData theData;
JTabbedPane thePane;
// instance variables
String numStr; // numerator coefficients
String denStr; // denominator coefficients
String startStr; // plot start frequency
String sampStr; // sample rate
String decadStr; // number of decades to plot
String unitsStr; // units of frequency
// Set look & feel to match local OS, before drawing anything.
private void setLAF()
{
String theLAF = UIManager.getSystemLookAndFeelClassName();
// System.out.println("Local look & feel: " + theLAF);
try{UIManager.setLookAndFeel(theLAF);}
catch(UnsupportedLookAndFeelException e)
{System.out.println("UnsupportedLookAndFeelException.");}
catch(Exception e)
{System.out.println("Failed to set Look And Feel.");}
}
// default constructor, needed for browsers and appletviewer
public BodeZ()
{
// Set the local look & feel before drawing anything.
setLAF();
}
// construct BodeZ instance for standalone execution
public BodeZ(String args[])
{
// preset to default values (notch filter 0.142797 rad/samp)
numStr = "0.00439456;(1,2,1)";
denStr = "1,-1.734834,0.752412";
startStr = "100";
decadStr = "2";
unitsStr = "cyc/sec";
sampStr = "44100";
// accept command line arguments if present
switch (args.length)
{
case 6:
sampStr = args[5];
case 5:
unitsStr = args[4];
case 4:
decadStr = args[3];
case 3:
startStr = args[2];
case 2:
denStr = args[1];
case 1:
numStr = args[0];
break;
default:
System.out.println("usage: java -cp BodeZ.jar BodeZ numCoeff [denCoeff [startFreq [2|3|4 [units [sampRate]]]]]");
break;
}
// Set look & feel to match local OS.
setLAF();
}
// main entry point for standalone execution
public static void main(String args[])
{
// construct an instance of this applet
final BodeZ thePlot = new BodeZ(args);
thePlot.init();
// construct window frame to run applet
JFrame theFrame = new JFrame("Z-Domain Bode/Nyquist Plot");
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.getContentPane().add(thePlot);
theFrame.setSize(755, 630);
theFrame.setVisible(true);
thePlot.start();
}
// initialization code
public void init()
{
// obtain applet parameters from HTML
if (null == numStr) {numStr = getParameter("numerator");}
if (null == denStr) {denStr = getParameter("denominator");}
if (null == startStr) {startStr = getParameter("startFreq");}
if (null == decadStr) {decadStr = getParameter("decades");}
if (null == unitsStr) {unitsStr = getParameter("units");}
if (null == sampStr) {sampStr = getParameter("sampRate");}
// Show version info on console
System.out.println(versionStr);
// add GUI component for plot area
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
theCanvas = new PlotCanvas(this);
thePolar = new PolarCanvas(this);
theImpulse = new ImpulseCanvas(this);
// set up tabbed pane
thePane = new JTabbedPane();
thePane.setOpaque(false);
thePane.addTab("BodeZ Plot", theCanvas);
thePane.addTab("Nyquist", thePolar);
thePane.addTab("Impulse", theImpulse);
thePanel = new PlotPanel(this);
getContentPane().add(thePane);
getContentPane().add(thePanel);
}
// start the applet
public void start()
{
// draw plot for the first time
thePanel.doPlot();
}
// implement some applet methods
public String getAppletInfo(){return versionStr;}
public String[][] getParameterInfo(){return infoStr;}
}
//==========================================================\\
// component subclass to hold Bode plot area
class PlotCanvas extends JPanel
{
// instance data members
private final BodeZ theApp;
// constructor with one arg, a reference to the parent
PlotCanvas(BodeZ anApp)
{
// keep reference to parent
theApp = anApp;
// required to allow look and feel to show through
setOpaque(false);
setPreferredSize(new Dimension(725, 325));
}
// draw the plot area as needed
public void paint(Graphics g)
{
if (null != theApp.theData)
{theApp.theData.paintPlot(g);}
}
}
//==========================================================\\
// component subclass to hold Nyquist (polar) plot
class PolarCanvas extends JPanel
{
// instance data members
private final BodeZ theApp;
// constructor with one arg, a reference to the parent
PolarCanvas(BodeZ anApp)
{
// keep reference to parent
theApp = anApp;
// required to allow look and feel to show through
setOpaque(false);
setPreferredSize(new Dimension(725, 325));
}
// draw the plot area as needed
public void paint(Graphics g)
{
if (null != theApp.theData)
{theApp.theData.paintPolar(g);}
}
}
//==========================================================\\
// component subclass to hold impulse and step function plots
class ImpulseCanvas extends JPanel
{
// instance data members
private final BodeZ theApp;
// constructor with one arg, a reference to the parent
ImpulseCanvas(BodeZ anApp)
{
// keep reference to parent
theApp = anApp;
// required to allow look and feel to show through
setOpaque(false);
setPreferredSize(new Dimension(725, 325));
}
// draw the plot area as needed
public void paint(Graphics g)
{
if (null != theApp.theData)
{theApp.theData.paintImpulse(g);}
}
}
//==========================================================\\
// component to hold GUI controls
class PlotPanel extends JPanel
implements ActionListener, ChangeListener
{
// reference to the applet
private final BodeZ theApp;
// Swing instance variables, to support platform-based look & feel.
final JButton theButton;
final JCheckBox theCheck;
final JLabel numLabel;
final JTextField numField;
final JLabel denLabel;
final JTextField denField;
final JLabel startLabel;
final JTextField startField;
final JTextArea resultsArea;
final JComboBox decadesCombo;
final JComboBox unitsCombo;
final JTextField sampField;
final JLabel sampLabel;
// constructor with one argument, a reference to the parent
PlotPanel(BodeZ anApp)
{
theApp = anApp;
setPreferredSize(new Dimension(725, 212));
setLayout(new GridLayout(1,2,8,8));
// required to allow look and feel to show through
setOpaque(false);
// button control to plot new data
theButton = new JButton("Plot Response");
theButton.setOpaque(false);
theButton.addActionListener(this); // register for events
// check box control to inhibit phase plot
theCheck = new JCheckBox("Hide Phase", false);
theCheck.setOpaque(false);
theCheck.addActionListener(this); // register for events
// choice control for decades
String decadesList[] = {"2 Decades", "3 Decades", "4 Decades"};
decadesCombo = new JComboBox(decadesList);
decadesCombo.setOpaque(false);
int numDecades = 2;
try{numDecades = Integer.parseInt(theApp.decadStr);}
catch(NumberFormatException e)
{
System.out.println("Couldn't parse number of decades: "
+ theApp.decadStr);
numDecades = 2;
}
// limit range for number of decades to (2...4)
numDecades = Math.min(numDecades, 4);
numDecades = Math.max(numDecades, 2);
decadesCombo.setSelectedIndex(numDecades-2);
decadesCombo.addActionListener(this); // register for events
// choice control for units
String unitsList[] = {"rad/samp", "cyc/samp", "rad/sec", "cyc/sec"};
unitsCombo = new JComboBox(unitsList);
unitsCombo.setOpaque(false);
if (null != theApp.unitsStr) {unitsCombo.setSelectedItem(theApp.unitsStr);}
unitsCombo.addActionListener(this); // register for events
// set up button controls
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(false);
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
buttonPanel.add(theButton);
buttonPanel.add(theCheck);
// set up drop down controls
JPanel dropPanel = new JPanel();
dropPanel.setOpaque(false);
dropPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
dropPanel.add(decadesCombo);
dropPanel.add(unitsCombo);
// text entry field for numerator coefficients
numField = new JTextField(theApp.numStr, 18);
numLabel = new JLabel("Numerator", Label.LEFT);
numLabel.setOpaque(false);
JPanel numPanel = new JPanel();
numPanel.setOpaque(false);
numPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
numPanel.add(numField);
numPanel.add(numLabel);
// text entry field for denominator coefficients
denField = new JTextField(theApp.denStr, 18);
denLabel = new JLabel("Denominator", Label.LEFT);
denLabel.setOpaque(false);
JPanel denPanel = new JPanel();
denPanel.setOpaque(false);
denPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
denPanel.add(denField);
denPanel.add(denLabel);
// text entry field for start frequency of plot
startField = new JTextField(theApp.startStr, 18);
startLabel = new JLabel("Start Freq.", Label.LEFT);
startLabel.setOpaque(false);
// panel to hold start frequency
JPanel startPanel = new JPanel();
startPanel.setOpaque(false);
startPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
startPanel.add(startField);
startPanel.add(startLabel);
// test entry field for samples per second
sampField = new JTextField(theApp.sampStr, 18);
sampLabel = new JLabel("Samples/Sec.", Label.LEFT);
sampLabel.setOpaque(false);
// panel to hold samples per second entry field
JPanel sampPanel = new JPanel();
sampPanel.setOpaque(false);
sampPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
sampPanel.add(sampField);
sampPanel.add(sampLabel);
// set up overall control panel
JPanel controlPanel = new JPanel();
controlPanel.setOpaque(false);
controlPanel.setLayout(new GridLayout(6,1));
controlPanel.setBorder(BorderFactory.createEtchedBorder());
add(controlPanel);
controlPanel.add(buttonPanel);
controlPanel.add(dropPanel);
controlPanel.add(numPanel);
controlPanel.add(denPanel);
controlPanel.add(startPanel);
controlPanel.add(sampPanel);
theApp.thePane.addChangeListener(this);
// static text field for transfer function results
resultsArea = new JTextArea("Transfer function results appear here.");
resultsArea.setEditable(false);
resultsArea.setBorder(BorderFactory.createEtchedBorder());
add(new JScrollPane(resultsArea));
}
// handle button click events
public void actionPerformed(ActionEvent e)
{
// checkbox doesn't need to recalculate
if (e.getSource() == theCheck)
{
theApp.theCanvas.repaint();
theApp.thePolar.repaint();
theApp.theImpulse.repaint();
}
// other controls must recalculate
else {doPlot();}
}
// handle tab pane changes
public void stateChanged(ChangeEvent e)
{
StringBuffer theBuff;
int theTab = theApp.thePane.getSelectedIndex();
switch (theTab)
{
case 0:
case 1: theBuff = theApp.theData.getResult(); break;
case 2: theBuff = theApp.theData.getImpulse(); break;
default: theBuff = new StringBuffer("Unexpected tab index:" + theTab); break;
}
if (null == theBuff)
{
System.out.println("Error: failed to plot data.");
resultsArea.setText("Error: failed to plot data.");
return;
}
resultsArea.setText(theBuff.toString());
}
void doPlot()
{
// build polynomial objects for numerator and denominator
double[] numCoeff;
double[] denCoeff;
double startFreq;
double sampRate;
// get user input from numerator text field
theApp.numStr = numField.getText();
try{numCoeff = Polynomial.convertPolyList(theApp.numStr);}
catch(NumberFormatException e)
{
resultsArea.setText("Couldn't parse numerator: " + theApp.numStr);
System.out.println("Couldn't parse numerator: " + theApp.numStr);
return;
}
// get user input from denominator text field
theApp.denStr = denField.getText();
try{denCoeff = Polynomial.convertPolyList(theApp.denStr);}
catch(NumberFormatException e)
{
resultsArea.setText("Couldn't parse denominator: "+theApp.denStr);
System.out.println("Couldn't parse denominator: "+theApp.denStr);
return;
}
if ((1 == denCoeff.length) && (0 == denCoeff[0]))
{
resultsArea.setText("Denominator can't be zero: "+theApp.denStr);
System.out.println("Denominator can't be zero: "+theApp.denStr);
return;
}
// get user input from start freq text field
theApp.startStr = startField.getText();
try{startFreq = Double.parseDouble(theApp.startStr);}
catch(NumberFormatException e)
{
resultsArea.setText("Couldn't parse start freq: "+theApp.startStr);
System.out.println("Couldn't parse start freq: "+theApp.startStr);
return;
}
if (0.0 == startFreq)
{
resultsArea.setText("Start freq can't be zero: "+theApp.startStr);
System.out.println("Start freq can't be zero: "+theApp.startStr);
return;
}
// get user input from samples per second text field
theApp.sampStr = sampField.getText();
try{sampRate = Double.parseDouble(theApp.sampStr);}
catch(NumberFormatException e)
{
resultsArea.setText("Couldn't parse sample rate: "+theApp.sampStr);
System.out.println("Couldn't parse sample rate: "+theApp.sampStr);
return;
}
if (0.0 == sampRate)
{
resultsArea.setText("Sample rate can't be zero: "+theApp.sampStr);
System.out.println("Sample rate can't be zero: "+theApp.sampStr);
return;
}
// check units of frequency
FreqUnits unitsRad = FreqUnits.radSamp;
int theItem = theApp.thePanel.unitsCombo.getSelectedIndex();
switch (theItem)
{
case 0: unitsRad = FreqUnits.radSamp; break;
case 1: unitsRad = FreqUnits.cycSamp; break;
case 2: unitsRad = FreqUnits.radSec; break;
case 3: unitsRad = FreqUnits.cycSec; break;
default: unitsRad = FreqUnits.radSamp; break;
}
// if no problems, show results on console
System.out.print(">>Numerator: ");
Polynomial.showArray(numCoeff);
System.out.print("Denominator: ");
Polynomial.showArray(denCoeff);
System.out.print("Start freq.: " + startFreq);
switch (theItem)
{
case 0: System.out.println(" rad/samp"); break;
case 1: System.out.println(" cyc/samp"); break;
case 2: System.out.println(" rad/sec"); break;
case 3: System.out.println(" cyc/sec"); break;
default: System.out.println(" (unknown units)"); break;
}
System.out.println("Sample rate: " + sampRate + ' ' +"samp/sec");
// calculate transfer function results
theApp.theData = new PlotData(theApp, startFreq, unitsRad, numCoeff, denCoeff, sampRate);
stateChanged(null);
// ask plots to redraw themselves with new data
theApp.theCanvas.repaint();
theApp.thePolar.repaint();
theApp.theImpulse.repaint();
}
}
//==========================================================\\
// container for complex frequency response
class PlotData
{
private final BodeZ theApp;
final double startFreq;
final FreqUnits unitsRad;
final int theRange;
final int numDecades;
final double sampRate;
Complex[] theResult;
double[] theFreqs;
double maxReal;
double minReal;
double maxImag;
double minImag;
double[] impulseOutput;
double[] stepFcnOutput;
double maxImpulse;
double minImpulse;
double maxStepFcn;
double minStepFcn;
// constructor with args
PlotData(BodeZ anApp, double aFreq, FreqUnits theUnits, double[] numCoeff, double[] denCoeff, double aRate)
{
// copy input parameters
theApp = anApp;
startFreq = aFreq;
unitsRad = theUnits;
sampRate = aRate;
// check number of decades from combo control
int theItem = theApp.thePanel.decadesCombo.getSelectedIndex();
switch (theItem)
{
case 0: theRange = 300; numDecades = 2; break;
case 1: theRange = 200; numDecades = 3; break;
case 2: theRange = 150; numDecades = 4; break;
default: theRange = 300; numDecades = 2; break;
}
// initialize list of frequencies to plot
theFreqs = new double[601];
theFreqs[0] = startFreq;
switch (unitsRad)
{
case cycSamp: theFreqs[0] *= (2. * Math.PI); break;
case radSec: theFreqs[0] /= sampRate; break;
case cycSec: theFreqs[0] /= (sampRate / 2. / Math.PI); break;
}
int index;
for (index = 1; index < theFreqs.length; index++)
{
// find next frequency in radians/sample as a ratio
theFreqs[index] = Math.pow(10.0, 1.0/theRange)*theFreqs[index-1];
}
// calculate complex response at each plot frequency
computePlot(numCoeff, denCoeff);
computeImpulse(numCoeff, denCoeff);
}
StringBuffer getResult()
{
// copy transfer function results to text buffer
StringBuffer theBuff;
theBuff = new StringBuffer("Freq. ");
switch (unitsRad)
{
case radSamp: theBuff.append("(rad/samp)"); break;
case cycSamp: theBuff.append("(cyc/samp)"); break;
case radSec: theBuff.append("(rad/sec)"); break;
case cycSec: theBuff.append("(cyc/sec)"); break;
}
theBuff.append("\tComplex Resp.\n");
// always use scientific notation with 6 sig. figs.
final DecimalFormat theFormat = new DecimalFormat("#.######E0");
int index;
for (index = 0; index < theResult.length; index++)
{
// first column in frequency in chosen units
double aFreq = theFreqs[index];
switch (unitsRad)
{
case cycSamp: aFreq /= (2. * Math.PI); break;
case radSec: aFreq *= sampRate; break;
case cycSec: aFreq *= (sampRate / 2. / Math.PI); break;
}
theBuff.append(theFormat.format(aFreq));
// second column is complex response
theBuff.append('\t');
theBuff.append(theResult[index].toString());
theBuff.append('\n');
}
return theBuff;
}
StringBuffer getImpulse()
{
// scientific notation, 6 sig. figs.
final DecimalFormat theFormat = new DecimalFormat("#.######E0");
StringBuffer theBuff;
theBuff = new StringBuffer("Time (sec)\tImpulse Response\tStep Function\n");
int index;
for (index = 0; index < impulseOutput.length; index++)
{
theBuff.append(theFormat.format(index / sampRate));
theBuff.append('\t');
theBuff.append(theFormat.format(impulseOutput[index]));
theBuff.append('\t');
theBuff.append(theFormat.format(stepFcnOutput[index]));
theBuff.append('\n');
}
return theBuff;
}
// draw Bode plot in first tabbed pane
void paintPlot(Graphics g)
{
final boolean hidePhase = theApp.thePanel.theCheck.isSelected();
// move origin to make room for text labels
g.translate(50, 3);
// draw white rectangle for plot area
g.setColor(Color.white);
g.fillRect(0, 0, 599, 299);
// draw log frequency scale
final DecimalFormat theFormat = new DecimalFormat("#.####");
double aFreq;
int index;
int outer;
int inner = 0;
for (outer = 1; outer < 10; outer++)
{
for (inner = 0; inner < numDecades; inner++)
{
// draw vertical grid lines
int gridx = (int) (Math.log(outer) * theRange / Math.log(10.0) + 0.5 + inner * theRange);
aFreq = outer * startFreq * Math.pow(10.,inner);
g.setColor(Color.lightGray);
g.drawLine(gridx, 0, gridx, 299);
g.setColor(Color.black);
// draw text labels as needed
switch (numDecades)
{
// handle 4 decades plot
case 4:
switch (outer)
{
case 1:
case 3:
g.drawLine(gridx, 299, gridx, 304);
g.drawString(theFormat.format(aFreq), gridx, 317);
break;
default:
break;
}
break;
// handle 3 decades plot
case 3:
switch (outer)
{
case 1:
case 2:
case 5:
g.drawLine(gridx, 299, gridx, 304);
g.drawString(theFormat.format(aFreq), gridx, 317);
break;
default:
break;
}
break;
// handle 2 decades plot
case 2:
switch (outer)
{
case 1:
case 2:
case 4:
case 6:
g.drawLine(gridx, 299, gridx, 304);
g.drawString(theFormat.format(aFreq), gridx, 317);
break;
default:
break;
}
break;
// should never reach here
default:
break;
}
}
}
// special case for last label on the right
g.drawLine(599, 299, 599, 304);
aFreq = startFreq * Math.pow(10.,inner);
g.drawString(theFormat.format(aFreq), 599, 317);
// draw linear dB scale
for (index = 1; index < 10; index++)
{
// draw horizontal grid lines
g.setColor(Color.lightGray);
int gridy = index * 30;
g.drawLine(0, gridy, 599, gridy);
// draw phase labels if not hidden
if (!hidePhase)
{
g.setColor(Color.black);
g.drawString(String.valueOf(225-(index*45)), 610, gridy+4);
}
}
// draw legend
g.setColor(Color.black);
switch (unitsRad)
{
case radSamp: g.drawString("Freq. (rad/samp)", 267, 290); break;
case cycSamp: g.drawString("Freq. (cyc/samp)", 267, 290); break;
case radSec: g.drawString("Freq. (rad/sec)", 267, 290); break;
case cycSec: g.drawString("Freq. (cyc/sec)", 267, 290); break;
}
g.setColor(Color.blue);
g.drawString("Gain (dB)", 10, 18);
if (!hidePhase)
{
g.setColor(Color.magenta);
g.drawString("Phase (deg)", 520, 18);
}
// draw outline rectangle on top of everything
g.setColor(Color.black);
g.drawRect(0, 0, 599, 299);
// check that data exists before plotting magnitude
if ((null == theResult) || (0 == theResult.length))
{
System.out.println("Error: nothing to plot.");
return;
}
// convert all data points to dB
double[] dBResult = new double[theResult.length];
double maxDB = -100.0;
for (index = 0; index < theResult.length; index++)
{
// convert magnitude to dB, scaled for 5 pixels/dB
double theMag = theResult[index].mod();
theMag = 20.0 * Math.log(theMag) / Math.log(10.0);
dBResult[index] = theMag;
// save maximum dB value
maxDB = Math.max(maxDB, theMag);
}
// limit vertical display to the range (-90...90)
maxDB = Math.max(Math.min(maxDB, 90), -90);
// snap to vertical grid, draw text labels
maxDB = 6.0 * Math.round(maxDB/6.0);
for (index = 0; index < 9; index++)
{
g.drawString(String.valueOf((int)(maxDB - (index * 6.))),
-35, index*30 + 34);
}
// reduce clip area while plotting
g.clipRect(1, 1, 599, 299);
// plot phase response first if not hidden
int oldy = 0;
int newy = 0;
int oldx = 0;
if (!hidePhase)
{
g.setColor(Color.magenta);
for (index = 0; index < theResult.length; index++)
{
// check Nyquist limit
if (theFreqs[index] >= Math.PI) {g.setColor(Color.lightGray);}
// plot on canvas scaled to 300 pixel height
newy = (int) (150.5-(theResult[index].arg()*120./Math.PI));
if (0 == index){oldy = newy;}
else {g.drawLine(oldx, oldy, (int)(index), newy);}
oldy = newy;
oldx = index;
}
}
// plot magnitude response last
oldy = 0;
newy = 0;
oldx = 0;
g.setColor(Color.blue);
for (index = 0; index < theResult.length; index++)
{
// check Nyquist limit
if (theFreqs[index] >= Math.PI) {g.setColor(Color.gray);}
// plot on canvas scaled to 300 pixel height
newy = (int) (5.0 * (maxDB - dBResult[index] + 6.) + 0.5);
if (0 == index){oldy = newy;}
else {g.drawLine(oldx, oldy, (int)(index), newy);}
oldy = newy;
oldx = index;
}
}
// draw Nyquist plot in second tabbed pane
void paintPolar(Graphics g)
{
final boolean hidePhase = theApp.thePanel.theCheck.isSelected();
// move origin to make room for text labels
g.translate(40, 3);
// scale plot to fit width and height
double xfactor = Math.max(maxReal, -minReal);
double yfactor = Math.max(maxImag, -minImag);
double preFactor = Math.max(0.5 * xfactor, yfactor);
preFactor = Math.max(1.e-6, preFactor);
// find a 'nice' number to set scale factor
double mult = Math.log(preFactor) / Math.log(10.);
mult = Math.pow(10., Math.round(mult - 1.5));
preFactor = mult * Math.round(preFactor / mult);
final int scale = 13;
double factor = 10. * scale / preFactor;
// draw white rectangle for plot area
g.setColor(Color.white);
g.fillRect(0, 0, 599, 299);
// draw horiz and vert axes
g.setColor(Color.lightGray);
g.drawLine(0, 150, 604, 150);
g.drawLine(300, 0, 300, 304);
// draw ticks and grid lines for vertical axis
final DecimalFormat theFormat = new DecimalFormat("#.######");
int index;
for (index = -10; index <= 10; index++)
{
if (0 == index % 10)
{
g.setColor(Color.gray);
g.drawLine(294,150+index*scale,306,150+index*scale);
g.setColor(Color.black);
g.drawLine(600,150+index*scale,604,150+index*scale);
String theStr = theFormat.format(index*preFactor/10.);
g.drawString(theStr, 610, 154-index*scale);
}
else if (0 == index % 5)
{
g.setColor(Color.gray);
g.drawLine(296,150+index*scale,304,150+index*scale);
g.drawLine(600,150+index*scale,604,150+index*scale);
}
else
{
g.setColor(Color.lightGray);
g.drawLine(298,150+index*scale,302,150+index*scale);
}
}
// draw ticks and grid lines for horizontal axis
for (index = -21; index <= 21; index++)
{
g.setColor(Color.lightGray);
if (0 == index % 10)
{
g.setColor(Color.gray);
g.drawLine(300+index*scale,144,300+index*scale,156);
g.setColor(Color.black);
g.drawLine(300+index*scale,300,300+index*scale,304);
String theStr = theFormat.format(index*preFactor/10.);
g.drawString(theStr, 300+index*scale, 317);
}
else if (0 == index % 5)
{
g.setColor(Color.gray);
g.drawLine(300+index*scale,146,300+index*scale,154);
}
else
{
g.setColor(Color.lightGray);
g.drawLine(300+index*scale,148,300+index*scale,152);
}
}
// draw outline rectangle on top
g.setColor(Color.black);
g.drawRect(0, 0, 599, 299);
g.drawString("Imaginary Plane", 256, 15);
// if data exists, plot magnitude
if ((theResult == null) || (theResult.length == 0))
{
System.out.println("Error: nothing to plot.");
return;
}
// reduce clip area while plotting
g.clipRect(1, 1, 598, 298);
// draw text label for first point
int newx = 0;
int newy = 0;
int oldx = 0;
int oldy = 0;
// plot negative frequencies if enabled
if (!hidePhase)
{
// draw unit circle
int tickx = (int)(300.5 - factor);
int dia = (int)(2. * factor);
g.setColor(Color.lightGray);
g.drawOval(tickx, tickx-150, dia, dia);
g.setColor(Color.magenta);
g.drawLine(tickx, 142, tickx, 158);
// plot response
boolean first = true;
for (index = theResult.length-1; index >= 0; index--)
{
// check Nyquist limit
if (theFreqs[index] < Math.PI) {g.setColor(Color.magenta);}
else {g.setColor(Color.lightGray);}
newx = (int)(300.5 + factor * theResult[index].real());
newy = (int)(150.5 + factor * theResult[index].imag());
if (first)
{ // special handling for first point
oldx = newx;
oldy = newy;
first = false;
}
else {g.drawLine(oldx, oldy, newx, newy);}
oldx = newx;
oldy = newy;
}
}
// plot continuous curve
boolean first = true;
for (index = theResult.length-1; index >= 0; index--)
{
newx = (int)(300.5 + factor * theResult[index].real());