-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathDisplayRoutines.cpp
1954 lines (1593 loc) · 64.3 KB
/
DisplayRoutines.cpp
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
//
// Copyright 2004-2010 Thomas C. McDermott, N5EG
// This file is part of VNAR - the Vector Network Analyzer program.
//
// VNAR is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// VNAR is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with VNAR, if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
//
//
// Routines to manipulate display points in rectangular
// and polar format for the Vector Network Analyzer
//
// 7-4-03 TCMcDermott
// 7-10-03 Add Frequency_Grid Class.
// 7-11-03 Add InstrumentCalDataSet.
// 7-12-03 Add routines to compute S-parameter error terms
// and convert measured S11 to actual S11.
// 7-13-03 Add routines to save CalDat to file, and load
// CalData from file.
// 7-27-03 Add routines to compute rectangular display
// coordinates.
// 8-17-03 Add Detector Class to support separate detector
// calibration.
// 9-16-03 Phase correction algorithm implemented for
// detector calibration. ResolveTranPolar and
// ResolveReflPolar changed to use detector cal values.
// 3-28-04 Add TxLevel adjust to IDAC on the VNA board
// 4-15-04 Revise amplitude interpretation algorithm
// 11-08-04 Revise Detector amplitude calibration algorithm to account for
// two sets of S21 readings - with and without 40 dB pad.
// Also improve to one reading every dB of range for S21.
// REFL detector does not have this done, but TRAN detector does,
// so there are two different calibration algorithms. Also affects
// MagTodB routine. May have to zero out the LowMag routine for
// REFL, but still take data every 1 dB like TRAN.
// 12-29-05 Add Coupler Ripple and Directivity calibration compensation
// independent of fixture calibration. These are both controlled
// by #define statements within this file. If they are changed, all
// detector and fixture calibrations will need to be re-run.
// 03-20-06 Change MagTodBTran to use 3 measurements: Hi, Mid, and Lo
// 02-25-07 Improve glitch detection for long cables (mostly phase).
// 04-10-07 Add 30 msec and 100 msec delays for very narrow filter sweeps.
// Also correct values for sweep delay (e.g. 10 msec was really about 6 msec).
// 07-17-07 Add DirectionalCoupler Class to encapsulate improved error model.
// Disable old Coupler Ripple compensation (via #define).
// 10-04-07 Added deglitching and smoothing routines for phase calibrations.
// 10-14-07 Refactored some code, adding MeasurementSet structure.
#include "stdafx.h"
#using <mscorlib.dll>
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Windows::Forms;
#include <math.h>
#include <complex>
#include "DataDisplay.h"
#include "Constants.h"
#include "DisplayRoutines.h"
#include <float.h>
std::complex<double> Ed_static[1025];
//#define DIRECTCAL // enable compensation of coupler directivity to magnitude
// Convert Mag and Phase to X,Y screen display coordinates in polar display mode
void ToDisplayPolar(double magnitude, double phase, int polarRad, int xoffset, int yoffset, int& X, int& Y)
{
double fx, fy, phase_radians;
int x, y;
phase_radians = phase * DEGR2RAD;
fx = magnitude * cos(phase_radians);
fy = magnitude * sin(phase_radians);
// Scale to the size of the chart (polar radius)
fx = fx * static_cast<double>(polarRad);
fy = fy * static_cast<double>(polarRad);
// Convert to integer
x = (int)fx;
y = (int)fy;
// Center on the chart
x = x + polarRad + xoffset;
y = polarRad + yoffset - y;
X = x; // return X and Y display points
Y = y;
}
// Convert Magnitude to rectangular (X, Y) display coordinates
int ToDisplayRectMag(double magnitude, System::Drawing::Rectangle scopeDisp, float dbScaleFactor, int refLevel)
{
/// magnitude has a normalized value.
/// Zero dB is the top of the screen - magnitude value = 1.000
/// -100 dB is the bottom of the screen (@ 10 db/div) - magnitude value 1e-5
/// Convert magnitude to vertical display accounting for the scale factor in dB/division
int height = scopeDisp.Height;
double dbmag;
if(magnitude < 0.0000000001)
dbmag = -500.0;
else
dbmag = refLevel - 20.0 * log10(magnitude); // 0 to 100 for zero dB to -100 dB.
dbmag /= ((double)dbScaleFactor * 10.0); // 0 to +1 for 10db/div
// scale to the vertical screen display area
int vertical = (int)(dbmag * (double)height); // 0 to scopeDisp.Height for zero dB to height for max dB
if (vertical > height) // crop display - probably a better way to do this
vertical = height;
if (vertical < 0)
vertical = 0;
return(scopeDisp.Y + vertical); // return Y as positive number
}
// Convert Phase to rectangular (X, Y) display coordinates
int ToDisplayRectPhs(double phase, System::Drawing::Rectangle scopeDisp)
{
int height = scopeDisp.Height;
// phase in degrees ranges from -180 to +180
phase += 180.0; ///< offset the phase display so zero is centerline
double range = phase * (double)height / 360.0; ///< top to bottom of display is 360 degrees
return(scopeDisp.Bottom - (int)range);
}
// Convert value with scale to Y-display coordinate
int ToDisplayRectScaled(double value, System::Drawing::Rectangle scopeDisp, int scaleFactor)
{
return scopeDisp.Bottom - (int)(value * scopeDisp.Height / scaleFactor);
}
// Convert value of groupdelay to Y-display coordinate
int ToDisplayRectGD(double groupdelay, System::Drawing::Rectangle scopeDisp, int scaleFactor)
{
int height = scopeDisp.Height;
// scale factor = 1 implies 100 picoseconds
// convert to nanoseconds
groupdelay *= 1000000000.0;
/// Set full screen display to 10 units of the selected scale.
// 100 picoseconds * 10 = 1 nanosecond full-scale at max resolution.
groupdelay /= scaleFactor;
// scale it to display region
groupdelay *= (double)height;
/// clip display value to screen height
if (groupdelay > height)
groupdelay = height;
return(scopeDisp.Bottom - (int)groupdelay);
}
// Convert Resistance portion of S11 to Y display coordinate
int ToDisplayRectR(float resistance, int scale, System::Drawing::Rectangle scopeDisp)
{
int height = scopeDisp.Height;
int vertical;
vertical = (int)((resistance * (float)height) / ((float)scale * 10.0));
if (vertical > height)
vertical = height;
if (vertical < 0)
vertical = 0;
return(scopeDisp.Bottom - vertical);
};
// Convert Reactance portion of S11 to Y display coordinate
int ToDisplayRectjX(float reactance, int scale, System::Drawing::Rectangle scopeDisp)
{
int height = scopeDisp.Height;
int vertical;
vertical = (int)((reactance * (float)height) / ((float)scale * 10.0));
vertical += height/2; // offset so that middle of the screen is zero reactance
if (vertical > height)
vertical = height;
if (vertical < 0)
vertical = 0;
return(scopeDisp.Bottom - vertical);
};
// Compensate for ModAmp buffer amplifer phase distortions
double BufferAmpPhaseComp(double phaseDegrees, int Frequency)
{
double phase = phaseDegrees;
phase -= HIGHPASSPOLE / (double)Frequency; // compensate for AC coupling caps
return (phase);
}
// Construct a new frequency grid of size numPoints
FrequencyGrid::FrequencyGrid(int numPoints)
{
if (numPoints > 1024)
throw gcnew System::IndexOutOfRangeException("FrequencyGrid constructor: numpoints out of range");
FrequencyIndex = gcnew array<__int64>(numPoints);
startFreq = 200000;
stopFreq = 120000000;
points = numPoints;
Build();
};
// Set start frequency of grid
void FrequencyGrid::SetStartF(__int64 start)
{
startFreq = start;
Build();
}
// Set stop frequency of grid
void FrequencyGrid::SetStopF(__int64 stop)
{
stopFreq = stop;
Build();
}
// Convert gridpoint to it's frequency
__int64 FrequencyGrid::Frequency(int gridpoint)
{
/// if gridpoint is out of range, clip to actual frequency range
if (gridpoint < 0)
return (FrequencyIndex[0]);
if (gridpoint >= points)
return (FrequencyIndex[points-1]);
return(FrequencyIndex[gridpoint]);
}
// Derive DDS divisor value (as 64-bit integer) from Frequency
__int64 FrequencyGrid::DDS(__int64 Frequency)
{
/// Calculate the 48-bit synthesizer accumulator value from Frequency
/// The VNA crystal is ~12.000 MHz. It gets multiplied by 24 going to the DDS accumulator
/// The clock rate is thus approximately 24 * ~12.000 MHz. = ~288.000 MHz.
/// The synthesizer accumulator value needed is: N = Fdesired * 2^48 / Fclk
// Division done in two steps to prevent numeric overflow.
// Calibration routine can determine a better value for Fclk than
// our initial guess.
// For calibration, emit F= 100.000000 Mhz.
// Then new guess for Fclk = 2.88 * Fmeasured
// Ferror is the Frequency calibration error at 100 MHz.
// It has to be scaled up to 288 MHz.
long long int N;
N = Frequency;
//N = Convert::ToInt64(Frequency) * 4294967296; // Freq * 2^32
//N /= (288000000 + (ferror * 288) / 100 ); // Ferror * 2.88
//N *= 65536; // Freq * 2^16
return(N);
}
/// Find nearest gridpoint to Frequency
/// \result is GridPoint Number or -1 if error
int FrequencyGrid::GridPoint(__int64 Frequency)
{
if (((double)Frequency > stopFreq) || ((double)Frequency < startFreq))
return(-1); // Frequency is outside the grid range
double result = ((double)Frequency - startFreq) / delta;
int iresult = (int)(result + 0.5);
return(iresult);
}
int FrequencyGrid::Points() { return points; } /// get number of points in grid
__int64 FrequencyGrid::StartF() { return startFreq; } /// get start frequency of grid
__int64 FrequencyGrid::StopF() { return stopFreq; } /// get stop frequency of grid
int FrequencyGrid::Ferror() { return ferror; } /// get Frequency error of the reference clock
void FrequencyGrid::set_Ferror(int f) { ferror = f; } /// set Frequency error of the reference clock
// Construct the FrequencyGrid once the stop, start, and numpoints are known
void FrequencyGrid::Build(void)
{
delta = ((double)stopFreq-(double)startFreq)/(points-1);
// build the frequency grid
for (int i = 0; i<points; i++)
FrequencyIndex[i] = startFreq + (__int64)((double)i * delta);
}
// InstrumentCalDataSet Constructor - allocate memory for Calibration Data
// Also holds specific fixture calibration data - if any.
InstrumentCalDataSet::InstrumentCalDataSet(String^ StartUpDir, VNADevice^ VNADev)
{
RxDet = gcnew Detector(this); // construct AD8702 objects
RxDet->name = "REFL";
TxDet = gcnew Detector(this);
TxDet->name = "TRAN";
DirCoupler = gcnew DirectionalCoupler(this); /// Holds Directional coupler error model
VNA = VNADev; ///< VNA hardware device
EdReal = gcnew array<Double>(1024); EdImag = gcnew array<Double>(1024);
// Ed = gcnew array<mycomplex>(1024);
// Es = gcnew array<mycomplex>(1024);
EsReal = gcnew array<Double>(1024); EsImag = gcnew array<Double>(1024);
EtReal = gcnew array<Double>(1024); EtImag = gcnew array<Double>(1024);
ThReal = gcnew array<Double>(1024); ThImag = gcnew array<Double>(1024);
S11shortReal = gcnew array<Double>(1024); S11shortImag = gcnew array<Double>(1024);
S11openReal = gcnew array<Double>(1024); S11openImag = gcnew array<Double>(1024);
S11termReal = gcnew array<Double>(1024); S11termImag = gcnew array<Double>(1024);
S21termReal = gcnew array<Double>(1024); S21termImag = gcnew array<Double>(1024);
FixtureCalLogFreqMode = false; // Default to Linear Frequency mode for Fixture Cal
maxCalFreq = VNA->GetMaxFreq();
minCalFreq = VNA->GetMinFreq();
OpenC0 = 0.0;
OpenC1 = 0.0;
OpenC2 = 0.0;
ShortL0 = 0.0;
ShortL1 = 0.0;
ShortL2 = 0.0;
OpenLength = 0.0;
ShortLength = 0.0;
LoadLength = 0.0;
LoadL0 = 0.0;
LoadR0 = 50.0;
// Try to read in the detector.ica file to pre-load the Detector calibration constants
// If the file does not exist, warn user to run detector cal first
FileStream^ fs;
BinaryReader^ br;
String^ filename = String::Concat(StartUpDir, "\\detector_",Convert::ToString(VNA->GetHardware()),".ica" );
try
{
// Create a filestream & binary reader
fs = gcnew FileStream(filename, FileMode::Open, FileAccess::Read);
br = gcnew BinaryReader(fs);
}
catch(System::IO::IOException^ pe)
{
(void) pe;
MessageBox::Show("Detector Calibration File Not Found.\n\r"
"Be sure to run Calibration->Detector Calibration... first", pe->Message,
MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
if (br)
br->Close();
if (fs)
fs->Close();
return;
}
// Define header to match file identifying type and version
String^ recognized = gcnew String("VNA Detector Calibration Data Set Version 2.1.1");
String^ header;
header = br->ReadString(); // get string header on infile
if (String::Compare(recognized, header) != 0)
{
MessageBox::Show(
"detector.ica file is incompatible type or version.\n\rExpecting Detector Version 2.1.1"
"\n\rNote: Detector Calibration must be re-run because the file \n\rformat has been changed in software release 2.1",
"Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
br->Close();
fs->Close();
return;
}
// read in the AD8302 Phase Detector constants, error tables, and DirCoupler tables
try
{
#if 0
RxDet->Qmid = br->ReadInt32();
RxDet->Qmag = br->ReadInt32();
RxDet->Imid = br->ReadInt32();
RxDet->Imag = br->ReadInt32();
RxDet->diffQDelayNs = br->ReadDouble();
RxDet->Iasym = br->ReadInt32();
RxDet->Qasym = br->ReadInt32();
for (int degree = 0; degree<360; degree++)
RxDet->pherror[degree] = br->ReadDouble();
TxDet->Qmid = br->ReadInt32();
TxDet->Qmag = br->ReadInt32();
TxDet->Imid = br->ReadInt32();
TxDet->Imag = br->ReadInt32();
TxDet->diffQDelayNs = br->ReadDouble();
TxDet->Iasym = br->ReadInt32();
TxDet->Qasym = br->ReadInt32();
for (int degree = 0; degree<360; degree++)
TxDet->pherror[degree] = br->ReadDouble();
// Read in the AD8302 Amplitude Detector coefficient tables
for (int FreqIdx=0; FreqIdx<21; FreqIdx++)
{
RxDet->m[FreqIdx] = br->ReadDouble();
RxDet->b[FreqIdx] = br->ReadDouble();
RxDet->r[FreqIdx] = br->ReadDouble();
RxDet->flat[FreqIdx] = br->ReadDouble();
}
for (int FreqIdx=0; FreqIdx<21; FreqIdx++)
{
TxDet->m[FreqIdx] = br->ReadDouble();
TxDet->b[FreqIdx] = br->ReadDouble();
TxDet->r[FreqIdx] = br->ReadDouble();
TxDet->flat[FreqIdx] = br->ReadDouble();
}
RxDet->phaseCalibrated = true; // loaded a valid detector calibration
TxDet->phaseCalibrated = true;
#endif
// Read in the Internal Crystal Frequency Error
// Test the value to make sure it's within reasonable range.
FreqError = br->ReadInt32();
if (Math::Abs(FreqError) > 3000000)
FreqError = 0;
#if 1
// Read in the directivity calibration raw values 10-18-2005
// Moved from RxDet to DirCoupler 05-27-2007
for (int i=0; i<PHASECALGRIDSIZE; i++)
{
DirCoupler->DirIphs[i] = br->ReadInt32();
DirCoupler->DirQphs[i] = br->ReadInt32();
DirCoupler->DirMag[i] = br->ReadInt32();
}
// 09-25-2007 - read the Ripple periodic error model parameters
for (int i=0; i<6; i++)
{
DirCoupler->MagRipCoeff[i]->freq = br->ReadInt32();
DirCoupler->MagRipCoeff[i]->offset = br->ReadDouble();
DirCoupler->MagRipCoeff[i]->mag = br->ReadDouble();
DirCoupler->PhRipCoeff[i]->freq = br->ReadInt32();
DirCoupler->PhRipCoeff[i]->offset = br->ReadDouble();
DirCoupler->PhRipCoeff[i]->mag = br->ReadDouble();
}
// 11-17-2007 - Read in the DC Offset of the Phase and Mag Open-Short calibrations
DirCoupler->PhaseDCOffset = br->ReadDouble();
DirCoupler->MagDCOffset = br->ReadDouble();
// 10-01-2007 - read the Iphase-low-ref-level values for TRAN
TxDet->ImidLo = br->ReadInt32();
TxDet->ImagLo = br->ReadInt32();
#endif
//RxDet->ImidLo = 0; // these are not meaningful for REFL
//RxDet->ImagLo = 0; // and should be initialized to zero by constructor
// Read the directional coupler calibration data - to ease debugging.
for(int i=0; i<PHASECALGRIDSIZE; i++)
{
DirCoupler->phaseError[i] = br->ReadDouble();
DirCoupler->magError[i] = br->ReadDouble();
DirCoupler->openAngle[i] = br->ReadDouble();
DirCoupler->shortAngle[i] = br->ReadDouble();
}
fs->Flush();
fs->Close();
}
catch(System::IO::IOException^ pe)
{
MessageBox::Show("Error trying to load Detector Calibration File.\n\r"
"Delete the file: detector.ica and re-run Detector Calibration", pe->Message,
MessageBoxButtons::OK, MessageBoxIcon::Error);
return;
}
__finally
{
if (br)
br->Close();
if (fs)
fs->Close();
}
DirCoupler->DirCalibrated = true;
DirCoupler->RippleCalibrated = true;
};
/// Compute Frequency of grid point for linear(f) and log(f) fixture cal points
__int64 InstrumentCalDataSet::GetFreqFromFixtureCalGrid(long index, bool LogMode) /// Convert Phase Calibration Grid index to Frequency.
{
// Note: linear mode is the default, and provides backwards-compatibility with older Fixture Cal files
if(LogMode) // Compute fixture calibration log frequency point
{ /// Grid is 1024 points.
double FreqIncrement;
FreqIncrement = Math::Pow(10,Math::Log10((double)maxCalFreq/(double)minCalFreq)/(NUMCALPTS-1));
if (index < PHASECALGRIDSIZE && index >= 0)
return (/* Convert::ToInt32*/(__int64) ((double)minCalFreq * Math::Pow(FreqIncrement, index)));
else
throw gcnew System::ArgumentOutOfRangeException(
"GetFreqFromFixtureCalGrid: index is invalid "); // bad index value
}
else // Compute fixture calibration linear frequency point
{ /// Grid is 1024 points.
// long temp;
// temp = (long) (minCalFreq + (index * (((double)maxCalFreq) - minCalFreq)/(NUMCALPTS-1)));
if (index < PHASECALGRIDSIZE && index >= 0)
return (/* Convert::ToInt32 */(__int64) ((double)minCalFreq + (index * (((double)maxCalFreq) - (double)minCalFreq)/(NUMCALPTS-1)))); // WATCH OVERFLOW!!!!!!!!
else
throw gcnew System::ArgumentOutOfRangeException(
"GetFreqFromFixtureCalGrid: index is invalid "); // bad index value
}
};
#if 1
__int64 InstrumentCalDataSet::GetFreqFromDetMagCalGrid(long index) /// Convert Detector Magnitude Calibration Grid index to Frequency.
{ /// Grid is 21 points.
if (index < 10 && index >= 0)
return(VNA->GetMaxFreq()/100*index + VNA->GetMaxFreq());
if (index < PHASECALGRIDSIZE && index >= 10)
return(VNA->GetMaxFreq()/10*(index+1));
else
throw gcnew System::ArgumentOutOfRangeException(
"GetFreqFromDetMagCalGrid: index is invalid "); // bad index value
};
int InstrumentCalDataSet::GetFreqFromPhaseCalGrid(long index) /// Convert Phase Calibration Grid index to Frequency.
{
if (index < PHASECALGRIDSIZE && index >= 0)
return (Convert::ToInt32(VNA->GetMaxFreq() + (index * (VNA->GetMaxFreq() - VNA->GetMaxFreq())/(NUMCALPTS-1))));
else
throw gcnew System::ArgumentOutOfRangeException(
"GetFreqFromPhaseCalGrid: index is invalid "); // bad index value
};
#endif
// Resolve reflected measured data set to Linear Magnitude and Phase in Degrees
void InstrumentCalDataSet::ResolveReflPolar(MeasurementSet^ dataPoint, __int64 Frequency, double& rmagLin, double& rphsDegr,
bool CouplerComp)
{
double magnitudeDB, phase, magnitudeLin;
double& rphase = phase;
double& rmagnitudeLin = magnitudeLin;
// translate raw readings to phaseDegr, magLin and magDB values from RxDet
magnitudeDB = SHORT2DB(dataPoint->ReflMQ); // RxDet->MagTodBRefl(Frequency, dataPoint->ReflMQ);
magnitudeLin = pow(10.0, (magnitudeDB/20.0));
phase = SHORT2PHASE(dataPoint->ReflPQ); // RxDet->IQtoDegrees(dataPoint->ReflPI, dataPoint->ReflPQ, Frequency, 0, 0, 0);
// Adjust the reflected Magnitude and Phase by the Directivity Cal
#ifdef DIRECTCAL
DirCoupler->CompensateDirectivity(this, rmagnitudeLin, rphase, Frequency);
#endif
#if 1
if(CouplerComp && false)
{
if(RxDet->phaseCalibrated)
{
// Compensate for buffer amp phase delays due to highpass filter formed by
// coupling caps, and time delay of the amplifier.
//phase = BufferAmpPhaseComp(phase, Frequency);
// Compensate for coupler phase & magnitude ripple 09-23-2007
phase = DirCoupler->PhaseRippleCompensate(phase, Frequency);
double magCorr = DirCoupler->MagRippleCorrection(phase, Frequency);
magnitudeLin += magnitudeLin * magCorr;
}
}
#endif
rphsDegr = NormalizePhaseDegr(phase); // return phase in degrees (-180..+180)
rmagLin = magnitudeLin; // return linear magnitude (0..1)
return;
}
// Resolve transmitted measured data set to Magnitude and Phase
void InstrumentCalDataSet::ResolveTranPolar(MeasurementSet^ dataPoint, __int64 Frequency, double& rmag, double& rphs)
{
double magnitudeDB, phase, magnitudeLin;
magnitudeDB = SHORT2DB(dataPoint->TranMQ);
phase = SHORT2PHASE(dataPoint->TranPQ);
//magnitudeDB = TxDet->MagTodBTran(Frequency, dataPoint->TranMQHi, dataPoint->TranMQ, dataPoint->TranMQMid);
//phase = TxDet->IQtoDegrees(dataPoint->TranPI, dataPoint->TranPQ, Frequency, magnitudeDB, dataPoint->TranPILow, dataPoint->TranPQLow);
// Compensate phase at low frequencies
//phase -= HIGHPASSPOLE/Frequency;
// offset phase by 180 degrees for Trans measurements
phase += 180.0;
phase = NormalizePhaseDegr(phase);
magnitudeLin = pow(10.0, (magnitudeDB/20.0)); // translate db to voltage ratio
rmag = magnitudeLin; // return linear magnitude (0..1)
rphs = phase; // return phase in degrees (-180..+180)
}
// Construct Cal error terms from Cal raw data at each frequency point
void CalToErrorTerms(InstrumentCalDataSet^ Cal)
{
for (int i=0; i<1024; i++)
{
#if 0
double freq = (double) Cal->GetFreqFromFixtureCalGrid(i, false);
std::complex<double> two(2.0, 0.0);
std::complex<double> rslt(0.0, 0.0);
double realpart, imagpart;
realpart = Cal->S11shortReal[i];
imagpart = Cal->S11shortImag[i];
std::complex<double> Sshort(realpart, imagpart);
realpart = Cal->S11openReal[i];
imagpart = Cal->S11openImag[i];
std::complex<double> Sopen(realpart, imagpart);
realpart = Cal->S11termReal[i];
imagpart = Cal->S11termImag[i];
std::complex<double> Sterm(realpart, imagpart);
Cal->Ed[i] = Cal->Es[i];
// Directivity error term
Cal->EdReal[i] = Cal->S11termReal[i];
Cal->EdImag[i] = Cal->S11termImag[i];
// Source mismatch error term
rslt = ((two * Sterm) - (Sshort + Sopen)) / (Sshort - Sopen);
Cal->EsReal[i] = real(rslt);
Cal->EsImag[i] = imag(rslt);
// Tracking error term
rslt = ((two * (Sopen - Sterm) * (Sshort - Sterm)) / (Sshort - Sopen));
Cal->EtReal[i] = real(rslt);
Cal->EtImag[i] = imag(rslt);
// Thru error term
Cal->ThReal[i] = Cal->S21termReal[i];
Cal->ThImag[i] = Cal->S21termImag[i];
#else
double freq = (double) Cal->GetFreqFromFixtureCalGrid(i, false);
std::complex<double> g1(-1, 0.0);
std::complex<double> g2(1, 0.0);
std::complex<double> g3(0.0, 0.0);
std::complex<double> plusJ(0.0, 1.0);
std::complex<double> minJ(0.0, -1.0);
std::complex<double> Zsp,Zop,Zl, gammaShort,gammaOpen, denominator,e00,e11,e10e32,e30,deltaE;
std::complex<double> two(2.0, 0.0);
std::complex<double> one(1.0, 0.0);
std::complex<double> pi(Math::PI, 0.0);
std::complex<double> e(Math::E, 0.0);
//double pi = Math::PI;
double shortL0 = Cal->ShortL0 * 1e-12;
double shortL1 = Cal->ShortL1 * 1e-24;
double shortL2 = Cal->ShortL2 * 1e-32;
double loadL0 = Cal->LoadL0 * 1e-12;
double loadR0 = Cal->LoadR0;
double openC0 = Cal->OpenC0 * 1e-15;
double openC1 = Cal->OpenC1 * 1e-24;
double openC2 = Cal->OpenC2 * 1e-34;
double openLength = Cal->OpenLength;
double shortLength = Cal->ShortLength;
double loadLength = Cal->LoadLength;
// double loadR = 50.0;
double divisor;
double realpart, imagpart;
realpart = Cal->S11shortReal[i];
imagpart = Cal->S11shortImag[i];
std::complex<double> gm1(realpart, imagpart);
realpart = Cal->S11openReal[i];
imagpart = Cal->S11openImag[i];
std::complex<double> gm2(realpart, imagpart);
realpart = Cal->S11termReal[i];
imagpart = Cal->S11termImag[i];
std::complex<double> gm3(realpart, imagpart);
realpart = Cal->S21termReal[i];
imagpart = Cal->S21termImag[i];
std::complex<double> s21m(realpart, imagpart);
Zsp = plusJ * two * pi * freq * (shortL0 + shortL1 * freq + shortL2 * freq * freq) / 50.0;
gammaShort = (Zsp - one)/(Zsp + one);
g1 = gammaShort * std::pow(e, plusJ * pi * (2*2*freq*shortLength*-1.0));
divisor = 2 * Math::PI * freq * (openC0 + openC1 * freq + openC2 * freq * freq);
if (divisor != 0.0) {
Zop= (minJ / divisor) / 50.0;
gammaOpen = (Zop - one)/(Zop + one);
g2 = gammaOpen * std::pow(e, plusJ * pi * (2*2*freq*openLength*-1.0));
} else
g2 = one;
Zl = (loadR0 + plusJ * pi * (2 * freq * loadL0))/50.0;
g3 = (Zl - one)/ (Zl + one);
g3 = g3 * std::pow(e, plusJ * pi * (2*2*freq*loadLength*-1.0));
denominator = g1*(g2-g3)*gm1;
denominator = denominator + g2*g3*gm2 - g2*g3*gm3 - (g2*gm2-g3*gm3)*g1;
e00 = - ((g2*gm3 - g3*gm3)*g1*gm2 - (g2*g3*gm2 - g2*g3*gm3 - (g3*gm2 - g2*gm3)*g1)*gm1) / denominator;
e11 = ((g2-g3)*gm1-g1*(gm2-gm3)+g3*gm2-g2*gm3) / denominator;
deltaE = - ((g1*(gm2-gm3)-g2*gm2+g3*gm3)*gm1+(g2*gm3-g3*gm3)*gm2) / denominator;
// e10e32 = s21m * (one - (e11*e11));
e10e32 = s21m; // * (one - (e11*e11));
// Directivity error term
Cal->EdReal[i] = real(e00);
Cal->EdImag[i] = imag(e00);
// Source mismatch error term
Cal->EsReal[i] = real(e11);
Cal->EsImag[i] = imag(e11);
// Tracking error term
Cal->EtReal[i] = real(deltaE);
Cal->EtImag[i] = imag(deltaE);
// Thru error term
Cal->ThReal[i] = real(e10e32);
Cal->ThImag[i] = imag(e10e32);
#endif
}
};
std::complex<double> CorrectS11(std::complex<double> point, InstrumentCalDataSet^ Cal, __int64 Frequency, bool ReflExtn, bool calMode, double measmag, double measphs, double& rsltmag, double& rsltphs)
{
return point;
}
// Convert measured S11 into actual S11 via fixture calibration
void CorrectS11(InstrumentCalDataSet^ Cal, __int64 Frequency, bool ReflExtn, bool calMode, double measmag, double measphs, double& rsltmag, double& rsltphs)
{
// Modified 02-07-2010 to select Linear(f) or Log(f) fixture calibration
// Convert measured data to rectangular coordinates
double phase_radians = measphs * DEGR2RAD;
double measreal = measmag * cos(phase_radians);
double measimag = measmag * sin(phase_radians);
std::complex<double> rslt(measreal, measimag);
int i, j;
double delta, position;
double realpart, imagpart;
if (calMode) {
if (Cal->FixtureCalLogFreqMode == false) // Linear(f) interpolation
{
// There are 1024 fixture calibration frequencies linearly spaced. Find the two adjacent to the
// measured frequency. Linearly interpolate (real, imag) between the two cal points.
delta = ((double)Cal->maxCalFreq - (double)Cal->minCalFreq)/ (NUMCALPTS - 1.0); // frequency separation of cal points
i = (int)(((double)Frequency - (double)Cal->minCalFreq) / delta); // Cal frequency directly below ours
if (i < 0)
i = 0;
if (i >= (int)NUMCALPTS)
i = (int)NUMCALPTS - 1;
j = i+1; // Cal frequency directly above ours
if(j >= (int)NUMCALPTS)
j = (int)NUMCALPTS - 1; // In case we are close to MAX cal frequnecy
position = (((double)Frequency - (double)Cal->minCalFreq) / delta) - i ; // fractional position between i and j
}
else // Log(f) interpolation
{
// There are 1024 fixture calibration frequencies, logrithmically spaced. Find the two adjacent to the
// measured frequency. Linearly interpolate (real, imag) between the two cal points.
double LogFreqIncrement = Math::Log10((double)Cal->maxCalFreq/(double)Cal->minCalFreq)/(NUMCALPTS-1);
double FreqIncrement = Math::Pow(10, LogFreqIncrement);
// compute index equivalent to the frequency
double exactIndex = Math::Log10((double)Frequency/(double)Cal->minCalFreq)/LogFreqIncrement;
i = (int)exactIndex; // Cal frequency index directly below ours
j=i+1; // Cal frequency index directly above ours
if(j >= (int)NUMCALPTS)
j = (int)NUMCALPTS - 1; // In case we are close to MAX cal frequency
double Flow = (double)Cal->minCalFreq * Math::Pow(FreqIncrement, i);
double Fhigh = (double)Cal->minCalFreq * Math::Pow(FreqIncrement, j);
if (abs(Fhigh - Flow) < 1e-6)
position = 0.0; // Supress interpolation at the end points
else
position = ((double)Frequency - Flow) / (Fhigh - Flow);
}
// transform measured S11 into actual S11
realpart = Cal->EdReal[i] + ((Cal->EdReal[j] - Cal->EdReal[i]) * position); // interpolate
imagpart = Cal->EdImag[i] + ((Cal->EdImag[j] - Cal->EdImag[i]) * position);
std::complex<double> Ed(realpart, imagpart);
realpart = Cal->EsReal[i] + ((Cal->EsReal[j] - Cal->EsReal[i]) * position); // interpolate
imagpart = Cal->EsImag[i] + ((Cal->EsImag[j] - Cal->EsImag[i]) * position);
std::complex<double> Es(realpart, imagpart);
realpart = Cal->EtReal[i] + ((Cal->EtReal[j] - Cal->EtReal[i]) * position); // interpolate
imagpart = Cal->EtImag[i] + ((Cal->EtImag[j] - Cal->EtImag[i]) * position);
std::complex<double> Et(realpart, imagpart);
#if 0
rslt = ((rslt - Ed) / (Es * (rslt - Ed) + Et));
#else
rslt = (rslt - Ed) / ((Es * rslt) - Et);
#endif
}
if (ReflExtn) // extend reference plane with calculated value
{
// Use reflTimeDelayEquivalent to calculate the required phase shift
// double linmag = sqrt(real(Et) * real(Et) + imag(Et) * imag(Et));
double linmag = 1.0; // Ignore magnitude impact for now
double newAngleRadians = -(Cal->reflTimeDelayEquivalent * 2 * Math::PI * Frequency);
double realLin = linmag * cos(newAngleRadians);
double imagLin = linmag * sin(newAngleRadians);
std::complex<double> ELin(realLin, imagLin);
rslt = rslt / ELin;
}
// Convert results to polar coordinates
double x = real(rslt);
double y = imag(rslt);
double fphase = atan2(y, x) * RAD2DEGR;
double fmagnitude = sqrt(x*x + y*y);
rsltmag = fmagnitude;
rsltphs = fphase;
}
// Convert measured S21 into actual S21 via fixture calibration
void CorrectS21(InstrumentCalDataSet^ Cal, __int64 Frequency, bool calMode, double measmag, double measphs, double& rsltmag, double& rsltphs)
{
// Modified 02-07-2010 to select Linear(f) or Log(f) fixture calibration
// Convert measured data to rectangular coordinates
double phase_radians = measphs * DEGR2RAD;
double measreal = measmag * cos(phase_radians);
double measimag = measmag * sin(phase_radians);
std::complex<double> rslt(measreal, measimag);
int i, j;
double delta, position;
double realpart, imagpart;
if (calMode) {
if (Cal->FixtureCalLogFreqMode == false) // Linear(f) interpolation
{
// There are 1024 fixture calibration frequencies linearly spaced. Find the two adjacent to the
// measured frequency. Linearly interpolate (real, imag) between the two cal points.
delta = ((double)Cal->maxCalFreq - (double)Cal->minCalFreq)/ (NUMCALPTS - 1); // frequency separation of cal points
i = (int)(((double)Frequency - (double)Cal->minCalFreq) / delta); // Cal frequency directly below ours
if (i >= (int)NUMCALPTS)
i = (int)NUMCALPTS - 1;
j = i+1; // Cal frequency directly above ours
if(j >= (int)NUMCALPTS)
j = (int)NUMCALPTS - 1; // In case we are close to MAX cal frequnecy
position = (((double)Frequency - (double)Cal->minCalFreq) / delta) - i ; // fractional position between i and j
}
else // Log(f) interpolation
{
// There are 1024 fixture calibration frequencies, logrithmically spaced. Find the two adjacent to the
// measured frequency. Linearly interpolate (real, imag) between the two cal points.
double LogFreqIncrement = Math::Log10((double)Cal->maxCalFreq/(double)Cal->minCalFreq)/(NUMCALPTS-1);
double FreqIncrement = Math::Pow(10, LogFreqIncrement);
// compute index equivalent to the frequency
double exactIndex = Math::Log10((double)Frequency/(double)Cal->minCalFreq)/LogFreqIncrement;
i = (int)exactIndex; // Cal frequency index directly below ours
j=i+1; // Cal frequency index directly above ours
if(j >= (int)NUMCALPTS)
j = (int)NUMCALPTS - 1; // In case we are close to MAX cal frequency
double Flow = (double)Cal->minCalFreq * Math::Pow(FreqIncrement, i);
double Fhigh = (double)Cal->minCalFreq * Math::Pow(FreqIncrement, j);
if (abs(Fhigh - Flow) < 1e-6)
position = 0.0; // supress interpolation at the end points
else
position = ((double)Frequency - Flow) / (Fhigh - Flow);
}
if (i < 0) i = 0;
if (j < 0) j = 0;
realpart = Cal->ThReal[i] + ((Cal->ThReal[j] - Cal->ThReal[i]) * position); // interpolate between calibration points
imagpart = Cal->ThImag[i] + ((Cal->ThImag[j] - Cal->ThImag[i]) * position);
// transform measured S21 into actual S21
std::complex<double> Th(realpart, imagpart);
rslt = rslt / Th;
}
// Convert results to polar coordinates
double x = real(rslt);
double y = imag(rslt);
double fphase = atan2(y, x) * RAD2DEGR;
double fmagnitude = sqrt(x*x + y*y);
rsltmag = fmagnitude;
rsltphs = fphase;
}
std::complex<double> ReadComplex(BinaryReader^ br)
{
double r,i;
r = br->ReadDouble();
i = br->ReadDouble();
std::complex<double> c(r,i);
return(c);
}
// Load Fixture Calibration Data Set. Modified 02-07-2010 to recognize LOG(f) type Fixture Cal file
bool LoadCalDataSet(OpenFileDialog^ infile, InstrumentCalDataSet^ Cal)
{
FileStream^ fs;
BinaryReader^ br;