예제 #1
0
    def new_upload_button(self,
                          save_path,
                          callback,
                          name="Eigenfaces/static/tmp.jpg",
                          label="Upload your photo! (.jpg, 92x112)"):
        def file_callback(attr, old, new):
            raw_contents = source.data['contents'][0]
            # remove the prefix that JS adds
            prefix, b64_contents = raw_contents.split(",", 1)
            file_contents = base64.b64decode(b64_contents)
            fname = join(save_path, name)

            with open(fname, "wb") as f:
                print(fname)
                f.write(file_contents)

            logging.info("Success: file uploaded " + fname)
            callback(fname)

        source = ColumnDataSource({'contents': [], 'name': []})
        source.on_change('data', file_callback)
        button = Button(label=label, button_type="success")
        button.callback = CustomJS(args=dict(source=source),
                                   code=self._upload_js)
        return button
예제 #2
0
def recommendopposite(R, title, plot):
    '''
    recommendoppostie- Take vector of distances from current point and vector of titles and append 'recommend alternative' hyperlink button to the ploting canavas.
    
    Returns
    -------
    grid: bokeh.layouts.grid_plot
        Spatial arrangement of glyphs on canvas.
    '''

    # Select title of the most distant datapoint
    maxR_id = np.argmax(R)
    title_opp = title[maxR_id]
    recomm = "Try reading something allternative:\n {}".format(title_opp[0])
    # Create Search URL
    base_url = "http://www.google.com/?#q="
    final_url = base_url + quote(title_opp[0])

    button = Button(label=recomm, button_type="primary")
    # available button_types = default, primary, success, warning, danger, link
    # Define event on callback
    code = """
    url = source.data['url']
    window.open(url, "_self")
    """
    source = ColumnDataSource(data=dict(url=[final_url]))
    callback = CustomJS(args=dict(source=source), code=code)
    button.callback = callback

    wdgtbox = widgetbox(button)

    # grid = gridplot([[plot],[wdgtbox]],toolbar_location='above', responsive = True, lnt = 1)
    grid = gridplot([[plot], [wdgtbox]])

    return grid
예제 #3
0
def update_annotation_exact(attr, old, new):
    # This function probablby needs a rewrite if too slow. if not new is an empty search box, else has input text
    if not new:
        # Display table header as PreText
        information_1 = "Showing {} of {} annotated genes total".format(maxindeces-1, totalrows)
        annotation_information_1 = PreText(text=information_1)
        funclayout.children[1] = annotation_information_1
        # Reset table to original
        annotation = ColumnDataSource(data=df.head(n=maxindeces))
        csv_download = ColumnDataSource(data=df)
        columns = [TableColumn(field=str(key), title=str(key)) for key in list(df)]
        annotation_table = DataTable(source=annotation, columns=columns, width=1800)
        funclayout.children[2] = annotation_table
        # Redo buttons to original
        funcbutton1 = Button(label="Download annotation (tsv)", button_type="primary")
        funcbutton1.callback = CustomJS(args=dict(source=csv_download.data),code=open(join(dirname(__file__), "download_tsv.js")).read())
        funcbutton2 = Button(label="Download sequences (Nuc, fasta)", button_type="success", disabled=True)
        funcbutton3 = Button(label="Download sequences (Prot, fasta)", button_type="success")
        funcbutton3.callback = CustomJS(args=dict(source=csv_download.data, seqs=seqs),code=open(join(dirname(__file__), "download_protseq.js")).read())
        funcbuttons = row(funcbutton1, funcbutton2, funcbutton3)
        funclayout.children[3] = funcbuttons

    else:
        # Display "Searching while searching"
        annotation_information_1 = PreText(text="Searching...(expect atleast 5 second search time pr. 10000 annotated genes)")
        funclayout.children[1] = annotation_information_1
        # Use template df pandas to search and create new pandas with search results
        current = df.where(df.apply(lambda row: row.astype(str).str.contains(new, case=False).any(), axis=1, result_type='broadcast')).dropna(how='all')
        hitcount= len(current)
        annotation = ColumnDataSource(data=current.head(n=maxindeces))
        csv_download = ColumnDataSource(data=current)
        columns = [TableColumn(field=str(key), title=str(key)) for key in list(current)]
        annotation_table = DataTable(source=annotation, columns=columns, width=1800)
        funclayout.children[2] = annotation_table
        # Display hit information
        tablecount = len(current.head(n=maxindeces))
        information_1 = "Showing {} of {} hits of {} annotated genes total".format(tablecount, hitcount,totalrows)
        annotation_information_1 = PreText(text=information_1)
        funclayout.children[1] = annotation_information_1
        # Change buttons
        funcbutton1 = Button(label="Download annotation of current hits (tsv)", button_type="primary")
        funcbutton1.callback = CustomJS(args=dict(source=csv_download.data),code=open(join(dirname(__file__), "download_tsv.js")).read())
        funcbutton2 = Button(label="Download sequences of current hits (Nuc, fasta)", button_type="success", disabled=True)
        funcbutton3 = Button(label="Download sequences of current hits (Prot, fasta)", button_type="success")
        funcbutton3.callback = CustomJS(args=dict(source=csv_download.data, seqs=seqs),code=open(join(dirname(__file__), "download_protseq.js")).read())
        funcbuttons = row(funcbutton1, funcbutton2, funcbutton3)
        funclayout.children[3] = funcbuttons
예제 #4
0
    def set_button(source, path):
        button = Button(label="Download", button_type="success")
        button.callback = CustomJS(args=dict(source=source),
                                   code=open(
                                       os.path.join(os.path.abspath('../../'),
                                                    path)).read())

        return button
    def set_button(source, path):
        root = os.path.abspath(os.sep)
        download_path = os.path.join(root, 'app/templates/download.js')

        button = Button(label="Download", button_type="success")
        button.callback = CustomJS(args=dict(source=source),
                                   code=open(download_path).read())

        return button
예제 #6
0
def button_print_page():
    """Button to print currently displayed webpage to paper or pdf.

    Notes
    -----
    * Available styles: 'default', 'primary', 'success', 'warning', 'danger'
    """
    button = Button(label="Print this page", button_type="success")
    button.callback = CustomJS(code="""print()""")
    return widgetbox(button)
예제 #7
0
def button_print_page():
    """Button to print currently displayed webpage to paper or pdf.

    Notes
    -----
    * Available styles: 'default', 'primary', 'success', 'warning', 'danger'
    """
    button = Button(label="Print this page", button_type="success")
    button.callback = CustomJS(code="""print()""")
    return widgetbox(button)
예제 #8
0
def button_save_table(table):
    """Button to save selected data table as csv.

    Notes
    -----
    * Does not work for column values containing tuples (like 'neighbors')
    * Currently columns being saved are hard coded in the javascript callback
    * Available styles: 'default', 'primary', 'success', 'warning', 'danger'
    """
    button = Button(label="Download selected data", button_type="success")
    button.callback = CustomJS(args=dict(source=table.source),
                               code=open(join(dirname(__file__),
                                              "js/download_data.js")).read())
    return widgetbox(button)
def new_upload_button(save_path, callback, label="Upload Data File"):
    def file_callback(attr, old, new):
        raw_contents = source.data['contents'][0]
        file_name = source.data['name'][0]
        # remove the prefix that JS adds
        prefix, b64_contents = raw_contents.split(",", 1)
        file_contents = base64.b64decode(b64_contents)
        callback(file_name, file_contents)

    source = ColumnDataSource({'contents': [], 'name': []})
    source.on_change('data', file_callback)

    button = Button(label=label, button_type="success")
    button.callback = CustomJS(args=dict(source=source), code=_upload_js)
    return button, source
