示例#1
0
    def _set_lim_and_transforms(self):
        self.transAxes = BboxTransformTo(self.bbox)

        # Transforms the x and y axis separately by a scale factor
        # It is assumed that this part will have non-linear components
        self.transScale = TransformWrapper(IdentityTransform())

        # A (possibly non-linear) projection on the (already scaled)
        # data.  This one is aware of rmin
        self.transProjection = self.PolarTransform(self)

        # This one is not aware of rmin
        self.transPureProjection = self.PolarTransform()

        # An affine transformation on the data, generally to limit the
        # range of the axes
        self.transProjectionAffine = self.PolarAffine(self.transScale,
                                                      self.viewLim)

        # The complete data transformation stack -- from data all the
        # way to display coordinates
        self.transData = self.transScale + self.transProjection + \
            (self.transProjectionAffine + self.transAxes)

        # This is the transform for theta-axis ticks.  It is
        # equivalent to transData, except it always puts r == 1.0 at
        # the edge of the axis circle.
        self._xaxis_transform = (self.transPureProjection + self.PolarAffine(
            IdentityTransform(), Bbox.unit()) + self.transAxes)
        # The theta labels are moved from radius == 0.0 to radius == 1.1
        self._theta_label1_position = Affine2D().translate(0.0, 1.1)
        self._xaxis_text1_transform = (self._theta_label1_position +
                                       self._xaxis_transform)
        self._theta_label2_position = Affine2D().translate(0.0, 1.0 / 1.1)
        self._xaxis_text2_transform = (self._theta_label2_position +
                                       self._xaxis_transform)

        # This is the transform for r-axis ticks.  It scales the theta
        # axis so the gridlines from 0.0 to 1.0, now go from 0.0 to
        # 2pi.
        self._yaxis_transform = (Affine2D().scale(np.pi * 2.0, 1.0) +
                                 self.transData)
        # The r-axis labels are put at an angle and padded in the r-direction
        self._r_label1_position = ScaledTranslation(
            22.5, self._rpad,
            blended_transform_factory(Affine2D(),
                                      BboxTransformToMaxOnly(self.viewLim)))
        self._yaxis_text1_transform = (self._r_label1_position +
                                       Affine2D().scale(1.0 / 360.0, 1.0) +
                                       self._yaxis_transform)
        self._r_label2_position = ScaledTranslation(
            22.5, -self._rpad,
            blended_transform_factory(Affine2D(),
                                      BboxTransformToMaxOnly(self.viewLim)))
        self._yaxis_text2_transform = (self._r_label2_position +
                                       Affine2D().scale(1.0 / 360.0, 1.0) +
                                       self._yaxis_transform)
示例#2
0
def add_letter(ax: Axes = None, offset: float = 0, offset2: float = 0, letter: str = None):
    """ add a letter indicating which subplot it is to the given figure """
    global letter_index
    from matplotlib.transforms import Affine2D, ScaledTranslation

    # get the axes
    if ax is None:
        ax = plt.gca()

    # get the figure
    fig = ax.figure

    # get the font properties for figure letters
    font = get_letter_font_prop()

    # if no letter is given
    if letter is None:
        # use the letter_format from the font
        letter = font.letter_format
        # and add a letter given the current letter_index
        letter = letter.replace("a", chr(ord("a") + letter_index))
        letter = letter.replace("A", chr(ord("A") + letter_index))
        # increase the letter index
        letter_index += 1

    # add a transform that gives the coordinates relative to the left top corner of the axes in cm
    transform = Affine2D().scale(1 / 2.54, 1 / 2.54) + fig.dpi_scale_trans + ScaledTranslation(0, 1, ax.transAxes)

    # add a text a the given position
    ax.text(-0.5+offset, offset2, letter, fontproperties=font, transform=transform, ha="center", va="bottom", picker=True)
示例#3
0
def auto_shift(offset):
    """
    Return a y-offset coordinate transform for the current axes.

    Each call to auto_shift increases the y-offset for the next line by
    the given number of points (with 72 points per inch).

    Example::

        from matplotlib import pyplot as plt
        from bumps.plotutil import auto_shift
        trans = auto_shift(plt.gca())
        plot(x, y, trans=trans)
    """
    from matplotlib.transforms import ScaledTranslation
    import pylab
    ax = pylab.gca()
    if ax.lines and hasattr(ax, '_auto_shift'):
        ax._auto_shift += offset
    else:
        ax._auto_shift = 0
    trans = pylab.gca().transData
    if ax._auto_shift:
        trans += ScaledTranslation(0, ax._auto_shift / 72.,
                                   pylab.gcf().dpi_scale_trans)
    return trans
示例#4
0
    def setup_xticklabels(self):
        """Setup the xtick labels."""

        # Labels are placed manually because this is around 25% faster than
        # using the minor ticks.

        xticks_info = self.make_xticks_info()
        self.ax1.set_xticks(xticks_info[0])

        for i in range(len(self.xlabels)):
            self.xlabels[i].remove()

        padding = ScaledTranslation(0, -5 / 72, self.dpi_scale_trans)

        self.xlabels = []
        for i in range(len(xticks_info[1])):
            new_label = self.ax1.text(xticks_info[1][i],
                                      0,
                                      xticks_info[2][i],
                                      rotation=45,
                                      va='top',
                                      ha='right',
                                      fontsize=10,
                                      transform=self.ax1.transData + padding)
            self.xlabels.append(new_label)
    def __init__(self, axes,
                 helper,
                 offset=None,
                 axis_direction="bottom",
                 **kw):
        """
        *axes* : axes
        *helper* : an AxisArtistHelper instance.
        """
        #axes is also used to follow the axis attribute (tick color, etc).

        super().__init__(**kw)

        self.axes = axes

        self._axis_artist_helper = helper

        if offset is None:
            offset = (0, 0)
        self.dpi_transform = Affine2D()
        self.offset_transform = ScaledTranslation(offset[0], offset[1],
                                                  self.dpi_transform)

        self._label_visible = True
        self._majortick_visible = True
        self._majorticklabel_visible = True
        self._minortick_visible = True
        self._minorticklabel_visible = True


        #if self._axis_artist_helper._loc in ["left", "right"]:
        if axis_direction in ["left", "right"]:
            axis_name = "ytick"
            self.axis = axes.yaxis
        else:
            axis_name = "xtick"
            self.axis = axes.xaxis


        self._axisline_style = None


        self._axis_direction = axis_direction


        self._init_line()
        self._init_ticks(axis_name, **kw)
        self._init_offsetText(axis_direction)
        self._init_label()

        self.set_zorder(self.ZORDER)

        self._rotate_label_along_line = False

        # axis direction
        self._tick_add_angle = 180.
        self._ticklabel_add_angle = 0.
        self._axislabel_add_angle = 0.
        self.set_axis_direction(axis_direction)
示例#6
0
    def __init__(self,
                 parent_axes=None,
                 transform=None,
                 coord_index=None,
                 coord_type='scalar',
                 coord_wrap=None,
                 frame=None):

        # Keep a reference to the parent axes and the transform
        self.parent_axes = parent_axes
        self.transform = transform
        self.coord_index = coord_index
        self.coord_type = coord_type
        self.frame = frame

        if coord_type == 'longitude' and coord_wrap is None:
            self.coord_wrap = 360
        elif coord_type != 'longitude' and coord_wrap is not None:
            raise NotImplementedError(
                'coord_wrap is not yet supported for non-longitude coordinates'
            )
        else:
            self.coord_wrap = coord_wrap

        # Initialize tick formatter/locator
        if coord_type == 'scalar':
            self._formatter_locator = ScalarFormatterLocator()
        elif coord_type in ['longitude', 'latitude']:
            self._formatter_locator = AngleFormatterLocator()
        else:
            raise ValueError(
                "coord_type should be one of 'scalar', 'longitude', or 'latitude'"
            )

        # Initialize ticks
        self.dpi_transform = Affine2D()
        self.offset_transform = ScaledTranslation(0, 0, self.dpi_transform)
        self.ticks = Ticks(transform=parent_axes.transData +
                           self.offset_transform)

        # Initialize tick labels
        self.ticklabels = TickLabels(
            transform=None,  # display coordinates
            figure=parent_axes.get_figure())

        # Initialize axis labels
        self.axislabels = AxisLabels(
            self.frame,
            transform=None,  # display coordinates
            figure=parent_axes.get_figure())

        # Initialize container for the grid lines
        self.grid_lines = []
        self.grid_lines_kwargs = {
            'visible': False,
            'facecolor': 'none',
            'transform': self.parent_axes.transData
        }
