fringeV6.cc 89.8 KB
Newer Older
1 2
#include <iostream>
#include <math.h> //floor in xastropack
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
3
#include <cmath>
4 5 6 7 8 9 10 11 12 13 14 15
//Sophya
#include "sopnamsp.h"
#include "machdefs.h"
#include "pexceptions.h"
#include "generalfunc.h"
#include "generalfit.h"
#include "timestamp.h"
#include "fioarr.h"
#include "datatable.h" 
#include "tarrinit.h"
#include "ppersist.h"
#include "matharr.h"
16
#include "datime.h"
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


//astrop
#include "xastropack.h"
#include "vector3d.h" 


#undef SOPHYAFIT
#define MINUITFIT

#ifdef MINUITFIT
//Minuit
#include "Math/MinimizerOptions.h"
#include "Minuit2/FCNBase.h"
#include "Minuit2/FunctionMinimum.h"
#include "Minuit2/MnUserParameterState.h"
#include "Minuit2/MnPrint.h"
#include "Minuit2/MnMigrad.h"
#include "Minuit2/MnMinimize.h"
#include "Minuit2/MnMinos.h"
#include "Minuit2/MnContours.h"
#include "Minuit2/MnPlot.h"
#include "Minuit2/MinosError.h"
#include "Minuit2/ContoursError.h"

using namespace ROOT::Minuit2;
#endif

//type of fit parameter container
typedef pair<string, int> PairFit_t;       //Name <-> Index
typedef vector< PairFit_t > ParFitCont_t;
typedef ParFitCont_t::iterator ParFit_Iter;
typedef ParFitCont_t::const_iterator ParFit_CstIter;


//201: pour extraire le fit a une frequence, 301: pour en plus debbuger
53
#define DEBUG_THRESH 0
54 55 56 57 58 59 60 61 62 63 64 65
#if  DEBUG_THRESH > 200
bool firstDBG = true;
int  nloop = 0;
#endif


//alternative 1: GAUSS_BEAM or 2: BESSEL_BEAM
#define TYPE_BEAM 1

//1 = partie reelle des cross, ou 0 partie imaginaire
#define PARTIE_REELLE 1

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
66

67
//nbre of polar per dish: 1 => default H-type, 2 => V-type
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
68 69
//FAIT A LA COMILATION via -DTYPE_POLAR=1 ou 2 (JEC 19/7/18)
//#define TYPE_POLAR 
70 71

//1= in fitAllCross fixed the position of the dishes, 0 no fixing
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
72
#define POSXYZ_FIXED 1
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
73 74

//JEC 20/7/18 auto-corr azimut contraint >0 (en general non => 0)
75
#define AZIMUT_FIXED 0
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
76 77


78 79 80 81 82

//the HA in [-HATHRESHOLD, +HATHRESHOLD] are used to estimate some initial parameters
#define HATHRESHOLD 4.


Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
83 84 85 86
#define XSTR(x) STR(x)
#define STR(x) #x
#pragma message "The value of AZIMUT_FIXED: " XSTR(AZIMUT_FIXED)

87
//-------- Utility
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
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
//------------------------
//---- MEDIAN : warning the nth_element reorder the input vector => input NO MORE VALID
//------------------------

//Warning; original order is not preserved
class median_of_empty_list_exception:public std::exception{
    virtual const char* what() const throw() {
    return "Attempt to take the median of an empty list of numbers.  "
      "The median of an empty list is undefined.";
  }
};
template<class RandAccessIter>
double median(RandAccessIter begin, RandAccessIter end) {
  if(begin == end){ throw median_of_empty_list_exception(); }  
  std::size_t size = end - begin;
  std::size_t middleIdx = size/2;
  RandAccessIter target = begin + middleIdx;
  std::nth_element(begin, target, end);
    
  if(size % 2 != 0){ //Odd number of elements
    return *target;
  }else{            //Even number of elements
    double a = *target;
    RandAccessIter targetNeighbor= target-1;
    std::nth_element(begin, targetNeighbor, end);
    return (a+*targetNeighbor)/2.0;
  }
}

template<class T>
T median(const vector<T>& vec){
  vector<T>tmp(vec);
  return median(tmp.begin(),tmp.end());
}

template<class T>
T median(TVector<T>& vec){
  vector<T>tmp(vec.ConvertTostdvec());
  return median(tmp.begin(),tmp.end());
}


//interquartile range normalized to Gauss(0,1) => sigma estimator
//The sigma on  iQRNorm is 1.16639*iQRNorm/sqrt(n) in case of gaussian random variable.
//warning median does not preserve original order
template<class RandAccessIter>
double iQRNorm(RandAccessIter begin, RandAccessIter end) {
  if(begin == end){ throw median_of_empty_list_exception(); }

  vector<r_4> tmp1(begin,end);
  sort(tmp1.begin(),tmp1.end());
  vector<r_4> tmp3(tmp1);
  std::size_t size = tmp1.end() - tmp1.begin();
  std::size_t middleIdx = size/2;
  double q1 = median(tmp1.begin(), tmp1.begin()+middleIdx);
  double q3 = median(tmp3.begin()+middleIdx,tmp3.end());
  return (q3-q1)/1.34898; //normalisation by Q3-Q1 for a Gauss(0,1) value
}


template <class T>
T iQRNorm(TVector<T>& vec){
  vector<T>tmp(vec.ConvertTostdvec());
  return iQRNorm(tmp.begin(),tmp.end());
}

template <class T>
T iQRNorm(const vector<T>& vec){
  vector<T>tmp(vec);
  return iQRNorm(tmp.begin(),tmp.end());
}




//input : vecin
//input : nbre de bins sur lesquels est calcule la mediane des vecin[i]
//output: vecout
template<class T>
void medianReduct(int NpackBin, TVector<T>& vecin, vector<T>& vecout){

  for (int ibin=0;ibin<vecout.size();ibin++){
    sa_size_t ilow = ibin*NpackBin;
    sa_size_t ihigh = ilow + NpackBin-1;
    TVector<r_8> tmp(vecin(Range(ilow,ihigh)),false); //no data sharing for the time beeing
    vecout[ibin] =  median(tmp);
  }

}


template <class T>
T my_remainder(T x) {
  return std::remainder(x,(T)2*M_PI);
}

template <class T>
void Modulo(TMatrix<T> mtx){
  MathArray<T>::ApplyFunctionInPlace(mtx,my_remainder);
}

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

r_8 FreqToWave(r_8 freq){ 
  //21.1061140542 cm <-> 1420405751.7667 Hz
  return 0.211061140542*(1420.4057517667/freq); // "c/nu" a 1420,4MHz = 21cm
}


template <class T>
size_t closest(std::vector<T> const& vec, T value) {
  typename std::vector<T>::const_iterator it = std::lower_bound(vec.begin(), vec.end(), value);
 if (it == vec.end()) { return -1; }
 return it-vec.begin();
}


sa_size_t Freq2Bin(r_4 freq, r_4 f0, r_4 width, sa_size_t nCha){
  return (sa_size_t)floor((freq-f0)*nCha/width);
}//Freq2Bin
r_4 Bin2Freq(sa_size_t ibin, r_4 f0, r_4 width, sa_size_t nCha){
  return f0+width/nCha*ibin;
}



template <class T>
std::string Num2String(T val){
  std::stringstream ss; ss<<val;
  return ss.str();
}

inline bool StrIsA(const std::string& str, const std::string& type, std::string& trail) {
  bool rc = str.compare(0,type.size(),type) == 0 ? true : false;
  if(rc) {
    trail = str.substr(type.size());
  }
  return rc;
}

