Exemple #1
0
def func(f1, b, set):
    """
	This function Perform the gate application on the initial state of qubit and then the state tomography,
	at the same time compute the analytical bloch state.
	INCOME:
	f1="string", b="string"
	fig_data="svg",fig_data2="svg"
	"""
    #### Create the bloch-sphere on qutip
    b1 = Bloch()
    b2 = Bloch()
    ## create the analyical quantum state and perform tranformation
    ## Add states to the bloch sphere and plot it
    b1.add_states(analytic(f1, b))
    if not set:
        states = qtomography(f1, b)
        b2.add_vectors(states)
    else:
        ### implements for
        states = qtomography_s(f1, b)
        for i in states:
            b2.add_points(i)
        b2.add_vectors(np.average(states, axis=0))
        ###
    b2.render()
    fig_data = print_figure(b2.fig, 'svg')
    b1.render()
    fig_data2 = print_figure(b1.fig, 'svg')

    #b1.show()
    #b2.show()
    b1.clear()
    b2.clear()
    return fig_data, fig_data2
Exemple #2
0
def repr_feature(feature: SlidingWindowFeature):
    """Get `png` data for `feature`"""
    import matplotlib.pyplot as plt

    figsize = plt.rcParams["figure.figsize"]

    if feature.data.ndim == 2:

        plt.rcParams["figure.figsize"] = (notebook.width, 2)
        fig, ax = plt.subplots()
        notebook.plot_feature(feature, ax=ax)
        data = print_figure(fig, "png")
        plt.close(fig)

    elif feature.data.ndim == 3:

        num_chunks = len(feature)

        if notebook.crop is None:
            notebook.crop = Segment(
                start=feature.sliding_window.start,
                end=feature.sliding_window[num_chunks - 1].end,
            )
        else:
            feature = feature.crop(notebook.crop, mode="loose", return_data=False)

        num_overlap = (
            round(feature.sliding_window.duration // feature.sliding_window.step) + 1
        )

        num_overlap = min(num_chunks, num_overlap)

        plt.rcParams["figure.figsize"] = (notebook.width, 1.5 * num_overlap)

        fig, axes = plt.subplots(nrows=num_overlap, ncols=1,)
        mini, maxi = np.nanmin(feature.data), np.nanmax(feature.data)
        ylim = (mini - 0.2 * (maxi - mini), maxi + 0.2 * (maxi - mini))
        for c, (window, data) in enumerate(feature):
            ax = axes[c % num_overlap]
            step = duration = window.duration / len(data)
            frames = SlidingWindow(start=window.start, step=step, duration=duration)
            window_feature = SlidingWindowFeature(data, frames, labels=feature.labels)
            notebook.plot_feature(
                window_feature,
                ax=ax,
                time=c % num_overlap == (num_overlap - 1),
                ylim=ylim,
            )
            ax.set_prop_cycle(None)
        data = print_figure(fig, "png")
        plt.close(fig)

    plt.rcParams["figure.figsize"] = figsize
    return data
Exemple #3
0
 def save_fig(cls, fig, figure_format, dpi):
     filename = cls._save_filename(figure_format)
     if filename is None: return
     figure_data = print_figure(fig, figure_format, dpi=dpi)
     if cls._digest(figure_data): return
     with open(filename, 'w') as f:
         f.write(figure_data)
Exemple #4
0
 def _repr_svg_(self):
     from IPython.core.pylabtools import print_figure
     from matplotlib import pyplot as plt
     fig = self._create_figure(open_new_figure=True)
     data = print_figure(fig, 'svg')
     plt.close(fig)
     return data
Exemple #5
0
	def _repr_svg_(self):
		fig,ax=plt.subplots(figsize=(10,3))
		#ax = fig.add_subplot(111)
		self.plot(ax)
		data = print_figure(fig,'svg')
		plt.close(fig)
		return data.decode('utf-8')
def _html_place(s,
                radius=1,
                fontsize=120,
                facecolor='red',
                ax=None,
                correct=None,
                bg_alpha=None):
    fig = plt.figure(figsize=(4, 4))
    ax = fig.gca()
    ax.set_xlim([-1.2, 1.2])
    ax.set_ylim([-1.2, 1.2])

    if correct is not None:
        alpha = 0.25
        if correct:
            ax.scatter([0, 0], [0, 0],
                       s=55000,
                       marker=r'$\checkmark$',
                       color='green')

        else:
            ax.scatter([0, 0], [0, 0],
                       s=55000,
                       marker=r'x',
                       color='red',
                       linewidth=15)
    else:
        alpha = 1.

    circle = Circle((0, 0),
                    1.,
                    facecolor=facecolor,
                    edgecolor='k',
                    alpha=alpha)
    ax.add_patch(circle)
    ax.text(0,
            0,
            s,
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=fontsize,
            color='white',
            alpha=alpha)
    ax.set_frame_on(False)
    ax.set_xticks([])
    ax.set_yticks([])

    if bg_alpha is not None:
        bg, alpha = bg_alpha
        rec = Rectangle((-2, -2), 4, 4, facecolor=bg, alpha=alpha, fill=True)
        ax.add_patch(rec)

    plt.draw()
    ax.set_xlim([-1.2, 1.2])
    ax.set_ylim([-1.2, 1.2])

    place_png = print_figure(fig, 'png')
    plt.close()
    place_png64 = encodestring(place_png).decode('ascii')
    return '<img src="data:image/png;base64,%s" height="150" width="150">' % place_png64
Exemple #7
0
def numbered_marble(col, number):
    if (col, number) not in _marble_cache:
        fig = plt.figure(figsize=(4,4))
        ax = fig.gca()
        ax.set_xlim([-1.2,1.2])
        ax.set_ylim([-1.2,1.2])

        circle = Circle((0,0), 1., facecolor=col,
                        edgecolor='k', alpha=0.7)
        ax.add_patch(circle)
        ax.set_frame_on(False)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.text(0, 0, str(number), fontsize=100,
                verticalalignment='center',
                horizontalalignment='center')
        plt.draw()
        ax.set_xlim([-1.2,1.2])
        ax.set_ylim([-1.2,1.2])

        marble_png = print_figure(fig, 'png')
        marble_png64 = encodestring(marble_png).decode('ascii')
        _marble_cache[(col, number)] = '<img src="data:image/png;base64,%s" height="40" width="40">' % marble_png64
        plt.close()
    return (col, number)
Exemple #8
0
 def _repr_svg_(self):
     from IPython.core.pylabtools import print_figure
     from matplotlib import pyplot as plt
     fig = self._create_figure(open_new_figure=True)
     data = print_figure(fig, 'svg')
     plt.close(fig)
     return data
Exemple #9
0
 def _repr__png_(self):
     param_order = list(self._variation_params.keys())
     param_order.sort()
     if len(self._variation_params) == 0:
         ys = 1
         xs = 1
     elif len(self._variation_params) == 1:
         p1 = param_order[0]
         vals = self._variation_params[p1]
         xs = min([3, len(vals)])
         ys = math.ceil(len(vals) / 3)
     else:
         p1 = param_order[0]
         p2 = param_order[1]
         xs = len(self._variation_params[p1])
         ys = len(self._variation_params[p2])
     fig, axs = plt.subplots(ys, xs, squeeze=False, figsize=(16, 9))
     for i, sim_params in enumerate(self._sim_ids):
         x = i % 3
         y = i // 3
         ax = axs[y, x]
         self._draw_sim(ax, sim_params)
     for i in range(i + 1, ys * xs):
         x = i % 3
         y = i // 3
         ax = axs[y, x]
         ax.set_axis_off()
     data = print_figure(fig, 'png')
     plt.close(fig)
     return data
Exemple #10
0
def _repr_png_(kde: gaussian_kde) -> bytes:
    sample = kde.dataset
    n, dim = sample.shape

    if n == 1:
        sample = sample.flatten()
        n, dim = dim, 1

    x_eval = np.linspace(np.min(sample, axis=0),
                         np.max(sample, axis=0),
                         num=200)
    pdf = kde(x_eval)

    fig, ax = plt.subplots()

    ax.plot(x_eval, pdf, "-", lw=5, alpha=0.6)

    # discrete samples
    delta = np.max(pdf) * 5e-2
    n = min(n, 100)
    ax.plot(sample[:n], -delta - delta * np.random.random(n), "+k")

    ax.set_ylabel(r"$f$")
    ax.set_xlabel(r"$x$")

    data = print_figure(fig, "png")

    # We MUST close the figure, otherwise IPython's display machinery
    # will pick it up and send it as output, resulting in a double display
    plt.close(fig)
    return data
def showInference(bn,ie,size="4",cmap=INFOcmap):
  """
  Shows a bn annoted with results from inference : entropy and mutual informations
  """
  vals={bn.variable(n).name():ie.H(n) for n in bn.ids()}
  gr=getBN(bn,size,_normalizeVals(vals,hilightExtrema=False),cmap)

  mi=min(vals.values())
  ma=max(vals.values())

  fig = mpl.figure.Figure(figsize=(8,3))
  canvas = fc(fig)
  ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
  norm = mpl.colors.Normalize(vmin=mi, vmax=ma)
  cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap,
                                   norm=norm,
                                   orientation='horizontal')
  cb1.set_label('Entropy')
  png=print_figure(canvas.figure,"png") # from IPython.core.pylabtools
  png_legend="<img style='vertical-align:middle' src='data:image/png;base64,%s'>"%encodestring(png).decode('ascii')

  IPython.display.display(IPython.display.HTML("<div align='center'>"+
                              gr.data+
                              "</div><div align='center'>"+
                              "<font color='"+_proba2bgcolor(0.01,cmap)+"'>"+str(mi)+"</font>"
                              +png_legend+
                              "<font color='"+_proba2bgcolor(0.99,cmap)+"'>"+str(ma)+"</font>"
                              "</div>"))
