Example #1
0
 def run(self, output_dir):
     model = models_index[self.model]('pt_BR')
     g = model.callback(**self.kwargs)
     t, y = self.nmethod(g, self.sample_time, self.total_time)
     fig = Figure(figsize=(8, 6), dpi=300)
     ax = fig.add_subplot(111, xlabel='Tempo (seg)', ylabel='Amplitude')
     ax.plot(t, y, label='Resposta ao Degrau')
     # generate the tuning line
     ident = Smith(t, y)
     t1, y1 = ident.tuning_line
     ax.plot(t1, y1, label='Reta de Sintonia')
     ax.annotate(
         '%.1f%% (p1)' % ident.point1,
         xy=(t1[1], y1[1]),
         xycoords='data',
         xytext=(t1[1] + (self.total_time / 15.0), y1[1]),
         arrowprops=dict(facecolor='black', shrink=0.05),
     )
     ax.annotate(
         '%.1f%% (p2)' % ident.point2,
         xy=(t1[2], y1[2]),
         xycoords='data',
         xytext=(t1[2] + (self.total_time / 15.0), y1[2]),
         arrowprops=dict(facecolor='black', shrink=0.05),
     )
     legend = []
     for arg in model.args:
         if arg in self.blacklist_args:
             continue
         legend.append('%s=%s' % (arg, self.kwargs[arg]))
     #ax.legend(loc='best', prop={'size': 'x-small'}, title='; '.join(legend))
     canvas = FigureCanvas(fig)
     filename = 'cap3_model%i_%i.eps' % (self.model, self.plot_id)
     canvas.print_eps(os.path.join(output_dir, filename))
Example #2
0
 def run(self, output_dir):
     model = models_index[self.model]('pt_BR')
     g = model.callback(**self.kwargs)
     t, y = self.nmethod(g, self.sample_time, self.total_time)
     fig = Figure(figsize=(8, 6), dpi=300)
     ax = fig.add_subplot(111, xlabel='Tempo (seg)', ylabel='Amplitude')
     ax.plot(t, y, label='Resposta ao Degrau')
     # generate the tuning line
     ident = Smith(t, y)
     t1, y1 = ident.tuning_line
     ax.plot(t1, y1, label='Reta de Sintonia')
     ax.annotate(
         '%.1f%% (p1)' % ident.point1, xy=(t1[1], y1[1]), xycoords='data',
         xytext=(t1[1]+(self.total_time/15.0), y1[1]),
         arrowprops=dict(facecolor='black', shrink=0.05),
     )
     ax.annotate(
         '%.1f%% (p2)' % ident.point2, xy=(t1[2], y1[2]), xycoords='data',
         xytext=(t1[2]+(self.total_time/15.0), y1[2]),
         arrowprops=dict(facecolor='black', shrink=0.05),
     )
     legend = []
     for arg in model.args:
         if arg in self.blacklist_args:
             continue
         legend.append('%s=%s' % (arg, self.kwargs[arg]))
     #ax.legend(loc='best', prop={'size': 'x-small'}, title='; '.join(legend))
     canvas = FigureCanvas(fig)
     filename = 'cap3_model%i_%i.eps' % (self.model, self.plot_id)
     canvas.print_eps(os.path.join(output_dir, filename))