예제 #10
0
def button_save_table(table):
    """Button to save selected data table as csv.

    Notes
    -----
    * Does not work for column values containing tuples (like 'neighbors')
    * Currently columns being saved are hard coded in the javascript callback
    * Available styles: 'default', 'primary', 'success', 'warning', 'danger'
    """
    button = Button(label="Download selected data", button_type="success")
    button.callback = CustomJS(args=dict(source=table.source),
                               code=open(
                                   join(dirname(__file__),
                                        "js/download_data.js")).read())
    return widgetbox(button)
예제 #11
0
def make_table():
    if __name__ == '__main__':
        df = pd.read_csv('salary_data.csv')
    else:
        #    df = pd.read_csv('./bokeh_pages/salary_data.csv')
        df = pd.read_csv('salary_data.csv')

    source = ColumnDataSource(data=dict())

    def update():
        current = df[df['salary'] <= slider.value].dropna()
        source.data = {
            'name': current.name,
            'salary': current.salary,
            'years_experience': current.years_experience,
        }

    slider = Slider(title="Max Salary",
                    start=10000,
                    end=250000,
                    value=150000,
                    step=1000)
    slider.on_change('value', lambda attr, old, new: update())

    button = Button(label="Download", button_type="success")
    button.callback = CustomJS(args=dict(source=source),
                               code=open(join(dirname(__file__),
                                              "download.js")).read())

    columns = [
        TableColumn(field="name", title="Employee Name"),
        TableColumn(field="salary",
                    title="Income",
                    formatter=NumberFormatter(format="$0,0.00")),
        TableColumn(field="years_experience", title="Experience (years)")
    ]

    data_table = DataTable(source=source, columns=columns, width=800)

    controls = widgetbox(slider, button)
    table = widgetbox(data_table)

    curdoc().add_root(row(controls, table))
    curdoc().title = "Export CSV"

    update()
예제 #12
0
    def create_button(self):

        s_java_script = """
						function table_to_csv(source) {
						    const columns = Object.keys(source.data)
						    const nrows = source.get_length()
						    const lines = [columns.join(',')]

						    for (let i = 0; i < nrows; i++) {
						        let row = [];
						        for (let j = 0; j < columns.length; j++) {
						            const column = columns[j]
						            row.push(source.data[column][i].toString())
						        }
						        lines.push(row.join(','))
						    }
						    return lines.join('\\n').concat('\\n')
						}


						const filename = 'XXXXXX'
						filetext = table_to_csv(source)
						const blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' })

						//addresses IE
						if (navigator.msSaveBlob) {
						    navigator.msSaveBlob(blob, filename)
						} else {
						    const link = document.createElement('a')
						    link.href = URL.createObjectURL(blob)
						    link.download = filename
						    link.target = '_blank'
						    link.style.visibility = 'hidden'
						    link.dispatchEvent(new MouseEvent('click'))
						}
		"""

        s_java_script = s_java_script.replace('XXXXXX', self.s_file_name)

        source = ColumnDataSource(self.df_data)
        o_btn = Button(label=self.s_btn_label, button_type="success")
        o_btn.callback = CustomJS(args=dict(source=source), code=s_java_script)
        # o_btn.js_on_click(CustomJS(args = dict(source = source), code = s_java_script))

        return o_btn
예제 #13
0
def interactive_CMD(specs,cid1='g_SDSS',cid2='i_SDSS'):
    '''
    Simplistic tool to create an interactive
    bokeh plot where outliers can be marked and saved in
    '/home/ekaterina/Documents/appaloosa/stars_shortlist/share/temp'
    '''
    # Create some random data and put it into a ColumnDataSource
    s = specs.set_index('EPIC')
    s = s[[cid1, cid2, 'e_'+cid1,'e_'+cid2]].dropna(how='any')
    x = list(s[cid1]-s[cid2])
    y = list(s[cid2])
    size = list(np.sqrt(s['e_'+cid1]**2+s['e_'+cid2]**2)*100.)
    z = list(s.index.values)
    source_data = ColumnDataSource(data=dict(x=x, y=y,desc=z))

    # Create a button that saves the coordinates of selected data points to a file
    savebutton = Button(label="Save", button_type="success")
    savebutton.callback = CustomJS(args=dict(source_data=source_data), code="""
            var inds = source_data.selected['1d'].indices;
            var data = source_data.data;
            var out = "";
            for (i = 0; i < inds.length; i++) {
                out += data['desc'][inds[i]] + " ";
            }
            var file = new Blob([out], {type: 'text/plain'});
            var elem = window.document.createElement('a');
            elem.href = window.URL.createObjectURL(file);
            elem.download = 'selected-data.txt';
            document.body.appendChild(elem);
            elem.click();
            document.body.removeChild(elem);
            """)

    # Plot the data and save the html file
    p = figure(plot_width=800, plot_height=400,
               #y_range=(20,7),
               tools="lasso_select, reset, hover",)
    p.circle(x='x', y='y',  source=source_data, fill_alpha=0.8)#add size='desc' to visualize uncertainties on mag
    p.xaxis.axis_label = '{}-{}'.format(cid1,cid2)
    p.yaxis.axis_label = cid1
    plot = Column(p, savebutton)
    output_file("test.html")
    show(plot)
    return
예제 #14
0
def displayResultTable(sortedKeys, dictionnary, name):
    #display a table in
    source = ColumnDataSource(dictionnary)

    columns = [
        TableColumn(field=key, title=key)
        for key in sortedKeys
    ]

    area = DataTable(source=source, columns=columns, width=600, height=800)
    button = Button(label="Download", button_type="success")
    button.callback = CustomJS(args=dict(source=source),
                           code=open(join(dirname(__file__), "download.js")).read())

    controls=widgetbox(button)

    output_file(name+".html", title=name)

    save(row(area,controls))
예제 #15
0
def button2csv():
    button = Button(label="Download", button_type="success")

    javaScript = """
    function table_to_csv(source) {
        const columns = Object.keys(source.data)
        const nrows = source.get_length()
        const lines = [columns.join(',')]

        for (let i = 0; i < nrows; i++) {
            let row = [];
            for (let j = 0; j < columns.length; j++) {
                const column = columns[j]
                row.push(source.data[column][i].toString())
            }
            lines.push(row.join(','))
        }
        return lines.join('\\n').concat('\\n')
    }


    const filename = 'data_result.csv'
    filetext = table_to_csv(source)
    const blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' })

    //addresses IE
    if (navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, filename)
    } else {
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = filename
        link.target = '_blank'
        link.style.visibility = 'hidden'
        link.dispatchEvent(new MouseEvent('click'))
    }
    """

    button.callback = CustomJS(args=dict(source=source), code=javaScript)
    show(button)
예제 #16
0
    def createUploadFileButton(self):
        self.file_source.on_change('data', self.file_callback)
        button = Button(label="Upload", button_type="success", name=str(uuid.uuid1()))
        button.on_click(partial(self.disableButton, button=button))
        #button.on_click(lambda: self.uploadFile(file_source=self.file_source, button=button))
        button.callback = CustomJS(args=dict(file_source=self.file_source), code="""
                                                  function read_file(filename) {
                                                      var reader = new FileReader();
                                                      reader.onload = load_handler;
                                                      reader.onerror = error_handler;
                                                      // readAsDataURL represents the file's data as a base64 encoded string
                                                      reader.readAsDataURL(filename);
                                                  }

                                                  function load_handler(event) {
                                                      var b64string = event.target.result;
                                                      file_source.data = {'file_contents' : [b64string], 'file_name':[input.files[0].name]};
                                                      file_source.trigger("change");
                                                  }

                                                  function error_handler(evt) {
                                                      if(evt.target.error.name == "NotReadableError") {
                                                          alert("Can't read file!");
                                                      }
                                                  }

                                                  var input = document.createElement('input');
                                                  input.setAttribute('type', 'file');
                                                  input.onchange = function(){
                                                      if (window.FileReader) {
                                                          read_file(input.files[0]);
                                                      } else {
                                                          alert('FileReader is not supported in this browser');
                                                      }
                                                  }
                                                  input.click();
                                                  """)
        return row(button)
