Example #1
0
def get_table_from_sheet(date):
    month = date.strftime("%B")
    result = SheetService().read_sheet_multiple(
        SPREADSHEET_ID, [f'{month}!A2:C', f'{month}!E2:G', f'{month}!I2:K'],
        major_dimension='COLUMNS')
    values = result.get('valueRanges', [])
    header = []
    l_ = []
    if len(values) > 0:
        for val in values:
            header = header + [item[0] for item in val['values']]
            l_ = l_ + [i[1:] for i in val['values']]
        scope = PlotlyScope()
        fig = go.Figure(data=[
            go.Table(columnwidth=[80, 150, 100, 80, 150, 100, 100, 100],
                     header=dict(values=header),
                     cells=dict(values=l_,
                                fill=dict(color=[
                                    'lightgreen', 'lightgreen', 'lightgreen',
                                    '#ff9982', '#ff9982', '#ff9982', '#ffbf70',
                                    '#ffbf70'
                                ]),
                                height=30))
        ])
        test = scope.transform(fig, format="png", scale=2)
        str_file = io.BytesIO(test)
        return str_file
    else:
        return None
Example #2
0
class Kaleido:
    def __init__(self):
        # Init scopes
        if not STATIC_EXPORT:
            raise ImportError(
                "Static export is not possible due to missing dependencies")
        self.plotly_scope = PlotlyScope()

    def render_plotly_svg(self, fig, width=None, height=None):
        """
        Function to render a plotly figure in SVG inside jupyter
        """
        if STATIC_EXPORT:
            svg_fig = self.plotly_scope.transform(fig,
                                                  format="svg",
                                                  width=width,
                                                  height=height)
            return SVG(svg_fig)

    def export_plotly_svg(self, fig, fn, width=None, height=None):
        """
        Function to export a plotly figure to SVG
        """
        if STATIC_EXPORT:
            svg_fig = self.plotly_scope.transform(fig,
                                                  format="svg",
                                                  width=width,
                                                  height=height)
            with open(fn, mode="wb") as fp:
                fp.write(svg_fig)
Example #3
0
 def save_static(self, figformat):
     scope = PlotlyScope()
     with open(self.path.replace('html', figformat), "wb") as f:
         f.write(scope.transform(self.fig, format=figformat))
         logging.info(
             f"Saved {self.path.replace('.html', '')}  as {figformat} (or png for --legacy)"
         )
Example #4
0
def test_missing_mapbox_token():
    fig = mapbox_figure()
    local_scope = PlotlyScope(mapbox_access_token=None)
    with pytest.raises(ValueError) as e:
        local_scope.transform(fig)

    e.match("access token")
Example #5
0
def test_bad_format_file():
    fig = simple_figure()
    local_scope = PlotlyScope()
    with pytest.raises(ValueError) as e:
        local_scope.transform(fig, format='bogus')

    e.match("Invalid format")
Example #6
0
    def datauri_from_fig(fig,
                         fmt: str = "png",
                         width: int = 600,
                         height: int = 400,
                         scale: int = 4) -> str:
        """
        Generate a data URI from a Plotly Figure.

        :param fig: Plotly Figure object or corresponding dictionary
        :param fmt: "png", "jpg", etc. (see PlotlyScope for supported formats)
        :param width: width in pixels
        :param height: height in pixels
        :param scale: scale factor
        :return:
        """

        from kaleido.scopes.plotly import PlotlyScope

        scope = PlotlyScope()
        output = scope.transform(fig,
                                 format=fmt,
                                 width=width,
                                 height=height,
                                 scale=scale)
        image = b64encode(output).decode("ascii")

        return f"data:image/{fmt};base64,{image}"
Example #7
0
def _create_donut(df, lang, filename, width, height, fontsize):
    scope = PlotlyScope()
    sentiment = get_sentiment(df, lang)
    labels, values = dict_to_list(sentiment)
    if lang == "tr":
        labels = ["Pozitif", "Nötr", "Negatif"]
    if lang == "en":
        labels = [label.capitalize() for label in labels]
    colors = ["darkgreen", "lightgreen", "red"]
    fig = go.Figure(data=[
        go.Pie(labels=labels,
               values=values,
               hole=0.5,
               textinfo="label+percent+value",
               textposition="inside")
    ])
    fig.update_traces(marker=dict(colors=colors),
                      textfont_size=fontsize,
                      showlegend=False)
    fig.update_layout(margin=dict(l=0, r=0, b=0, t=0, pad=4),
                      paper_bgcolor="rgba(0,0,0,0)",
                      plot_bgcolor="rgba(0,0,0,0)",
                      width=width,
                      height=height)
    fname_stamped = filename + "".join(str(time()).split("."))
    donuts_filenames[filename] = "img/" + fname_stamped + ".svg"
    with open(f"mint/static/img/{fname_stamped}.svg", "wb") as f:
        f.write(scope.transform(fig, format="svg"))
Example #8
0
def generate(data, title: str, format: str = "svg") -> go.Figure:
    datetimes = []
    prices = []
    for kp in data:
        if kp['price'] is not None and kp['date'] is not None:
            if type(kp['date']) != 'datetime':
                dt = datetime.datetime.strptime(kp['date'], "%Y-%m-%d")
                datetimes.append(dt)
            else:
                datetimes.append(kp['date'])
            prices.append(kp['price'])
        
    fig = go.Figure(
        data = go.Scatter(x=datetimes, y=prices), 
        layout = dict( 
            title = dict(
                text=title
            )
        )
    )

    scope = PlotlyScope()
    img = scope.transform(fig, format=format)
    # img = plotly.io.to_image(fig=fig, format=format)
    return img
Example #9
0
def test_plotlyjs_file_url():
    fig = simple_figure()
    plotlyjs_url = local_plotlyjs_url
    local_scope = PlotlyScope(plotlyjs=plotlyjs_url)

    result = local_scope.transform(fig, format='png', width=700, height=500, scale=1)
    expected = load_baseline('simple', 'png')
    assert result == expected
Example #10
0
def save_fig(date_str, new=True):
    '''Saves either new/total plot for a given date YYYY-MM-DD
    as a .png file.'''
    if new:
        kind = 'new'
    else:
        kind = 'total'

    fig = create_fig(date_str, new)
    scope = PlotlyScope()
    with open(f'{kind}_cases/{date_str}_{kind}_cases.png', 'wb') as f:
        f.write(scope.transform(fig, format='png'))
