-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathTKspectrum.C
More file actions
1741 lines (1595 loc) · 51.7 KB
/
TKspectrum.C
File metadata and controls
1741 lines (1595 loc) · 51.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
// Copyright (C) 2006,2007,2008,2009, George Hobbs, Russel Edwards
/*
* This file is part of TEMPO2.
*
* TEMPO2 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 3 of the License, or
* (at your option) any later version.
* TEMPO2 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 TEMPO2. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* If you use TEMPO2 then please acknowledge it by citing
* Hobbs, Edwards & Manchester (2006) MNRAS, Vol 369, Issue 2,
* pp. 655-672 (bibtex: 2006MNRAS.369..655H)
* or Edwards, Hobbs & Manchester (2006) MNRAS, VOl 372, Issue 4,
* pp. 1549-1574 (bibtex: 2006MNRAS.372.1549E) when discussing the
* timing model.
*/
/* Routines useful for spectral analysis
* Based on work carried out by G. Hobbs
* and W. Coles
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "tempo2.h"
#include "T2toolkit.h"
#include "TKfit.h"
#include "TKspectrum.h"
/* Global variables used in the fortran code for sigmaz*/
int npt,nusewt,nxunits,ntunits,nformat,nwriteres,nbintype;
int npt1last,npt2last,ncubic,ncubics,ntau,linfile,indx[90000],ndim;
double data[90000],utjd[90000],taumin,sigmai[90000],permax,root2;
double utjd1,utjd2,tmin,tmax,xmin,xmax,utjdlast,tausec,taumax,tauday;
double prtl[5],utmean,secyear,taulog,addvar,tauyear,tauensure,tdiffmin;
double utfirst,utlast;
bool verbose_calc_spectra=false;
/* ************************************************************** *
* General routines:
*
* TKspectrum() - spectral analysis of a data set
* x = array of arrival times
* y = array of residuals
* n = number of observations
* averageTime > 0 => average to sampling of given number of days
* = 0 => no averaging
* smoothWidth = smoothing width (days; odd, integer)
* smoothType = 0 => No smoothing
* = 1 => Hann smoothing
* preWhite = 0 => no pre-whitening
* = 1 => first differencing
* = 2 => second differencing
* specType = 1 => DFT
* = 2 => Lomb-Scargle periodogram
* = 3 => FFT
* = 4 => Weighted L-S periodogram
* ofac = oversampling factor
* hifac = the highest frequency to which we want to calculate, expressed as a multiple of the Nyquist frequency
* output = 0 => no text output
* = 1 => print sorted input data set, then stop
* = 2 => print averaged data points, then stop
*
* Output:
*
* outX = frequency channels
* outY = power
* nout = number of frequency channels
*
* NOTE: All arrays start from zero
* ************************************************************** */
double TKspectrum(double *x,double *y,double *e,int n,int averageTime,int smoothWidth,int smoothType,
int fitSpline,int preWhite,int specType,double ofac,double hifac,int specOut,double *outX,
double *outY,int *nout,int calcWhite,int output, double *outY_re, double *outY_im)
{
double avPtsX[n],avPtsY[n];
double interpX[n],interpY[n];
double smoothX[n],smoothY[n];
double specX[(int)ceil(1 + ofac * hifac * MAX_OBSN / 2.0)],specY[(int)ceil(1 + ofac * hifac * MAX_OBSN / 2.0)];
int splineDaily=0;
double mean;
int i;
int nAv=0;
int nInterp=0;
int nSmooth=0;
int nSpec=0;
// Step 1: Sort the data in increasing time order
//NB THIS SORTING CAN CHANGE THE ORDER OF SATS AND RESIDUALS!!!! Causes many strange problems
TKsortit(x,y,n);
if (output==1)
{
for (i=0;i<n;i++)
printf("sortdata: %d %g %g\n",i,x[i],y[i]);
exit(1);
}
// Step 2: Average the points within a given time of each other
// CURRENTLY NOT USING ERROR BARS
if (averageTime==0) // No averaging
{
for (i=0;i<n;i++)
{
avPtsX[i] = x[i];
avPtsY[i] = y[i];
}
nAv = n;
}
else
TKaveragePts(x,y,n,averageTime,avPtsX,avPtsY,&nAv);
// for(i=0;i<n;i++){
//printf("Joris: %.10lg %.10lg %.10lg %.10lg.\n",x[i],avPtsX[i],y[i],avPtsY[i]);
//}
// printf("Joris2: %d %d.\n",n,nAv);
if (output==2)
{
for (i=0;i<nAv;i++)
printf("averagePoints: %d %g %g\n",i,avPtsX[i],avPtsY[i]);
exit(1);
}
// Step 3: Remove mean from the timing residuals
mean=TKmean_d(avPtsY,nAv);
for (i=0;i<nAv;i++)
avPtsY[i]-=mean;
if (output==3)
{
for (i=0;i<nAv;i++)
printf("meanRemoved: %d %g %g\n",i,avPtsX[i],avPtsY[i]);
exit(1);
}
// Step 4: Fit a spline to the data and obtain equally spaced sampling
if (fitSpline==1)
{
double yd[MAX_OBSN][4];
TKcmonot(nAv,avPtsX,avPtsY,yd);
if (splineDaily==1)
{
nInterp=0;
do{
interpX[nInterp] = avPtsX[0]+nInterp;
nInterp++;
}while (interpX[nInterp-1]<avPtsX[nAv-1]);
nInterp--;
}
else
{
// nInterp = nAv;
nInterp = 4096;
for (i=0;i<nInterp;i++)
interpX[i] = avPtsX[0]+i*(avPtsX[nAv-1]-avPtsX[0])/(double)nInterp;
// interpX[i] = avPtsX[i];
}
TKspline_interpolate(nAv,avPtsX,avPtsY,yd,interpX,interpY,nInterp);
if (output==4)
{
for (i=0;i<nInterp;i++)
printf("spline: %d %g %g\n",i,interpX[i],interpY[i]);
exit(1);
}
}
else
{
for (i=0;i<nAv;i++)
{
interpX[i] = avPtsX[i];
interpY[i] = avPtsY[i];
}
nInterp = nAv;
}
// Step 5: Smooth using Hann filter
if (smoothType==0) // No smoothing
{
for (i=0;i<nInterp;i++)
{
smoothX[i] = interpX[i];
smoothY[i] = interpY[i];
}
nSmooth = nInterp;
}
else if (smoothType==1) // Hann smoother
{
int smoothWidth2;
// Convert to days
// smoothWidth2 = (int)(smoothWidth*nInterp/(interpX[nInterp-1]-interpX[0]));
smoothWidth2=smoothWidth;
if (smoothWidth < 1) smoothWidth = 1;
printf("SmoothWidth = %d\n",smoothWidth2);
TKhann(interpX,interpY,nInterp,smoothX,smoothY,&nSmooth,smoothWidth2);
}
else
{
printf("SmoothType = %d unknown\n",smoothType);
exit(1);
}
if (output==5)
{
for (i=0;i<nSmooth;i++)
printf("smooth: %d %g %g\n",i,smoothX[i],smoothY[i]);
exit(1);
}
// Do we want to calculate the white noise component?
if (calcWhite==1)
{
double reInterpX[MAX_OBSN],reInterpY[MAX_OBSN];
double yd[MAX_OBSN][4];
int nReInterp=n,c=0;
double xv=0.0,xvsq=0.0;
TKcmonot(nSmooth,smoothX,smoothY,yd);
for (i=0;i<n;i++)
reInterpX[i] = x[i];
TKspline_interpolate(nSmooth,smoothX,smoothY,yd,reInterpX,reInterpY,nReInterp);
for (i=0;i<nReInterp;i++)
{
// printf("reinterp: %d %g %g\n",i,reInterpX[i],reInterpY[i]);
y[i]-=reInterpY[i];
// printf("white: %d %g %g\n",i,x[i],y[i]);
if (x[i]>x[0]+smoothWidth/2.0 && x[i]<x[n-1]-smoothWidth/2.0)
{
xv+=y[i];
xvsq+=(y[i]*y[i]);
c++;
}
}
printf("rms = %g\n",sqrt(xvsq/(double)c-pow(xv/(double)c,2)));
return sqrt(xvsq/(double)c-pow(xv/(double)c,2));
}
// Pre-whiten if requested
if (preWhite==1)
{
TKfirstDifference(smoothX,smoothY,nSmooth);
smoothY[0] = 0.0;
// for (i=0;i<nSmooth;i++)
// printf("firstdiff %g %g\n",smoothX[i],smoothY[i]);
}
else if (preWhite==2)
{
TKfirstDifference(smoothX,smoothY,nSmooth);
TKfirstDifference(smoothX,smoothY,nSmooth);
smoothY[0] = 0.0;
smoothY[1] = 0.0;
}
// Step 6: Calculate the spectrum
{
// UNUSED VARIABLE // int jmax;
double var,tspan;
tspan = TKrange_d(smoothX,nSmooth);
if (specType==1) // DFT
{
TK_dft(smoothX,smoothY,nSmooth,specX,specY,&nSpec,outY_re, outY_im);
// The following code to form the PSD in units of yr^3 and
// frequency in 1/days (required for the whitening/postdarkening)
// has been checked by G. Hobbs (30/10/08).
//
// Do not modify without leaving a comment here.
//
for (i=0;i<nSpec;i++)
{
if (specOut==1)
specY[i] = (specY[i]/pow(365.25*86400.0,2))*2*(tspan/365.25)/(double)nSmooth/(double)nSmooth;
else if (specOut==2) // Amplitude
specY[i]=sqrt(specY[i])/nSpec;
else if (specOut==3) // Power
specY[i]=specY[i]/nSpec/nSpec;
}
// End of checked section
}
else if (specType==2) // Lomb-Scargle
{
// The following code to form the PSD in units of yr^3 and
// frequency in 1/days (required for the whitening/postdarkening)
// has been checked by G. Hobbs (30/10/08).
//
// Do not modify without leaving a comment here.
//
// 05 Jan 09: G Hobbs: changed to use TKlomb_d instead of numerical recipes
// 05 Jan 09: G Hobbs: added PSD, amp and pow outputs (originally just PSD)
// 06 May 09: D Yardley: added "*ofac/hifac" in PSD calculation. Now should be consistent measured power regardless of oversampling.
// 06 May 09: D Yardley: added "*ofac*hifac" in power calculation. Now should be consistent measured power regardless of oversampling.
// 11 Aug 09: D Yardley: added specOut = 4 option for normalized power (important when adding power spectra together)
TKlomb_d(smoothX,smoothY,nSmooth,ofac,hifac,specX,specY,&nSpec,&var);
for (i=0;i<nSpec;i++)
{
if (specOut==1) // PSD
{
specY[i]*=(2.0*var*nSpec*ofac/hifac);
specY[i] = (specY[i]/pow(365.25*86400.0,2))*2*(tspan/365.25)/(double)nSmooth/(double)nSmooth;
}
else if (specOut==2) // Amplitude
specY[i]=sqrt(specY[i]*2.0*var/nSpec);
else if (specOut==3) // Power
specY[i]=specY[i]*2.0*var/nSpec*ofac*hifac;
else if (specOut==4) // Power Normalised by variance.
specY[i]=specY[i]*2.0/nSpec*ofac*hifac;
}
// End of checked section
}
else if (specType==3) //fast fourier transform
{
double imag[nSmooth];
// The following code to form the PSD in units of yr^3 and
// frequency in 1/days (required for the whitening/postdarkening)
// has been checked by G. Hobbs (30/10/08).
// Note that a 2**N number of points is required for an FFT
// (this is not checked)
//
// Do not modify without leaving a comment here.
// G. Hobbs 05 Jan 2009: Use TK_FFT instead of TK_four1
for (i=0;i<nSmooth;i++)imag[i] = 0.0;
TK_fft(1,nSmooth,smoothY,imag);
nSpec = nSmooth/2;
for (i=1;i<nSpec;i++)
{
specX[i-1] = i/(tspan);
specY[i-1] = pow(smoothY[i],2)+pow(imag[i],2);
if (specOut==1)
specY[i-1] = (specY[i-1]/pow(365.25*86400.0,2))*2*(tspan/365.25);///(double)nSmooth/(double)nSmooth;
else if (specOut==2) // Amplitude
specY[i-1]=sqrt(specY[i-1]*4.0);
else if (specOut==3) // Power
specY[i-1]=specY[i-1]*4.0;
}
nSpec--;
// End of checked version
}
else if (specType==4) // Weighted Lomb-Scargle
{
TK_weightLS(smoothX,smoothY,e,nSmooth,specX,specY,&nSpec,outY_re,outY_im);
var=1;
for (i=0;i<nSpec;i++)
{
if (specOut==1) // PSD
{
// specY[i]*=(2.0*var*nSpec);
specY[i] = (specY[i]/pow(365.25*86400.0,2))*(tspan/365.25)/2.0; ///(double)nSpec;///(double)nSmooth/(double)nSmooth;
}
else if (specOut==2) // Amplitude
specY[i]=sqrt(specY[i]);
else if (specOut==3) // Power
specY[i]=specY[i]; //*2.0*var/nSpec;
}
}
else if (specType==5) // Fit sinusoids
{
TK_fitSinusoids(smoothX,smoothY,e,nSmooth,specX,specY,&nSpec);
var=1;
for (i=0;i<nSpec;i++)
{
if (specOut==1) // PSD
{
// specY[i]*=(2.0*var*nSpec);
specY[i] = (specY[i]/pow(365.25*86400.0,2))*(tspan/365.25)/2.0; ///(double)nSpec;///(double)nSmooth/(double)nSmooth;
}
else if (specOut==2) // Amplitude
specY[i]=sqrt(specY[i]);
else if (specOut==3) // Power
specY[i]=specY[i]; //*2.0*var/nSpec;
}
}
// Post-darken if requested
if (preWhite==1)
{
for (i=0;i<nSpec;i++)
{
if (specX[i]!=0)
specY[i]/=(4.0*pow(sin(M_PI*specX[i]*(smoothX[1]-smoothX[0])),2));
}
}
else if (preWhite==2)
{
for (i=0;i<nSpec;i++)
{
if (specX[i]!=0.0)
specY[i]/=pow(4.0*pow(sin(M_PI*specX[i]*(smoothX[1]-smoothX[0])),2),2);
}
}
if (output==6)
{
for (i=0;i<nSpec;i++)
printf("spectrum: %d %g %g\n",i,specX[i],specY[i]);
exit(1);
}
}
// Return the spectrum
for (i=0;i<nSpec;i++)
{
outX[i] = specX[i];
outY[i] = specY[i];
}
*nout = nSpec-1;
return 0.0;
}
/* PUTBACK: removed TK_fitSine */
void TKfirstDifference(double *x,double *y,int n)
{
int i;
float sy[n];
for (i=0;i<n;i++)
sy[i] = y[i];
for (i=0;i<n;i++)
{
if (i!=0)
y[i] = sy[i]-sy[i-1];
else
y[i] = 0.0;
}
}
/* TK_fitSinusoids attempts to fit a bunch of harmonically related sinusoids to the data. */
void TK_fitSinusoids(double *x,double *y,double *sig,int n,double *outX,double *outY,int *outN)
{
*outN = n/2;
double outE[MAX_OBSN]; // why??
// Here the whitening matrix is just a diagonal
// // weighting matrix. Store diagonal matrix as 1xN
// // so that types match later.
double** weights=malloc_blas(1,n);
for(int k=0; k < n; k++){
weights[0][k] = 1.0 / sig[k];
}
calcSpectraErr(weights,x,y,n,outX,outY,outE,*outN);
}
//GEORGE'S ALGORITHM!!!! I think mine is better. Calculates a weighted Lomb-Scargle periodogram
//void TK_weightLS(double *x,double *y,double *sig,int n,double *outX,double *outY,int *outN)
void TK_weightLS(double *x,double *y,double *sig,int n,double *outX,double *outY,int *outN, double *outY_re, double *outY_im)
{
longdouble s1,s2,s3,s4,s5;
//double recA[MAX_OBSN],recB[MAX_OBSN];
// UNUSED VARIABLE // double pred;
double omega=0.0;
double si,ci;
double a,b;
double omega0;
// UNUSED VARIABLE // double var;
int i,j;
//omega0 = 2.0*M_PI/TKrange_d(x,n);
omega0 = longdouble(2.0)*M_PI/(TKrange_d(x,n) * (double)n / (double)(n-1));
*outN = n/2 - 1;
//USE THIS FOR AN UNWEIGHTED LEAST SQUARES FIT
//printf("IGNORING ERROR BARS --> unweighted LSq Fit in TK_weightLS, all input errors are now equal to 1.0 (even in your own code - this is a side effect!!!\n");
//for (i=0;i<n;i++)
// sig[i]=1.0;
for (j=0;j<*outN;j++)
{
omega = omega0*(j+1); //the DC term will be zero always since we explicitly removed a mean from the input data set in Step 3 above.
s1 = s2 = s3 = s4 = s5 = 0.0;
for (i=0;i<n;i++)
{
si = sin(omega*x[i]);
ci = cos(omega*x[i]);
s1 += (longdouble)(y[i]*si/sig[i]/sig[i]);
s2 += (longdouble)(si*si/sig[i]/sig[i]);
s3 += (longdouble)(si*ci/sig[i]/sig[i]);
s4 += (longdouble)(y[i]*ci/sig[i]/sig[i]);
s5 += (longdouble)ci*ci/sig[i]/sig[i]; //NB!!!!!!!!!!!!!!!! THIS IS NOT TYPECAST PROPERLY!!!! - DY
}
b = (double)((s4-s1/s2)/(s5-s3/s2)); //the real Fourier component (since it has y*cos) George's solution
a = (double)((s1-b*s3)/s2); //the imaginary Fourier component (since it has y*sin) George
//recA[j] = a;
outY_im[j] = a;
//recB[j] = b;
outY_re[j] = b;
outX[j] = omega/2.0/M_PI;
outY[j] = a*a+b*b;
}
}
/* Calculates the discrete Fourier transform of a data-set */
/* Assumes that the x-values are in units of days and the */
/* y-values are in seconds */
/* This code was checked by G. Hobbs - 30/10/08 */
/* DO NOT MODIFY WITHOUT LEAVING COMMENTS HERE */
/* 13th November: DY added capability for retrieval of imaginary part into main code */
void TK_dft(double *x,double *y,int n,double *outX,double *outY,int *outN, double *outY_re, double *outY_im)
{
complexVal spec[n];
// UNUSED VARIABLE // double xo;
// UNUSED VARIABLE // int nfreq;
int i,j;
// UNUSED VARIABLE // double f0;
double range,t,f;
range = TKrange_d(x,n)*(double)n/(double)(n-1);
//nfreq = n/2;
for (i=0;i<n;i++)
outX[i]=1.0/range*(i+1);
for (i=0;i<n;i++)
{
spec[i].real = 0.0;
spec[i].imag = 0.0;
for (j=0;j<n;j++)
{
t = x[j]*86400.0; // In seconds
f = outX[i]/86400.0; // In Hz
spec[i].real+=y[j]*cos(2*M_PI*f*t);
spec[i].imag+=y[j]*sin(2*M_PI*f*t);
}
}
// Form spectrum
for (i=0;i<n;i++)
{
outY_re[i] = spec[i].real;
outY_im[i] = spec[i].imag;
outY[i] = (pow(spec[i].real,2)+pow(spec[i].imag,2));
}
*outN = n/2;
}
void TKaveragePts(double *x,double *y,int n,int width,double *meanX,double *meanY,int *nMean)
{
double max,min;
int i;
meanX[*nMean] = 0.0;
meanY[*nMean] = 0.0;
max = x[0],min=x[0];
for (i=0;i<n;i++)
{
if (max < x[i]) max=x[i];
if (min > x[i]) min=x[i];
meanY[*nMean]+=y[i];
meanX[*nMean]+=x[i];
}
meanY[*nMean]/=(double)n;
meanX[*nMean]/=(double)n;
if (max-min < (double)width)
{
(*nMean)++;
return;
}
else
{
// Find largest gap in the data-points
// printf("Finding largest gap\n");
double gap=-1;
int igap=-1;
for (i=1;i<n;i++)
{
if (gap < fabs(x[i]-x[i-1]))
{
gap = fabs(x[i]-x[i-1]);
igap=i;
}
}
if (igap==-1)
{
printf("Error when averaging points x[0] = %g, x[1] = %g\n",x[0],x[1]);
exit(1);
}
// printf("LEFT SIDE %d %d %g [%g %g]\n",n,igap,gap,x[igap],x[igap-1]);
// Consider left hand side
TKaveragePts(x,y,igap,width,meanX,meanY,nMean);
// Consider right hand side
// printf("RIGHT SIDE %d %d %g [%g %g]\n",n,igap,gap,x[igap],x[igap-1]);
TKaveragePts(x+igap,y+igap,(n-igap),width,meanX,meanY,nMean);
}
}
/* This sorting routine should be replaced by something better in toolkit.h */
void TKsortit(double *x,double *y,int n)
{
int sort=0,i;
double t1,t2;
do {
sort=0;
for (i=0;i<n-1;i++)
{
if (x[i]>x[i+1])
{
sort=1;
t1=x[i];
t2=y[i];
x[i]=x[i+1];
y[i]=y[i+1];
x[i+1] = t1;
y[i+1] = t2;
break;
}
}
} while (sort==1);
}
/* ************************************************************** *
* Smoothing routines: *
* *
* These routines input an irregularly sampled time series *
* and output a smoothed version of the time series *
* *
* boxcar *
* hann - also called raised cosine smoothing *
* *
* ************************************************************** */
/* Boxcar smoothing
* The width of the box-car must be an odd integer
*/
void TKboxcar(double *x,double *y,int n,double *ox,double *oy,int *on,int width)
{
int i,j;
double sy;
int nStore;
*on = 0;
if (width/2.0 == (int)width/2)
logerr("Should use odd number for the width. Used %d",width);
for (i=(width-1)/2;i<n-(width-1)/2;i++)
{
sy = 0.0;
nStore=0;
for (j=i-(width-1)/2;j<i+(width-1)/2;j++)
{
sy += y[j];
nStore++;
}
ox[*on] = x[i];
oy[*on] = sy/(double)nStore;
(*on)++;
}
}
/*
* Hann (or raised cosine) smoother
*/
void TKhann(double *x,double *y,int n,double *ox,double *oy,int *on,int width)
{
int i,j;
double sy;
int nStore;
*on = 0;
for (i=(width-1)/2;i<n-(width-1)/2;i++)
{
sy = 0.0;
nStore=0;
for (j=i-(width-1)/2;j<i+(width-1)/2;j++)
{
sy += 0.5*(1.0-cos(2*M_PI*(j-(i-(width-1)/2))/(double)width))*y[j];
nStore++;
}
ox[*on] = x[i];
// Normalise so that the area under the Hann smoother = 1
oy[*on] = sy/((double)width/2.0);
(*on)++;
}
}
/* ************************************************************** *
* Spline routines *
* ************************************************************** */
#define ABS(x) ((x) < 0 ? -(x) : (x))
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
void TKcmonot (int n, double x[], double y[], double yd[][4])
/*****************************************************************************
compute cubic interpolation coefficients via the Fritsch-Carlson method,
which preserves monotonicity
******************************************************************************
Input:
n number of samples
x array[n] of monotonically increasing or decreasing abscissae
y array[n] of ordinates
Output:
yd array[n][4] of cubic interpolation coefficients (see notes)
******************************************************************************
Notes:
The computed cubic spline coefficients are as follows:
yd[i][0] = y(x[i]) (the value of y at x = x[i])
yd[i][1] = y'(x[i]) (the 1st derivative of y at x = x[i])
yd[i][2] = y''(x[i]) (the 2nd derivative of y at x = x[i])
yd[i][3] = y'''(x[i]) (the 3rd derivative of y at x = x[i])
To evaluate y(x) for x between x[i] and x[i+1] and h = x-x[i],
use the computed coefficients as follows:
y(x) = yd[i][0]+h*(yd[i][1]+h*(yd[i][2]/2.0+h*yd[i][3]/6.0))
The Fritsch-Carlson method yields continuous 1st derivatives, but 2nd
and 3rd derivatives are discontinuous. The method will yield a
monotonic interpolant for monotonic data. 1st derivatives are set
to zero wherever first divided differences change sign.
For more information, see Fritsch, F. N., and Carlson, R. E., 1980,
Monotone piecewise cubic interpolation: SIAM J. Numer. Anal., v. 17,
n. 2, p. 238-246.
Also, see the book by Kahaner, D., Moler, C., and Nash, S., 1989,
Numerical Methods and Software, Prentice Hall. This function was
derived from SUBROUTINE PCHEZ contained on the diskette that comes
with the book.
******************************************************************************
Author: Dave Hale, Colorado School of Mines, 09/30/89
Modified: Dave Hale, Colorado School of Mines, 02/28/91
changed to work for n=1.
Modified: Dave Hale, Colorado School of Mines, 08/04/91
fixed bug in computation of left end derivative
*****************************************************************************/
{
int i;
double h1,h2,del1,del2,dmin,dmax,hsum,hsum3,w1,w2,drat1,drat2,divdf3;
/* copy ordinates into output array */
for (i=0; i<n; i++)
yd[i][0] = y[i];
/* if n=1, then use constant interpolation */
if (n==1) {
yd[0][1] = 0.0;
yd[0][2] = 0.0;
yd[0][3] = 0.0;
return;
/* else, if n=2, then use linear interpolation */
} else if (n==2) {
yd[0][1] = yd[1][1] = (y[1]-y[0])/(x[1]-x[0]);
yd[0][2] = yd[1][2] = 0.0;
yd[0][3] = yd[1][3] = 0.0;
return;
}
/* set left end derivative via shape-preserving 3-point formula */
h1 = x[1]-x[0];
h2 = x[2]-x[1];
hsum = h1+h2;
del1 = (y[1]-y[0])/h1;
del2 = (y[2]-y[1])/h2;
w1 = (h1+hsum)/hsum;
w2 = -h1/hsum;
yd[0][1] = w1*del1+w2*del2;
if (yd[0][1]*del1<=0.0)
yd[0][1] = 0.0;
else if (del1*del2<0.0) {
dmax = 3.0*del1;
if (ABS(yd[0][1])>ABS(dmax)) yd[0][1] = dmax;
}
/* loop over interior points */
for (i=1; i<n-1; i++) {
/* compute intervals and slopes */
h1 = x[i]-x[i-1];
h2 = x[i+1]-x[i];
hsum = h1+h2;
del1 = (y[i]-y[i-1])/h1;
del2 = (y[i+1]-y[i])/h2;
/* if not strictly monotonic, zero derivative */
if (del1*del2<=0.0) {
yd[i][1] = 0.0;
/*
* else, if strictly monotonic, use Butland's formula:
* 3*(h1+h2)*del1*del2
* -------------------------------
* ((2*h1+h2)*del1+(h1+2*h2)*del2)
* computed as follows to avoid roundoff error
*/
} else {
hsum3 = hsum+hsum+hsum;
w1 = (hsum+h1)/hsum3;
w2 = (hsum+h2)/hsum3;
dmin = MIN(ABS(del1),ABS(del2));
dmax = MAX(ABS(del1),ABS(del2));
drat1 = del1/dmax;
drat2 = del2/dmax;
yd[i][1] = dmin/(w1*drat1+w2*drat2);
}
}
/* set right end derivative via shape-preserving 3-point formula */
w1 = -h2/hsum;
w2 = (h2+hsum)/hsum;
yd[n-1][1] = w1*del1+w2*del2;
if (yd[n-1][1]*del2<=0.0)
yd[n-1][1] = 0.0;
else if (del1*del2<0.0) {
dmax = 3.0*del2;
if (ABS(yd[n-1][1])>ABS(dmax)) yd[n-1][1] = dmax;
}
/* compute 2nd and 3rd derivatives of cubic polynomials */
for (i=0; i<n-1; i++) {
h2 = x[i+1]-x[i];
del2 = (y[i+1]-y[i])/h2;
divdf3 = yd[i][1]+yd[i+1][1]-2.0*del2;
yd[i][2] = 2.0*(del2-yd[i][1]-divdf3)/h2;
yd[i][3] = (divdf3/h2)*(6.0/h2);
}
yd[n-1][2] = yd[n-2][2]+(x[n-1]-x[n-2])*yd[n-2][3];
yd[n-1][3] = yd[n-2][3];
}
// Interpolate the spline fit on to a given set of x-values
void TKspline_interpolate(int n,double *x,double *y,double yd[][4],double *interpX,
double *interpY,int nInterp)
{
double h;
int jpos;
int i,j;
//To evaluate y(x) for x between x[i] and x[i+1] and h = x-x[i],
//use the computed coefficients as follows:
//y(x) = yd[i][0]+h*(yd[i][1]+h*(yd[i][2]/2.0+h*yd[i][3]/6.0))
// Assume the data are sorted so x[i] < x[i+1]
for (i=0;i<nInterp;i++)
{
jpos=-1;
for (j=0;j<n-1;j++)
{
if (interpX[i]>=x[j] && interpX[i]<x[j+1])
{
jpos=j;
break;
}
}
if (jpos!=-1)
{
h = interpX[i]-x[jpos];
interpY[i] = yd[jpos][0]+h*(yd[jpos][1]+h*(yd[jpos][2]/2.0+h*yd[jpos][3]/6.0));
}
else
interpY[i] = 0.0;
}
}
void TKlomb_d(double *x,double *y,int n,double ofac,double hifac,double *ox,double *oy,int *outN,double *var)
{
// UNUSED VARIABLE // double store;
double freq0; /* Initial frequency */
int i,j;
// UNUSED VARIABLE // double arg;
double sum1,sum2,sum3,sum4;
// UNUSED VARIABLE // double tau;
double omegaTau;
double aveX;
double ybar;
double alpha[n],beta[n]; /* See equation 5.5.7 */
double theta,omega0;
double cosTau,sinTau,st,ct;
double cosTheta[n],sinTheta[n];
double scale;
double y2;
ybar = TKmean_d(y,n);
*var = TKvariance_d(y,n);
// Use to get the L-S periodogram to give the same results as the DFT
scale = (double)n/(double)(n-1);
// scale = 1;
freq0 = 1.0/(TKrange_d(x,n)*ofac*scale);
aveX = (TKfindMin_d(x,n)+TKfindMax_d(x,n))/2.0;
*outN = (int)(0.5*ofac*hifac*n);
/* Find initial value of cos and sin theta for the trigonometric recurrence */
for (i=0;i<n;i++)
{
omega0 = 2.0*M_PI*freq0;
theta = omega0*(x[i]-aveX);
alpha[i] = -2.0*sin(theta/2.0)*sin(theta/2.0);
sinTheta[i] = beta[i] = sin(theta);
cosTheta[i] = cos(theta);
}
for (j=0;j<*outN;j++)
{
ox[j] = freq0*(j+1);
sum1 = 0.0; sum2 = 0.0;
for (i=0;i<n;i++)
{
st = sinTheta[i];
ct = cosTheta[i];
sum1 += st*ct;
sum2 += (ct-st)*(ct+st);
}
omegaTau = 0.5*atan2(2.0*sum1,sum2);
cosTau = cos(omegaTau);
sinTau = sin(omegaTau);
sum1 = sum2 = sum3 = sum4 = 0.0;
for (i=0;i<n;i++)
{
y2 = y[i]-ybar;
ct = cosTheta[i];
st = sinTheta[i];
sum1 += y2*(ct*cosTau+st*sinTau);
sum2 += y2*(st*cosTau-ct*sinTau);
sum3 += pow((ct*cosTau)+st*sinTau,2);
sum4 += pow((ct*sinTau)-st*cosTau,2);
/* Now update the recurrence relations */
cosTheta[i]+=(alpha[i]*ct-beta[i]*sinTheta[i]);
sinTheta[i]+=(alpha[i]*sinTheta[i]+beta[i]*ct);
}
oy[j] = 0.5/(*var)*(sum1*sum1/sum3 + sum2*sum2/sum4);
}
}
// Fourier transform
// Requires npts = 2**M value - does not check for this
// Routine modified from http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/dft
/*
This computes an in-place complex-to-complex FFT
x and y are the real and imaginary arrays of n = 2^m points.
dir = 1 gives forward transform
dir = -1 gives reverse transform
*/
int TK_fft(short int dir,long n,double *x,double *y)
{
long i,i1,j,k,i2,l,l1,l2;
double c1,c2,tx,ty,t1,t2,u1,u2,z;
int m;
m = (int)(log(n)/log(2)+0.1);
logdbg("m = %d, n = %ld %g %g %g %d\n",m,n,log(n),log(2),log(n)/log(2),(int)(log(n)/log(2)+0.1));
/* Do the bit reversal */
i2 = n >> 1;
j = 0;
// printf("Here\n");
for (i=0;i<n-1;i++) {
// printf("I = %d, n = %d\n",i,n);
if (i < j) {
tx = x[i];
ty = y[i];
x[i] = x[j];
y[i] = y[j];
x[j] = tx;
y[j] = ty;
}
k = i2;
while (k <= j) {
// printf("k = %d %d\n",k,j);
j -= k;
k >>= 1;
}
j += k;
}
// printf("Here 2\n");
/* Compute the FFT */
c1 = -1.0;
c2 = 0.0;
l2 = 1;
for (l=0;l<m;l++) {
l1 = l2;
l2 <<= 1;