Exemple #12
0
def numbered_marble(col, number):
    if (col, number) not in _marble_cache:
        fig = plt.figure(figsize=(4,4))
        ax = fig.gca()
        ax.set_xlim([-1.2,1.2])
        ax.set_ylim([-1.2,1.2])

        circle = Circle((0,0), 1., facecolor=col,
                        edgecolor='k', alpha=0.7)
        ax.add_patch(circle)
        ax.set_frame_on(False)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.text(0, 0, str(number), fontsize=100,
                verticalalignment='center',
                horizontalalignment='center')
        plt.draw()
        ax.set_xlim([-1.2,1.2])
        ax.set_ylim([-1.2,1.2])

        marble_png = print_figure(fig, 'png')
        marble_png64 = encodestring(marble_png).decode('ascii')
        _marble_cache[(col, number)] = '<img src="data:image/png;base64,%s" height="40" width="40">' % marble_png64
        plt.close()
    return (col, number)
Exemple #13
0
 def _figure_data(self, format):
     fig = self.plot()
     data = print_figure(fig, format)
     # We MUST close the figure, otherwise IPython's display machinery
     # will pick it up and send it as output, resulting in a double display
     plt.close(fig)
     return data
Exemple #14
0
 def _figure_data(self, format):
     fig = self.plot()
     data = print_figure(fig, format)
     # We MUST close the figure, otherwise IPython's display machinery
     # will pick it up and send it as output, resulting in a double display
     plt.close(fig)
     return data