Example #11
0
def boxplot(dataset, title, render="colab", filename='figure.png'):
    fig = go.Figure()
    fig.add_trace(
        go.Box(x=dataset,
               name=str(title),
               fillcolor=L_BLUE_BOX,
               marker_color=L_YELOW,
               marker_size=10,
               line_width=1.5,
               boxmean=True))
    fig.update_layout(height=250,
                      paper_bgcolor=COLAB_BKGROUND,
                      font={'color': ORANGE},
                      margin={
                          'l': 50,
                          't': 5,
                          'b': 30
                      },
                      plot_bgcolor=PLOT_BKGROUND,
                      xaxis={
                          'gridcolor': BLACK_GRID,
                          'zerolinecolor': BLACK_GRID
                      },
                      yaxis={
                          'autorange': True,
                          'showgrid': True,
                          'zeroline': True,
                          'dtick': 5,
                          'gridcolor': BLACK_GRID,
                          'gridwidth': 1,
                          'zerolinecolor': BLACK_GRID,
                          'zerolinewidth': 4
                      },
                      showlegend=False,
                      hovermode='x',
                      hoverlabel=dict(bgcolor=PLOT_BKGROUND,
                                      font_size=14,
                                      font_family="verdana"))
    if render == 'png':
        scope = PlotlyScope()
        with open(filename, "wb") as f:
            f.write(scope.transform(fig, format="png"))
        display(Image(filename=filename))
    else:
        fig.show()
Example #12
0
def plot_meter(value,
               reference=10,
               render="colab",
               filename='figure.png',
               title='Error medio'):
    '''Medidor tipo `barra horizontal` de una sola magnitud'''
    fig = go.Figure(
        go.Indicator(mode="number+gauge+delta",
                     gauge={
                         'shape': "bullet",
                         'bgcolor': PLOT_BKGROUND,
                         'bar': {
                             'color': L_GREEN
                         }
                     },
                     align='center',
                     value=value,
                     delta={'reference': reference},
                     domain={
                         'x': [0, 1],
                         'y': [0, 1]
                     },
                     title={
                         'text': "<b style = 'color: " + ORANGE + ";'>" +
                         title + "</b>",
                         'font': {
                             "size": 18
                         }
                     }))
    fig.update_layout(height=50,
                      paper_bgcolor=COLAB_BKGROUND,
                      font={'color': ORANGE},
                      margin={
                          'l': 150,
                          't': 0,
                          'b': 0
                      })
    if render == 'png':
        scope = PlotlyScope()
        with open(filename, "wb") as f:
            f.write(scope.transform(fig, format="png"))
        display(Image(filename=filename))
    else:
        fig.show()
Example #13
0
def plot_pattcorr(PC, labels, plotpath, lats, latn):
    """
    Plot pattern correlation curves as a function of lead time.
    :param PC:
    :type PC:
    :param labels:
    :type labels:
    :param plotpath:
    :type plotpath:
    :param region:
    :type region: str
    :return:
    :rtype:
    """

    latstring = get_latstring(lats, latn)

    plttype = "png"
    plotname = plotpath + "PatternCorrelationHovmoeller." + plttype
    nlines = len(labels)

    colors = ['black', 'dodgerblue', 'orange', 'seagreen', 'firebrick']

    scope = PlotlyScope()
    fig = go.Figure()
    for ll in np.arange(0, nlines):
        fig.add_trace(
            go.Scatter(x=PC['fchrs'],
                       y=PC[:, ll],
                       mode='lines',
                       name=labels[ll],
                       line=dict(color=colors[ll], width=2)))

    fig.update_layout(title=latstring)

    fig.update_xaxes(ticks="", tick0=0, dtick=24, title_text='lead time (h)')
    fig.update_yaxes(ticks="",
                     range=[0, 1],
                     dtick=0.1,
                     title_text='correlation')

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))
Example #14
0
def test_gpu_arg():
    # --disable-gpu is a default
    assert "--disable-gpu" in PlotlyScope.default_chromium_args()

    # Check that --disable-gpu is in scope instance chromium_args
    scope = PlotlyScope()
    assert "--disable-gpu" in scope.chromium_args
    assert "--disable-gpu" in scope._build_proc_args()

    # Check that --disable-gpu is in scope instance chromium_args
    scope = PlotlyScope(disable_gpu=False)
    assert "--disable-gpu" not in scope.chromium_args
    assert "--disable-gpu" not in scope._build_proc_args()
    scope.disable_gpu = True
    assert "--disable-gpu" in scope.chromium_args
    assert "--disable-gpu" in scope._build_proc_args()
Example #15
0
def plot_activity(act, wavename, labels, plotpath, fchr=[]):
    """
    Plot pattern correlation curves as a function of lead time.
    :param act:
    :type act:
    :param labels:
    :type labels:
    :return:
    :rtype:
    """

    plttype = "png"
    plotname = plotpath + wavename + "Activity." + plttype
    if fchr:
        plotname = plotpath + wavename + "Activity_f" + f"{fchr:03d}" + "." + plttype

    nlines, ntim = act.shape

    timestr = get_timestr(act['time'])

    colors = ['black', 'dodgerblue', 'orange', 'seagreen', 'firebrick']

    scope = PlotlyScope()
    fig = go.Figure()
    for ll in np.arange(nlines):
        fig.add_trace(
            go.Scatter(x=timestr,
                       y=act[ll, :].values,
                       mode='lines',
                       name=labels[ll],
                       line=dict(color=colors[ll], width=2)))

    fig.update_layout(title=wavename + " FH" + f"{fchr:03d}",
                      yaxis=dict(range=[0, 25]))

    #fig.update_xaxes(ticks="", tick0=0, dtick=12, title_text='date')
    fig.update_yaxes(ticks="", tick0=0, dtick=1., title_text='activity')

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))
Example #16
0
def _create_timeviz_donut(df, lang, filename, width, height, fontsize, metric):
    # Template function for creating donut graphs based on time segments
    # For more info about time segments, check time_utils.py
    scope = PlotlyScope()
    labels, values = None, None
    if metric not in ["weekdays", "hours"]:
        raise ValueError("weekdays and hours are available time viz metrics")
    if metric == "weekdays" and lang not in ["tr", "en"]:
        raise ValueError("parameter lang should be either en or tr")
    if metric == "weekdays":
        scores = get_weekdays_score(df)
        labels, values = dict_to_list(scores)
        if lang == "tr":
            labels = ["Hafta içi", "Hafta sonu"]
        if lang == "en":
            labels = [label.capitalize() for label in labels]
    if metric == "hours":
        scores = get_hours_score(df)
        labels, values = dict_to_list(scores)
        labels = [
            "00:00 - 06:59", "07:00 - 12:59", "13:00 - 17:59", "18:00 - 23:59"
        ]
    fig = go.Figure(data=[
        go.Pie(labels=labels,
               values=values,
               hole=0.5,
               textinfo="label+percent+value",
               textposition="inside")
    ])
    fig.update_traces(textfont_size=fontsize, showlegend=False)
    fig.update_layout(margin=dict(l=0, r=0, b=0, t=0, pad=4),
                      paper_bgcolor="rgba(0,0,0,0)",
                      plot_bgcolor="rgba(0,0,0,0)",
                      width=width,
                      height=height)
    fname_stamped = filename + "".join(str(time()).split("."))
    timeviz_filenames[filename] = "img/" + fname_stamped + ".svg"
    with open(f"mint/static/img/{fname_stamped}.svg", "wb") as f:
        f.write(scope.transform(fig, format="svg"))