예제 #17
0
    def _set_button(self, specs):
        button = Button()
        # button = figure()
        # button = figure(plot_width=400, plot_height=400,
        #            tools="tap", title="Click the Dots")
        #
        # source = ColumnDataSource(data=dict(
        #     x=[1, 2, 3, 4, 5],
        #     y=[2, 5, 8, 2, 7],
        #     color=["navy", "orange", "olive", "firebrick", "gold"]
        # ))
        #
        # button.circle('x', 'y', color='color', size=20, source=source)
        #
        # url = _convert_url_to_bokeh("mast_folder/mast.html")
        # taptool = button.select(type=TapTool)
        # taptool.callback = OpenURL(url=url)

        button.label = specs.text
        button.width = specs.width
        button.height = specs.height
        button.name = _convert_url_to_bokeh("mast_folder/mast.html")
        button.callback = self.widget_callback()
        return button
예제 #18
0
source = ColumnDataSource(data=dict())

def update():
    current = df[(df['salary'] >= slider.value[0]) & (df['salary'] <= slider.value[1])].dropna()
    source.data = {
        'name'             : current.name,
        'salary'           : current.salary,
        'years_experience' : current.years_experience,
    }

slider = RangeSlider(title="Max Salary", start=10000, end=110000, value=(10000, 50000), step=1000, format="0,0")
slider.on_change('value', lambda attr, old, new: update())

button = Button(label="Download", button_type="success")
button.callback = CustomJS(args=dict(source=source),
                           code=open(join(dirname(__file__), "download.js")).read())

columns = [
    TableColumn(field="name", title="Employee Name"),
    TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")),
    TableColumn(field="years_experience", title="Experience (years)")
]

data_table = DataTable(source=source, columns=columns, width=800)

controls = widgetbox(slider, button)
table = widgetbox(data_table)

curdoc().add_root(row(controls, table))
curdoc().title = "Export CSV"
예제 #19
0
                  step=10,
                  callback=callback)

callback.args["mej"] = M_slider
callback.args["vej"] = v_slider
callback.args["k"] = k_slider
callback.args["nindex"] = n_slider
callback.args["rhoo"] = rho_slider
callback.args["r0o"] = r0_slider
callback.args["t00"] = T_slider

button.callback = CustomJS(args=dict(source=source,
                                     vej=v_slider,
                                     name_v=text,
                                     mej=M_slider,
                                     myk=k_slider,
                                     myt0=T_slider,
                                     myn=n_slider,
                                     myrho=rho_slider,
                                     myr0=r0_slider),
                           code=javaScript)

callback2.args["SNName"] = text

text.on_change('value', update_title)

# Set up layouts and add to document
inputs = widgetbox(text, M_slider, v_slider, k_slider, n_slider, r0_slider,
                   rho_slider, T_slider)
layout = row(plot, column(inputs, button))

output_file("CSM.html")
예제 #20
0
from bokeh.layouts import column, row
from bokeh.plotting import show, output_file
from bokeh.models.callbacks import CustomJS

USER = "******"
PASSWD = "Bok3h"

text = PreText(text="LOGIN TO KNOW\nTHE SECRET:")
user = TextInput(placeholder="username", title="(UserName: "******")")
pwd = PasswordInput(placeholder="password", title="(Password: "******")")
btn = Button(label="GO!", width=150)

secret = PreText()  # Secret information displayed if correct password entered

## Verify if the password typed is bokeh using a JS script
verify_pwd = CustomJS(args=dict(user=user, pwd=pwd, secret=secret),
                      code="""
    secret.text = 'Wrong Password.';
    if (user.value == %r && pwd.value == %r) {
        secret.text = 'Right Password. The Secret is 42.';
    }
""" % (USER, PASSWD))

#user.callback = verify_pwd # Check password pressing enter.
pwd.callback = verify_pwd  # Check password pressing enter.
btn.callback = verify_pwd  # Check password clicking on the Button.

output_file("using_password_input.html", title="Password Field")
page = row(column(text, user, pwd, btn), secret)
show(page)
예제 #21
0
    p.x_range.end = x_minmax[1] + (x_minmax[1] - x_minmax[0] + 1) / 20
    p.y_range.start = y_minmax[0] - (y_minmax[1] - y_minmax[0] + 1) / 20
    p.y_range.end = y_minmax[1] + (y_minmax[1] - y_minmax[0] + 1) / 20


# Maintain current axes ranges upon reset
p.on_event('reset', readjust_axes)

# Add callbacks to the 3 widgets manually created back at the start
x_field.on_change('value', lambda a, r, g: update())
y_field.on_change('value', lambda a, r, g: update())
hide_null.on_click(lambda arg: update())

download_button = Button(label="Download", button_type="success")
download_button.callback = CustomJS(args=dict(source=source),
                                    code=open(
                                        join(dirname(__file__),
                                             "js/csv_download_all.js")).read())

download_selected_button = Button(label="Download Selected",
                                  button_type="success")
download_selected_button.callback = CustomJS(
    args=dict(source=source),
    code=open(join(dirname(__file__), "js/csv_download_selected.js")).read())

widgets.extend((download_button, download_selected_button))