示例#7
0
    def __init__(self,
                 parent_axes=None,
                 parent_map=None,
                 transform=None,
                 coord_index=None,
                 coord_type='scalar',
                 coord_unit=None,
                 coord_wrap=None,
                 frame=None,
                 format_unit=None):

        # Keep a reference to the parent axes and the transform
        self.parent_axes = parent_axes
        self.parent_map = parent_map
        self.transform = transform
        self.coord_index = coord_index
        self.coord_unit = coord_unit
        self.format_unit = format_unit
        self.frame = frame

        self.set_coord_type(coord_type, coord_wrap)

        # Initialize ticks
        self.dpi_transform = Affine2D()
        self.offset_transform = ScaledTranslation(0, 0, self.dpi_transform)
        self.ticks = Ticks(transform=parent_axes.transData +
                           self.offset_transform)

        # Initialize tick labels
        self.ticklabels = TickLabels(
            self.frame,
            transform=None,  # display coordinates
            figure=parent_axes.get_figure())
        self.ticks.display_minor_ticks(rcParams['xtick.minor.visible'])
        self.minor_frequency = 5

        # Initialize axis labels
        self.axislabels = AxisLabels(
            self.frame,
            transform=None,  # display coordinates
            figure=parent_axes.get_figure())

        # Initialize container for the grid lines
        self.grid_lines = []

        # Initialize grid style. Take defaults from matplotlib.rcParams.
        # Based on matplotlib.axis.YTick._get_gridline.
        self.grid_lines_kwargs = {
            'visible': False,
            'facecolor': 'none',
            'edgecolor': rcParams['grid.color'],
            'linestyle':
            LINES_TO_PATCHES_LINESTYLE[rcParams['grid.linestyle']],
            'linewidth': rcParams['grid.linewidth'],
            'alpha': rcParams['grid.alpha'],
            'transform': self.parent_axes.transData
        }
示例#8
0
    def __init__(self,
                 axes,
                 helper,
                 offset=None,
                 major_tick_size=None,
                 major_tick_pad=None,
                 minor_tick_size=None,
                 minor_tick_pad=None,
                 **kw):
        """
        axes is also used to follow the axis attribute (tick color, etc).
        """
        super(AxisArtist, self).__init__(**kw)

        self.axes = axes

        self._axis_artist_helper = helper

        if offset is None:
            offset = (0, 0)
        self.dpi_transform = Affine2D()
        self.offset_transform = ScaledTranslation(offset[0], offset[1],
                                                  self.dpi_transform)

        self._label_visible = True
        self._majortick_visible = True
        self._majorticklabel_visible = True
        self._minortick_visible = True
        self._minorticklabel_visible = True

        if self._axis_artist_helper.label_direction in ["left", "right"]:
            axis_name = "ytick"
            self.axis = axes.yaxis
        else:
            axis_name = "xtick"
            self.axis = axes.xaxis

        if major_tick_size is None:
            self.major_tick_size = rcParams['%s.major.size' % axis_name]
        if major_tick_pad is None:
            self.major_tick_pad = rcParams['%s.major.pad' % axis_name]
        if minor_tick_size is None:
            self.minor_tick_size = rcParams['%s.minor.size' % axis_name]
        if minor_tick_pad is None:
            self.minor_tick_pad = rcParams['%s.minor.pad' % axis_name]

        self._axisline_style = None

        self._init_line()
        self._init_ticks()
        self._init_offsetText(self._axis_artist_helper.label_direction)
        self._init_label()

        self.set_zorder(self.ZORDER)

        self._rotate_label_along_line = False
示例#9
0
    def draw_figure_title(self):
        """Draw the title of the figure."""
        labelDB = LabelDatabase(self.language)
        if self.isGraphTitle:
            # Set the text and position of the title.
            if self.meteo_on:
                offset = ScaledTranslation(0, 7/72, self.dpi_scale_trans)
                self.text1.set_text(
                    labelDB.station_meteo % (self.name_meteo, self.dist))
                self.text1.set_transform(self.ax0.transAxes + offset)

            dy = 30 if self.meteo_on else 7
            offset = ScaledTranslation(0, dy/72, self.dpi_scale_trans)
            self.figTitle.set_text(labelDB.title % self.wldset['Well'])
            self.figTitle.set_transform(self.ax0.transAxes + offset)

        # Set whether the title is visible or not.
        self.text1.set_visible(self.meteo_on and self.isGraphTitle)
        self.figTitle.set_visible(self.isGraphTitle)
示例#10
0
    def __init__(self, parent_axes=None, parent_map=None, transform=None, coord_index=None,
                 coord_type='scalar', coord_unit=None, coord_wrap=None, frame=None):

        # Keep a reference to the parent axes and the transform
        self.parent_axes = parent_axes
        self.parent_map = parent_map
        self.transform = transform
        self.coord_index = coord_index
        self.coord_unit = coord_unit
        self.frame = frame

        self.set_coord_type(coord_type, coord_wrap)

        # Initialize ticks
        self.dpi_transform = Affine2D()
        self.offset_transform = ScaledTranslation(0, 0, self.dpi_transform)
        self.ticks = Ticks(transform=parent_axes.transData + self.offset_transform)

        # Initialize tick labels
        self.ticklabels = TickLabels(self.frame,
                                     transform=None,  # display coordinates
                                     figure=parent_axes.get_figure())
        self.ticks.display_minor_ticks(False)
        self.minor_frequency = 5

        # Initialize axis labels
        self.axislabels = AxisLabels(self.frame,
                                     transform=None,  # display coordinates
                                     figure=parent_axes.get_figure())

        # Initialize container for the grid lines
        self.grid_lines = []

        # Initialize grid style. Take defaults from matplotlib.rcParams.
        # Based on matplotlib.axis.YTick._get_gridline.
        #
        # Matplotlib's gridlines use Line2D, but ours use PathPatch.
        # Patches take a slightly different format of linestyle argument.
        lines_to_patches_linestyle = {'-': 'solid',
                                      '--': 'dashed',
                                      '-.': 'dashdot',
                                      ':': 'dotted',
                                      'none': 'none',
                                      'None': 'none',
                                      ' ': 'none',
                                      '': 'none'}
        self.grid_lines_kwargs = {'visible': False,
                                  'facecolor': 'none',
                                  'edgecolor': rcParams['grid.color'],
                                  'linestyle': lines_to_patches_linestyle[rcParams['grid.linestyle']],
                                  'linewidth': rcParams['grid.linewidth'],
                                  'alpha': rcParams.get('grid.alpha', 1.0),
                                  'transform': self.parent_axes.transData}
示例#11
0
    def __init__(self,
                 axes,
                 helper,
                 offset=None,
                 axis_direction="bottom",
                 **kwargs):
        """
        Parameters
        ----------
        axes : `mpl_toolkits.axisartist.axislines.Axes`
        helper : `~mpl_toolkits.axisartist.axislines.AxisArtistHelper`
        """
        #axes is also used to follow the axis attribute (tick color, etc).

        super().__init__(**kwargs)

        self.axes = axes

        self._axis_artist_helper = helper

        if offset is None:
            offset = (0, 0)
        self.offset_transform = ScaledTranslation(
            *offset,
            Affine2D().scale(1 / 72)  # points to inches.
            + self.axes.figure.dpi_scale_trans)

        if axis_direction in ["left", "right"]:
            axis_name = "ytick"
            self.axis = axes.yaxis
        else:
            axis_name = "xtick"
            self.axis = axes.xaxis

        self._axisline_style = None
        self._axis_direction = axis_direction

        self._init_line()
        self._init_ticks(axis_name, **kwargs)
        self._init_offsetText(axis_direction)
        self._init_label()

        self.set_zorder(self.ZORDER)

        self._rotate_label_along_line = False

        # axis direction
        self._tick_add_angle = 180.
        self._ticklabel_add_angle = 0.
        self._axislabel_add_angle = 0.
        self.set_axis_direction(axis_direction)
