Exemple #1
0
def input_tab():
    output_file("bokeh_app/output/text_input.html")
    text_input = TextAreaInput(value="Voer je review hier in :)",
                               rows=6,
                               title="Sentiment tester")
    text_input.on_change("value", input_handler)
    tab = Panel(child=column(text_input, toggle), title='Tester')
    return tab
    def __init__(self, doc):
        ###############     Initiating Variables     ###################
        self.doc = doc
        self.uploaded_projects_path = join(dirname(__file__),"..","data","uploaded_projects")
        self.extracted_projects_path = join(dirname(__file__),"..","data","extracted_projects")
        self.current_uploaded_file = "No file loaded"
        self.current_extracted_file = "No Project"
        self.full_uploaded_project_path = "empty"
        self.full_extracted_project_path = "empty"
        self.download_file_path = "No file to download"
        self.tables = []

        ###############     Creating Controls        ###################
        #self.fileinput = FileInput(accept=".xer", name="fileinput", css_classes=["myinput"])
        self.fileinput = FileInput(accept=".xer", name="fileinput", css_classes=["myinput"])
        self.textarea = TextAreaInput(value="XER file contents will show here!", rows = 10, name="textarea", css_classes=["mytext"])
        self.extract = Button(label="Extract Data", name="extract", css_classes=["mybutton"])
        self.download = Div(text="""No file to download""", name="download", css_classes=["mylink"])
        self.panel_tabs = self.init_panels()

        ###############     Defining Responses        ###################
        self.fileinput.on_change('value', self.upload_init)
        self.extract.on_click(self.extract_init)

        ###############     Exporting Controls        ###################
        self.doc.add_root(self.fileinput)
        self.doc.add_root(self.textarea)
        self.doc.add_root(self.extract)
        self.doc.add_root(self.download)
        self.doc.add_root(self.panel_tabs)
 def doInit(self):
     if 'type' in self._settings and self._settings['type'] == 'textarea':
         self.div = TextAreaInput(value=".",cols = int(self._settings['width']/10),height=int(300/10))
     else:
         self.div = Div(text=".", width=self._settings['width'], height=300)
     assert 'data_field' in self._settings
     assert 'display_range' in self._settings
     pass
Exemple #4
0
def classification_tab():
    pairs = [["stackoverflow.com", "academia.stackexchange.com"],["stackoverflow.com", "softwareengineering.stackexchange.com"]]
    
    # pretrained classification models
    nbsoac = load("app/models/10k_so_ac_bayes_model.joblib")
    nbsose = load("app/models/10k_so_se_bayes_model.joblib")
    svmsoac = load("app/models/10k_so_ac_SVM_model.joblib")
    svmsose = load("app/models/10k_so_se_SVM_model.joblib")
    
    learning_type = RadioButtonGroup(labels=["Bayes", "Support Vector Machine"], active=0)
    
    site_pair = RadioButtonGroup(labels=["Stack Overflow/Academia", "Stack Overflow/Software Engineering"], active=0)
    
    tai = TextAreaInput(value="", rows=6, title="Enter a post message:")
    
    predict = Button(label="Predict", button_type="success")
    
    p = Paragraph(text="""Your Site Prediction will be displayed here""",
            width=300, height=50)
    
    def make_prediction():
        lt = learning_type.active
        sp = site_pair.active
        model = None
        if lt == 0:
            if sp == 0:
                model = nbsoac
            else:
                model = nbsose
        else:
            if sp == 0:
                model = svmsoac
            else:
                model = svmsose
        prediction = model.predict([tai.value])[0]
        p.text = "Message belongs to site: " + pairs[sp][prediction - 1]


    predict.on_click(make_prediction)

    # Put controls in a single element
    controls = WidgetBox(learning_type, site_pair, tai, predict, p)

    # Create a row layout
    layout = row(controls)

    tab = Panel(child=layout, title='Message Site Classification')
    
    return tab
 def __init__(self, max_length=1024, doc=None, log=None):
     clear_button = Button(
         label='Clear',
         sizing_mode='fixed',
         width_policy='min',
     )
     text = TextAreaInput(
         value='',
         sizing_mode='stretch_both',
         max_length=2**20,
     )
     view = column(
         row(clear_button, sizing_mode='stretch_width'),
         text,
         sizing_mode='stretch_both',
     )
     super(ConsoleViewController, self).__init__(view, doc, log)
     self.text = text
     self.clear_button = clear_button
     self.clear_button.on_click(self.clear_button_on_click)
     self.max_length = max_length
     self.buffer = []
     self.lock = Lock()
Exemple #6
0

def p1c1_on_allele_table_edit(attrname, old, new):
    # print(p1c1_allele_table.source.data)
    pass


# results_files = []
source_cases = {}
df_cases = {}

pNc0_select_results = Button(label='Add GeneMapper Results',
                             button_type='success')
pNc0_select_results.on_click(pNc0_on_results_click)
pNc0_results_text = TextAreaInput(value='<results file>',
                                  disabled=True,
                                  rows=5)

# select_host_case = Select(title='Select Host', options=list(source_cases.keys()))
p0c0_select_host_case = Select(title='Select Host', options=[])
p0c0_select_host_case.on_change('value', p0c0_on_host_click)

p0c0_select_donor_cases = MultiSelect(
    title='Select Donor(s) <ctrl+click to multiselect>', options=[], size=20)
p0c0_select_donor_cases.on_change('value', p0c0_on_donor_change)

p0c0_export_template = Button(label='Export Template', button_type='warning')
p0c0_export_template.on_click(p0c0_on_export_template_click)

p0c0_enter_host_name = TextInput(title='Enter Host Name',
                                 value='<type host name here>')
Exemple #7
0

alpha_range_slider.on_change('value', alpha_size)

size_range_slider.on_change('value', alpha_size)

bt = Button(label='Update Plot',
            default_size=300,
            css_classes=['custom_button_1'])
bt.on_click(my_slider_handler)

hovertool_widget = RadioButtonGroup(labels=["No Hover tool", "Hover tool"],
                                    active=0)

hovertool_timer = TextAreaInput(value="",
                                rows=1,
                                title="Select display time for tooltip")

radio_button_group = RadioButtonGroup(
    labels=["Darwin", "Darwin E", "Darwin S", "Daytona", "Eiffel"], active=3)


def drs_function(attr, old, new):
    pre.text = '<h4 style="border-top: 2px solid #778899;width: 1600px"><br><b style="color:slategray">Adjusting presets to reduce load....</b><br></h4>'
    if radio_button_group.active == 0:
        df = pd.read_csv('generated_data/darwin_rental_datagenerated.csv')
    elif radio_button_group.active == 1:
        df = pd.read_csv('generated_data/darwin_e_rental_datagenerated.csv')
    elif radio_button_group.active == 2:
        df = pd.read_csv('generated_data/darwin_s_rental_datagenerated.csv')
    elif radio_button_group.active == 3:
Exemple #8
0
from datetime import date
from random import randint

from bokeh.io import show, output_notebook
from bokeh.models import ColumnDataSource, DataTable, DateFormatter, TableColumn
from bokeh.models import Button, Column

from bokeh.models.widgets import Div
from bokeh.layouts import column

from intent_classifier import Intent_classifier

intent_classifier = Intent_classifier()

intent_0 = TextInput(title="Intent 0", name='intent_0', value='delayed')
sentence_0 = TextAreaInput(value="Is my bill delayed", title="Prototype Sentence:", rows=5, cols=1000, max_length=1400)
row_0 = row(intent_0, sentence_0, width=800)

intent_1 = TextInput(title="Intent 1", name='intent_1', value='send')
sentence_1 = TextAreaInput(value="Can you email me my statement", title="Prototype Sentence:", rows=5, cols=1000, max_length=1400)
row_1 = row(intent_1, sentence_1, width=800)

intent_2 = TextInput(title="Intent 2", name='intent_2', value='status')
sentence_2 = TextAreaInput(value="what is the billing status of john doe", title="Prototype Sentence:", rows=5, cols=1000, max_length=1400)
row_2 = row(intent_2, sentence_2, width=800)

def train_intents():
#     out_div.text = 'training begins'
    intents = [intent_0.value, intent_1.value, intent_2.value]
    sentences = [sentence_0.value, sentence_1.value, sentence_2.value]
    intent_classifier.train(intents, sentences)
Exemple #9
0
    def __init__(self, controller):
        """Initialize object.

        First part of two-part initialization.
        Put initialization code here that's very unlikely to fail.
        """
        self.controller = controller

        # Explains how to run the model.
        self.headingrunexplain = Div(
            text="""You can run an analysis or load an existing analysis. """
                 """Select the year for analysis then run the forecast.""",
            sizing_mode="""stretch_width""")

        self.loadedheading = Div(
            text="""<span style='font-weight:bold;font-size:14pt'>"""
                 """Year currently loaded.</span>""",
            sizing_mode="""stretch_width""")

        self.loaded = Div(
            text="""<span style='color:red;font-size:12pt'>"""
                 """No analysis year loaded.</span>""",
            sizing_mode="""stretch_width""")

        self.datainsystemheading = Div(
            text="""<span style='font-weight:bold;font-size:14pt'>"""
                 """Analysis years in system.</span>""",
            sizing_mode="""stretch_width""")

        self.datainsystem = TextAreaInput(
            title="""Elections years analyzed in system""",
            value="""No years in system""",
            rows=1)

        self.selecttheyeartoload = Select(
            title="""Year to load and display""",
            options=['dummy1', 'dummy2', 'dummy3'],
            value="""dummy1""")

        # Load year button
        self.loadyear = Button(
            label="""Load year""",
            width=300,
            button_type="""success""")

        self.forecastheading = Div(
            text="""<span style='font-weight:bold;font-size:14pt'>"""
                 """Election year to forecast.</span>""",
            sizing_mode="""stretch_width""")

        # Menu of available Presidential elections to forecast.
        self.selecttheyeartoforecast = Select(
            title="""Year to forecast""",
            options=['dummy1', 'dummy2', 'dummy3'],
            value="""dummy1""")
        # Run forecast button
        self.runforecast = Button(
            label="""Run forecast""",
            width=300,
            button_type="""success""")
        # Shows status of the forecast model.
        self.statusreport = TextAreaInput(
            title="""Forecast run response""",
            value="""No forecast results run.""",
            sizing_mode="""stretch_width""",
            rows=6)

        # Layout the widgets
        r1 = row(children=[self.headingrunexplain])
        c1 = column(children=[self.forecastheading,
                              self.selecttheyeartoforecast,
                              self.runforecast,
                              self.statusreport])
        c2 = column(children=[self.datainsystemheading,
                              self.datainsystem,
                              self.selecttheyeartoload,
                              self.loadyear])
        c3 = column(children=[self.loadedheading,
                              self.loaded])

        self.layout = column(children=[r1,
                                       row(children=[c1,
                                                     Spacer(width=40),
                                                     c2,
                                                     Spacer(width=40),
                                                     c3])],
                             sizing_mode='scale_width')
        self.panel = Panel(child=self.layout,
                           title='Run/load forecast')