# Add all models and widgets to the document
box = widgetbox(*widgets, sizing_mode='stretch_both')
fig = column(row(box, p), table, sizing_mode='scale_width')
update()  # initial update
curdoc().add_root(fig)
예제 #22
0
def selection_plot(response):
    # Let's move these into a settings file somewhere?
    # height/width could potentially be driven by the request?


    # Include color data in the ColumnDataSource to allow for changing the color on
    # the client side.
    urls = [x[0] for x in response["pages"]]
    xdata = [x[1] for x in response["pages"]]
    ydata = [x[2] for x in response["pages"]]
    tags = [x[3] for x in response["pages"]]
    color = [colormap(x[0]) if x else colormap(None) for x in tags]

    source = ColumnDataSource(
        data=dict(
            x=xdata,
            y=ydata,
            urls=urls,
            tags=tags,
            color=color,
        )
    )
    # Callback code for CDS.
    source.callback = CustomJS(code="""
        var inds = cb_obj.get('selected')["1d"].indices;
        var data = cb_obj.get('data');
        BokehPlots.showPages(inds);
    """)


    # Create the figure with FIGURE_WIDTH and FIGURE_HEIGHT
    p = figure(tools="hover", width=FIGURE_WIDTH,
            toolbar_location=None, responsive=True, tags=["clusterPlot"])

    # Ensure that the lasso only selects with mouseup, not mousemove.
    p.add_tools(LassoSelectTool(select_every_mousemove=False))

    # These turn off the x/y axis ticks
    p.axis.visible = None

    # These turn the major grid off
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Plot non-selected circles with a particular style using CIRCLE_SIZE and
    # 'color' list
    p.circle("x", "y", size=13, line_width=2, line_alpha=1,
            line_color=None, fill_alpha=1, color='color', source=source,
            name="urls")
    nonselected_circle = Circle(fill_alpha=0.1, line_alpha=0.1, fill_color='color',
            line_color='color')
    renderer = p.select(name="urls")
    renderer.nonselection_glyph = nonselected_circle


    # Create buttons and their callbacks, use button_code string for callbacks.
    button_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        tag = "%s";
        for(var i = 0; i < inds.length; i++){
            selected.push({
                x: data.x[inds[i]],
                y: data.y[inds[i]],
                url: data.urls[inds[i]],
                tags: data.tags[inds[i]],
                selected: true,
                possible: false,
            });
            data["color"][inds[i]] = "%s";
        }
        BokehPlots.updateTags(selected, tag, inds);
        source.trigger("change");
    """

    # Supply color with print formatting.
    button1 = Button(label="Relevant", type="success")
    button1.callback = CustomJS(args=dict(source=source),
            code=button_code % ("Relevant", POSITIVE_COLOR))

    button2 = Button(label="Irrelevant", type="success")
    button2.callback = CustomJS(args=dict(source=source),
            code=button_code % ("Irrelevant", NEGATIVE_COLOR))

    button3 = Button(label="Neutral", type="success")
    button3.callback = CustomJS(args=dict(source=source),
            code=button_code % ("Neutral", NEUTRAL_COLOR))


    # Adjust what attributes are displayed by the HoverTool
    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [
        ("urls", "@urls"),
    ]
    layout = vform(p, button1, button2, button3)

    # Combine script and div into a single string.
    plot_code = components(layout)
    return plot_code[0] + plot_code[1]
예제 #23
0
def load_page(experiment_df, experiment_db):

    ########## bokeh plots ##########

    # general plot tools
    plot_tools = 'wheel_zoom, pan, reset, save, hover'
    hover = HoverTool(tooltips=[("(x,y)", "($x, $y)")])

    # progress curve plots
    global raw_source
    raw_source = ColumnDataSource(data=dict(x=[], y=[], yr=[], yfit=[]))
    global raw
    raw = figure(title="Initial Rate Fit",
                 x_axis_label="Time",
                 y_axis_label="Signal",
                 plot_width=350,
                 plot_height=300,
                 tools=plot_tools)
    raw.circle('x',
               'y',
               size=2,
               source=raw_source,
               color='gray',
               selection_color="black",
               alpha=0.6,
               nonselection_alpha=0.2,
               selection_alpha=0.6)
    raw.line('x', 'yfit', source=raw_source, color='red')
    global warning_source
    warning_source = ColumnDataSource(data=dict(
        x=[0],
        y=[0],
        t=[
            'Please enter transform equation! \nMust convert signal to [substrate] \nin Schnell-Mendoza mode (e.g. via \nx/6.22/0.45/0.001 for sample data). \nNote: this transform may need \nto be inverted through multiplying \nby -1 when analyzing experiments \nthat measure increasing product \nconcentration over time)'
        ]))
    global warning
    warning = raw.text(x='x',
                       y='y',
                       text='t',
                       text_font_size='12pt',
                       angle=0,
                       source=warning_source)
    warning.visible = False
    global circles_source
    circles_source = ColumnDataSource(
        data=dict(x=[-.05, -.05, 1.6, 1.6], y=[0, 0.6, 0, 0.6]))
    global circles
    circles = raw.circle(x='x', y='y', alpha=0., source=circles_source)
    circles.visible = False
    global resi
    resi = figure(title="Initial Rate Fit Residuals",
                  x_axis_label="Time",
                  y_axis_label="Residual",
                  plot_width=700,
                  plot_height=200,
                  tools='wheel_zoom,pan,reset')
    resi.yaxis.formatter = BasicTickFormatter(precision=2, use_scientific=True)
    resi.circle('x', 'yr', size=5, source=raw_source, color='grey', alpha=0.6)

    # model plot for titration experiments
    global model_data_source
    model_data_source = ColumnDataSource(
        data=dict(xt=[], yt=[], n=[], ct=[], et=[]))
    global model_plot_source
    model_plot_source = ColumnDataSource(
        data=dict(xp=[], yp=[], l=[], u=[], cp=[], ep=[]))
    global model_fit_source
    model_fit_source = ColumnDataSource(data=dict(x=[], y=[]))
    global varea_source
    varea_source = ColumnDataSource(data=dict(x=[], r1=[], r2=[]))
    global model
    model = figure(title='Model Fit',
                   x_axis_label='Concentration',
                   y_axis_label='Rate',
                   plot_width=350,
                   plot_height=300,
                   tools=plot_tools)
    model.circle('xp',
                 'yp',
                 size=8,
                 source=model_plot_source,
                 color='cp',
                 alpha=0.6)
    model.add_layout(
        Whisker(source=model_plot_source, base='xp', upper='u', lower='l'))
    model.line('x',
               'y',
               source=model_fit_source,
               line_width=3,
               color='black',
               alpha=0.8)
    model.varea('x', 'r1', 'r2', source=varea_source, color='grey', alpha=0.3)

    ########## bokeh widgets ##########

    # button for selecting progress curve fitting routine
    global fit_button
    fit_button = RadioButtonGroup(labels=[
        'Maximize Slope Magnitude', 'Linear Fit', 'Logarithmic Fit',
        'Schnell-Mendoza'
    ],
                                  active=0,
                                  width=375)
    fit_button.on_change('active', widget_callback)

    # button for selecting progress curve fitting routine
    global scalex_box
    scalex_box = CheckboxButtonGroup(
        labels=["transform x-axis to Log10 scale"], active=[])
    scalex_box.on_change('active', widget_callback)

    # dropdown menu for selecting titration experiment model
    global model_select
    model_select = Select(
        title='Choose Model',
        value='Michaelis-Menten',
        options=['Michaelis-Menten', 'pEC50/pIC50', 'High-Throughput Screen'],
        width=350)
    model_select.on_change('value', widget_callback)

    # dropdown menu for selecting blank sample to subtract from remaining titration samples
    global subtract_select
    subtract_select = Select(title='Select Blank Sample for Subtraction',
                             value='',
                             options=list(experiment_df)[1:] + [''],
                             width=350)
    subtract_select.on_change('value', widget_callback)

    # dropdown menu for selecting titration sample to plot in current view
    global sample_select
    sample_select = Select(title='Y Axis Sample',
                           value=list(experiment_df)[-1],
                           options=list(experiment_df)[1:],
                           width=350)
    sample_select.on_change('value', sample_callback)

    # text input box for transforming slopes to rates
    global transform_input
    transform_input = TextInput(value='',
                                title="Enter Transform Equation",
                                width=350)
    transform_input.on_change('value', widget_callback)

    # text input box for setting delay time in logarithmic progress curve fitting
    global offset_input
    offset_input = TextInput(value='',
                             title="Enter Time Between Mixing and First Read",
                             width=350)
    offset_input.on_change('value', widget_callback)

    # text input boxes for fixing EC/IC50 parameters
    global bottom_fix
    bottom_fix = TextInput(value='', title="Fix pIC50/pEC50 Bottom")
    bottom_fix.on_change('value', widget_callback)

    global top_fix
    top_fix = TextInput(value='', title="Fix pIC50/pEC50 Top")
    top_fix.on_change('value', widget_callback)

    global slope_fix
    slope_fix = TextInput(value='', title="Fix pIC50/pEC50 Hill Slope")
    slope_fix.on_change('value', widget_callback)

    # text input boxes for progress curve xrange selection
    global start_time
    start_time = TextInput(value=str(
        experiment_df[list(experiment_df)[0]].values[0]),
                           title="Enter Start Time")
    global end_time
    end_time = TextInput(value=str(
        experiment_df[list(experiment_df)[0]].values[-1]),
                         title='Enter End Time')
    start_time.on_change('value', xbox_callback)
    end_time.on_change('value', xbox_callback)

    # range slider to select threshold for hit detection in HTS mode
    global threshold_slider
    threshold_slider = Slider(start=0,
                              end=5,
                              value=2,
                              step=0.1,
                              title='HTS Hit Threshold (Standard Deviation)',
                              width=350)
    threshold_slider.on_change('value', threshold_callback)

    # range slider to update plots according to progress cuve xrange selection
    xmin = experiment_df[experiment_df.columns[0]].values[0]
    xmax = experiment_df[experiment_df.columns[0]].values[-1]
    global range_slider
    range_slider = RangeSlider(
        start=xmin,
        end=xmax,
        value=(xmin, xmax),
        step=experiment_df[experiment_df.columns[0]].values[1] - xmin,
        title='Fine Tune X-Axis Range',
        width=650)
    range_slider.on_change('value', slider_callback)

    # button to upload local data file
    global file_source
    file_source = ColumnDataSource(data=dict(file_contents=[], file_name=[]))
    file_source.on_change('data', file_callback)
    try:
        output_filename = file_source.data['file_name'] + '-out.csv'
    except:
        output_filename = 'output.csv'
    global upload_button
    upload_button = Button(label="Upload Local File",
                           button_type="success",
                           width=350)
    upload_button.callback = CustomJS(args=dict(file_source=file_source),
                                      code=open(
                                          join(dirname(__file__),
                                               "upload.js")).read())

    # table containing rate fits and errors
    template = """
    <div style="background:<%=ct%>"; color="white";>
    <%= value %></div>
    """
    formatter = HTMLTemplateFormatter(template=template)
    columns = [
        TableColumn(field='n', title='Sample'),
        TableColumn(field='yt',
                    title='Slope (Initial Rate)',
                    formatter=formatter),
        TableColumn(field='et', title='Std. Error')
    ]
    global rate_table
    rate_table = DataTable(source=model_data_source,
                           columns=columns,
                           width=350,
                           height=250,
                           selectable=True,
                           editable=True)

    # tables containing model fits and errors
    global mm_source
    mm_source = ColumnDataSource(dict(label=[], Km=[], Vmax=[]))
    columns = [
        TableColumn(field='label', title=''),
        TableColumn(field='Vmax', title='Vmax'),
        TableColumn(field='Km', title='Km')
    ]
    global mm_table
    mm_table = DataTable(source=mm_source,
                         columns=columns,
                         width=350,
                         height=75,
                         selectable=True,
                         editable=True)
    global ic_source
    ic_source = ColumnDataSource(
        dict(label=[], Bottom=[], Top=[], Slope=[], p50=[]))
    columns = [
        TableColumn(field='label', title=''),
        TableColumn(field='Bottom', title='Bottom'),
        TableColumn(field='Top', title='Top'),
        TableColumn(field='Slope', title='Slope'),
        TableColumn(field='p50', title='pEC/IC50')
    ]
    global ic_table
    ic_table = DataTable(source=ic_source,
                         columns=columns,
                         width=350,
                         height=75,
                         selectable=True,
                         editable=True)

    # button for copying rate data table to clipboard
    global copy_button
    copy_button = Button(label="Copy Table to Clipboard",
                         button_type="primary",
                         width=350)
    copy_button.callback = CustomJS(args=dict(source=model_data_source),
                                    code=open(
                                        join(dirname(__file__),
                                             "copy.js")).read())

    # button for downloading rate data table to local csv file
    global download_button
    download_button = Button(label="Download Table to CSV",
                             button_type="primary",
                             width=350)
    download_button.callback = CustomJS(args=dict(source=model_data_source,
                                                  file_name=output_filename),
                                        code=open(
                                            join(dirname(__file__),
                                                 "download.js")).read())

    ########## document formatting #########

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

    advanced = Div(
        text="""<strong>Advanced Settings for \npEC/IC50 Analysis</strong>""")

    widgets = widgetbox(model_select, sample_select, subtract_select,
                        transform_input, offset_input, advanced, scalex_box,
                        bottom_fix, top_fix, slope_fix)
    table = widgetbox(rate_table)
    main_row = row(
        column(upload_button, widgets),
        column(fit_button, row(raw, model), resi, row(start_time, end_time),
               range_slider),
        column(download_button, copy_button, table, mm_table, ic_table,
               threshold_slider))

    sizing_mode = 'scale_width'
    l = layout([[desc], [main_row]], sizing_mode=sizing_mode)

    update()
    curdoc().clear()
    curdoc().add_root(l)
    curdoc().title = "ICEKAT"
예제 #24
0
         source=source)

formatter = HTMLTemplateFormatter(template="<div><%= value %></div>")
table_source = ColumnDataSource(data=table_data)
columns = [TableColumn(field='IMGS', title='Structure', width=300, formatter=formatter),
           TableColumn(field='SMILES', title='SMILES', width=300, editor=StringEditor())] + \
          [TableColumn(field=prop, title=prop, width=150) for prop in properties.keys()]
table = HighTable(source=table_source,
                  columns=columns,
                  editable=True,
                  width=1200,
                  height=1200)

button = Button(label="Download", button_type="warning")
button.callback = CustomJS(args=dict(source=table_source),
                           code=open(
                               os.path.join(os.path.dirname(__file__),
                                            "download.js")).read())


def colors_from_data(data):
    min_data = min(data)
    max_data = max(data)
    if not max_data == min_data:
        data_0_to_256 = [
            int(255 * (data_point - min_data) / (max_data - min_data))
            for data_point in data
        ]
        colors = [bokeh.palettes.Plasma256[i] for i in data_0_to_256]
    else:
        colors = [bokeh.palettes.Plasma256[200] for _ in data]
    return colors
예제 #25
0
def modify_doc(doc):

    df = pd.read_csv(join(dirname(__file__), 'charity_input.csv'))

    source = ColumnDataSource(data=dict())

    table_title_div = Div(text="")

    m_dict = dict({'True': True, 'False': False})

    # calculate min and max of latest_income, to nearest £100,000
    inc_min = math.floor(min(df['latest_income'])/100000)*100000
    inc_max = math.ceil(max(df['latest_income'])/100000)*100000

    # Create lists of all regions and districts present in dataset to use in dropdown filter
    regions = sorted(list(set(df['region'][df.region.notnull()].values)))
    regions.insert(0,'All')
    districts = sorted(list(set(df['district'][df.district.notnull()].values)))
    districts.insert(0,'All')

    # function to quickly return sorted list of values from current selection,
    # used to update dropdown filter below
    def col_list(table, col):
        l1 = ['All']
        l2 = sorted(list(set(table[col][table[col].notnull()].values)))
        l1.extend(l2)
        return l1

    def update():

        # conditions of filters to create current selection
        current = df[(df['latest_income'] >= inc_slider.value[0]) &
                     (df['latest_income'] <= inc_slider.value[1])]

        if act_match.value != "All":
            current = current[current['activity_keyword_match'] == m_dict[act_match.value]]
        if gr_match.value != "All":
            current = current[current['grant_keyword_match'] == m_dict[gr_match.value]]
        if district_input.value != "All":
            current = current[current['district'] == district_input.value]
        if name_input.value != "":
            current = current[current.name.str.contains(name_input.value)]
        if id_input.value != "":
            current = current[current.charity_id == int(id_input.value)]

        if region_input.value != "All":
            current = current[current['region'] == region_input.value]
            district_input.options = col_list(current, 'district')
        else: district_input.options = districts

        # define source data as dictionary of current selection
        source.data = current.to_dict('list')

        # update selection counter div based on length of current
        table_title = "<b>%s</b> charities selected" % "{:,}".format(len(current))
        table_title_div.update(text=table_title)

    match_options = ["All", "True", "False"]

    inc_slider = RangeSlider(title="Latest Income", start=inc_min, end=inc_max, value=(inc_min, inc_max), step=100000, format="0,0")
    act_match = Select(title="Activity Keyword Match", options=match_options, value="All")
    gr_match = Select(title="Grant Keyword Match", options=match_options, value="All")
    region_input = Select(title="Region", options=regions, value="All")
    district_input = Select(title="District", options=districts, value="All")
    name_input = TextInput(value="", title="Charity Name Search")
    id_input = TextInput(value="", title="Charity ID Search")


    bok_cols = [#TableColumn(field='charity_id', title='Charity ID', width=100),
                TableColumn(field='charity_id', title='Charity ID', width=100, #),
                            formatter=HTMLTemplateFormatter(template='<a href="http://beta.charitycommission.gov.uk/charity-details/?regid=<%= value %>&subid=0"target="_blank"><%= value %></a>')),
                TableColumn(field='name', title='Name', width=200),
                TableColumn(field='activities', title='Activities', width=300),
                TableColumn(field='website', title='Website', width=200,
                            formatter=HTMLTemplateFormatter(template='<a href="http://<%= value %>"target="_blank"><%= value %></a>')),
                TableColumn(field='latest_income', title='Latest Income', width=100,
                            formatter=NumberFormatter(format='£ 0,0'))]


    data_table = DataTable(source=source, columns=bok_cols, width=1000, height=600)

    controls = [inc_slider, act_match, gr_match, region_input, district_input,name_input, id_input] #
    for control in controls:
        control.on_change('value', lambda attr, old, new: update())


    button = Button(label="Download", button_type="success")
    button.callback = CustomJS(args=dict(source=source),
                               code=open(join(dirname(__file__), "download.js")).read())


    table = widgetbox(data_table)
    table_section = column(table_title_div, data_table)
    filters = widgetbox(*controls, button, sizing_mode='scale_width')

    desc = Div(text=open(join(dirname(__file__), 'templates/index.html')).read(), width=1000)


    l1 = layout([
        [desc],
        [filters, table_section]
        # [Div()],
        # [filters, table_section],
    ], sizing_mode='fixed')

    update()

    doc.add_root(l1)
예제 #26
0
                 })

#Text for tab3
texto1_tab3 = "The table of best distributions for your classification is: "
texto_tab3 = PreText(text=texto1_tab3)

#Table
texto2_tab3 = PreText(text="Select a filter to see results here")

#Buttom
downloadButton = Button(label="Export in csv")

#downloadButton.js_on_event(ButtonClick, CustomJS(args=dict(source=dataExport),
#                           code=open(join(dirname(__file__), "static/download.js")).read()))

downloadButton.callback = CustomJS(
    code=open(join(dirname(__file__), "static/JS/download.js")).read())

##########################################################################
##########################################################################
#Actions and updatings

targetVar.on_change('value', updateHisto)  #Updating target variable

filterSelect.on_change('value', check_box_populate, compute_summary,
                       clean_filter)  #Updating filter variable

radioButtom_group.on_change('active', filterHisto)  #Enabling checkbox

###########################################################################
#Layout and WebScreen
from bokeh.models.widgets import PasswordInput, TextInput, PreText, Button
from bokeh.layouts import column, row
from bokeh.plotting import show, output_file
from bokeh.models.callbacks import CustomJS

USER = "******"
PASSWD = "Bok3h"

text = PreText(text="LOGIN TO KNOW\nTHE SECRET:")
user = TextInput(placeholder="username", title="(UserName: "******")")
pwd = PasswordInput(placeholder="password", title="(Password: "******")")
btn = Button(label="GO!",width=150)

secret = PreText() # Secret information displayed if correct password entered

## Verify if the password typed is bokeh using a JS script
verify_pwd = CustomJS(args=dict(user=user, pwd=pwd, secret=secret), code="""
    secret.text = 'Wrong Password.';
    if ( user.value == %r && pwd.value == %r) {
        secret.text = 'Right Password. The Secret is 42.';
    }