void DumpMinuitParam(const MnUserParameters& upar) {
  int pr = cout.precision();
#define PRECISION 13
#define WIDTH     12

  for(std::vector<MinuitParameter>::const_iterator ipar = upar.Parameters().begin(); 
      ipar != upar.Parameters().end(); ipar++) {
	
    cout << std::setw(4) << (*ipar).Number() << std::setw(5) << "||"; 
    cout << std::setw(10) << (*ipar).Name()   << std::setw(3) << "||";
    if((*ipar).IsConst()) {
      cout << "  const  ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << (*ipar).Value() << " ||" << std::endl;
    } else if((*ipar).IsFixed()) {
      cout << "  fixed  ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << (*ipar).Value() << " ||" << std::endl;
    } else if((*ipar).HasLimits()) {
      if((*ipar).Error() > 0.) {
	cout << " limited ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << (*ipar).Value();
	cout << " || " << std::setw(12) << (*ipar).Error() << " ||";
	cout << " [" << ((*ipar).HasLowerLimit()?Num2String((*ipar).LowerLimit()):" - ") 
	     << ", " << ( (*ipar).HasUpperLimit()?Num2String((*ipar).UpperLimit()):" - ") << "]" << std::endl;
      } else
	cout << "  free   ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << (*ipar).Value() 
	     << " || " << std::setw(12) << "no" << std::endl;
    } else {
      if((*ipar).Error() > 0.)
	cout << "  free   ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << (*ipar).Value() 
	     << " || " << std::setw(12) << (*ipar).Error() << std::endl;
      else
	cout << "  free   ||" << std::setprecision(PRECISION) << std::setw(WIDTH) << (*ipar).Value() 
	     << " || " << std::setw(12) << "no" << std::endl;
    }
      
  }//loop on parameter
  cout << std::endl;
  cout.precision(pr);
#undef PRECISION
#undef WIDTH

  
}


//------------------------ global parameters passed to all functions --------------------
struct PARAM {
  int debug;
  string inputDir;
  string inputParamDir;
  string inputFile;
  string inputParamFile;

  string outputDir;
  string outputFile;

  string ouputFile;

  string source;

  r_4 FreqCentre;
  r_4 FreqBand;
  r_4 FreqMin;
  r_4 FreqMax;

  r_8 raSrcHour;
  r_8 raSrcMin;
  r_8 raSrcSec;

  r_8 decSrcDeg;
  r_8 decSrcMin;
  r_8 decSrcSec;

  TimeStamp MeridianDate; //passage au meridien de la source
298
  TimeStamp ReferenceDate; //JEC 18/2/19 reference des temps pour TimeVec
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

  Now LocalGeoTime; 
  int year0;
  int month0;
  int iday0;

  r_4 hourAngleMin; //to select "time interval" arround transit (here hour angle)
  r_4 hourAngleMax;
  
  string Type;

} param ; 

//--------------------------------- BEAM CLASS -----------------------------------
/*
  Dish single Beam as function of the current position (hour angle) of the source

  normalization      Par[0]
  Effective diameter Par[1]
  Azimuthshift       Par[2]
*/
#define NBEAMPARAM 3

class Beam : public GeneralFunction {

public:
  Beam(r_8 waveL, r_8 raSrc,  r_8 decSrc, const Now& np, int nPar=NBEAMPARAM);
  virtual ~Beam() {}
  
  virtual r_8 Value(r_8 const xp[], r_8 const* Par);

  static int NbreParam() { return NBEAMPARAM; }

private:

  int  nPar_;

  r_8  waveL_; //the current wave length
  
  r_8 raSrc_;  //the true ra-dec of the source
  r_8 decSrc_;

  Now np_;     //the observatory vector parameter

  Vector3d nPara0_; //the ideal pointing direction
};

Beam::Beam(r_8 waveL, r_8 raSrc,  r_8 decSrc, const Now& np, int nPar): 
  GeneralFunction(1,nPar),
  nPar_(nPar),
  waveL_(waveL),
  raSrc_(raSrc),
  decSrc_(decSrc),
  np_(np) {
  
  //position nominale des parabolles ideale
355 356
  //JEC 13/6/18 BUG  r_8 l0 = -sin(decSrc - np.n_lat);
  r_8 l0 = sin(decSrc - np.n_lat);
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
  r_8 m0 = 0.;
  r_8 n0 = cos(decSrc - np.n_lat);
  
  nPara0_.Setxyz(l0,m0,n0);

}//Ctor

r_8 Beam::Value(r_8 const xp[], r_8 const* Par) {

  r_8 l0 = nPara0_.X(); r_8 m0 = nPara0_.Y(); r_8 n0 = nPara0_.Z();
  
  r_8 azRad = Angle(Par[2], Angle::Degree).ToRadian();
  
  r_8 l1 = cos(azRad)*l0 - sin(azRad)*m0;
  r_8 m1 = sin(azRad)*l0 + cos(azRad)*m0;
  r_8 n1 = n0;
  Vector3d nPara; nPara.Setxyz(l1,m1,n1);
  
  
  r_8 ha = xp[0]; // l'angle horaire de la source (LST - RA_source)

  //cos directeur de la direction de la source dans le repere horizontal
379 380
  //JEC 13/6/18 BUG   r_8 ls = cos(decSrc_)*cos(ha)*sin(np_.n_lat)-sin(decSrc_)*cos(np_.n_lat);
  r_8 ls = -cos(decSrc_)*cos(ha)*sin(np_.n_lat)+sin(decSrc_)*cos(np_.n_lat);
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  r_8 ms = cos(decSrc_)*sin(ha);
  r_8 ns = sin(np_.n_lat)*sin(decSrc_)+ cos(np_.n_lat)*cos(decSrc_)*cos(ha);
  Vector3d nStar(ls,ms,ns);

  //sin(theta) angle entre ns et n0
  r_8 sintheta = (nStar.vecprod(nPara)).Norm(); //JEc 30/5/16 nPar_ -> nPar car on le change (se referer a nPar0_ pour la position nominale)
  //variable reduite du beam
  r_8 x = M_PI * Par[1]/waveL_ * sintheta;
  
  //Beam  formula

  r_8 lob;
  if(fabs(x)>6) {
    lob=0;
  } else {

#if TYPE_BEAM == 1
398 399
    //BUG JEC 20/9/19  the magic coeff was determined on spherical_bessel fonction and not the Bessel function  lob = exp(-0.220544*x*x); //gaussian equivalent of J1 formula normalise a 1
    lob = exp(-0.280092*x*x); //gaussian equivalent of J1 formula normalise a 1
400 401 402 403
#else
    if(x==0.) {
      lob = 1.;
    } else {
404
      lob = 2. * boost::math::bessel_j(1, x)/x;
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
      lob *= lob; 
    }
#endif
  }

  return Par[0]*lob;

}//Beam::Value


//--------------------------------- AutoCorr  CLASS --------------------
/*
  Single auto corr 
  normalization      Par[0]
  Effective diameter Par[1]
  Azimuthshift       Par[2]
  Cte terme          Par[3]
  Slope terme        Par[4]

*/
#define NAUTOPARAM 5
class AutoCorr : public GeneralFunction {
public:
  //Ctor
  AutoCorr(r_8 waveL, r_8 raSrc,  r_8 decSrc, const Now& np, int nPar=NAUTOPARAM);
  //Dtor
  virtual ~AutoCorr() {}
  
  virtual r_8 Value(r_8 const xp[], r_8 const* Par);

  static size_t NbreParam() { return NAUTOPARAM;}
  
  void SetDebug() {debug_=true;}
  void UnSetDebug() {debug_=false;}


private:

  Beam b1_;   //Effective beam single dish

  int nPar_;  //number of internal parameters

  r_8 waveL_; //the current wave length
  r_8 raSrc_; //the true ra-dec of the source
  r_8 decSrc_;

  Now np_;    //the observatory vector parameter

  bool debug_; //TMP

  Vector3d nPara0_; //the ideal pointing direction  

};

