Example #1
0
 def build_sources_layout(self):
     divs = []
     # was initially going to make this a set, but Source objects have a
     # dict, and aren't immutable... also, number of sources is small enough
     # that iterating over list should be fine
     seen = []
     for cache_item in datamod.data_cache.values():
         retriever = cache_item.retriever
         source = retriever.source()
         if source in seen:
             continue
         seen.append(source)
         lines = []
         for data_type in retriever.data_types():
             entity = data_type.entity
             if isinstance(entity, Entity):
                 entity_name = str(entity)
             else:
                 entity_name = entity.__name__
             lines.append('<b>{} {}:</b>'.format(entity_name,
                                                 data_type.data_type))
         lines.append('{}'.format(source.name))
         links = [
             '<a href="{}">{}</a>'.format(url, name)
             for name, url in source.urls.items()
         ]
         links = ', '.join(links)
         date = cache_item.max_date()
         if date is not None:
             date = date.strftime('%a, %x')
             lines.append('Most recent data: {}'.format(date))
         lines.append('Links: {}'.format(links))
         divs.append(mdl.Div(text='<br>'.join(lines)))
     return lyt.column(divs)
class SimulatedParamWidgets:
    """Collection of Bokeh Widgets for specifying simulation parameters"""

    top_section_div = models.Div(text='<h2>Simulated Parameters</h2>')

    # User input widgets for setting model parameters
    sim_z_slider = models.Slider(start=0.001,
                                 end=1,
                                 value=.55,
                                 step=.01,
                                 title='z')
    sim_t0_slider = models.Slider(start=-10,
                                  end=10,
                                  value=-2,
                                  step=.01,
                                  title='t0')
    sim_x0_slider = models.Slider(start=0.001,
                                  end=2,
                                  value=.25,
                                  step=.01,
                                  title='x0')
    sim_x1_slider = models.Slider(start=-1,
                                  end=1,
                                  value=0.11,
                                  step=.01,
                                  title='x1')
    sim_c_slider = models.Slider(start=-1,
                                 end=1,
                                 value=-.05,
                                 step=.01,
                                 title='c')
    sampling_input = models.TextInput(value='4', title='Sampling (Days):')
    sim_pwv_slider = models.Slider(start=-0,
                                   end=15,
                                   value=7,
                                   step=.1,
                                   title='PWV')
    plot_button = models.Button(label='Plot Light-Curve',
                                button_type='success')

    snr_input = models.TextInput(value='10.0', title='SNR:', default_size=220)
    checkbox = models.CheckboxGroup(
        labels=["Plot SNR", 'Subtract Reference Star'], active=[0])

    # Having all inputs as a list is useful when constructing layouts
    # as it establishes the default column order
    sim_params_widgets_list = [
        top_section_div, sim_z_slider, sim_t0_slider, sim_x0_slider,
        sim_x1_slider, sim_c_slider, sim_pwv_slider, sampling_input, snr_input,
        checkbox, plot_button
    ]
class FittedParamWidgets:
    """Collection of Bokeh Widgets for fitting a light-curve parameters"""

    top_section_div = models.Div(text=(
        '<h2>Fitted Parameters</h2>'
        '<p>Current parameter values are used as an initial guess when fitting. '
        'Note that redshift values are not varied as part of the fit.</p>'))

    # User input widgets for setting model parameters
    fit_t0_slider = models.Slider(start=-10,
                                  end=10,
                                  value=0,
                                  step=1E-4,
                                  title='t0')
    fit_x0_slider = models.Slider(start=0.001,
                                  end=2,
                                  value=.1,
                                  step=1E-4,
                                  title='x0')
    fit_x1_slider = models.Slider(start=-1,
                                  end=1,
                                  value=0,
                                  step=1E-4,
                                  title='x1')
    fit_c_slider = models.Slider(start=-1,
                                 end=1,
                                 value=0,
                                 step=1E-4,
                                 title='c')
    plot_model_button = models.Button(label='Plot Model',
                                      button_type='warning')
    fit_button = models.Button(label='Fit Light-Curve', button_type='success')

    fitted_params_widgets_list = [
        top_section_div, fit_t0_slider, fit_x0_slider, fit_x1_slider,
        fit_c_slider, plot_model_button, fit_button
    ]
Example #4
0
from copy import copy
from os.path import join

from bokeh.plotting import figure
from bokeh.layouts import layout, widgetbox
import bokeh.models as bmd
from bokeh.palettes import Viridis256
from bokeh.models.widgets import RangeSlider, Select, Button, PreText, CheckboxButtonGroup
from bokeh.io import curdoc

import config
from config import quantities, presets
from figure.query import get_data_sqla as get_data
from figure.query import data_empty

html = bmd.Div(text=open(join(config.static_dir, "description.html")).read(),
               width=800)

redraw_plot = False