""" % (USER, PASSWD))

#user.callback = verify_pwd # Check password pressing enter.
pwd.callback = verify_pwd # Check password pressing enter.
btn.callback = verify_pwd # Check password clicking on the Button.

output_file("using_password_input.html", title="Password Field")
page = row(column(text,user, pwd,btn),secret)
show(page)
예제 #28
0
def selection_plot(response):
    # Let's move these into a settings file somewhere?
    # height/width could potentially be driven by the request?


    # Include color data in the ColumnDataSource to allow for changing the color on
    # the client side.
    urls = [x[0] for x in response["pages"]]
    xdata = [x[1] for x in response["pages"]]
    ydata = [x[2] for x in response["pages"]]
    tags = [x[3] for x in response["pages"]]
    color = []
    custom_tags = ["Custom tags"]
    
    for tag in tags:
        custom = False
        if tag:
            for t in tag:
                if t not in ["Relevant", "Irrelevant", ""]:
                    custom = True
                    if t not in custom_tags:
                        custom_tags.append(t)
            if not custom:    
                color.append(colormap(tag[0]))
            else:
                color.append(colormap("Custom"))
        else:
            color.append(colormap(None))

    source = ColumnDataSource(
        data=dict(
            x=xdata,
            y=ydata,
            urls=urls,
            tags=tags,
            color=color,
        )
    )
    # Callback code for CDS.
    source.callback = CustomJS(code="""
        var inds = cb_obj.get('selected')["1d"].indices;
        var data = cb_obj.get('data');
        BokehPlots.showPages(inds);
    """)


    # Create the figure with FIGURE_WIDTH and FIGURE_HEIGHT
    p = figure(
        tools="hover,wheel_zoom,reset",
        width=FIGURE_WIDTH,
        responsive=True,
        tags=["clusterPlot"],
    )

    # Ensure that the lasso only selects with mouseup, not mousemove.
    p.add_tools(
        LassoSelectTool(select_every_mousemove=False),
    )

    # These turn off the x/y axis ticks
    p.axis.visible = None

    # These turn the major grid off
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Plot non-selected circles with a particular style using CIRCLE_SIZE and
    # 'color' list
    p.circle("x", "y", size=13, line_width=2, line_alpha=1,
            line_color=None, fill_alpha=1, color='color', source=source,
            name="urls")
    nonselected_circle = Circle(fill_alpha=0.1, line_alpha=0.1, fill_color='color',
            line_color='color')
    renderer = p.select(name="urls")
    renderer.nonselection_glyph = nonselected_circle


    # Create buttons and their callbacks, use button_code string for callbacks.
    button_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        tag = "%s";
        for(var i = 0; i < inds.length; i++){
            selected.push({
                x: data.x[inds[i]],
                y: data.y[inds[i]],
                url: data.urls[inds[i]],
                tags: data.tags[inds[i]],
                selected: true,
                possible: false,
            });
            data["color"][inds[i]] = "%s";
        }
        BokehPlots.updateTags(selected, tag, "Apply");
        source.trigger("change");
    """

    textinput_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        var tag = cb_obj.get("value");

        // Reinitialise to the default value
        cb_obj.set("value", "Add custom tag...")

        if(tag.indexOf("Add custom tag...") < 0) {
        //Update the custom tags selection list 
        var options = custom_tags_select.get("options");
        if(options.indexOf(tag) < 0){
            options.push(tag);
            custom_tags_select.set("options", options);
        }

        for(var i = 0; i < inds.length; i++){
            selected.push({
                x: data.x[inds[i]],
                y: data.y[inds[i]],
                url: data.urls[inds[i]],
                tags: data.tags[inds[i]],
                selected: true,
                possible: false,
            });
            data["color"][inds[i]] = "%s";
        }
        BokehPlots.updateTags(selected, tag, "Apply");
        source.trigger("change");
        }
    """

    selectinput_code = """
    event.preventDefault();
    var inds = source.get('selected')["1d"].indices;
    var data = source.get('data');
    var selected = [];
    var tag = cb_obj.get("value");    

    cb_obj.set("value", "Enter tags...")
    if(tag.indexOf("Add custom tag...") < 0) {
    for(var i = 0; i < inds.length; i++){
         selected.push({
            x: data.x[inds[i]],
            y: data.y[inds[i]],
            url: data.urls[inds[i]],
            tags: data.tags[inds[i]],
            selected: true,
            possible: false,
         });
         data["color"][inds[i]] = "%s";
    }
    BokehPlots.updateTags(selected, tag, "Apply");
    source.trigger("change");
    }
    """

    # Create buttons and their callbacks, use button_code string for callbacks.
    crawl_code = """
        event.preventDefault();
        var inds = source.get('selected')["1d"].indices;
        var data = source.get('data');
        var selected = [];
        var crawl = '%s';
        for(var i = 0; i < inds.length; i++){
            selected.push(data.urls[inds[i]]);
        }
        BokehPlots.crawlPages(selected, crawl);
        source.trigger("change");
    """

    # Supply color with print formatting.
    but_relevant = Button(label="Relevant", type="success")
    but_relevant.callback = CustomJS(args=dict(source=source),
                    code=button_code % ("Relevant", POSITIVE_COLOR))

    but_irrelevant = Button(label="Irrelevant", type="success")
    but_irrelevant.callback = CustomJS(args=dict(source=source),
                    code=button_code % ("Irrelevant", NEGATIVE_COLOR))

    but_neutral = Button(label="Neutral", type="success")
    but_neutral.callback = CustomJS(args=dict(source=source),
                    code=button_code % ("Neutral", NEUTRAL_COLOR))

    custom_tag_input = TextInput(value="Add custom tag...")
    custom_tag_input.callback = CustomJS(args=dict(source=source),
                    code=textinput_code % (CUSTOM_COLOR))
    
    custom_tag_select = Select(value="Custom tags", options=custom_tags)
    custom_tag_select.callback = CustomJS(args=dict(source=source),
                    code=selectinput_code % (CUSTOM_COLOR))
    custom_tag_input.callback.args["custom_tags_select"] = custom_tag_select

    but_backward_crawl = Button(label="Backlinks", type="success")
    but_backward_crawl.callback = CustomJS(args=dict(source=source),
                                           code=crawl_code % ("backward"))

    but_forward_crawl = Button(label="Forwardlinks", type="success")
    but_forward_crawl.callback = CustomJS(args=dict(source=source),
                                          code=crawl_code % ("forward"))

    
    # Adjust what attributes are displayed by the HoverTool
    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [
        ("urls", "@urls"),
    ]
    tags = hplot(custom_tag_input, custom_tag_select,  but_neutral, but_relevant, but_irrelevant)
    tags_crawl = hplot(but_backward_crawl, but_forward_crawl)
    layout = vplot(p, tags, tags_crawl)
    
    # Combine script and div into a single string.
    plot_code = components(layout)
    return plot_code[0] + plot_code[1]
예제 #29
0
esiid_textbox = TextInput(title='ESIID', value='None')


#day_slider = Slider(title='day', value=1, start=1, end=31, step=1)

month_slider = Slider(title='month', value=finalMonth, start=1, end=12, step=1)

year_slider = Slider(title='year', value=finalYear, start=firstYear, end=finalYear, step=1)

tdsp_group = CheckboxGroup(labels=tdsps,
                           active=list(range(len(tdsps))))

exclude_approval_textbox = TextInput(title='Exclude' value='None')

savebutton = Button(label="Download", button_type="success")
savebutton.callback = CustomJS(args=dict(source=source_dl), code=open(os.path.join(os.path.dirname(__file__), "dl_820transactions.js")).read())

#updatebutton = Button(label="Approve", button_type="")
#updatebutton.callback =


columns = [
    TableColumn(field="DocumentTrackingNumber", title="Document Tracking Number", width=150),
    TableColumn(field="OriginalDocumentID", title="Original Document ID", width=100),
    TableColumn(field="MarketerDUNS", title="Marketer DUNS", width=100),
    TableColumn(field="TDSP", title="TDSP", width=75),
    TableColumn(field="PaymentDueDate", title="Payment Due Date", width=100, formatter=DateFormatter(format="%m/%d/%Y")),
    TableColumn(field="ESIID", title="ESIID", width=100),
    TableColumn(field="InvoiceTotalAmount", title="Invoice Total Amount", width=100, formatter=NumberFormatter(format='$0,0.00')),
    TableColumn(field="Processed", title="Processed", width=75),
]
        # j2sPath="https://www.materialscloud.org/discover/scripts/external/jsmol/j2s",
        serverURL="detail/static/jsmol/php/jsmol.php",
        j2sPath="detail/static/jsmol/j2s",
        script="""set antialiasDisplay ON;