Exemple #15
0
 def _repr_svg_(self):
     from IPython.core.pylabtools import print_figure
     from matplotlib import pyplot as plt
     fig = plt.figure(figsize=TRAJECTORY_FIGSIZE, dpi=TRAJECTORY_DPI)
     ax = self._create_plot()
     data = print_figure(fig, 'svg')
     plt.close(fig)
     return data
Exemple #16
0
 def _repr_svg_(self):
     from IPython.core.pylabtools import print_figure
     from matplotlib import pyplot as plt
     fig = plt.figure(figsize=TRAJECTORY_FIGSIZE, dpi=TRAJECTORY_DPI)
     ax = self._create_plot()
     data = print_figure(fig, 'svg')
     plt.close(fig)
     return data
Exemple #17
0
def _render(fig):
    """Render figure as png and return raw image data"""
    # render figure as png
    data = print_figure(fig, 'png')
    # prevent IPython notebook from displaying the figure
    plt.close(fig)
    # return raw image data
    return data
Exemple #18
0
def _render(fig):
    """Render figure as png and return raw image data"""
    # render figure as png
    data = print_figure(fig, 'png')
    # prevent IPython notebook from displaying the figure
    plt.close(fig)
    # return raw image data
    return data
Exemple #19
0
def mpl2html(fig, title="Figure"):
    """ Converts a matplotlib fig into an IPython HTML Core object for display 
    compatibility in widgets."""
    from IPython.core.pylabtools import print_figure
    import base64

    fdata64 = base64.b64encode(print_figure(fig))
    html_tpl = '<img alt="{title}" src="data:image/png;base64,{fdata64}">'
    return html_tpl.format(**locals())
def get_contours_image(path):
    from IPython.core.pylabtools import print_figure
    
    img, dark, light = find_contours(path)
    plot_contours(img, dark, light, show=False)
    fig = plt.gcf()
    pngdata = print_figure(fig)
    plt.close(fig)
    return pngdata
def mpl2html(fig, title="Figure"):
    """ Converts a matplotlib fig into an IPython HTML Core object for display 
    compatibility in widgets."""
    from IPython.core.pylabtools import print_figure
    import base64

    fdata64 = base64.b64encode(print_figure(fig))
    html_tpl = '<img alt="{title}" src="data:image/png;base64,{fdata64}">'
    return html_tpl.format(**locals())
Exemple #22
0
 def _repr_svg_(self):  # pragma: no cover
     from IPython.core.pylabtools import print_figure
     import matplotlib.pyplot as plt
     fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
     ax = fig.add_subplot(111, projection='3d')
     self.render(ax)
     fig_data = print_figure(fig, 'svg')
     plt.close(fig)
     return fig_data
Exemple #23
0
    def _repr_png_(self):
        """Render as a PNG for IPython notebook, per display_protocol.ipynb
        
        Invoke with `display(myViewer)`
        """
        from IPython.core.pylabtools import print_figure

        self.plot()
        return print_figure(self.axes.get_figure(), "png")
Exemple #24
0
 def _repr_png_(self):
     """Render as a PNG for IPython notebook, per display_protocol.ipynb
     
     Invoke with `display(myViewer)`
     """
     from IPython.core.pylabtools import print_figure
     
     self.plot()
     return print_figure(self.axes.get_figure(), "png")