Exemple #10
0
def graph():
    def reading_config(path):

        #Reading the configuration file
        file = open(path, "r")

        #dictio=yaml.full_load(file)
        dictio = yaml.load(file, Loader=yaml.FullLoader)

        file.close()

        #Exctraction of the sensors part and the database part
        dictio_sensors = dictio['sensors']
        dictio_database = dictio['database']

        #Transformation in DataFrame to allow an easy read
        df_sensors = pd.DataFrame(dictio_sensors)
        df_databases = pd.DataFrame(dictio_database)

        list_sensor_name = []
        for i in range(0, df_sensors.shape[1]):
            list_sensor_name.append(df_sensors.loc['name_sensor'][i])

        L = []
        L.append(df_sensors.loc['Registre'][0])

        list_registre_name = L[len(L) - 1]

        L_influx = []
        L_influx.append(df_databases.loc['name'][i])
        L_influx.append(df_databases.loc['username'][i])
        L_influx.append(df_databases.loc['password'][i])
        L_influx.append(df_databases.loc['ip'][i])
        L_influx.append(df_databases.loc['port'][i])

        return (list_sensor_name, list_registre_name, L_influx)

    def make_dataset(capteur_list, text_input_start, text_input_end,
                     nom_capteur, L_influx):

        xs = []
        ys = []
        colors = []
        labels = []

        client = DataFrameClient(host=L_influx[3],
                                 port=L_influx[4],
                                 username=L_influx[1],
                                 password=L_influx[2])
        client.switch_database(L_influx[0])

        #Granularity to avoid to display too much points on the figure
        end = datetime.strptime(text_input_end, "%Y-%m-%d %H:%M:%S")
        start = datetime.strptime(text_input_start, "%Y-%m-%d %H:%M:%S")
        ecartSecondes = (end - start).total_seconds()

        if ecartSecondes < 86401:
            groupby = None
        elif ecartSecondes > 86401 and ecartSecondes < 5000000:
            groupby = '1m'
        elif ecartSecondes > 5000000 and ecartSecondes < 77000000:
            groupby = '15m'
        else:
            groupby = '1h'

        #print(ecartSecondes, groupby)

        #Construction of vectors x and y for each register to be displayed
        for elt in capteur_list:

            if groupby == None:
                requete = "SELECT " + '"' + elt + '"' + " FROM measure WHERE time >= " + "'" + text_input_start + "'" + " AND " + "time <= " + "'" + text_input_end + "'" + " AND " + "ID=" + "'" + nom_capteur + "'"
                datasets = client.query(requete)
                df = pd.DataFrame(datasets['measure'])
                df = df.rename_axis('Date')
                df.index = df.index.astype('datetime64[ns]')

                client.close()

                #Convert data in list of lists
                a = []
                b = []
                for i in range(df.shape[0]):
                    a.append(df[elt][i])
                    b.append(df.index[i])
                xs.append(a)
                ys.append(b)

                colors.append(capteur_color[capteur_list.index(elt)])

                labels.append(elt)

            else:
                requete = "SELECT MEAN(" + '"' + elt + '"' + ") FROM measure WHERE time >= " + "'" + text_input_start + "'" + " AND " + "time <= " + "'" + text_input_end + "'" + " AND " + "ID=" + "'" + nom_capteur + "'" + " GROUP BY time(" + groupby + ") fill(0)"
                datasets = client.query(requete)
                df = pd.DataFrame(datasets['measure'])
                df = df.rename_axis('Date')
                df.index = df.index.astype('datetime64[ns]')

                client.close()

                #Conversion des données en liste de liste
                a = []
                b = []
                for i in range(df.shape[0]):
                    a.append(df['mean'][i])
                    b.append(df.index[i])
                xs.append(a)
                ys.append(b)

                colors.append(capteur_color[capteur_list.index(elt)])

                labels.append(elt)

        #Construction of the source of the figure
        new_src = ColumnDataSource(data={
            'x': xs,
            'y': ys,
            'color': colors,
            'label': labels
        })

        return new_src

    def make_plot(src):
        # Blank plot with correct labels
        p = figure(plot_width=1000,
                   plot_height=700,
                   title='Graph of the registers',
                   x_axis_type="datetime",
                   x_axis_label='Date',
                   y_axis_label='Unit',
                   output_backend='webgl')

        p.multi_line('y',
                     'x',
                     color='color',
                     legend='label',
                     line_width=3,
                     source=src)

        # Hover tool with next line policy
        hover = HoverTool(tooltips=[('Capteur', '@label')], line_policy='next')

        # Add the hover tool and styling
        p.add_tools(hover)

        # Styling
        p = style(p)

        return p

    # Update function takes three default parameters
    def update(attr, old, new):
        #clear_plot(old)

        # Get the list of carriers for the graph
        capteur_to_plot = [
            capteur_selection.labels[i] for i in capteur_selection.active
        ]

        l = text_input.value
        L_text = []
        for val in l.split('\n'):
            L_text.append(val)

        text_input_start = L_text[1]
        text_input_end = L_text[4]

        nom_capteur = select.value

        # Make a new dataset based on the selected sensors
        new_src = make_dataset(capteur_to_plot, text_input_start,
                               text_input_end, nom_capteur, L_influx)

        # Update the source used the quad glpyhs
        src.data.update(new_src.data)

    def style(p):
        # Title
        p.title.align = 'center'
        p.title.text_font_size = '20pt'
        p.title.text_font = 'serif'

        # Axis titles
        p.xaxis.axis_label_text_font_size = '14pt'
        p.xaxis.axis_label_text_font_style = 'bold'
        p.yaxis.axis_label_text_font_size = '14pt'
        p.yaxis.axis_label_text_font_style = 'bold'

        # Tick labels
        p.xaxis.major_label_text_font_size = '12pt'
        p.yaxis.major_label_text_font_size = '12pt'

        return p

    #Select
    """
    WARNING : you need to change the path to your config file to run this code
    """
    (available_name, available_capteur, L_influx) = reading_config(
        "/home/rsm/Desktop/Arnaud_Debar/bokehapp_final/config/config.yml")
    select = Select(title="Select one sensor:",
                    value=available_name[0],
                    options=available_name)
    select.on_change('value', update)

    available_capteur.sort()

    #capteur_color=Category20_20
    capteur_color = []
    for val in cc.glasbey_hv:
        capteur_color.append(plt.colors.to_hex(val))
    #capteur_color.sort()

    #Capteur to plot
    capteur_selection = CheckboxGroup(labels=available_capteur, active=[0, 1])
    capteur_selection.on_change('active', update)

    #Date input
    text_input = TextAreaInput(
        value='Start:\n2019-08-08 18:20:00\n  \nEnd:\n2019-08-09 10:27:00\n ',
        rows=5,
        title="Date: Year-Month-Day Hour:Minute:Second")
    text_input.on_change('value', update)

    l = text_input.value
    L_text_input = []
    for val in l.split('\n'):
        L_text_input.append(val)

    initial_text_input_start = L_text_input[1]
    initial_text_input_end = L_text_input[4]

    #Initial register display
    initial_capteur = [
        capteur_selection.labels[i] for i in capteur_selection.active
    ]

    #Make the initial dataset
    src = make_dataset(initial_capteur, initial_text_input_start,
                       initial_text_input_end, available_name[0], L_influx)

    #Make the plot
    p = make_plot(src)

    # Add style to the plot
    p = style(p)

    # Put control in a single element
    controls = WidgetBox(select, capteur_selection, text_input)

    layout = row(controls, p)

    tab = Panel(child=layout, title='Summary Graph')

    return tab
Exemple #11
0
def table():
    def reading_config(path):

        #Reading the configuration file
        file = open(path, "r")

        #dictio=yaml.full_load(file)
        dictio = yaml.load(file, Loader=yaml.FullLoader)

        file.close()

        #Exctraction of the sensors part and the database part
        dictio_sensors = dictio['sensors']
        dictio_database = dictio['database']

        #Transformation in DataFrame to allow an easy read
        df_sensors = pd.DataFrame(dictio_sensors)
        df_databases = pd.DataFrame(dictio_database)

        list_sensor_name = []
        for i in range(0, df_sensors.shape[1]):
            list_sensor_name.append(df_sensors.loc['name_sensor'][i])

        L = []
        L.append(df_sensors.loc['Registre'][0])

        list_registre_name = L[len(L) - 1]

        L_influx = []
        L_influx.append(df_databases.loc['name'][i])
        L_influx.append(df_databases.loc['username'][i])
        L_influx.append(df_databases.loc['password'][i])
        L_influx.append(df_databases.loc['ip'][i])
        L_influx.append(df_databases.loc['port'][i])

        return (list_sensor_name, list_registre_name, L_influx)

    def make_dataset(capteur_list, text_input_start, text_input_end,
                     nom_capteur, L_influx):

        client = DataFrameClient(host=L_influx[3],
                                 port=L_influx[4],
                                 username=L_influx[1],
                                 password=L_influx[2])
        client.switch_database(L_influx[0])

        src = pd.DataFrame()

        for elt in capteur_list:
            requete = "SELECT " + '"' + elt + '"' + " FROM measure WHERE time >= " + "'" + text_input_start + "'" + " AND " + "time <= " + "'" + text_input_end + "'" + " AND " + "ID=" + "'" + nom_capteur + "'"
            datasets = client.query(requete)
            df = pd.DataFrame(datasets['measure'])
            df = df.rename_axis('Date')
            df.index = df.index.astype('datetime64[ns]')
            src = pd.concat([df, src], axis=1)

        client.close()
        src['Date'] = src.index
        Index = [i for i in range(0, df.shape[0])]
        src.index = Index

        cols = src.columns.tolist()
        cols = cols[-1:] + cols[:-1]
        src = src[cols]

        return (src)

    def make_table(source, src):
        table_columns = [
            TableColumn(field='Date',
                        title='Date',
                        formatter=DateFormatter(format="%m/%d/%Y %H:%M:%S"))
        ]
        colonne = src.columns
        colonne = colonne.delete(0)
        table_columns += [TableColumn(field=col, title=col) for col in colonne]
        liste = [k for k in range(0, 10)]
        longueur = src.shape[0]
        for k in range(longueur - 10, longueur):
            liste.append(k)

        view1 = CDSView(source=source, filters=[IndexFilter(indices=liste)])
        #table_source = ColumnDataSource(src)
        datatable = DataTable(source=source,
                              columns=table_columns,
                              width=1200,
                              height=1000,
                              view=view1)

        #print(datatable.fit_columns)
        return datatable

    # Update function takes three default parameters
    def update(attr, old, new):

        capteur_to_plot = [
            capteur_selection.labels[i] for i in capteur_selection.active
        ]
        l = text_input.value
        L_text = []
        for val in l.split('\n'):
            L_text.append(val)

        text_input_start = L_text[1]
        text_input_end = L_text[4]

        nom_capteur = select.value

        new_src = make_dataset(capteur_to_plot, text_input_start,
                               text_input_end, nom_capteur, L_influx)
        new_source = ColumnDataSource(new_src)
        dictio = {}
        for i in range(0, len(new_src.columns)):
            dictio[new_src.columns[i]] = new_src[new_src.columns[i]]

        source.data = dictio

        table_columns = [
            TableColumn(field='Date',
                        title='Date',
                        formatter=DateFormatter(format="%m/%d/%Y %H:%M:%S"))
        ]
        colonne = new_src.columns
        colonne = colonne.delete(0)
        table_columns += [TableColumn(field=col, title=col) for col in colonne]
        datatable.columns = table_columns

        liste = [k for k in range(0, 10)]
        longueur = new_src.shape[0]
        for k in range(longueur - 10, longueur):
            liste.append(k)
        view1 = CDSView(source=new_source,
                        filters=[IndexFilter(indices=liste)])
        datatable.view = view1

    #Select
    """
    WARNING : you need to change the path to your config file to run this code
    """
    (available_name, available_capteur, L_influx
     ) = reading_config("/home/rsm/Desktop/bokehapp_final/config/config.yml")
    select = Select(title="Select one sensor:",
                    value=available_name[0],
                    options=available_name)
    select.on_change('value', update)

    available_capteur.sort()

    #Capteur to plot
    capteur_selection = CheckboxGroup(labels=available_capteur, active=[0])
    capteur_selection.on_change('active', update)

    text_input = TextAreaInput(
        value='Start:\n2019-08-08 18:20:00\n  \nEnd:\n2019-08-08 18:27:00\n ',
        rows=5,
        title="Date: Year-Month-Day Hour:Minute:Second")
    text_input.on_change('value', update)

    initial_capteur = [
        capteur_selection.labels[i] for i in capteur_selection.active
    ]
    l = text_input.value
    L_text_input = []
    for val in l.split('\n'):
        L_text_input.append(val)

    initial_text_input_start = L_text_input[1]
    initial_text_input_end = L_text_input[4]

    src = make_dataset(initial_capteur, initial_text_input_start,
                       initial_text_input_end, available_name[0], L_influx)
    source = ColumnDataSource(src)
    #Make the plot
    datatable = make_table(source, src)

    #Download part
    button = Button(label='Download', button_type='success')
    button.callback = CustomJS(args=dict(source=source),
                               code=open(join(dirname(__file__),
                                              "download.js")).read())
    #text_banner = Paragraph(text='To download the displayed data, please indicate the name you want to give to the file in the box below. The file will be automatically created in CSV format in the "Folder_CSV" folder as soon as you click on the "Download" button', width=250, height=130)
    #path_input=TextInput(value="Name", title="Name of the file :")

    # Put control in a single element
    controls = WidgetBox(select, capteur_selection, text_input, button)

    layout = row(controls, datatable)

    tab = Panel(child=layout, title='Summary Table')

    return tab
