casa  $Rev:20696$
BasePlot.h
Go to the documentation of this file.
00001 //# BasePlot.h: Basic table access class for the TablePlot (tableplot) tool
00002 //# Copyright (C) 1994,1995,1996,1997,1998,1999,2000,2001,2002,2003-2008
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 receied 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 addressed 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 //# $Id$
00027 //#
00028 //# ----------------------------------------------------------------------------
00029 //# Change Log
00030 //# ----------------------------------------------------------------------------
00031 //# Date         Name             Comments
00032 //# 01/10/2007   Urvashi R.V.     Added a locateData function here and to CrossPlot
00033 //# 08/24/2007   Urvashi R.V.     Modified documentation for all recent changes.
00034 
00035 
00036 #ifndef BASEPLOT_H
00037 #define BASEPLOT_H
00038 
00039 //# Includes
00040 
00041 #include <casa/aips.h>
00042 #include <casa/iostream.h>
00043 #include <casa/OS/Timer.h>
00044 
00045 #include <casa/Arrays/Vector.h>
00046 #include <casa/Arrays/Array.h>
00047 #include <casa/Arrays/Matrix.h>
00048 #include <casa/Arrays/Slicer.h>
00049 
00050 #include <tables/Tables/Table.h>
00051 #include <tables/Tables/ArrayColumn.h>
00052 #include <tables/Tables/ScalarColumn.h>
00053 #include <tables/Tables/TableColumn.h>
00054 
00055 #include <tables/Tables/ExprNode.h>
00056 #include <tables/Tables/RecordGram.h>
00057 
00058 #include <tableplot/TablePlot/SLog.h>
00059 
00060 #include <tableplot/TablePlot/TPCallBackHooks.h>
00061 #include <tableplot/TablePlot/FlagVersion.h>
00062 
00063 #include <ms/MeasurementSets/MeasurementSet.h>
00064 
00065 
00066 namespace casa { //# NAMESPACE CASA - BEGIN
00067 
00068 // <summary>
00069 // Basic table access class for the TablePlot (tableplot) tool
00070 // </summary>
00071 
00072 // <use visibility=export>
00073 
00074 // <reviewed reviewer="" date="" tests="">
00075 // </reviewed>
00076 
00077 // <prerequisite>
00078 //#! Classes or concepts you should understand before using this class.
00079 // </prerequisite>
00080 
00081 // <etymology>
00082 // BasePlot is the basic class that accesses one table/subtable and extracts
00083 // data to be plotted. It provides the interface between the TablePlot class
00084 // and the actual tables.
00085 // </etymology>
00086 
00087 // <synopsis>
00088 // Class BasePlot is the basic table access class for the purpose of plotting
00089 // data via TaQL expressions. A BasePlot object can operate on one table/subtable
00090 // and handles the extraction of data corresponding to TaQL expressions for the
00091 // purpose of plotting. It is to be used in conjunction with the TPPlotter class
00092 // via the TablePlot class, to connect the data from a table to a plotting device.
00093 // 
00094 // </synopsis>
00095 
00096 // <example>
00097 // <srcblock>
00098 // ( see TablePlot.cc )
00099 // // Instantiate BasePlot 
00100 // BasePlot<T> BP();
00101 // BP.Init(Table&);
00102 // BP.getData();
00103 // ... followed by TPPlotter 'setPlotRange' and 'plotData' calls
00104 // </srcblock>
00105 // </example>
00106 
00107 // <motivation>
00108 // This class was written so that each table/subtable can be handled
00109 // independant of each other. This allows simple bookkeeping and clean
00110 // relationships between tables and data sets when multiple tables are
00111 // being simultaneously accessed (plotting/editing). Issues like different 
00112 // numbers of data points to be plotted from different tables, and 
00113 // simultaneous editing on multiple tables/subtables (on one or more
00114 // plot panels) are handled by this class organization.
00115 // </motivation>
00116 
00117 // <templating arg=T>
00118 //    <li>
00119 // </templating>
00120 
00121 // <thrown>
00122 //    <li>
00123 //    <li>
00124 // </thrown>
00125 
00126 
00127 // <todo asof="$DATE:$">
00128 //# A List of bugs, limitations, extensions or planned refinements.
00129 //   <li> Provide the option to flag all channels (or a range) for a chosen range of stokes, or to flag all (or range of) stokes for the chosen channel range.
00130 //   <li> At some point, use TempArray instead of Matrix, to hold all the data to plot. Then,
00131 // one can limit the memory consumption, at the expense of having TempArrays on disk.
00132 // </todo>
00133 
00134 enum { XYPLOT, CROSSPLOT, HISTPLOT };
00135 enum { FLAG=1, UNFLAG=0 };
00136  
00137 class BasePlot 
00138 {
00139    public:
00140       // Constructor
00141       BasePlot();  
00142 
00143       // Destructor
00144       virtual ~BasePlot();
00145 
00146       // Operator=
00147       // Equate by reference.
00148       BasePlot& operator=(const BasePlot&){return *this;}
00149 
00150       // Attach the BasePlot object to a table/subtable.
00151       // This function also checks if the FLAG and/or 
00152       // FLAG_ROW column names exist.
00153       Int init(Table &tab, Int &tableNumber,String &rootTabName, 
00154                String &tableSelection, String &dataFlagColName, 
00155                String &rowFlagColName);   
00156       
00157       // Create TableExprNodes for all TaQL strings.
00158       // The RecordGram::parse() function is used to 
00159       // create TableExprNodes for each of the TaQL strings in the
00160       // input vector. The parse tree for each expression is also
00161       // traversed to extract table column names and corresponding
00162       // index ranges that are accessed. This is required while flagging
00163       // based on the result of a TaQL expression. For instance, in a MS
00164       // type table, if the 'MEAN' TaQL function is used to average data 
00165       // over several channels/stokes, only one set of data is plotted,
00166       // but while flagging all accessed channels/stokes must be flagged.
00167       // The function returns -1 if there is a TaQL syntax error, or if
00168       // the data-type of the expression result is not TpDouble, or if
00169       // an odd number of TaQL strings in sent in the input vector.
00170       // (Only expressions that return a TpDouble scalar or array can
00171       // be directly plotted).
00172       Int createTENS(Vector<String> &datastr);   
00173       
00174       // Read data from the table and fill up storage arrays.
00175       // This function reads the results of all TableExprNodes
00176       // from the first row of the table/subtable, to obtain the
00177       // shapes of the TaQL results. Data storage arrays are
00178       // accordingly resized and the reading continues for all
00179       // other rows.
00180       // Flags are read using the getFlags function.
00181       // If the shape of the data column being accessed matches that of
00182       // the FLAG column, a one-to-one mapping of flags is done.
00183       // If the shapes mis-match (or if only one flag exists per row), 
00184       // then the FLAG_ROW column is read. If neither FLAG nor FLAG_ROW
00185       // exist, all flags are assumed as False.
00186       // Errors in TaQL indices are caught and -1 is returned.
00187       Int getData(Vector<String> &datastr, Int layer, 
00188          TPConvertBase* conv, TPGuiCallBackHooks* callbackhooks_p);      
00189       
00190       // This function is callse from TPPlotter::setPlotRange().
00191       // Set plot range (all plots for this table).
00192       // Scan the data storage arrays to compute data ranges. In the case 
00193       // of overlay plots (due to Array TpDouble TaQL results), combined
00194       // data ranges for this tables data are computed.
00195       // This function requires that all stored data arrays be traversed.
00196       // This can get expensive for large number of data points. It is
00197       // assumed that for such a large number of data points, plotting
00198       // could broken down into chunks using an iteration axis.
00199       virtual Int setPlotRange(Double &xmin, Double &xmax, 
00200               Double &ymin, Double &ymax, 
00201               Bool showflags, Bool columnsxaxis, String flagversion, 
00202               Int averagenrows, String connectpoints=String("tablerow"),
00203               Bool doscalingcorrection=True,String multicolour=String("none"),
00204               Bool honourxflags=False); 
00205 
00206       
00207       // This function is called from TPPlotter::setFlagRegions().
00208       // The list of regions that have been marked for flagging
00209       // via TPPlotter::markFlags() is passed into BasePlot and 
00210       // stored.
00211       Int convertCoords(Vector<Vector<Double> > &flagmarks);
00212       
00213       // Fill in flags in the storage arrays.
00214       // The data storage arrays are traversed and flags for all
00215       // data values falling within the chosen flag regions are
00216       // set to true. If diskwrite=1, updated flags are written to disk.
00217       // If diskwrite=0, the flags are not written to disk, but will
00218       // be applied to plots that use the current instance of BasePlot.
00219       // If rowflag=1, a the FLAG_ROW column is set (if it exists) in
00220       // addition to the individual flags in the FLAG column (if it exists).
00221       Int flagData(Int diskwrite, Int rowflag, Int direction);     
00222 
00223       virtual Bool selectedPoint(Int np, Int nr);     
00224 
00225       Int flagData(Int direction, String msname, 
00226                    String ext);     
00227       Int flagData(Int direction, String msname, String spwexpr, 
00228                    Matrix<Int>& rowMap, Matrix<Int>& chanMap, String ext);     
00229       Int getFlags(String versionname, String msname);
00231       
00232       // Clear all flags (FLAG and FLAG_ROW) from the current
00233       // table/subtable.
00234       Int clearFlags();   
00235       
00236       Bool saveData(const String& filename);
00237 
00238       // Query the internal structures for X data values
00239       virtual Double getXVal(Int pnum, Int col);
00240       
00241       // Query the internal structures for Y data values
00242       virtual Double getYVal(Int pnum, Int col);
00243 
00244       // Query the internal structures for flags
00245       virtual Bool getYFlags(Int pnum, Int col);
00246       void showFlags();
00247 
00248       // Query for the number of points per plot
00249       virtual Int getNumRows();
00250 
00251       // Query for the number of plots
00252       virtual Int getNumPlots();
00253 
00254       // Get the plot colour to use - based on "multicolour"
00255       // This number is added to the "color" in PlotOption, to
00256       // generate the different colours for different cellrows/cellcols
00257       virtual Int getColourAddOn(Int pnum);
00258 
00259       // Query for the type of plot (BASEPLOT)
00260       // For BasePlot, this is "XYPLOT".
00261       // For CrossPlot, this is "CROSS".
00262       Int getPlotType();
00263 
00264       // Get some Table Info
00265       Vector<String> getBasePlotInfo();
00266       
00267       // Locate Data
00268       // Step through the data, check if each point has been selected.
00269       // If it has, then read out the row number, and index into the
00270       // Table and pull out the values of each of the LocateColumns
00271       // for each selected row number.  Channel/Corr (cellcol/cellrow)
00272       // indices are also found, and concatenated into a [row,col] string
00273       // to be returned for printing.
00274       virtual Int locateData(Vector<String> collist, 
00275            Matrix<Double> &info, Vector<String> &cpol);
00276 
00277       // Make this different from the above just in case
00278       // somebody else also use this function
00279       // make TablePlot to know which one to call
00280       virtual Int locateData(Vector<String> collist, 
00281            Matrix<Double> &info, Vector<String> &cpol,
00282            Matrix<Int>& rmap, Matrix<Int> &cmap);
00283       
00284       // Update Flag History
00285       // Fill in these parameters with a list of flag regions, 
00286       // flag or unflag, and the
00287       // number of points selected in these regions.
00288       Int updateFlagHistory(Vector<Vector<Double> > &flagmarks, 
00289            Int &direction, Int &numflags);
00290 
00291       //Number of rows in the BP's Table.
00292       Int NRows_p;
00293                 
00294       // A pointer to the CallBack class. One of them is held
00295       // for each BP.
00296       TPGuiCallBackHooks* callbackhooks_p;
00297 
00298        // Return the name of the Table being held by BP.
00299        String getTableName();
00300 
00301    protected:
00302       
00303       // Create TableExprNodes from input TAQL strings
00304       virtual Int createXTENS(Vector<String> &datastr);   
00305       Int createYTENS(Vector<String> &datastr);   
00306       
00307       // Read in the values ( after TaQL evaluations ) into
00308       // the storage arrays.
00309       virtual Int getXData(TPConvertBase* conv,Bool dummyread=False);
00310       Int getYData(TPConvertBase* conv,Bool dummyread=False);
00311 
00312       // Read flags from the table into theflags_p
00313       // This reconciles the original indices in the FLAG column, with the
00314       // indices selected via TaQL. It also take care of getting the flags
00315       // in when a TaQL Scalar or Vector reduction has been done.
00316       // Also, it checks with flagsum_p, to see if anyone else has
00317       // updated flags for this Table, and if so, recomputes the TaQL so that
00318       // channel averages take into account updated flags.
00319       // And lots more !!
00320       Int getFlags( String versionname, Bool showflags );
00321 
00322       // Recompute TaQLs in case another BP has changed the flags
00323       // for this row. 
00324       Int reGetYData(Int tenid, Int row, TPConvertBase* conv);
00325 
00326       // Get TaQL incides
00327       Int getIndices(TableExprNode &ten);
00328       
00329       // Traverse the TaQL parse tree and collect TaQL index ranges
00330       void ptTraverse(const TableExprNodeRep *tenr);
00331       
00332       // Write flags to disk.
00333       // This does the inverse of getFlags.
00334       // Flag expansion for TaQL scalar/vector reduction happens here.
00335       Int setFlags(Int direction, Int setrowflag);
00336    
00337       // Clears currently held flag region lists and TaQL index lists.
00338       Int cleanUp();      
00339 
00340       // Get the chan, pol from np
00341       Matrix<String> getLocateIndices();
00342       Matrix<String> getLocateIndices(Matrix<Int>& cmap);
00343 
00344       // Get the chan, pol from np
00345       Matrix<Int> getLocatePolChan();
00346       
00347       // Create Map_p = a matrix of important indices.
00348       // nrows : NPlots_p. So each cellcol/cellrow gets
00349       //         its own Map_p row.
00350       // ncols : 5
00351       // Col 0 : index into xplotdata 
00352       // Col 1 : index into yplotdata
00353       // Col 2 : index into tens (z)
00354       // Col 3 : yplotdata row index
00355       // Col 4 : yplotdata col index
00356       Int createMap();
00357 
00358       // Compute averages of rows.
00359       Int computeAverages(Int averagenrows);      
00360 
00361       // Compute averages of X values.. this is just a place-holder.
00362       virtual Int computeXAverages(Int averagenrows, Int remrows);
00363 
00364       // Exceptions..
00365       void BasePlotError(String msg);
00366 
00367       
00368       // The single Table to be accessed.
00369       Table SelTab_p;
00370 
00371       Table* itsTab_p;
00372       String itsTabName_p;
00373 
00374       // The internal number assigned to the table by
00375       // TablePlot
00376       uInt tabNum_p;
00377       // The name of the root Table on disk.
00378       // If a memory Table, this should be "".
00379       String rootTabName_p;
00380       // A string with selection information.
00381       String tabSelString_p;
00382 
00383       // List of TaQL strings.
00384       Vector<String> DataStr_p;
00385       // Flag to signal a new table being attached
00386       Int TableTouch_p; 
00387       // Remember the "layer" of the plot from this basePlot.
00388       // This is used to discard "getData" calls for other layers.
00389       Int Layer_p;
00390 
00391       // Flag to signal the use of averages or not.
00392       // This is for "averagenrows" and averaging across rows.
00393       // If True, then points are averaged, before being sent to TPLP.
00394       Bool Average_p; 
00395 
00396       // number of TaQL string pairs.
00397       Int nTens_p; 
00398       // TableExprnodes created from these TaQL string pairs
00399       Vector<TableExprNode> xtens_p;
00400       Vector<TableExprNode> ytens_p;
00401 
00402       // Matrices to hold the actual data to be plotted.
00403       // i.e. the values obtained after TaQL evaluation.
00404       Matrix<Double> xplotdata_p;
00405       Matrix<Float> yplotdata_p;
00406 
00407       // Matrix to hold the data flags
00408       Matrix<Bool> theflags_p;
00409       // Vector to hold the row flags
00410       Vector<Bool> rowflags_p;
00411                 
00412       // Vector to hold the number of flagged cell rows/cols per row.
00413       // For an MS, this is the number of corrs/chans flagged per row.
00414       // This is used to check when another BasePlot has changed the
00415       // flags. ( remember - multiple BPs can work on the same Table
00416       // at once...) and this ensures that channel averages are 
00417       // recomputed for rows for which the flags have changed.
00418       // This is how flags changed through one plot, are immediately
00419       // updated in all other plots from the same Table.
00420       Matrix<Int> flagsum_p;
00421 
00422       // Flag to distinguish between loading flagsum_p for the first
00423       // time, and using it to check for "changed" rows.
00424       Bool firsttime_p;
00425 
00426       // If averaging is done across rows, the averaged
00427       // values are stored in these variables.
00428       // This is in addition to "xplotdata_p, etc.. "
00429       // Since this is filled on the fly, one can generate
00430       // plots with different 'averagenrows', without
00431       // having to re-read data from disk.
00432       ArrayColumn<Bool> AvgFlags_p;
00433       ScalarColumn<Bool> AvgRowFlags_p;
00434 
00435       Matrix<Double> avgxplotdata_p;
00436       Matrix<Float> avgyplotdata_p;
00437       Matrix<Bool> avgtheflags_p;
00438       Vector<Bool> avgrowflags_p;
00439       Vector<Int> avgindices_p;
00440       
00441       // Number of plots
00442       // sum (ncellrows x ncellcols from each TaQL XY pair )
00443       // TPLP sees this number, and asks for data to create
00444       // this number of plots.
00445       Int NPlots_p;
00446 
00447        // Number of rows left after averaging across rows
00448        // ( averagenrows )
00449        Int NAvgRows_p; 
00450 
00451       // a VERY important data structure that holds 
00452       // very useful index information. This is used
00453       // all over the place. A description of this
00454       // Matrix is in the code of BasePlot::createMap().
00455       Matrix<Int> Map_p;
00456 
00457       // The first TaQL indices for each Y-TaQL.
00458       Vector<Slicer> TENslices_p;
00459 
00460       // The Column shapes for columns accessed by each Y-TaQL.
00461       // This is used to decide if a scalar/vector TaQL reduction
00462       // has happened or not. This info goes into ReductionType_p
00463       Vector<IPosition> TENcolshapes_p;
00464 
00465       // Holds info about which cellrows/cellcols are
00466       // completely flagged per row. This is for use in
00467       // averaging channel numbers -- not really used.
00468       Vector<Vector<Bool> > TENRowColFlag_p;
00469                 
00470       // List of reduction-types for each Y-TaQL.
00471       // 0 : no reduction
00472       // 1 : scalar reduction (SUM(..))
00473       // 2 : vector reduction (SUM(..,1))
00474       // 3 : vector reduction (SUM(..,2))
00475       Vector<Int> ReductionType_p;
00476       
00477       // Signal for each TaQL using an ArrayCol or ScalarCol.
00478       Vector<Bool> isArrayCol_p;
00479 
00480       // Shapes for Xdata and Ydata.
00481       Vector<IPosition> Yshape_p;
00482       Vector<IPosition> Xshape_p;
00483                 
00484       // accessed column names
00485       Vector<String> colnames_p;
00486       // accessed column slices
00487       Vector<Slicer> ipslice_p;
00488       // number of pairs of colnames and indices.
00489       Int nip_p; 
00490       // mapping from yplotdata index to colnames_p indices.
00491       Vector<Int> IndCnt_p; 
00492       
00493       // Flag holders...
00494       ArrayColumn<Bool> Flags_p;
00495       ScalarColumn<Bool> RowFlags_p;
00496       String FlagColName_p,FlagRowName_p;
00497       IPosition FlagColShape_p;
00498       // flags of FLAG,FLAG_ROW existence.
00499       Bool fcol_p,frcol_p; 
00500       
00501       // list of flag regions ( or locate regions )
00502       Vector<Vector<Double> > locflagmarks_p; 
00503       // # flag regions
00504       Int nflagmarks_p; 
00505       // 1 : FLAG, 0 : UNFLAG
00506       Int flagdirection_p; 
00507       // number of selected points.
00508       Int numflagpoints_p;
00509 
00510       // Plot Options that need to be used here.
00511       Bool showflags_p;
00512       Bool doscalingcorrection_p;
00513       String multicolour_p;
00514 
00515       // Pointer to the Convert function
00516       TPConvertBase* conv_p;
00517 
00518       // Dear ol' FlagVersion pointer.
00519       FlagVersion *FV;
00520       String currentflagversion_p;
00521 
00522       Int dbg,ddbg,adbg;
00523       Timer tmr;
00524 
00525       Int pType_p;
00526 
00527       SLog *log;
00528       static String clname;
00529 };
00530 
00531 } //# NAMESPACE CASA - END 
00532 
00533 //#ifndef AIPS_NO_TEMPLATE_SRC
00534 //#include <tableplot/TablePlot/BasePlot.cc>
00535 //#endif //# AIPS_NO_TEMPLATE_SRC
00536 #endif
00537 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines