SSDOptimizeEDS.cpp 108 KB
Newer Older
Miroslav Shaltev's avatar
Miroslav Shaltev committed
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
/*
 *  Copyright (C) 2012 Miroslav Shaltev.
 *
 *  This program 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.
 *
 *  This program 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 with program; see the file COPYING. If not, write to the
 *  Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 */

/*********************************************************************************/
/** \author Miroslav Shaltev
 * \file
 * \ingroup pulsarApps
 * \brief Semi-coherent search optimization using real data at fixed computing cost
 * This code determines the optimal search parameters for a semi-coherent search,
 * in particular StackSlide, when using real data and at constrained compuing cost.
 * The result of the optimization are the mismatch of the coarse and fine grid,
 * the number of segments and segment duration, as well as a segment list.
 * The optimization of the search parameters is numerical and rely on the
 * NOMAD library. This is the Simple Data Selection (SDS) version.
 *********************************************************************************/
#define MEMORY_DEBUG
#define __STDC_CONSTANT_MACROS
#define LAL_USE_OLD_COMPLEX_STRUCTS
#include <nomad.hpp>

#define	UTSEG segments.second.Tseg
#define UNSEG segments.second.Nseg


#include "SSDOptimizeEDS.h"

using namespace std;

#define TRUE (1==1)
#define FALSE (1==0)


Miroslav Shaltev's avatar
Miroslav Shaltev committed
50
51
#define EARTHEPHEMERIS  "earth00-19-DE405.dat"
#define SUNEPHEMERIS 	"sun00-19-DE405.dat"
Miroslav Shaltev's avatar
Miroslav Shaltev committed
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
#define BLOCKSRNGMED 	101 	/**< Default running median window size */
#define FSTART 		100.0	/**< Default Start search frequency */
#define FBAND           5e-2  /**< Default search band */
#define FDOT            0.0	  /**< Default value of first spindown */
#define DFDOT           0.0	  /**< Default range of first spindown parameter */
#define SKYREGION       "allsky" /**< default sky region to search over -- just a single point*/
#define DTERMS          8    /**< Default number of dirichlet kernel terms for calculating Fstat */

#define F0 50
#define TAU 600
#define GEOF 0.5
#define MAXDIM 6

#define COCC0 7e-8
#define ICCC0 6e-9
#define TOTCC 6

#define SNRTHTYPE 4
#define SNRTHTYPESWITCH 50
#define CONSTSNRTH 40.0
#define PFA 0.01
#define PFD 0.1

#define TCType_FullMetric 0
#define TCType_GCTFreqMetric 1

#define USERNALLSKY 1.0

#define MINFREQ 50.0
#define TAUPROJ 180.0
#define NCPUAVAIL 12000

#define NMIN 2.0
#define NMAX 7.0
#define MMIN 10.0
#define MMAX 20.0

#define SPINUP 0.1

#define LIMITMAXFREQ 2000.

/**< Default number of dirichlet kernel terms for calculating Fstat */
#define FSTATTHRESHOLD 	2.6	/**< Default threshold on Fstatistic for peak selection */
#define NCAND1          10 	/**< Default number of candidates to be followed up from first stage */
#define FNAMEOUT        "./SC.out"  /**< Default output file basename */
#ifndef LAL_INT4_MAX
#define LAL_INT4_MAX 	2147483647
#endif

#define BLOCKSIZE_REALLOC 50

#define TSFT 1800.0

SIGMAth_params empty_SIGMAth_params;

SNRth_params empty_SNRth_params;

SSDOptimize *MSSDOptimize;

#define CALFAC 1.0

class SSDOptimizeEvaluator : public NOMAD::Evaluator {
public:
    SSDOptimizeEvaluator  ( const NOMAD::Parameters & p ):NOMAD::Evaluator ( p ) {}
    ~SSDOptimizeEvaluator ( void ) {}
    bool eval_x( NOMAD::Eval_Point   & x, const NOMAD::Double & h_max, bool & count_eval);
};

