<commit_before>import matplotlib
import matplotlib.pyplot
import matplotlib.figure
import itertools
from config import *
import numpy as np

interactive_help_message = """
Interactive key commands for plotter.  An additional help message may appear if
you have initiated the fitter.
'?' - bring up this message
'f' - initiate the fitter 
'b' - initiate the baseliner 
"""

class Plotter(object):
    """
    Class to plot a spectrum
    """


    def __init__(self, Spectrum, autorefresh=True, title="", ylabel="",
            xlabel="", silent=False, **kwargs):
        self.figure = None
        self.axis = None
        self.Spectrum = Spectrum

        # plot parameters
        self.offset = 0.0 # vertical offset
        self.autorefresh = autorefresh
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.title  = title
        self.errorplot = None
        self.plotkwargs = kwargs
        self.xmax = None
        self.xmin = None
        self.ymax = None
        self.ymin = None
        self.keyclick = None
        self.silent = silent

        self._xclick1 = None
        self._xclick2 = None

    def __call__(self, figure=None, axis=None, clear=True, autorefresh=None, **kwargs):
        """
        Plot a spectrum
        
        Keywords:
        figure - either a matplotlib figure instance or a figure number
            to pass into pyplot.figure.  
        axis - Alternative to figure, can pass an axis instance and use
            it as the plotting canvas
        clear - Clear the axis before plotting?
        """

        # figure out where to put the plot
        if isinstance(figure,matplotlib.figure.Figure):
            self.figure = figure
            self.axis = self.figure.gca()
        elif type(figure) is int:
            self.figure = matplotlib.pyplot.figure(figure)
            self.axis = self.figure.gca()
        elif self.figure is None:
            if isinstance(axis,matplotlib.axes.Axes):
                self.axis = axis
                self.figure = axis.figure
            else:
                self.figure = matplotlib.pyplot.figure()

        if self.keyclick is None:
            self.keyclick = self.figure.canvas.mpl_connect('key_press_event',self.parse_keys)

        if axis is not None:
            self.figure.canvas.mpl_disconnect(self.keyclick)
            self.axis = axis
            self.figure = axis.figure
            self.keyclick = self.figure.canvas.mpl_connect('key_press_event',self.parse_keys)
        elif len(self.figure.axes) > 0 and self.axis is None:
            self.axis = self.figure.axes[0] # default to first axis
        elif self.axis is None:
            self.axis = self.figure.gca()


        if clear: self.axis.clear()

        if autorefresh is not None:
            self.autorefresh = autorefresh

        self.plotkwargs = kwargs

        self.plot(**kwargs)

    def plot(self, offset=0.0, color='k', linestyle='steps-mid', linewidth=0.5,
            errstyle=None, erralpha=0.2, silent=None, **kwargs):
        """
        Plot the spectrum!

        Tries to automatically find a reasonable plotting range if one is not set.  

        offset - vertical offset to add to the spectrum before plotting.  Useful if you
        want to overlay multiple spectra on a single plot

        color - default to plotting spectrum in black

        linestyle - histogram-style plotting
        linewidth - narrow lines are helpful when histo-plotting
        xmin/xmax/ymin/ymax - override defaults for plot range.  Once set, these parameters
        are sticky (i.e., replotting will use the same ranges)

        reset_[xy]limits - Reset the limits to "sensible defaults" 

        ypeakscale - Scale up the Y maximum value.  Useful to keep the
        annotations away from the data.

        errstyle - can be "fill", which draws partially transparent boxes around the data to show
            the error region, or "bars" which draws standard errorbars
        """

        if self.axis is None:
            raise Exception("You must call the Plotter class to initiate the canvas before plotting.")

        self.offset += offset

        self.label(**kwargs)
        for arg in ['title','xlabel','ylabel']:
            if kwargs.has_key(arg): kwargs.pop(arg)

        reset_kwargs = {}
        for arg in ['xmin','xmax','ymin','ymax','reset_xlimits','reset_ylimits','ypeakscale']:
            if kwargs.has_key(arg): reset_kwargs[arg] = kwargs.pop(arg)

        self._spectrumplot = self.axis.plot(self.Spectrum.xarr,
                self.Spectrum.data+self.offset, color=color,
                linestyle=linestyle, linewidth=linewidth, **kwargs)

        if errstyle is not None:
            if errstyle == 'fill':
                order = -1 if self.Spectrum.xarr[-1] < self.Spectrum.xarr[0] else 1
                self.errorplot = [self.axis.fill_between(steppify(self.Spectrum.xarr[::order],isX=True),
                    steppify((self.Spectrum.data+self.offset-self.Spectrum.error)[::order]),
                    steppify((self.Spectrum.data+self.offset+self.Spectrum.error)[::order]),
                    facecolor=color, alpha=erralpha, **kwargs)]
            elif errstyle == 'bars':
                self.errorplot = self.axis.errorbar(self.Spectrum.xarr, self.Spectrum.data+self.offset,
                        yerr=self.Spectrum.error, ecolor=color, fmt=None,
                        **kwargs)

        if silent is not None:
            self.silent = silent

        self.reset_limits(**reset_kwargs)

        if self.autorefresh: self.refresh()
    
    def reset_limits(self,xmin=None, xmax=None, ymin=None, ymax=None,
            reset_xlimits=False, reset_ylimits=False, ypeakscale=1.2,
            silent=None, **kwargs):
        """
        Automatically or manually reset the plot limits
        """

        if silent is not None:
            self.silent = silent

        if (self.Spectrum.xarr.max() < self.xmin or self.Spectrum.xarr.min() > self.xmax 
                or reset_xlimits):
            if not self.silent: print "Resetting X-axis min/max because the plot is out of bounds."
            self.xmin = None
            self.xmax = None
        if xmin is not None: self.xmin = xmin
        elif self.xmin is None: self.xmin=self.Spectrum.xarr.min()
        if xmax is not None: self.xmax = xmax
        elif self.xmax is None: self.xmax=self.Spectrum.xarr.max()
        self.axis.set_xlim(self.xmin,self.xmax)

        xpixmin = np.argmin(np.abs(self.Spectrum.xarr-self.xmin))
        xpixmax = np.argmin(np.abs(self.Spectrum.xarr-self.xmax))
        if xpixmin>xpixmax: xpixmin,xpixmax = xpixmax,xpixmin
        elif xpixmin == xpixmax:
            if not self.silent: print "ERROR: the X axis limits specified were invalid.  Resetting."
            self.reset_limits(reset_xlimits=True, ymin=ymin, ymax=ymax, reset_ylimits=reset_ylimits, ypeakscale=ypeakscale, **kwargs)
            return
        
        if (self.Spectrum.data.max() < self.ymin or self.Spectrum.data.min() > self.ymax
                or reset_ylimits):
            if not self.silent: print "Resetting Y-axis min/max because the plot is out of bounds."
            self.ymin = None
            self.ymax = None
        if ymin is not None: self.ymin = ymin
        elif self.ymin is None: self.ymin=np.nanmin(self.Spectrum.data[xpixmin:xpixmax])
        if ymax is not None: self.ymax = ymax
        elif self.ymax is None: self.ymax=(np.nanmax(self.Spectrum.data[xpixmin:xpixmax])-self.ymin) * ypeakscale + self.ymin
        self.axis.set_ylim(self.ymin+self.offset,self.ymax+self.offset)
        

    def label(self, title=None, xlabel=None, ylabel=None, **kwargs):
   
        if title is not None:
            self.title = title
        elif hasattr(self.Spectrum,'specname'):
            self.title = self.Spectrum.specname
        if self.title is not "":
            self.axis.set_title(self.title)

        if xlabel is not None:
            self.xlabel = xlabel
        elif isinstance(self.Spectrum.xarr.xtype,str):
            self.xlabel = self.Spectrum.xarr.xtype
            if isinstance(self.Spectrum.xarr.units,str):
                self.xlabel += " ("+self.Spectrum.xarr.units+")"
        if self.xlabel is not None:
            self.axis.set_xlabel(self.xlabel)

        if ylabel is not None:
            self.ylabel=ylabel
            self.axis.set_ylabel(self.ylabel)
        elif self.Spectrum.units in ['Ta*','Tastar','K']:
            self.axis.set_ylabel("$T_A^*$ (K)")
        elif self.Spectrum.units == 'mJy':
            self.axis.set_ylabel("$S_\\nu$ (mJy)")<commit_msg>added "axis=0" to nanmin/nanmax.  I have no idea why I had to do this, but it suddenly started being required on my latest install of numpy in order to prevent those numpy functions from returning iterators<commit_after>import matplotlib