Exemple #25
0
 def _figure_data(self, format):
     fig, ax = plt.subplots()
     ax.hist(self.data, bins=50)
     ax.set_title(self._repr_latex_())
     ax.set_xlim(-10.0, 10.0)
     data = print_figure(fig, format)
     # We MUST close the figure, otherwise IPython's display machinery
     # will pick it up and send it as output, resulting in a double display
     plt.close(fig)
     return data
Exemple #26
0
def repr_timeline(timeline):
    """Get `png` data for `timeline`"""
    import matplotlib.pyplot as plt
    figsize = plt.rcParams['figure.figsize']
    plt.rcParams['figure.figsize'] = (notebook.width, 1)
    fig, ax = plt.subplots()
    notebook.plot_timeline(timeline, ax=ax)
    data = print_figure(fig, 'png')
    plt.close(fig)
    plt.rcParams['figure.figsize'] = figsize
    return data
Exemple #27
0
def repr_segment(segment: Segment):
    """Get `png` data for `segment`"""
    import matplotlib.pyplot as plt
    figsize = plt.rcParams['figure.figsize']
    plt.rcParams['figure.figsize'] = (notebook.width, 1)
    fig, ax = plt.subplots()
    notebook.plot_segment(segment, ax=ax)
    data = print_figure(fig, 'png')
    plt.close(fig)
    plt.rcParams['figure.figsize'] = figsize
    return data
Exemple #28
0
    def _repr_png_(self):
        """Render as a PNG for IPython notebook, per `display_protocol.ipynb`

        Invoke with `display(myViewer)`
        """
        from IPython.core.pylabtools import print_figure, retina_figure

        if _isretina():
            return retina_figure(self.fig)
        else:
            return print_figure(self.fig, "png")
Exemple #29
0
def repr_feature(feature: SlidingWindowFeature):
    """Get `png` data for `feature`"""
    import matplotlib.pyplot as plt
    figsize = plt.rcParams['figure.figsize']
    plt.rcParams['figure.figsize'] = (notebook.width, 2)
    fig, ax = plt.subplots()
    notebook.plot_feature(feature, ax=ax)
    data = print_figure(fig, 'png')
    plt.close(fig)
    plt.rcParams['figure.figsize'] = figsize
    return data
Exemple #30
0
def repr_annotation(annotation: Annotation):
    """Get `png` data for `annotation`"""
    import matplotlib.pyplot as plt
    figsize = plt.rcParams['figure.figsize']
    plt.rcParams['figure.figsize'] = (notebook.width, 2)
    fig, ax = plt.subplots()
    notebook.plot_annotation(annotation, ax=ax)
    data = print_figure(fig, 'png')
    plt.close(fig)
    plt.rcParams['figure.figsize'] = figsize
    return data
Exemple #31
0
    def _repr_png_(self):
        '''
      Image representation form ipython console/notebook. 
    '''
        fig = Figure(figsize=(8, 5), dpi=300, facecolor='#FFFFFF')
        FigureCanvasAgg(fig)
        ax = fig.add_subplot(111)

        self.plot(ax=ax)

        return print_figure(fig, dpi=72)
Exemple #32
0
def repr_scores(scores):
    """Get `png` data for `scores`"""
    import matplotlib.pyplot as plt
    figsize = plt.rcParams['figure.figsize']
    plt.rcParams['figure.figsize'] = (notebook.width, 2)
    fig, ax = plt.subplots()
    notebook.plot_scores(scores, ax=ax)
    data = print_figure(fig, 'png')
    plt.close(fig)
    plt.rcParams['figure.figsize'] = figsize
    return data
Exemple #33
0
def repr_timeline(timeline: Timeline):
    """Get `png` data for `timeline`"""
    import matplotlib.pyplot as plt
    figsize = plt.rcParams['figure.figsize']
    plt.rcParams['figure.figsize'] = (notebook.width, 1)
    fig, ax = plt.subplots()
    notebook.plot_timeline(timeline, ax=ax)
    data = print_figure(fig, 'png')
    plt.close(fig)
    plt.rcParams['figure.figsize'] = figsize
    return data
Exemple #34
0
def figure_display(fig, size=None, format='svg', message=None):
    if size is not None:
        inches = size / float(fig.dpi)
        fig.set_size_inches(inches, inches)
    prefix = 'data:image/png;base64,'
    b64 = prefix + print_figure(fig, 'png').encode("base64")
    if size is not None:
        html = "<img height='%d' width='%d' src='%s' />" % (size, size, b64)
    else:
        html = "<img src='%s' />" % b64
    plt.close(fig)
    return html if (message is None) else '<b>%s</b></br>%s' % (message, html)
 def _repr_html_(self):
     lines = ['<div class="myfigure">']
     #get figure as PNG:
     pngdata = print_figure(self.figure, 'png')
     b64png = base64.b64encode(pngdata)
     lines.append('<img src=data:png;base64,%s>' % b64png)
     
     lines.append("<p>%s</p>" % self.caption)
     lines.append("<b>%s</b>" % self.name)
     lines.append("</div>")
     
     return "\n".join(lines)