def get_preset_label_from_url():
    # get preset for figure from arguments
    args = curdoc().session_context.request.arguments
    try:
        preset_label = args.get('preset')[0]
    except (TypeError, KeyError):
        preset_label = 'Pd'
    if preset_label is not 'Pd':
        preset_label = preset_label.decode("utf-8")
    return preset_label
from collections import OrderedDict
import json

from bokeh.layouts import layout, widgetbox
import bokeh.models as bmd
from bokeh.models.widgets import PreText, Button, Div
from bokeh.io import curdoc
from jsmol_bokeh_extension import JSMol
from import_db import get_cif_content_from_disk as get_cif_str
from import_db import get_rdf_dataframe_from_disk as get_rdf_df
from import_db import get_results_dataframes_from_disk as get_results_df

# from import_db import get_cif_content_from_os as get_cif_str
from detail.query import get_sqlite_data as get_data

html = bmd.Div(text=open(join(dirname(__file__), "description.html")).read(),
               width=800)

download_js = open(join(dirname(__file__), "static", "download.js")).read()

plot_info = Div(text="Pore blocking is not relevant for this structure.",
                width=300,
                height=100)

plot_info_blocked_pockets = Div(
    text="Pore blocking is relevant and used for this structure.",
    width=800,
    height=100)

plot_info_non_permeable = Div(
    text=
    "This structure has no accessible pore volume. We show simulations without pore blocking. ",
Example #6
0
                        lay.gridplot([decomp_plots],
                                      toolbar_location='left')
                column_plots[column_name] = freq_plots
            table_plots[table_name] = column_plots

        return table_plots


start_time = datetime.datetime.now()
reader  = ReadData.setup(source_name, start_point, tables)
process = ProcessData(reader)
plots   = PlotData(process)
end_time = datetime.datetime.now()
elapsed_time = end_time - start_time

periodogram_title = mdl.Div(text='<h1>Larva Periodogram Data, {} runs</h1>'.
                                    format(len(reader.dataframes)))
periodogram_plots = [
    plots.periodogram[larva][homo_r], plots.sample_periodogram[larva][homo_r],
    plots.periodogram[larva][hetero], plots.sample_periodogram[larva][hetero],
    plots.periodogram[larva][homo_s], plots.sample_periodogram[larva][homo_s]
]
periodogram_lay = lay.gridplot(periodogram_plots,
                               toolbar_location='left')
#
# seasonal_title = mdl.Div(text='<h1>Larva Seasonal Decomposition Data, '
#                               '{} runs</h1>'.
#                             format(len(reader.dataframes)))
# sample_seasonal_title = mdl.Div(text='<h1>Larva Seasonal Decomposition Data, '
#                                      '{} runs</h1>'.
#                                 format(sample_size))
# seasonal_plots = [seasonal_title]
Example #7
0
                                      toolbar_location='left')
                column_plots[column_name] = freq_plots
            table_plots[table_name] = column_plots

        return table_plots


start_time = datetime.datetime.now()
reader = ReadData.setup(source_name, start_point, tables)
process = ProcessData(reader)
plots = PlotData(process)
end_time = datetime.datetime.now()
elapsed_time = end_time - start_time

periodogram_title = mdl.Div(
    text='<h1>Larva Periodogram Data, {} runs</h1>'.format(
        len(reader.dataframes)))
periodogram_plots = [
    plots.periodogram[larva][homo_r], plots.sample_periodogram[larva][homo_r]
]
periodogram_lay = lay.gridplot(periodogram_plots, toolbar_location='left')

seasonal_title = mdl.Div(text='<h1>Larva Seasonal Decomposition Data, '
                         '{} runs</h1>'.format(len(reader.dataframes)))
sample_seasonal_title = mdl.Div(text='<h1>Larva Seasonal Decomposition Data, '
                                '{} runs</h1>'.format(sample_size))
seasonal_plots = [seasonal_title]
seasonal_plots.extend(list(plots.decompose[larva][homo_r].values()))
seasonal_plots.append(sample_seasonal_title)
seasonal_plots.extend(list(plots.sample_decompose[larva][homo_r].values()))
seasonal_plots = tuple(seasonal_plots)
###############################################################################

# The figure objects to plot on
central_figure = figure(plot_height=400,
                        plot_width=700,
                        sizing_mode='scale_both',
                        toolbar_location='above')
spectrum_figure = figure(plot_height=200,
                         plot_width=700,
                         sizing_mode='scale_both')
for fig in (central_figure, spectrum_figure):
    fig.legend.location = "top_left"
    fig.legend.click_policy = "hide"

# Div for displaying fitted ``Results`` object
fit_results = models.Div()
callbacks = Callbacks(central_figure, spectrum_figure, fit_results, SOURCE)

###############################################################################
# Layout the page
###############################################################################