load data "cifstring"
{}
end "cifstring"
""".format(cif_str)
        ## Note: Need PHP server for approach below to work
        #    script="""set antialiasDisplay ON;
        # load cif::{};
        # """.format(get_cif_url(entry.filename))
    )

    btn_download_cif.callback = bmd.CustomJS(args=dict(
        string=cif_str, filename=entry.filename),
                                             code=download_js)
    script_source = bmd.ColumnDataSource()

    applet = JSMol(
        width=600,
        height=600,
        script_source=script_source,
        info=info,
        js_url="detail/static/jsmol/JSmol.min.js",
    )

    df_tailcorrection, df_no_tailcorrection = get_results_df()

    if cof_name in used_block:
        plot_info_ = plot_info_blocked_pockets
예제 #31
0
        } else {
            btn.label = "Connect to device";
            btn.button_type = "success";
        }
    """))

read_point_btn.on_click(read_point_btn_callback)
read_point_btn.callback = CustomJS(args=dict(
    p=plot,
    dt=data_table,
    conn_status=conn_status,
),
                                   code="""
        if(!conn_status.value) {
            console.log('This application must be connected to ESP device to read data from it.');
            return;
        }

        p.toolbar.tools[""" + util.reset_tool_index(g.TOOLS3) +
                                   """].trigger('do');

        setTimeout(function(){
            dt.trigger('change');
        },""" + str(g.DEBOUNCE_VAL) + """);
    """)

clear_points_btn.on_click(clear_points_btn_callback)
clear_points_btn.callback = click_reset_tool

clear_everything_btn.on_click(clear_everything_btn_callback)
clear_everything_btn.callback = click_reset_tool
예제 #32
0
upload_button.callback = CustomJS(args=dict(file_source=file_source),
                                  code="""