Exemple #36
0
def repr_feature(feature):
    """Get `png` data for `feature`"""
    import matplotlib.pyplot as plt

    figsize = plt.rcParams["figure.figsize"]
    plt.rcParams["figure.figsize"] = (notebook.width, 2)
    fig, ax = plt.subplots()
    notebook.plot_feature(feature, ax=ax)
    data = print_figure(fig, "png")
    plt.close(fig)
    plt.rcParams["figure.figsize"] = figsize
    return data
Exemple #37
0
 def _figure_data(self, format):
     fig, axs = pyplot.subplots(3, 3, figsize=(10, 6))
     ax = axs[0, 0]
     for w in self.waves[0], self.waves[2]:
         if len(w.wavespeed) == 1:
             ax.plot([0, w.wavespeed[0]], [0, 1], 'k-', linewidth=3)
         elif len(w.wavespeed) == 2:
             xi_end = numpy.linspace(w.wavespeed[0], w.wavespeed[1], 5)
             ax.fill_between([0, xi_end[0], xi_end[-1], 0], [0, 1, 1, 0],
                             color='k',
                             alpha=0.1)
             for xi in xi_end:
                 ax.plot([0, xi], [0, 1], 'k-', linewidth=1)
     if len(self.waves[1].wavespeed):
         ax.plot([0, self.waves[1].wavespeed[0]], [0, 1],
                 'k--',
                 linewidth=1)
     ax.set_xlim(-1, 1)
     ax.set_ylim(0, 1)
     ax.set_xlabel(r"$x$")
     ax.set_ylabel(r"$t$")
     ax.set_title("Characteristics")
     names = [
         r"$\rho$", r"$v$", r"$v_t$", r"$\epsilon$", r"$p$", r"$W$", r"$h$",
         r"$c_s$"
     ]
     xi = [-1.05]
     data = self.state_l.state()
     for wave in self.waves:
         xi_wave, data_wave = wave.plotting_data()
         xi = numpy.hstack((xi, xi_wave))
         data = numpy.vstack((data, data_wave))
     xi = numpy.hstack((xi, [1.05]))
     data = numpy.vstack((data, self.state_r.state()))
     for ax_j in range(3):
         for ax_i in range(3):
             if ax_i == 0 and ax_j == 0:
                 continue
             nvar = ax_i * 3 + ax_j - 1
             axs[ax_i, ax_j].plot(xi, data[:, nvar])
             var_max = numpy.max(data[:, nvar])
             var_min = numpy.min(data[:, nvar])
             d_var = max(var_max - var_min,
                         0.01 * min(abs(var_min), abs(var_max)), 0.01)
             axs[ax_i, ax_j].set_xlim(-1.05, 1.05)
             axs[ax_i, ax_j].set_ylim(var_min - 0.05 * d_var,
                                      var_max + 0.05 * d_var)
             axs[ax_i, ax_j].set_xlabel(r"$\xi$")
             axs[ax_i, ax_j].set_ylabel(names[nvar])
     fig.tight_layout()
     data = print_figure(fig, format)
     pyplot.close(fig)
     return data
def get_corners_image(path):
    """Given a path, return a PNG of the image with contour lines
    
    Calls both find_contours and plot_contours
    """
    from IPython.core.pylabtools import print_figure
    
    img, corners = find_corners(path)
    plot_corners(img, corners, show=False)
    fig = plt.gcf()
    pngdata = print_figure(fig)
    plt.close(fig)
    return pngdata
def matplotlib_post_run(data_list):
  png_data = None
  figure = plt.gcf()
  # Always try to get the current figure.
  # This is not efficient, but we can support any libraries
  # that use matplotlib.
  png_data = print_figure(figure, fmt='png')
  figure.clear()
  if png_data is not None:
    width, height = _pngxy(png_data)
    data = encode_images({'image/png':png_data})
    metadata = {'image/png':dict(width=width, height=height)}
    data_list.append(json_clean(dict(data=data, metadata=metadata)))
Exemple #40
0
def get_corners_image(path):
    """Given a path, return a PNG of the image with contour lines
    
    Calls both find_contours and plot_contours
    """
    from IPython.core.pylabtools import print_figure

    img, corners = find_corners(path)
    plot_corners(img, corners, show=False)
    fig = plt.gcf()
    pngdata = print_figure(fig)
    plt.close(fig)
    return pngdata