Example #3
0
    def run(self, output_dir):
        model = models_index[self.model]('pt_BR')
        g = model.callback(**self.kwargs)
        t, y = self.nmethod(g, self.sample_time, self.total_time)
        fig = Figure(figsize=(8, 6), dpi=300)
        ax = fig.add_subplot(111, xlabel='Tempo (seg)', ylabel='Amplitude')
        ax.plot(t, y, label='Resposta ao Degrau')

        if self.kp is None or self.ki is None or self.kd is None:
            kp, ki, kd = ZieglerNichols(t, y, Smith).gains
        else:
            kp, ki, kd = self.kp, self.ki, self.kd

        if self.simulate:
            # transfer function of the PID controller
            g_ = tf([kd, kp, ki], [1, 0])
            my_g = (g_ * g).feedback_unit()

            # discretize the controlled system
            t1, y1 = self.nmethod(my_g, self.sample_time, self.total_time)
            ax.plot(t1, y1, label='Resposta ao Degrau Controlada')
        else:
            # generate the tuning line
            ident = Smith(t, y)
            t1, y1 = ident.tuning_line
            ax.plot(t1, y1, label='Reta de Sintonia')
            ax.annotate(
                '%.1f%%' % ident.point1,
                xy=(t1[1], y1[1]),
                xycoords='data',
                xytext=(t1[1] + (self.total_time / 15.0), y1[1]),
                arrowprops=dict(facecolor='black', shrink=0.05),
            )
            ax.annotate(
                '%.1f%%' % ident.point2,
                xy=(t1[2], y1[2]),
                xycoords='data',
                xytext=(t1[2] + (self.total_time / 15.0), y1[2]),
                arrowprops=dict(facecolor='black', shrink=0.05),
            )
        legend = []
        for arg in model.args:
            if arg in self.blacklist_args:
                continue
            legend.append('%s=%s' % (arg, self.kwargs[arg]))
        ax.legend(
            loc='best',
            prop={'size': 'x-small'},
            title='kp=%.1f; ki=%.1f; kd=%.1f;' % (kp, ki, kd),
        )
        canvas = FigureCanvas(fig)
        filename = 'cap4_model%i_%i.eps' % (self.model, self.plot_id)
        canvas.print_eps(os.path.join(output_dir, filename))
Example #4
0
 def run(self, output_dir):
     model = models_index[self.model]('pt_BR')
     g = model.callback(**self.kwargs)
     t, y = self.nmethod(g, self.sample_time, self.total_time)
     fig = Figure(figsize=(8, 6), dpi=300)
     ax = fig.add_subplot(111, xlabel='Tempo (seg)', ylabel='Amplitude')
     ax.plot(t, y, label='Resposta ao Degrau')
     legend = []
     for arg in model.args:
         if arg in self.blacklist_args:
             continue
         legend.append('%s=%s' % (arg, self.kwargs[arg]))
     ax.legend(loc='best', prop={'size': 'x-small'}, title='; '.join(legend))
     canvas = FigureCanvas(fig)
     filename = 'cap2_model%i_%i.eps' % (self.model, self.plot_id)
     canvas.print_eps(os.path.join(output_dir, filename))
Example #5
0
    def __init__(self, filename, plot_type='ps', items=[], output_prefix=''):
        self.type = plot_type

        self.filename = filename
        self.output_prefix = output_prefix
        self.figure = Figure((8.5, 11))
        #self.figure = Figure((8.3,11.7))
        if plot_type == 'png':
            self.canvas = FigureCanvasAgg(self.figure)
            self.extension = '.png'
        else:
            self.canvas = FigureCanvasPS(self.figure)
            self.extension = '.ps'
        self.plots = {}

        #if self.type=='quartz': r.quartz()

        try:
            self.plot_raw_data(filename + '_raw_data.csv')
            self.plot_trails(filename + '_autocorrelations.csv')
            self.plot_trails(filename + '_trails.csv')
            self.plot_samples(filename + '_samples.csv')
            self.plot_min_mean_max(filename + '_min_mean_max.csv', items)
        except Exception, e:
            print e