AutoCorr::AutoCorr(r_8 waveL, r_8 raSrc,  r_8 decSrc, const Now& np, int nPar): 
  GeneralFunction(1,nPar),
  b1_(waveL,raSrc,decSrc,np),
  nPar_(nPar),
  waveL_(waveL),
  raSrc_(raSrc),
  decSrc_(decSrc),
  np_(np),
  debug_(false){
}//Ctor

r_8 AutoCorr::Value(r_8 const xp[], r_8 const* Par) {

  //extract effective parameters of the 2 dishes
  int Npar4Beam = Beam::NbreParam();
  r_8 pB[Npar4Beam];
  for(int i=0;i<Npar4Beam;i++){
    pB[i] = Par[i];  
  }
  r_8 beam1 = b1_.Value(xp,pB);  //|B_1(x)|^2
  
  if(debug_)cout << "beam1: " << beam1 << endl;  
  
  r_8 result =  beam1;

  //add a linear baseline NEW 8/11/17
  int off7 = Npar4Beam;
  result += Par[off7] + xp[0]*Par[off7+1];
  
  if(debug_)cout << " res: " << result << endl;

  return result;

}//AutoCorr::Value


//--------------------------------- Cross CLASS --------------------
/*
  2-Dishes cross correlation as function of the current position (hour angle) of the source

  Dish 1
  normalization      Par[0]
  Effective diameter Par[1]
  Azimuthshift       Par[2]

  Dish 2
  normalization      Par[3]
  Effective diameter Par[4]
  Azimuthshift       Par[5]

  LSN baseline       Par[6]
  LEW baseline       Par[7]
  Cte terme          Par[8]
  Phase difference   Par[9]

  LVERT              Par[10]


*/

#define NCROSSPARAM 11

class Cross : public GeneralFunction {
public:
  //Ctor
  Cross(r_8 waveL, r_8 raSrc,  r_8 decSrc, const Now& np, int nPar=NCROSSPARAM);
  //Dtor
  virtual ~Cross() {}
  
  virtual r_8 Value(r_8 const xp[], r_8 const* Par);

  static size_t NbreParam() { return NCROSSPARAM;}
  
  void SetDebug() {debug_=true;}
  void UnSetDebug() {debug_=false;}


private:

  Beam b1_;   //Effective beam single dish

  int nPar_;  //number of internal parameters

  r_8 waveL_; //the current wave length
  r_8 raSrc_; //the true ra-dec of the source
  r_8 decSrc_;

  Now np_;    //the observatory vector parameter

  bool debug_; //TMP

  Vector3d nPara0_; //the ideal pointing direction


};

Cross::Cross(r_8 waveL, r_8 raSrc,  r_8 decSrc, const Now& np, int nPar): 
  GeneralFunction(1,nPar),
  b1_(waveL,raSrc,decSrc,np),
  nPar_(nPar),
  waveL_(waveL),
  raSrc_(raSrc),
  decSrc_(decSrc),
  np_(np),
  debug_(false){
}//Ctor

r_8 Cross::Value(r_8 const xp[], r_8 const* Par) {

  if(debug_){
    cout <<  "x= " << xp[0] << "\n";
    for(int i=0; i<Cross::NbreParam(); i++){
      cout << " p["<<i<<"]: " << Par[i];
    }
    cout << endl;
  }


  //extract effective parameters of the 2 dishes
  int Npar4Beam = Beam::NbreParam();
  r_8 pB[Npar4Beam];
  for(int i=0;i<Npar4Beam;i++){
    pB[i] = Par[i];  
  }
  r_8 beam1 = b1_.Value(xp,pB);  //|B_1(x)|^2
  
  for(int i=0;i<Npar4Beam;i++) {
    pB[i] = Par[i+Npar4Beam];  
  }
  r_8 beam2 = b1_.Value(xp,pB);  //|B_2(x)|^2

  r_8 beam12 = sqrt(beam1 * beam2); //geometric mean of the two beams

  if(debug_)cout << "beam1,2,12: " << beam1 << " " << beam2 << " " << beam12 << endl;  


  r_8 ha = xp[0]; // l'angle horaire de la source (LST - RA_source)
   
  //cos directeur de la direction de la source dans le repere horizontal
598 599
  //JEC 13/6/18 BUG  r_8 ls = cos(decSrc_)*cos(ha)*sin(np_.n_lat)-sin(decSrc_)*cos(np_.n_lat);
  r_8 ls = -cos(decSrc_)*cos(ha)*sin(np_.n_lat)+sin(decSrc_)*cos(np_.n_lat);
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
  r_8 ms = cos(decSrc_)*sin(ha);
  r_8 ns = sin(np_.n_lat)*sin(decSrc_)+ cos(np_.n_lat)*cos(decSrc_)*cos(ha);
  Vector3d nStar(ls,ms,ns);
  
  //phase
  int off7 = 2*Npar4Beam;
  r_8 LSN = Par[off7];
  r_8 LEW = Par[off7+1];
  r_8 LVERT = Par[off7+4];   //<---------------NEW
  Vector3d Dx(LSN, LEW, LVERT); 


  r_8 phase = -2*M_PI/waveL_ * nStar.Psc(Dx);

  phase += Par[off7+3];  //addition phase difference
  
  r_8 result = 0;

#if PARTIE_REELLE >=1
  result +=  beam12*cos(phase);
#else
  result +=  beam12*sin(phase);
#endif

  //add a possible constante baseline
  result += Par[off7+2];
  
  if(debug_)cout << " res: " << result << endl;

  return result;

}//Cross::Value


//--------------------------------- MINUIT Chi2 CLASS --------------------
// class to be used by Minuit
// Simple chi^2 = Sum_i [(y_i - f(x_i))/sigma_i]^2
class AutoCorrChi2 : public FCNBase {
public:
  
  AutoCorrChi2(GeneralFunction* func, GeneralFitData* data): func_(func), errDef_(1.) {
    npts_ = data->NData();
    for(size_t i=0;i<npts_;i++){
      x_.push_back(data->X1(i));
      y_.push_back(data->Val(i));
      erry_.push_back(data->EVal(i));
      bool flag = data->IsValid(i) == 1 ? true: false;
      valid_.push_back(flag);
    }
  }
	 

  //Dtor
  virtual ~AutoCorrChi2() {}
  

  //Specialization of the baseclass
  virtual r_8 operator() (const vector< r_8 > &par) const { 

    r_8 chi2 =0.;

    for (size_t i=0;i<npts_;i++){
      if(valid_[i]) {

	r_8 xp[1]; xp[0] = x_[i];

	r_8 val = (func_->Value(xp, par.data()) - y_[i])/erry_[i];
	chi2 += val*val;
					  
      }
    }
    
    return chi2;
  }

  virtual r_8 Up() const { return errDef_;}
  
private:
  
  size_t npts_; //nbre of points in the fit
  GeneralFunction* func_;  //function to fit
  vector<r_8> x_;          //position values
  vector<r_8> y_;          //measurements
  vector<r_8> erry_;       //error on measurements
  vector<bool> valid_;     // if the measurement is valid or not
  r_8 errDef_;             // 1: 1-sigma Chi2, n*n for n-sigma errors
}; //AutoCorrChi2

// Chi2 for the entire set of Cross Correlations of type H-H and V-V
class TotCrossChi2 : public FCNBase {
public:
  TotCrossChi2(GeneralFunction* func, 
	       vector<GeneralFitData>& vecData, 
	       int nCross,
	       int nDish,
	       vector< pair<int, int> >& crossPair,
	       vector<string>& crossName,
	       vector<string>& polarName,
	       ParFitCont_t& paramIds
	       ):  
    func_(func),
    vecData_(vecData),
    nCrossSet_(nCross),
    Ndish_(nDish),
    crossPair_(crossPair),
    crossName_(crossName),
    polarName_(polarName),
    paramIds_(paramIds),
    errDef_(1.) {

    
    if(vecData_.size() != (size_t)nCross)
      throw ParmError("TotCrossChi2: size missmatched");
    
  }
  virtual ~TotCrossChi2() {}
  