bool SSDOptimizeEvaluator::eval_x( NOMAD::Eval_Point   & x, const NOMAD::Double & h_max, bool & count_eval) {
    const CHAR* fn = "SSDOptimizeEvaluator::eval_x";

    if (MSSDOptimize->StartPoint()) {
        x.set_bb_output(0,1);
        MSSDOptimize->StartPoint(FALSE);
        count_eval = TRUE;
        return TRUE;
    }

    if ( x[2].value() * x[3].value() - (MSSDOptimize->MaxEndTimeGPS().gpsSeconds - MSSDOptimize->MinStartTimeGPS().gpsSeconds) > 0 ) {
        /* Tseg * Nseg > Tspan */
        LogPrintf(LOG_DEBUG,"[%s]: Tseg * Nseg > Tspan: %f > %d\n",fn,x[2].value() * x[3].value(),(MSSDOptimize->MaxEndTimeGPS().gpsSeconds - MSSDOptimize->MinStartTimeGPS().gpsSeconds));
        count_eval = FALSE;
        return FALSE;
    }

    if ( abs(MSSDOptimize->segments.second.Tseg - x[2].value()) == 0 && abs(MSSDOptimize->segments.second.Nseg - x[3].value()) == 0 ) {
        LogPrintf(LOG_DEBUG,"[%s]: reuse segments and metric: last used Tseg,Nseg,Nsft: %f,%f,%d ask for %f,%f\n",fn,MSSDOptimize->segments.second.Tseg,MSSDOptimize->segments.second.Nseg,MSSDOptimize->segments.second.Nsft,x[2].value(),x[3].value());
    }
    else {
        MSSDOptimize->segments = MSSDOptimize->MultiMAPtoSegments(MSSDOptimize->SFTMap(),x[2].value(),x[3].value(),MSSDOptimize->Tsft());
//         MSSDOptimize->UsedTseg(x[2].value()); /* UsedTseg() is called in compute_metric (cm) and must be updated BEFORE calling cm!!! */
//         MSSDOptimize->UsedNseg(x[3].value());
        if ((INT4)floor(x[3].value()) != MSSDOptimize->segments.first.size()) {
            /* we could not find NSEG segments */
            LogPrintf(LOG_DEBUG,"[%s]: we could not find NSEG segments\n",fn);
            count_eval = FALSE;
            return FALSE;
        }
        if (MSSDOptimize->AnalyticSpindownMetric()?MSSDOptimize->compute_analytic_metric():MSSDOptimize->compute_metric() < 0) {
            LogPrintf(LOG_DEBUG,"[%s]: error\n",fn);
            count_eval = FALSE;
            return FALSE;
        }
    }

    MSSDOptimize->compute_Nt(x[0].value(),x[1].value());

    if ( ( (MSSDOptimize->Nt.coN - MSSDOptimize->Nt.icN) > 0 ) || ( (MSSDOptimize->Nt.cod - MSSDOptimize->Nt.icd) > 0 ) ) {
        LogPrintf(LOG_DEBUG,"[%s]: coNt > icNt or cod > icd: %f, %f, %d, %d\n",fn,MSSDOptimize->Nt.coN,MSSDOptimize->Nt.icN,MSSDOptimize->Nt.cod,MSSDOptimize->Nt.icd);
        count_eval = FALSE;
        return FALSE;
    }

    if ( ( MSSDOptimize->CC() - MSSDOptimize->totCC() ) > 0  || ( MSSDOptimize->mintotCC() - MSSDOptimize->CC() ) > 0 ) {
        LogPrintf(LOG_DEBUG,"[%s]: CC: %e\ttotCC: %e\n",fn,MSSDOptimize->CC(),MSSDOptimize->totCC());
        count_eval = FALSE;
        return FALSE;
    }

    LogPrintf(LOG_DEBUG,"[%s]: Nt: %f, %f, %d, %d, cost: %e in %e [h], Tseg: %f, Nseg: %f, Nsft: %d\n",fn,MSSDOptimize->Nt.coN,MSSDOptimize->Nt.icN,MSSDOptimize->Nt.cod,MSSDOptimize->Nt.icd,MSSDOptimize->CC(),MSSDOptimize->CC()/HOUR,x[2].value(),x[3].value(),MSSDOptimize->segments.second.Nsft);

    REAL8 hth = MSSDOptimize->get_hnot(x[0].value(),x[1].value(),x[2].value(),x[3].value(),MSSDOptimize->Nt.coN)/MSSDOptimize->CalFac();

    LogPrintf(LOG_DEBUG,"[%s]: Nt: %f, %f, %d, %d, cost: %e in %e [h], Tseg: %f, Nseg: %f, Nsft: %d, hth: %e\n",fn,MSSDOptimize->Nt.coN,MSSDOptimize->Nt.icN,MSSDOptimize->Nt.cod,MSSDOptimize->Nt.icd,MSSDOptimize->CC(),MSSDOptimize->CC()/HOUR,x[2].value(),x[3].value(),MSSDOptimize->segments.second.Nsft,hth);


    x.set_bb_output(0,hth);

    MSSDOptimize->update_solution(hth,x[0].value(),x[1].value(),x[2].value(),x[3].value());

    count_eval = TRUE; // count a black-box evaluation
    return TRUE;       // the evaluation succeeded
}


REAL8 SSDOptimize::get_hnot(REAL8 com,REAL8 icm, REAL8 TSEG, REAL8 NSEG, REAL8 NTEMP) {
    const CHAR* fn = "SSDOptimize::get_hnot";
    LogPrintf(LOG_DEBUG,"[%s]: SNRth: %f\n",fn,SNRth(NSEG,NTEMP));
    return 5./2.*1./sqrt(1 - GeoFactor()*(com + icm))*SNRth(NSEG,NTEMP)*sqrt(NSEG)*sqrt(1./segments.second.totG);
}

REAL8 SSDOptimize::get_output_hnot(REAL8 com,REAL8 icm, REAL8 TSEG, REAL8 NSEG, REAL8 NTEMP, REAL8 use_SNRth) {
    const CHAR* fn = "SSDOptimize::get_output_hnot";
    LogPrintf(LOG_DEBUG,"[%s]: SNRth: %f\n",fn,use_SNRth);
    return 5./2.*1./sqrt(1 - GeoFactor()*(com + icm))*use_SNRth*sqrt(NSEG)*sqrt(1./segments.second.totG);
}