Example #17
0
def plot_skill(skill, wavename, labels, plotpath):
    """
    Plot pattern correlation curves as a function of lead time.
    :param skill:
    :type skill:
    :param labels:
    :type labels:
    :return:
    :rtype:
    """

    plttype = "png"
    plotname = plotpath + wavename + "Skill." + plttype

    nfchr, nlines = skill.shape

    colors = ['dodgerblue', 'orange', 'seagreen', 'firebrick']

    scope = PlotlyScope()
    fig = go.Figure()
    for ll in np.arange(nlines):
        fig.add_trace(
            go.Scatter(x=skill['fchrs'],
                       y=skill[:, ll],
                       mode='lines',
                       name=labels[ll],
                       line=dict(color=colors[ll], width=2)))

    fig.update_layout(title=wavename + " skill", yaxis=dict(range=[0, 1]))

    fig.update_xaxes(ticks="", tick0=0, dtick=24, title_text='lead time (h)')
    fig.update_yaxes(ticks="",
                     tick0=0,
                     dtick=0.1,
                     title_text='skill correlation')

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))
Example #18
0
from __future__ import absolute_import
from six import string_types
import os
import json
from pathlib import Path
import plotly
from plotly.io._utils import validate_coerce_fig_to_dict

try:
    from kaleido.scopes.plotly import PlotlyScope

    scope = PlotlyScope()

    # Compute absolute path to the 'plotly/package_data/' directory
    root_dir = os.path.dirname(os.path.abspath(plotly.__file__))
    package_dir = os.path.join(root_dir, "package_data")
    scope.plotlyjs = os.path.join(package_dir, "plotly.min.js")
    if scope.mathjax is None:
        scope.mathjax = (
            "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js")
except ImportError:
    PlotlyScope = None
    scope = None