Exemple #41
0
def svgfig(figures):
    '''Display a matplotlib figure as SVG in an IPython notebook.
        f: matplotlib.figure
            figure to display as SVG
            
        Note that this routine assumes you are NOT using ipython notebook --pylab inline, as 
        otherwise the original figure will be displayed as a rasterized PNG in addition to this SVG 
        figure by default.'''
    
    if type(figures) != list and type(figures) != tuple: figures = [figures]
    
    for f in figures:
        display(HTML(print_figure(f, fmt='svg')))
Exemple #42
0
def poly_to_png(p):
    fig, ax = plt.subplots()
    x = np.linspace(-1, 1)
    y = [p(_x) for _x in x]
    ax.plot(x, y)
    ax.set_title(poly_to_latex(p))
    ax.set_xlabel('x')
    ax.set_ylabel('P(x)')
    # from IPython.core.pylabtools import print_figure
    data = print_figure(fig, 'png')
    # We MUST close the figure, otherwise IPython's display machinery
    # will pick it up and send it as output, resulting in a double display
    plt.close(fig)
    return data
Exemple #43
0
def figure_display(fig, size=None, message=None):
    if size is not None:
        inches = size / float(fig.dpi)
        fig.set_size_inches(inches, inches)

    mime_type = 'svg+xml' if FIGURE_FORMAT.lower()=='svg' else 'png'
    prefix = 'data:image/%s;base64,' % mime_type
    b64 = prefix + print_figure(fig, FIGURE_FORMAT).encode("base64")
    if size is not None:
        html = "<center><img height='%d' width='%d' src='%s'/><center/>" % (size, size, b64)
    else:
        html = "<center><img src='%s' /><center/>" % b64
    plt.close(fig)
    return html if (message is None) else '<b>%s</b></br>%s' % (message, html)
Exemple #44
0
def send_figure(fig):
    """Draw the current figure and send it as a PNG payload.
    """
    fmt = InlineBackend.instance().figure_format
    data = print_figure(fig, fmt)
    # print_figure will return None if there's nothing to draw:
    if data is None:
        return
    mimetypes = {"png": "image/png", "svg": "image/svg+xml"}
    mime = mimetypes[fmt]
    # flush text streams before sending figures, helps a little with output
    # synchronization in the console (though it's a bandaid, not a real sln)
    sys.stdout.flush()
    sys.stderr.flush()
    publish_display_data("IPython.zmq.pylab.backend_inline.send_figure", {mime: data})
Exemple #45
0
 def _figure_data(self, format):
     fig, axs = pyplot.subplots(3,3, figsize=(10,6))
     ax = axs[0,0]
     for w in self.waves[0], self.waves[2]:
         if len(w.wavespeed)==1:
             ax.plot([0, w.wavespeed[0]], [0, 1], 'k-', linewidth=3)
         elif len(w.wavespeed)==2:
             xi_end = numpy.linspace(w.wavespeed[0], w.wavespeed[1], 5)
             ax.fill_between([0, xi_end[0], xi_end[-1], 0],
                             [0, 1, 1, 0], color='k', alpha=0.1)
             for xi in xi_end:
                 ax.plot([0, xi], [0, 1], 'k-', linewidth=1)
     if len(self.waves[1].wavespeed):
         ax.plot([0, self.waves[1].wavespeed[0]], [0, 1], 'k--', linewidth=1)
     ax.set_xlim(-1, 1)
     ax.set_ylim(0, 1)
     ax.set_xlabel(r"$x$")
     ax.set_ylabel(r"$t$")
     ax.set_title("Characteristics")
     names = [r"$\rho$", r"$v$", r"$v_t$", r"$\epsilon$", r"$p$", r"$W$",
              r"$h$", r"$c_s$"]
     xi = [-1.05]
     data = self.state_l.state()
     for wave in self.waves:
         xi_wave, data_wave = wave.plotting_data()
         xi = numpy.hstack((xi, xi_wave))
         data = numpy.vstack((data, data_wave))
     xi = numpy.hstack((xi, [1.05]))
     data = numpy.vstack((data, self.state_r.state()))
     for ax_j in range(3):
         for ax_i in range(3):
             if ax_i == 0 and ax_j == 0:
                 continue
             nvar = ax_i*3 + ax_j - 1
             axs[ax_i, ax_j].plot(xi, data[:, nvar])
             var_max = numpy.max(data[:, nvar])
             var_min = numpy.min(data[:, nvar])
             d_var = max(var_max - var_min,
                         0.01 * min(abs(var_min), abs(var_max)), 0.01)
             axs[ax_i, ax_j].set_xlim(-1.05, 1.05)
             axs[ax_i, ax_j].set_ylim(var_min - 0.05 * d_var,
                                      var_max + 0.05 * d_var)
             axs[ax_i, ax_j].set_xlabel(r"$\xi$")
             axs[ax_i, ax_j].set_ylabel(names[nvar])
     fig.tight_layout()
     data = print_figure(fig, format)
     pyplot.close(fig)
     return data