  //Class Predicat needed for C++ version < C++11
  class CtePredicat: public std::unary_function<string,bool> {
  public:
    CtePredicat(string str): str_(str) {}
    bool operator() (const PairFit_t& element) {return element.first == str_;}
  private:
    string str_;
  };

  class Predicat: public std::unary_function<string,bool> {
  public:
    Predicat(string str): str_(str) {}
    bool operator() (PairFit_t& element) {return element.first == str_;}
  private:
    string str_;
  };

  ParFit_CstIter Find(string str) const {
//C++11 version     return find_if(paramIds_.cbegin(), paramIds_.cend(), 
// 		   [&str](const PairFit_t& element){ return element.first == str;} );
    
    return find_if(paramIds_.begin(), paramIds_.end(),CtePredicat(str));

  }//Find const


  ParFit_Iter Find(string str) {
//C++11 version     return find_if(paramIds_.begin(), paramIds_.end(), 
// 		   [&str](PairFit_t& element){ return element.first == str;} );
    return find_if(paramIds_.begin(), paramIds_.end(),Predicat(str));
  }//Find

  //utility function to extract the parameters of a specific cross
  template<class T>
  void GetCrossParm(int iCross, TVector<T>& parTot, vector<T>& parCross)  const {
    vector<T> stdParTot = parTot.ConvertTostdvec();
    GetCrossParm(iCross,stdParTot,parCross);
  }//GetCrossParm

  template<class T>
  void GetCrossParm(int iCross, const vector<T>& parTot, vector<T>& parCross)  const {

    if(parCross.size() != Cross::NbreParam()) 
      throw ParmError("GetCrossParm: size missmatch: ie # of param for a single cross");

    string xName = crossName_[iCross];

    bool debug=false;
#if  DEBUG_THRESH > 200
    debug=true;
#endif

    //select the set of parameters to pass to the cross function
    
    //pseudo Beam parameters 
    //use find algo as map[] operator return a reference but here we are in a "const" function
    //in C++11 an alternative would be to use map.at operator
    

    int iPol = crossPair_[iCross].first; //warning 0-indexed
    int jPol = crossPair_[iCross].second;
    
    int iDish = iPol%Ndish_ + 1;         // 1-indexed dish number
    int jDish = jPol%Ndish_ + 1;         

    string iStr = Num2String(iDish);
    string jStr = Num2String(jDish);

    parCross[0] = parTot[Find("NormCross" + iStr)->second];
    parCross[1] = parTot[Find("Deff" + iStr)->second];
    parCross[2] = parTot[Find("Az"   + iStr)->second];
    parCross[3] = parTot[Find("NormCross" + jStr)->second];
    parCross[4] = parTot[Find("Deff" + jStr)->second];
    parCross[5] = parTot[Find("Az"   + jStr)->second];
    

#if  DEBUG_THRESH > 400

    if(debug) {
      cout << "Debug" << xName << "....." << endl;
      cout << "Cross pair = (" << iPol << ", " << jPol << ")" << endl;
      cout << "Dish  pair 1-index = (" << iStr << ", " << jStr << ")" << endl;   
      cout << ("NormCross" + iStr)<< " <=> "  << Find("NormCross" + iStr)->second << endl;
      cout << ("Deff" + iStr)<< " <=> "  << Find("Deff" + iStr)->second << endl;
      cout << ("Az" + iStr)<< " <=> "  << Find("Az" + iStr)->second << endl;

      cout << ("NormCross" + jStr)<< " <=> "  << Find("NormCross" + jStr)->second << endl;
      cout << ("Deff" + jStr)<< " <=> "  << Find("Deff" + jStr)->second << endl;
      cout << ("Az" + jStr)<< " <=> "  << Find("Az" + jStr)->second << endl;

      cout << "NormCross" << iStr << " = " <<  parCross[0] << " "
	   << "Deff = " <<  parCross[1] << " "
	   << "Az   = " <<  parCross[2] << endl;
      cout << "NormCross" << jStr << " = "  <<  parCross[3] << " "
	   << "Deff = " <<  parCross[4] << " "
	   << "Az   = " <<  parCross[5] << endl;
    }
#endif    
    
    //baseline parameters
    r_8 xi = 0.;
    r_8 yi = 0.;
    r_8 zi = 0.;
    if (iDish != 1 ) { //the Dish 1 is the origin of the horizontal frame
      xi = parTot[Find("X" + iStr)->second];
      yi = parTot[Find("Y" + iStr)->second];
      zi = parTot[Find("Z" + iStr)->second];
    }
    
    r_8 xj = 0.; 
    r_8 yj = 0.;
    r_8 zj = 0.;
    {
      xj = parTot[Find("X" + jStr)->second];
      yj = parTot[Find("Y" + jStr)->second];
      zj = parTot[Find("Z" + jStr)->second];
    }


    parCross[6]  = xj - xi; //LSN
    parCross[7]  = yj - yi; //LEW
    parCross[10] = zj - zi; //vertical diff

#if  DEBUG_THRESH > 400
    if(debug) {
      if(iDish !=1){
	cout << ("X" + iStr)<< " <=> "  << Find("X" + iStr)->second << endl;
	cout << ("Y" + iStr)<< " <=> "  << Find("Y" + iStr)->second << endl;
	cout << ("Z" + iStr)<< " <=> "  << Find("Z" + iStr)->second << endl;
      }
      cout << ("X" + jStr)<< " <=> "  << Find("X" + jStr)->second << endl;
      cout << ("Y" + jStr)<< " <=> "  << Find("Y" + jStr)->second << endl;
      cout << ("Z" + jStr)<< " <=> "  << Find("Z" + jStr)->second << endl;

      cout << "(x,y,z)_i: " << xi << ", " << yi << ", " << zi <<endl;
      cout << "(x,y)_j: " << xj << ", " << yj << ", " << zj <<endl;
      cout << "LSN, LEW, LVERT " << parCross[6] << ", " << parCross[7] << ", " 
	   << parCross[10] << endl;
    }
#endif
    
    
    //Cte term factor
    parCross[8] = parTot[Find("CTCross" + xName)->second];

#if  DEBUG_THRESH > 400
    if(debug) {
      cout  << ("CTCross" + xName) << " <=> "  <<  Find("CTCross" + xName)->second << endl;
      cout << "CTCross = " <<  parCross[8] << endl;
    }
#endif
    
    //phase parameters
    string iPolName = polarName_[iPol];
    string jPolName = polarName_[jPol];

#if  DEBUG_THRESH > 400
    if(debug){
      cout << "Polar Name: " << iPolName << ", " << jPolName << endl;
    }
#endif

    
    r_8 Phij = parTot[Find("Phi"+jPolName)->second];
    r_8 Phii = 0.; 
    if (iDish != 1 ) { // Dish 1 is the reference of the H and the V phases (separately)
      Phii = parTot[Find("Phi"+iPolName)->second];
    }
    
    
    parCross[9] = Phij - Phii;


#if  DEBUG_THRESH > 400
    if(debug){
      if(iDish !=1){
	cout << ("Phi"+iPolName) << " <=> "  << Find("Phi"+iPolName)->second << endl;
      }
      cout << ("Phi"+jPolName) << " <=> "  << Find("Phi"+jPolName)->second << endl;
      cout << "Phi_i: " << Phii << ", Phi_j: " <<  Phij << ", Dphi " <<  parCross[9] << endl;
    }
#endif




   
  }//GetCrossParm