def to_image(fig,
             format=None,
             width=None,
             height=None,
             scale=None,
             validate=True,
Example #19
0
from kaleido.scopes.plotly import PlotlyScope
import plotly.graph_objects as go
scope = PlotlyScope()

fig = go.Figure(data=[go.Scatter(y=[1, 3, 2])])
with open("figure.png", "wb") as f:
    f.write(scope.transform(fig, format="png"))
Example #20
0
def generar_reportes(fig_principal, fig_sec1, fig_sec2, valor_promedio,
                     valor_max, valor_min, fecha_valor_max, fecha_valor_min,
                     num_valor_max, num_valor_min, alert_sup, alert_inf,
                     fecha_alert_sup, fecha_alert_inf, sensor, sensor_multi,
                     fecha, ventana_tiempo, valor_linea_control_sup,
                     valor_linea_control_inf, hora, cantidad_sensores, ejes,
                     eje):
    scope = PlotlyScope()

    #Transforma las figuras (graficos generados) en uri, para poder ser visualizados en html
    #Escritorio
    def fig_to_uri(fig):
        return base64.b64encode(scope.transform(fig,
                                                format="png")).decode('utf-8')

    #Transforma el logo en uri, para poder ser visualizados en html
    with open("./DatosRecientes/assets/SHM-logo2.bmp", "rb") as imageFile:
        logo = base64.b64encode(imageFile.read()).decode('utf-8')

    # se guardan los garficos en formato uri en una lista
    #escritorio
    graficos = [
        fig_to_uri(fig_principal),
        fig_to_uri(fig_sec1),
        fig_to_uri(fig_sec2)
    ]

    # si es mas de 1 sensor en la visualizacion, se guardan los nombres en un string
    sensores_multi = ''
    ejes_uni = ''

    if cantidad_sensores != '1-sensor':
        for sen in sensor_multi:
            sensores_multi += str(sen) + ','
    else:
        for e in ejes:
            ejes_uni += str(e) + ','
    meses = [
        '', 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio',
        'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'
    ]
    fecha_datos = str(fecha).split(sep='T')[0]
    fecha_max = str(fecha_valor_max).split(sep=' ')[0]
    fecha_min = str(fecha_valor_min).split(sep=' ')[0]
    dia_datos = str(fecha_datos).split(sep='-')[2]
    dia_max = str(fecha_max).split(sep='-')[2]
    dia_min = str(fecha_min).split(sep='-')[2]
    mes_datos = str(meses[int(str(fecha_datos).split(sep='-')[1])])
    mes_max = str(meses[int(str(fecha_max).split(sep='-')[1])])
    mes_min = str(meses[int(str(fecha_min).split(sep='-')[1])])
    ano_datos = str(fecha_datos).split(sep='-')[0]
    ano_max = str(fecha_max).split(sep='-')[0]
    ano_min = str(fecha_min).split(sep='-')[0]

    if valor_linea_control_sup != None and valor_linea_control_inf != None:
        fecha_inf = str(fecha_alert_inf).split(sep=' ')[0]
        fecha_sup = str(fecha_alert_sup).split(sep=' ')[0]
        dia_inf = str(fecha_inf).split(sep='-')[2]
        dia_sup = str(fecha_sup).split(sep='-')[2]
        mes_inf = str(meses[int(str(fecha_inf).split(sep='-')[1])])
        mes_sup = str(meses[int(str(fecha_sup).split(sep='-')[1])])
        ano_inf = str(fecha_inf).split(sep='-')[0]
        ano_sup = str(fecha_sup).split(sep='-')[0]
    elif valor_linea_control_inf != None:
        fecha_inf = str(fecha_alert_inf).split(sep=' ')[0]
        dia_inf = str(fecha_inf).split(sep='-')[2]
        mes_inf = str(meses[int(str(fecha_inf).split(sep='-')[1])])
        ano_inf = str(fecha_inf).split(sep='-')[0]
    elif valor_linea_control_sup != None:
        fecha_sup = str(fecha_alert_sup).split(sep=' ')[0]
        dia_sup = str(fecha_sup).split(sep='-')[2]
        mes_sup = str(meses[int(str(fecha_sup).split(sep='-')[1])])
        ano_sup = str(fecha_sup).split(sep='-')[0]

    ##Plantilla html
    encabezado_multi = (
        '<html lang="es">'
        '<head>'
        '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>'
        '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">'
        '<style>body{ margin:0 100; background:whitesmoke; }</style>'
        '</head>'
        '<body style="margin:60">'
        '<h1 style="text-align: center;"><img style="font-size: 14px; text-align: justify; float: left;" src="data:image/png;base64,'
        + logo +
        '" alt="Logo SHM" width="102" height="73" margin= "5px"/></h1>'
        '<h1 style="text-align: left;"><span style="font-family:arial,helvetica,sans-serif;"><strong>  Datos Recientes</strong></h1>'
        '<h2> <span style="font-family:arial,helvetica,sans-serif;">Plataforma Monitoreo Salud Estructural</h2>'
        '<p>&nbsp;</p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Datos obtenidos de los sensores <strong>"'
        + str(sensores_multi) + '"</strong> en el eje <strong>"' + str(eje) +
        '"</strong>, la ventana de tiempo seleccionada para las visualizaciones es de <strong>"'
        + str(titulo_OHLC(ventana_tiempo)) + '"</strong>, el dia ' +
        str(dia_datos) + ' de ' + str(mes_datos) + ' de ' + str(ano_datos) +
        ' desde las ' + str(crear_hora(int(hora))) + ' a las ' +
        str(crear_hora(int(hora) + 1)) + ' .</p>'
        '<p>&nbsp;</p>')

    #heroku
    '''
    img = (''
        '<p><div style="display: block; margin-left: auto; margin-right: auto; height:400; width:850;"> {image} </div></p>'
        '')

    img2 = (''
        '<p><div style="display: block; margin-left: auto; margin-right: auto; height:400; width:600;"> {image} </div></p>'
        '')
    '''
    #Escritorio

    img = (
        ''
        '<p><img style="display: block; margin-left: auto; margin-right: auto;" src="data:image/png;base64,{image}" alt="Gr&aacute;fico Principal" width="850" height="400" /></p>'
        '')
    img2 = (
        ''
        '<p><img style="display: block; margin-left: auto; margin-right: auto;" src="data:image/png;base64,{image}" alt="Gr&aacute;fico Principal" width="600" height="400" /></p>'
        '')

    encabezado = (
        '<html lang="es">'
        '<head>'
        '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>'
        '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">'
        '<style>body{ margin:0 100; background:whitesmoke; }</style>'
        '</head>'
        '<body style="margin:60">'
        '<h1 style="text-align: center;"><img style="font-size: 14px; text-align: justify; float: left;" src="data:image/png;base64,'
        + logo +
        '" alt="Logo SHM" width="102" height="73" margin= "5px"/></h1>'
        '<h1 style="text-align: left;"><span style="font-family:arial,helvetica,sans-serif;"><strong>  Datos Recientes</strong></h1>'
        '<h2> <span style="font-family:arial,helvetica,sans-serif;">Plataforma Monitoreo Salud Estructural</h2>'
        '<p>&nbsp;</p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Datos obtenidos del sensor <strong>"'
        + str(sensor) + '"</strong> en los eje(s) <strong>"' + str(ejes_uni) +
        '"</strong>, la ventana de tiempo seleccionada para las visualizaciones es de <strong>"'
        + str(titulo_OHLC(ventana_tiempo)) + '"</strong>, el dia ' +
        str(dia_datos) + ' de ' + str(mes_datos) + ' de ' + str(ano_datos) +
        ' desde las ' + str(crear_hora(int(hora))) + ' a las ' +
        str(crear_hora(int(hora) + 1)) + ' .</p>'
        '<p>&nbsp;</p>')

    resumen = (
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;"><strong>Resumen de Indicadores</strong></p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor promedio: <strong>'
        + str(valor_promedio) + '</strong></p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor m&aacute;ximo: <strong>'
        + str(valor_max) + '</strong>,   Repeticiones: <strong>' +
        str(num_valor_max)[10:len(str(num_valor_max))] +
        '</strong>,   Fecha de &uacute;ltima repetici&oacute;n: <strong>' +
        str(dia_max) + '-' + str(mes_max) + '-' + str(ano_max) + ' ' +
        str(fecha_valor_max).split(sep=' ')[1] + '</strong></p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor m&iacute;nimo: <strong>'
        + str(valor_min) + '</strong>,   Repeticiones: <strong>' +
        str(num_valor_min)[10:len(str(num_valor_min))] +
        '</strong>,   Fecha de &uacute;ltima repetici&oacute;n: <strong>' +
        str(dia_min) + '-' + str(mes_min) + '-' + str(ano_min) + ' ' +
        str(fecha_valor_min).split(sep=' ')[1] + '</strong></p>'
        '<p>&nbsp;</p>')
    resumen_multi = (
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;"><strong>Resumen de Indicadores</strong></p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">(Datos del &uacute;ltimo sensor seleccionado)</p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor promedio: <strong>'
        + str(valor_promedio) + '</strong></p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor m&aacute;ximo: <strong>'
        + str(valor_max) + '</strong>,   Repeticiones: <strong>' +
        str(num_valor_max)[10:len(str(num_valor_max))] +
        '</strong>,   Fecha de &uacute;ltima repetici&oacute;n: <strong>' +
        str(dia_max) + '-' + str(mes_max) + '-' + str(ano_max) + ' ' +
        str(fecha_valor_max).split(sep=' ')[1] + '</strong></p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor m&iacute;nimo: <strong>'
        + str(valor_min) + '</strong>,   Repeticiones: <strong>' +
        str(num_valor_min)[10:len(str(num_valor_min))] +
        '</strong>,   Fecha de &uacute;ltima repetici&oacute;n: <strong>' +
        str(dia_min) + '-' + str(mes_min) + '-' + str(ano_min) + ' ' +
        str(fecha_valor_min).split(sep=' ')[1] + '</strong></p>'
        '<p>&nbsp;</p>')

    #version con indicadores descritos en parrafos
    '''
    resumen = (
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;"><strong>Resumen de Indicadores</strong></p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Los datos seleccionados tienen un valor promedio de '+str(valor_promedio)+', adem&aacute;s de un valor m&aacute;ximo de '+str(valor_max)+', que se repite '+str(num_valor_max)[10:len(str(num_valor_max))]+' vez y su &uacute;ltima repetici&oacute;n fue el '+str(dia_max)+' de '+str(mes_max)+' de '+str(ano_max)+' a las '+str(fecha_valor_max).split(sep=' ')[1]+' y por &uacute;ltimo un valor m&iacute;nimo de '+str(valor_min)+' que se repite '+str(num_valor_min)[10:len(str(num_valor_min))]+' vez y su &uacute;ltima repetici&oacute;n fue el '+str(dia_min)+' de '+str(mes_min)+' de '+str(ano_min)+' a las '+str(fecha_valor_min).split(sep=' ')[1]+'.</p>'
        '<p>&nbsp;</p>'
    )
    resumen_multi = (
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;"><strong>Resumen de Indicadores</strong></p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">(Datos del &uacute;ltimo sensor seleccionado)</p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Los datos seleccionados tienen un valor promedio de '+str(valor_promedio)+', adem&aacute;s de un valor m&aacute;ximo de '+str(valor_max)+', que se repite '+str(num_valor_max)[10:len(str(num_valor_max))]+' vez y su &uacute;ltima repetici&oacute;n fue el '+str(dia_max)+' de '+str(mes_max)+' de '+str(ano_max)+' a las '+str(fecha_valor_max).split(sep=' ')[1]+' y por &uacute;ltimo un valor m&iacute;nimo de '+str(valor_min)+' que se repite '+str(num_valor_min)[10:len(str(num_valor_min))]+' vez y su &uacute;ltima repetici&oacute;n fue el '+str(dia_min)+' de '+str(mes_min)+' de '+str(ano_min)+' a las '+str(fecha_valor_min).split(sep=' ')[1]+'.</p>'
        '<p>&nbsp;</p>'
    )
    '''
    linea = (
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;"><strong>L&iacute;neas de control </strong></p>'
    )
    linea_multi = (
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;"><strong>L&iacute;neas de control </strong></p>'
        '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">(Datos de todos los sensores seleccionados)</p>'
    )
    if valor_linea_control_sup != None and valor_linea_control_inf != None:
        linea_sup = (
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor de l&iacute;nea de control superior: <strong>'
            + str(valor_linea_control_sup) + '</strong></p>'
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Peaks superiores: <strong>'
            + str(alert_sup) + '</strong></p>'
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Fecha &uacute;ltimo peak superior detectado: <strong>'
            + str(dia_sup) + '-' + str(mes_sup) + '-' + str(ano_sup) + ' ' +
            str(fecha_alert_sup).split(sep=' ')[1] + '</strong></p>')
        linea_inf = (
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor de l&iacute;nea de control inferior: <strong>'
            + str(valor_linea_control_inf) + '</strong></p>'
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Peaks inferiores: <strong>'
            + str(alert_inf) + '</strong></p>'
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Fecha &uacute;ltimo peak inferior detectado: <strong>'
            + str(dia_inf) + '-' + str(mes_inf) + '-' + str(ano_inf) + ' ' +
            str(fecha_alert_inf).split(sep=' ')[1] + '</strong></p>')
        #version con lineas de control descritos en parrafos
        '''
        linea_sup = ('<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">L&iacute;nea de control superior ubicada en el valor '+str(valor_linea_control_sup)+', existen '+str(alert_sup)+' que superan este umbral y el &uacute;ltimo peak detectado fue el '+str(dia_sup)+' de '+str(mes_sup)+' de '+str(ano_sup)+' a las '+str(fecha_alert_sup).split(sep=' ')[1]+'.')
        linea_inf = ('<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">L&iacute;nea de control inferior ubicada en el valor '+str(valor_linea_control_inf)+', existen '+str(alert_inf)+' que superan este umbral y el &uacute;ltimo peak detectado fue el '+str(dia_inf)+' de '+str(mes_inf)+' de '+str(ano_inf)+' a las '+str(fecha_alert_inf).split(sep=' ')[1]+'.')
        '''
    elif valor_linea_control_sup != None:
        linea_sup = (
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor de l&iacute;nea de control superior: <strong>'
            + str(valor_linea_control_sup) + '</strong></p>'
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Peaks superiores: <strong>'
            + str(alert_sup) + '</strong></p>'
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Fecha &uacute;ltimo peak superior detectado: <strong>'
            + str(dia_sup) + '-' + str(mes_sup) + '-' + str(ano_sup) + ' ' +
            str(fecha_alert_sup).split(sep=' ')[1] + '</strong></p>')
        #version con lineas de control descritos en parrafos
        #linea_sup = ('<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">L&iacute;nea de control superior ubicada en el valor '+str(valor_linea_control_sup)+', existen '+str(alert_sup)+' que superan este umbral y el &uacute;ltimo peak detectado fue el '+str(dia_sup)+' de '+str(mes_sup)+' de '+str(ano_sup)+' a las '+str(fecha_alert_sup).split(sep=' ')[1]+'.')
    elif valor_linea_control_inf != None:
        linea_inf = (
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Valor de l&iacute;nea de control inferior: <strong>'
            + str(valor_linea_control_inf) + '</strong></p>'
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Peaks inferiores: <strong>'
            + str(alert_inf) + '</strong></p>'
            '<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">Fecha &uacute;ltimo peak inferior detectado: <strong>'
            + str(dia_inf) + '-' + str(mes_inf) + '-' + str(ano_inf) + ' ' +
            str(fecha_alert_inf).split(sep=' ')[1] + '</strong></p>')
        #version con lineas de control descritos en parrafos
        #linea_inf = ('<p style="text-align: justify;"><span style="font-family:arial,helvetica,sans-serif;">L&iacute;nea de control inferior ubicada en el valor '+str(valor_linea_control_inf)+', existen '+str(alert_inf)+' que superan este umbral y el &uacute;ltimo peak detectado fue el '+str(dia_inf)+' de '+str(mes_inf)+' de '+str(ano_inf)+' a las '+str(fecha_alert_inf).split(sep=' ')[1]+'.')

    #heroku
    '''
    fecha = (
        '<p style="text-align: justify; padding-left: 30px; padding-right: 30px;"><span style="font-family:arial,helvetica,sans-serif;">Reporte del obtenido el '+str(time.strftime("%d/%m/%y"))+' a las&nbsp;'+str(time.strftime("%H:%M:%S"))+'</p>'
        '<a style="text-align: center;" href="#" onclick="window.print();return false;" title="Click para guardar o imprimir reporte"><strong>Guardar/Imprimir Reporte</strong></a>'
        '</body>'
        '</html>')
    '''
    #escritorio

    fecha = (
        '<p style="text-align: justify; padding-left: 30px; padding-right: 30px;"><span style="font-family:arial,helvetica,sans-serif;">Reporte del obtenido el '
        + str(time.strftime("%d/%m/%y")) + ' a las&nbsp;' +
        str(time.strftime("%H:%M:%S")) + '</p>'
        '</body>'
        '</html>')

    #Se agregan las imagenes a la plantilla html
    imagenes = ''
    tmp = 1
    for image in graficos:
        if tmp == 3:
            _ = img2
        else:
            _ = img
        _ = _.format(image=image)
        imagenes += _
        tmp += 1

    #Dependiendo de la situacion se modifica la plantilla html, tanto como para agregar contenido o para quitarlo
    if cantidad_sensores != '1-sensor':
        reporte = encabezado_multi + resumen_multi + imagenes + fecha
        if valor_linea_control_sup != None and valor_linea_control_inf != None:
            reporte = encabezado_multi + resumen_multi + linea_multi + linea_sup + linea_inf + imagenes + fecha
        elif valor_linea_control_inf != None:
            reporte = encabezado_multi + resumen_multi + linea_multi + linea_inf + imagenes + fecha
        elif valor_linea_control_sup != None:
            reporte = encabezado_multi + resumen_multi + linea_multi + linea_sup + imagenes + fecha

    else:
        reporte = encabezado + resumen + imagenes + fecha

        if valor_linea_control_sup != None and valor_linea_control_inf != None:
            reporte = encabezado + resumen + linea + linea_sup + linea_inf + imagenes + fecha
        elif valor_linea_control_inf != None:
            reporte = encabezado + resumen + linea + linea_inf + imagenes + fecha
        elif valor_linea_control_sup != None:
            reporte = encabezado + resumen + linea + linea_sup + imagenes + fecha

    #Funcion que transforma el html en pdf para la version de escritorio o servidor con linux
    pdfkit.from_string(reporte, 'reporte.pdf')

    webbrowser.open_new_tab('reporte.pdf')
Example #21
0
def main():
    # Calcular parâmetros iniciais fixos da tubeira
    v_test_rad, v_test_deg = v(M_TEST)

    A_test_ratio = A_ratio(M_TEST)

    theta_1_rad, theta_1_deg = empirical_theta_1(v_test_rad, A_test_ratio)

    v_1_rad = v_test_rad - theta_1_rad
    v_1_deg = v_test_deg - theta_1_deg

    M_1 = M_from_v(v_1_rad)

    # Determinar coordenadas depois do ponto de inflexão, utilizando o método de Foelsch
    x_final_curve, y_final_curve = foelsch(Y_0, theta_1_rad, v_1_rad,
                                           v_test_rad, M_1)

    y_1 = y_final_curve[0]

    # Determinar coordenadas antes do ponto de inflexão
    x_initial_curve, y_initial_curve = initial_curve(Y_0, y_1, theta_1_rad)

    np.savetxt("nozzle_x.csv",
               np.concatenate([x_initial_curve, x_final_curve]),
               fmt='%s',
               delimiter=";")
    np.savetxt("nozzle_y.csv",
               np.concatenate([y_initial_curve, y_final_curve]),
               fmt='%s',
               delimiter=";")

    # Plotar resultados
    fig, ax = plt.subplots()
    ax.plot(x_initial_curve, y_initial_curve, 'r-')
    ax.plot(x_initial_curve, -y_initial_curve, 'r-')
    ax.plot(x_final_curve, y_final_curve, 'r-')
    ax.plot(x_final_curve, -y_final_curve, 'r-')
    ax.plot(x_initial_curve, np.zeros(x_initial_curve.shape), 'k--')
    ax.plot(x_final_curve, np.zeros(x_final_curve.shape), 'k--')
    ax.set_title("")
    ax.set_xlabel("")
    ax.set_ylabel("")

    plt.xlim(x_initial_curve[0], x_final_curve[-1] * 1.05)
    plt.ylim(-y_final_curve[-1] * 2, y_final_curve[-1] * 2)
    plt.show()

    throat_index = np.where(y_initial_curve == 10)[0][0]

    # Quasi Unidimensional
    graph_y_points = list(
        float_range(0, 200,
                    max(y_final_curve) / len(y_final_curve)))
    mach_matriz = []
    for i in range(len(graph_y_points)):
        mach_matriz.append(
            add_line_on_quasi_graph(
                graph_y_points[i],
                np.concatenate([y_initial_curve[throat_index:],
                                y_final_curve]),
                len(
                    np.concatenate(
                        [x_initial_curve[throat_index:], x_final_curve]))))

    # Espelhar resultados de Mach e pontos de y
    mirror = mach_matriz[::-1]
    mirror_y = [-x for x in graph_y_points[::-1]]

    scope = PlotlyScope()
    fig_quasi_unidimensional = make_subplots(rows=1, cols=1)
    fig_quasi_unidimensional.add_trace(
        go.Heatmap(z=mirror + mach_matriz,
                   x=np.concatenate(
                       [x_initial_curve[throat_index:], x_final_curve]),
                   y=mirror_y + graph_y_points,
                   colorbar=dict(title='Mach', titleside='right'),
                   connectgaps=True,
                   zsmooth='best'), 1, 1)
    fig_quasi_unidimensional.update
    fig_quasi_unidimensional.update_yaxes(title_text="Y axis (mm)",
                                          row=1,
                                          col=1)
    fig_quasi_unidimensional.update_xaxes(title_text="X axis (mm)",
                                          row=1,
                                          col=1)
    with open("quasi_unidimensional_graph.png", "wb") as f:
        f.write(scope.transform(fig_quasi_unidimensional, format="png"))
Example #22
0
def test_custopm_chromium_arg():
    # Check that --disable-gpu is in scope instance chromium_args
    chromium_args = PlotlyScope.default_chromium_args() + (
        "--single-process", )
    scope = PlotlyScope(chromium_args=chromium_args)
    assert "--single-process" in scope._build_proc_args()
Example #23
0
    from mock import Mock

os.environ['LIBGL_ALWAYS_SOFTWARE'] = '1'
os.environ['GALLIUM_DRIVER'] = 'softpipe'


# Constants
mapbox_access_token = os.environ.get("MAPBOX_TOKEN")
local_plotlyjs_path = tests_root / "plotly" / "resources" / "plotly.min.js"
local_plotlyjs_url = local_plotlyjs_path.as_uri()

mathjax = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js"

# Initialize a global scope, this way we test multiple uses
scope = PlotlyScope(
    mathjax=mathjax, mapbox_access_token=mapbox_access_token
)


def load_baseline(name, format):
    baseline_path = baseline_root / 'plotly' / (name + '.' + format)
    with baseline_path.open('rb') as f:
        expected = f.read()
    return expected


def write_baseline(data, name, format):
    baseline_path = baseline_root / 'plotly' / (name + '.' + format)
    with baseline_path.open('wb') as f:
        f.write(data)
Example #24
0
def hovmoeller(data,
               lon,
               time,
               datestrt,
               datelast,
               plotpath,
               lats,
               latn,
               spd,
               source,
               pltvarname,
               lev=[],
               cmin=[],
               cmax=[],
               cspc=[]):
    """
    Main driver for plotting Hovmoeller diagrams.
    :param data: input data, should be (time, lon)
    :type data: numeric
    :param lon: longitude coordinate of data
    :type lon: float
    :param time: time coordinate of data
    :type time: datetime
    :param datestrt: start date for Hovmoeller, used in plot file name
    :type datestrt: str
    :param datelast: end date for Hovmoeller, used in plot file name
    :type datelast: str
    :param plotpath: path for saving the figure
    :type plotpath: str
    :param lats: southern latitude limit of the average
    :type lats: float
    :param latn: northern latitude limit of the average
    :type latn: float
    :param spd: number of observations per day
    :type spd: int
    :param source: source of the data, e.g. (ERAI, TRMM, ...), used in plot file name
    :type source: str
    :param pltvarname: name of variable to be plotted
    :type pltvarname: str
    :param lev: vertical level of data (optional)
    :type lev: str
    :param cmin: contour level minimum (optional)
    :type cmin: float
    :param cmax: contour level maximum (optional)
    :type cmax: float
    :param cspc: contour spacing (optional)
    :type cspc: float
    :return: none
    :rtype: none
    """
    """
    Set plot type and plot file name.
    """
    plttype = "png"
    plotname = plotpath + "Hovmoeller_" + source + pltvarname + lev + "_" + str(
        datestrt) + "-" + str(datelast) + "." + plttype
    """
    Set plot resources: colormap, time string, contour levels, latitude band string
    """
    cmap_rgb = hov_resources(pltvarname)

    timestr = get_timestr(time)

    if (not cmin) or (not cmax) or (not cspc):
        cmin, cmax, cspc = get_clevels(pltvarname)

    latstring = get_latstring(lats, latn)
    """
    Generate the Hovmoeller plot.
    """
    scope = PlotlyScope()
    fig = go.Figure()

    fig.add_trace(
        go.Contour(z=data.values,
                   x=lon,
                   y=timestr,
                   colorscale=cmap_rgb,
                   contours=dict(start=cmin,
                                 end=cmax,
                                 size=cspc,
                                 showlines=False),
                   colorbar=dict(title=data.attrs['units'],
                                 len=0.6,
                                 lenmode='fraction')))

    fig.update_layout(title=source + " " + pltvarname + lev,
                      width=600,
                      height=900,
                      annotations=[
                          go.layout.Annotation(x=300,
                                               y=timestr[5],
                                               xref="x",
                                               yref="y",
                                               text=latstring,
                                               showarrow=False,
                                               bgcolor="white",
                                               opacity=0.9,
                                               font=dict(size=16))
                      ])

    fig.update_xaxes(ticks="inside", tick0=0, dtick=30, title_text='longitude')
    fig.update_yaxes(autorange="reversed", ticks="inside", nticks=11)

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))

    return