function read_file(filename) {
    var reader = new FileReader();
    reader.onload = load_handler;
    reader.onerror = error_handler;
    // readAsDataURL represents the file's data as a base64 encoded string
    reader.readAsDataURL(filename);
}

function load_handler(event) {
    var b64string = event.target.result;
    file_source.data = {'file_contents' : [b64string], 'file_name':[input.files[0].name]};
    file_source.trigger("change");
}

function error_handler(evt) {
    if(evt.target.error.name == "NotReadableError") {
        alert("Can't read file!");
    }
}

var input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function(){
    if (window.FileReader) {
        read_file(input.files[0]);
    } else {
        alert('FileReader is not supported in this browser');
    }
}
input.click();
""")
예제 #33
0
                    low=[low],
                    close=[close],
                    color=[color],
                    rsi=[rsi[-1]],
                    ema1=[EMA1[-1]],
                    ema2=[EMA2[-1]],
                    date=[date],
                    strdate=[strdate],
                    position=[strat_1.position])
    #maj du titre
    p.title.text = """{0} | prix: {1:.3f} | rsi : {2:.0f}| position : {3} |
 stock : {4:.3f} | valeur : {5:.3f} | vars : {6}/{7}  >>> {8}""".format(
        strdate, close, rsi[-1], strat_1.position, strat_1.stock,
        strat_1.stock * close, strat_1.varema, strat_1.varrsi,
        strat_1.strategy)
    close = source.data['close'] + [close]
    new_data['emaD'] = [EMA1[-1] - EMA2[-1]]
    source.stream(new_data, None)


curdoc().add_root(
    row(
        column(
            gridplot([[p], [p2], [p3]],
                     toolbar_location="left",
                     plot_width=1000)),
        column(DLbutton, data_table1, data_table2)))
curdoc().add_periodic_callback(update, 5000)
curdoc().title = "XRPUSDT"
DLbutton.callback = CustomJS(args=dict(source=source), code=javaScript)
예제 #34
0
            for ci in source_df.columns
        ]
        model_table.source.data = source_df.to_dict(orient='list')
        print(source_df.to_dict(orient='list'))


#        charge_model()

pay_button.on_event(ButtonClick, pay_and_get_model)

# Define the download button to download data from the table
download_button = Button(label="Download the Model",
                         width=360,
                         button_type="success")
download_button.callback = CustomJS(args=dict(source=model_table.source),
                                    code=open(
                                        join(dirname(__file__),
                                             "download.js")).read())

model_widget_right = widgetbox(model_table,
                               modelhere_div,
                               download_button,
                               width=360)

#def show_model_param(event):
##    source_table.data = (data_to_fill)
#    model_table.source.data = model_param_to_fill
#
#pay_button.on_event(ButtonClick, show_model_param)

# Adding all widgets into the main port
curdoc().add_root(row(param_txt, width=800))
예제 #35
0
파일: main.py 프로젝트: 280185386/bokeh
                   data['salary'][i].toString(),
                   data['years_experience'][i].toString().concat('\\n')];

    var joined = currRow.join();
    filetext = filetext.concat(joined);
}

var filename = 'data_result.csv';
var blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' });

//addresses IE
if (navigator.msSaveBlob) {
    navigator.msSaveBlob(blob, filename);
}

else {
    var link = document.createElement("a");
    link = document.createElement('a')
    link.href = URL.createObjectURL(blob);
    link.download = filename
    link.target = "_blank";
    link.style.visibility = 'hidden';
    link.dispatchEvent(new MouseEvent('click'))
}"""