示例#12
0
def plotEllipse(ax,
                x,
                y,
                semi_major,
                semi_minor,
                angle=0,
                fill=False,
                lw=3,
                log=False,
                **kwargs):
    from matplotlib.patches import Ellipse
    from matplotlib.transforms import ScaledTranslation

    if log:
        # use the axis scale tform to figure out how far to translate
        circ_offset = ScaledTranslation(x, y, ax.transScale)

        # construct the composite tform
        circ_tform = circ_offset + ax.transLimits + ax.transAxes

        # create the circle centred on the origin, apply the composite tform
        circ = Ellipse((0, 0),
                       2 * semi_major,
                       2 * semi_minor,
                       angle=angle,
                       fill=fill,
                       lw=lw,
                       transform=circ_tform,
                       **kwargs)
        ax.add_artist(circ)

    else:
        return ax.add_artist(
            Ellipse((x, y),
                    semi_major,
                    semi_minor,
                    angle=angle,
                    fill=fill,
                    lw=lw,
                    **kwargs))
示例#13
0
    def setNode(self, node):
        if self.artist_ != None:
            self.artist_[0].remove()
            self.artist_[1].remove()

        if self.parent_ == None: return

        [m11, m12, m13, m21, m22, m23] = node.getTransformation()
        #https://matplotlib.org/3.1.0/tutorials/advanced/transforms_tutorial.html
        mtx = np.array([[m11, m12, 0], [m21, m22, 0], [0, 0, 1]])
        refcs = Affine2D(matrix=mtx)
        xx, xy = refcs.transform((0.0, 1.0))
        yx, yy = refcs.transform((1.0, 0.0))
        self.ox_ = m13
        self.oy_ = m23

        axes = self.parent_.axes_
        figure = self.parent_.fig_
        trans = (figure.dpi_scale_trans +
                 ScaledTranslation(self.ox_, self.oy_, axes.transData))
        cx = axes.arrow(0,
                        0,
                        xx,
                        xy,
                        head_width=0.1,
                        head_length=0.2,
                        fc='b',
                        ec='b',
                        transform=trans)
        cy = axes.arrow(0,
                        0,
                        yx,
                        yy,
                        head_width=0.1,
                        head_length=0.2,
                        fc='r',
                        ec='r',
                        transform=trans)
        self.artist_ = (cx, cy)
示例#14
0
    def plot_legend(self):
        """Plot the legend of the figure."""
        ax = self.figure.axes[2]

        # bbox transform :

        padding = ScaledTranslation(5 / 72, -5 / 72,
                                    self.figure.dpi_scale_trans)
        transform = ax.transAxes + padding

        # Define proxy artists :

        colors = ColorsReader()
        colors.load_colors_db()

        rec1 = Rectangle((0, 0), 1, 1, fc=colors.rgb['Snow'], ec='none')
        rec2 = Rectangle((0, 0), 1, 1, fc=colors.rgb['Rain'], ec='none')

        # Define the legend labels and markers :

        lines = [ax.lines[0], ax.lines[1], ax.lines[2], rec2, rec1]
        labels = [
            self.fig_labels.Tmax, self.fig_labels.Tavg, self.fig_labels.Tmin,
            self.fig_labels.rain, self.fig_labels.snow
        ]

        # Plot the legend :

        leg = ax.legend(lines,
                        labels,
                        numpoints=1,
                        fontsize=13,
                        borderaxespad=0,
                        loc='upper left',
                        borderpad=0,
                        bbox_to_anchor=(0, 1),
                        bbox_transform=transform)
        leg.draw_frame(False)