Exemple #46
0
def send_figure(fig):
    """Draw the given figure and send it as a PNG payload.
    """
    fmt = InlineBackend.instance().figure_format
    data = print_figure(fig, fmt)
    # print_figure will return None if there's nothing to draw:
    if data is None:
        return
    mimetypes = {'png': 'image/png', 'svg': 'image/svg+xml'}
    mime = mimetypes[fmt]
    # flush text streams before sending figures, helps a little with output
    # synchronization in the console (though it's a bandaid, not a real sln)
    sys.stdout.flush()
    sys.stderr.flush()
    publish_display_data('IPython.zmq.pylab.backend_inline.send_figure',
                         {mime: data})
def _html_place(s, radius=1, fontsize=120,
                facecolor='red', ax=None,
                correct=None,
                bg_alpha=None
                ):
    fig = plt.figure(figsize=(4,4))
    ax = fig.gca()
    ax.set_xlim([-1.2,1.2])
    ax.set_ylim([-1.2,1.2])

    if correct is not None:
        alpha=0.25
        if correct:
            ax.scatter([0,0], [0,0], s=55000, marker=r'$\checkmark$', color='green')

        else:
            ax.scatter([0,0], [0,0], s=55000, marker=r'x', color='red',
                       linewidth=15)
    else:
        alpha = 1.

    circle = Circle((0,0), 1., facecolor=facecolor,
                    edgecolor='k', alpha=alpha)
    ax.add_patch(circle)
    ax.text(0, 0, s,
            horizontalalignment='center',
            verticalalignment='center', 
            fontsize=fontsize,
            color='white', alpha=alpha)
    ax.set_frame_on(False)
    ax.set_xticks([])
    ax.set_yticks([])

    if bg_alpha is not None:
        bg, alpha = bg_alpha
        rec = Rectangle((-2,-2), 4, 4, facecolor=bg, 
                        alpha=alpha, fill=True)
        ax.add_patch(rec)

    plt.draw()
    ax.set_xlim([-1.2,1.2])
    ax.set_ylim([-1.2,1.2])

    place_png = print_figure(fig, 'png')
    plt.close()
    place_png64 = encodestring(place_png).decode('ascii')
    return '<img src="data:image/png;base64,%s" height="150" width="150">' % place_png64
Exemple #48
0
def send_figure(fig):
    """Draw the current figure and send it as a PNG payload.
    """
    # For an empty figure, don't even bother calling figure_to_svg, to avoid
    # big blank spaces in the qt console
    if not fig.axes:
        return
    fmt = InlineBackend.instance().figure_format
    data = print_figure(fig, fmt)
    mimetypes = {'png': 'image/png', 'svg': 'image/svg+xml'}
    mime = mimetypes[fmt]
    # flush text streams before sending figures, helps a little with output
    # synchronization in the console (though it's a bandaid, not a real sln)
    sys.stdout.flush()
    sys.stderr.flush()
    publish_display_data('IPython.zmq.pylab.backend_inline.send_figure',
                         {mime: data})
Exemple #49
0
def dice_html(digits, color_alpha=None):
    """
    Return pair of dice, side by side as HTML img.
    If color_alpha is not None, then the black and white
    pair of dice will be blended as if they were labelled
    with a particular color.

    Parameters
    ----------

    digits : (int, int)
        Which dice (from 1 to 6)

    color_alpha : (color_hex, float)
        The first argument should be a color as
        in hex string format, (i.e. "#820000")
        while the second is an alpha value between 0 and 1.

    Returns
    -------

    img_html : str
        HTML version of dice as an <img>.

    """

    dice_arr = dice(digits)
    color_arr = np.ones(dice_arr.shape, np.uint8)
    if color_alpha is not None:
        color, alpha = color_alpha
        color_arr[:,:,0] = eval('0x%s' % color[1:3])
        color_arr[:,:,1] = eval('0x%s' % color[3:5])
        color_arr[:,:,2] = eval('0x%s' % color[5:7])
        color_arr[:,:,3] = 255
        dice_arr[:] = (1 - alpha) * dice_arr + alpha * color_arr
        
    f = plt.figure()
    ax = f.gca()
    ax.imshow(dice_arr)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_frame_on(False)
    dice_png = print_figure(f, 'png')
    plt.close()
    dice_png64 = encodestring(dice_png).decode('ascii')
    return '<img src="data:image/png;base64,%s" height="150" width="150"/>' % dice_png64