button.callback = CustomJS(args=dict(source=source), code=js_callback)
controls = [salary_range, button]
inputs = HBox(VBoxForm(*controls), width=400)
update(None, None, None)
curdoc().add_root(HBox(inputs, data_table, width=800))
예제 #36
0

years_selections = [str(year) for year in range(2016, 2018)]
year_select = Select(value="2016",
                     title="开始年份",
                     width=200,
                     options=years_selections)
year_select.on_change("value", lambda attr, old, new: update_data())
slider = TextInput(title="阈值", value="0.5")
# slider = Slider(title="阈值", start=0.0, end=1.0, value=0.3, step=0.1)
slider.on_change('value', lambda attr, old, new: update_data())
text = TextInput(title="关键词(例如:MPA、房地产、通胀)", value=u'楼市')
text.on_change('value', lambda attr, old, new: update_data())
button = Button(label=u"下载数据", button_type="success", width=300)
button.callback = CustomJS(args=dict(source=source_download),
                           code=open(join(dirname(__file__),
                                          "download.js")).read())

absolute_corr_columns = [TableColumn(field=x, title=x) for x in assets]
absolute_corr_data_table = DataTable(source=source_absolute_corr,
                                     columns=absolute_corr_columns,
                                     width=1000)
asset_text = TextInput(title=u'资产', value='AU9999.SGE')
asset_text.on_change('value', lambda attr, old, new: update_corr())
word_text = TextInput(title=u'关键词', value=u'加息')
word_text.on_change('value', lambda attr, old, new: update_corr())

update_data()
update_correlation()
update_corr()
update_percentile()
예제 #37
0
    def showGUI(self, pth_to_img, y_form, pred):
        ''' 
        Method builds the bokeh GUI
        
        Parameters
        ----------
        pth_to_img: path to ultrasound image
        y_form: true form of the lesion
        pred: predicted form the lesion
        '''

        ##############
        #Set up a figure
        ##############
        p = figure(x_range=(0, self.DIMS[0]),
                   y_range=(0, self.DIMS[1]),
                   tools=self._tools_to_show,
                   plot_width=self.DIMS[0],
                   plot_height=self.DIMS[1],
                   toolbar_location="above")

        #Add image as background
        p.image_url(url=[self.root_pth + pth_to_img],
                    x=431,
                    y=302,
                    w=862,
                    h=604,
                    anchor="center")

        #Nicier plot
        self._makeShiny(plot=p)

        ##############
        #Add lines and plot them
        ##############
        src_true, src_pred = self._getData()
        self._plotLines(plot=p, src_true=src_true, src_pred=src_pred)

        ##############
        #Add table
        ##############
        table = self._addTable(src_pred=src_pred)

        ##############
        #Add polygons
        ##############
        true_pol, c_t = self._addLesionForm(form=y_form, color='red', plot=p)
        pred_pol, c_p = self._addLesionForm(form=pred, color='blue', plot=p)

        #Add toggles for polygons
        toggle_true = Toggle(label="Show true form",
                             button_type="primary",
                             active=True)
        toggle_true.js_link('active', true_pol, 'visible')
        toggle_true.js_link('active', c_t, 'visible')

        toggle_pred = Toggle(label="Show predicted form",
                             button_type="primary",
                             active=True)
        toggle_pred.js_link('active', pred_pol, 'visible')
        toggle_true.js_link('active', c_p, 'visible')

        ##############
        #Add download button
        ##############
        button_csv = Button(label="Download", button_type="primary")
        button_csv.callback = CustomJS(args=dict(source=src_pred),
                                       code=open(self.root_pth +
                                                 "download.js").read())

        ##############
        #Add title div
        ##############
        div_title = Div(text="""<div> <b>LESION ADJUSTER</b> </div>""",
                        align='center',
                        style={
                            'font-size': '150%',
                            'color': '#1f77b4'
                        })
        ##############
        #Add description to the buttons
        ##############
        div_desc = Div(text="""<div> <b>CONTROLS</b> </div>""",
                       align='center',
                       style={
                           'font-size': '110%',
                           'color': '#1f77b4'
                       })

        ##############
        #Add Div to show euclidean distance and button to recalculate it
        ##############
        div_euclid = Div(text="""
                         <b>Diameter of predicted form is:</b> 334.80 <br>
                         <b>Diameter of true form is:</b> 368.64 <br>
                         <b>RMSE is:</b> 34.13
                         """,
                         align='center',
                         style={'font-size': '100%'})

        p.js_on_event(
            events.MouseMove,
            CustomJS(args=dict(div=div_euclid,
                               source_data_pred=src_pred,
                               source_data_true=src_true),
                     code="""
               var data_p = source_data_pred.data;
               var data_t = source_data_true.data;
               
               var x_p = data_p['x']
               var y_p = data_p['y']
               
               var x_t = data_t['x']
               var y_t = data_t['y']
               
               var diam_p = 0
               var diam_t = 0
               var rmse = 0
               
               //Diameter of pred form
               diam_p = Math.sqrt(Math.pow((x_p[0]-x_p[1]),2) + Math.pow((y_p[0]-y_p[1]),2))
               
               //Diameter of true form
               diam_t = Math.sqrt(Math.pow((x_t[0]-x_t[1]),2) + Math.pow((y_t[0]-y_t[1]),2))
               
               //RMSE
               rmse = Math.sqrt(Math.pow(diam_p - diam_t,2)/1)
               
               //Result
               div.text = "<b>Diameter of predicted form is: </b>" + diam_p.toFixed(2) + "<br> <b>Diameter of true form is: </b>" + diam_t.toFixed(2) + " <br> <b>RMSE is: </b>" + rmse.toFixed(2);
               
               """))

        ##############
        #Show
        ##############
        show(
            Column(
                div_title,
                Row(
                    Column(p, table),
                    Column(div_desc, toggle_true, toggle_pred, button_csv,
                           div_euclid))))