示例#15
0
    def generate_hydrograph(self, wxdset=None, wldset=None):
        wxdset = self.wxdset if wxdset is None else wxdset
        wldset = self.wldset if wldset is None else wldset

        # Reinit the figure.
        self.clf()
        self.set_size_inches(self.fwidth, self.fheight, forward=True)
        self.setup_figure_frame()

        # Assign Weather Data.
        if self.wxdset is None:
            self.name_meteo = ''
            self.TIMEmeteo = np.array([])
            self.TMAX = np.array([])
            self.PTOT = np.array([])
            self.RAIN = np.array([])
        else:
            self.name_meteo = wxdset.metadata['Station Name']
            self.TIMEmeteo = datetimeindex_to_xldates(wxdset.data.index)
            self.TMAX = wxdset.data['Tmax'].values
            self.PTOT = wxdset.data['Ptot'].values
            self.RAIN = wxdset.data['Rain'].values

        # Resample Data in Bins :

        self.resample_bin()

        # -------------------------------------------------- AXES CREATION ----

        # ---- Time (host) ----

        # Also holds the gridlines.

        self.ax1 = self.add_axes([0, 0, 1, 1], frameon=False)
        self.ax1.set_zorder(100)

        # ---- Frame ----

        # Only used to display the frame so it is always on top.

        self.ax0 = self.add_axes(self.ax1.get_position(), frameon=True)
        self.ax0.patch.set_visible(False)
        self.ax0.set_zorder(self.ax1.get_zorder() + 200)
        self.ax0.tick_params(bottom=False, top=False, left=False, right=False,
                             labelbottom=False, labelleft=False)

        # ---- Water Levels ----

        self.ax2 = self.add_axes(self.ax1.get_position(), frameon=False,
                                 label='axes2', sharex=self.ax1)
        self.ax2.set_zorder(self.ax1.get_zorder() + 100)
        self.ax2.yaxis.set_ticks_position('left')
        self.ax2.yaxis.set_label_position('left')
        self.ax2.tick_params(axis='y', direction='out', labelsize=10)

        # ---- Precipitation ----

        self.ax3 = self.add_axes(self.ax1.get_position(), frameon=False,
                                 label='axes3', sharex=self.ax1)
        self.ax3.set_zorder(self.ax1.get_zorder() + 150)
        self.ax3.set_navigate(False)

        # ---- Air Temperature ----

        self.ax4 = self.add_axes(self.ax1.get_position(), frameon=False,
                                 label='axes4', sharex=self.ax1)
        self.ax4.set_zorder(self.ax1.get_zorder() + 150)
        self.ax4.set_navigate(False)
        self.ax4.set_axisbelow(True)
        self.ax4.tick_params(bottom=False, top=False, left=False,
                             right=False, labelbottom=False, labelleft=False)

        if self.meteo_on is False:
            self.ax3.set_visible(False)
            self.ax4.set_visible(False)

        # ---- Bottom Graph Grid ----

        self.axLow = self.add_axes(self.ax1.get_position(), frameon=False,
                                   label='axLow', sharex=self.ax1)
        self.axLow.patch.set_visible(False)
        self.axLow.set_zorder(self.ax2.get_zorder() - 50)
        self.axLow.tick_params(bottom=False, top=False, left=False,
                               right=False, labelbottom=False, labelleft=False)

        self.setup_waterlvl_scale()

        # -------------------------------------------------- Remove Spines ----

        for axe in self.axes[2:]:
            for loc in axe.spines:
                axe.spines[loc].set_visible(False)

        # ------------------------------------------------- Update margins ----

        self.bottom_margin = 0.75
        self.set_margins()  # set margins for all the axes

        # --------------------------------------------------- FIGURE TITLE ----

        # Calculate horizontal distance between weather station and
        # observation well.
        if self.wxdset is not None:
            self.dist = calc_dist_from_coord(
                wldset['Latitude'], wldset['Longitude'],
                wxdset.metadata['Latitude'], wxdset.metadata['Longitude'])
        else:
            self.dist = 0

        # Weather Station name and distance to the well
        self.text1 = self.ax0.text(0, 1, '', va='bottom', ha='left',
                                   rotation=0, fontsize=10)

        # Well Name
        self.figTitle = self.ax0.text(0, 1, '', fontsize=18,
                                      ha='left', va='bottom')

        self.draw_figure_title()

        # ----------------------------------------------------------- TIME ----

        self.xlabels = []
        self.set_time_scale()

        self.ax1.xaxis.set_ticklabels([])
        self.ax1.xaxis.set_ticks_position('bottom')
        self.ax1.tick_params(axis='x', direction='out')
        self.ax1.tick_params(top=False, left=False, right=False,
                             labeltop=False, labelleft=False, labelright=False)

        self.set_gridLines()

        # ---- Init water level artists

        # Continuous Line Datalogger
        self.l1_ax2, = self.ax2.plot(
            [], [], '-', zorder=10, lw=1, color=self.colorsDB.rgb['WL solid'])

        # Data Point Datalogger
        self.l2_ax2, = self.ax2.plot(
            [], [], '.', color=self.colorsDB.rgb['WL data'], markersize=5)

        # Manual Mesures
        self.h_WLmes, = self.ax2.plot(
            [], [], 'o', zorder=15, label='Manual measures',
            markerfacecolor='none', markersize=5, markeredgewidth=1.5,
            mec=self.colorsDB.rgb['WL obs'])

        # Predicted Recession Curves
        self._mrc_plt, = self.ax2.plot(
            [], [], color='red', lw=1.5, dashes=[5, 3], zorder=100,
            alpha=0.85)

        # Predicted GLUE water levels
        self.glue_plt, = self.ax2.plot([], [])

        self.draw_waterlvl()
        self.draw_glue_wl()
        self.draw_mrc_wl()

        # ---- Init weather artists

        # ---- PRECIPITATION -----

        self.ax3.yaxis.set_ticks_position('right')
        self.ax3.yaxis.set_label_position('right')
        self.ax3.tick_params(axis='y', direction='out', labelsize=10)

        self.PTOT_bar, = self.ax3.plot([], [])
        self.RAIN_bar, = self.ax3.plot([], [])
        self.baseline, = self.ax3.plot(
            [self.TIMEmin, self.TIMEmax], [0, 0], 'k')

        # ---- AIR TEMPERATURE -----

        TEMPmin = -40
        TEMPscale = 20
        TEMPmax = 40

        self.ax4.axis(ymin=TEMPmin, ymax=TEMPmax)

        yticks_position = np.array([TEMPmin, 0, TEMPmax])
        yticks_position = np.arange(
            TEMPmin, TEMPmax + TEMPscale / 2, TEMPscale)
        self.ax4.set_yticks(yticks_position)
        self.ax4.yaxis.set_ticks_position('left')
        self.ax4.tick_params(axis='y', direction='out', labelsize=10)
        self.ax4.yaxis.set_label_position('left')

        self.ax4.set_yticks([-20, 20], minor=True)
        self.ax4.tick_params(axis='y', which='minor', length=0)
        self.ax4.xaxis.set_ticklabels([], minor=True)

        self.l1_ax4, = self.ax4.plot([], [])  # fill shape
        self.l2_ax4, = self.ax4.plot(
            [], [], color='black', lw=1)  # contour line

        # ---- MISSING VALUES MARKERS

        # Precipitation.
        vshift = 5 / 72
        offset = ScaledTranslation(0, vshift, self.dpi_scale_trans)
        if self.wxdset is not None:
            t1 = pd.DataFrame(self.wxdset.missing_value_indexes['Ptot'],
                              index=self.wxdset.missing_value_indexes['Ptot'],
                              columns=['datetime'])
            t2 = pd.DataFrame(self.wxdset.missing_value_indexes['Ptot'] +
                              pd.Timedelta('1 days'),
                              self.wxdset.missing_value_indexes['Ptot'] +
                              pd.Timedelta('1 days'),
                              columns=['datetime'])
            time = datetimeindex_to_xldates(pd.DatetimeIndex(
                pd.concat([t1, t2], axis=0)
                .drop_duplicates()
                .resample('1D')
                .asfreq()
                ['datetime']
                ))
            y = np.ones(len(time)) * self.ax4.get_ylim()[0]
        else:
            time, y = [], []
        self.lmiss_ax4, = self.ax4.plot(
            time, y, ls='-', solid_capstyle='projecting', lw=1, c='red',
            transform=self.ax4.transData + offset)

        # Air Temperature.
        offset = ScaledTranslation(0, -vshift, self.dpi_scale_trans)
        if self.wxdset is not None:
            t1 = pd.DataFrame(self.wxdset.missing_value_indexes['Tmax'],
                              index=self.wxdset.missing_value_indexes['Tmax'],
                              columns=['datetime'])
            t2 = pd.DataFrame(self.wxdset.missing_value_indexes['Tmax'] +
                              pd.Timedelta('1 days'),
                              self.wxdset.missing_value_indexes['Tmax'] +
                              pd.Timedelta('1 days'),
                              columns=['datetime'])
            time = datetimeindex_to_xldates(pd.DatetimeIndex(
                pd.concat([t1, t2], axis=0)
                .drop_duplicates()
                .resample('1D')
                .asfreq()
                ['datetime']
                ))
            y = np.ones(len(time)) * self.ax4.get_ylim()[1]
        else:
            time, y = [], []
        self.ax4.plot(time, y, ls='-', solid_capstyle='projecting',
                      lw=1., c='red', transform=self.ax4.transData + offset)

        self.draw_weather()
        self.draw_ylabels()
        self.setup_legend()

        self.__isHydrographExists = True