# Descriptive text for the top of the page
header_path = _file_dir / "lc_fit_header.html"
with header_path.open() as infile:
    header_div = models.Div(text=infile.read(), sizing_mode="stretch_width")

left_column = column(*callbacks.sim_params_widgets_list,
                     width=320,
                     height=1000,
                     sizing_mode="fixed")
Example #9
0
# Tooltip when hovering over circle
hover = bmo.HoverTool(
    tooltips=[
        ('model', '@index'),
        ('tasmin', '@tasmin'),
        ('tasmax', '@tasmax'),
        ('pr', '@pr'),
        ('rsds', '@rsds')
    ]
)

# Tools to show in toolbox
TOOLS = "pan,wheel_zoom,box_zoom,reset,box_select,save"

# Load description from file
div_desc = bmo.Div(text=open(join(dirname(__file__), "description.html")).read(),
               width=800)
div_hr = bmo.Div(text="<hr>", width=800)

# Create empty panel with empty tabs
ls_tab = []
dct_buttons = {}
pdf_ts = {}
p = {}

tabs = bmo.widgets.Tabs(tabs=ls_tab)

# Create empty div for spinner
div_spinner = bmo.widgets.Div(text="",width=120,height=120)

# Create Input controls
inp_country = bmo.widgets.Select(title="Country",
Example #10
0
bbox_countries = {
    "Whole Domain": {"lat":[38, 47], "lon": [13, 25]},
    "Albania": {"lat":[39.583, 42.659], "lon": [19, 21.05]},
    "Bosnia and Herzegovina": {"lat":[42.558, 45.268], "lon": [15.746, 19.671]},
    "Croatia": {"lat":[42.367, 46.527], "lon": [13.484, 19.391]},
    "Kosovo": {"lat":[41.8577, 43.2696], "lon": [20.0141, 21.7894]},
    "Macedonia": {"lat":[40.867, 42.373], "lon": [20.405, 23.033]},
    "Montenegro": {"lat":[41.864, 43.548], "lon": [18.438, 20.345]},
    "Serbia": {"lat":[41.844, 46.167], "lon": [18.859, 22.967]},
}

# Tools to show in toolbox
TOOLS = "pan,wheel_zoom,box_zoom,reset,box_select,save"

# Load description from file
div_desc = bmo.Div(text=open(os.path.join(os.path.dirname(__file__), "description.html")).read(),
               width=800)
div_hr = bmo.Div(text="<hr>", width=800)

# Create empty div for spinner
div_spinner = bmo.widgets.Div(text="",width=120,height=120)

# Create Input controls
inp_country = bmo.widgets.Select(title="Country",
                                 value = "Whole Domain",
                                 options = list(bbox_countries.keys()))
inp_lat = bmo.widgets.TextInput(title="Latitude (Format: [MIN, MAX])",
                                value = "[38, 47]" )
inp_lon = bmo.widgets.TextInput(title="Longitude (Format: [MIN, MAX])",
                                value = "[13, 25]" )
inp_start_year = bmo.widgets.TextInput(title="End year:",
                                value = "1999" )
Example #11
0
def generate_report(io_generator, tr):
    """
    Parameters
    ----------
    io_generator : tedana.io.OutputGenerator
        io_generator object for this workflow's output
    tr : float
        The repetition time (TR) for the collected multi-echo
        sequence

    Returns
    -------
    HTML : file
        A generated HTML report
    """
    # Load the component time series
    comp_ts_path = io_generator.get_name("ICA mixing tsv")
    comp_ts_df = pd.read_csv(comp_ts_path, sep="\t", encoding="utf=8")
    n_vols, n_comps = comp_ts_df.shape

    # Load the component table
    comptable_path = io_generator.get_name("ICA metrics tsv")
    comptable_cds = df._create_data_struct(comptable_path)

    # Create kappa rho plot
    kappa_rho_plot = df._create_kr_plt(comptable_cds)

    # Create sorted plots
    kappa_sorted_plot = df._create_sorted_plt(
        comptable_cds, n_comps, "kappa_rank", "kappa", "Kappa Rank", "Kappa"
    )
    rho_sorted_plot = df._create_sorted_plt(
        comptable_cds, n_comps, "rho_rank", "rho", "Rho Rank", "Rho"
    )
    varexp_pie_plot = df._create_varexp_pie_plt(comptable_cds, n_comps)

    # link all dynamic figures
    figs = [kappa_rho_plot, kappa_sorted_plot, rho_sorted_plot, varexp_pie_plot]

    div_content = models.Div(width=500, height=750, height_policy="fixed")

    for fig in figs:
        df._link_figures(fig, comptable_cds, div_content, io_generator)

    # Create a layout
    app = layouts.gridplot(
        [
            [
                layouts.row(
                    layouts.column(
                        layouts.row(kappa_rho_plot, varexp_pie_plot),
                        layouts.row(rho_sorted_plot, kappa_sorted_plot),
                    ),
                    layouts.column(div_content),
                )
            ]
        ],
        toolbar_location="left",
    )

    # Embed for reporting and save out HTML
    kr_script, kr_div = embed.components(app)

    # Generate html of buttons (only for images that were generated)
    buttons_html = _generate_buttons(opj(io_generator.out_dir, "figures"))

    # Read in relevant methods
    with open(opj(io_generator.out_dir, "report.txt"), "r+") as f:
        about = f.read()

    body = _update_template_bokeh(kr_div, about, kr_script, buttons_html)
    html = _save_as_html(body)
    with open(opj(io_generator.out_dir, "tedana_report.html"), "wb") as f:
        f.write(html.encode("utf-8"))
                         color=colors[2], legend='Susceptible')
    median_log_hover = tools.HoverTool()
    median_log_hover.tooltips = [
        ('Frequency', '@frequency'),
        ('Period', '@period'),
        ('Spectral Density', '@power'),
        ('Genotype', '@genotype')
    ]
    median_log_plot.add_tools(median_log_hover)

    return lay.gridplot([[mean_plot,     median_plot],
                         [mean_log_plot, median_log_plot]],
                        toolbar_location='left')


