Beispiel #1
0
def test_kaleido_engine_to_image():
    with mocked_scope() as scope:
        pio.to_image(fig, engine="kaleido", validate=False)

    scope.transform.assert_called_with(fig,
                                       format=None,
                                       width=None,
                                       height=None,
                                       scale=None)
Beispiel #2
0
    def _figure_data(self, plot, fmt, as_script=False, **kwargs):
        if fmt == 'gif':
            import plotly.io as pio

            from PIL import Image
            from plotly.io.orca import ensure_server, shutdown_server, status

            running = status.state == 'running'
            if not running:
                ensure_server()

            nframes = len(plot)
            frames = []
            for i in range(nframes):
                plot.update(i)
                img_bytes = BytesIO()
                figure = go.Figure(self.get_plot_state(plot))
                img = pio.to_image(figure, 'png', validate=False)
                img_bytes.write(img)
                frames.append(Image.open(img_bytes))

            if not running:
                shutdown_server()

            bio = BytesIO()
            duration = (1. / self.fps) * 1000
            frames[0].save(bio,
                           format='GIF',
                           append_images=frames[1:],
                           save_all=True,
                           duration=duration,
                           loop=0)
            bio.seek(0)
            data = bio.read()
        elif fmt in ('png', 'svg'):
            import plotly.io as pio

            # Wrapping plot.state in go.Figure here performs validation
            # and applies any default theme.
            figure = go.Figure(self.get_plot_state(plot))
            data = pio.to_image(figure, fmt)

            if fmt == 'svg':
                data = data.decode('utf-8')
        else:
            raise ValueError("Unsupported format: {fmt}".format(fmt=fmt))

        if as_script:
            b64 = base64.b64encode(data).decode("utf-8")
            (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
            src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
            div = tag.format(src=src, mime_type=mime_type, css='')
            return div
        return data
def test_invalid_figure_json():
    # Do image export
    bad_fig = {"foo": "bar"}
    with pytest.raises(ValueError) as err:
        pio.to_image(bad_fig, format="png")

    assert "Invalid" in str(err.value)

    with pytest.raises(ValueError) as err:
        pio.to_image(bad_fig, format="png", validate=False)

    assert "The image request was rejected by the orca conversion utility" in str(
        err.value)

    assert "400: invalid or malformed request syntax" in str(err.value)
Beispiel #4
0
def createBarChart(filename, xAxis, yAxis, xName, yName, name):
    trace1 = go.Bar(text=list(yAxis),
                    textposition='auto',
                    x=list(xAxis),
                    y=list(yAxis))

    layout = go.Layout(barmode='group',
                       title=name,
                       xaxis=dict(title=xName),
                       yaxis=dict(title=yName))

    data = [trace1]
    fig = go.Figure(data=data, layout=layout)

    img_bytes = pio.to_image(fig,
                             format='PNG',
                             width=1600,
                             height=960,
                             scale=2)

    if not os.path.exists('images/bar'):
        os.mkdir('images/bar')

    with open('images/bar/' + filename + '.PNG', 'wb') as f:
        f.write(img_bytes)
    return
Beispiel #5
0
def render_barchart(title,
                    names,
                    dates,
                    datas,
                    colours,
                    scale=2,
                    type="linear"):
    if type == "log":
        datas = [x[1:] for x in datas]
        dates = dates[1:]

    fig = go.Figure(data=[
        go.Bar(name=name, x=dates, y=item, marker_color=colour)
        for name, item, colour in zip(names, datas, colours)
    ])

    fig.update_yaxes(rangemode="tozero")
    fig.update_xaxes(rangemode="tozero")

    fig.update_layout(title=title,
                      yaxis_type=type,
                      xaxis_title="Date",
                      yaxis_title="Total",
                      xaxis_tickangle=-45,
                      barmode="stack")

    return plotio.to_image(fig, format="png", scale=scale)
Beispiel #6
0
def render_linechart(title,
                     names,
                     dates,
                     datas,
                     colours,
                     scale=2,
                     type="linear"):
    if type == "log":
        datas = [x[1:] for x in datas]
        dates = dates[1:]

    fig = go.Figure()

    for name, data, colour in zip(names, datas, colours):
        fig.add_trace(
            go.Scatter(x=dates,
                       y=data,
                       name=name,
                       line=dict(color=colour, width=2),
                       line_shape="linear",
                       mode="lines+markers"))

    fig.update_yaxes(rangemode="tozero")
    fig.update_xaxes(rangemode="tozero")

    fig.update_layout(title=title,
                      yaxis_type=type,
                      xaxis_title="Date",
                      yaxis_title="Total",
                      xaxis_tickangle=-45)

    return plotio.to_image(fig, format="png", scale=scale)
Beispiel #7
0
def render_plot(static_fig=None,
                interactive_fig=None,
                backend=None,
                filename=None):
    """
    Render the plot using either file export, static png inline display or
    interactive display.
    """

    # Delay imports
    import IPython.display as disp
    from plotly.io import write_html, write_image, to_image

    if filename is not None:
        if filename.endswith(".html"):
            write_html(fig=static_fig, file=filename, auto_open=False)
        else:
            write_image(fig=static_fig, file=filename)
    else:
        if backend == "static":
            disp.display(disp.Image(to_image(static_fig, format='png')))
        elif backend == "interactive":
            disp.display(interactive_fig)
        else:
            raise RuntimeError("Unknown backend {}. Currently supported "
                               "backends are 'interactive' and "
                               "'static'".format(backend))
    return
def test_invalid_figure_json():
    # Do image export
    bad_fig = {'foo': 'bar'}
    with pytest.raises(ValueError) as err:
        pio.to_image(bad_fig, format='png')

    assert "Invalid value of type" in str(err.value)

    with pytest.raises(ValueError) as err:
        pio.to_image(bad_fig, format='png', validate=False)

    assert ('The image request was rejected by the orca conversion utility'
            in str(err.value))

    assert ('400: invalid or malformed request syntax'
            in str(err.value))
def test_png_renderer_mimetype(fig1):
    pio.renderers.default = "png"

    # Configure renderer so that we can use the same parameters
    # to build expected image below
    pio.renderers["png"].width = 400
    pio.renderers["png"].height = 500
    pio.renderers["png"].scale = 1

    image_bytes = pio.to_image(fig1, width=400, height=500, scale=1)
    image_str = base64.b64encode(image_bytes).decode("utf8")

    expected = {"image/png": image_str}

    pio.renderers.render_on_display = False

    with mock.patch("IPython.display.display") as mock_display:
        fig1._ipython_display_()

    # assert fig1._repr_mimebundle_(None, None) is None
    mock_display.assert_not_called()

    pio.renderers.render_on_display = True
    with mock.patch("IPython.display.display") as mock_display:
        fig1._ipython_display_()

    mock_display.assert_called_once_with(expected, raw=True)
Beispiel #10
0
def test_latex_fig_to_image(latexfig, format):
    img_bytes = pio.to_image(latexfig,
                             format=format,
                             width=700,
                             height=500,
                             engine="orca")
    assert_image_bytes(img_bytes, "latexfig." + format)
Beispiel #11
0
def test_topojson_fig_to_image(topofig, format):
    img_bytes = pio.to_image(topofig,
                             format=format,
                             width=700,
                             height=500,
                             engine="orca")
    assert_image_bytes(img_bytes, "topofig." + format)
Beispiel #12
0
def test_simple_to_image(fig1, format):
    img_bytes = pio.to_image(fig1,
                             format=format,
                             width=700,
                             height=500,
                             engine="orca")
    assert_image_bytes(img_bytes, "fig1." + format)
def test_mimetype_combination(fig1):
    pio.renderers.default = 'png+jupyterlab'

    # Configure renderer so that we can use the same parameters
    # to build expected image below
    pio.renderers['png'].width = 400
    pio.renderers['png'].height = 500
    pio.renderers['png'].scale = 1

    # pdf
    image_bytes = pio.to_image(
        fig1, format='png', width=400, height=500, scale=1)

    image_str = base64.b64encode(image_bytes).decode('utf8')

    # plotly mimetype
    plotly_mimetype_dict = json.loads(
        pio.to_json(fig1, remove_uids=False))

    plotly_mimetype_dict['config'] = {
        'plotlyServerURL': get_config()['plotly_domain']}

    # Build expected bundle
    expected = {
        'image/png': image_str,
        plotly_mimetype: plotly_mimetype_dict,
    }

    pio.renderers.render_on_display = False
    assert fig1._repr_mimebundle_(None, None) is None

    pio.renderers.render_on_display = True
    bundle = fig1._repr_mimebundle_(None, None)
    assert bundle == expected
Beispiel #14
0
def test_kaleido_engine_to_image_kwargs():
    with mocked_scope() as scope:
        pio.to_image(
            fig,
            format="pdf",
            width=700,
            height=600,
            scale=2,
            engine="kaleido",
            validate=False,
        )

    scope.transform.assert_called_with(fig,
                                       format="pdf",
                                       width=700,
                                       height=600,
                                       scale=2)
def world_map(df, return_base64=False):
    """Create a world map.
    @param attribute: df (dataframe) dataframe containing the data
    @param attribute: return_base64 (bool): Whether to return the result as a
        base64 string or not.
    :returns: HTML or base64 string."""

    # Limit data to page views
    df = df[~df.type.str.contains('users')]

    scl = [[0.0, '#C5A653'], [0.2, '#C5A653'], [0.4, '#C5A653'],
           [0.6, '#C5A653'], [0.8, '#C5A653'], [1.0, '#C5A653']]

    data = [
        dict(
            type='choropleth',
            locations=df['country_iso_code'],
            z=df['value'],
            text=df['country'],
            colorscale=scl,
            showscale=False,
        )
    ]

    layout = dict(
        geo=dict(showframe=False,
                 showcoastlines=False,
                 showcountries=True,
                 projection=dict(type='equirectangular')),
        autosize=False,
        width=700,
        height=300,
        margin=go.layout.Margin(
            l=0,  # noqa: E741
            r=0,
            b=0,
            t=0,
            pad=0),
    )

    fig = dict(data=data, layout=layout)

    if return_base64:
        img = pio.to_image(
            fig,
            format='svg',
        )
        data = "data:image/svg;base64," + base64.b64encode(img).decode('utf8')
    else:
        # Generate the HTML
        data = plotly.offline.plot(
            fig,
            output_type='div',
            show_link=False,
            config=dict(displaylogo=False,
                        modeBarButtonsToRemove=['sendDataToCloud']))

    return mark_safe(data)
Beispiel #16
0
    def _figure_data(self, plot, fmt=None, divuuid=None, comm=True, as_script=False, width=800, height=600):
        # Wrapping plot.state in go.Figure here performs validation
        # and applies any default theme.
        figure = go.Figure(plot.state)

        if fmt in ('png', 'svg'):
            import plotly.io as pio
            data = pio.to_image(figure, fmt)
            if as_script:
                b64 = base64.b64encode(data).decode("utf-8")
                (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
                src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
                div = tag.format(src=src, mime_type=mime_type, css='')
                js = ''
                return div, js
            return data

        if divuuid is None:
            divuuid = plot.id

        jdata = json.dumps(figure.data, cls=utils.PlotlyJSONEncoder)
        jlayout = json.dumps(figure.layout, cls=utils.PlotlyJSONEncoder)

        config = {}
        config['showLink'] = False
        jconfig = json.dumps(config)

        if as_script:
            header = 'window.PLOTLYENV=window.PLOTLYENV || {};'
        else:
            header = ('<script type="text/javascript">'
                      'window.PLOTLYENV=window.PLOTLYENV || {};'
                      '</script>')

        script = '\n'.join([
            'var plotly = window._Plotly || window.Plotly;'
            'plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{',
            '    var elem = document.getElementById("{id}.loading"); elem.parentNode.removeChild(elem);',
            '}})']).format(id=divuuid,
                           data=jdata,
                           layout=jlayout,
                           config=jconfig)

        html = ('<div id="{id}.loading" style="color: rgb(50,50,50);">'
                'Drawing...</div>'
                '<div id="{id}" style="height: {height}; width: {width};" '
                'class="plotly-graph-div">'
                '</div>'.format(id=divuuid, height=height, width=width))
        if as_script:
            return html, header + script

        content = (
            '{html}'
            '<script type="text/javascript">'
            '  {script}'
            '</script>'
        ).format(html=html, script=script)
        return '\n'.join([header, content])
Beispiel #17
0
    def to_image(self, format="png", **kwargs):
        """creates static image, suffix dictates format"""
        from plotly.io import to_image

        fig = self.figure
        kwargs["width"] = kwargs.get("width", fig.layout.width)
        kwargs["height"] = kwargs.get("height", fig.layout.height)

        return to_image(fig, format=format, **kwargs)
Beispiel #18
0
def test_bytesio(fig1):
    """Verify that writing to a BytesIO object contains the same data as to_image().

    The goal of this test is to ensure that Plotly correctly handles a writable buffer
    which doesn't correspond to a filesystem path.
    """
    bio = BytesIO()
    pio.write_image(fig1, bio, format="jpg", validate=False)
    bio.seek(0)
    bio_bytes = bio.read()
    to_image_bytes = pio.to_image(fig1, format="jpg", validate=False)
    assert bio_bytes == to_image_bytes
Beispiel #19
0
    def to_mimebundle(self, fig_dict):
        image_bytes = to_image(fig_dict,
                               format=self.format,
                               width=self.width,
                               height=self.height,
                               scale=self.scale)

        if self.b64_encode:
            image_str = base64.b64encode(image_bytes).decode('utf8')
        else:
            image_str = image_bytes.decode('utf8')

        return {self.mime_type: image_str}
Beispiel #20
0
def test_problematic_environment_variables(fig1, format):
    pio.orca.config.restore_defaults(reset_server=True)

    os.environ['NODE_OPTIONS'] = '--max-old-space-size=4096'
    os.environ['ELECTRON_RUN_AS_NODE'] = '1'

    # Do image export
    img_bytes = pio.to_image(fig1, format=format, width=700, height=500)
    assert_image_bytes(img_bytes, 'fig1.' + format)

    # Check that environment variables were restored
    assert os.environ['NODE_OPTIONS'] == '--max-old-space-size=4096'
    assert os.environ['ELECTRON_RUN_AS_NODE'] == '1'
def test_problematic_environment_variables(fig1, format):
    pio.orca.config.restore_defaults(reset_server=True)

    os.environ["NODE_OPTIONS"] = "--max-old-space-size=4096"
    os.environ["ELECTRON_RUN_AS_NODE"] = "1"

    # Do image export
    img_bytes = pio.to_image(fig1, format=format, width=700, height=500)
    assert_image_bytes(img_bytes, "fig1." + format)

    # Check that environment variables were restored
    assert os.environ["NODE_OPTIONS"] == "--max-old-space-size=4096"
    assert os.environ["ELECTRON_RUN_AS_NODE"] == "1"
Beispiel #22
0
    def to_mimebundle(self, fig_dict):
        image_bytes = to_image(
            fig_dict,
            format=self.format,
            width=self.width,
            height=self.height,
            scale=self.scale,
            validate=False,
        )

        if self.b64_encode:
            image_str = base64.b64encode(image_bytes).decode('utf8')
        else:
            image_str = image_bytes.decode('utf8')

        return {self.mime_type: image_str}
Beispiel #23
0
def boxplot_scores(scores, name='Cost'):
    data = []
    for col in scores.columns:
        data.append(go.Box(y=scores[col], name=col, showlegend=False))

    layout = go.Layout(title=go.layout.Title(text='%s Boxplot' % name,
                                             xref='paper',
                                             x=0), )

    fig = go.Figure(data=data, layout=layout)

    if exporting == True:
        static_image_bytes = pio.to_image(fig, format='png')
        display(Image(static_image_bytes))
    else:
        display(iplot(fig))
Beispiel #24
0
def test_bytesio():
    """Verify that writing to a BytesIO object contains the same data as to_image().

    The goal of this test is to ensure that Plotly correctly handles a writable buffer
    which doesn't correspond to a filesystem path.
    """
    bio = BytesIO()
    pio.write_image(fig, bio, format="jpg", engine="kaleido", validate=False)
    bio.seek(
        0
    )  # Rewind to the beginning of the buffer, otherwise read() returns b''.
    bio_bytes = bio.read()
    to_image_bytes = pio.to_image(fig,
                                  format="jpg",
                                  engine="kaleido",
                                  validate=False)
    assert bio_bytes == to_image_bytes
    def to_mimebundle(self, fig_dict):
        image_bytes = to_image(
            fig_dict,
            format=self.format,
            width=self.width,
            height=self.height,
            scale=self.scale,
            validate=False,
            engine=self.engine,
        )

        if self.b64_encode:
            image_str = base64.b64encode(image_bytes).decode("utf8")
        else:
            image_str = image_bytes.decode("utf8")

        return {self.mime_type: image_str}
Beispiel #26
0
def make_sankey_chart(labels, sources, targets, values, descs,
                      title:str=DEFAULT_TITLE, black_theme:bool=False,
                      png:bool or (int, int)=False) -> str:
    "Return the HTML describing a sankey chart, according to given args"
    data = {
        'type': 'sankey',
        # 'width': 4000,
        # 'height': 1000,
        'orientation': 'h',
        'valuesuffix': " personnages",
        'valueformat': '.i',
        'node': {
            'pad': 15,
            'thickness': 3,
            'line': {'color': 'black'},
            'label': labels,
        },
        'link': {
            'source': sources,
            'target': targets,
            'value': values,
            'label': descs,
        }
    }
    layout = {'title': title, 'font': {'size': 12}}
    if black_theme:
        layout.update({
            'plot_bgcolor': 'black',
            'paper_bgcolor': 'black',
        })
        layout['font']['color'] = 'white'
    fig = {'data': [data], 'layout': layout}
    if png:
        kwargs = {}
        if not isinstance(png, bool):
            width, height = png
            if width: kwargs['width'] = width
            if height: kwargs['height'] = height
        return pio.to_image(
            fig,
            format='png',
            **kwargs
        )
    else:
        return plotly.offline.plot(fig, auto_open=False, output_type='div')
def main():
    n = 1
    file_prefix = 'fig'
    color = 'Viridis'
    zvmax = float('-inf')
    zvmin = float('inf')
    images = []
    print('Converting output ...')
    with open("output_wave2d.txt", 'r') as f:
        lines = f.readlines()
        for counter, line in enumerate(lines[:-1]):
            line = line.replace('|\n', '')
            rows = line.split('|')
            matrix = []

            for row in rows:
                try:
                    vals = list(literal_eval(row))
                    matrix.append(vals)
                    temp_min = np.min(vals)
                    temp_max = np.max(vals)
                    if (temp_min < zvmin):
                        zvmin = temp_min
                    if (temp_max > zvmax):
                        zvmax = temp_max

                except Exception as e:
                    print(row)

            fig = go.Figure()
            fig.add_heatmap(z=matrix, zmin=-32, zmax=20, colorscale=color)

            print(n)
            n += 1
            #pio.write_image(fig, f'{file_prefix}{int(counter + 1)}.png')
            images.append(
                pio.to_image(fig, format='png', width=700, height=500))

    print("Range: [", zvmin, ", ", zvmax, "]")
    print('Creating animation ...')
    convertGif(file_prefix, f'Wave2D_{color}', n, images)
    print('Cleaning up ...')
    cleanUp(file_prefix, n)
    print('Done.')
Beispiel #28
0
def fig_to_buffer(fig,
                  format,
                  width=DEFAULT_WIDTH,
                  height=DEFAULT_HEIGHT,
                  margin=None,
                  scale=DEFAULT_SCALE):
    """Converts the specified figure to an image buffer with the specified format."""
    update_layout_size(fig, width=width, height=height, margin=margin)
    if is_matplot(fig):
        buffer = io.BytesIO()
        fig.savefig(buffer, format=format, dpi=scale * 100)
        buffer.seek(0)
        return buffer.read()
    elif is_plotly(fig):
        return pio.to_image(fig,
                            format=format,
                            width=width,
                            height=height,
                            scale=scale)
def test_png_renderer_mimetype(fig1):
    pio.renderers.default = 'png'

    # Configure renderer so that we can use the same parameters
    # to build expected image below
    pio.renderers['png'].width = 400
    pio.renderers['png'].height = 500
    pio.renderers['png'].scale = 1

    image_bytes = pio.to_image(fig1, width=400, height=500, scale=1)
    image_str = base64.b64encode(image_bytes).decode('utf8')

    expected = {'image/png': image_str}

    pio.renderers.render_on_display = False
    assert fig1._repr_mimebundle_(None, None) is None

    pio.renderers.render_on_display = True
    bundle = fig1._repr_mimebundle_(None, None)
    assert bundle == expected
def test_pdf_renderer_show_override(fig1):
    pio.renderers.default = None

    # Configure renderer so that we can use the same parameters
    # to build expected image below
    pio.renderers['png'].width = 400
    pio.renderers['png'].height = 500
    pio.renderers['png'].scale = 1

    image_bytes_png = pio.to_image(
        fig1, format='png', width=400, height=500, scale=1)

    image_str_png = base64.b64encode(image_bytes_png).decode('utf8')

    with mock.patch('IPython.display.display') as mock_display:
        pio.show(fig1, renderer='png')

    expected_bundle = {'image/png': image_str_png}

    mock_display.assert_called_once_with(expected_bundle, raw=True)
Beispiel #31
0
def createPieChart(filename, xAxis, yAxis, name):
    trace1 = go.Pie(labels=list(xAxis), values=list(yAxis))

    layout = go.Layout(title=name)

    data = [trace1]
    fig = go.Figure(data=data, layout=layout)

    img_bytes = pio.to_image(fig,
                             format='PNG',
                             width=1600,
                             height=960,
                             scale=2)

    if not os.path.exists('images/pie'):
        os.mkdir('images/pie')

    with open('images/pie/' + filename + '.PNG', 'wb') as f:
        f.write(img_bytes)
    return
def test_mimetype_combination(fig1):
    pio.renderers.default = "png+jupyterlab"

    # Configure renderer so that we can use the same parameters
    # to build expected image below
    pio.renderers["png"].width = 400
    pio.renderers["png"].height = 500
    pio.renderers["png"].scale = 1

    # pdf
    image_bytes = pio.to_image(fig1,
                               format="png",
                               width=400,
                               height=500,
                               scale=1)

    image_str = base64.b64encode(image_bytes).decode("utf8")

    # plotly mimetype
    plotly_mimetype_dict = json.loads(pio.to_json(fig1, remove_uids=False))

    plotly_mimetype_dict["config"] = {
        "plotlyServerURL": _get_jconfig()["plotlyServerURL"]
    }

    # Build expected bundle
    expected = {"image/png": image_str, plotly_mimetype: plotly_mimetype_dict}

    pio.renderers.render_on_display = False

    with mock.patch("IPython.display.display") as mock_display:
        fig1._ipython_display_()

    # assert fig1._repr_mimebundle_(None, None) is None
    mock_display.assert_not_called()

    pio.renderers.render_on_display = True
    with mock.patch("IPython.display.display") as mock_display:
        fig1._ipython_display_()

    mock_display.assert_called_once_with(expected, raw=True)
Beispiel #33
0
def home():
  data = request.json
  df = pd.DataFrame.from_dict(data)
  df.head()
  geojson="https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson"
  fig = px.choropleth(
    df[['States','Deaths']],
    geojson="https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson",
    featureidkey='properties.ST_NM',
    locations='States',
    color='Deaths',
    color_continuous_scale='Reds',
    )

  fig.update_geos(fitbounds="locations", visible=False)
  unwrapped = plotly.io._orca.request_image_with_retrying.__wrapped__
  wrapped = retrying.retry(wait_random_min=1000)(unwrapped)
  plotly.io._orca.request_image_with_retrying = wrapped
  img_bytes =  pio.to_image(fig,format='png')
  encoding = b64encode(img_bytes).decode()
  return str(encoding)
Beispiel #34
0
def test_external_server_url():
    # Build server url
    port = find_open_port()
    server_url = "http://{hostname}:{port}".format(hostname="localhost", port=port)

    # Build external orca command
    orca_path = which("orca")
    cmd_list = [orca_path] + [
        "serve",
        "-p",
        str(port),
        "--plotly",
        pio.orca.config.plotlyjs,
        "--graph-only",
    ]

    # Run orca as subprocess to simulate external orca server
    DEVNULL = open(os.devnull, "wb")
    with orca_env():
        proc = subprocess.Popen(cmd_list, stdout=DEVNULL)

    # Start plotly managed orca server so we can ensure it gets shut down properly
    pio.orca.config.port = port
    pio.orca.ensure_server()
    assert pio.orca.status.state == "running"

    # Configure orca to use external server
    pio.orca.config.server_url = server_url

    # Make sure that the locally managed orca server has been shutdown and the local
    # config options have been cleared
    assert pio.orca.status.state == "unvalidated"
    assert pio.orca.config.port is None

    fig = go.Figure()
    img_bytes = pio.to_image(fig, format="svg")
    assert img_bytes.startswith(b"<svg class")

    # Kill server orca process
    proc.terminate()
Beispiel #35
0
def test_simple_to_image(fig1, format):
    img_bytes = pio.to_image(fig1, format=format, width=700, height=500)
    assert_image_bytes(img_bytes, 'fig1.' + format)
    def sample(self, filename, save_samples):
        gan = self.gan
        generator = gan.generator.sample

        sess = gan.session
        config = gan.config

        contours = args.contour_size

        x,y = np.meshgrid(np.arange(-1.5, 1.5, 3/contours), np.arange(-1.5, 1.5, 3/contours))
        d = []
        for i in range(args.contour_size):
            _x = np.reshape(x[:,i], [-1]) 
            _y = np.reshape(y[:,i], [-1]) 
            for j in range(args.contour_size // gan.batch_size()):
                offset = j*gan.batch_size()
                endoffset = (j+1)*gan.batch_size()
                _x_sample = _x[offset:endoffset]
                _y_sample = _y[offset:endoffset]
                _d = gan.session.run(gan.loss.d_real, {gan.inputs.x: [[__x,__y] for __x, __y in zip(_x_sample, _y_sample)]})
                d.append(_d)
        contour = go.Contour(
            z = np.reshape(d, [-1]),
            x = np.reshape(x, [-1]),
            y = np.reshape(y, [-1]),
            opacity=0.5,
            showlegend=False,
            contours = dict(
                start=-0.5,
                end=0.5,
                size=0.03,
            )
        )
        print(np.shape(x), np.shape(y))
        #z = sess.run(gan.discriminator.sample, 

        global x_v, z_v
        if x_v is None:
            x_v = []
            z_v = []
            for j in range(args.sample_points // gan.batch_size()):
                _x_v, _z_v = sess.run([gan.inputs.x, gan.latent.sample])
                x_v.append(_x_v)
                z_v.append( _z_v)
            x_v = np.reshape(x_v, [-1,gan.inputs.x.shape[1]])
            z_v = np.reshape(z_v, [-1,gan.latent.sample.shape[1]])

        sample = []
        for j in range(args.sample_points // gan.batch_size()):
            offset = j*gan.batch_size()
            endoffset = (j+1)*gan.batch_size()
            z_v_sample = z_v[offset:endoffset]
            x_v_sample = x_v[offset:endoffset]
            _sample = sess.run(generator, {gan.inputs.x: x_v_sample, gan.latent.sample: z_v_sample})
            sample.append(_sample)
        sample = np.reshape(sample, [-1, 2])
        points = go.Scatter(x=sample[:,0], y=sample[:,1],
                mode='markers',
                marker = dict(
                    size = 10,
                    color = 'rgba(0, 152, 0, .8)',
                    line = dict(
                       width = 2,
                       color = 'rgb(0, 0, 0)'
                    )),
                name='fake')

        xpoints = go.Scatter(x=x_v[:,0], y=x_v[:,1],
                mode='markers',
                marker = dict(
                    size = 10,
                    color = 'rgba(255, 182, 193, .9)',
                    line = dict(
                       width = 2,
                       color = 'rgb(0, 0, 0)'
                    )),
                name='real')

        layout = go.Layout(hovermode='closest',
                xaxis=dict(range=[-1.5,1.5]),
                yaxis=dict(range=[-1.5,1.5]),
                width=1920,
                showlegend=False,
                height=1080
        )
        fig = go.Figure([contour, xpoints, points], layout=layout)
        data = pio.to_image(fig, format='png')
        #pio.write_image(fig,"sample.png")
        img = Image.open(io.BytesIO(data))
        #img = Image.open("sample.png").convert("RGB")
        #img.save("save.jpg")
        #plt.savefig(filename)
        self.plot(np.array(img), filename, save_samples, regularize=False)
        return [{'image': filename, 'label': '2d'}]
Beispiel #37
0
def test_latex_fig_to_image(latexfig, format):
    img_bytes = pio.to_image(latexfig, format=format, width=700, height=500)
    assert_image_bytes(img_bytes, 'latexfig.' + format)
Beispiel #38
0
def test_topojson_fig_to_image(topofig, format):
    img_bytes = pio.to_image(topofig, format=format, width=700, height=500)
    assert_image_bytes(img_bytes, 'topofig.' + format)
Beispiel #39
0
def test_to_image_default(fig1, format):
    pio.orca.config.default_format = format
    img_bytes = pio.to_image(fig1, width=700, height=500)
    assert_image_bytes(img_bytes, 'fig1.' + format)