REAL8 SSDOptimize::ana_hth(REAL8 Tseg, REAL8 Sn, REAL8 Ndet, REAL8 avgSNRth, REAL8 gf, REAL8 com, REAL8 icm) {
    LogPrintf(LOG_DEBUG,"SSDOptimize::ana_hth(T: %f, Sn: %e, Ndet: %f, avgSNRth: %f, gf: %f, com: %f, icm: %f)\n", Tseg, Sn, Ndet, avgSNRth, gf, com, icm);
//     return 5./2.*avgSNRth*sqrt(Sn/(2.*Ndet*(1-gf*(com+icm))*T))/MSSDOptimize->CalFac();
    return 5./2.*avgSNRth*sqrt(Sn/(Ndet*(1-gf*(com+icm))*Tseg))/MSSDOptimize->CalFac();
}


SSDOptimize::SSDOptimize(int argc, char* argv[]) {

    /* ---------- Global variables -------------------- */

    /* variables for logging */
    fnamelog=NULL;
    fpLog=NULL;
    logstr=NULL;

    /* ephemeris */
    edat = NULL;

    /* user variables */
    uvar_help = FALSE; 	/* true if -h option is given */
    uvar_log = FALSE; 	/* logging done if true */
    uvar_loglevel = 0;

    uvar_CalFac = CALFAC;

    uvar_f1dot = FDOT; 	/* first spindown value */
    uvar_f1dotBand = 0.0; /* range of first spindown parameter */
    uvar_DataFreq = F0;
    uvar_Freq = FSTART;
    uvar_FreqBand = FBAND;

    uvar_f2dot = 0;
    uvar_f2dotBand = 0;

    uvar_f3dot = 0;
    uvar_f3dotBand = 0;

    uvar_f0 = F0;
    uvar_tau0 = TAU;

    uvar_minStartTime = -1;
    uvar_maxEndTime = -1;

    uvar_refTime = 0;

    uvar_blocksRngMed = BLOCKSRNGMED;

    uvar_segmentList = NULL;	/**< ALTERNATIVE: file containing a pre-computed segment list of tuples (startGPS endGPS duration[h] NumSFTs) */

    uvar_Dterms = DTERMS;
    uvar_SSBprecision = SSBPREC_RELATIVISTIC;
    uvar_sftUpsampling = 1;
    uvar_dopplerMax = 1.05e-4;

    uvar_ephemE = NULL;
    uvar_ephemS = NULL;

    uvar_Alpha = 0;
    uvar_AlphaBand = 0;
    uvar_Delta = 0;
    uvar_DeltaBand = 0;

    uvar_gsl_det = FALSE;

    uvar_fnameout = NULL;
    uvar_DataFiles = NULL;
    uvar_version = 0;

    uvar_SaveNomadStat = FALSE;


    uvar_timeStampsFile = NULL;
    uvar_TSPSDFile = NULL;

    uvar_UseTSPSDFile = FALSE;

    uvar_DumpLoadedSFTs = FALSE;

    uvar_ComputeSpindownBands = FALSE;

    uvar_UseTauAtSearchFrequency = FALSE;

    uvar_GeoFactor = GEOF;

    uvar_maxdim = MAXDIM;

    uvar_EnablePartialSFTs = FALSE;

    uvar_FixedFAP = FALSE;


    uvar_cocc0 = COCC0;
    uvar_iccc0 = ICCC0;
    uvar_totcc = TOTCC;
    uvar_mintotcc = 0.9*TOTCC;

    uvar_SNRthType = SNRTHTYPE;
    uvar_SNRthTypeSwitch = SNRTHTYPESWITCH;
    uvar_ConstSNRth = CONSTSNRTH;
    uvar_pFA = PFA;
    uvar_pFD = PFD;

    if ( (uvar_MetricIFO = XLALCreateStringVector ( "H1", NULL )) == NULL ) {
        LogPrintf (LOG_CRITICAL, "Call to XLALCreateStringVector() failed with xlalErrno = %d\n", xlalErrno );
//     XLAL_ERROR ( "SCSearch constructor", XLAL_ENOMEM );
    }

    inputSFTs = NULL;

    multiPSD = NULL;

    uvar_DirectedSearch = FALSE;

    uvar_UserNallsky = USERNALLSKY;

    uvar_UseNallsky = FALSE;

    uvar_TemplatesCountingType = TCType_FullMetric;

    //     const char *fn = __func__;
    status = blank_status;

    uvar_UseBrakingIndex = FALSE;
    uvar_ComputeJerkIndex = FALSE;

    uvar_GridType = 1;

    uvar_nmin = NMIN;
    uvar_nmax = NMAX;
    uvar_mmin = MMIN;
    uvar_mmax = MMAX;

    uvar_n0 = 2.0;

    uvar_RHPVolume = FALSE;
    uvar_BOXVolume = FALSE;

    uvar_basic_debug = FALSE;
    uvar_debug_check = FALSE;
    uvar_debug_Tseg = 86400;
    uvar_debug_com = 0.5;
    uvar_debug_icm = 0.5;
    uvar_debug_Nseg = 1.0;
    uvar_debug_Nsft = 1;

    sol_hnot = 1e+6;
    sol_com = 0.;
    sol_icm = 0.;
    sol_Tseg = 0.;
    sol_Nseg = 0.;
    sol_refTime = 0.;
    sol_Nsft = 0;

    uvar_Tsft = TSFT;

    cur_refTime = 0.;

    uvar_spinup = SPINUP;

    uvar_CheckDim = FALSE;

    uvar_CheckDimFreqBand = -1;
    uvar_CheckDimf1dotBand = -1;
    uvar_CheckDimf2dotBand = -1;
    uvar_CheckDimf3dotBand = -1;

    uvar_AnalyticSpindownMetric = FALSE;

    uvar_CompareApproximation = FALSE;

    uvar_SimpleThirdSpindown = FALSE;

    /* set log-level */
    uvar_loglevel = lalDebugLevel;
}