Example #25
0
def test_plotlyjs_bad_local_file():
    plotlyjs_path = str(local_plotlyjs_path) + ".bogus"
    with pytest.raises(ValueError) as e:
        PlotlyScope(plotlyjs=plotlyjs_path).transform(simple_figure())

    e.match("plotlyjs argument is not a valid URL")
Example #26
0
def test_figure_size():
    # Create mocked scope
    scope = PlotlyScope()
    transform_mock = Mock(return_value={"code": 0, "result": "image"})
    scope._perform_transform = transform_mock

    # Set defualt width / height
    scope.default_width = 543
    scope.default_height = 567
    scope.default_format = "svg"
    scope.default_scale = 2

    # Make sure default width/height is used when no figure
    # width/height specified
    transform_mock.reset_mock()
    fig = go.Figure()
    scope.transform(fig)
    transform_mock.assert_called_once_with(
        fig.to_dict(), format="svg", scale=2, width=543, height=567
    )

    # Make sure figure's width/height takes precedence over defaults
    transform_mock.reset_mock()
    fig = go.Figure().update_layout(width=123, height=234)
    scope.transform(fig)
    transform_mock.assert_called_once_with(
        fig.to_dict(), format="svg", scale=2, width=123, height=234
    )

    # Make sure kwargs take precedence over Figure layout values
    transform_mock.reset_mock()
    fig = go.Figure().update_layout(width=123, height=234)
    scope.transform(fig, width=987, height=876)
    transform_mock.assert_called_once_with(
        fig.to_dict(), format="svg", scale=2, width=987, height=876
    )