Exemple #12
0
dmo_data = ColumnDataSource(pd.read_sql(sqlalchemy.select([dmo]), conn))
disk_data = ColumnDataSource(pd.read_sql(sqlalchemy.select([disk]), conn))
dmo_source = ColumnDataSource(data=df)
disk_source = ColumnDataSource(data=df2)
dmo_scatter = ColumnDataSource(data={'x': [], 'y': [], 'host_id': []})
disk_scatter = ColumnDataSource(data={'x': [], 'y': [], 'host_id': []})
dmo_line = ColumnDataSource(data={'x': [], 'y': []})
disk_line = ColumnDataSource(data={'x': [], 'y': []})

# Build Bokeh inputs and callbacks

col_exclude = ['x', 'y', 'z', 'index', 'host_id', 'id']
col_allow = [i for i in df.columns if i not in col_exclude]
default_query = "WHERE vmax > 10 AND dist BETWEEN 1 AND 100"

sql_query = TextAreaInput(value=default_query, title='SQL filter:', rows=2)
sql_query2 = TextAreaInput(value=default_query, title='SQL filter:', rows=2)
x_col = Select(title="X-axis Data:", value="vmax", options=col_allow)
y_col = Select(title="Y-axis Data:", value="mass", options=col_allow)
log_axes = CheckboxGroup(labels=["Log(x)", "Log(y)"], active=[], inline=True)
plot_type = Select(title="Standard plots:",
                   value="Infall",
                   options=["Infall", "Mvir", "Vmax", "Vpeak", "Pericenter"])

labels_dict = dict(vmax='Vmax (km/s)',
                   mass='Mvir (M_sun)',
                   rvir='Rvir (kpc)',
                   dist='Dist from MW (kpc)',
                   peri='Pericenter (kpc)',
                   rs='NFW scale radius (kpc)',
                   vx='X Velocity (km/s)',
Exemple #13
0
        TableColumn(field="max", title="Max. #", formatter=NumberFormatter(format='0,0'), width=50),
        TableColumn(field="stride", title="Stride", formatter=NumberFormatter(format='0,0'), width=50),
    ]
complex_table = DataTable(source=SU_act, name='Complex table', columns=columns_complex_table, width=450, height=280, index_position=None, editable=True)

# Define buttons for adding subunits
Add_SU_cb=CustomJS(args=dict(SU_act=SU_act), code=open(os.path.join(os.getcwd(), 'JS_Functions', "Add_SU_cb.js")).read() )
Del_SU_cb=CustomJS(args=dict(SU_act=SU_act), code=open(os.path.join(os.getcwd(), 'JS_Functions', "del_SU_cb.js")).read() )

SU_add_button=Button(label='Add subunit', width=120, height=30, button_type='success')
SU_del_button=Button(label='Delete subunit', width=120, height=30, button_type='danger')

SU_add_button.js_on_event(ButtonClick, Add_SU_cb)
SU_del_button.js_on_event(ButtonClick, Del_SU_cb)

comment_window = TextAreaInput(value="Add comments here", width = 340, height= 280)


stoich = AjaxDataSource(dict(stoichiometry=[], mass=[], mass_diff=[]))
diff_match   = TextInput(value= str(1000.0), title='Allowed ΔMass',  disabled=False, width=150, height=50)

columns_match_table = [
        TableColumn(field="stoichiometry", title="Stoichiometry"),
        TableColumn(field="mass", title="Mass of Combination", formatter=NumberFormatter(format='0,0.00')),
        TableColumn(field="mass_diff", title="Difference to Measured Mass", formatter=NumberFormatter(format='0,0.00')),
    ]



# Further options to implement ("Export SVG","expo_svg"), ("Export high-res PNG","expo_svg")]
match_table = DataTable(source=stoich, name='Complex table', columns=columns_match_table, width=534, height=280, index_position=None)
Exemple #14
0
def kde():
    ###------------------------PARAMETER DEFAULTS-----------------------------###
    #  range[Lower, Upper, Step Size]
    ### - SAMPLING Parameters
    d_nsamp, r_nsamp = 500, [100, 2000, 50]  # Number of samples

    plot_data = figure(
        plot_height=400,
        plot_width=800,
        title="Data Histogram",
        toolbar_location="above",
        x_axis_label="x",
        y_axis_label="Density",
        tools="pan,save,box_zoom,wheel_zoom",
    )
    style(plot_data)

    plot_clear = Button(label="Clear All", button_type="warning")

    # Plot Control Buttons

    ctl_title = Div(text="<h3>Simulator</h3>")
    dist_type = Select(
        title="Select sampling distribution:",
        value="Gaussian",
        options=["Gaussian", "Beta", "Gamma"],
    )

    div1 = Div(
        text=
        """<p style="border:3px; border-style:solid; border-color:grey; padding: 1em;">
                    Parameters depend on the distribution. Refer to Scipy Documentation. <br />  
                    - Gaussian: loc (mean), scale (variance).<br />  
                    - Gamma: a, loc, scale.<br /> 
                    - Beta: a, b, loc, scale.<br /> 
                    </p>""",
        width=300,
        height=130,
    )

    ctl_nsamp = Slider(
        title="Number of samples",
        value=d_nsamp,
        start=r_nsamp[0],
        end=r_nsamp[1],
        step=r_nsamp[2],
    )

    mu = TextInput(title="Mean", value="0.0")
    sigma = TextInput(title="Variance", value="1.0")
    a = TextInput(title="a", value="1.0")
    b = TextInput(title="b", value="1.0")

    plot_sim = Button(label="Simulate", button_type="primary")
    simulate = widgetbox(ctl_title, dist_type, div1, ctl_nsamp, mu, sigma, a,
                         b, plot_sim)

    # plot_ctls = column(ctl_title, div1, plot_sim)

    ### Manual Fitting
    fit_title = Div(text="<h3>Manual KDE</h3>")

    kernel = Select(
        title="Select kernel to fit on data:",
        value="gaussian",
        options=["gaussian", "tophat", "exponential", "linear", "cosine"],
    )
    bandwidth = TextInput(title="Bandwidth", value="1.0")

    fit_sim = Button(label="Fit", button_type="success")

    fit1 = widgetbox(fit_title, kernel, bandwidth, fit_sim)

    ### Cross Validation fit
    fit_title = Div(
        text=
        "<h3>Cross Validation - Params Search</h3> <br /> Select kernels for parameter search."
    )

    kernels = CheckboxButtonGroup(
        active=[0, 1],
        labels=["gaussian", "tophat", "exponential", "linear", "cosine"])
    bandwidths = RangeSlider(title="Bandwidth in Log-space",
                             start=-2,
                             end=1,
                             value=(-1, 0.5),
                             step=0.05)

    cv_slider = Slider(title="Nb of cross-validation",
                       value=5,
                       start=1,
                       end=10,
                       step=1)

    fit_sim2 = Button(label="Fit", button_type="success")
    text_output = TextAreaInput(
        value="Choose Bandwidth Range and Kernels from above.",
        rows=4,
        title="Estimated Paramters:",
    )

    fit2 = widgetbox(fit_title, kernels, bandwidths, cv_slider, fit_sim2,
                     text_output)

    ###-----------------------------------------------------------------------###
    ###-----------------------BASE-LEVEL FUNCTIONS----------------------------###

    def make_data(dist_type, params):
        # sample data according to dist_type
        data = DISTRIBUTIONS[dist_type].rvs(**params)
        return data

    ###-----------------------------------------------------------------------###
    ###------------------DATA SOURCES AND INITIALIZATION----------------------###

    source1 = ColumnDataSource(data=dict(hist=[], left=[], right=[]))
    plot_data.quad(
        source=source1,
        bottom=0,
        top="hist",
        left="left",
        right="right",
        fill_color="blue",
        line_color="white",
        alpha=0.5,
    )

    source2 = ColumnDataSource(data=dict(x=[], y=[]))
    plot_data.line(
        "x",
        "y",
        source=source2,
        line_width=2,
        alpha=0.7,
        legend="Estimated PDF",
        line_color="black",
    )

    def click_simulate():
        # Make it global to be used later
        global d_data
        # reset pdf
        source2.data = dict(x=[], y=[])
        text_output.value = ""

        if dist_type.value == "Gaussian":
            params = {
                "loc": float(mu.value),
                "scale": float(sigma.value),
                "size": int(ctl_nsamp.value),
            }

        elif dist_type.value == "Gamma":
            params = {
                "loc": float(mu.value),
                "scale": float(sigma.value),
                "a": float(a.value),
                "size": int(ctl_nsamp.value),
            }

        elif dist_type.value == "Beta":
            params = {
                "loc": float(mu.value),
                "scale": float(sigma.value),
                "a": float(a.value),
                "b": float(b.value),
                "size": int(ctl_nsamp.value),
            }

        d_data = make_data(dist_type.value, params)

        hist, edges = np.histogram(d_data, density=True, bins=100)

        source1.data = dict(hist=hist, left=edges[:-1], right=edges[1:])

        plot_data.y_range.start = 0
        plot_data.y_range.end = 1.2 * hist.max()

        plot_data.x_range.start = edges.min() - 1 * (dist_type.value != "Beta")
        plot_data.x_range.end = edges.max() + 1 * (dist_type.value != "Beta")

        plot_data.xaxis.axis_label = "x"
        plot_data.yaxis.axis_label = "Density"

    plot_sim.on_click(click_simulate)

    # KDE Fit

    def fit_kde():
        kde = KernelDensity(kernel=kernel.value,
                            bandwidth=float(bandwidth.value)).fit(
                                d_data.reshape(-1, 1))

        x = np.linspace(d_data.min() - 0.5,
                        d_data.max() + 0.5, 1000).reshape(-1, 1)
        log_dens = kde.score_samples(x)

        source2.data = dict(x=x, y=np.exp(log_dens))

    fit_sim.on_click(fit_kde)

    # Fir CV-model

    def fit_kde_cv():
        text_output.value = "Running..."

        kernels_space = [KERNELS[i] for i in kernels.active]

        min_b = list(bandwidths.value)[0]
        max_b = list(bandwidths.value)[1]

        params = {
            "bandwidth": np.logspace(min_b, max_b, 10),
            "kernel": kernels_space
        }

        grid = GridSearchCV(KernelDensity(),
                            params,
                            cv=int(cv_slider.value),
                            iid=False)

        grid.fit(d_data.reshape(-1, 1))

        x = np.linspace(d_data.min() - 0.5,
                        d_data.max() + 0.5, 1000).reshape(-1, 1)
        log_dens = grid.best_estimator_.score_samples(x)

        source2.data = dict(x=x, y=np.exp(log_dens))

        text_output.value = "CV done. \nBest Params: \n" + str(
            grid.best_params_)

    fit_sim2.on_click(fit_kde_cv)

    # Behavior when the "Clear" button is clicked
    def clear_plot():
        source1.data = dict(hist=[], left=[], right=[])
        source2.data = dict(x=[], y=[])
        text_output.value = ""

    plot_clear.on_click(clear_plot)

    ###-----------------------------------------------------------------------###
    ###----------------------------PAGE LAYOUT--------------------------------###

    col_inputs = column(simulate)
    col_output = column(fit1, fit2, plot_clear)
    col_plots = column(plot_data)
    row_page = row(col_inputs, col_plots, col_output, width=1200)

    # Make a tab with the layout
    tab = Panel(child=row_page, title="Kernel Density Estimation")
    return tab