SSDOptimize::~SSDOptimize() {}

/** Function that *truncates the PSD in place* to the requested frequency-bin interval [firstBin, lastBin] for the given multiPSDVector.
 */
UINT4 SSDOptimize::XLALCropMultiPSDVector ( MultiPSDVector *multiPSDVect, UINT4 firstBin, UINT4 lastBin)
{
    /* check user input */
    if ( !multiPSDVect ) {
        XLALPrintError ("invalid NULL input 'multiPSDVect'\n");
        XLAL_ERROR ( XLAL_EINVAL );
    }
    if ( lastBin < firstBin ) {
        XLALPrintError ("empty bin interval requested [%d, %d]\n", firstBin, lastBin );
        XLAL_ERROR ( XLAL_EDOM );
    }

    UINT4 numIFOs = multiPSDVect->length;
    UINT4 numBins = multiPSDVect->data[0]->data[0].data->length;

    if ( (firstBin >= numBins) || (lastBin >= numBins ) ) {
        XLALPrintError ("requested bin-interval [%d, %d] outside of PSD bins [0, %d]\n",firstBin, lastBin, 0, numBins - 1 );
        XLAL_ERROR ( XLAL_EDOM );
    }

    /* ----- check if there's anything to do at all? ----- */
    if ( (firstBin == 0)  && (lastBin == numBins - 1) )
        return XLAL_SUCCESS;

    REAL8 f0    = multiPSDVect->data[0]->data[0].f0;
    REAL8 dFreq = multiPSDVect->data[0]->data[0].deltaF;

    Tsft(1./dFreq);

    /* ----- loop over detectors, timestamps, then crop each PSD ----- */
    UINT4 X;
    for ( X=0; X < numIFOs; X ++ )
    {
        PSDVector *thisPSDVect = multiPSDVect->data[X];
        UINT4 numTS   = thisPSDVect->length;

        UINT4 iTS;
        for ( iTS = 0; iTS < numTS; iTS ++ )
        {
            REAL8FrequencySeries *thisPSD = &thisPSDVect->data[iTS];

            if ( numBins != thisPSD->data->length ) {
                XLALPrintError ("inconsistent number of frequency-bins across multiPSDVector: X=%d, iTS=%d: numBins = %d != %d\n",
                                X, iTS, numBins, thisPSD->data->length );
                XLAL_ERROR ( XLAL_EDOM );
            }

            UINT4 numNewBins = lastBin - firstBin + 1;
            /* now do some clever memory-sane cropping on this PSD */
            if ( firstBin > 0 )
            {
                void *dest = thisPSD->data->data;	/* always copy to the beginning of array */
                void *src  = thisPSD->data->data + firstBin;	/* we're copying from firstBin on ... */

                if ( dest != memmove(dest, src, numNewBins * sizeof(*thisPSD->data->data)) ) { /* memmove() handles overlapping memory correctly */
                    XLALPrintError ("something failed in moving PSD data with memmove()\n");
                    XLAL_ERROR ( XLAL_EFAILED );
                }
            }
            /* truncate array to new size */
            thisPSD->data->length = numNewBins;

            /* set correct start-frequency in cropped PSD */
            thisPSD->f0 = f0 + firstBin * dFreq;

        } /* for iTS < numTS */

    } /* for X < numIFOs */

    /* that should be all ... */
    return XLAL_SUCCESS;

} /* XLALCropMultiPSDVector() */


std::multimap<INT4,SFT_t> SSDOptimize::MultiPSDtoSFTmap(MultiPSDVector *multiPSD) {
    std::multimap<INT4,SFT_t> sftmap;

    REAL8 dFreq = multiPSD->data[0]->data[0].deltaF;

// 	NORMALIZE!!! normalize rngmd(power) to get proper *single-sided* PSD: Sn = (2/Tsft) rngmed[|data|^2]]

    REAL8 normPSD = 2.0 * dFreq;

    for ( int d = 0; d < multiPSD->length; d++ )
        for (int t = 0; t < multiPSD->data[d]->length; t++)
        {
            SFT_t thissft;
            thissft.ts = multiPSD->data[d]->data[t].epoch;
            thissft.det = d;
            thissft.psd = normPSD * multiPSD->data[d]->data[t].data->data[0];
            strcpy(thissft.detname,multiPSD->data[d]->data[t].name);
            sftmap.insert(pair<INT4,SFT_t>(thissft.ts.gpsSeconds,thissft));
        }
    return sftmap;
}

bool segsort (SEGMENT_t s1,SEGMENT_t s2) {
    return ((s1.G - s2.G )> 0);
}

bool fastsegsort (FAST_SEGMENT_t s1,FAST_SEGMENT_t s2) {
    return ((s1.G - s2.G )> 0);
}


bool segsortstart (SEGMENT_t s1,SEGMENT_t s2) {
    return ((s2.start - s1.start )> 0);
}

bool fastsegsortstart (FAST_SEGMENT_t s1,FAST_SEGMENT_t s2) {
    return ((s2.start - s1.start )> 0);
}