Example #6
0
  def canvas(self):
    type = self.get("imageType", "png")
    fig = Figure()
    if type == "png":
      canvas = FigureCanvasAgg(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "svg":
      canvas = FigureCanvasSVG(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "pdf":
      canvas = FigureCanvasPdf(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "ps" or type == "eps":
      canvas = FigureCanvasPS(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    else:
      raise "Invalid render target requested"

    # Set basic figure parameters
    dpi = float(self.get('dpi'))
    (w, h) = (float(self.get('width')), float(self.get('height')))
    (win, hin) = (w/dpi, h/dpi)
    fig.set_size_inches(win, hin)
    fig.set_dpi(dpi)
    fig.set_facecolor('white')
    return (fig, canvas, w, h)
Example #7
0
def save_as_eps(x, y, xlim, figsize, orientation):
    """Create and save an EPS file from plot data.

    :param x: (numpy ndarray)
    :param y: (numpy ndarray)
    :param xlim: (float, float) a tuple of
    (max chemical shift, min chemical shift)
    :param figsize: (float, float) a tuple of (plot width, plot height) in
    inches.
    :param orientation: 'landscape' or 'portrait'"""
    figure = _create_figure(x, y, xlim, figsize)
    backend = FigureCanvasPS(figure)
    filename = asksaveasfilename()
    if filename:
        if filename[-4:] != '.eps':
            filename += '.eps'
        backend.print_eps(filename, orientation=orientation)
Example #8
0
    def save_annotated(self,
                       fname=None,
                       label_fmt=None,
                       text_annotate=None,
                       dpi=100,
                       sigma_clip=None):
        r"""Saves the most recently rendered image of the Scene to disk,
        including an image of the transfer function and and user-defined
        text.

        Once you have created a scene and rendered that scene to an image
        array, this saves that image array to disk with an optional filename.
        If an image has not yet been rendered for the current scene object,
        it forces one and writes it out.

        Parameters
        ----------
        fname: string, optional
            If specified, save the rendering as a bitmap to the file "fname".
            If unspecified, it creates a default based on the dataset filename.
            Default: None
        sigma_clip: float, optional
            Image values greater than this number times the standard deviation
            plus the mean of the image will be clipped before saving. Useful
            for enhancing images as it gets rid of rare high pixel values.
            Default: None

            floor(vals > std_dev*sigma_clip + mean)
        dpi: integer, optional
            By default, the resulting image will be the same size as the camera
            parameters.  If you supply a dpi, then the image will be scaled
            accordingly (from the default 100 dpi)
        label_fmt : str, optional
           A format specifier (e.g., label_fmt="%.2g") to use in formatting 
           the data values that label the transfer function colorbar. 
        text_annotate : list of iterables
           Any text that you wish to display on the image.  This should be an
           list containing a tuple of coordinates (in normalized figure 
           coordinates), the text to display, and, optionally, a dictionary of 
           keyword/value pairs to pass through to the matplotlib text() 
           function.

           Each item in the main list is a separate string to write.


        Returns
        -------
            Nothing


        Examples
        --------

        >>> sc.save_annotated("fig.png", 
        ...                   text_annotate=[[(0.05, 0.05),
        ...                                   "t = {}".format(ds.current_time.d),
        ...                                   dict(horizontalalignment="left")],
        ...                                  [(0.5,0.95),
        ...                                   "simulation title",
        ...                                   dict(color="y", fontsize="24",
        ...                                        horizontalalignment="center")]])

        """
        from yt.visualization._mpl_imports import \
            FigureCanvasAgg, FigureCanvasPdf, FigureCanvasPS
        sources = list(itervalues(self.sources))
        rensources = [s for s in sources if isinstance(s, RenderSource)]

        if fname is None:
            # if a volume source present, use its affiliated ds for fname
            if len(rensources) > 0:
                rs = rensources[0]
                basename = rs.data_source.ds.basename
                if isinstance(rs.field, string_types):
                    field = rs.field
                else:
                    field = rs.field[-1]
                fname = "%s_Render_%s.png" % (basename, field)
            # if no volume source present, use a default filename
            else:
                fname = "Render_opaque.png"
        suffix = get_image_suffix(fname)
        if suffix == '':
            suffix = '.png'
            fname = '%s%s' % (fname, suffix)

        self.render()

        # which transfer function?
        rs = rensources[0]
        tf = rs.transfer_function
        label = rs.data_source.ds._get_field_info(rs.field).get_label()

        ax = self._show_mpl(self._last_render.swapaxes(0, 1),
                            sigma_clip=sigma_clip,
                            dpi=dpi)
        self._annotate(ax.axes, tf, rs, label=label, label_fmt=label_fmt)

        # any text?
        if text_annotate is not None:
            f = self._render_figure
            for t in text_annotate:
                xy = t[0]
                string = t[1]
                if len(t) == 3:
                    opt = t[2]
                else:
                    opt = dict()

                # sane default
                if "color" not in opt:
                    opt["color"] = "w"

                ax.axes.text(xy[0],
                             xy[1],
                             string,
                             transform=f.transFigure,
                             **opt)

        suffix = get_image_suffix(fname)

        if suffix == ".png":
            canvas = FigureCanvasAgg(self._render_figure)
        elif suffix == ".pdf":
            canvas = FigureCanvasPdf(self._render_figure)
        elif suffix in (".eps", ".ps"):
            canvas = FigureCanvasPS(self._render_figure)
        else:
            mylog.warning("Unknown suffix %s, defaulting to Agg", suffix)
            canvas = self.canvas

        self._render_figure.canvas = canvas
        self._render_figure.tight_layout()
        self._render_figure.savefig(fname, facecolor='black', pad_inches=0)
Example #9
0
    def save(self, fname=None, sigma_clip=None):
        r"""Saves the most recently rendered image of the Scene to disk.

        Once you have created a scene and rendered that scene to an image
        array, this saves that image array to disk with an optional filename.
        If an image has not yet been rendered for the current scene object,
        it forces one and writes it out.

        Parameters
        ----------
        fname: string, optional
            If specified, save the rendering as to the file "fname".
            If unspecified, it creates a default based on the dataset filename.
            The file format is inferred from the filename's suffix. Supported
            fomats are png, pdf, eps, and ps.
            Default: None
        sigma_clip: float, optional
            Image values greater than this number times the standard deviation
            plus the mean of the image will be clipped before saving. Useful
            for enhancing images as it gets rid of rare high pixel values.
            Default: None

            floor(vals > std_dev*sigma_clip + mean)

        Returns
        -------
            Nothing

        Examples
        --------

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # Modify camera, sources, etc...
        >>> sc.render()
        >>> sc.save('test.png', sigma_clip=4)

        Or alternatively:

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # save with different sigma clipping values
        >>> sc.save('raw.png')
        >>> sc.save('clipped_2.png', sigma_clip=2)
        >>> sc.save('clipped_4.png', sigma_clip=4)

        """
        if fname is None:
            sources = list(itervalues(self.sources))
            rensources = [s for s in sources if isinstance(s, RenderSource)]
            # if a volume source present, use its affiliated ds for fname
            if len(rensources) > 0:
                rs = rensources[0]
                basename = rs.data_source.ds.basename
                if isinstance(rs.field, string_types):
                    field = rs.field
                else:
                    field = rs.field[-1]
                fname = "%s_Render_%s.png" % (basename, field)
            # if no volume source present, use a default filename
            else:
                fname = "Render_opaque.png"
        suffix = get_image_suffix(fname)
        if suffix == '':
            suffix = '.png'
            fname = '%s%s' % (fname, suffix)

        self.render()

        mylog.info("Saving render %s", fname)
        # We can render pngs natively but for other formats we defer to
        # matplotlib.
        if suffix == '.png':
            self._last_render.write_png(fname, sigma_clip=sigma_clip)
        else:
            from matplotlib.figure import Figure
            from matplotlib.backends.backend_pdf import \
                FigureCanvasPdf
            from matplotlib.backends.backend_ps import \
                FigureCanvasPS
            shape = self._last_render.shape
            fig = Figure((shape[0] / 100., shape[1] / 100.))
            if suffix == '.pdf':
                canvas = FigureCanvasPdf(fig)
            elif suffix in ('.eps', '.ps'):
                canvas = FigureCanvasPS(fig)
            else:
                raise NotImplementedError(
                    "Unknown file suffix '{}'".format(suffix))
            ax = fig.add_axes([0, 0, 1, 1])
            ax.set_axis_off()
            out = self._last_render
            nz = out[:, :, :3][out[:, :, :3].nonzero()]
            max_val = nz.mean() + sigma_clip * nz.std()
            alpha = 255 * out[:, :, 3].astype('uint8')
            out = np.clip(out[:, :, :3] / max_val, 0.0, 1.0) * 255
            out = np.concatenate([out.astype('uint8'), alpha[..., None]],
                                 axis=-1)
            # not sure why we need rot90, but this makes the orientation
            # match the png writer
            ax.imshow(np.rot90(out), origin='lower')
            canvas.print_figure(fname, dpi=100)
Example #10
0
    def save(self, fname=None, sigma_clip=None, render=True):
        r"""Saves a rendered image of the Scene to disk.

        Once you have created a scene, this saves an image array to disk with
        an optional filename. This function calls render() to generate an
        image array, unless the render parameter is set to False, in which case
        the most recently rendered scene is used if it exists.

        Parameters
        ----------
        fname: string, optional
            If specified, save the rendering as to the file "fname".
            If unspecified, it creates a default based on the dataset filename.
            The file format is inferred from the filename's suffix. Supported
            fomats are png, pdf, eps, and ps.
            Default: None
        sigma_clip: float, optional
            Image values greater than this number times the standard deviation
            plus the mean of the image will be clipped before saving. Useful
            for enhancing images as it gets rid of rare high pixel values.
            Default: None

            floor(vals > std_dev*sigma_clip + mean)
        render: boolean, optional
            If True, will always render the scene before saving.
            If False, will use results of previous render if it exists.
            Default: True

        Returns
        -------
            Nothing

        Examples
        --------

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # Modify camera, sources, etc...
        >>> sc.save('test.png', sigma_clip=4)

        When saving multiple images without modifying the scene (camera,
        sources,etc.), render=False can be used to avoid re-rendering when a scene is saved.
        This is useful for generating images at a range of sigma_clip values:

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # save with different sigma clipping values
        >>> sc.save('raw.png')  # The initial render call happens here
        >>> sc.save('clipped_2.png', sigma_clip=2, render=False)
        >>> sc.save('clipped_4.png', sigma_clip=4, render=False)

        """
        if fname is None:
            sources = list(self.sources.values())
            rensources = [s for s in sources if isinstance(s, RenderSource)]
            # if a volume source present, use its affiliated ds for fname
            if len(rensources) > 0:
                rs = rensources[0]
                basename = rs.data_source.ds.basename
                if isinstance(rs.field, str):
                    field = rs.field
                else:
                    field = rs.field[-1]
                fname = "%s_Render_%s.png" % (basename, field)
            # if no volume source present, use a default filename
            else:
                fname = "Render_opaque.png"
        suffix = get_image_suffix(fname)
        if suffix == "":
            suffix = ".png"
            fname = "%s%s" % (fname, suffix)

        render = self._sanitize_render(render)
        if render:
            self.render()
        mylog.info("Saving rendered image to %s", fname)

        # We can render pngs natively but for other formats we defer to
        # matplotlib.
        if suffix == ".png":
            self._last_render.write_png(fname, sigma_clip=sigma_clip)
        else:
            from matplotlib.backends.backend_pdf import FigureCanvasPdf
            from matplotlib.backends.backend_ps import FigureCanvasPS
            from matplotlib.figure import Figure

            shape = self._last_render.shape
            fig = Figure((shape[0] / 100.0, shape[1] / 100.0))
            if suffix == ".pdf":
                canvas = FigureCanvasPdf(fig)
            elif suffix in (".eps", ".ps"):
                canvas = FigureCanvasPS(fig)
            else:
                raise NotImplementedError("Unknown file suffix '{}'".format(suffix))
            ax = fig.add_axes([0, 0, 1, 1])
            ax.set_axis_off()
            out = self._last_render
            nz = out[:, :, :3][out[:, :, :3].nonzero()]
            max_val = nz.mean() + sigma_clip * nz.std()
            alpha = 255 * out[:, :, 3].astype("uint8")
            out = np.clip(out[:, :, :3] / max_val, 0.0, 1.0) * 255
            out = np.concatenate([out.astype("uint8"), alpha[..., None]], axis=-1)
            # not sure why we need rot90, but this makes the orientation
            # match the png writer
            ax.imshow(np.rot90(out), origin="lower")
            canvas.print_figure(fname, dpi=100)