larva_periodogram_title = mdl.Div(text='<h1>Larva Periodogram, '
                                         '{} runs</h1>'.format(number_of_runs))
larva_periodogram_plot = periodogram_plotter(larva_mean_periodogram_sources,
                                             larva_median_periodogram_sources,
                                             'Larva')


def seasonal_data_plotter(timeseries_mean_source,   decomp_mean_source: dict,
                          timeseries_median_source, decomp_median_source: dict,
                          life_stage_title: str):
    """
    Create a plot of the seasonal data via frequencies
    Args:
        timeseries_mean_source:   original series source for mean
        decomp_mean_source:       decomposition source   for mean
        timeseries_median_source: original series source for median
        decomp_median_source:     decomposition source   for median
Example #13
0
# -*- coding: utf-8 -*-
# pylint: disable=unsubscriptable-object, too-many-locals
from __future__ import print_function
from os.path import dirname, join

from bokeh.layouts import layout
import bokeh.models as bmd
from bokeh.io import curdoc

html = bmd.Div(text=open(join(dirname(__file__), "static",
                              "table.html")).read(),
               width=960)

# Put the tabs in the current document for display
curdoc().title = "C-C Cross-Coupling Genome"
curdoc().add_root(layout([html]))
Example #14
0
def generate_report(out_dir, tr):
    """
    Parameters
    ----------
    out_dir : str
        File path to a completed tedana output directory
    tr : float
        The repetition time (TR) for the collected multi-echo
        sequence

    Returns
    -------
    HTML : file
        A generated HTML report
    """
    # Load the component time series
    comp_ts_path = opj(out_dir, 'ica_mixing.tsv')
    comp_ts_df = pd.read_csv(comp_ts_path, sep='\t', encoding='utf=8')
    n_vols, n_comps = comp_ts_df.shape

    # Load the component table
    comptable_path = opj(out_dir, 'ica_decomposition.json')
    comptable_cds = df._create_data_struct(comptable_path)

    # Create kappa rho plot
    kappa_rho_plot = df._create_kr_plt(comptable_cds)

    # Create sorted plots
    kappa_sorted_plot = df._create_sorted_plt(comptable_cds, n_comps,
                                              'kappa_rank', 'kappa',
                                              'Kappa Rank', 'Kappa')
    rho_sorted_plot = df._create_sorted_plt(comptable_cds, n_comps,
                                            'rho_rank', 'rho',
                                            'Rho Rank', 'Rho')
    varexp_pie_plot = df._create_varexp_pie_plt(comptable_cds, n_comps)

    # link all dynamic figures
    figs = [kappa_rho_plot, kappa_sorted_plot,
            rho_sorted_plot, varexp_pie_plot]

    div_content = models.Div(width=500, height=750, height_policy='fixed')

    for fig in figs:
        df._link_figures(fig, comptable_cds, div_content, out_dir=out_dir)

    # Create a layout
    app = layouts.gridplot([[
        layouts.column(layouts.row(kappa_rho_plot, varexp_pie_plot),
                       layouts.row(rho_sorted_plot, kappa_sorted_plot)),
        layouts.column(div_content)]],
        toolbar_location='left')

    # Embed for reporting and save out HTML
    kr_script, kr_div = embed.components(app)

    # Read in relevant methods
    with open(opj(out_dir, 'report.txt'), 'r+') as f:
        about = f.read()

    body = _update_template_bokeh(kr_div, about, kr_script)
    html = _save_as_html(body)
    with open(opj(out_dir, 'tedana_report.html'), 'wb') as f:
        f.write(html.encode('utf-8'))