INT4 SSDOptimize::dump_SFT_list() {
    UINT4 NsftToDump = 0;
    UINT4 NsftSum = 0;

    std::pair<std::vector<SEGMENT_t>,SEGINFO_t>  use_segments = FinalMultiMAPtoSegments(sftmap, sol_Tseg, sol_Nseg, Tsft());

    if (sol_Nsft != use_segments.second.Nsft) {
        LogPrintf(LOG_NORMAL,"Cannot dump segments: expected Nsft: %d, selected Nsft: %d\n",sol_Nsft,use_segments.second.Nsft);
        return -1;
    }

    vector<SEGMENT_t> dumpseg = use_segments.first;
    sort(dumpseg.begin(),dumpseg.end(),segsortstart);

    for (int d = 0; d < Ndet(); d++) {
        std::vector<INT4> usesft;
        bool no_name = TRUE;
        char* detname = (char*)LALCalloc( 32, sizeof(CHAR) );
        for (int s = 0; s < use_segments.first.size(); s++) {
            UINT4 pdNsft = 0;
            if (d == 0) NsftSum += dumpseg.at(s).Nsft;
            INT4 stime = (INT4)dumpseg.at(s).start;
            INT4 etime = (INT4)dumpseg.at(s).end - Tsft();
            for (int tsc = 0; tsc<dumpseg.at(s).ts.size(); tsc++) {
                for (std::multimap<INT4,SFT_t>::iterator it=sftmap.begin(); it!=sftmap.end(); it++) {
                    SFT_t sft = (*it).second;
                    if ( sft.det == d && d == dumpseg.at(s).ts.at(tsc).det && (*it).first == dumpseg.at(s).ts.at(tsc).ts) {
                        usesft.push_back((INT4)sft.ts.gpsSeconds);
                        if (no_name) {
                            sprintf(detname,"%s",sft.detname);
                            no_name = FALSE;
                        }
                        NsftToDump += 1;
                        pdNsft += 1;
// 					printf("Det: %s, Segment: %d, %d, %d, %d, %d, pdNsft: %d\n",detname,s,stime,(INT4)sft.ts.gpsSeconds,(*it).first,etime,pdNsft);
                    }
                }
            }
// 			printf("Det: %s, Segment: %d, Nsft: %d, SegNsft: %d\n",detname,s,pdNsft,dumpseg.at(s).Nsft);
        }
        if ((fpSftList = fopen(SFTlistFile(detname), "wb")) == NULL) {
            LogPrintf(LOG_CRITICAL, "Unable to open file %s for writing\n", SFTlistFile(detname));
// 			LALFree(SFTlistFile());
            /*exit*/
            return(SSDOPTIMIZE_EFILE);
        }
        for (int t = 0; t < usesft.size(); t++) {
            fprintf(fpSftList,"%d 0\n",usesft.at(t));
        }
        fclose(fpSftList);
        LogPrintf(LOG_NORMAL,"Dumped %d %s SFTs for det number: %d.\n",usesft.size(),detname,d);
        usesft.clear();
        LALFree(detname);
    }
//     printf("NsftToDump: %d, Nsft: %d, AAA: %d\n",NsftToDump,sol_segments.second.Nsft,NsftSum);
    return 0;
}

REAL8 SSDOptimize::compute_S(multimap< INT4, SFT_t > sftmap) {
    std::vector<REAL8> Sx;
    for (INT4 d = 0; d < Ndet(); d++) {
        REAL8 invpsd = 0;
        UINT4 nsft = 0;

        for (std::multimap<INT4,SFT_t>::iterator git=sftmap.begin(); git != sftmap.end(); git++) {
            if ((*git).second.det == d) {
                invpsd += 1./(*git).second.psd;
                nsft++;
            }
        }
        Sx.push_back(1./(1./(REAL8)nsft*invpsd));
        printf("det: %d, Sx: %e\n",d,Sx.at(d));
    }
    REAL8 S = 0;
    for (INT4 d = 0; d < Sx.size(); d++) {
        S += 1./Sx.at(d);
    }
    return 1./S;
}