import matplotlib.pyplot
import matplotlib.figure
import itertools
from config import *
import numpy as np

interactive_help_message = """
Interactive key commands for plotter.  An additional help message may appear if
you have initiated the fitter.
'?' - bring up this message
'f' - initiate the fitter 
'b' - initiate the baseliner 
"""

class Plotter(object):
    """
    Class to plot a spectrum
    """


    def __init__(self, Spectrum, autorefresh=True, title="", ylabel="",
            xlabel="", silent=False, **kwargs):
        self.figure = None
        self.axis = None
        self.Spectrum = Spectrum

        # plot parameters
        self.offset = 0.0 # vertical offset
        self.autorefresh = autorefresh
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.title  = title
        self.errorplot = None
        self.plotkwargs = kwargs
        self.xmax = None
        self.xmin = None
        self.ymax = None
        self.ymin = None
        self.keyclick = None
        self.silent = silent

        self._xclick1 = None
        self._xclick2 = None

    def __call__(self, figure=None, axis=None, clear=True, autorefresh=None, **kwargs):
        """
        Plot a spectrum
        
        Keywords:
        figure - either a matplotlib figure instance or a figure number
            to pass into pyplot.figure.  
        axis - Alternative to figure, can pass an axis instance and use
            it as the plotting canvas
        clear - Clear the axis before plotting?
        """

        # figure out where to put the plot
        if isinstance(figure,matplotlib.figure.Figure):
            self.figure = figure
            self.axis = self.figure.gca()
        elif type(figure) is int:
            self.figure = matplotlib.pyplot.figure(figure)
            self.axis = self.figure.gca()
        elif self.figure is None:
            if isinstance(axis,matplotlib.axes.Axes):
                self.axis = axis
                self.figure = axis.figure
            else:
                self.figure = matplotlib.pyplot.figure()

        if self.keyclick is None:
            self.keyclick = self.figure.canvas.mpl_connect('key_press_event',self.parse_keys)

        if axis is not None:
            self.figure.canvas.mpl_disconnect(self.keyclick)
            self.axis = axis
            self.figure = axis.figure
            self.keyclick = self.figure.canvas.mpl_connect('key_press_event',self.parse_keys)
        elif len(self.figure.axes) > 0 and self.axis is None:
            self.axis = self.figure.axes[0] # default to first axis
        elif self.axis is None:
            self.axis = self.figure.gca()


        if clear: self.axis.clear()

        if autorefresh is not None:
            self.autorefresh = autorefresh

        self.plotkwargs = kwargs

        self.plot(**kwargs)

    def plot(self, offset=0.0, color='k', linestyle='steps-mid', linewidth=0.5,
            errstyle=None, erralpha=0.2, silent=None, **kwargs):
        """
        Plot the spectrum!

        Tries to automatically find a reasonable plotting range if one is not set.  

        offset - vertical offset to add to the spectrum before plotting.  Useful if you
        want to overlay multiple spectra on a single plot

        color - default to plotting spectrum in black

        linestyle - histogram-style plotting
        linewidth - narrow lines are helpful when histo-plotting
        xmin/xmax/ymin/ymax - override defaults for plot range.  Once set, these parameters
        are sticky (i.e., replotting will use the same ranges)

        reset_[xy]limits - Reset the limits to "sensible defaults" 

        ypeakscale - Scale up the Y maximum value.  Useful to keep the
        annotations away from the data.

        errstyle - can be "fill", which draws partially transparent boxes around the data to show
            the error region, or "bars" which draws standard errorbars
        """

        if self.axis is None:
            raise Exception("You must call the Plotter class to initiate the canvas before plotting.")

        self.offset += offset

        self.label(**kwargs)
        for arg in ['title','xlabel','ylabel']:
            if kwargs.has_key(arg): kwargs.pop(arg)

        reset_kwargs = {}
        for arg in ['xmin','xmax','ymin','ymax','reset_xlimits','reset_ylimits','ypeakscale']:
            if kwargs.has_key(arg): reset_kwargs[arg] = kwargs.pop(arg)

        self._spectrumplot = self.axis.plot(self.Spectrum.xarr,
                self.Spectrum.data+self.offset, color=color,
                linestyle=linestyle, linewidth=linewidth, **kwargs)

        if errstyle is not None:
            if errstyle == 'fill':
                order = -1 if self.Spectrum.xarr[-1] < self.Spectrum.xarr[0] else 1
                self.errorplot = [self.axis.fill_between(steppify(self.Spectrum.xarr[::order],isX=True),
                    steppify((self.Spectrum.data+self.offset-self.Spectrum.error)[::order]),
                    steppify((self.Spectrum.data+self.offset+self.Spectrum.error)[::order]),
                    facecolor=color, alpha=erralpha, **kwargs)]
            elif errstyle == 'bars':
                self.errorplot = self.axis.errorbar(self.Spectrum.xarr, self.Spectrum.data+self.offset,
                        yerr=self.Spectrum.error, ecolor=color, fmt=None,
                        **kwargs)

        if silent is not None:
            self.silent = silent

        self.reset_limits(**reset_kwargs)

        if self.autorefresh: self.refresh()
    
    def reset_limits(self,xmin=None, xmax=None, ymin=None, ymax=None,
            reset_xlimits=False, reset_ylimits=False, ypeakscale=1.2,
            silent=None, **kwargs):
        """
        Automatically or manually reset the plot limits
        """

        if silent is not None:
            self.silent = silent

        if (self.Spectrum.xarr.max() < self.xmin or self.Spectrum.xarr.min() > self.xmax 
                or reset_xlimits):
            if not self.silent: print "Resetting X-axis min/max because the plot is out of bounds."
            self.xmin = None
            self.xmax = None
        if xmin is not None: self.xmin = xmin
        elif self.xmin is None: self.xmin=self.Spectrum.xarr.min()
        if xmax is not None: self.xmax = xmax
        elif self.xmax is None: self.xmax=self.Spectrum.xarr.max()
        self.axis.set_xlim(self.xmin,self.xmax)

        xpixmin = np.argmin(np.abs(self.Spectrum.xarr-self.xmin))
        xpixmax = np.argmin(np.abs(self.Spectrum.xarr-self.xmax))
        if xpixmin>xpixmax: xpixmin,xpixmax = xpixmax,xpixmin
        elif xpixmin == xpixmax:
            if not self.silent: print "ERROR: the X axis limits specified were invalid.  Resetting."
            self.reset_limits(reset_xlimits=True, ymin=ymin, ymax=ymax, reset_ylimits=reset_ylimits, ypeakscale=ypeakscale, **kwargs)
            return
        
        if (self.Spectrum.data.max() < self.ymin or self.Spectrum.data.min() > self.ymax
                or reset_ylimits):
            if not self.silent: print "Resetting Y-axis min/max because the plot is out of bounds."
            self.ymin = None
            self.ymax = None
        if ymin is not None: self.ymin = ymin
        elif self.ymin is None: self.ymin=np.nanmin(self.Spectrum.data[xpixmin:xpixmax],axis=0)
        if ymax is not None: self.ymax = ymax
        elif self.ymax is None: self.ymax=(np.nanmax(self.Spectrum.data[xpixmin:xpixmax],axis=0)-self.ymin) * ypeakscale + self.ymin
        self.axis.set_ylim(self.ymin+self.offset,self.ymax+self.offset)
        

    def label(self, title=None, xlabel=None, ylabel=None, **kwargs):
   
        if title is not None:
            self.title = title
        elif hasattr(self.Spectrum,'specname'):
            self.title = self.Spectrum.specname
        if self.title is not "":
            self.axis.set_title(self.title)

        if xlabel is not None:
            self.xlabel = xlabel
        elif isinstance(self.Spectrum.xarr.xtype,str):
            self.xlabel = self.Spectrum.xarr.xtype
            if isinstance(self.Spectrum.xarr.units,str):
                self.xlabel += " ("+self.Spectrum.xarr.units+")"
        if self.xlabel is not None:
            self.axis.set_xlabel(self.xlabel)

        if ylabel is not None:
            self.ylabel=ylabel
            self.axis.set_ylabel(self.ylabel)
        elif self.Spectrum.units in ['Ta*','Tastar','K']:
            self.axis.set_ylabel("$T_A^*$ (K)")
        elif self.Spectrum.units == 'mJy':
            self.axis.set_ylabel("$S_\\nu$ (mJy)")
{'fraction_non_alphanumeric': 0.10079697265065077, 'fraction_numerical': 0.002236110314775529, 'mean_word_length': 2.1140867702196036, 'pattern_counts': {'":': 2, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7125250', 'n_tokens_mistral': 5373, 'n_tokens_neox': 5108, 'n_words': 1370}