Exemple #50
0
def dice_html(digits, color_alpha=None):
    """
    Return pair of dice, side by side as HTML img.
    If color_alpha is not None, then the black and white
    pair of dice will be blended as if they were labelled
    with a particular color.

    Parameters
    ----------

    digits : (int, int)
        Which dice (from 1 to 6)

    color_alpha : (color_hex, float)
        The first argument should be a color as
        in hex string format, (i.e. "#820000")
        while the second is an alpha value between 0 and 1.

    Returns
    -------

    img_html : str
        HTML version of dice as an <img>.

    """

    dice_arr = dice(digits)
    color_arr = np.ones(dice_arr.shape, np.uint8)
    if color_alpha is not None:
        color, alpha = color_alpha
        color_arr[:, :, 0] = eval('0x%s' % color[1:3])
        color_arr[:, :, 1] = eval('0x%s' % color[3:5])
        color_arr[:, :, 2] = eval('0x%s' % color[5:7])
        color_arr[:, :, 3] = 255
        dice_arr[:] = (1 - alpha) * dice_arr + alpha * color_arr

    f = plt.figure()
    ax = f.gca()
    ax.imshow(dice_arr)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_frame_on(False)
    dice_png = print_figure(f, 'png')
    plt.close()
    dice_png64 = encodestring(dice_png).decode('ascii')
    return '<img src="data:image/png;base64,%s" height="150" width="150"/>' % dice_png64
Exemple #51
0
def send_figure(fig):
    """Draw the current figure and send it as a PNG payload.
    """
    # For an empty figure, don't even bother calling figure_to_svg, to avoid
    # big blank spaces in the qt console
    if not fig.axes:
        return
    fmt = InlineBackend.instance().figure_format
    data = print_figure(fig, fmt)
    mimetypes = { 'png' : 'image/png', 'svg' : 'image/svg+xml' }
    mime = mimetypes[fmt]
    # flush text streams before sending figures, helps a little with output
    # synchronization in the console (though it's a bandaid, not a real sln)
    sys.stdout.flush(); sys.stderr.flush()
    publish_display_data(
        'IPython.zmq.pylab.backend_inline.send_figure',
        {mime : data}
    )
Exemple #52
0
	def _repr_svg_(self):
		fig,ax=plt.subplots(figsize=(10,3))
		
		ax.grid(True)
		ax.axhline(0, color='black', lw=2)
		ax.set_ylabel('channels')
		ax.set_xlabel('time [s]')
	
		#~ Plot the state evolution to axes object	
		self.active().plot(   ax,  c='green',lw=2)
		self.open().plot(     ax,  c='red',  lw=2)
		self.inhibited().plot(ax,  c='cyan', lw=2)
		self.resting().plot(  ax,  c='blue', lw=2)
		ax.legend(loc=2)
		
		data = print_figure(fig,'svg')
		plt.close(fig)
		return data.decode('utf-8')
Exemple #53
0
def save_print(fig):
    try:
        # from IPython.core.debugger import Tracer; Tracer()()
        base_dir, buffer = os.path.split(buffer_file_name())
        name = savefig()
        if name.lower() is not "none":
            path = os.path.realpath(
                os.path.join(base_dir, resources_dir,
                             os.path.splitext(buffer)[0], name))
            # the ``None`` kwargs force values to be taken from the default style,
            # so they can be easily set in style sheets
            fig.savefig(path,
                        dpi=None,
                        facecolor=None,
                        edgecolor=None,
                        bbox_inches=None)
            return publish_display_data({'text/org': '[[{}]]'.format(path)})
    except NameError:  # might not be defined
        return print_figure(fig, 'png', bbox_inches='tight')
Exemple #54
0
    def plot(self, figsize=(10, 8), dpi=70):
        """
        Make a plot of the data and model for embedding in IPython notebooks

        Doesn't require ``%matplotlib inline`` to embed the plot (as that would
        not allow the app to run).

        Parameters:

        * figsize : list = (width, height)
            The figure size in inches.
        * dpi : float
            The number of dots-per-inch for the figure resolution.

        """
        fig = self._figure_setup(figsize=figsize, facecolor='white')
        self._update_data_plot()
        pyplot.close(fig)
        data = print_figure(fig, dpi=dpi)
        return Image(data=data)
Exemple #55
0
def die_html(digit, height=100, width=100):
    """
    Return pair of dice, side by side as HTML img.
    If color_alpha is not None, then the black and white
    pair of dice will be blended as if they were labelled
    with a particular color.

    Parameters
    ----------

    digit : int
        Which die (from 1 to 6)

    color_alpha : (color_hex, float)
        The first argument should be a color as
        in hex string format, (i.e. "#820000")
        while the second is an alpha value between 0 and 1.

    Returns
    -------

    img_html : str
        HTML version of dice as an <img>.

    """

    die_arr = die(digit)
        
    f = plt.figure()
    ax = f.gca()
    ax.imshow(die_arr)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_frame_on(False)
    die_png = print_figure(f, 'png')
    plt.close()
    die_png64 = encodestring(die_png).decode('ascii')
    return '<img src="data:image/png;base64,%s" height="%d" width="%d"/>' % (die_png64, height, width)
 def _figure_data(self, format):
     fig, ax = plb.subplots()
     self.plot(ax=ax)
     data = print_figure(fig, format)
     plb.close(fig)
     return data