std::pair<std::vector<FAST_SEGMENT_t>,SEGINFO_t> SSDOptimize::MultiMAPtoSegments(std::multimap<INT4,SFT_t> sftmap, REAL8 tseg, INT4 Nseg, REAL8 tsft) {
    UINT4 Tseg = (UINT4)floor(tseg);
    UINT4 Tsft = (UINT4)floor(tsft);
    printf("sftmap.size: %d, Tseg: %d, Nseg: %d, Tsft: %d\n",sftmap.size(),Tseg,Nseg,Tsft);
    std::vector<FAST_SEGMENT_t> segments;
    std::multimap<INT4,SFT_t> lsftmap = sftmap;

//     for ( std::multimap<INT4,SFT_t>::iterator git=lsftmap.begin() ; git != lsftmap.end(); git++ ) {

// 	  printf("CCCC: %d, %d, %e, %d, %s\n",git->first,git->second.ts.gpsSeconds,git->second.psd,git->second.det,git->second.detname);
//     }

    SEGINFO_t seginfo;
    seginfo.totG = 0;
    seginfo.Nsft = 0;
    REAL8 si_G = 0;
    UINT4 si_Nsft = 0;
    while (lsftmap.size() > 0) {
        FAST_SEGMENT_t lsegment;
        REAL8 max_G = 0;
        for ( std::multimap<INT4,SFT_t>::iterator git=lsftmap.begin() ; git != lsftmap.end(); git++ ) {
            UINT4 etime = (*git).first + Tseg - Tsft;
// 			printf("CCCC: %d, %f, Tseg, %d, %d, %e, %d, %s\n",git->first,git->second.ts.gpsSeconds,etime,git->second.psd,git->second.det,git->second.detname);
            REAL8 invpsd = 0;
            REAL8 G = 0;
            FAST_SEGMENT_t seg;
            seg.Nsft = 0;
            std::multimap<INT4,SFT_t>::iterator it;
            for ( it=git ; it != lsftmap.end() && ((*it).first <= etime); it++ ) {
                seg.Nsft += 1;
                invpsd += 1./(*it).second.psd;
//                 seg.ts.push_back((*it).second.ts.gpsSeconds);
                seg.ts.push_back((*it).first);
            }
            seg.G = Tsft*invpsd;
            if (seg.G > max_G) {
                max_G = seg.G;
                seg.start = (*git).first;
//                 seg.end = etime + Tsft;
                seg.end = seg.ts.at(seg.ts.size()-1) + Tsft;
                lsegment = seg;
            }
        }

        segments.push_back(lsegment);


// 		printf("\nSEGMENT: %d\n\n",segments.size()+1);
// 		for (INT4 a = 0; a < segments.at(segments.size()-1).ts.size(); a++){
// 		printf("start: %.0f, end: %.0f, ts: %d\n",segments.at(segments.size()-1).start,segments.at(segments.size()-1).end,segments.at(segments.size()-1).ts.at(a)+Tsft);
// 		}



        si_G += lsegment.G;
        si_Nsft += lsegment.Nsft;
        if (segments.size() >= Nseg ) break;

        if (!EnablePartialSFTs()) {

            BOOLEAN doerase = TRUE;
            while (doerase) {
                multimap<INT4,SFT_t>::iterator mit;

                INT4 mitpos = 0;

                for( mit = lsftmap.begin(); mit != lsftmap.find((INT4)lsegment.ts[0]); mit++ ) {
                    mitpos++;
                }
                mit--;

                REAL8 tsdiff = ((INT4)lsftmap.find((INT4)lsegment.ts[0])->first - (INT4)mit->first)/tsft;
                if (std::distance(lsftmap.begin(),mit) >= 1) {


                    if ( tsdiff > 0 && tsdiff < 1 ) {
                        lsftmap.erase(mit);
                    }
                    else {
                        doerase = FALSE;
                    }
                }
                else {
                    doerase = FALSE;
                }
            }

            INT4 lasttime = (INT4)lsegment.ts[lsegment.ts.size()-1];
            doerase = TRUE;

            while (doerase) {
                multimap<INT4,SFT_t>::iterator mit = lsftmap.find((INT4)lsegment.ts[lsegment.ts.size()-1]);
                mit++;
                if (mit != lsftmap.end()) {
                    if (( (*mit).first - lasttime ) < Tsft ) {
                        lsftmap.erase(mit);
                    }
                    else {
                        doerase = FALSE;
                    }
                }
                else {
                    doerase = FALSE;
                }
            }
        } // end doerase

        for (INT4 i = 0; i < (lsegment.ts.size()); i++) {
            multimap<INT4,SFT_t>::iterator mit = lsftmap.find((INT4)lsegment.ts[i]);
            if (mit != lsftmap.end()) lsftmap.erase(mit);
        }
    }
    sort(segments.begin(),segments.end(),fastsegsort);
    seginfo.totG = si_G;
    seginfo.Nsft = si_Nsft;
    seginfo.Tseg = Tseg;
    seginfo.Nseg = Nseg;
    return make_pair(segments,seginfo);
}