Exemple #15
0
from pdf_files.pdf_agent import PDF_agent

print('instantiating agent')
covid_agent = PDF_agent()
print('agent initiated')

file = 'EBC External 06.10.20 FAQs.pdf'
covid_agent.read_file(file)
corpus = covid_agent.get_corpus()

# print(corpus)

corpus_text = TextAreaInput(title="Source Corpus",
                            value=corpus,
                            rows=20,
                            cols=20,
                            max_length=10000)

question_field = TextInput(title='Enter question here')
button = Button(label="Ask", button_type="success")
inputs = Column(corpus_text, question_field, button, width=550)

lines = [{'Question': 'question text', 'Answer': 'answer text'}]
summary_df = pd.DataFrame(lines)

Columns = [
    TableColumn(
        field=Ci,
        title=Ci,
        width=296,
Exemple #16
0
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import TextAreaInput

output_file("text_area_input.html")

text_area_input = TextAreaInput(value="default",
                                title="Label:",
                                rows=5,
                                cols=50,
                                max_length=200)

show(widgetbox(text_area_input))
Exemple #17
0
from datetime import date
from random import randint

from bokeh.io import show
from bokeh.models import ColumnDataSource, DataTable, DateFormatter, TableColumn
from bokeh.models import Button, Column

from bokeh.models.widgets import Div
from bokeh.layouts import column

from summarizer_infer import Summarizer
# output_file("layout.html")

text = TextAreaInput(title="Input Text",
                     value='Enter Text to summarize',
                     rows=20,
                     cols=20,
                     max_length=10000)
button = Button(label="Summarize", button_type="success")
inputs = Column(text, button, width=400)

print('instantiating summarizer')
summarizer = Summarizer()
print('summarizer initiated')

# summary_df = summarizer.summarize(source_text)

lines = [{'cnn_summary': 'cnn_summary', 'xsum_summary': 'xsum_summary'}]
summary_df = pd.DataFrame(lines)

Columns = [
Exemple #18
0
 data_table_panel[origin] = DataTable(columns=Columns,
                                      source=source[origin],
                                      reorderable=True,
                                      fit_columns=True,
                                      index_position=None,
                                      width=1000,
                                      height=260,
                                      row_height=23,
                                      css_classes=["my-table"])
 table_row_1[origin] = TextInput(value='', title="Job title")
 table_row_2[origin] = TextInput(value='', title="Company")
 table_row_3[origin] = TextInput(value='', title="Location")
 table_row_4[origin] = TextInput(value='', title="Recruitment responsible")
 table_bloc[origin] = TextAreaInput(value='',
                                    title="Job description",
                                    cols=1000,
                                    max_length=5000,
                                    rows=11)
 grid[origin] = gridplot([[cv_input[origin], location_select[origin]],
                          [
                              column(select_1[origin], select_2[origin],
                                     select_3[origin],
                                     div_job_number[origin]),
                              data_table_panel[origin]
                          ],
                          [
                              column(table_row_1[origin],
                                     table_row_2[origin],
                                     table_row_3[origin],
                                     table_row_4[origin]),
                              table_bloc[origin]
class Protocol:
    def __init__(self):
        note = Div(
            text="<b>NOTE</b>: Each plan may only have one protocol assigned. "
            "Updating database will overwrite any existing data.",
            width=700)
        self.update_checkbox = CheckboxGroup(
            labels=["Only update plans in table."], active=[0])

        self.toxicity = []  # Will be used to link to Toxicity tab

        self.source = ColumnDataSource(data=dict(mrn=['']))
        self.source.selected.on_change('indices', self.source_listener)

        self.clear_source_selection_button = Button(label='Clear Selection',
                                                    button_type='primary',
                                                    width=150)
        self.clear_source_selection_button.on_click(
            self.clear_source_selection)

        self.protocol = Select(value='', options=[''], title='Protocols:')
        self.physician = Select(value='',
                                options=[''],
                                title='Physician:',
                                width=150)

        self.date_filter_by = Select(
            value='None',
            options=['None', 'sim_study_date', 'import_time_stamp'],
            title='Date Filter Type:',
            width=150)
        self.date_filter_by.on_change('value', self.date_ticker)
        self.date_start = DatePicker(title='Start Date:', width=200)
        self.date_start.on_change('value', self.date_ticker)
        self.date_end = DatePicker(title='End Date:', width=200)
        self.date_end.on_change('value', self.date_ticker)

        self.update_protocol_options()
        self.update_physician_options()

        self.protocol_input = TextInput(value='',
                                        title='Protocol for MRN Input:')
        self.update_button = Button(label='Need MRNs to Update',
                                    button_type='default',
                                    width=150)
        self.update_button.on_click(self.update_db)

        self.mrn_input = TextAreaInput(value='',
                                       title='MRN Input:',
                                       rows=30,
                                       cols=25,
                                       max_length=2000)
        self.mrn_input.on_change('value', self.mrn_input_ticker)

        self.columns = [
            'mrn', 'protocol', 'physician', 'tx_site', 'sim_study_date',
            'import_time_stamp', 'toxicity_grades'
        ]
        relative_widths = [1, 0.8, 0.5, 1, 0.75, 1, 0.8]
        column_widths = [int(250. * rw) for rw in relative_widths]
        table_columns = [
            TableColumn(field=c, title=c, width=column_widths[i])
            for i, c in enumerate(self.columns)
        ]
        self.table = DataTable(source=self.source,
                               columns=table_columns,
                               width=800,
                               editable=True,
                               height=600)

        self.protocol.on_change('value', self.protocol_ticker)
        self.physician.on_change('value', self.physician_ticker)
        self.update_source()

        self.layout = column(
            row(self.protocol, self.physician),
            row(self.date_filter_by, Spacer(width=30), self.date_start,
                Spacer(width=30), self.date_end), note,
            row(
                self.table, Spacer(width=30),
                column(self.update_checkbox,
                       row(self.protocol_input, self.update_button),
                       self.clear_source_selection_button, self.mrn_input)))

    def source_listener(self, attr, old, new):
        mrns = [self.source.data['mrn'][x] for x in new]
        self.mrn_input.value = '\n'.join(mrns)

    def update_source(self):

        condition = []

        if self.protocol.value not in self.protocol.options[0:3]:
            condition.append("protocol = '%s'" % self.protocol.value)
        elif self.protocol.value == self.protocol.options[1]:
            condition.append("protocol != ''")
        elif self.protocol.value == self.protocol.options[2]:
            condition.append("protocol = ''")

        if self.physician.value != self.physician.options[0]:
            condition.append("physician = '%s'" % self.physician.value)

        if self.date_filter_by.value != 'None':
            if self.date_start.value:
                condition.append(
                    "%s >= '%s'::date" %
                    (self.date_filter_by.value, self.date_start.value))
            if self.date_end.value:
                condition.append(
                    "%s >= '%s'::date" %
                    (self.date_filter_by.value, self.date_end.value))

        condition = ' AND '.join(condition)

        columns = ', '.join(self.columns + ['study_instance_uid'])

        data = DVH_SQL().query('Plans',
                               columns,
                               condition,
                               order_by='mrn',
                               bokeh_cds=True)

        self.source.data = data

    def update_protocol_options(self):
        options = ['All Data', 'Any Protocol', 'No Protocol'
                   ] + self.get_protocols()
        self.protocol.options = options
        if self.protocol.value not in options:
            self.protocol.value = options[0]

    @property
    def mrns_to_add(self):
        return parse_text_area_input_to_list(self.mrn_input.value,
                                             delimeter=None)

    @staticmethod
    def get_protocols(condition=None):
        return DVH_SQL().get_unique_values('Plans',
                                           'protocol',
                                           condition,
                                           ignore_null=True)

    def update_physician_options(self):
        physicians = ['Any'] + DVH_SQL().get_unique_values(
            'Plans', 'physician')

        self.physician.options = physicians
        if self.physician.value not in physicians:
            self.physician.value = physicians[0]

    def protocol_ticker(self, attr, old, new):
        self.update_source()

    def physician_ticker(self, attr, old, new):
        self.update_source()

    def date_ticker(self, attr, old, new):
        self.update_source()

    def update_db(self):
        if 0 in self.update_checkbox.active:
            condition = "mrn in ('%s')" % "', '".join(self.mrns_to_add)
        else:
            uids = []
            for i, mrn in enumerate(self.mrns_to_add):
                if mrn in self.source.data['mrn']:
                    index = self.source.data['mrn'].index(mrn)
                    uids.append(self.source.data['study_instance_uid'][index])

            condition = "study_instance_uid in ('%s')" % "', '".join(uids)

        DVH_SQL().update(
            'Plans', 'protocol',
            self.protocol_input.value.replace("'",
                                              "").replace("\"", "").replace(
                                                  "\\", ""), condition)

        self.update_source()

        self.clear_source_selection()
        self.protocol_input.value = ''

        self.update_protocol_options()

        self.toxicity.update_protocol_options()
        self.toxicity.update_source()

    def clear_source_selection(self):
        self.source.selected.indices = []

    def add_toxicity_tab_link(self, toxicity):
        self.toxicity = toxicity

    def mrn_input_ticker(self, attr, old, new):
        self.update_update_button_status()

    def update_update_button_status(self):
        if self.mrns_to_add:
            self.update_button.label = 'Update'
            self.update_button.button_type = 'primary'
        else:
            self.update_button.label = 'Need MRNs to Update'
            self.update_button.button_type = 'default'
Exemple #20
0
def draw_bokeh(X, cluster, sentences):
    """Dimension reduction with PCA and plotting with bokeh """

    X_reduced = PCA(n_components=2).fit_transform(X)

    colors = [Category10[10][i % 10] for i in cluster.labels_]
    sizes = np.ones(len(X)) * 10
    sizes[cluster.cluster_centers_indices_] = 20

    source = ColumnDataSource(data=dict(
        eigenv1=[x[0] for x in X_reduced],
        eigenv2=[x[1] for x in X_reduced],
        s=sentences,
        c=colors,
        size=sizes,
    ))

    hover = HoverTool(tooltips=[("index",
                                 "$index"), ("(x,y)",
                                             "@eigenv1, @eigenv2)"), ("s",
                                                                      "@s")])

    p = figure(title="reforma_educativa",
               tools=[hover, ResetTool(), BoxSelectTool()])
    p.toolbar.logo = None
    p.xaxis.axis_label = '1st eigenv'
    p.yaxis.axis_label = '2nd eigenv'
    p.scatter('eigenv1',
              'eigenv2',
              size='size',
              fill_color='c',
              fill_alpha=1,
              line_color='c',
              nonselection_fill_color="c",
              nonselection_fill_alpha=0.5,
              source=source)

    div = Div(width=600)

    text_input = TextAreaInput(title="Text: ", rows=50, max_length=2000)

    layout = row(p, div, text_input)

    source.callback = CustomJS(args=dict(source=source,
                                         div=div,
                                         sentences=sentences,
                                         colors=colors),
                               code="""
            var inds = source.selected.indices
            div.text = ""
            for (var i = 0; i < sentences.length; i++) {
                if (inds.includes(i)) {
                    div.text += '<p style="background-color:' + colors[i] + ';">' + sentences[i] + "</p>"
                }
                else {
                    r = parseInt(colors[i].substring(1, 3), 16)
                    g = parseInt(colors[i].substring(3, 5), 16)
                    b = parseInt(colors[i].substring(5, 7), 16)
                    a = 0.3
                    rgba = r  + "," + g + "," + b + "," + a
                    div.text += '<p style="background-color:rgba(' + rgba + ');">' + sentences[i] + "</p>"
                }   
            }
        """)

    output_file("reforma_educativa.html", title="Sentence embedding example")

    show(layout)
    def __init__(self):
        note = Div(
            text="<b>NOTE</b>: Each plan may only have one protocol assigned. "
            "Updating database will overwrite any existing data.",
            width=700)
        self.update_checkbox = CheckboxGroup(
            labels=["Only update plans in table."], active=[0])

        self.toxicity = []  # Will be used to link to Toxicity tab

        self.source = ColumnDataSource(data=dict(mrn=['']))
        self.source.selected.on_change('indices', self.source_listener)

        self.clear_source_selection_button = Button(label='Clear Selection',
                                                    button_type='primary',
                                                    width=150)
        self.clear_source_selection_button.on_click(
            self.clear_source_selection)

        self.protocol = Select(value='', options=[''], title='Protocols:')
        self.physician = Select(value='',
                                options=[''],
                                title='Physician:',
                                width=150)

        self.date_filter_by = Select(
            value='None',
            options=['None', 'sim_study_date', 'import_time_stamp'],
            title='Date Filter Type:',
            width=150)
        self.date_filter_by.on_change('value', self.date_ticker)
        self.date_start = DatePicker(title='Start Date:', width=200)
        self.date_start.on_change('value', self.date_ticker)
        self.date_end = DatePicker(title='End Date:', width=200)
        self.date_end.on_change('value', self.date_ticker)

        self.update_protocol_options()
        self.update_physician_options()

        self.protocol_input = TextInput(value='',
                                        title='Protocol for MRN Input:')
        self.update_button = Button(label='Need MRNs to Update',
                                    button_type='default',
                                    width=150)
        self.update_button.on_click(self.update_db)

        self.mrn_input = TextAreaInput(value='',
                                       title='MRN Input:',
                                       rows=30,
                                       cols=25,
                                       max_length=2000)
        self.mrn_input.on_change('value', self.mrn_input_ticker)

        self.columns = [
            'mrn', 'protocol', 'physician', 'tx_site', 'sim_study_date',
            'import_time_stamp', 'toxicity_grades'
        ]
        relative_widths = [1, 0.8, 0.5, 1, 0.75, 1, 0.8]
        column_widths = [int(250. * rw) for rw in relative_widths]
        table_columns = [
            TableColumn(field=c, title=c, width=column_widths[i])
            for i, c in enumerate(self.columns)
        ]
        self.table = DataTable(source=self.source,
                               columns=table_columns,
                               width=800,
                               editable=True,
                               height=600)

        self.protocol.on_change('value', self.protocol_ticker)
        self.physician.on_change('value', self.physician_ticker)
        self.update_source()

        self.layout = column(
            row(self.protocol, self.physician),
            row(self.date_filter_by, Spacer(width=30), self.date_start,
                Spacer(width=30), self.date_end), note,
            row(
                self.table, Spacer(width=30),
                column(self.update_checkbox,
                       row(self.protocol_input, self.update_button),
                       self.clear_source_selection_button, self.mrn_input)))
    def __init__(self, protocol):

        self.protocol = protocol  # link to Protocol tab so we can info in the protocol tab

        self.source = ColumnDataSource(data=dict(mrn=[]))
        self.source.selected.on_change('indices', self.source_listener)
        # self.source.on_change('data', self.update_toxicity_grades_from_table)
        self.data = [
        ]  # This will keep all data from query, self.source may display a subset

        self.clear_source_selection_button = Button(label='Clear Selection',
                                                    button_type='primary',
                                                    width=150)
        self.clear_source_selection_button.on_click(
            self.clear_source_selection)

        self.protocol_select = Select(value='All Data',
                                      options=['All Data', 'None'],
                                      title='Protocol:')
        self.protocol_select.on_change('value', self.protocol_ticker)
        self.update_protocol_options()

        self.display_by = RadioGroup(labels=[
            'Display by Institutional ROI', 'Display by Physician ROI'
        ],
                                     active=0)
        self.display_by.on_change('active', self.display_by_ticker)

        self.physician = Select(value='',
                                options=[''],
                                title='Physician:',
                                width=150)
        self.physician.on_change('value', self.physician_ticker)

        self.roi = Select(value='', options=[''], title='Institutional ROI:')
        self.roi.on_change('value', self.roi_ticker)

        self.mrn_input_count = 0
        self.toxicity_grade_input_count = 0

        self.mrn_input = TextAreaInput(value='',
                                       title="MRN Input:",
                                       rows=30,
                                       cols=25,
                                       max_length=2000)
        self.mrn_input.on_change('value', self.mrn_input_ticker)
        self.toxicity_grade_input = TextAreaInput(
            value='',
            title="Toxicity Grade Input:",
            rows=30,
            cols=5,
            max_length=500)
        self.toxicity_grade_input.on_change('value',
                                            self.toxicity_input_ticker)
        self.update_button = Button(label='Update',
                                    button_type='primary',
                                    width=425)
        self.update_button.on_click(self.update_toxicity_grades)
        self.update_update_button_status()

        self.columns = ['mrn', 'roi_name', 'toxicity_grade']
        relative_widths = [1, 1, 1, 1]
        column_widths = [int(250. * rw) for rw in relative_widths]
        table_columns = [
            TableColumn(field=c, title=c, width=column_widths[i])
            for i, c in enumerate(self.columns)
        ]
        table_columns.insert(
            1,
            TableColumn(field='protocol',
                        title='protocol',
                        width=column_widths[0]))
        table_columns.insert(
            1,
            TableColumn(field='physician',
                        title='physician',
                        width=column_widths[0] / 3))
        self.table = DataTable(source=self.source,
                               columns=table_columns,
                               width=800,
                               editable=True,
                               height=600)

        self.update_physicians()

        note = Div(
            text=
            '<b>NOTE</b>: MRNs input below that are not in the table to the left will be '
            'ignored on update.')

        self.layout = column(
            self.protocol_select, row(self.display_by, self.physician,
                                      self.roi),
            row(
                self.table, Spacer(width=50),
                column(note, self.update_button,
                       self.clear_source_selection_button,
                       row(self.mrn_input, self.toxicity_grade_input))))
Exemple #23
0
def plot_bokeh(title):
	global topic_names, authors
	topic_names = grab_topics(t_model, feature_names, 5)

	x_ = []
	y_ = []
	t_ = []
	o_=[]
	topic_ = []

	global source
	source = ColumnDataSource(
			data =dict(
				x=x_,
				y=y_,
				t=t_,
				o=o_,
				desc=titles,
				topics=topic_,
				auth=authors,
				year=years
				))

	#Draw plots
	update_plot()
	

	global year_from, year_to, custom_text, search_text, radio_search, search_items, Keyword_text, custom_text1

	#Year filtering controls
	year_from = Slider(title="Include papers from", value=1981, start=1981, end=2017, step=1)

	year_to = Slider(title="Inlude papers to", value=2017, start=year_from.value-1, end=2017, step=1)
	year_from.on_change('value', update_years)
	year_to.on_change('value', update_years)
	now_change = Button(label="Update", button_type="success")
	now_change.on_click(update_plot)
	

	#Custom text placement controls
	#sizing_mode = 'scale_both' -- need to look for scaling the text box size
	#sizing_mode = 'stretch_both'
	
	custom_text = TextAreaInput(value=" ", title="Enter some text you are working on here:",width=600,height=400)
	text_button = Button(label="Process", button_type="success")
	# for i in custom_text.value:
	# 	if i == '.':
	# 		process_text()

	# 	callback1 = CustomJS( code="""
	# 	    // the event that triggered the callback is cb_obj:
	# // The event type determines the relevant attributes
	# console.log('Tap event occurred at x-position: ' + cb_obj.x)
	# """)
	
	# custom_text.on_change("value", my_text_input_handler)
	# custom_text.js_on_event('tap', callback1)
	# custom_text.on_event(MouseEnter, callback1)
	text_button.on_click(process_text)
	text_button.on_click(update_table)

	custom_text1 = TextAreaInput(value=" ", title="Enter text here if you want to search for individual words or lines:",width=600,height=200)
	text_button1 = Button(label="Process", button_type="success")
	text_button1.on_click(process_text1)
	text_button1.on_click(update_table)

	template200 = """
	<div style="font-size: 15px;">
	<%= value %>
	</div>
	"""
	
	keyword_data = ColumnDataSource(data ={})
	columns =[TableColumn(field ="keywords_", title ="<b> Keyword </b>", width = 700, formatter=HTMLTemplateFormatter(template=template200))]
	# Keyword_text = TextAreaInput(value ="default",title="Keywords", width = 800, height = 100)
	Keyword_text = DataTable(source=keyword_data, columns=columns, width=800, row_height=50, editable=True, fit_columns = True)

	Keyword_text.source.selected.on_change("indices", some_func)
	






	#Search button controls
	search_text = TextInput(value="", title="Search box: (separate terms with ';' - not for DOIs)")
	search_button = Button(label="Search", button_type="success")
	search_button.on_click(process_search)
	radio_search = RadioButtonGroup(labels=["Title", "Full Text", "doi","Author"], active=1)
	print("helllllll")
	#increase size
	#txtIn_rng = widgetbox(children=[custom_text], width=wd)
	#curdoc().add_root(txtIn_rng)


	#Data Table for selected papers
	
	global table_data, chosen_papers,dict2,table_row, table_cell_column_1, value1, value2, table_cell_column_2, summary3, dict4
	template = """<span href="#" data-toggle="tooltip" title="<%= value %>" style="font-size:15px"><%= value %></span>"""
	template_str = '<a href="http://dx.doi.org/<%=dois_%>" target="_blank"><%= value %></a>'



	# output_file("openurl.html")
	table_data = ColumnDataSource(data = {})
	print("***********")
	columns = [TableColumn(field="years_", title="<b>Year</b>",width = 50, formatter=HTMLTemplateFormatter(template=template)), TableColumn(field="titles_", title="<b>Paper Title</b>", width = 200, formatter=HTMLTemplateFormatter(template=template)), TableColumn(field="authors_", title="<b>Authors</b>", width = 100, formatter=HTMLTemplateFormatter(template=template)), TableColumn(field="dois_", title="<b>Link</b>",width = 100, formatter=HTMLTemplateFormatter(template=template_str)),TableColumn(field="summary_", title="<b>Summary</b>", width =600,formatter=HTMLTemplateFormatter(template=template))]
	print("1*")
	chosen_papers = DataTable(source=table_data, columns=columns, width=600, row_height=100, editable=True, fit_columns = True)

	table_row = TextInput(value = '', title = "Row index:")
	value1 =[]
	value2 = int(0)
	value3 =[]
	dict4 =[]
	table_cell_column_1 = TextAreaInput(value = '', title = "Papers from table", height = 100)
	table_cell_column_2 = TextAreaInput(value = '', title = "Papers from graph", height = 100)
	summary3 = TextAreaInput(value = '', title = "Summary of the recently selected paper", height = 300)
	# table_cell_column_2 = TextInput(value= '', title = "Author", height = 100)

	

	
	chosen_papers.source.selected.on_change('indices', function_source)


	# Adding a title for data table
	pre = Div(text="""Please hover over each column to see the full text. </br>
By clicking on each row, the desirable papers can be added to the 'Papers from table' list below.</br>
By clicking on authors column, authors can be directly placed in search.""",
width=600, height=50, style={'font-size': '100%', 'color': 'black', 'font-weight':'bold'})

# 	pre = PreText(text="""Please hover over each column to see the full text.\n
# By clicking on each row, the desirable papers can be added to the 'Papers from table' list below.\n
# By clicking on authors column, authors can be directly placed in search""",
# 	width=500, height=100)

	# Adding title for keyword data table
	pre1 = Div(text=""" If you click on keywords, the keyword will be directly placed in the 'Search Box' """, width=500, height=20,style={'font-size': '100%', 'color': 'black', 'font-weight':'bold'})







	# chosen_papers.append(HoverTool(tooltips=[("Summary", "@summary_")]))

	# para5 = Paragraph(text = 'summary' , height = 1)

	
	#chosen_papers.source.data.update(update_table())
	# chosen_papers.source.on_change('data', update_table1)


	# global table_data1, chosen_papers1
	# template = """<span href="#" data-toggle="tooltip" title="<%= value %>"><%= value %></span>"""

	# table_data1 = ColumnDataSource(data = {})
	# print("***********")
	# columns = [TableColumn(field="summary_", title="Summary", formatter=HTMLTemplateFormatter(template=template))]
	# print("1*")
	# chosen_papers1 = DataTable(source=table_data, columns=columns, width=800, row_height=100, editable=True,fit_columns = True, scroll_to_selection = True)

	
	# df = pd.DataFrame([
	# 	['this is a longer text that needs a tooltip, because otherwise we do not see the whole text', 'this is a short text'],
	# 	['this is another loooooooooooooooong text that needs a tooltip', 'not much here'],
	# ], columns=['a', 'b'])

	# columns = [TableColumn(field=c, title=c, width=20, formatter=HTMLTemplateFormatter(template=template)) for c in ['a', 'b']]

	# table = DataTable(source=ColumnDataSource(df), columns=columns)

	




	# create a new plot with a title and axis labels
	global patch, value6, value7
	p = figure(title="CHI scatter", tools="tap", x_axis_label='x', y_axis_label='y', width=800, plot_height=850)
	p.add_tools(BoxZoomTool())
	p.add_tools(ZoomInTool())
	p.add_tools(ZoomOutTool())
	p.add_tools(ResetTool())
	p.add_tools(HoverTool(tooltips=[("Title", "@desc"), ("Topic", "@topics"), ("Authors", "@auth"), ("Year", "@year")]))

	patch = p.circle(x='x', y='y', fill_color='t', nonselection_fill_color='t', radius=0.01, fill_alpha='o', nonselection_fill_alpha='o', line_color=None, source=source)
	url = "http://dx.doi.org/@dois"
	taptool = p.select(type=TapTool)
	taptool.callback = OpenURL(url=url)

	value6 = []
	value7 = []
	patch.data_source.on_change('selected', callback)

	p.on_event(Tap, callback1)



	l = gridplot([[ row([column(row([widgetbox(year_from, year_to, now_change), widgetbox(search_text, radio_search, search_button)]),widgetbox(custom_text, text_button), widgetbox(custom_text1, text_button1),widgetbox(pre,chosen_papers))]) ,column([p,widgetbox(pre1,Keyword_text)])  ],[table_cell_column_1], [table_cell_column_2], [summary3]   ])
	curdoc().add_root(l)
Exemple #24
0
    def __init__(self, doc, refresh_rate=1000, collection=None, **kwargs):
        """Produces a widget that allows the user to add / remove plots for any
        counters from any collection

        Arguments
        ---------
        doc : Bokeh Document
            bokeh document for auto-updating the widget
        refresh_rate : int
            refresh rate at which the Select refreshes and checks for new data collections (in ms)
        **kwargs
            arguments for the bokeh Select widget
        """
        super().__init__(doc, refresh_rate=refresh_rate, collection=collection, **kwargs)

        self._defaults_opts = dict(plot_width=800, plot_height=300)
        self._defaults_opts.update((key, value) for key, value in kwargs.items())

        self._lines = {}
        self._lines_info = set()
        self._line_counter = 0

        # Buttons for editing the lines
        self._add_line_b = Button(label="+", width=40)
        self._add_line_b.on_click(self._add_line)

        # Toggle button for the shading of the plots
        self._shade_b = Toggle(label="Toggle plot shading", width=150)
        self._shade_b.on_click(self._toggle_shade)

        # Buttons for adding and removing plots
        self._add_plot_b = Button(label="+", width=40)
        self._add_plot_b.on_click(self._add_plot)

        self._remove_plot_b = Button(label="-", width=40)
        self._remove_plot_b.on_click(self._remove_plot)

        # For editing the lines
        self._edit_button = Toggle(label="Edit lines", width=100)
        self._edit_button.on_click(self._toggle_edit)

        self._json_input = TextAreaInput(
            title="Export / inport widget:", width=500, max_length=20000
        )
        self._json_update_button = Button(label="Update from input", width=150)
        self._json_update_button.on_click(self._set_from_input)

        self._save_button = Button(label="Save state of widget to session", width=170)
        self._save_button.on_click(self._save_widget)

        self._root = column(
            row(
                Div(text="Add or remove plots:"),
                self._remove_plot_b,
                self._add_plot_b,
                self._edit_button,
                self._shade_b,
                self._save_button,
            ),
            empty_placeholder(),
            empty_placeholder(),
        )

        self._plots = []
        self._add_plot()

        # If there is a saved state in the session of the widget
        json_txt = DataAggregator().get_custom_widget_config()
        if json_txt:
            self.from_json(json_txt)
Exemple #25
0
def mle():
    ###------------------------PARAMETER DEFAULTS-----------------------------###
    #  range[Lower, Upper, Step Size]
    ### - SAMPLING Parameters
    d_nsamp, r_nsamp = 500, [100, 2000, 50]  # Number of samples

    plot_data = figure(
        plot_height=400,
        plot_width=800,
        title="Data Histogram",
        toolbar_location="above",
        x_axis_label="x",
        y_axis_label="Density",
        tools="pan,save,box_zoom,wheel_zoom",
    )
    style(plot_data)

    plot_clear = Button(label="Clear All", button_type="warning")

    # Plot Control Buttons

    ctl_title = Div(text="<h3>1 - Simulator</h3>")
    dist_type = Select(
        title="Select sampling distribution:",
        value="Gaussian",
        options=["Gaussian", "Beta", "Gamma"],
    )

    div1 = Div(
        text=
        """<p style="border:3px; border-style:solid; border-color:grey; padding: 1em;">
                    Parameters depend on the distribution. Refer to Scipy Documentation. <br />  
                    - Gaussian: loc (mean), scale (variance).<br />  
                    - Gamma: a, loc, scale.<br /> 
                    - Beta: a, b, loc, scale.<br /> 
                    </p>""",
        width=300,
        height=130,
    )

    ctl_nsamp = Slider(
        title="Number of samples",
        value=d_nsamp,
        start=r_nsamp[0],
        end=r_nsamp[1],
        step=r_nsamp[2],
    )

    mu = TextInput(title="Mean", value="0.0")
    sigma = TextInput(title="Variance", value="1.0")
    a = TextInput(title="a", value="1.0")
    b = TextInput(title="b", value="1.0")

    plot_sim = Button(label="Simulate", button_type="primary")
    simulate = widgetbox(ctl_title, dist_type, div1, ctl_nsamp, mu, sigma, a,
                         b, plot_sim)

    ### MLE fitting parameters
    fit_title = Div(text="<h3>2 - Maximum Likelihood Estimation</h3>")

    dist_fit = Select(
        title="Select distribution to fit on data:",
        value="Gaussian",
        options=["Gaussian", "Beta", "Gamma"],
    )
    fit_sim = Button(label="Fit", button_type="success")
    text_output = TextAreaInput(value="", rows=4, title="Estimated Paramters:")

    fit = widgetbox(fit_title, dist_fit, fit_sim, text_output)

    ###-----------------------------------------------------------------------###
    ###-----------------------BASE-LEVEL FUNCTIONS----------------------------###

    def make_data(dist_type, params):
        # sample data according to dist_type
        data = DISTRIBUTIONS[dist_type].rvs(**params)
        return data

    ###-----------------------------------------------------------------------###
    ###------------------DATA SOURCES AND INITIALIZATION----------------------###

    source1 = ColumnDataSource(data=dict(hist=[], left=[], right=[]))
    plot_data.quad(
        source=source1,
        bottom=0,
        top="hist",
        left="left",
        right="right",
        fill_color="blue",
        line_color="white",
        alpha=0.5,
    )

    source2 = ColumnDataSource(data=dict(x=[], y=[]))
    plot_data.line(
        "x",
        "y",
        source=source2,
        line_width=2,
        alpha=0.7,
        legend="Estimated PDF",
        line_color="black",
    )

    def click_simulate():
        # Make it global to be used later
        global d_data
        # reset pdf
        source2.data = dict(x=[], y=[])
        text_output.value = ""

        if dist_type.value == "Gaussian":
            params = {
                "loc": float(mu.value),
                "scale": float(sigma.value),
                "size": int(ctl_nsamp.value),
            }

        elif dist_type.value == "Gamma":
            params = {
                "loc": float(mu.value),
                "scale": float(sigma.value),
                "a": float(a.value),
                "size": int(ctl_nsamp.value),
            }

        elif dist_type.value == "Beta":
            params = {
                "loc": float(mu.value),
                "scale": float(sigma.value),
                "a": float(a.value),
                "b": float(b.value),
                "size": int(ctl_nsamp.value),
            }

        d_data = make_data(dist_type.value, params)

        hist, edges = np.histogram(d_data, density=True, bins=100)

        source1.data = dict(hist=hist, left=edges[:-1], right=edges[1:])

        plot_data.y_range.start = 0
        plot_data.y_range.end = 1.2 * hist.max()

        plot_data.x_range.start = edges.min() - 1 * (dist_type.value != "Beta")
        plot_data.x_range.end = edges.max() + 1 * (dist_type.value != "Beta")

        plot_data.xaxis.axis_label = "x"

    plot_sim.on_click(click_simulate)

    # MLE Fit
    def fit_plot():

        dist_to_fit = DISTRIBUTIONS[dist_fit.value]
        x = np.linspace(d_data.min() - 0.5, d_data.max() + 0.5, 1000)

        estimated_params = dist_to_fit.fit(d_data)
        pdf = dist_to_fit.pdf(x, *estimated_params)

        source2.data = dict(x=x, y=pdf)
        text_output.value = str(estimated_params)

    fit_sim.on_click(fit_plot)

    # Behavior when the "Clear" button is clicked
    def clear_plot():
        source1.data = dict(hist=[], left=[], right=[])
        source2.data = dict(x=[], y=[])
        text_output.value = ""

    plot_clear.on_click(clear_plot)

    ###-----------------------------------------------------------------------###
    ###----------------------------PAGE LAYOUT--------------------------------###

    col_inputs = column(simulate)
    col_output = column(fit, plot_clear)
    col_plots = column(plot_data)
    row_page = row(col_inputs, col_plots, col_output, width=1200)

    # Make a tab with the layout
    tab = Panel(child=row_page, title="Maximum Likelihood Estimation")
    return tab
Exemple #26
0
from bokeh.io import output_file, show
from bokeh.models.widgets import TextAreaInput

output_file("text_input.html")

text_input = TextAreaInput(value="default", rows=6, title="Label:")

show(text_input)
class Toxicity:
    def __init__(self, protocol):

        self.protocol = protocol  # link to Protocol tab so we can info in the protocol tab

        self.source = ColumnDataSource(data=dict(mrn=[]))
        self.source.selected.on_change('indices', self.source_listener)
        # self.source.on_change('data', self.update_toxicity_grades_from_table)
        self.data = [
        ]  # This will keep all data from query, self.source may display a subset

        self.clear_source_selection_button = Button(label='Clear Selection',
                                                    button_type='primary',
                                                    width=150)
        self.clear_source_selection_button.on_click(
            self.clear_source_selection)

        self.protocol_select = Select(value='All Data',
                                      options=['All Data', 'None'],
                                      title='Protocol:')
        self.protocol_select.on_change('value', self.protocol_ticker)
        self.update_protocol_options()

        self.display_by = RadioGroup(labels=[
            'Display by Institutional ROI', 'Display by Physician ROI'
        ],
                                     active=0)
        self.display_by.on_change('active', self.display_by_ticker)

        self.physician = Select(value='',
                                options=[''],
                                title='Physician:',
                                width=150)
        self.physician.on_change('value', self.physician_ticker)

        self.roi = Select(value='', options=[''], title='Institutional ROI:')
        self.roi.on_change('value', self.roi_ticker)

        self.mrn_input_count = 0
        self.toxicity_grade_input_count = 0

        self.mrn_input = TextAreaInput(value='',
                                       title="MRN Input:",
                                       rows=30,
                                       cols=25,
                                       max_length=2000)
        self.mrn_input.on_change('value', self.mrn_input_ticker)
        self.toxicity_grade_input = TextAreaInput(
            value='',
            title="Toxicity Grade Input:",
            rows=30,
            cols=5,
            max_length=500)
        self.toxicity_grade_input.on_change('value',
                                            self.toxicity_input_ticker)
        self.update_button = Button(label='Update',
                                    button_type='primary',
                                    width=425)
        self.update_button.on_click(self.update_toxicity_grades)
        self.update_update_button_status()

        self.columns = ['mrn', 'roi_name', 'toxicity_grade']
        relative_widths = [1, 1, 1, 1]
        column_widths = [int(250. * rw) for rw in relative_widths]
        table_columns = [
            TableColumn(field=c, title=c, width=column_widths[i])
            for i, c in enumerate(self.columns)
        ]
        table_columns.insert(
            1,
            TableColumn(field='protocol',
                        title='protocol',
                        width=column_widths[0]))
        table_columns.insert(
            1,
            TableColumn(field='physician',
                        title='physician',
                        width=column_widths[0] / 3))
        self.table = DataTable(source=self.source,
                               columns=table_columns,
                               width=800,
                               editable=True,
                               height=600)

        self.update_physicians()

        note = Div(
            text=
            '<b>NOTE</b>: MRNs input below that are not in the table to the left will be '
            'ignored on update.')

        self.layout = column(
            self.protocol_select, row(self.display_by, self.physician,
                                      self.roi),
            row(
                self.table, Spacer(width=50),
                column(note, self.update_button,
                       self.clear_source_selection_button,
                       row(self.mrn_input, self.toxicity_grade_input))))

    def source_listener(self, attr, old, new):
        new.sort()
        mrns = [self.source.data['mrn'][x] for x in new]
        self.mrn_input.value = '\n'.join(mrns)

        toxicities = [str(self.source.data['toxicity_grade'][x]) for x in new]
        toxicities = [['NULL', t][t.isdigit()] for t in toxicities]
        self.toxicity_grade_input.value = '\n'.join(toxicities)

    def update_source(self):
        cnx = DVH_SQL()
        if self.display_by.active == 1:  # Display by Physician ROI
            uids_physician = cnx.get_unique_values(
                'Plans', 'study_instance_uid',
                "physician = '%s'" % self.physician.value)

            condition = ["physician_roi = '%s'" % self.roi.value]
            if uids_physician:
                condition.append("study_instance_uid in ('%s')" %
                                 "', '".join(uids_physician))

        else:  # Display by Institutional ROI
            condition = ["institutional_roi = '%s'" % self.roi.value]

            if self.physician.value != 'Any':
                uids_physician = cnx.get_unique_values(
                    'Plans', 'study_instance_uid',
                    "physician = '%s'" % self.physician.value)
                if uids_physician:
                    condition.append("study_instance_uid in ('%s')" %
                                     "', '".join(uids_physician))

        condition = ' AND '.join(condition)

        self.data = cnx.query('DVHs',
                              ', '.join(self.columns + ['study_instance_uid']),
                              condition,
                              bokeh_cds=True,
                              order_by='mrn')
        cnx.close()

        for col in ['protocol', 'physician']:
            self.data[col] = self.get_sql_values_based_on_source(
                'Plans', col, return_list=True)

        self.clean_toxicity_grades()

        if self.protocol_select.value == 'All Data':
            self.source.data = self.data
        else:
            self.source.data = self.get_data_filtered_by_protocol()

    def get_data_filtered_by_protocol(self):
        selected_protocol = self.protocol_select.value
        if selected_protocol == 'No Protocol':
            selected_protocol = ''
        protocols = self.get_sql_values_based_on_source('Plans', 'protocol')
        if not protocols:
            return self.data
        new_data = {key: [] for key in list(self.data)}
        for i in range(len(self.data['mrn'])):
            if (selected_protocol == 'Any Protocol' and protocols[self.data['study_instance_uid'][i]]) or \
                    (not selected_protocol and not protocols[self.data['study_instance_uid'][i]]) or\
                    (selected_protocol and selected_protocol in protocols[self.data['study_instance_uid'][i]]):
                for key in list(self.data):
                    new_data[key].append(self.data[key][i])
        return new_data

    def clean_toxicity_grades(self):
        # Replace any toxicity grade values of -1 to None. Stored in SQL as integer, but integer columns can't have NULL
        for i, value in enumerate(self.data['toxicity_grade']):
            if value == -1:
                self.data['toxicity_grade'][i] = None

    def update_protocol_options(self):
        options = ['All Data', 'Any Protocol', 'No Protocol'
                   ] + self.get_protocols()
        self.protocol_select.options = options
        if self.protocol_select.value not in options:
            self.protocol_select.value = options[0]

    def get_sql_values_based_on_source(self,
                                       sql_table,
                                       sql_column,
                                       return_list=False):
        cnx = DVH_SQL()
        uids = self.data['study_instance_uid']
        data = cnx.query(sql_table, 'study_instance_uid, %s' % sql_column,
                         "study_instance_uid in ('%s')" % "', '".join(uids))

        if data:
            return_data = {line[0]: line[1] for line in data}
            if return_list:
                return [
                    return_data[uid] for uid in self.data['study_instance_uid']
                ]
            else:
                return return_data
        return []

    def update_physicians(self):
        physicians = DVH_SQL().get_unique_values('Plans', 'physician')
        if self.display_by.active == 0:
            physicians.insert(0, 'Any')

        self.physician.options = physicians
        if self.physician.value not in physicians:
            self.physician.value = physicians[0]

    def protocol_ticker(self, attr, old, new):
        self.update_source()

    def physician_ticker(self, attr, old, new):
        self.update_source()
        self.update_rois()

    def roi_ticker(self, attr, old, new):
        self.update_source()

    def update_rois(self):
        cnx = DVH_SQL()
        if self.display_by.active == 1:  # Display by Physician ROI
            uids_physician = cnx.get_unique_values(
                'Plans', 'study_instance_uid',
                "physician = '%s'" % self.physician.value)
            condition = "study_instance_uid in ('%s')" % "', '".join(
                uids_physician)
            rois = cnx.get_unique_values('DVHs', 'physician_roi', condition)
        else:  # Display by Institutional ROI
            rois = cnx.get_unique_values('DVHs', 'institutional_roi')
        cnx.close()
        self.roi.options = rois
        if self.roi.value not in rois:
            self.roi.value = rois[0]

    def display_by_ticker(self, attr, old, new):
        self.roi.title = ['Institutional ROI:', 'Physician ROI:'][new]
        self.update_physicians()
        self.update_rois()

    @staticmethod
    def get_protocols(condition=None):
        return DVH_SQL().get_unique_values('Plans',
                                           'protocol',
                                           condition,
                                           ignore_null=True)

    def update_toxicity_grades(self):
        if self.update_button.label == 'Update':
            mrns = parse_text_area_input_to_list(self.mrn_input.value,
                                                 delimeter=None)
            toxicities = parse_text_area_input_to_list(
                self.toxicity_grade_input.value, delimeter=None)

            cnx = DVH_SQL()
            for i, mrn in enumerate(mrns):
                if mrn in self.data['mrn']:
                    index = self.data['mrn'].index(mrn)
                    uid = self.data['study_instance_uid'][index]
                    roi_name = self.data['roi_name'][index]
                    cnx.update(
                        'DVHs', 'toxicity_grade', toxicities[i],
                        "study_instance_uid = '%s' and roi_name = '%s'" %
                        (uid, roi_name))
                    update_plan_toxicity_grades(cnx, uid)
            cnx.close()
            self.update_source()

            self.clear_source_selection()
            self.toxicity_grade_input.value = ''

            self.protocol.update_source(
            )  # update the table in the Protocol tab since it has toxicity grades in it

    def mrn_input_ticker(self, attr, old, new):
        count = len(parse_text_area_input_to_list(new))
        self.mrn_input.title = "MRN Input%s:" % (
            ['', ' (count = %d)' % count][count > 0])
        self.mrn_input_count = count
        self.update_update_button_status()

    def toxicity_input_ticker(self, attr, old, new):
        toxicity_grades = parse_text_area_input_to_list(new, delimeter=None)
        count = len(toxicity_grades)
        self.toxicity_grade_input.title = "Toxicity Grade Input%s:" % (
            ['', ' (count = %d)' % count][count > 0])
        self.toxicity_grade_input_count = count
        self.update_update_button_status()

        self.validate_toxicity_grade_input(toxicity_grades)

    def update_update_button_status(self):
        if not self.mrn_input_count and not self.toxicity_grade_input_count:
            self.update_button.label = "Need data to update"
            self.update_button.button_type = 'default'

        elif self.mrn_input_count != self.toxicity_grade_input_count:
            self.update_button.label = 'Input data row count mismatch'
            self.update_button.button_type = 'default'

        else:
            self.update_button.label = 'Update'
            self.update_button.button_type = 'primary'

    def validate_toxicity_grade_input(self, toxicity_grades):

        validated_data = [['NULL', grade][grade.isdigit() and grade > -1]
                          for grade in toxicity_grades]  # remove non-int > -1
        for i, x in enumerate(validated_data):
            if x.isdigit():
                validated_data[i] = str(
                    int(x))  # clean, convert to string (removes leading zeros)

        self.toxicity_grade_input.value = '\n'.join(validated_data)

        # if 'NULL' in validated_data:
        #     label = self.update_button.label
        #     button_type = self.update_button.button_type
        #     self.update_button.label = 'Invalid grade detected. Setting to None.'
        #     self.update_button.button_type = 'danger'
        #     time.sleep(1)
        #     self.update_button.label = label
        #     self.update_button.button_type = button_type

    def clear_source_selection(self):
        self.source.selected.indices = []
Exemple #28
0
 def __init__(self, directory, ext, doc=None, log=None):
     self.options = sorted(list(find_files(directory, ext)))
     options0 = None
     if len(self.options) > 0:
         options0 = self.options[0]
     regexp_textinput = TextInput(
         title='regexp',
         height=40,
         height_policy="fixed",
         value='.*',
     )
     select = Select(
         title="Select File:",
         value=options0,
         options=self.options,
         height=40,
         height_policy="fixed",
     )
     select_button = Button(
         label='Select',
         align="end",
         button_type="success",
         width=100,
         width_policy="fixed",
         height=40,
         height_policy="fixed",
     )
     preview_button = Button(
         label='Preview',
         align="end",
         button_type="success",
         width=100,
         width_policy="fixed",
         height=40,
         height_policy="fixed",
     )
     file_preview = TextAreaInput(
         value=preview_size(options0),
         sizing_mode='stretch_both',
         max_length=16 * 2**20,
         disabled=False,
     )
     view = column(
         row(
             regexp_textinput,
             select,
             preview_button,
             select_button,
             sizing_mode='scale_width',
         ),
         file_preview,
         sizing_mode='stretch_both',
     )
     super(SelectFileViewController, self).__init__(view, doc, log)
     self.regexp_textinput = regexp_textinput
     self.regexp_textinput.on_change('value', self.regexp_changed_value)
     self.select = select
     self.select.on_change('value', self.select_changed_value)
     self.preview_button = preview_button
     self.preview_button.on_click(self.preview_button_on_click)
     self.select_button = select_button
     self.on_selected_callback = None
     self.select_button.on_click(self.select_on_click)
     self.file_preview = file_preview
Exemple #29
0
    def __init__(self, controller):
        """Initialize object safely.

        Put initialization code here that's very unlikely to fail.
        """
        self.controller = controller

        self.help = Div(
            text="""This tab displays the raw data in the system. """
                 """You can run forecasts for any election year where you """
                 """have electoral college, results, and polling data. """
                 """The cross-check button cross checks the data for """
                 """consistency.""",
            sizing_mode="""stretch_width""")

        self.datainsystemheading = Div(
            text="""<span style='font-weight:bold;font-size:14pt'>"""
                 """Data in system.</span>""",
            sizing_mode="""stretch_width""")
        # Displays the Electoral College Vote allocations by year.
        self.ecvyearallocations = TextAreaInput(
            title="""Electoral college vote allocations in system""",
            value="""No allocations in system""",
            rows=1)
        # Displays the election result years in the system.
        self.electionresults = TextAreaInput(
            title="""Presidential election results in system""",
            value="""No allocations in system""",
            rows=1)
        # Displays the Presidential polling in system.
        self.polling = TextAreaInput(
            title="""Presidential election polling in system""",
            value="""No allocations in system""",
            rows=1)
        self.crosscheckheading = Div(
            text="""<span style='font-weight:bold;font-size:14pt'>"""
                 """Cross-check data.</span>""",
            sizing_mode="""stretch_width""")
        # Header to explain what cross-check button does.
        self.headingverification = Div(
            text="""Click the button to start a cross-check that """
                 """the data in the system is both correct and consistent.""",
            width=300)
        # Starts the verification data cross-check..
        self.verificationbutton = Button(
            label="""Cross-check data.""",
            width=300,
            button_type="""success""")
        # Displays the results of the cross-check.
        self.verfificationresults = TextAreaInput(
            title="""Cross-check results""",
            value="""Cross-check verification not run.""",
            rows=6,
            width=610)

        # Layout the widgets
        self.layout = column(
            children=[row(self.help),
                      row(self.datainsystemheading),
                      row(children=[self.ecvyearallocations,
                                    self.electionresults,
                                    self.polling]),
                      row(children=[self.crosscheckheading]),
                      row(children=[self.headingverification,
                                    self.verificationbutton]),
                      row(children=[self.verfificationresults])],
            sizing_mode='scale_width')

        self.panel = Panel(child=self.layout,
                           title='Manage data')
Exemple #30
0
Yselect = Select(title="Y-axis",
                 value="Average_time_between_rental(including park time)",
                 options=CL)
#Yselect.on_change('value', my_slider_handler)

Zselect = Select(title="Color Threshold Column",
                 value="Rental_Counts",
                 options=CL)
#Zselect.on_change('value', my_slider_handler)

from bokeh.io import output_file, show
from bokeh.models.widgets import TextAreaInput

text_input = TextAreaInput(value="42",
                           rows=1,
                           title="Random State (For repeatable sampling):")
#text_input.on_change('value', my_slider_handler)

#TOOLTIP=[('threshold', '@thr'),('Customer_id', '@cid')]

#TOOLTIP=[(name_cols,'@{'+name_cols+'}') for name_cols in display_columns]
#TOOLTIP = [TOOLTIP[0]]

from bokeh.models import HoverTool
TOOLTIP = HoverTool()
TOOLTIP_list = [
    '<b style="color:MediumSeaGreen;">' + name_cols + ':' + '</b><b>' + ' @{' +
    name_cols + '}</b>' for name_cols in display_columns
]
#TOOLTIP=[(name_cols,'@{'+name_cols+'}') for name_cols in display_columns]