  //Specialization of the baseclass
  virtual r_8 operator() (const vector< r_8 > &par) const { 

    r_8 chi2 =0.;

    for(int iCross=0; iCross< nCrossSet_; iCross++){

      //The data related to this cross
      GeneralFitData  data = vecData_[iCross];

#if  DEBUG_THRESH > 400
      string xName = crossName_[iCross];
      bool debug=false;
      string crossDebug("1H2H");
      if(xName == crossDebug) debug=true;
      if(::nloop>=10) ::firstDBG=false;
      debug = debug &&::firstDBG;

      if(debug)cout << "Debug["<<::nloop<< " : " << crossDebug << "] data: " << endl;
#endif       

      //Extract the corresponding parameters for this cross
      vector<r_8> funcPar(Cross::NbreParam());
      GetCrossParm(iCross, par, funcPar);
       
#if  DEBUG_THRESH > 400
      if(debug){
	for(int i=0;i<Cross::NbreParam();i++){
	  cout << "funcPar["<<i<<"]: " << funcPar[i] << endl;
	}
      }
#endif

      int npts = data.NData();
      for(int i=0;i<npts;i++){
	if(1 == data.IsValid(i)){
	  r_8 xp[1]; xp[0] = data.X1(i);
	  r_8 y = data.Val(i);
	  r_8 erry = data.EVal(i);
	  r_8 funcVal = func_->Value(xp, funcPar.data()); 
	  r_8 val = (funcVal - y)/erry;
#if  DEBUG_THRESH > 400
	  if(debug)cout << "x, y, erry, fval: " << xp[0] << " "
			<< y << " " << erry << " " << funcVal << endl; 
#endif
	  chi2 += val*val;
	}//valid data
      }//dataset loop

    }//cross loop

#if  DEBUG_THRESH > 400
    cout << "chi2 = " << chi2 << endl;
#endif
     
    return chi2;
    
  }//operator()

  virtual r_8 Up() const { return errDef_;}
  
private:
  GeneralFunction* func_;               // generic function model common to each dataset
  vector<GeneralFitData> vecData_;      // the data sets
  int    nCrossSet_;                    // number of data-cross sets
  int Ndish_;                           //nber of dishes 
  vector< pair<int, int> > crossPair_;  // (i,j) <-> k index in Cross matrix 
  vector<string>  crossName_;            // Cross Name: "1H2H", ...
  vector<string>  polarName_;            // Polarization Name : "1H", "2H", ... 
  ParFitCont_t paramIds_;            // identification of fit parameters name->id
  r_8 errDef_;                          // 1: 1-sigma Chi2, n*n for n-sigma errors
  
};//TotCrossChi2



//------------- Application ---------------------

