Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/asapplotter.py

    r2290 r2453  
    4545        if visible is not None:
    4646            self._visible = visible
    47         self._plotter = self._newplotter(**kwargs)
    48         # additional tool bar
    49         self._plotter.figmgr.casabar=self._new_custombar()
     47        self._plotter = None
     48        self._inikwg = kwargs
    5049
    5150        self._panelling = None
     
    5554        self._rows = None
    5655        self._cols = None
    57         self._autoplot = False
    5856        self._minmaxx = None
    5957        self._minmaxy = None
     
    7674        self._panelrows = []
    7775        self._headtext={'string': None, 'textobj': None}
     76        self._colormap = None
     77        self._linestyles = None
     78        self._legendloc = None
    7879
    7980    def _translate(self, instr):
     
    8586        return None
    8687
    87     def _newplotter(self, **kwargs):
    88         return new_asaplot(self._visible,**kwargs)
     88    def _reload_plotter(self):
     89        if self._plotter is not None:
     90            if  not self._plotter.is_dead:
     91                # clear lines and axes
     92                self._plotter.clear()
     93            if self.casabar_exists():
     94                del self._plotter.figmgr.casabar
     95            self._plotter.quit()
     96            del self._plotter
     97        self._plotter = new_asaplot(self._visible,**self._inikwg)
     98        self._plotter.figmgr.casabar=self._new_custombar()
     99        # just to make sure they're set
     100        self._plotter.palette(color=0,colormap=self._colormap,
     101                              linestyle=0,linestyles=self._linestyles)
     102        self._plotter.legend(self._legendloc)
    89103
    90104    def _new_custombar(self):
     
    107121        return False
    108122
     123    def _assert_plotter(self,action="status",errmsg=None):
     124        """
     125        Check plot window status. Returns True if plot window is alive.
     126        Parameters
     127            action:    An action to take if the plotter window is not alive.
     128                       ['status'|'reload'|'halt']
     129                       The action 'status' simply returns False if asaplot
     130                       is not alive. When action='reload', plot window is
     131                       reloaded and the method returns True. Finally, an
     132                       error is raised when action='halt'.
     133            errmsg:    An error (warning) message to send to the logger,
     134                       when plot window is not alive.
     135        """
     136        if self._plotter and not self._plotter.is_dead:
     137            return True
     138        # Plotter is not alive.
     139        haltmsg = "Plotter window has not yet been loaded or is closed."
     140        if type(errmsg)==str and len(errmsg) > 0:
     141            haltmsg = errmsg
     142       
     143        if action.upper().startswith("R"):
     144            # reload plotter
     145            self._reload_plotter()
     146            return True
     147        elif action.upper().startswith("H"):
     148            # halt
     149            asaplog.push(haltmsg)
     150            asaplog.post("ERROR")
     151            raise RuntimeError(haltmsg)
     152        else:
     153            if errmsg:
     154                asaplog.push(errmsg)
     155                asaplog.post("WARN")
     156            return False
     157
     158
    109159    @asaplog_post_dec
    110160    def plot(self, scan=None):
     
    119169            are consistent e.g. all 'channel' or all 'velocity' etc.
    120170        """
     171        if not self._data and not scan:
     172            msg = "Input is not a scantable"
     173            raise TypeError(msg)
    121174        self._startrow = 0
    122175        self._ipanel = -1
    123176        self._reset_header()
    124         if self._plotter.is_dead:
    125             if self.casabar_exists():
    126                 del self._plotter.figmgr.casabar
    127             self._plotter = self._newplotter()
    128             self._plotter.figmgr.casabar=self._new_custombar()
     177        self._panelrows = []
     178
     179        self._assert_plotter(action="reload")
    129180        if self.casabar_exists():
    130181            self._plotter.figmgr.casabar.set_pagecounter(1)
    131         self._panelrows = []
     182
    132183        self._plotter.hold()
    133184        #self._plotter.clear()
    134         if not self._data and not scan:
    135             msg = "Input is not a scantable"
    136             raise TypeError(msg)
    137185        if scan:
    138186            self.set_data(scan, refresh=False)
     187        self._plotter.palette(color=0,colormap=self._colormap,
     188                              linestyle=0,linestyles=self._linestyles)
     189        self._plotter.legend(self._legendloc)
     190
    139191        self._plot(self._data)
    140192        if self._minmaxy is not None:
     
    147199
    148200    def gca(self):
     201        errmsg = "No axis to retun. Need to plot first."
     202        if not self._assert_plotter(action="status",errmsg=errmsg):
     203            return None
    149204        return self._plotter.figure.gca()
    150205
    151206    def refresh(self):
    152207        """Do a soft refresh"""
     208        errmsg = "No figure to re-plot. Need to plot first."
     209        self._assert_plotter(action="halt",errmsg=errmsg)
     210
    153211        self._plotter.figure.show()
    154212
     
    163221                        if different IFs are spread over panels (default 0)
    164222        """
    165         if self._data is None:
     223        ## this method relies on already plotted figure
     224        if not self._assert_plotter(action="status") or (self._data is None):
     225            msg = "Cannot create mask interactively on plot. Can only create mask after plotting."
     226            asaplog.push( msg )
     227            asaplog.post( "ERROR" )
    166228            return []
    167229        outmask = []
     
    210272    # forwards to matplotlib axes
    211273    def text(self, *args, **kwargs):
     274        self._assert_plotter(action="reload")
    212275        if kwargs.has_key("interactive"):
    213276            if kwargs.pop("interactive"):
     
    219282
    220283    def arrow(self, *args, **kwargs):
     284        self._assert_plotter(action="reload")
    221285        if kwargs.has_key("interactive"):
    222286            if kwargs.pop("interactive"):
     
    231295
    232296    def annotate(self, text, xy=None, xytext=None, **kwargs):
     297        self._assert_plotter(action="reload")
    233298        if kwargs.has_key("interactive"):
    234299            if kwargs.pop("interactive"):
     
    242307
    243308    def axvline(self, *args, **kwargs):
     309        self._assert_plotter(action="reload")
    244310        if kwargs.has_key("interactive"):
    245311            if kwargs.pop("interactive"):
     
    251317
    252318    def axhline(self, *args, **kwargs):
     319        self._assert_plotter(action="reload")
    253320        if kwargs.has_key("interactive"):
    254321            if kwargs.pop("interactive"):
     
    260327
    261328    def axvspan(self, *args, **kwargs):
     329        self._assert_plotter(action="reload")
    262330        if kwargs.has_key("interactive"):
    263331            if kwargs.pop("interactive"):
     
    274342
    275343    def axhspan(self, *args, **kwargs):
     344        self._assert_plotter(action="reload")
    276345        if kwargs.has_key("interactive"):
    277346            if kwargs.pop("interactive"):
     
    288357
    289358    def _axes_callback(self, axesfunc, *args, **kwargs):
     359        self._assert_plotter(action="reload")
    290360        panel = 0
    291361        if kwargs.has_key("panel"):
     
    504574        """
    505575        self._lmap = mp
    506         self._plotter.legend(mode)
     576        #self._plotter.legend(mode)
     577        self._legendloc = mode
    507578        if isinstance(fontsize, int):
    508579            from matplotlib import rc as rcp
     
    513584    def set_title(self, title=None, fontsize=None, refresh=True):
    514585        """
    515         Set the title of the plot. If multiple panels are plotted,
     586        Set the title of sub-plots. If multiple sub-plots are plotted,
    516587        multiple titles have to be specified.
    517588        Parameters:
     589            title:      a list of titles of sub-plots.
     590            fontsize:   a font size of titles (integer)
    518591            refresh:    True (default) or False. If True, the plot is
    519592                        replotted based on the new parameter setting(s).
     
    521594        Example:
    522595             # two panels are visible on the plotter
    523              plotter.set_title(["First Panel","Second Panel"])
     596             plotter.set_title(['First Panel','Second Panel'])
    524597        """
    525598        self._title = title
     
    537610            ordinate:    a list of ordinate labels. None (default) let
    538611                         data determine the labels
     612            fontsize:    a font size of vertical axis labels (integer)
    539613            refresh:     True (default) or False. If True, the plot is
    540614                         replotted based on the new parameter setting(s).
     
    542616        Example:
    543617             # two panels are visible on the plotter
    544              plotter.set_ordinate(["First Y-Axis","Second Y-Axis"])
     618             plotter.set_ordinate(['First Y-Axis','Second Y-Axis'])
    545619        """
    546620        self._ordinate = ordinate
     
    559633            abcissa:     a list of abcissa labels. None (default) let
    560634                         data determine the labels
     635            fontsize:    a font size of horizontal axis labels (integer)
    561636            refresh:     True (default) or False. If True, the plot is
    562637                         replotted based on the new parameter setting(s).
     
    564639        Example:
    565640             # two panels are visible on the plotter
    566              plotter.set_ordinate(["First X-Axis","Second X-Axis"])
     641             plotter.set_ordinate(['First X-Axis','Second X-Axis'])
    567642        """
    568643        self._abcissa = abcissa
     
    584659                        Otherwise,the parameter(s) are set without replotting.
    585660        Example:
    586              plotter.set_colors("red green blue")
     661             plotter.set_colors('red green blue')
    587662             # If for example four lines are overlaid e.g I Q U V
    588663             # 'I' will be 'red', 'Q' will be 'green', U will be 'blue'
    589664             # and 'V' will be 'red' again.
    590665        """
    591         if isinstance(colmap,str):
    592             colmap = colmap.split()
    593         self._plotter.palette(0, colormap=colmap)
     666        #if isinstance(colmap,str):
     667        #    colmap = colmap.split()
     668        #self._plotter.palette(0, colormap=colmap)
     669        self._colormap = colmap
    594670        if refresh and self._data: self.plot(self._data)
    595671
     
    604680                         is taken from the .asaprc setting
    605681                         plotter.histogram
     682            linewidth:   a line width
    606683            refresh:     True (default) or False. If True, the plot is
    607684                         replotted based on the new parameter setting(s).
     
    620697        only one color has been set.
    621698        Parameters:
    622              linestyles:     a list of linestyles to use.
     699            linestyles:      a list of linestyles to use.
    623700                             'line', 'dashed', 'dotted', 'dashdot',
    624701                             'dashdotdot' and 'dashdashdot' are
    625702                             possible
     703            linewidth:       a line width
    626704            refresh:         True (default) or False. If True, the plot is
    627705                             replotted based on the new parameter setting(s).
    628706                             Otherwise,the parameter(s) are set without replotting.
    629707        Example:
    630              plotter.set_colors("black")
    631              plotter.set_linestyles("line dashed dotted dashdot")
     708             plotter.set_colors('black')
     709             plotter.set_linestyles('line dashed dotted dashdot')
    632710             # If for example four lines are overlaid e.g I Q U V
    633711             # 'I' will be 'solid', 'Q' will be 'dashed',
    634712             # U will be 'dotted' and 'V' will be 'dashdot'.
    635713        """
    636         if isinstance(linestyles,str):
    637             linestyles = linestyles.split()
    638         self._plotter.palette(color=0,linestyle=0,linestyles=linestyles)
     714        #if isinstance(linestyles,str):
     715        #    linestyles = linestyles.split()
     716        #self._plotter.palette(color=0,linestyle=0,linestyles=linestyles)
     717        self._linestyles = linestyles
    639718        if isinstance(linewidth, float) or isinstance(linewidth, int):
    640719            from matplotlib import rc as rcp
     
    707786        If the spectrum is flagged no line will be drawn in that location.
    708787        """
     788        errmsg = "Cannot plot spectral lines. Need to plot scantable first."
     789        self._assert_plotter(action="halt",errmsg=errmsg)
    709790        if not self._data:
    710791            raise RuntimeError("No scantable has been plotted yet.")
     
    784865             dpi:         The dpi of the output non-ps plot
    785866        """
     867        errmsg = "Cannot save figure. Need to plot first."
     868        self._assert_plotter(action="halt",errmsg=errmsg)
     869       
    786870        self._plotter.save(filename,orientation,dpi)
    787871        return
     
    791875        """
    792876        Set a plotting mask for a specific polarization.
    793         This is useful for masking out "noise" Pangle outside a source.
     877        This is useful for masking out 'noise' Pangle outside a source.
    794878        Parameters:
    795879             mask:           a mask from scantable.create_mask
     
    800884        Example:
    801885             select = selector()
    802              select.setpolstrings("Pangle")
     886             select.setpolstrings('Pangle')
    803887             plotter.set_mask(mymask, select)
    804888        """
     
    12561340        PL.ion()
    12571341        PL.draw()
    1258         PL.gcf().show()
     1342        if matplotlib.get_backend() == 'Qt4Agg': PL.gcf().show()
    12591343        if (self._outfile is not None):
    12601344           PL.savefig(self._outfile)
     
    12951379        [xmin,xmax,ymin,ymax] = PL.axis()
    12961380        PL.axis([xmax,xmin,ymin,ymax])
    1297         #PL.ion()
     1381        PL.ion()
    12981382        PL.draw()
    1299         PL.gcf().show()
     1383        if matplotlib.get_backend() == 'Qt4Agg': PL.gcf().show()
    13001384        if (self._outfile is not None):
    13011385           PL.savefig(self._outfile)
     
    13051389    @asaplog_post_dec
    13061390    def plottp(self, scan=None, outfile=None):
    1307         if self._plotter.is_dead:
    1308             if self.casabar_exists():
    1309                 del self._plotter.figmgr.casabar
    1310             self._plotter = self._newplotter()
    1311             self._plotter.figmgr.casabar=self._new_custombar()
     1391        self._assert_plotter(action="reload")
    13121392        self._plotter.hold()
    13131393        self._plotter.clear()
     
    13991479        See the method help for detailed information.
    14001480        """
     1481        self._assert_plotter(action="reload")
    14011482        self._plotter.text(*args, **kwargs)
    14021483    # end matplotlib.Figure.text forwarding function
     
    14371518
    14381519        if plot:
     1520            errmsg = "Can plot header only after the first call to plot()."
     1521            self._assert_plotter(action="halt",errmsg=errmsg)
    14391522            self._plotter.hold()
    14401523            self._header_plot(headstr,fontsize=fontsize)
     
    14691552            asaplog.push("No header has been plotted. Exit without any operation")
    14701553            asaplog.post("WARN")
    1471         else:
     1554        elif self._assert_plotter(action="status"):
    14721555            self._plotter.hold()
    14731556            for textobj in self._headtext['textobj']:
Note: See TracChangeset for help on using the changeset viewer.