casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines
SolvableVisCal.h
Go to the documentation of this file.
00001 //# SolvableVisCal.h: Definitions of interface for SolvableVisCal 
00002 //# Copyright (C) 1996,1997,2000,2001,2002,2003
00003 //# Associated Universities, Inc. Washington DC, USA.
00004 //#
00005 //# This library is free software; you can redistribute it and/or modify it
00006 //# under the terms of the GNU Library General Public License as published by
00007 //# the Free Software Foundation; either version 2 of the License, or (at your
00008 //# option) any later version.
00009 //#
00010 //# This library is distributed in the hope that it will be useful, but WITHOUT
00011 //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00012 //# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
00013 //# License for more details.
00014 //#
00015 //# You should have received a copy of the GNU Library General Public License
00016 //# along with this library; if not, write to the Free Software Foundation,
00017 //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
00018 //#
00019 //# Correspondence concerning AIPS++ should be adressed as follows:
00020 //#        Internet email: aips2-request@nrao.edu.
00021 //#        Postal address: AIPS++ Project Office
00022 //#                        National Radio Astronomy Observatory
00023 //#                        520 Edgemont Road
00024 //#                        Charlottesville, VA 22903-2475 USA
00025 //#
00026 //#
00027 
00028 #ifndef SYNTHESIS_SOLVABLEVISCAL_H
00029 #define SYNTHESIS_SOLVABLEVISCAL_H
00030 
00031 #include <casa/aips.h>
00032 #include <casa/Containers/Record.h>
00033 #include <casa/BasicSL/Complex.h>
00034 #include <casa/BasicSL/Constants.h>
00035 #include <synthesis/MeasurementComponents/VisCal.h>
00036 #include <synthesis/MeasurementComponents/CalCorruptor.h>
00037 #include <synthesis/MeasurementComponents/Mueller.h>
00038 #include <synthesis/MeasurementComponents/Jones.h>
00039 #include <synthesis/MeasurementComponents/VisVector.h>
00040 #include <synthesis/TransformMachines/SynthesisError.h>
00041 #include <synthesis/CalTables/NewCalTable.h>
00042 #include <synthesis/CalTables/CTPatchedInterp.h>
00043 #include <synthesis/CalTables/CalSetMetaInfo.h>
00044 #include <synthesis/CalTables/VisCalEnum.h>
00045 #include <synthesis/MSVis/VisSet.h>
00046 #include <synthesis/MSVis/CalVisBuffer.h>
00047 #include <synthesis/MSVis/VisBuffGroupAcc.h>
00048 
00049 #include <casa/Logging/LogMessage.h>
00050 #include <casa/Logging/LogSink.h>
00051 #include <casa/Logging/LogIO.h>
00052 #include <casa/OS/Timer.h>
00053 
00054 #include <iostream>
00055 #include <fstream>
00056 
00057 namespace casa { //# NAMESPACE CASA - BEGIN
00058 
00059 
00060 // **********************************************************
00061 //  SolvableVisCal
00062 //
00063 
00064 // Forward
00065 class VisEquation;
00066 
00067 class SolvableVisCal : virtual public VisCal {
00068 public:
00069 
00070   typedef struct fluxScaleStruct {
00071     Matrix<Double> fd;
00072     Matrix<Double> fderr;
00073     Matrix<Int> numSol;
00074     Vector<Double> freq;
00075     Matrix<Double> spidx;
00076     Matrix<Double> spidxerr;
00077   } fluxScaleStruct;
00078 
00079 
00080   SolvableVisCal(VisSet& vs);
00081   
00082   SolvableVisCal(const Int& nAnt);
00083 
00084   virtual ~SolvableVisCal();
00085 
00086   // Access to user-supplied parameters
00087   inline String&      calTableName()   { return calTableName_; };
00088   inline String&      calTableSelect() { return calTableSelect_; };
00089   inline Bool&        append()         { return append_; };
00090   inline String&      tInterpType()    { return tInterpType_; };
00091   inline String&      fInterpType()    { return fInterpType_; };
00092   inline Vector<Int>& spwMap()         { return spwMap_; };
00093   inline Int&         refant()         { return refantlist()(0); };
00094   inline Vector<Int>& refantlist()     { return urefantlist_; };
00095   inline Int&         minblperant()    { return minblperant_; };
00096   inline String&      apmode()         { return apmode_; };
00097   inline String&      solint()         { return solint_; };
00098   inline String&      fsolint()        { return fsolint_; };
00099   inline Double&      preavg()         { return preavg_; };
00100   inline Bool&        solnorm()        { return solnorm_;};
00101   inline Float&       minSNR()         { return minSNR_; };
00102 
00103   inline String&      combine()        { return combine_; };
00104   inline Bool         combspw()        { return upcase(combine_).contains("SPW"); };
00105   inline Bool         combfld()        { return upcase(combine_).contains("FIELD"); };
00106   inline Bool         combscan()       { return upcase(combine_).contains("SCAN"); };
00107   inline Bool         combobs()        { return upcase(combine_).contains("OBS"); };
00108 
00109   // Total number of (complex) parameters per solve
00110   //  (specialize to jive with ant- or bln-basedness, etc.)
00111   virtual Int nTotalPar()=0;
00112 
00113   // Report if calibration available for specified spw
00114   //  (if no CalInterp available, assume True)
00115 
00116   // Use generic data gathering mechanism for solve
00117   virtual Bool useGenericGatherForSolve() { return True; };
00118 
00119   // Use generic solution engine for a single solve
00120   //  (usually inside the generic gathering mechanism)
00121   virtual Bool useGenericSolveOne() { return useGenericGatherForSolve(); };
00122 
00123   // Solve for point-source X or Q,U?
00124   //  nominally no (0)
00125   virtual Int solvePol() { return 0; };
00126 
00127   // Does normalization by MODEL_DATA commute with this VisCal?
00128   //   (if so, permits pre-solve time-averaging)
00129   virtual Bool normalizable()=0;
00130 
00131   // Is this type capable of accumulation?  (nominally no)
00132   virtual Bool accumulatable() { return False; };
00133 
00134   // Is this type capable of smoothing?  (nominally no)
00135   virtual Bool smoothable() { return False; };
00136 
00137   // Should only parallel-hands be used in solving?
00138   //  (generally no (default=False), but GJones and related
00139   //   will override, and eventually this will be a user-set-able
00140   //   parameter)
00141   virtual Bool phandonly() { return False; }
00142 
00143   // Access to focus channel
00144   inline Int&         focusChan()      { return focusChan_; };
00145 
00146   // Is this ready to solve?
00147   inline Bool isSolved() {return solved_;};
00148 
00149   // Is this solveable? (via this interface, nominally yes)
00150   virtual Bool isSolvable() {return True;};
00151 
00152   // Set the application parameters 
00153   virtual void setApply();
00154   virtual void setApply(const Record& apply);
00155   virtual void setModel(const String& )
00156   {throw(SynthesisError("Internal error: setModel() not yet supported for non EPJones type."));};
00157 
00158   // Report apply info/params, e.g. for logging
00159   virtual String applyinfo();
00160 
00161   // Set the solving parameters
00162   virtual void setSolve();
00163   virtual void setSolve(const Record& solve);
00164 
00165   // Report solve info/params, e.g., for logging
00166   virtual String solveinfo();
00167 
00168   // Arrange for accumulation
00169   virtual void setAccumulate(VisSet& vs,
00170                              const String& table,
00171                              const String& select,
00172                              const Double& t,
00173                              const Int& refAnt=-1);
00174 
00175   // Default value for parameters
00176   virtual Complex defaultPar() { return Complex(1.0); };
00177   virtual Float defaultRPar() { return Float(0.0); };
00178   virtual Complex defaultCPar() { return Complex(1.0); };
00179 
00180   // Arrange to build a cal table from specified values
00181   virtual void setSpecify(const Record& specify);
00182 
00183   // Fill a caltable with specified values
00184   virtual void specify(const Record& specify);
00185 
00186   // Size up the solving arrays, etc.  (supports combine)
00187   virtual Int sizeUpSolve(VisSet& vs, Vector<Int>& nChunkPerSol);
00188 
00189 
00190   // These inflate methods soon to deprecate (gmoellen, 20121212)
00191   // Inflate the pristine CalSet (from VisSet info)
00192   void inflate(VisSet& vs, const Bool& fillMeta=False);
00193   // Inflate the pristine CalSet (generically)
00194   virtual void inflate(const Vector<Int>& nChanDat,
00195                        const Vector<Int>& startChanDat,
00196                        const Vector<Int>& nSlot);
00197 
00198 
00199   // Hazard a guess at the parameters (solveCPar) given the data
00200   virtual void guessPar(VisBuffer& vb)=0;
00201 
00202   // Freq-dep solint values 
00203   inline Double& fintervalHz() { return fintervalHz_; };
00204   inline Double& fintervalCh() { return fintervalCh_(currSpw()); };  // for current Spw
00205   Matrix<Int> chanAveBounds()  { return chanAveBounds_(currSpw()); }; // for current Spw
00206   Matrix<Int> chanAveBounds(Int spw)  { return chanAveBounds_(spw); }; 
00207 
00208   // Access to current solution parameters and matrices
00209   inline virtual Cube<Complex>& solveCPar()   {return (*solveCPar_[currSpw()]);};
00210   inline virtual Cube<Float>&   solveRPar()   {return (*solveRPar_[currSpw()]);};
00211   inline virtual Cube<Bool>&    solveParOK()  {return (*solveParOK_[currSpw()]);};
00212   inline virtual Cube<Float> &  solveParErr() {return (*solveParErr_[currSpw()]);};
00213   inline virtual Cube<Float> &  solveParSNR() {return (*solveParSNR_[currSpw()]);};
00214   inline virtual Cube<Complex>& solveAllCPar()   {return (*solveAllCPar_[currSpw()]);};
00215   inline virtual Cube<Float>&   solveAllRPar()   {return (*solveAllRPar_[currSpw()]);};
00216   inline virtual Cube<Bool>&    solveAllParOK()  {return (*solveAllParOK_[currSpw()]);};
00217   inline virtual Cube<Float> &  solveAllParErr() {return (*solveAllParErr_[currSpw()]);};
00218   inline virtual Cube<Float> &  solveAllParSNR() {return (*solveAllParSNR_[currSpw()]);};
00219 
00220   // Access to source pol parameters
00221   inline Vector<Complex>& srcPolPar() { return srcPolPar_; };
00222 
00223   // Synchronize the meta data with a solvable VisBuffer
00224   //   (returns False if VisBuffer has no valid data)
00225   Bool syncSolveMeta(VisBuffer& vb, const Int& fieldId);
00226   Bool syncSolveMeta(VisBuffGroupAcc& vbga);
00227 
00228   // Provide for override of currScan and currObs
00229   void overrideObsScan(Int obs, Int scan);
00230 
00231   // If apmode() is "A", convert vb's visibilities to amp + 0i.
00232   // If it is "P", convert them to phase + 0i.
00233   // Otherwise (i.e. "AP"), leave them alone.
00234   virtual void enforceAPonData(VisBuffer& vb);
00235 
00236   // Verify VisBuffer data sufficient for solving (wts, etc.)
00237   virtual Bool verifyConstraints(VisBuffGroupAcc& vbag);
00238   virtual Bool verifyForSolve(VisBuffer& vb);
00239   
00240   // Self- gather and/or solve prototypes
00241   //  (triggered by useGenericGatherForSolve=F or useGenericSolveOne=F; 
00242   //   must be overridden in derived specializations)
00243   virtual void selfGatherAndSolve(VisSet& vs, VisEquation& ve);
00244   virtual void selfSolveOne(VisBuffGroupAcc& vs);
00245 
00246   // Set up data and model for pol solve
00247   void setUpForPolSolve(VisBuffer& vb);
00248 
00249   // Differentiate VB model w.r.t. Cal  parameters (no 2nd derivative yet)
00250   virtual void differentiate(CalVisBuffer& cvb)=0;
00251   virtual void differentiate(VisBuffer& vb,        
00252                              Cube<Complex>& V,     
00253                              Array<Complex>& dV,
00254                              Matrix<Bool>& Vflg)=0;
00255   virtual void differentiate(VisBuffer& ,          // vb.visCube() has the obs. data.  vb.modelVisCube() will receive the residuals
00256                              VisBuffer&   ,       // 1st. Derivative w.r.t. first parameter
00257                              VisBuffer& ,         // 1st. Derivative w.r.t. second parameter
00258                              Matrix<Bool>& ){ throw(AipsError("Invalid use of differentiate(vb,dV0,dv1)")); };
00259 
00260 
00261   // Differentiate VB model w.r.t. Source parameters
00262   virtual void diffSrc(VisBuffer& vb,        
00263                        Array<Complex>& dV)=0;
00264 
00265   // Update solve parameters incrementally (additive)
00266   virtual void updatePar(const Vector<Complex> dCalPar,const Vector<Complex> dSrcPar);
00267 
00268   // Form solution SNR
00269   virtual void formSolveSNR();
00270 
00271   // Apply SNR threshold
00272   virtual void applySNRThreshold();
00273 
00274   // Apply refant (implemented in SVJ)
00275   virtual void reReference()=0;
00276 
00277   // Retrieve the cal flag info as a record
00278   virtual Record actionRec();
00279 
00280   // Accumulate another VisCal onto this one
00281   virtual void accumulate(SolvableVisCal* incr,
00282                           const Vector<Int>& fields)=0;
00283 
00284   virtual void smooth(Vector<Int>& fields,
00285                       const String& smtype,
00286                       const Double& smtime);
00287 
00288   // Report solved-for QU
00289   virtual void reportSolvedQU();
00290 
00291 
00292   // New CalTable handling
00293   virtual void createMemCalTable();
00294   virtual void keep1(Int ichan);
00295   virtual void keepNCT();
00296   virtual void storeNCT();
00297   void storeNCT(const String& tableName,const Bool& append);
00298 
00299   virtual void loadMemCalTable(String ctname,String field="");
00300 
00301   // New spwOK
00302   virtual Bool spwOK(Int ispw);
00303 
00304   // Post solve tinkering (generic version)
00305   virtual void globalPostSolveTinker();
00306 
00307   // Divide all solutions by their amplitudes
00308   virtual void enforceAPonSoln();
00309 
00310   // Normalize a solution (generic implementation)
00311   virtual void normalize();
00312 
00313   // Determine and apply flux density scaling
00314   virtual void fluxscale(const String& outfile,
00315                          const Vector<Int>& refFieldIn,
00316                          const Vector<Int>& tranFieldIn,
00317                          const Vector<Int>& inRefSpwMap,
00318                          const Vector<String>& fldNames,
00319                          fluxScaleStruct& oFluxScaleStruct,
00320                          const String& oListFile,
00321                          const Bool& incremental,
00322                          const Int& fitorder)=0;
00323 
00324   // Report state:
00325   inline virtual void state() { stateSVC(True); };
00326 
00327   virtual VisCalEnum::VCParType setParType(VisCalEnum::VCParType type) 
00328   {parType_ = type;return (VisCalEnum::VCParType)parType_;};
00329   virtual void currMetaNote();
00330 
00331   virtual void listCal(const Vector<Int> ufldids, const Vector<Int> uantids,
00332                        const Matrix<Int> uchanids,  //const Int& spw, const Int& chan,
00333                        const String& listfile="",const Int& pagerows=50)=0;
00334 
00335   // Handle external channel mask
00336   inline void setChanMask(PtrBlock<Vector<Bool>*>& chanmask) { chanmask_=&chanmask; };
00337   inline void clearChanMask() { chanmask_=NULL; };
00338   void applyChanMask(VisBuffer& vb);
00339   // Log periodic solver activity
00340   virtual void printActivity(const Int nSlots, const Int slotNo, 
00341                              const Int fieldId, const Int spw, 
00342                              const Int nSolutions);
00343   virtual void markTimer() {timer_p.mark();};
00344 
00345 
00346   // -------------
00347   // Set the simulation parameters
00348   virtual void setSimulate(VisSet& vs, Record& simpar, Vector<Double>& solTimes);
00349 
00350   // make a corruptor in a VC-specific way
00351   virtual void createCorruptor(const VisIter& vi,const Record& simpar, const int nSim);
00352 
00353   // access to simulation variables that are general to all VisCals
00354   inline String& simint() { return simint_; };
00355 
00356   // Simulation info/params, suitable for logging
00357   virtual String siminfo();
00358 
00359   // Is this calibration simulated?
00360   inline Bool isSimulated() {return simulated_;};
00361 
00362   // object that can simulate the corruption terms
00363   CalCorruptor *corruptor_p;
00364 
00365   // calculate # required slots to simulate this SVC
00366   Int sizeUpSim(VisSet& vs, Vector<Int>& nChunkPerSol, Vector<Double>& solTimes);
00367 
00368 protected:
00369 
00370   // Set to-be-solved-for flag
00371   inline void setSolved(const Bool& flag) {solved_=flag;};
00372 
00373   // Initialize solve parameters (shape)
00374   virtual void initSolvePar()=0;
00375 
00376   // Invalidate diff cal matrices generically 
00377   inline virtual void invalidateDiffCalMat()=0;
00378 
00379   // Explicitly synchronize pars with a CalSet slot
00380   using VisCal::syncPar;
00381 
00382   // Set matrix channelization according to a VisSet
00383   virtual void setSolveChannelization(VisSet& vs);
00384 
00385   // Calculate chan averaging bounds
00386   virtual void setFracChanAve();
00387 
00388   // Inflate an NCT w/ meta-data according to a VisSet 
00389   //   (for accum)
00390   void inflateNCTwithMetaData(VisSet& vs);
00391 
00392   // Synchronize calibration for solve context
00393   void syncSolveCal();
00394 
00395   // Synchronize parameters for solve context
00396   void syncSolvePar();
00397 
00398   // Calculate parameters by some means (e.g., interpolation from a CalSet)
00399   virtual void calcPar();
00400 
00401   // Synchronize the differentiated calibration 
00402   virtual void syncDiffMat()=0;
00403 
00404   // Report the SVC-specific state, w/ option for VC::state()
00405   virtual void stateSVC(const Bool& doVC);
00406 
00407   // Normalize a (complex) solution array (generic)
00408   void normSolnArray(Array<Complex>& sol,
00409                      const Array<Bool>& solOK,
00410                      const Bool doPhase=False);
00411 
00412   // Logger
00413   LogIO& logSink() { return logsink_p; };
00414 
00415   // Check if a cal table is appropriate
00416   void verifyCalTable(const String& caltablename);
00417 
00418   void sortVisSet(VisSet& vs, const Bool verbose=False);
00419 
00420   Int parType_;
00421 
00422   // New CalTable 
00423   NewCalTable *ct_;
00424   CTPatchedInterp *ci_;
00425   Vector<Bool> spwOK_;
00426 
00427   CalSetMetaInfo csmi;
00428 
00429   Double maxTimePerSolution_p, minTimePerSolution_p, avgTimePerSolution_p;
00430   Float userPrintActivityInterval_p, userPrintActivityFraction_p;
00431   uInt caiRC_p, cafRC_p;
00432   Timer timer_p;
00433 
00434   // Set state flag to simulate cal terms
00435   inline void setSimulated(const Bool& flag) {simulated_=flag;};
00436 
00437   // RI todo implement calcOneJones like calcAllMueller
00438   // calculate terms during apply, or up front during setSim?
00439   inline Bool& simOnTheFly() { 
00440     //    cout << "simOTF=" << onthefly_ << endl;
00441     return onthefly_; };
00442 
00443 
00444 
00445 private:
00446 
00447   // Default ctor is private
00448   SolvableVisCal();
00449 
00450   // Initialize pointers, etc.
00451   void initSVC();
00452 
00453   // Delete pointers
00454   void deleteSVC();
00455 
00456 
00457   // Cal table name
00458   String calTableName_;
00459   String calTableSelect_;
00460   Bool append_;
00461 
00462   // Interpolation types
00463   String tInterpType_;
00464   String fInterpType_;
00465 
00466   // Spw mapping
00467   Vector<Int> spwMap_;
00468 
00469   // Refant
00470   Vector<Int> urefantlist_;
00471 
00472   // Min baselines per ant for solve
00473   Int minblperant_;
00474 
00475   // Solved-for flag
00476   Bool solved_;
00477 
00478   // Solving mode
00479   String apmode_;
00480 
00481   // User-specified time-dep solint (string)
00482   String solint_;
00483 
00484   // User-specified freq-dep solint info
00485   String fsolint_;
00486   Double fintervalHz_;
00487   Vector<Double> fintervalCh_;   // (nSpw)
00488 
00489   // Channel averaging bounds
00490   Vector<Matrix<Int> > chanAveBounds_;  // (nSpw)(2,nOutChan)
00491 
00492   // Preavering interval
00493   Double preavg_;
00494 
00495   // Do solution normalization after a solve
00496   Bool solnorm_;
00497 
00498   // SNR threshold
00499   Float minSNR_;
00500 
00501   // axes to combine for solve
00502   String combine_;
00503 
00504   // In-focus channel for single-chan solves on multi-chan data
00505   Int focusChan_;
00506 
00507   // Solving meta-data
00508   Double dataInterval_;
00509   Double fitWt_;
00510   Double fit_;
00511 
00512 
00513   // Current parameters
00514   PtrBlock<Cube<Complex>*> solveCPar_;  // [nSpw](nPar,1,{1|nElem})
00515   PtrBlock<Cube<Float>*>   solveRPar_;  // [nSpw](nPar,1,{1|nElem})
00516   PtrBlock<Cube<Bool>*>    solveParOK_; // [nSpw](nPar,1,{1|nElm})
00517   PtrBlock<Cube<Float>*>   solveParErr_; // [nSpw](nPar,1,{1|nElm})
00518   PtrBlock<Cube<Float>*>   solveParSNR_; // [nSpw](nPar,1,{1|nElm})
00519 
00520   PtrBlock<Cube<Complex>*> solveAllCPar_;   // [nSpw](nPar,nChan,{1|nElem})
00521   PtrBlock<Cube<Float>*>   solveAllRPar_;   // [nSpw](nPar,nChan,{1|nElem})
00522   PtrBlock<Cube<Bool>*>    solveAllParOK_;  // [nSpw](nPar,nChan,{1|nElm})
00523   PtrBlock<Cube<Float>*>   solveAllParErr_; // [nSpw](nPar,nChan,{1|nElm})
00524   PtrBlock<Cube<Float>*>   solveAllParSNR_; // [nSpw](nPar,nChan,{1|nElm})
00525 
00526   Vector<Complex> srcPolPar_;
00527 
00528   // A _pointer_ to the external channel mask
00529   PtrBlock<Vector<Bool>*> *chanmask_;
00530 
00531   // LogIO
00532   LogIO logsink_p;
00533 
00534   // Simulation flag
00535   Bool simulated_;
00536 
00537   // simulation interval
00538   String simint_;
00539 
00540   Bool onthefly_;  
00541 
00542 };
00543 
00544 
00545 
00546 // **********************************************************
00547 //  SolvableVisMueller
00548 //
00549 
00550 class SolvableVisMueller : public SolvableVisCal, virtual public VisMueller
00551 {
00552 
00553 public:
00554 
00555   SolvableVisMueller(VisSet& vs);
00556 
00557   SolvableVisMueller(const Int& nAnt);
00558 
00559   virtual ~SolvableVisMueller();
00560 
00561   // Total number of (complex) parameters per solve
00562   //  Mueller version:  just return number of per-Bln parameters
00563   virtual Int nTotalPar() { return nPar(); };
00564 
00565   // Does normalization by MODEL_DATA commute with this VisCal?
00566   virtual Bool normalizable() { return (this->muellerType() < Mueller::General); };
00567 
00568   // Hazard a guess at the parameters (solvePar) given the data
00569   virtual void guessPar(VisBuffer& ) { throw(AipsError("NYI")); };
00570 
00571   // Differentiate VB model w.r.t. Mueller parameters (no 2nd derivative yet)
00572   virtual void differentiate(CalVisBuffer& ) {throw(AipsError("NYI")); };
00573   virtual void differentiate(VisBuffer& ,          // input data
00574                              Cube<Complex>& ,       // trial apply (nCorr,nChan,nRow)
00575                              Array<Complex>& ,     // 1st deriv   (nCorr,nPar,nChan,nRow)
00576                              Matrix<Bool>& ) { throw(AipsError("NYI")); };
00577   using SolvableVisCal::differentiate;
00578 
00579   // Differentiate VB model w.r.t. Source parameters
00580   virtual void diffSrc(VisBuffer& ,
00581                        Array<Complex>& ) {throw(AipsError("NYI")); };
00582 
00583   // Apply refant (no-op for Muellers)
00584   virtual void reReference() {};
00585 
00586   // Accumulate another VisCal onto this one
00587   virtual void accumulate(SolvableVisCal* ,
00588                           const Vector<Int>& ) { throw(AipsError("NYI")); };
00589 
00590   // Scale solutions
00591   virtual void fluxscale(const String&,
00592                          const Vector<Int>& ,
00593                          const Vector<Int>& ,
00594                          const Vector<Int>& ,
00595                          const Vector<String>& ,
00596                          SolvableVisCal::fluxScaleStruct&,
00597                          const String&,
00598                          const Bool&,
00599                          const Int&)
00600         { throw(AipsError("NYI")); };
00601 
00602   // SVM-specific write to caltable
00603   virtual void keepNCT();
00604 
00605   // Report state:
00606   inline virtual void state() { stateSVM(True); };
00607 
00608   // List calibration solutions in tabular form.
00609   virtual void listCal(const Vector<Int> ,
00610                        const Vector<Int> ,
00611                        const Matrix<Int> ,
00612                                const String& ,
00613                        const Int& )
00614   { throw(AipsError(String("Calibration listing not supported for "+typeName()))); };
00615 
00616 protected:
00617 
00618   // Number of Cal Matrices to form on baseline axis
00619   //  (Mueller, solve context: 1)
00620   virtual Int nCalMat() { return isSolved() ? 1 : nBln(); };
00621 
00622   // Are differentiated M matrices constant in chan & bln?
00623   virtual Bool trivialDM() { return False; };
00624 
00625   // Initialize solve parameter shape
00626   //  Mueller version:  (nPar(),1,1)   (one chan, one baseline)
00627   virtual void initSolvePar();
00628 
00629   // Access to matrix rendering of dM (per par)
00630   inline Mueller& dM() { return *dM_; };
00631 
00632   // Access to differentiated Mueller elements
00633   inline Array<Complex>& diffMElem() {return diffMElem_;};
00634 
00635   // Invalidate diff cal matrices generically (at this level, just M, dM)
00636   inline virtual void invalidateDiffCalMat() { invalidateM(); invalidateDM(); };
00637 
00638   // Validation of diffMueller matrices
00639   inline void invalidateDM() {DMValid_=False;};
00640   inline void validateDM()   {DMValid_=True;};
00641   inline Bool DMValid()      {return DMValid_;};
00642 
00643   // Synchronize the differentiated calibration (specialization for Mueller);
00644   virtual void syncDiffMat();
00645 
00646   // Synchronize the Muellers AND diffMuellers
00647   virtual void syncDiffMueller();
00648 
00649   // Calculate the ensemble of diff'd Mueller Elements
00650   virtual void calcAllDiffMueller();
00651 
00652   // Calculate one diffMElem 
00653   virtual void calcOneDiffMueller(Matrix<Complex>& mat, const Vector<Complex>& par);
00654 
00655   // Create matrix renderers for dMs
00656   void createDiffMueller();
00657 
00658   // Override VM::setMatByOk in solve context
00659   void setMatByOk() { if (!isSolved()) VisMueller::setMatByOk(); };
00660 
00661   // Initialize trivial diff'd Muellers
00662   virtual void initTrivDM();
00663 
00664   // SVM-specific state
00665   virtual void stateSVM(const Bool& doVC);
00666 
00667 
00668 private:
00669 
00670   // Default ctor is private
00671   SolvableVisMueller();
00672 
00673   // Mueller wrapper for diffMElem_;
00674   Mueller *dM_;
00675 
00676   // Differentiated Mueller matrix elements
00677   Array<Complex> diffMElem_;    // (nDMEl,nPar,nChanMat,nBln)
00678 
00679   // diffMueller validation
00680   Bool DMValid_;
00681 
00682 
00683 };
00684 
00685 // **********************************************************
00686 //  SolvableVisJones
00687 //
00688 
00689 class SolvableVisJones : public SolvableVisMueller, public VisJones {
00690 
00691 public:
00692 
00693   SolvableVisJones(VisSet& vs);
00694 
00695   SolvableVisJones(const Int& nAnt);
00696 
00697   virtual ~SolvableVisJones();
00698 
00699   // Total number of (complex) parameters per solve
00700   //  Jones version:  nPar()*nAnt()
00701   virtual Int nTotalPar() { return nPar()*nAnt(); };
00702 
00703   // Does normalization by MODEL_DATA commute with this VisCal?
00704   virtual Bool normalizable() { return (this->jonesType() < Jones::GenLinear); };
00705 
00706   // Differentiate VB model w.r.t. Jones parameters
00707   virtual void differentiate(CalVisBuffer& cvb);
00708   virtual void differentiate(VisBuffer& vb,          // input data
00709                              Cube<Complex>& V,       // trial apply (nCorr,nChan,nRow)
00710                              Array<Complex>& dV,     // 1st deriv   (nCorr,nPar,nChan,nRow,2)
00711                              Matrix<Bool>& Vflg);
00712   using SolvableVisMueller::differentiate;
00713 
00714   // Differentiate VB model w.r.t. Source parameters
00715   virtual void diffSrc(VisBuffer& vb,        
00716                        Array<Complex>& dV);
00717 
00718   // Apply refant
00719   virtual void reReference();
00720 
00721   // Accumulate another VisCal onto this one
00722   virtual void accumulate(SolvableVisCal* incr,
00723                           const Vector<Int>& fields);
00724 
00725   // Post solve tinkering (Jones version: includes refant application)
00726   virtual void globalPostSolveTinker();
00727 
00728   // Apply reference antenna (generic Jones version)
00729   virtual void applyRefAnt();
00730 
00731   // Fluxscale is implemented here
00732   void fluxscale(const String& outfile,
00733                  const Vector<Int>& refFieldIn,
00734                  const Vector<Int>& tranFieldIn,
00735                  const Vector<Int>& inRefSpwMap,
00736                  const Vector<String>& fldNames,
00737                  SolvableVisCal::fluxScaleStruct& oFluxScaleStruct,
00738                  const String& oListFile,
00739                  const Bool& incremental=False,
00740                  const Int& fitorder=1);
00741 
00742   // SVJ-specific write to caltable
00743   virtual void keepNCT();
00744                              
00745   // Report state:
00746   inline virtual void state() { stateSVJ(True); };
00747 
00748   // Write calibration solutions to the terminal
00749   virtual void listCal(const Vector<Int> ufldids, const Vector<Int> uantids,
00750                        const Matrix<Int> uchanids,
00751                        const String& listfile="",const Int& pagerows=50);
00752 
00753   // Write header for listCal output
00754   int writeHeader(const uInt numAntCols, 
00755                   const uInt numAnts,
00756                   const uInt iElem);
00757 
00758   virtual void nearest(const Double , Array<Float>& ) {};
00759   virtual void nearest(const Double , Array<Complex>& ) {};
00760 protected:
00761  
00762   // Number of Cal Matrices to form on baseline axis
00763   //  (Jones, all contexts: nAnt())
00764   virtual Int nCalMat() { return nAnt(); };
00765 
00766   // DM never trivial for SVJ
00767   virtual Bool trivialDM() { return False; };
00768 
00769   // Are differentiated J matrices constant in chan & ant?
00770   inline virtual Bool trivialDJ() { return False; };
00771 
00772   // Initialize solve parameter shape
00773   //  Jones version:  (nPar(),1,nAnt())   (one chan, all antennas)
00774   virtual void initSolvePar();
00775 
00776   // Access to matrix rendering of dJ1, dJ2
00777   inline Jones& dJ1() { return *dJ1_; };
00778   inline Jones& dJ2() { return *dJ2_; };
00779 
00780   // Access to differentiated Joness
00781   Array<Complex>& diffJElem() { return diffJElem_; };
00782 
00783   // Invalidate diff cal matrices generically (at this level, M, dM, J, dJ)
00784   inline virtual void invalidateDiffCalMat() { 
00785     SolvableVisMueller::invalidateDiffCalMat(); invalidateJ(); invalidateDJ(); };
00786 
00787   // Validation of Jones matrix derivatives
00788   inline void invalidateDJ() {DJValid_=False;};
00789   inline void validateDJ()   {DJValid_=True;};
00790   inline Bool DJValid()      {return DJValid_;};
00791 
00792   // Synchronize the differentiated calibration (specialization for Jones)
00793   virtual void syncDiffMat();
00794 
00795   // Synchronize the Jones AND diffJones matrices
00796   virtual void syncDiffJones();
00797 
00798   // Calculate the ensemble of diff'd Jones Elements
00799   virtual void calcAllDiffJones();
00800 
00801   // Calculate one ant/chan's diffJElem w.r.t. each par
00802   virtual void calcOneDiffJones(Matrix<Complex>& mat, const Vector<Complex>& par);
00803 
00804   // Create matrix renderers for dJs
00805   void createDiffJones();
00806 
00807   // Override VJ::setMatByOk in solve context
00808   void setMatByOk() { if (!isSolved()) VisJones::setMatByOk(); };
00809 
00810   // Initialize trivial diff'd Jones
00811   virtual void initTrivDJ();
00812 
00813   virtual void stateSVJ(const Bool& doVC);
00814 private:
00815 
00816   // Default ctor is private
00817   SolvableVisJones();
00818 
00819   // Jones wrappers for diffJElem_;
00820   Jones *dJ1_;
00821   Jones *dJ2_;
00822 
00823   // Differentiated Jones matrix elements
00824   Array<Complex> diffJElem_;    // (nJME,nPar,nChanMat,nAnt,2)
00825 
00826   // Validity of Jones matrix derivatives
00827   Bool DJValid_;
00828 
00829   // Column widths for listing
00830   uInt wTime_p,  wField_p, wChan_p, wAmp_p, 
00831        wPhase_p, wFlag_p,  wPol_p,  wAntCol_p, 
00832        wTotal_p, wPreAnt_p;
00833           
00834 };
00835 
00836 // Global methods
00837 
00838 // Discern cal table type from the table itself
00839 String calTableType(const String& tablename);
00840 
00841 } //# NAMESPACE CASA - END
00842 
00843 #endif