//---------
// fitAutoCrossCorr: 
//    o fit the auto-correlations separately and then the cross-correlations
//    simultaneously.
//
//    o As input there are the different Sophya containers:
//       - FreqVec/TimeVec: frequence and time vectors
//       - TFM : time-frenquency real(auto)/complex(cross) visibilities
//       - the file name is coded by 
//           string fName = inputDir + "/" + source + ".ppf";
//
//    o As output there are different files depending on use-case
//        - by default the result of the fit frequency per frequency of the auto/cross
//           parameters are saved on file
//           #if PARTIE_REELLE >=1
//               string file= outputDir + "/fitCross-" + source + "-" + ss1.str() + "-" + ss2.str()+ "-RE.ppf";
//           #else
//               string file= outputDir + "/fitCross-" + source + "-" + ss1.str() + "-" + ss2.str()+ "-IM.ppf";
//           #endif
//
//        - if DEBUG_THRESH 301 then new files are produced one per visibility for a
//          single frequency which contain the raw data and the fitted curves. 
//          The file names are coded according to
//          string file= outputDir + "/fitAllAuto-" + source + "-" + nameCh[ia] + ".ppf";
//          #if PARTIE_REELLE >=1
//	      string file= outputDir + "/fitAllCross-" + source + "-" + xName + "-RE.ppf";
//          #else
//	      string file= outputDir + "/fitAllCross-" + source + "-" + xName + "-IM.ppf";
//          #endif
//
//---------
void fitAutoCrossCorr(){

  using namespace std;

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  //JEC 19/7/18 pour la nomenclature des fichiers
#if TYPE_POLAR == 1
  string polarTag = "H";	
#else
  string polarTag = "V";	
#endif


  cout << "fitAutoCrossCorr: Processing " + polarTag + " polar" << endl;

#if  AZIMUT_FIXED > 0
  cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" <<endl;
  cout <<" WARNING !!!! AZIMUT fix durant le fit des Auto corr" <<endl;
  cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" <<endl;
#endif


1037 1038 1039 1040
  //--------------------
  // Extract interactive user information
  //--------------------

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1041 1042
  cout << "coucou" << endl;

1043 1044 1045 1046
  int debug = param.debug;
  string inputDir = param.inputDir;
  string outputDir = param.outputDir;

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1047 1048
  

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
  r_4 FreqMin  = param.FreqMin;
  r_4 FreqMax  = param.FreqMax;
  r_4 FreqBand = param.FreqBand;

  string source = param.source;
  r_8 raSrcHour = param.raSrcHour;
  r_8 raSrcMin  = param.raSrcMin;
  r_8 raSrcSec  = param.raSrcSec;

  r_8 raSrc  =  HdecfrHMS(raSrcHour,raSrcMin,raSrcSec); //J2000     
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1059

1060 1061 1062 1063 1064 1065
  r_8 decSrcDeg  =  param.decSrcDeg;
  r_8 decSrcMin  =  param.decSrcMin;
  r_8 decSrcSec  =  param.decSrcSec;
  r_8 decSrc = degrad(decSrcDeg+decSrcMin/60.+decSrcSec/3600.); //J2000


1066

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1067

1068 1069 1070 1071 1072
  cout << "raSrc (hr): " << raSrc << ", decSrc (rad): " << decSrc << "\n";  

 
  TimeStamp meridianT = param.MeridianDate;

1073 1074 1075
  //JEC 18/2/19 new input the reference date HH::MM::SS
  TimeStamp referenceDate = param.ReferenceDate;

1076 1077 1078 1079 1080 1081 1082 1083

  r_4 hourAngleMax = param.hourAngleMax;
  r_4 hourAngleMin = param.hourAngleMin;
  if(hourAngleMax<HATHRESHOLD)
    throw ParmError("fitAllCross hourAngleMax<HATHRESHOLD");
  if(fabs(hourAngleMin)<HATHRESHOLD)
    throw ParmError("fitAllCross |hourAngleMin|<HATHRESHOLD");

1084 1085 1086
  Now LocalGeoTime = param.LocalGeoTime;


1087 1088 1089 1090 1091 1092 1093 1094
  //--------------------
  // Prepare numbering & naming stuff
  //--------------------

  size_t Ndish  = 4;
  size_t Nauto  = Ndish; //JEC 3/6/16 NPOLAR dependant
  size_t Ncross = Ndish*(Ndish-1)/2;   //2*(Ndish*(Ndish-1)/2)  and Ndish = Nauto/2

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1095
  cout << "Ndish, Nauto, Ncross: " << Ndish << " " << Nauto << " " << Ncross << endl;
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114


  vector<string> nameCh(Nauto);
#if TYPE_POLAR == 1
  nameCh[0] = "1H";
  nameCh[1] = "2H";
  nameCh[2] = "3H";
  nameCh[3] = "4H";
#else
  nameCh[0] = "1V";
  nameCh[1] = "2V";
  nameCh[2] = "3V";
  nameCh[3] = "4V";
#endif

  //Position par defaut des dipoles. 
  // ATTENTION !!!!!!!!! Repere Oriente vers North positif X, vers West positif Y, Z vertical
  vector<r_8> posXCh(Ndish), posYCh(Ndish), posZCh(Ndish);

1115
  //Geometrical initial values (units = meters)
1116 1117 1118 1119 1120 1121
  posXCh[0] = 0.; 
  posYCh[0] = 0.;      
  posZCh[0] = 0.;
  
  posXCh[1] = 0.; 
  posYCh[1] = 5.993;   
1122
  posZCh[1] = 0.; //was 0.100 pour tester => phase se translate
1123 1124 1125 1126 1127 1128 1129 1130

  posXCh[2] = -5.996; 
  posYCh[2] = -4.380;  
  posZCh[2] = 0.;

  posXCh[3] = 5.995; 
  posYCh[3] = -4.380;  
  posZCh[3] = 0.;
1131

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
#if AZIMUT_FIXED > 0
  //JEC 20/7/18 values sur CAsA 17 Juil 18
  vector<r_8> azimut_fix(Ndish);
  azimut_fix[0] = 0.96;  //degree dish 1
  azimut_fix[1] = -0.37; // dish 2
  azimut_fix[2] = -0.37; // dish 3
  azimut_fix[3] = 1.78;  // dish 4
  for(int i=0;i<Ndish;i++){
    cout << "FIX Az["<<i<<"] = " << azimut_fix[i] << " (deg)" << endl;
  }
#endif

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278

  vector< pair<int, int> > crossPair; //(i,j)  numbering starts at 0
  vector<string> crossName;
  for(size_t i=0;i<Nauto-1;i++){
    for(size_t j=i+1;j<Nauto;j++){
      crossPair.push_back(make_pair(i,j));
      crossName.push_back(nameCh[i]+nameCh[j]);
    }
  }

  if(crossPair.size() != Ncross) {
    cout << "Curieux !!!! crossPair.size() != Ncross " << endl;
    return;
  }
  
  {//debug
    for(size_t ix=0; ix<Ncross; ix++){
      int iCh = crossPair[ix].first;
      int jCh = crossPair[ix].second;
      cout << "Cross["<<ix<<"]: pair ("<< iCh << ", " << jCh
	   << "), name " <<  crossName[ix] 
	   <<endl;
    }
  }//debug

  
  {//debug
    for(size_t i=0; i<Ndish; i++){
      cout << "Polar [" << nameCh[i] << "]: (X,Y)= " << posXCh[i] << ", " << posYCh[i] << endl;
    }
  }//debug

  
    
  //--------------------
  //---------------
  // Parameters used in the Global Fit
  //---------------
  //--------------------
  ParFitCont_t paramIds;
  ParFitCont_t::iterator paramIter;

  int pId=0;

  //Beam parameters for all dishes
  for(size_t id=1; id<=Ndish; id++){  //index stats at 1
    string iName = Num2String(id);
    string NormCross = "NormCross"  + iName;
    string DeffName  = "Deff"+ iName;
    string AzName    = "Az"  + iName;
    paramIds.push_back(make_pair(NormCross,pId++));
    paramIds.push_back(make_pair(DeffName,pId++));
    paramIds.push_back(make_pair(AzName,pId++));
  }

  //position des dishs par rapport a la dish central (1) qui est placee en (0,0)
  for(size_t id=2; id <= Ndish; id++) { // dish numbering starts at 1
    stringstream ss; ss << id; 
    string XName = "X" + ss.str();
    string YName = "Y" + ss.str();
    string ZName = "Z" + ss.str(); //NEW
    paramIds.push_back(make_pair(XName,pId++));
    paramIds.push_back(make_pair(YName,pId++));
    paramIds.push_back(make_pair(ZName,pId++));
  }
  
  //phase: comme on ne considere que des cross H-H, et V-V on prend 2 references Phi1H = Phi1V = 0
  for (size_t ia=0; ia<Nauto; ia++){
    if (nameCh[ia] == "1H" || nameCh[ia] == "1V") continue; //skip 1H, 1V taken as reference phases H and V polar separately as we do not consider H-V cross corr
    string PhaseName = "Phi" + nameCh[ia];
    paramIds.push_back(make_pair(PhaseName,pId++));
  }

  //cte terms
  for(size_t ix=0; ix<Ncross; ix++){
    string xName = crossName[ix];
    string Cterm = "CTCross" + xName;
    paramIds.push_back(make_pair(Cterm,pId++));
  }


  //Keep Auto corr parameters
  for(size_t id=1; id<=Ndish; id++){  //index stats at 1
    string iName = Num2String(id);
    string NormAuto  = "NormAuto"   + iName;
    string CTAuto    = "CTAuto" + iName;
    string SLAuto = "SLAuto" + iName;
    paramIds.push_back(make_pair(NormAuto,pId++));
    paramIds.push_back(make_pair(CTAuto,pId++));
    paramIds.push_back(make_pair(SLAuto,pId++));
  }

  //total number of parameters to be fit
  int nTotPar = pId;  

  if((size_t)nTotPar != paramIds.size()) 
    throw ParmError("fitAllCross:: nTotPar != paramIds.size() ");


  cout << "Registration of " << nTotPar << " parameters: " << endl;
  for(paramIter=paramIds.begin(); paramIter != paramIds.end(); ++paramIter) {
    cout << "param [" << paramIter->first << "] with id : " << paramIter->second << endl;
  }  


  //-----------------
  //Data table to save the fit results
  //-----------------
  DataTable dt;
  dt.SetShowMinMaxFlag(true);
  dt.AddFloatColumn("freq");   //0
  dt.AddIntegerColumn("rc");   //1
  
  //include all parameter values
  for(paramIter=paramIds.begin(); paramIter != paramIds.end(); ++paramIter) {
    cout << "Add to dt param [" << paramIter->first << "] with id : " << paramIter->second << endl;
    dt.AddFloatColumn(paramIter->first);
  }
  
  //probably add errors on parameters afterwards  
  
  DataTableRowPtr rowp=dt.EmptyRowPtr();


  
  //--------------------
  //---------
  //Data loading and selection
  //---------
  //--------------------
  string fName = inputDir + "/" + source + ".ppf";
  cout << "Load data from <"<<fName<<">\n";
  PInPersist fIn(fName);


1279
  //RAVec
1280 1281
  //JEC 18/2/19 : attention we have during long data acquisition many [0h,24h] a cyclic RAVec
  //2: select indices according to TimeVec: #seconds since a 0h0 of a given day
1282 1283
  TArray<r_8> RAVec;
  fIn >> PPFNameTag("RAVec") >> RAVec;
1284

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
  TArray<r_8> TimeVec;
  fIn >> PPFNameTag("TimeVec") >> TimeVec;
  
  //number of second since reference date of source meridian transit
  r_8 tOfMeridianSinceRef = TimeStamp::TimeDifferenceSeconds(meridianT,referenceDate);
  //select +/- 5h arround 
  r_8 rangeOfTime = 5.0*3600.; //sec
  sa_size_t ifirstTime=0;
  sa_size_t ilastTime=0;
  {
    bool first=true;
    bool last=true;  
    
    for(sa_size_t i=0; i<TimeVec.Size();i++){
      if(fabs(TimeVec(i)-tOfMeridianSinceRef)<=rangeOfTime){
	if(first){
	  first  = false;
	  ifirstTime = i;
	  last   = true;
	}
	if(!first && last)ilastTime=i;
      } else {
	last = false;
      }
    }
  }//find ifirstTime/ilastTime

  if(ifirstTime==ilastTime)
    throw RangeCheckError("Time selection not valid");

  cout << "Select Time/RA range in index [" << ifirstTime << ", " << ilastTime << "]" << endl;


1318 1319 1320 1321
  TVector<r_4> HAVec(RAVec.Size());
  //JEC 9/6/18 seems that xephem routine has bugs
  for(sa_size_t i=0; i<RAVec.Size();i++){
    HAVec(i) = hrrad(RAVec(i)-raSrc); //hour angle = RA-raSrc hour -> radian
1322
  }
1323

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1324
   
1325
  //Selection des Angles Horaires
1326

1327 1328 1329 1330 1331 1332 1333 1334
  r_8 haMin =  Angle(hourAngleMin, Angle::Degree).ToRadian();
  r_8 haMAX =  Angle(hourAngleMax, Angle::Degree).ToRadian();
  sa_size_t ifirstHA=0;
  sa_size_t ilastHA=0;

  //Select the first transit of the source during observation
  bool first=true;
  bool last=true;  
1335 1336 1337 1338
  
  //JEC 18/2/19 restriction of the good HA range according to the ifirstTime/ilastTime range
  //was  for(sa_size_t i=0; i<HAVec.Size();i++){
  for(sa_size_t i=ifirstTime; i<ilastTime;i++){
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    if(HAVec(i)<haMAX && HAVec(i)>haMin){
      if(first){
	first  = false;
	ifirstHA = i;
	last   = true;
      }
      if(!first && last)ilastHA=i;
    } else {
      last = false;
    }
  } 
  cout << "Select HA index in ["<<ifirstHA <<","<<ilastHA <<"]\n";
  cout << "                in ["<<HAVec(ifirstHA) <<","<<HAVec(ilastHA) <<"] rad\n";
  
  if(ifirstHA==ilastHA)
    throw RangeCheckError("HA selection not valid");

  TVector<r_4> HASelected(HAVec(Range(ifirstHA,ilastHA)));

  sa_size_t NHA = HASelected.Size();

  //select the Frequence range
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378

  //JEC 19/7/18 Un nouveau vecteur precise les bornes en frequences coupees par l'operation des gains
  TVector<r_8> FreqLims;
  fIn >> PPFNameTag("FreqLims") >> FreqLims;
  r_4 freqLow  = (r_4)FreqLims(0);
  r_4 freqHigh = (r_4)FreqLims(1);


  if(FreqMin<freqLow){
    cout << "INFO: FreqMin too low, changed to " << freqLow << endl;
    FreqMin = freqLow;
  }
  if(FreqMax>freqHigh){
    cout << "INFO: FreqMax too high, changed to " << freqHigh << endl;
    FreqMax = freqHigh;
  }
  

1379 1380 1381 1382 1383 1384 1385
  int iFreqMin=0;
  int iFreqMax=0;
  TVector<r_8> FreqVec;
  fIn >> PPFNameTag("FreqVec") >> FreqVec;
  {
    vector<r_8> tmpStdV = FreqVec.ConvertTostdvec();  
    iFreqMin = closest(tmpStdV,(r_8)FreqMin);
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1386

1387 1388 1389
    if(iFreqMin<0)
      throw RangeCheckError("fitAutoCrossCorr: FreqMin not found in FreqVec vector");

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1390 1391 1392 1393
    //JEC 25/7/18 for safety
    iFreqMin += 1; 


1394
    iFreqMax = closest(tmpStdV,(r_8)FreqMax);
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1395
    if(iFreqMax<0 && iFreqMax > FreqVec.Size())
1396 1397
      throw RangeCheckError("fitAutoCrossCorr: FreqMax not found in FreqVec vector");

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1398 1399 1400 1401
    //JEC 25/7/18 for safety
    iFreqMax -= 1; 


1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    cout << "Debug from FreqVec: iFreqMin = " << iFreqMin << " -> " << FreqVec(iFreqMin)
	 << " iFreqMax = iFreqMax " << iFreqMax << " -> " << FreqVec(iFreqMax) << endl;
  }
   
  int Nfreq = iFreqMax-iFreqMin+1;

  cout << "Ncross,Nfreq,NHA: " << Ncross<< ", " <<Nfreq<< ", "<< NHA << endl;

  //-----
  // The auto correlations
  //-----

  POutPersist po("test.ppf");

  TArray<r_4> yPtsAuto(Nauto,NHA,Nfreq);
  TArray<r_4> eyPtsAuto(Nauto,NHA,Nfreq);

  string   objName;
  for(size_t ia=0; ia<Nauto; ia++){ //Loop on auto-corr
    cout << "Auto["<<ia<<"]: " <<  nameCh[ia] << endl;
    objName = "TFM_"+nameCh[ia];
    TMatrix<r_4> tmpVAL;         // CARE here we load Matrix to use Range selection afterwards
    fIn >> PPFNameTag(objName) >> tmpVAL;    
    
    yPtsAuto(Range(ia),Range::all(),Range::all()).CompactAllDimensions() = 
      tmpVAL(Range(iFreqMin,iFreqMax),Range(ifirstHA,ilastHA));

    //The variance
    TMatrix<r_4> tmpVAR;
    objName = "VARTFM_"+nameCh[ia];
    fIn >> PPFNameTag(objName) >> tmpVAR;

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1434

1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
    eyPtsAuto(Range(ia),Range::all(),Range::all()).CompactAllDimensions() = 
      Sqrt(tmpVAR(Range(iFreqMin,iFreqMax),Range(ifirstHA,ilastHA)));

  }//auto-loop



  //-----
  // The cross correlations
  //-----
  TArray<r_4> yPtsCross(Ncross,NHA,Nfreq);
  TArray<r_4> eyPtsCross(Ncross,NHA,Nfreq);


  for(size_t ix=0; ix<Ncross; ix++){ //Loop on cross-corr
    int iCh = crossPair[ix].first;
    int jCh = crossPair[ix].second;
    cout << "Cross["<<ix<<"]: pair ("<< iCh << ", " << jCh
 	 << "), name " <<  crossName[ix] 
 	 <<endl;
    
    //The values (REAL & IMAG) of the visibility
    objName = "TFM_"+crossName[ix];
    TMatrix< complex<r_4> > tmpVAL;         // CARE here we load Matrix to use Range selection afterwards
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1459 1460 1461

    
    fIn >> PPFNameTag(objName) >> tmpVAL; 
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479


    //In the File are stored TVector <Time-X, Freq-Y>
    //For a TMatrix
    /*
      line=axe-Y, Col=axe-X
      TMatrix< T > operator() (Range rline, Range rcol) const 
    */

#if defined(PARTIE_REELLE)

    yPtsCross(Range(ix),Range::all(),Range::all()).CompactAllDimensions() = 
      real(tmpVAL(Range(iFreqMin,iFreqMax),Range(ifirstHA,ilastHA)));

    //The variance
    TMatrix<r_4> tmpVAR;
    objName = "RVARTFM_"+crossName[ix];
    fIn >> PPFNameTag(objName) >> tmpVAR;
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1480

1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
    eyPtsCross(Range(ix),Range::all(),Range::all()).CompactAllDimensions() = 
      Sqrt(tmpVAR(Range(iFreqMin,iFreqMax),Range(ifirstHA,ilastHA)));

    
#else

    yPtsCross(Range(ix),Range::all(),Range::all()).CompactAllDimensions() = 
      imag(tmpVAL(Range(iFreqMin,iFreqMax),Range(ifirstHA,ilastHA)));

    //The variance
    TMatrix<r_4> tmpVAR;
    objName = "IVARTFM_"+crossName[ix];
    fIn >> PPFNameTag(objName) >> tmpVAR;
    eyPtsCross(Range(ix),Range::all(),Range::all()).CompactAllDimensions() = 
      Sqrt(tmpVAR(Range(iFreqMin,iFreqMax),Range(ifirstHA,ilastHA)));

#endif

  }//cross-corr

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1501 1502 1503 1504 1505
  {
    POutPersist po("test.ppf");
    po <<  PPFNameTag("yAuto") << yPtsAuto;
    po << PPFNameTag("yCross") <<yPtsCross;
  }
1506 1507 1508 1509 1510 1511 1512 1513 1514


  //--------------------
  //---------
  // Fit part
  //---------
  //--------------------
  cout << "Fit process... DEBUG ONE FREQ" << endl;

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1515 1516 1517 1518 1519 1520 1521
//   //TEST des bornes en Frequence et de la production des fichiers en sortie
//   vector<int> freqBins(2);
//   freqBins[0] = 0;
//   freqBins[1] = Nfreq-1;
//   for(int iFreqBin; iFreqBin < 2; iFreqBin++) {
//     int iFreq = freqBins[iFreqBin];

1522 1523
  for(int iFreq =0; iFreq < Nfreq; iFreq++) {

Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1524

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
    bool debug=true;

    
    r_4 freqCentre = FreqVec(iFreq+iFreqMin);
    cout << ">>>>>> Freq = " <<iFreq << ", " <<  freqCentre << endl;
    r_8 waveL = FreqToWave(freqCentre);
    

    //---------
    //Start with the auto-correlations to fit Beam parameters (single dish)
    // that are used as fixed values for cross-correlations  
    //---------
    typedef map<string, r_8> PairInitCont_t; 

    PairInitCont_t normAutoInit; //for future initial value of Cross Normalization
    PairInitCont_t deffInit; //for future initial value of Eff. Diameter for each dish
    PairInitCont_t azInit;   //for future initial value of Azimuthal angle deffect for each dish 
    PairInitCont_t ctAutoInit;   //to keep Auto baseline level 
    PairInitCont_t slAutoInit;   //to keep Auto baseline slope (8/11/17)
    

    AutoCorr funcAuto(waveL, raSrc, decSrc, LocalGeoTime);
    for(size_t ia=0; ia<Nauto; ia++){
      cout << ">>>>>> Auto = " << ia << endl;
      GeneralFitData dataFit(1, NHA); //1 pt (X=ha, Y=visi, EY: sigma_visi)
      
      //Todo: some part can be put in common with cross correlation
      r_8 normInit = -1;  //to set initial value of the normalisation
      r_8 cteInit=0;  //to set initial value of the constant term baseline
      r_8 slopeInit=0; //to set initial value of the slope of the baseline (8/11/17)
      
      r_8 edge_level_before=0.; //baseline level before transit (8/11/17)
      r_8 edge_level_after=0.;  //baseline level after  transit (8/11/17)
      r_8 mean_ra_edge_before=0;
      r_8 mean_ra_edge_after=0;
      r_8 nedge_before=0.;
      r_8 nedge_after=0.;
      r_8 central_min=0.;
      r_8 central_max=0.;
      for(sa_size_t c=0;c<NHA; c++){
	
	r_4 curX = HASelected(c);
	r_4 curY = yPtsAuto(ia,c,iFreq);
	r_4 curEY= eyPtsAuto(ia,c,iFreq);	
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1569 1570


1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
	dataFit.AddData1(curX,curY,curEY);

	if(curY > central_max){
	  central_max = curY;
	}
	if(curY < central_min){
	  central_min = curY;
	}
	if( curX > Angle(HATHRESHOLD, Angle::Degree).ToRadian() ) {
	  mean_ra_edge_after += curX;
	  edge_level_after += curY;
	  nedge_after++;
	}
	if( curX < -Angle(HATHRESHOLD, Angle::Degree).ToRadian() ) {
	  mean_ra_edge_before += curX;
	  edge_level_before += curY;
	  nedge_before++;
	}

 
      }//validation data

      if(nedge_before* nedge_after == 0)
	throw RangeCheckError("fitAutoCrossCorr problem to determine baseline cte/slope for Auto");

      //8/11/17 compute baseline cte and slope
      r_8 mean_edge = 0.5*(edge_level_before/nedge_before+edge_level_after/nedge_after); 
      r_8 slope_edge= (edge_level_after/nedge_after - edge_level_before/nedge_before)
	/ (mean_ra_edge_after/nedge_after - mean_ra_edge_before/nedge_before);
            
      normInit  = central_max - mean_edge; 
      cteInit   = mean_edge;
      slopeInit = slope_edge;


      if(debug){
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1607
	cout << nameCh[ia] << ": central_min, central_max,  normInit, cteInit, slopeInit : "
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
	     << central_min << " "
	     << central_max << " "
	     << normInit    << " "
	     << cteInit     << " "
	     << slopeInit   << " "
	     << endl;
	dataFit.Show();
      }

      int rc = 0; //retrun code du fit;


      //---------
      //Function to Minimize
      //---------
      
      AutoCorrChi2 fitf(&funcAuto,&dataFit);

      //---------
      //Initializatioin of fit parameters
      //---------
      
      MnUserParameters upar;
      upar.Add("NormAuto",normInit,fabs(normInit)*0.10,normInit/5., 5.*normInit);
      upar.Add("Deff",4.5,0.1,3.,6.);
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1633
#if  AZIMUT_FIXED == 0
1634
      upar.Add("Az",0.,0.1,-5.,5.);
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1635 1636 1637 1638 1639
#else
      cout << "Fix Az(deg) ="<< azimut_fix[ia] << endl;
      upar.Add("Az",azimut_fix[ia]);
      upar.Fix("Az");
#endif
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
      upar.Add("CTAuto",cteInit,fabs(cteInit)*0.1,cteInit-0.2*fabs(cteInit),
	       cteInit+0.2*fabs(cteInit));
      //8/11/17 add a slope parameter
      upar.Add("SLAuto",slopeInit,fabs(slopeInit)*0.1,slopeInit-0.5*slopeInit,slopeInit+0.5*slopeInit);

      if(upar.Parameters().size() != AutoCorr::NbreParam())
	throw ParmError("fitAllCross: upar for Auto size missmatch ");

      cout << "Param Ini." << endl;
      //The default print does not give the bounds    cout << upar << endl;
      {
	DumpMinuitParam(upar);
      }//Print initial values


      //---------
      // create the MnMinimizer
      //---------

      MnMigrad migrad(fitf, upar);
      unsigned int nparFree = migrad.VariableParameters();
      cout << "Nbre of free parameters = " << nparFree << endl;


      //---------
      // Minimize
      //---------
      unsigned int maxfcn = 200+100*nparFree + 100*nparFree*nparFree; 
      FunctionMinimum min = migrad(maxfcn,0.001);
      cout << "Minimizer..." << endl;
       
      cout << min << endl;
       
      rc = 0;
      if(!min.IsValid()) {
	rc = -1; //TODO be more explicit
	cout << "Minuit FAIL: Freq " <<  freqCentre << endl;
      }


      //--------
      // save usefull parameters for the cross: Deff and Az 
      //      and keep Normalization and baseline param too
      //--------
      deffInit[nameCh[ia]]     = min.UserParameters().Value("Deff");
      azInit[nameCh[ia]]       = min.UserParameters().Value("Az");
      normAutoInit[nameCh[ia]] = min.UserParameters().Value("NormAuto");
      ctAutoInit[nameCh[ia]]   = min.UserParameters().Value("CTAuto");
      slAutoInit[nameCh[ia]]   = min.UserParameters().Value("SLAuto");      //8/11/17

      cout << "Deff, Az, NormAuto, CTAuto saved for ["<<nameCh[ia]<<"]: " 
	   << deffInit[nameCh[ia]]  << " "
	   << azInit[nameCh[ia]] << " "
	   << normAutoInit[nameCh[ia]] << " "
	   << ctAutoInit[nameCh[ia]] << " "
	   << slAutoInit[nameCh[ia]]
	   << endl;


#if DEBUG_THRESH > 300
      {

	vector<MinuitParameter> minpar= min.UserParameters().Parameters();
	vector<r_8>dfuncPar(AutoCorr::NbreParam());
	for(size_t ip=0; ip<(size_t)AutoCorr::NbreParam(); ip++){
	  dfuncPar[ip] = minpar[ip].Value();
	}

	//compute fit function
	GeneralFitData dataFitFunc(1,NHA);
	for(sa_size_t c=0;c<NHA; c++){
	  r_8 xp[1]; xp[0] = HASelected(c);
	  r_8 valFunc = funcAuto.Value(xp, dfuncPar.data());
	  dataFitFunc.AddData1(xp[0], valFunc);
	}
Jean-Eric Campagne's avatar
Jean-Eric Campagne committed
1715 1716 1717 1718

	string file= outputDir + "/fitAllAuto-" + source + "-" + nameCh[ia] + "-" + polarTag + ".ppf";


1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762