Example #27
0
def plot_vertcoh_panel(ds_plot,
                       labels,
                       titlestr,
                       plotname,
                       plotpath,
                       lats,
                       latn,
                       xlim=[0, 0.5]):
    """
    Panel plot of averaged coherence and phase values by level.
    :param ds_plot: xarray dataset containing the data to plot. This includes nplot as an attribute and
    the source names and forecast hours. The
    :param labels: Labels for each variable, should include variable and symm/ anti-symm tag.
    :param titlestr: Title for the plot, should include CCEW/ MJO tag and variable name for var1 (usually precip).
    :param plotname: Name for the plot to be saved under.
    :param plotpath: Path for the plot to be saved at.
    :param lats: Southern latitude value the spectra were averaged over.
    :param latn: Northern latitude value the spectra were averaged over.
    :param xlim: optional parameter specifying the maximum coherence value on the x-axis
    :return:
    """

    # sources1 = ds_plot['sources1']
    # sources2 = ds_plot['sources2']
    nplot = int(ds_plot.attrs['nplot'])
    varnames = list(ds_plot.data_vars)
    sourcenames = ds_plot.attrs["sourcenames"]
    titles = []
    for name in sourcenames:
        titles.append(name)
        titles.append('')
    abcstrings = list(string.ascii_lowercase)

    # compute phase angle (in degrees) from x-y components.
    angcnst = 1.

    # latitude string for plot title
    latstring = get_latstring(lats, latn)

    # set up plotname for saving
    plttype = "png"
    plotname = plotpath + plotname + "." + plttype

    # plot
    nlines = len(labels)
    colors = ['firebrick', 'black', 'orange', 'dodgerblue', 'seagreen']
    symbols = ['circle', 'square', 'diamond', 'x', 'triangle-up']

    ncols = 4
    nrows = int(np.ceil(nplot / 2))
    scope = PlotlyScope()
    fig = make_subplots(rows=nrows,
                        cols=ncols,
                        shared_yaxes=True,
                        horizontal_spacing=0.04,
                        vertical_spacing=0.04,
                        subplot_titles=titles)

    for pp in np.arange(0, nrows):
        coh = ds_plot[varnames[pp * nplot]]
        try:
            levels = coh['plev']
        except KeyError:
            levels = coh['level']
        px = ds_plot[varnames[pp * nplot + 1]]
        py = ds_plot[varnames[pp * nplot + 2]]
        angle = np.arctan2(angcnst * px, py) * 180 / np.pi

        for ll in np.arange(0, nlines):
            if pp == 0:
                fig.add_trace(go.Scatter(x=coh[ll, :],
                                         y=levels,
                                         mode='lines',
                                         name=labels[ll],
                                         line=dict(color=colors[ll], width=2)),
                              row=pp + 1,
                              col=1)
            else:
                fig.add_trace(go.Scatter(x=coh[ll, :],
                                         y=levels,
                                         mode='lines',
                                         name=labels[ll],
                                         showlegend=False,
                                         line=dict(color=colors[ll], width=2)),
                              row=pp + 1,
                              col=1)
            fig.add_trace(go.Scatter(x=angle[ll, :],
                                     y=levels,
                                     mode='markers',
                                     showlegend=False,
                                     marker=dict(color=colors[ll],
                                                 size=8,
                                                 symbol=symbols[ll])),
                          row=pp + 1,
                          col=2)

        coh = ds_plot[varnames[pp * nplot + int(np.ceil(nplot / 2))]]
        try:
            levels = coh['plev']
        except KeyError:
            levels = coh['level']
        px = ds_plot[varnames[pp * nplot + int(np.ceil(nplot / 2)) + 1]]
        py = ds_plot[varnames[pp * nplot + int(np.ceil(nplot / 2)) + 2]]
        angle = np.arctan2(angcnst * px, py) * 180 / np.pi

        for ll in np.arange(0, nlines):
            fig.add_trace(go.Scatter(x=coh[ll, :],
                                     y=levels,
                                     mode='lines',
                                     showlegend=False,
                                     name=labels[ll],
                                     line=dict(color=colors[ll], width=2)),
                          row=pp + 1,
                          col=3)
            fig.add_trace(go.Scatter(x=angle[ll, :],
                                     y=levels,
                                     mode='markers',
                                     showlegend=False,
                                     marker=dict(color=colors[ll],
                                                 size=8,
                                                 symbol=symbols[ll])),
                          row=pp + 1,
                          col=4)

    for i in np.arange(2, nrows * ncols + 1, 2):
        istr = str(i)
        fig.add_annotation(x=-90,
                           y=50,
                           xref="x" + istr,
                           yref="y" + istr,
                           text="precip lags",
                           showarrow=False,
                           bgcolor="white",
                           opacity=0.8)
        fig.add_annotation(x=90,
                           y=50,
                           xref="x" + istr,
                           yref="y" + istr,
                           text="precip leads",
                           showarrow=False,
                           bgcolor="white",
                           opacity=0.8)

    for i in np.arange(1, nrows * ncols + 1):
        if i % 2 == 0:
            xpos = -180
        else:
            xpos = xlim[0]
        fig.add_annotation(x=xpos,
                           y=50,
                           xref="x" + str(i),
                           yref="y" + str(i),
                           text=abcstrings[i - 1],
                           showarrow=False,
                           bgcolor="white",
                           opacity=0.8)

    fig.update_layout(title=titlestr + ' ' + latstring,
                      width=1800,
                      height=1800,
                      legend=dict(yanchor="bottom",
                                  y=0.45,
                                  xanchor="left",
                                  x=0.15))

    for j in np.arange(1, ncols, 2):
        fig.update_xaxes(title_text='coh^2',
                         range=[xlim[0], xlim[1]],
                         row=nrows,
                         col=j)
        fig.update_xaxes(title_text='phase angle',
                         range=[-180, 180],
                         dtick=90,
                         row=nrows,
                         col=(j + 1))
        for i in range(nrows - 1):
            fig.update_xaxes(range=[xlim[0], xlim[1]], row=(i + 1), col=j)
            fig.update_xaxes(range=[-180, 180],
                             dtick=90,
                             row=(i + 1),
                             col=(j + 1))

    for i in range(nrows):
        fig.update_yaxes(range=[100, 1000],
                         dtick=100,
                         title_text='hPa',
                         autorange="reversed",
                         row=(i + 1),
                         col=1)
        for j in np.arange(2, ncols + 1):
            fig.update_yaxes(range=[100, 1000],
                             dtick=100,
                             autorange="reversed",
                             row=(i + 1),
                             col=j)

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))

    return
