-
Notifications
You must be signed in to change notification settings - Fork 0
/
MathCalculations.c
459 lines (403 loc) · 14.2 KB
/
MathCalculations.c
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
/**
* @file MathCalculations.c
* @author Alex Ryan
* @date MAR 16, 2015
* @brief Math heavy code for calculations on stop/start/index times are here
*
* Moved all of the calculation code to this file
*
*/
#include "MathCalculations.h"
#include <math.h>
//Calculation Variables
float buf[M]; // search buffer
float matchedFilterCosine[M]; // in-phase correlation buffer
float matchedFilterSine[M]; // quadrature correlation buffer
float corr_max, corr_max_s, corr_max_c; // correlation variables
float corr_c[2*M];
float corr_s[2*M];
float s[2*M];
short corr_max_lag;
short bufindex = 0;
float corrSumCosine,corrSumSine,corrSumIncoherent;
short i,j,k; // Indices
double t,x,y; // More Indices
float basebandSincRef[2*N+1]; // baseband sinc pulse buffer
float recbuf[2*N+2*M]; // recording buffer
float downMixedCosine[2*N+2*M]; // in-phase downmixed buffer
float downMixedSine[2*N+2*M]; // quadrature downmixed buffer
short recbufindex = 0; //
volatile char local_carrier_phase = 0;
char r = 0;
double phase_correction_factor;
short max_samp = 0;
volatile int recbuf_start_clock = 0; // virtual clock counter for first sample in recording buffer
/**
* Calculates the delay estimates
* Stores the results in the coarse_delay_estimate and fine_delay_estimate buffers
*/
void runReceviedSincPulseTimingAnalysis(){
// this is where we apply the matched filter
// we only do this over a limited range
for (i=0;i<=(2*M-1);i++) {
corr_c[i] = 0;
corr_s[i] = 0;
for (j=0;j<(2*N+1);j++) {
corr_c[i] += basebandSincRef[j]*downMixedCosine[j+i];
corr_s[i] += basebandSincRef[j]*downMixedSine[j+i];
}
s[i] = corr_c[i]*corr_c[i]+corr_s[i]*corr_s[i]; // noncoherent correlation metric
}
// now find the peak
corr_max = 0;
corr_max_lag = 0;
for (i=0;i<=(2*M-1);i++) {
if (s[i]>corr_max){
corr_max = s[i];
corr_max_lag = i;
}
}
corr_max_c = corr_c[corr_max_lag];
corr_max_s = corr_s[corr_max_lag];
/*
printf wrecks the real-time operation
printf("Max lag: %d\n",corr_max_lag);
printf("Coarse delay estimate: %d.\n",recbuf_start_clock+corr_max_lag);
*/
//increment indices
cde_index++;
if(cde_index>=MAX_STORED_DELAYS_COARSE) cde_index = 0;
fde_index++;
if(fde_index>=MAX_STORED_DELAYS_FINE) fde_index = 0;
//We do this here, so that the current indice that we are about to store is always the most recent.
// store coarse delay estimates
coarse_delay_estimate[cde_index] = recbuf_start_clock+corr_max_lag;
// fine delay estimate
y = (double) corr_max_s;
x = (double) corr_max_c;
phase_correction_factor = atan2(y,x)*2*INVPI; // phase
r = (recbuf_start_clock+corr_max_lag) & 3; // compute remainder
if (r==0)
fine_delay_estimate[fde_index] = recbuf_start_clock+corr_max_lag+phase_correction_factor;
else if (r==1)
fine_delay_estimate[fde_index] = recbuf_start_clock+corr_max_lag+phase_correction_factor-1;
else if (r==2) {
if (phase_correction_factor>0)
fine_delay_estimate[fde_index] = recbuf_start_clock+corr_max_lag+phase_correction_factor-2;
else
fine_delay_estimate[fde_index] = recbuf_start_clock+corr_max_lag+phase_correction_factor+2;
}
else if (r==3)
fine_delay_estimate[fde_index] = recbuf_start_clock+corr_max_lag+phase_correction_factor+1;
else
printf("ERROR");
// --- Calculations Finished ---
}
/**
* Mixes the received waveform in recbuf down to baseband. ONLY WORKS at currently set center freq (1/2 of nyquist)
*/
void runReceivedPulseBufferDownmixing(){
// downmix (had problems using sin/cos here so used a trick)
/* The trick is based on the incoming frequency per sample being (n * pi/2), so every other sample goes to zero,
* while the non-zero components sin() multiplicative factor is unity/1 */
for (i=0;i<(2*N+2*M);i+=4){
downMixedCosine[i] = recbuf[i];
downMixedSine[i] = 0;
}
for (i=1;i<(2*N+2*M);i+=4){
downMixedCosine[i] = 0;
downMixedSine[i] = recbuf[i];
}
for (i=2;i<(2*N+2*M);i+=4){
downMixedCosine[i] = -recbuf[i];
downMixedSine[i] = 0;
}
for (i=3;i<(2*N+2*M);i+=4){
downMixedCosine[i] = 0;
downMixedSine[i] = -recbuf[i];
}
}
/**
* Note, receiveBufSize typically 2N+2M
* @param receiveBuf The receive buffer to downmix from, which contains the received modulated signal
* @param dmCos In-phase baseband buffer to receive into
* @param dmSin Quadrature baseband buffer
* @param receiveBufSize Size of the buffer
*/
void quarterWavePulseDownmix(float* receiveBuf, float* dmCos, float* dmSin, short receiveBufSize){
// downmix (had problems using sin/cos here so used a trick)
/* The trick is based on the incoming frequency per sample being (n * pi/2), so every other sample goes to zero,
* while the non-zero components sin() multiplicative factor is unity/1 */
for (i=0;i<receiveBufSize;i+=4){
*(dmCos + i) = *(receiveBuf+i);
*(dmSin + i) = 0;
}
for (i=1;i<(2*N+2*M);i+=4){
*(dmCos + i) = 0;
*(dmSin + i) = *(receiveBuf+i);
}
for (i=2;i<(2*N+2*M);i+=4){
*(dmCos + i) = -(*(receiveBuf+i));
*(dmSin + i) = 0;
}
for (i=3;i<(2*N+2*M);i+=4){
*(dmCos + i) = 0;
*(dmSin + i) = -(*(receiveBuf+i));
}
}
/**
Sets up the transmit buffer for the sinc pulse modulated at quarter sampling frequency
*/
void SetupTransmitModulatedSincPulseBuffer(){
for (i=-N;i<=N;i++){
x = i*BW;
t = i*CBW;
if (i!=0)
y = cos(2*PI*t)*(sin(PI*x)/(PI*x)); // modulated sinc pulse at carrier freq = fs/4
else
y = 1; //x = 0 case.
tClockSincPulse[i+N] = y*32767; //Both of these may be modified in the future calculations anywas
tVerifSincPulse[i+N] = y*32767; //If FDE mode is on in order to do partial synchronization
}
//Half sample delayed
for (i=-N;i<=N;i++){
x = (i-0.5)*BW;
t = (i-0.5)*0.25;
y = cos(2*PI*t)*(sin(PI*x)/(PI*x)); // modulated sinc pulse at carrier freq = fs/4
tVerifSincPulsePhased[i+N] = y*32767;
}
}
/**
* Calculates a transmission waveform to be placed into a buffer.
* @param tBuffer The buffer to put the waveform into
* @param halfBufLen The size of one half of the buffer (e.g. -N, to 0, to N)
* @param sincBandwidth The bandwidth of the sinc pulse (e.g. 0.0125 BW)
* @param carrierFreq The frequency to modulate at (e.g. 0.25 CBW)
* @param delay the fractional delay in samples to allow for sync (e.g. 0.5 is one half sample delay)
*/
void setupTransmitBuffer(short* tBuffer, short halfBufLen, float sincBandwidth, float carrierFreq, float delay){
//i is index per element, y is temp for output
int idx;
float x, y, t;
for (idx=-halfBufLen;idx<=halfBufLen;idx++){
x = (idx - delay) * sincBandwidth;
t = (idx - delay) * carrierFreq;
if (x == 0.00000) //floating point check if delay is too close to 1 or 0 to keep division by zero from occurring
y = 1.0;
else
y = cos(2*PI*t)*(sin(PI*x)/(PI*x)); // modulated sinc pulse at carrier freq = fs/4
*(tBuffer + idx + halfBufLen) = (short)(y*32767);
}
}
/**
Sets up the buffer used for matched filtering of the sinc pulse
*/
void SetupReceiveBasebandSincPulseBuffer(){
for (i=-N;i<=N;i++){
x = i*BW;
if (i!=0)
y = sin(PI*x)/(PI*x); // double
else
y = 1.0;
basebandSincRef[i+N] = (float) y;
}
}
/**
* sets up a buffer with an unmodulated sinc pulse centered at x=0
* @param buffer the buffer to write into
* @param halfBufLen half the buffer size, plus 0
* @param sincBandwidth the bandwidth of the sinc pulse (e.g. 0.0125 BW)
*/
void setupBasebandSincBuffer(float* buffer, short halfBufLen, float sincBandwidth){
for (i=-N;i<=N;i++){
x = i*sincBandwidth;
if (i!=0)
y = sin(PI*x)/(PI*x); // double
else
y = 1.0;
*(buffer + i + halfBufLen) = (float) y;
}
}
/**
Sets up the matched filter buffers which are used for matching and filtering of the incoming sines and cosines
*/
void SetupReceiveTrigonometricMatchedFilters(){
for (i=0;i<M;i++){
t = i*CBW; // time
y = cos(2*PI*t); // cosine matched filter (double)
matchedFilterCosine[i] = (float) y; // cast and store
y = sin(2*PI*t); // sine matched filter (double)
matchedFilterSine[i] = (float) y; // cast and store
buf[i] = 0; // clear searching buffer
}
}
/**
*
* @param inPhaseBuffer
* @param quadraturebuffer
* @param bufLen
* @param cFreq
*/
void setupQuadratureCarrierWaveFilterBuffer(float* inPhaseBuffer, float* quadraturebuffer, short bufLen, float cFreq){
for (i=0;i<M;i++){
t = i*CBW; // time
y = cos(2*PI*t); // cosine matched filter (double)
matchedFilterCosine[i] = (float) y; // cast and store
y = sin(2*PI*t); // sine matched filter (double)
matchedFilterSine[i] = (float) y; // cast and store
buf[i] = 0; // clear searching buffer
}
}
/**
* Looks at the received response time, the current time (to prevent trying to send immediately a fractional waveform,
* and calculates the new mirrored center time around a clock tick upon which to center the response at
*/
short calculateNewResponseTimeMaster(short curTime, short delayEstimate){
return 0; /** \todo */
}
/**
*
*/
short calculateNewSynchronizationTimeSlave(short curTime, short delayEstimate){
return 0; /** \todo */
}
/**
* Returns the index to output for a buffer, based on the current clock counter and the expected center pulse
* @param VClockCurrent
* @param VClockCenterPulse
*/
int GetPulseIndex(int VClockCurrent, int VClockCenterPulse, short halfBufLen){
int tempIndex = VClockCurrent - VClockCenterPulse + halfBufLen;
if (tempIndex <= -1) //index too early
tempIndex = -1; //too far behind, just clamp at -1 to indicate we're not outputing now and actually output 0
if (tempIndex >= (2*halfBufLen+1)) //index too ahead
tempIndex = -1;
return tempIndex;
}
/**
* Sums up an array of floats to produce the sum
* @param array The array to sum
* @param numElmts Number of elements to sum
* @return The sum
*
*
*/
float sumFloatArray(float* array, short numElmts){
float sum = 0.0;
short idx = 0;
for(idx=0; idx < numElmts; idx++){
sum += array[idx];
}
return sum;
}
/**
* Sums an array of integers and returns the result
* @param array pointer to array of values
* @param numElmts
* @return the sum of the array. In long format to prevent overflow
*/
long sumIntArray(short* array, short numElmts){
long sum = 0;
short idx = 0;
for(idx=0; idx < numElmts; idx++){
sum += (long)array[idx];
}
return sum;
}
/**
* calculates the new time to transmit for the verification on the slave
* @param curTime
* @param delayEstimate
* @return the center time of the vclock counter
*/
int calculateNewSynchronizationTimeSlaveCoarse(int curTime, int delayEstimate){
return 0;
}
/**
* Calculates the new center time to transmit at for the masters mirrored response to the slave
* @param curTime
* @param delayEstimate
* @return the center time of vclock counter
*/
int calculateNewResponseTimeMasterCoarse(int curTime, int delayEstimate){
return 0;
}
/**
* Calculates the new master buffer given the prior delay estimates for responding around the center tick.
* @param buffer
* @param bufferLen
* @param fine_delay_estimate
* @param fde_index
*/
void calculateNewResponseBufferMaster(short* buffer, short bufferLen, float* fine_delay_estimate, short fde_index){
}
/**
* Writes the verification waveform used to show synchronization with the master to the slaves buffer.
* This is used for fine synchronization (subsample)
* @param buffer Bufer to write into
* @param bufferLen length of buffer (usually N2)
* @param fine_delay_estimate array of prior delay estimations to allow for linear extrapolation
* @param fde_index index of latest estimate
*/
void calculateNewVerifBufferSlave(short* buffer, short bufferLen, float* fine_delay_estimate, short fde_index){
}
/**
*
* @param vclock_counter
* @param fine_delay_estimate
* @param fde_index
* @return the clock time to put into
*/
int calculateNewResponseTimeMasterFine(int vclock_counter, float* fine_delay_estimate, short fde_index){
return 0;
}
/**
*
* @param vclock_counter current counter time
* @param fine_delay_estimate array of prior delay estimates
* @param fde_index index of current estimate
* @return
*/
int calculateNewSynchronizationTimeSlaveFine(int vclock_counter, float* fine_delay_estimate, short fde_index){
return 0;
}
/**
* Takes the delay estimate time, wraps it around the nearest virtual clock tick based on the counter time
* @param fine_delay_estimate_array Array of the variables containing the delay estimates
* @param fde_index index offset for the array indicating the latest estimate
* @return The new virtual clock tick to center around to transmit
*/
float masterMirrorResponseTime(float* fine_delay_estimate_array, short fde_index){
int curVClockTime = vclock_counter;
int wrappedTime = SMALL_VCLK_WRAP(vclock_counter);
int nearestNodeTime = curVClockTime - wrappedTime; //take current time and find the nearest node by removing the offset
float floatingNearestNodeTime = (float) nearestNodeTime; //This should be LATER than the estimate since the clock counter is always running
//index time, we shouldn't need to run any linear regression analysis since we're the master
float delayEstimate = *(fine_delay_estimate_array + fde_index);
//equiv to floatingNearestNodeTime + -(delayEstimate - floatingNearestNodeTime)
float wrappedMasterTime = 2*floatingNearestNodeTime - delayEstimate;
//If we're on wrapping clock time, might be negative
while (wrappedMasterTime < 0.0f)
wrappedMasterTime += (float) SMALL_VCLK_MAX; //make positive
//This next line is ONLY NECCESARY FOR THE NON-WRAPPING CLOCK!
if ((float)vclock_counter + MIN_THRESHOLD_FOR_CALCS >= wrappedMasterTime)
wrappedMasterTime += 2.0 * (float) SMALL_VCLK_MAX; //adds another clock period to wait for if our calc time is too close to current time.
return wrappedMasterTime;
}
/**
* Gets the fractional part of the calculated center time to transmit at for the array recalculation function
* @param mirroredResponseTime
* @return
*/
float getMasterDelayLevelFromResponseTime(float mirroredResponseTime){
int integerizedTime = (int)mirroredResponseTime; //This should work if it's floor to negative infinity rounding, otherwise ~\_-_-_/~
return mirroredResponseTime - (float)integerizedTime;
}
/**
* Converts the precise response time value to an integer which corresponds with the proper ISR tick to send at
* @param mirroredResponseTime
* @return
*/
int getMasterIntegerResponseTime(float mirroredResponseTime){
return (int) mirroredResponseTime;
}