std::pair<std::vector<SEGMENT_t>,SEGINFO_t> SSDOptimize::FinalMultiMAPtoSegments(std::multimap<INT4,SFT_t> sftmap, REAL8 tseg, INT4 Nseg, REAL8 tsft) {
// 	printf("sftmap.size: %d, Tseg: %.32f, Nseg: %d, Tsft: %.32f\n",sftmap.size(),Tseg,Nseg,Tsft);
    UINT4 Tsft = (UINT4)floor(tsft);
    UINT4 Tseg = (UINT4)floor(tseg);
    std::vector<SEGMENT_t> segments;
    std::multimap<INT4,SFT_t> lsftmap = sftmap;
    SEGINFO_t seginfo;
    seginfo.totG = 0;
    seginfo.Nsft = 0;
    REAL8 si_G = 0;
    UINT4 si_Nsft = 0;
    while (lsftmap.size() > 0) {
        SEGMENT_t lsegment;
        REAL8 max_G = 0;
        for ( std::multimap<INT4,SFT_t>::iterator git=lsftmap.begin() ; git != lsftmap.end(); git++ ) {
// 			printf("\nSEGMENT: %d\n\n",segments.size());
            UINT4 etime = (*git).first + Tseg - Tsft;
            REAL8 invpsd = 0;
            REAL8 G = 0;
            SEGMENT_t seg;
            seg.Nsft = 0;
            std::multimap<INT4,SFT_t>::iterator it;
            for ( it=git ; it != lsftmap.end() && ((*it).first <= etime); it++ ) {
// 				printf("start time: %d end time: %d sft: %d\n",(*git).first,etime,(*it).first);
                seg.Nsft += 1;
                invpsd += 1./(*it).second.psd;
                TS_t lts;
                lts.ts = (*it).second.ts.gpsSeconds;
                lts.det = (*it).second.det;
                seg.ts.push_back(lts);
            }
            seg.G = Tsft*invpsd;
            if (seg.G > max_G) {
                max_G = seg.G;
                seg.start = (*git).first;
//                 seg.end = etime + Tsft;
                seg.end = seg.ts.at(seg.ts.size()-1).ts + Tsft;
                lsegment = seg;
            }
        }
        segments.push_back(lsegment);
        si_G += lsegment.G;
        si_Nsft += lsegment.Nsft;
        if (segments.size() >= Nseg ) break;


        if (!EnablePartialSFTs()) {

            BOOLEAN doerase = TRUE;
            while (doerase) {

                multimap<INT4,SFT_t>::iterator mit;

                INT4 mitpos = 0;

                for( mit = lsftmap.begin(); mit != lsftmap.find((INT4)lsegment.ts[0].ts); mit++ ) {
                    mitpos++;
                }
                mit--;

                REAL8 tsdiff = ((INT4)lsftmap.find((INT4)lsegment.ts[0].ts)->first - (INT4)mit->first)/tsft;
                if (std::distance(lsftmap.begin(),mit) >= 1) {


                    if ( tsdiff > 0 && tsdiff < 1 ) {
                        lsftmap.erase(mit);
                    }
                    else {
                        doerase = FALSE;
                    }
                }
                else {
                    doerase = FALSE;
                }
            }

            INT4 lasttime = (INT4)lsegment.ts[lsegment.ts.size()-1].ts;
            doerase = TRUE;

            while (doerase) {
                multimap<INT4,SFT_t>::iterator mit = lsftmap.find((INT4)lsegment.ts[lsegment.ts.size()-1].ts);
                mit++;
                if (mit != lsftmap.end()) {
                    if (( (*mit).first - lasttime ) < Tsft ) {
                        lsftmap.erase(mit);
                    }
                    else {
                        doerase = FALSE;
                    }
                }
                else {
                    doerase = FALSE;
                }
            }

        }

        for (INT4 i = 0; i < (lsegment.ts.size()); i++) {
            multimap<INT4,SFT_t>::iterator mit = lsftmap.find((INT4)lsegment.ts[i].ts);
            if (mit != lsftmap.end()) lsftmap.erase(mit);
        }

//        for (INT4 i = 0; i < (lsegment.ts.size()); i++) {
//             lsftmap.erase(lsftmap.find((INT4)lsegment.ts[i].ts));
//         }

    }
    sort(segments.begin(),segments.end(),segsort);
    seginfo.totG = si_G;
    seginfo.Nsft = si_Nsft;
    seginfo.Tseg = Tseg;
    seginfo.Nseg = Nseg;
    return make_pair(segments,seginfo);
}


std::pair<std::vector<FAST_SEGMENT_t>,SEGINFO_t> SSDOptimize::read_segments_from_file() {
    std::vector<FAST_SEGMENT_t> lsegments;
    SEGINFO_t seginfo;
    seginfo.totG = 1;
    seginfo.Nsft = 0;
    UINT4 si_Nsft = 0;

    INT4 cnt = 0;

    ifstream fin;
    fin.open(segmentList()); // open a file
    if (fin.good()) {
        while (!fin.eof())
        {

            // read an entire line into memory
            char buf[1024];
            fin.getline(buf, 1024);
            int n = 0; // a for-loop index

            // array to store memory addresses of the tokens in buf
            const char* token[4] = {0}; // initialize to 0

            FAST_SEGMENT_t seg;

            token[0] = strtok(buf, " ");

            if (token[0]) {

                token[1] = strtok(0, " ");
                token[2] = strtok(0, " ");
                token[3] = strtok(0, " ");

                seg.start = atof(token[0]);
                seg.end = atof(token[1]);
                REAL8 deltaT = atof(token[2]);
                seg.Nsft = atoi(token[3]);
                si_Nsft +=  seg.Nsft;
                seg.G = 1;
                printf("segment %d: %f %f %f %d\n",cnt,seg.start,seg.end,deltaT,seg.Nsft);
                cnt++;
                lsegments.push_back(seg);
            }
        }
    }
    seginfo.Nsft = si_Nsft;
    return make_pair(lsegments,seginfo);
}