示例#16
0
def fnoise_plots(mode,ifeed):
    filelist = np.loadtxt(sys.argv[1],dtype=str)
    obsid = np.array([int(f.split('-')[1]) for f in filelist])
    filelist = filelist[np.argsort(obsid)]
    obsid = np.sort(obsid)

    fnoise = np.zeros(filelist.size)
    enoise = np.zeros(filelist.size)
    feed = None
    isfg4 = np.zeros(filelist.size,dtype=bool)
    dist = np.zeros(filelist.size)

    fnoise_power = np.zeros((filelist.size,64*4))
    alphas = np.zeros((filelist.size,64*4))

    for ifile, filename in enumerate(filelist):
        
        try:
            data = h5py.File(filename,'r')
        except OSError:
            print('{} cannot be opened (Resource unavailable)'.format(filename))
            fnoise[ifile] = np.nan

        if mode.lower() in data['level1/comap'].attrs['source'].decode('utf-8').lower():
            isfg4[ifile] = True

        try:
            fits = data['level2/fnoise_fits'][ifeed,:,:,:]
            fnoise[ifile] = np.median(fits[:,1])
            enoise[ifile] = np.sqrt(np.median(np.abs(fits[:,1]-fnoise[ifile])**2))*1.4826
            ps = data['level2/powerspectra'][ifeed,:,:,:]
            rms = data['level2/wnoise_auto'][ifeed,:,:,:]
            nu = data['level2/freqspectra'][ifeed,:,:,:]
            freq = data['level1/spectrometer/frequency'][...]
            bw = 16
            freq = np.mean(np.reshape(freq, (freq.shape[0],freq.shape[1]//bw, bw)),axis=-1).flatten()
            sfreq = np.argsort(freq)
        
            fnoise_power[ifile,:] = (rms[:,:,0]**2 * (1/fits[:,:,0])**fits[:,:,1]).flatten()[sfreq]
            alphas[ifile,:] = (fits[:,:,1]).flatten()[sfreq]

            #print(nu.shape,ps.shape, rms.shape, fits.shape)
            #pyplot.plot(freq[sfreq],fnoise_power[ifile,:])
        except IOError:
            print('{} not processed'.format(filename.split('/')[-1]))
            fnoise[ifile] = np.nan

        if isinstance(feed, type(None)):
            feed = data['level1/spectrometer/feeds'][ifeed]

        # Calculate sun distance
        mjd = data['level1/spectrometer/MJD'][0:1]
        lon=-118.2941
        lat=37.2314
        ra_sun, dec_sun, raddist = Coordinates.getPlanetPosition('SUN', lon, lat, mjd)
        az_sun, el_sun = Coordinates.e2h(ra_sun, dec_sun, mjd, lon, lat)
        ra = data['level1/spectrometer/pixel_pointing/pixel_ra'][0,0:1]
        dec = data['level1/spectrometer/pixel_pointing/pixel_dec'][0,0:1]
        dist[ifile] = el_sun[0]#angular_seperation(ra_sun, ra, dec_sun, dec)
        data.close()


    # Plot obs ID vs fnoise power
    pyplot.imshow(np.log10(fnoise_power*1e3),aspect='auto',origin='lower',
                  extent=[np.min(freq),np.max(freq),-.5,fnoise_power.shape[0]-0.5])
    pyplot.yticks(np.arange(fnoise_power.shape[0])-0.5, obsid, rotation=0,
                  ha='right',va='center',size=10)
    ax = pyplot.gca()
    fig = pyplot.gcf()
    offset = ScaledTranslation(-0.08,0.02,fig.transFigure)
    for label in ax.yaxis.get_majorticklabels():
        label.set_transform(label.get_transform() + offset)
    pyplot.grid()
    pyplot.xlabel('Frequency (GHz)')
    pyplot.ylabel('obs ID')
    pyplot.colorbar(label=r'$\mathrm{log}_{10}$(mK)')
    pyplot.title('Feed {}'.format(feed))
    pyplot.savefig('Plots/fnoise_gfields_Feed{}.png'.format(feed),bbox_inches='tight')
    pyplot.clf()
    # Plot obs ID vs fnoise power
    pyplot.imshow(alphas,aspect='auto',origin='lower',vmin=-1.5,vmax=-0.9,
                  extent=[np.min(freq),np.max(freq),-.5,fnoise_power.shape[0]-0.5])
    pyplot.yticks(np.arange(fnoise_power.shape[0])-0.5, obsid, rotation=0,
                  ha='right',va='center',size=10)
    ax = pyplot.gca()
    fig = pyplot.gcf()
    for label in ax.yaxis.get_majorticklabels():
        label.set_transform(label.get_transform() + offset)
    pyplot.grid()
    pyplot.xlabel('Frequency (GHz)')
    pyplot.ylabel('obs ID')
    pyplot.colorbar(label=r'$\alpha$')
    pyplot.title('Feed {}'.format(feed))
    pyplot.savefig('Plots/alphas_gfields_Feed{}.png'.format(feed),bbox_inches='tight')
    pyplot.clf()
示例#17
0
########## simulations without binding ##########
plt.figure("0bind", figsize=figsize)
a, t, ood = fields.get("eventspara_nobind", "a", "t", "ood") 
a, t, success = np.array(a), np.array(t), np.array(ood) == 0

plt.scatter(t[~success], a[~success], **s_fail)
plt.scatter(t[success], a[success], **s_success)
plt.scatter(t_exp, a_exp, **s_experiment)
ax = plt.gca()
format_ticks(ax)

plt.legend(loc="lower left", scatterpoints=3, frameon=False,
           borderaxespad=0.2, handletextpad=0.4)

# encircle long bindings
offset = ScaledTranslation(18, 27, ax.transScale)
tform = offset + ax.transLimits + ax.transAxes
ell = mpatch.Ellipse((0, 0), 1.8, 10, angle=0.0, transform=tform,
                     fc="None", ec=long_bind_color)
ax.add_patch(ell)
plt.text(15, 21, "Assumed\n long bindings", color=long_bind_color,
         horizontalalignment="center")

########## simulations with one binding ##########
plt.figure("1bind", figsize=figsize)
a, t, ood = fields.get("eventsnew_onlyone_2_", "a", "t", "ood") 
a, t, success = np.array(a), np.array(t), np.array(ood) == 0

plt.scatter(t[~success], a[~success], **s_fail)
plt.scatter(t[success], a[success], **s_success)
plt.scatter(t_exp, a_exp, **s_experiment)
示例#18
0
    def __init__(self, lang='English'):
        super(BRFFigure, self).__init__()
        lang = lang if lang.lower() in FigureLabels.LANGUAGES else 'English'
        self.__figlang = lang
        self.__figlabels = FigureLabels(lang)

        # ---- Figure Creation

        fig_width = 8
        fig_height = 5

        self.set_size_inches(fig_width, fig_height)
        self.patch.set_facecolor('white')

        left_margin = 0.8
        right_margin = 0.25
        bottom_margin = 0.75
        top_margin = 0.25

        # ---- Axe Setup

        ax = self.add_axes([
            left_margin / fig_width, bottom_margin / fig_height, 1 -
            (left_margin + right_margin) / fig_width, 1 -
            (bottom_margin + top_margin) / fig_height
        ],
                           zorder=1)
        ax.set_visible(False)

        # ---- Ticks Setup

        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        ax.tick_params(axis='both',
                       which='major',
                       direction='out',
                       gridOn=True)

        # ---- Artists Init

        self.line, = ax.plot([], [],
                             ls='-',
                             color='blue',
                             linewidth=1.5,
                             zorder=20,
                             clip_on=True)

        self.markers, = ax.plot([], [],
                                color='0.1',
                                mec='0.1',
                                marker='.',
                                ls='None',
                                ms=5,
                                zorder=30,
                                mew=1,
                                clip_on=False)

        self.errbar, = ax.plot([], [])

        offset = ScaledTranslation(0, -5 / 72, self.dpi_scale_trans)

        self.title = ax.text(0.5,
                             1,
                             '',
                             ha='center',
                             va='top',
                             fontsize=14,
                             transform=ax.transAxes + offset)
示例#19
0
 def _T(self):
     F = self.plotter.figure.dpi_scale_trans
     S = ScaledTranslation(self.point[0], self.point[1], self.plotter.axes.transData)
     T = F + S
     return T
示例#20
0
 def transform_non_affine(self, values):
     x, y = self._get_translation()
     trans = ScaledTranslation(x, y, self.figure.dpi_scale_trans)
     return trans.transform(values)
示例#21
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import blended_transform_factory, ScaledTranslation

fig = plt.figure(figsize=(6, 4))

ax = fig.add_subplot(1, 1, 1, aspect=1)
ax.set_xlim(0, 10)
ax.set_xticks(range(11))
ax.set_ylim(0, 5)
ax.set_xticks(range(11))

point = 1 / 72
fontsize = 12
dx, dy = 0, -1.5 * fontsize * point
offset = ScaledTranslation(dx, dy, fig.dpi_scale_trans)
transform = blended_transform_factory(ax.transData, ax.transAxes + offset)

for x in range(11):
    plt.text(x,
             0,
             "↑",
             transform=transform,
             ha="center",
             va="top",
             fontsize=fontsize)

plt.tight_layout()
plt.savefig("../../figures/coordinates/transforms-blend.pdf")
plt.show()
示例#22
0
    def __init__(self, lang='English'):
        lang = lang if lang.lower() in FigureLabels.LANGUAGES else 'English'
        self.__figlang = lang
        self.__figlabels = FigureLabels(lang)
        self.normals = None

        fw, fh = 8.5, 5.
        fig = MplFigure(figsize=(fw, fh), facecolor='white')
        super(FigWeatherNormals, self).__init__(fig)

        # Define the margins.
        left_margin = 1 / fw
        right_margin = 1 / fw
        bottom_margin = 0.7 / fh
        top_margin = 0.1 / fh

        # ---- Yearly Avg Labels

        # The yearly yearly averages for the mean air temperature and
        # the total precipitation are displayed in <ax3>, which is placed on
        # top of the axes that display the data (<ax0> and <ax1>).

        ax3 = fig.add_axes([0, 0, 1, 1], zorder=1, label='axe3')
        ax3.patch.set_visible(False)
        ax3.spines['bottom'].set_visible(False)
        ax3.tick_params(axis='both',
                        bottom=False,
                        top=False,
                        left=False,
                        right=False,
                        labelbottom=False,
                        labeltop=False,
                        labelleft=False,
                        labelright=False)

        # Mean Annual Air Temperature :

        # Places first label at the top left corner of <ax3> with a horizontal
        # padding of 5 points and downward padding of 3 points.

        dx, dy = 5 / 72., -3 / 72.
        padding = ScaledTranslation(dx, dy, fig.dpi_scale_trans)
        transform = ax3.transAxes + padding

        ax3.text(0.,
                 1.,
                 'Mean Annual Air Temperature',
                 fontsize=13,
                 va='top',
                 transform=transform)

        # Mean Annual Precipitation :

        # Get the bounding box of the first label.

        renderer = self.get_renderer()
        bbox = ax3.texts[0].get_window_extent(renderer)
        bbox = bbox.transformed(ax3.transAxes.inverted())

        # Places second label below the first label with a horizontal
        # padding of 5 points and downward padding of 3 points.

        ax3.text(0.,
                 bbox.y0,
                 'Mean Annual Precipitation',
                 fontsize=13,
                 va='top',
                 transform=transform)

        bbox = ax3.texts[1].get_window_extent(renderer)
        bbox = bbox.transformed(fig.transFigure.inverted())

        # Update geometry :

        # Updates the geometry and position of <ax3> to accomodate the text.

        x0 = left_margin
        axw = 1 - (left_margin + right_margin)
        axh = 1 - bbox.y0 - (dy / fw)
        y0 = 1 - axh - top_margin

        ax3.set_position([x0, y0, axw, axh])

        # ---- Data Axes

        axh = y0 - bottom_margin
        y0 = y0 - axh

        # Precipitation :

        ax0 = fig.add_axes([x0, y0, axw, axh], zorder=1, label='axe0')
        ax0.patch.set_visible(False)
        ax0.spines['top'].set_visible(False)
        ax0.set_axisbelow(True)

        # Air Temperature :

        ax1 = fig.add_axes(ax0.get_position(),
                           frameon=False,
                           zorder=5,
                           sharex=ax0,
                           label='axe1')

        # ---- Initialize the Artists

        # This is only to initiates the artists and to set their parameters
        # in advance. The plotting of the data is actually done by calling
        # the <plot_monthly_normals> method.

        XPOS = np.arange(-0.5, 12.51, 1)
        XPOS[0] = 0
        XPOS[-1] = 12
        y = range(len(XPOS))
        colors = ['#990000', '#FF0000', '#FF6666']

        # Dashed lines for Tmax, Tavg, and Tmin :

        for i in range(3):
            ax1.plot(XPOS, y, color=colors[i], ls='--', lw=1.5, zorder=100)

        # Markers for Tavg :

        ax1.plot(XPOS[1:-1],
                 y[1:-1],
                 color=colors[1],
                 marker='o',
                 ls='none',
                 ms=6,
                 zorder=100,
                 mec=colors[1],
                 mfc='white',
                 mew=1.5)

        # ---- Xticks Formatting

        Xmin0 = 0
        Xmax0 = 12.001

        # Major ticks
        ax0.xaxis.set_ticks_position('bottom')
        ax0.tick_params(axis='x', direction='out')
        ax0.xaxis.set_ticklabels([])
        ax0.set_xticks(np.arange(Xmin0, Xmax0))

        ax1.tick_params(axis='x',
                        which='both',
                        bottom=False,
                        top=False,
                        labelbottom=False)

        # Minor ticks
        ax0.set_xticks(np.arange(Xmin0 + 0.5, Xmax0 + 0.49, 1), minor=True)
        ax0.tick_params(axis='x',
                        which='minor',
                        direction='out',
                        length=0,
                        labelsize=13)
        ax0.xaxis.set_ticklabels(self.fig_labels.month_names, minor=True)

        # ---- Y-ticks Formatting

        # Precipitation
        ax0.yaxis.set_ticks_position('right')
        ax0.tick_params(axis='y', direction='out', labelsize=13)

        ax0.tick_params(axis='y', which='minor', direction='out')
        ax0.yaxis.set_ticklabels([], minor=True)

        # Air Temperature
        ax1.yaxis.set_ticks_position('left')
        ax1.tick_params(axis='y', direction='out', labelsize=13)

        ax1.tick_params(axis='y', which='minor', direction='out')
        ax1.yaxis.set_ticklabels([], minor=True)

        # ---- Grid Parameters

        #    ax0.grid(axis='y', color=[0.5, 0.5, 0.5], linestyle=':', linewidth=1,
        #             dashes=[1, 5])
        #    ax0.grid(axis='y', color=[0.75, 0.75, 0.75], linestyle='-',
        #                 linewidth=0.5)

        # ---- Limits of the Axes

        ax0.set_xlim(Xmin0, Xmax0)

        # ---- Legend

        self.plot_legend()
示例#23
0
def plotGenomeTracks(tracks,
                     chromosome,
                     coordStart,
                     coordEnd,
                     style='ggplot',
                     outpath=None,
                     figsize=None):
    # TODO Refactor into separate functions and classes
    if figsize is None:
        figsize = (13., 1. * len(tracks))

    def coordFmt(t):
        if t >= 1000000:
            return '%.3f Mb' % (t / 1000000.)
        if t >= 1000:
            return '%.3f kb' % (t / 1000.)
        return '%.3f bp' % t

    try:
        import matplotlib.pyplot as plt
        import base64
        from io import BytesIO
        from IPython.core.display import display, HTML
        from matplotlib.collections import PatchCollection
        from matplotlib.patches import Rectangle, FancyBboxPatch, Polygon
        from matplotlib.lines import Line2D
        from matplotlib.transforms import ScaledTranslation
        import struct
        with plt.style.context(style):
            fig, ax = plt.subplots(1, figsize=figsize)
            # Set up axes
            plt.yticks(range(len(tracks)))
            ax.set_xlim(coordStart, coordEnd)
            ax.set_ylim(0, len(tracks))
            ticks = ax.get_xticks()
            ax.set_xticklabels([coordFmt(t) for t in ticks], fontsize=12)
            ax.set_yticklabels([])
            setYA = []
            setYB = []
            width = coordEnd - coordStart
            y = 0.
            for rs in tracks:
                yA = y
                if isinstance(rs, genome):
                    y += 3.
                elif isinstance(rs, curves):
                    y += 3.
                    if rs.thresholdValue is not None:
                        y += 1.
                else:
                    y += 1.
                setYA.append(yA)
                setYB.append(y)
                plt.text(coordStart - width * 0.015, (y + yA) / 2. + 0.05,
                         rs.name,
                         verticalalignment='top',
                         horizontalalignment='right',
                         color=ax.yaxis.label.get_color(),
                         fontsize=15,
                         rotation=45,
                         clip_on=False)
            ax.set_yticks([0.] + setYB)
            ax.yaxis.set_label_coords(-0.3, 1.5)
            plt.setp(ax.get_yticklabels(),
                     rotation=45,
                     ha="right",
                     rotation_mode="anchor")
            plt.tick_params(axis='y', which='both', left=False, right=False)
            # Shift y axis labels
            dx = -0.1
            dy = 0.2
            offset = ScaledTranslation(dx, dy, fig.dpi_scale_trans)
            for label in ax.yaxis.get_majorticklabels():
                label.set_transform(label.get_transform() + offset)
            # Iterate over tracks
            rmargin = 0.2
            for rsi, ((yA, yB), rs) in enumerate(zip(zip(setYA, setYB),
                                                     tracks)):
                # Special treatment of gene annotations, with plotting of genes with exons, CDS and names
                height = yB - yA
                colorRaw = plt.rcParams['axes.prop_cycle'].by_key()['color'][
                    rsi %
                    len(plt.rcParams['axes.prop_cycle'].by_key()['color'])]
                color = [
                    v / 255.
                    for v in struct.unpack('BBB', bytes.fromhex(colorRaw[1:]))
                ]

                def drawRoundBox(start,
                                 end,
                                 y,
                                 height,
                                 fc,
                                 ec,
                                 rlabel=None,
                                 clip_on=True):
                    w = end - start + 1
                    rs = min(w * 0.5 * width * 0.00001, 500. * width * 0.00001)
                    patch = FancyBboxPatch(
                        (start, y),
                        w,
                        height,
                        boxstyle="round,rounding_size=" + str(rs),
                        mutation_aspect=2. * max(setYB) / width,
                        fc=fc,
                        ec=ec,
                        clip_on=clip_on)
                    ax.add_patch(patch)
                    if rlabel is not None:
                        plt.text(end + width * 0.015,
                                 y + height * .5,
                                 rlabel,
                                 verticalalignment='center',
                                 horizontalalignment='left',
                                 color=ax.yaxis.label.get_color(),
                                 fontsize=10,
                                 clip_on=False)
                    return patch

                def drawBox(start,
                            end,
                            y,
                            height,
                            fc,
                            ec,
                            rlabel=None,
                            clip_on=True):
                    w = end - start + 1
                    rs = min(w * width * 0.00001, 500. * width * 0.00001)
                    patch = FancyBboxPatch(
                        (start, y),
                        w,
                        height,
                        boxstyle="square",
                        mutation_aspect=2. * max(setYB) / width,
                        fc=fc,
                        ec=ec,
                        clip_on=clip_on)
                    ax.add_patch(patch)
                    if rlabel is not None:
                        plt.text(end + width * 0.015,
                                 y + height * .5,
                                 rlabel,
                                 verticalalignment='center',
                                 horizontalalignment='left',
                                 color=ax.yaxis.label.get_color(),
                                 fontsize=10,
                                 clip_on=False)
                    return patch

                if isinstance(rs, genome):
                    cgenes = [
                     g for g in rs.genes
                     if g.region.seq == chromosome\
                       and g.region.end >= coordStart\
                       and g.region.start <= coordEnd
                    ]
                    cy = height / 2.
                    geneheight = 1. - 2. * rmargin
                    colBody = [0.75, 0.75, 0.75]
                    colExons = [0.45, 0.45, 0.45]
                    colCDS = [0.1, 0.1, 0.1]
                    colBorder = [0.1, 0.1, 0.1, 1.]
                    colInvisible = [0., 0., 0., 0.]

                    # Legend: Gene body
                    def drawGeneBody(start,
                                     end,
                                     y,
                                     height,
                                     rlabel=None,
                                     clip_on=True):
                        return drawRoundBox(start=start,
                                            end=end,
                                            y=y,
                                            height=height,
                                            fc=colBody + [0.4],
                                            ec=colInvisible,
                                            rlabel=rlabel,
                                            clip_on=clip_on)

                    def drawGeneOutline(start, end, y, height, clip_on=True):
                        drawRoundBox(start=start,
                                     end=end,
                                     y=y,
                                     height=height,
                                     fc=colInvisible,
                                     ec=colBorder,
                                     clip_on=clip_on)

                    drawGeneBody(start=coordEnd + width * 0.01,
                                 end=coordEnd + width * 0.01 +
                                 3. * 0.006 * width,
                                 y=yB - 0.1 - geneheight,
                                 height=geneheight,
                                 rlabel='Gene body',
                                 clip_on=False)
                    drawGeneOutline(start=coordEnd + width * 0.01,
                                    end=coordEnd + width * 0.01 +
                                    3. * 0.006 * width,
                                    y=yB - 0.1 - geneheight,
                                    height=geneheight,
                                    clip_on=False)

                    # Legend: Gene exon
                    def drawGeneExon(start,
                                     end,
                                     y,
                                     height,
                                     rlabel=None,
                                     clip_on=True):
                        drawBox(start=start,
                                end=end,
                                y=y,
                                height=height,
                                fc=colExons + [1.],
                                ec=colInvisible,
                                rlabel=rlabel,
                                clip_on=clip_on)

                    drawGeneExon(start=coordEnd + width * 0.01,
                                 end=coordEnd + width * 0.01 +
                                 3. * 0.006 * width,
                                 y=yB - 0.1 - geneheight - 0.1 - geneheight,
                                 height=geneheight,
                                 rlabel='Exon',
                                 clip_on=False)

                    #drawGeneOutline(start = coordEnd + width*0.01, end = coordEnd + width*0.01 + 3. * 0.006 * width, y = yB - 0.1 - geneheight - 0.1 - geneheight, height = geneheight, clip_on = False)
                    # Legend: Gene CDS
                    def drawGeneCDS(start,
                                    end,
                                    y,
                                    height,
                                    rlabel=None,
                                    clip_on=True):
                        drawBox(start=start,
                                end=end,
                                y=y,
                                height=height,
                                fc=colCDS + [1.],
                                ec=colInvisible,
                                rlabel=rlabel,
                                clip_on=clip_on)

                    drawGeneCDS(
                        start=coordEnd + width * 0.01,
                        end=coordEnd + width * 0.01 + 3. * 0.006 * width,
                        y=yB - 0.1 - geneheight - 0.1 - geneheight - 0.1 -
                        geneheight,
                        height=geneheight,
                        rlabel='CDS',
                        clip_on=False)
                    #drawGeneOutline(start = coordEnd + width*0.01, end = coordEnd + width*0.01 + 3. * 0.006 * width, y = yB - 0.1 - geneheight - 0.1 - geneheight - 0.1 - geneheight, height = geneheight, clip_on = False)
                    #
                    for strand in [False, True]:
                        gh = 0.02
                        exonh = 0.2
                        ccy = yA + (cy + 0.5 if strand else cy - 0.5)
                        for g in cgenes:
                            if g.region.strand != strand: continue
                            # Gene body
                            drawGeneBody(start=g.region.start,
                                         end=g.region.end,
                                         y=ccy - geneheight * .5,
                                         height=geneheight)
                            # Exons
                            for r in g.exons:
                                drawGeneExon(start=r.start,
                                             end=r.end,
                                             y=ccy - geneheight * .5,
                                             height=geneheight)
                            # CDS
                            for r in g.CDS:
                                drawGeneCDS(start=r.start,
                                            end=r.end,
                                            y=ccy - geneheight * .5,
                                            height=geneheight)
                            #
                            drawGeneOutline(start=g.region.start,
                                            end=g.region.end,
                                            y=ccy - geneheight * .5,
                                            height=geneheight)
                        for g in cgenes:
                            if g.region.strand == strand:
                                center = (g.region.start + g.region.end) / 2.
                                if center <= coordStart or center >= coordEnd:
                                    continue
                                ax.text(center,
                                        ccy + (0.65 if strand else -0.65),
                                        g.name,
                                        horizontalalignment='center',
                                        verticalalignment='center')
                    continue
                # Special handling of curves
                elif isinstance(rs, curves):
                    ccurve = next((c for c in rs if c.seq == chromosome), None)
                    if ccurve == None: continue
                    # Rasterize - logic required depends on curve type
                    if isinstance(ccurve, fixedStepCurve):
                        iA = max(int((coordStart - ccurve.span) / ccurve.step),
                                 0)
                        iB = max(
                            min(int((coordEnd) / ccurve.step),
                                len(ccurve) - 1), 0)
                        span = ccurve.span
                        step = ccurve.step
                        vals = ccurve[iA:iB + 1]
                        #
                        res = 2048
                        srcXA = iA * ccurve.step  #coordStart
                        srcXB = iB * ccurve.step  #coordEnd
                        scale = res / (srcXB - srcXA)
                        ret = [None for _ in range(res)]
                        for i, v in enumerate(vals):
                            dstXA = int(
                                min(
                                    max(
                                        i * ccurve.step * res /
                                        ((iB - iA) * ccurve.step), 0),
                                    res - 1))
                            dstXB = int(
                                min(
                                    max(
                                        res * (i + ccurve.span / ccurve.step) /
                                        (iB - iA), 0), res - 1))
                            for x in range(dstXA, dstXB + 1):
                                Q = (ccurve.step *
                                     (iA + (iB - iA) * float(x) / res), v)
                                if ret[x] is None or Q > ret[x]:
                                    ret[x] = Q
                        raster = [v for v in ret if v is not None]
                    elif isinstance(ccurve, variableStepCurve):
                        vals = [
                            v for v in ccurve if v.start +
                            v.span >= coordStart and v.start <= coordEnd
                        ]
                        #
                        res = 2048
                        srcXA = coordStart
                        srcXB = coordEnd
                        scale = res / (srcXB - srcXA)
                        ret = [None for _ in range(res)]
                        for v in vals:
                            dstXA = int(
                                min(max((v.start - srcXA) * scale, 0),
                                    res - 1))
                            dstXB = int(
                                min(max((v.start + v.span - srcXA) * scale, 0),
                                    res - 1))
                            for x in range(dstXA, dstXB + 1):
                                ret[x] = (srcXA + (float(x) / scale), v.value)
                        raster = [v for v in ret if v is not None]
                    # Plot curve
                    vBase = 0.
                    vMin = min(y for x, y in raster)
                    vMax = max(y for x, y in raster)
                    yBottom = min(vBase, vMin)
                    yTop = vMax
                    cheight = height
                    predHeight = 1.

                    def V2Y(v):
                        return yA + rmargin + ((v + vBase - yBottom) * vScale)

                    if rs.thresholdValue is not None:
                        yBottom = min(yBottom, rs.thresholdValue)
                        yTop = max(yTop, rs.thresholdValue)
                        cheight -= predHeight
                    vScale = (cheight - rmargin * 2.) / (yTop - yBottom)
                    polypts = []
                    polypts += [(x, V2Y(max(y, vBase))) for x, y in raster]
                    polypts += reversed([(x, V2Y(min(y, vBase)))
                                         for x, y in raster])
                    poly = Polygon(polypts,
                                   fc=color[:3] + [0.4],
                                   ec=colInvisible)
                    #ec = [ c*0.5 for c in color[:3] ] + [1.])
                    ax.add_patch(poly)
                    ax.add_line(
                        Line2D([x for x, y in raster],
                               [V2Y(y) for x, y in raster],
                               linewidth=0.8,
                               color=[c * 0.75 for c in color[:3]] + [0.75]))
                    #color = color))
                    # Legend
                    lyA = V2Y(vMin)
                    lyB = V2Y(vMax)
                    ax.add_patch(
                        Rectangle((coordEnd, lyA),
                                  1. * 0.006 * width,
                                  lyB - lyA,
                                  fc=(0.2, 0.2, 0.2, 1.),
                                  ec=colInvisible,
                                  clip_on=False))
                    tticks = [(vMax, str(vMax)), (vMin, str(vMin))]
                    if rs.thresholdValue is not None:
                        tticks.append(
                            (rs.thresholdValue,
                             str(rs.thresholdValue) + ' (threshold)'))
                    if vMin < 0. and vMax > 0.:
                        tticks.append((0.0, str(0.0)))
                    tticks = sorted(tticks, key=lambda p: p[0])
                    for v, n in tticks:
                        ly = V2Y(v)
                        ax.add_line(
                            Line2D([
                                coordEnd + 0. * 0.006 * width,
                                coordEnd + 2. * 0.006 * width
                            ], [ly, ly],
                                   color=(0.2, 0.2, 0.2, 1.),
                                   linewidth=1.,
                                   clip_on=False))
                        plt.text(coordEnd + 3. * 0.006 * width,
                                 ly,
                                 n,
                                 verticalalignment='center',
                                 horizontalalignment='left',
                                 color=ax.yaxis.label.get_color(),
                                 fontsize=8,
                                 clip_on=False)
                    # Thresholded
                    if rs.thresholdValue is not None:
                        tthr = V2Y(rs.thresholdValue)
                        ax.plot([coordStart, coordEnd], [tthr, tthr],
                                linestyle='-',
                                color='grey',
                                label='Expected at random')
                        frs = rs.regions().filter('', lambda r: r.seq == chromosome\
                         and r.end >= coordStart\
                         and r.start <= coordEnd)
                        for r in frs:
                            drawRoundBox(start=r.start,
                                         end=r.end,
                                         y=yB - predHeight + rmargin,
                                         height=predHeight - 2 * rmargin,
                                         fc=color[:3] + [0.4],
                                         ec=[c * 0.5
                                             for c in color[:3]] + [1.])
                        # Legend
                        drawRoundBox(start=coordEnd + width * 0.01,
                                     end=coordEnd + width * 0.01 +
                                     3. * 0.006 * width,
                                     y=yB - 0.1 - geneheight,
                                     height=geneheight,
                                     fc=color[:3] + [0.4],
                                     ec=[c * 0.5 for c in color[:3]] + [1.],
                                     rlabel='Thresholded',
                                     clip_on=False)
                    continue
                # Simpler handling of region sets
                frs = rs.filter('', lambda r: r.seq == chromosome\
                 and r.end >= coordStart\
                 and r.start <= coordEnd)
                for r in frs:
                    drawRoundBox(start=r.start,
                                 end=r.end,
                                 y=yA + rmargin,
                                 height=height - 2 * rmargin,
                                 fc=color[:3] + [0.4],
                                 ec=[c * 0.5 for c in color[:3]] + [1.])
            #
            plt.xlabel('Chromosome ' + chromosome, fontsize=18)
            fig.tight_layout()
            if outpath is None:
                bio = BytesIO()
                fig.savefig(bio, format='png')
                plt.close('all')
                encoded = base64.b64encode(bio.getvalue()).decode('utf-8')
                html = '<img src=\'data:image/png;base64,%s\'>' % encoded
                display(HTML(html))
            else:
                fig.savefig(outpath)
                plt.close('all')
    #
    except ImportError as err:
        raise err
示例#24
0
def plotInclusiveResponse(dataframe, name):
    fig, ax = plt.subplots(nrows=1,
                           ncols=1,
                           figsize=(3, 6),
                           constrained_layout=True)
    fig.suptitle("Inclusive response")
    trans1 = ax.transData + ScaledTranslation(-5 / 72, 0, fig.dpi_scale_trans)
    trans2 = ax.transData + ScaledTranslation(+5 / 72, 0, fig.dpi_scale_trans)

    colors = [sns.xkcd_rgb["cerulean"], sns.xkcd_rgb["rouge"]]
    gluons_l1l2l3 = dataframe.loc[dataframe.isPhysG == 1,
                                  "jetPt"] / dataframe.loc[dataframe.isPhysG ==
                                                           1, "genJetPt"]
    uds_l1l2l3 = dataframe.loc[dataframe.isPhysG != 1,
                               "jetPt"] / dataframe.loc[dataframe.isPhysG != 1,
                                                        "genJetPt"]
    gluons_dnn = dataframe.loc[dataframe.isPhysG == 1, "response"]
    uds_dnn = dataframe.loc[dataframe.isPhysG != 1, "response"]

    mean_g_l1l2l3, std_g_l1l2l3 = norm.fit(gluons_l1l2l3)
    mean_uds_l1l2l3, std_uds_l1l2l3 = norm.fit(uds_l1l2l3)
    median_g_l1l2l3 = np.median(gluons_l1l2l3)
    median_uds_l1l2l3 = np.median(uds_l1l2l3)
    mean_g_dnn, std_g_dnn = norm.fit(gluons_dnn)
    mean_uds_dnn, std_uds_dnn = norm.fit(uds_dnn)
    median_g_dnn = np.median(gluons_dnn)
    median_uds_dnn = np.median(uds_dnn)

    iqr_g_l1l2l3 = np.subtract(*np.percentile(gluons_l1l2l3, [75, 25])) * 0.1
    iqr_uds_l1l2l3 = np.subtract(*np.percentile(uds_l1l2l3, [75, 25])) * 0.1
    iqr_g_dnn = np.subtract(*np.percentile(gluons_dnn, [75, 25])) * 0.1
    iqr_uds_dnn = np.subtract(*np.percentile(uds_dnn, [75, 25])) * 0.1

    ax.set_xlim(-1.0, 2.0)
    ax.set_ylim(0.975, 1.04)
    ax.text(-0.5,
            1.041,
            "60 GeV < p$_T$ < 600 GeV, |$\eta$| < 2.5",
            fontsize=7)
    ax.set_ylabel("Median response")
    ax.set_xlabel("Jet class")
    plt.errorbar(x=['g', 'uds'],
                 y=[median_g_l1l2l3, median_uds_l1l2l3],
                 fmt='o',
                 label="L1L2L3",
                 color=colors[1],
                 ls='none',
                 ecolor='k',
                 transform=trans1)
    plt.errorbar(x=['g', 'uds'],
                 y=[median_g_dnn, median_uds_dnn],
                 yerr=[iqr_g_dnn, iqr_uds_dnn],
                 fmt='o',
                 label="DNN",
                 color=colors[0],
                 ls='none',
                 ecolor='k',
                 transform=trans2)
    ax.plot([-1.0, 2.0], [1.0, 1.0], linestyle='--', linewidth=1.5, color='k')
    ax.legend()
    plt.savefig("./plots/InclusiveResponse.pdf".format(name))
    plt.clf()
    plt.close()