# work in offline
import plotly.offline as pyo

pyo.init_notebook_mode()

# graph renderer
import plotly.io as pio

png_renderer = pio.renderers["png"]
# png_renderer.width=1800
# png_renderer.height=1200
# png_renderer.autoscale=True
pio.renderers.default = "png"

scope = PlotlyScope()

plotly.__version__

FIGURE_DIR = "C:\\Users\\joinp\\Downloads\\Figures\\"

# In[2]:


def latency_df(result_dir, dir_prefix, minTime):
    latency_data = pd.read_csv(os.path.join(result_dir, dir_prefix,
                                            "count-latency.txt"),
                               delimiter=" ",
                               header=None,
                               index_col=False,
                               names="count latency currTime subTask".split())
Example #29
0
def plot_vertcoh(coh,
                 px,
                 py,
                 levels,
                 labels,
                 titlestr,
                 plotname,
                 plotpath,
                 lats,
                 latn,
                 xlim=[0, 0.5]):
    """
    Plot averaged coherence and phase values by level.
    :param coh: Averaged coherence values. nvar x nlevels
    :param px: Averaged phase angle (x-component) values. nvar x nlevels
    :param py: Averaged phase angle (y-component) values. nvar x nlevels
    :param levels: Vertical level coordinate.
    :param labels: Labels for each variable, should include variable and symm/ anti-symm tag.
    :param titlestr: Title for the plot, should include CCEW/ MJO tag and variable name for var1 (usually precip).
    :param plotname: Name for the plot to be saved under.
    :param plotpath: Path for the plot to be saved at.
    :param lats: Southern latitude value the spectra were averaged over.
    :param latn: Northern latitude value the spectra were averaged over.
    :param xlim: optional parameter specifying the maximum coherence value on the x-axis
    :return:
    """

    # compute phase angle (in degrees) from x-y components.
    angcnst = 1.
    angle = np.arctan2(angcnst * px, py) * 180 / np.pi
    print(np.min(angle), np.max(angle))

    # latitude string for plot title
    latstring = get_latstring(lats, latn)

    # set up plotname for saving
    plttype = "png"
    plotname = plotpath + plotname + "." + plttype

    # plot
    nlines = len(labels)
    colors = ['firebrick', 'black', 'orange', 'dodgerblue', 'seagreen']
    symbols = ['circle', 'square', 'diamond', 'x', 'triangle-up']

    scope = PlotlyScope()
    fig = make_subplots(rows=1,
                        cols=2,
                        shared_yaxes=True,
                        horizontal_spacing=0.04)

    for ll in np.arange(0, nlines):
        fig.add_trace(go.Scatter(x=coh[ll, :],
                                 y=levels,
                                 mode='lines',
                                 name=labels[ll],
                                 line=dict(color=colors[ll], width=2)),
                      row=1,
                      col=1)
        fig.add_trace(go.Scatter(x=angle[ll, :],
                                 y=levels,
                                 mode='markers',
                                 showlegend=False,
                                 marker=dict(color=colors[ll],
                                             size=8,
                                             symbol=symbols[ll])),
                      row=1,
                      col=2)

    fig.add_annotation(x=-90,
                       y=50,
                       xref="x2",
                       yref="y2",
                       text="precip lags",
                       showarrow=False,
                       bgcolor="white",
                       opacity=0.8)
    fig.add_annotation(x=90,
                       y=50,
                       xref="x2",
                       yref="y2",
                       text="precip leads",
                       showarrow=False,
                       bgcolor="white",
                       opacity=0.8)

    fig.update_layout(title=titlestr + ' ' + latstring,
                      width=900,
                      height=600,
                      legend=dict(yanchor="bottom",
                                  y=0.01,
                                  xanchor="left",
                                  x=0.01))

    fig.update_xaxes(title_text='coh^2',
                     range=[xlim[0], xlim[1]],
                     row=1,
                     col=1)
    fig.update_xaxes(title_text='phase angle',
                     range=[-180, 180],
                     dtick=90,
                     row=1,
                     col=2)
    fig.update_yaxes(range=[100, 1000],
                     dtick=100,
                     title_text='hPa',
                     autorange="reversed",
                     row=1,
                     col=1)
    fig.update_yaxes(range=[100, 1000],
                     dtick=100,
                     autorange="reversed",
                     row=1,
                     col=2)

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))

    return
Example #30
0
 def save_static(self):
     scope = PlotlyScope()
     with open(self.path.replace('html', 'png'), "wb") as f:
         f.write(scope.transform(self.fig, format="png"))