multimap< INT4, SFT_t > SSDOptimize::ReadTSPSDFile() {
    LogPrintf(LOG_NORMAL,"Read TSPSDFile...\n");

    std::multimap<INT4,SFT_t> sftmap;

    INT4 lndet = 0;

    REAL8 lminStartTime=1e+32;
    REAL8 lmaxEndTime=0;

    ifstream fin;
    fin.open(TSPSDFile()); // open a file
    if (fin.good()) {
        while (!fin.eof())
        {

            // read an entire line into memory
            char buf[1024];
            fin.getline(buf, 1024);

            // array to store memory addresses of the tokens in buf
            const char* token[4] = {0}; // initialize to 0

            FAST_SEGMENT_t seg;

            token[0] = strtok(buf, " ");

            SFT_t thissft;
            if (token[0]) {

                token[1] = strtok(0, " ");
                token[2] = strtok(0, " ");
                token[3] = strtok(0, " ");

                XLALGPSSetREAL8(&thissft.ts,atof(token[0]));
                if (thissft.ts.gpsSeconds < lminStartTime) lminStartTime = thissft.ts.gpsSeconds;
                if (thissft.ts.gpsSeconds > lmaxEndTime) lmaxEndTime = thissft.ts.gpsSeconds;
                thissft.det = atoi(token[2]);
                lndet = HSMAX(thissft.det,lndet);
                thissft.psd = atof(token[1]);
                strcpy(thissft.detname,token[3]);
// 				printf("%d %e %d %s\n",thissft.ts.gpsSeconds,thissft.psd,thissft.det,thissft.detname);
                sftmap.insert(pair<INT4,SFT_t>(thissft.ts.gpsSeconds,thissft));
            }
        }
    }

    LIGOTimeGPS t;
    XLALGPSSetREAL8(&t,lminStartTime);
    MinStartTimeGPS(t);
    XLALGPSSetREAL8(&t,lmaxEndTime);
    MaxEndTimeGPS(t);
    Ndet(lndet+1);
    return sftmap;
}

ConfigVariables empty_ConfigVariables;

INT4 SSDOptimize::compute_Nt(REAL8 com, REAL8 icm) {
    const CHAR* fn = "SSDOptimize::compute_Nt";
    BOOLEAN accept = TRUE;
    REAL8 maxcoNt = 0;
    REAL8 maxicNt = 0;
    REAL8 coNt = 0;
    REAL8 icNt = 0;
    INT4 codim = 0;
    INT4 icdim = 0;
    if (TemplatesCountingType() == TCType_FullMetric) {
        for (INT4 d = 1; d < 7; d++) {
            if (d < 3) {
                coNt = thickness(d)*pow(com,-0.5*d)*sqrt(CODet(d-1))*prodBand(0,d);
                icNt = thickness(d)*pow(icm,-0.5*d)*sqrt(ICDet(d-1))*prodBand(0,d);
            }
            else {
                coNt = thickness(d)*pow(com,-0.5*d)*sqrt(CODet(d-1))*prodBand(0,d)*NatToPhysRescale(UTSEG,d);
                icNt = thickness(d)*pow(icm,-0.5*d)*sqrt(ICDet(d-1))*prodBand(0,d)*NatToPhysRescale(UTSEG,d);
            }
            LogPrintf(LOG_DEBUG,"[%s]:TCType_FullMetric coNt: %f\n",fn,coNt);
            if ((coNt - maxcoNt) > 0) {
                maxcoNt = coNt;
                codim = d;
            }
            LogPrintf(LOG_DEBUG,"[%s]:TCType_FullMetric icNt: %f\n",fn,icNt);
            if ((icNt - maxicNt) > 0) {
                maxicNt = icNt;
                icdim = d;
            }
        }
    }
    else if (TemplatesCountingType() == TCType_GCTFreqMetric) {
        for (INT4 d = 1; d < 5; d++) {
            REAL8 lNsky = 0.0;
            if (DirectedSearch()) {
                if (UseNallsky()) {
                    lNsky = UserNallsky();
                    LogPrintf(LOG_DEBUG,"[%s]: TCType_GCTFreqMetric + DirectedSearch() + UserNallsky() lNsky: %f\n",fn,lNsky);
                }
                else {
                    lNsky = 1.0;
                    LogPrintf(LOG_DEBUG,"[%s]: TCType_GCTFreqMetric + DirectedSearch() lNsky: %f\n",fn,lNsky);
                }
            }
            else {
                if (UseNallsky()) {
                    lNsky = UserNallsky()*prodBand(0,2)/(4*PI);
                    LogPrintf(LOG_DEBUG,"[%s]: TCType_GCTFreqMetric UseNallsky() lNsky: %f\n",fn,lNsky);
                }
                else {
                    lNsky = Nsky(com, Freq(), AlphaBand(), DeltaBand(), Delta());
                    LogPrintf(LOG_DEBUG,"[%s]: TCType_GCTFreqMetric lNsky: %f\n",fn,lNsky);
                }
            }
            lNsky = MAX(1,(unsigned long long)round(lNsky));

            REAL8 Vl = 0;

            if (UseBrakingIndex()) {
                if (RHPVolume()) {
                    Vl = rhpvolume(d,Freq(),Freq()+FreqBand());
                }
                else if (SimpleThirdSpindown()) {
                    Vl = brkvolumeCasA(d);
                }
                else {
                    Vl = brkvolume(d);
                }
            }
            else {
//                  Vl = prodBand(2,d+2);
                if (BOXVolume()) {
                    Vl = boxvolume(d);
                }
                else {
                    Vl = smpvolume(d,Freq(),Freq()+FreqBand());
                }
// 				   Vl = prodA(d)/(d+1.)*(pow(Freq()+FreqBand(),d)-pow(Freq(),d));
            }
            coNt = lNsky*thickness(d)*pow(com,-0.5*d)*sqrt(CODet(d-1))*Vl*NatToPhysRescale(UTSEG,d);
            LogPrintf(LOG_DEBUG,"[%s]: thickness(%i): %f, Vl: %e, Tseg: %f, rescale: %e sqrt(det):%e\tcoNt: %e\n",fn,d,thickness(d),Vl,UTSEG,NatToPhysRescale(UTSEG,d),sqrt(CODet(d-1)),coNt);