예제 #1
0
    def create_table(source_table):
        template_classicFisher = """
			<div style="background:<%= 
				(function colorfromint(){
					if(value <= 0.01){
						return("green")}
					else{return("gray")}
					}()) %>; 
				color: white"> 
			<%= value %></div>
			"""
        template_term = """<span href="#" data-toggle="tooltip" title="<%= value %>"><%= value %></span>"""

        formatter1 = HTMLTemplateFormatter(template=template_term)
        formatter2 = HTMLTemplateFormatter(template=template_classicFisher)

        columns = [
            TableColumn(field="GO.ID", title="GO.ID", width=100),
            TableColumn(field="Term",
                        title="Term",
                        width=270,
                        formatter=formatter1),
            TableColumn(field="classicFisher",
                        title="classicFisher",
                        width=50,
                        formatter=formatter2)
        ]
        data_table = DataTable(source=source_table,
                               columns=columns,
                               width=520,
                               height=500)

        return widgetbox(data_table)
예제 #2
0
파일: main.py 프로젝트: ap7422/FlavorTool
def get_table(data, names):
    data = dict(Mol1=data[0],
                Mol2=data[1],
                Mol3=data[2],
                other=data[6],
                sum=data[8],
                s=data[9],
                name=data[10],
                link=data[11])

    source = ColumnDataSource(data)
    color_template = """
          <div style="background:<%= 
              (function colorfromint(){
                  if(s == 2){
                      return("rgba(255, 0, 0, .4)")}
                  else if (s  == 1 ){
                       return("rgba(255, 255, 51, .4)")}
                  else 
                  {return("rgba(0, 128, 0, .4)")}
                  }()) %>; 
              color: black"> 
          <%= value %>
          </div>
          """
    link_template = """
                    <a href= <%= link %> > <%= value %> </a>
                    
                    
                    """
    columns = []
    color_formatter = HTMLTemplateFormatter(template=color_template)
    link_formatter = HTMLTemplateFormatter(template=link_template)
    columns.append(TableColumn(field='Mol1', title=names[0], width=215))
    columns.append(TableColumn(field='Mol2', title=names[1], width=215))
    columns.append(TableColumn(field='Mol3', title=names[2], width=215))
    columns.append(TableColumn(field='other', title="Other", width=100))
    columns.append(
        TableColumn(field='sum',
                    title='Value',
                    formatter=color_formatter,
                    width=100))
    columns.append(
        TableColumn(field="name",
                    title="Model",
                    width=150,
                    formatter=link_formatter))
    data_table = DataTable(source=source,
                           columns=columns,
                           index_position=None,
                           fit_columns=True,
                           selectable=True,
                           sortable=False,
                           width=(3 * 215 + 250),
                           height=450)
    return data_table
예제 #3
0
    def _build_plot_legend_table(self):
        template = """
        <div style="background:<%=color%>; color:<%=color%>;">
        <%= value %></div>
        """
        formatter = HTMLTemplateFormatter(template=template)
        color_width = 70
        pdb_width = 60
        cid_width = 60
        resno_width = 130
        pos_width = 100
        total_width = color_width + pdb_width + cid_width + resno_width + pos_width

        columns = [
            TableColumn(field="color",
                        title="Line Colour",
                        width=color_width,
                        formatter=formatter),
            TableColumn(field="pdb", title="PDB Code", width=pdb_width),
            TableColumn(field="cid", title="Chain ID", width=cid_width),
            TableColumn(field="resno",
                        title="Starting Residue No",
                        width=resno_width),
            TableColumn(field="seqno", title="Position Range", width=pos_width)
        ]
        data_table = DataTable(source=self.plot_legend_CDS,
                               columns=columns,
                               width=total_width,
                               height=150,
                               index_position=None,
                               fit_columns=True)
        return data_table
예제 #4
0
def plot_table(df,
               header_style="color: #757575; font-family: Courier; font-weight:800",
               table_style="color: #757575; font-family: Courier; font-weight:normal",
               height=250):
    source = ColumnDataSource(df)

    header = Div(text="<style>.slick-header.ui-state-default{" + header_style + "}</style>")

    template = """
    <div style="{}"> 
        <%= value %>
    </div>
    """.format(table_style)

    columns = [
        TableColumn(field=col,
                    title=col,
                    formatter=HTMLTemplateFormatter(template=template)
                    )
        for col in df.columns
    ]
    data_table = DataTable(source=source,
                           columns=columns,
                           fit_columns=True,
                           header_row=True,
                           index_position=None,
                           height=height
                           )
    return Column(header, widgetbox(data_table))
예제 #5
0
 def __pass_fail_formatter(self):
     # Data tables
     # custom js to highlight mismatches in red with white text
     template = """
                        <div style="background:<%= 
                            (function colorfrommismatch(){
                                if(pass_fail != "" ){
                                    if(pass_fail == "Fail"){
                                       return('HIGHLIGHT_COLOR_FAIL')
                                    }
                                    if(pass_fail == "Pass"){
                                       return('HIGHLIGHT_COLOR_PASS')
                                    }
                                }
                                }()) %>; 
                            color: <%= 
                                 (function colorfrommismatch(){
                                     if(pass_fail == "Fail"){return('TEXT_COLOR_FAIL')}
                                     }()) %>;"> 
                        <%= value %>
                        </div>
                        """
     template = template.replace('HIGHLIGHT_COLOR_FAIL', 'red')
     template = template.replace('TEXT_COLOR_FAIL', 'white')
     template = template.replace('HIGHLIGHT_COLOR_PASS', 'lightgreen')
     template = template.replace('TEXT_COLOR_PASS', 'black')
     return HTMLTemplateFormatter(template=template)
예제 #6
0
    def get_res_table(cls, payload):
        df = Model.get_res_df(payload)

        template = """<div class="tooltip-parent"><div class="tooltipped"><%= value %></div><div class="tooltip-text"><%= value %></div></div>"""
        columns = [
            TableColumn(field=c,
                        title=c,
                        width=COL_WIDTHS[c],
                        formatter=HTMLTemplateFormatter(template=template))
            for c in DISPLAYED_COLS
        ]

        source = ColumnDataSource(df)

        callback = CustomJS(
            args=dict(source=source),
            code=
            """select_res(source.attributes.selected['1d']['indices'][0])""")
        source.js_on_change('selected', callback)

        res_table = DataTable(source=source,
                              columns=columns,
                              width=PAGE_WIDTH,
                              height=320,
                              editable=True)

        return res_table
예제 #7
0
def _create_examples_table() -> DataTable:
    """Utility function for creating and styling the events table."""

    formatter = HTMLTemplateFormatter(template='''
    <style>
        .AS {color: #0000FF; font-weight: bold;}
        .OP {color: #0000FF; font-weight: bold;}
    </style>
    <div><%= value %></div>''')
    columns = [
        TableColumn(field='Examples',
                    title='<span class="header">Examples</span>',
                    formatter=formatter)
    ]
    empty_source = ColumnDataSource()
    empty_source.data = {'Examples': []}
    return DataTable(source=empty_source,
                     columns=columns,
                     height=500,
                     index_position=None,
                     width=1500,
                     sortable=False,
                     editable=False,
                     reorderable=False,
                     header_row=True)
예제 #8
0
 def _create_table(df, columns, width, height):
     if columns is None:
         columns = df.columns
     selection = df[columns]
     template = """<span href="#" data-toggle="tooltip" title="<%= value %>"><%= value %></span>"""
     table = pnw.DataFrame(selection, formatters={key: HTMLTemplateFormatter(template=template) for key in selection.columns}, selection=[0], width=width, height=height, **kwargs)
     return table
예제 #9
0
def _create_events_table() -> DataTable:
    """Utility function for creating and styling the events table."""
    formatter = HTMLTemplateFormatter(template='''
    <style>
        .AS_POS {color: #0000FF; font-weight: bold;}
        .AS_NEG {color: #0000FF; font-weight: bold;}
        .OP_POS {color: #1aaa0d; font-style: bold;}
        .OP_NEG {color: #f40000;font-style: bold;}
        .NEG_POS {font-style: italic;}
        .NEG_NEG {color: #f40000; font-style: italic;}
        .INT_POS {color: #1aaa0d; font-style: italic;}
        .INT_NEG {color: #f40000; font-style: italic;}
    </style>
    <%= value %>''')
    columns = [
        TableColumn(field='POS_events',
                    title='Positive Examples',
                    formatter=formatter),
        TableColumn(field='NEG_events',
                    title='Negative Examples',
                    formatter=formatter)
    ]
    return DataTable(source=ColumnDataSource(),
                     columns=columns,
                     height=400,
                     index_position=None,
                     width=2110,
                     sortable=False,
                     editable=True,
                     reorderable=False)
예제 #10
0
def make_layout():
    import pandas as pd
    plot, source = make_plot()
    template = """<span href="#" data-toggle="tooltip"  title="<%= value %>"><%= value %></span>"""
    columns = [
        TableColumn(field="dates", title="Date", editor=DateEditor(), formatter=DateFormatter()),
        TableColumn(field="downloads", title="Downloads", editor=IntEditor()),
    ]

    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']]
    source = ColumnDataSource(data=df)
    data_table = DataTable(source=source, columns = columns)
    l = layout([[data_table]])
    return l

    data_table = DataTable(source=source, columns=columns, width=400, height=400, editable=True)
    button = Button(label="Randomize data", button_type="success")
    button.on_click(click_handler)
    buttons = WidgetBox(children=[button], width=400)
    column = Column(children=[buttons, plot, data_table])
    return column
예제 #11
0
def gen_column():
    columns = [
            TableColumn(
                field="features", title="Features", width=300,
                formatter=HTMLTemplateFormatter(
                template='<a href=<%= value %>.html target="_blank"><%= value %></a>')),
            TableColumn(field="start", title="Begin", width=150),
            TableColumn(field="end", title="End", width=150),
            TableColumn(field="strand", title="Strand", width=100),
            TableColumn(field="gene_name", title="Gene name", width=400),
            TableColumn(field="tran", title="Parent transcript"),
            TableColumn(field="tss", title="Associated TSSs", width=1000),
            TableColumn(field="ps", title="Associated processing sites", width=800),
            TableColumn(field="term", title="Associated terminators", width=420),
            TableColumn(
                field="link", title="Functional reference", width=460,
                formatter=HTMLTemplateFormatter(template='<%= value %>')),
            TableColumn(field="TSB_OD_0.2", title="RPKM:TSB_OD_0.2"),
            TableColumn(field="TSB_OD_0.2_TEX", title="RPKM:TSB_OD_0.2_TEX"),
            TableColumn(field="TSB_OD_0.5", title="RPKM:TSB_OD_0.5"),
            TableColumn(field="TSB_OD_0.5_TEX", title="RPKM:TSB_OD_0.5_TEX"),
            TableColumn(field="TSB_OD_1", title="RPKM:TSB_OD_1"),
            TableColumn(field="TSB_OD_1_TEX", title="RPKM:TSB_OD_1_TEX"),
            TableColumn(field="TSB_t0", title="RPKM:TSB_t0"),
            TableColumn(field="TSB_t0_TEX", title="RPKM:TSB_t0_TEX"),
            TableColumn(field="TSB_t1", title="RPKM:TSB_t1"),
            TableColumn(field="TSB_t1_TEX", title="RPKM:TSB_t1_TEX"),
            TableColumn(field="TSB_t2", title="RPKM:TSB_t2"),
            TableColumn(field="TSB_t2_TEX", title="RPKM:TSB_t2_TEX"),
            TableColumn(field="TSB_ON", title="RPKM:TSB_ON"),
            TableColumn(field="TSB_ON_TEX", title="RPKM:TSB_ON_TEX"),
            TableColumn(field="pMEM_OD_0.2", title="RPKM:pMEM_OD_0.2"),
            TableColumn(field="pMEM_OD_0.2_TEX", title="RPKM:pMEM_OD_0.2_TEX"),
            TableColumn(field="pMEM_OD_0.5", title="RPKM:pMEM_OD_0.5"),
            TableColumn(field="pMEM_OD_0.5_TEX", title="RPKM:pMEM_OD_0.5_TEX"),
            TableColumn(field="pMEM_OD_1", title="RPKM:pMEM_OD_1"),
            TableColumn(field="pMEM_OD_1_TEX", title="RPKM:pMEM_OD_1_TEX"),
            TableColumn(field="pMEM_t0", title="RPKM:pMEM_t0"),
            TableColumn(field="pMEM_t0_TEX", title="RPKM:pMEM_t0_TEX"),
            TableColumn(field="pMEM_t1", title="RPKM:pMEM_t1"),
            TableColumn(field="pMEM_t1_TEX", title="RPKM:pMEM_t1_TEX"),
            TableColumn(field="pMEM_t2", title="RPKM:pMEM_t2"),
            TableColumn(field="pMEM_t2_TEX", title="RPKM:pMEM_t2_TEX"),
            TableColumn(field="pMEM_ON", title="RPKM:pMEM_ON"),
            TableColumn(field="pMEM_ON_TEX", title="RPKM:pMEM_ON_TEX"),
            TableColumn(field="frag", title="Fragmentation")]
    return columns
예제 #12
0
파일: plotting.py 프로젝트: tblaschke/vizor
def render_vizard(doc):
    args = doc.session_context.request.arguments
    req_path = args["req_path"][0].decode('utf-8')

    data = logparser.read_output_log(req_path)
    hover = create_hover_tool()

    score_plot, score_source = create_score_chart(data, title="Scores", x_name="Step", y_name="Average Score",
                                                  text_font_size="20pt")

    molecule_plot = create_2d_molecule(data, position=-1)
    slider = Slider(start=-1, end=len(data) - 1, value=-1, step=1, title="Step")

    template = """<span data-toggle="tooltip" title="<%= value %>"><%= svg %></span>"""
    columns = [
        TableColumn(field="Step", title="Step"),
        TableColumn(field="Score", title="Score"),
        TableColumn(field="SMILES", title="SMILES", formatter=HTMLTemplateFormatter(template=template)),
    ]
    smiles, score = extract_compounds(data, -1)
    molsvg = [create_hover_svg(smi) for smi in smiles]
    tabledf = dict(Step=[get_position(data, -1)] * len(smiles), SMILES=smiles, Score=score, svg=molsvg)
    table_source = ColumnDataSource(data=tabledf)
    data_table = DataTable(source=table_source, columns=columns, width=900, height=400)

    def slider_callback(attr, old, new):
        new = int(new)
        data = score_source.data["raw_data"]
        new_molecule_plot = create_2d_molecule(data, position=new)
        molecule_plot.text = new_molecule_plot.text
        smiles, score = extract_compounds(data, new)
        molsvg = [create_hover_svg(smi) for smi in smiles]
        tabledf = dict(Step=[get_position(data, new)] * len(smiles), SMILES=smiles, Score=score, svg=molsvg)
        table_source.data = tabledf

    def redraw_new_sliderend(attr, old, new):
        if slider.value == -1:
            slider_callback(attr, -1, -1)

    slider.on_change('value', slider_callback)
    slider.on_change('end', redraw_new_sliderend)

    bokehlayout = layout([row(column(molecule_plot, slider), score_plot), ], sizing_mode="fixed")
    doc.add_root(bokehlayout)

    def check_new_data():
        newdata = logparser.read_output_log(req_path)
        if len(newdata) > len(score_source.data["raw_data"]):
            x, y = extract_average_scores(newdata)
            y_mean = running_average(y, 50)
            score_source.data.update(x=x.tolist(), y=y.tolist(), y_mean=y_mean.tolist(), raw_data=newdata)
            slider.end = len(x) - 1

    doc.add_periodic_callback(check_new_data, 1000)
    doc.theme = Theme(filename=os.path.dirname(os.path.realpath(__file__)) + "/templates/theme.yaml")
def metric_comparison(metric1, metric2):
    print(metric1.metricName)
    print(metric2)
    data = {
        'Field':['Metric Name', 'Source', 'Organisation', 'Database',
               'Schema', 'Table', 'Metric Numerator', 'Metric Denominator',
               'Exclude Bulk?', 'Residential Only?', 'Exclude Courtesy?',
               'Exclude IE?', 'Exclude Prepaid?', 'Geography', 'Time granularity',
               'Start Date', 'End Date'],
        'Metric1':[metric1.metricName, metric1.source,
                 metric1.organisation, metric1.database, metric1.schema,
                 metric1.table, metric1.metricNumer, metric1.metricDenom,
                 metric1.exclusions['excl_bulk'], metric1.exclusions['excl_resi'],
                 metric1.exclusions['excl_courtesy'], metric1.exclusions['excl_ie'],
                 metric1.exclusions['excl_prepaid'], metric1.topGeoAgg, metric1.timeDensity,
                 metric1.dateRange['start_date'], metric1.dateRange['end_date']],
        'Metric2':[metric2.metricName, metric2.source,
                 metric2.organisation, metric2.database, metric2.schema,
                 metric2.table, metric2.metricNumer, metric2.metricDenom,
                 metric2.exclusions['excl_bulk'], metric2.exclusions['excl_resi'],
                 metric2.exclusions['excl_courtesy'], metric2.exclusions['excl_ie'],
                 metric2.exclusions['excl_prepaid'], metric2.topGeoAgg, metric2.timeDensity,
                 metric2.dateRange['start_date'], metric2.dateRange['end_date']]
    }

    source = ColumnDataSource(data)

    template = """
                <div style="background:<%= 
                    (function colorfromint(){
                        if(Metric1 != Metric2 ){
                            return("yellow")}
                        }()) %>; 
                    color: <%= 
                        (function colorfromint(){
                            if(Metric1 != Metric2){return('red')}
                            }()) %>;"> 
                    <%= value %>
                    </font>
                </div>
                """
    formatter = HTMLTemplateFormatter(template=template)

    columns = [
        TableColumn(field="Field", title="Field"),
        TableColumn(field="Metric1", title="Metric 1"),
        TableColumn(field="Metric2", title="Metric 2", formatter=formatter)
    ]
    data_table = DataTable(source=source, columns=columns, width=800, height=500)
    return bokeh.embed.json_item(data_table, "mytable")
예제 #14
0
파일: Dashboard.py 프로젝트: Ukasz123D/GPW
def wallettable(width, height):
    #kwerenda do wyciągania przychodów
    df = pd.read_sql("""SELECT * FROM [PORTFEL_VW]""", conn)
    #dane
    source = ColumnDataSource(data=df)
    #formatowanie warunkowe
    cndtemplate = """
    <div style="color:<%= 
        (function colorfromint(){
            if(value < 0){
                return("red")}
            else{return("green")}
            }()) %>"> 
    <%= (value).toFixed(2) %></div>
    """
    cndformatter = HTMLTemplateFormatter(template=cndtemplate)
    #kolumny
    columns = [
        TableColumn(field="NAZWA", title="Nazwa"),
        TableColumn(field="CURR_COUNT", title="Pakiet"),
        TableColumn(field="PUR_PRICE",
                    title="Zakup",
                    formatter=NumberFormatter(format='0,0.00')),
        TableColumn(field="PRICE_TODAY",
                    title="Obecnie",
                    formatter=NumberFormatter(format='0,0.00')),
        TableColumn(field="PRICE_MIN",
                    title="Próg",
                    formatter=NumberFormatter(format='0,0.00')),
        TableColumn(field="CURR_COST",
                    title="Koszt całk.",
                    formatter=NumberFormatter(format='0,0.00')),
        TableColumn(field="CURR_VALUE",
                    title="Wart. całk.",
                    formatter=NumberFormatter(format='0,0.00')),
        TableColumn(field="TAX",
                    title="Podatek",
                    formatter=NumberFormatter(format='0,0.00')),
        TableColumn(field="YIELD", title="Zysk", formatter=cndformatter),
        TableColumn(field="%",
                    title="%",
                    formatter=NumberFormatter(format='0,0.00%'))
    ]
    #tabela
    t = DataTable(source=source, columns=columns, width=width, height=height)
    t = finalize_table(t, True, False, False, False)
    return t
예제 #15
0
def dataTable():
    elecData = pd.read_csv('test1.csv')
    tableCount = len(elecData.index)
    global data
    data = dict(
        aptNo=[elecData['AprtNo'][i] for i in range(tableCount)],
        roomNo=[elecData['RoomNo'][i] for i in range(tableCount)],
        peopleNo=[elecData['PeopleNo'][i] for i in range(tableCount)],
        electroFee=[elecData['ElectroFee'][i] for i in range(tableCount)],
        useElectro=[elecData['UseElectro'][i] for i in range(tableCount)],
        firstMethod=[elecData['FirstMethod'][i] for i in range(tableCount)],
        secondMethod=[elecData['SecondMethod'][i] for i in range(tableCount)],
        proposed=[elecData['Proposed'][i] for i in range(tableCount)])
    source = ColumnDataSource(data)

    template = """
                <div style="background:<%= 
                    (function colorfromint(){
                        if(firstMethod > secondMethod ){
                            return("green")}
                        }()) %>; 
                    color: <%= 
                        (function colorfromint(){
                            if(firstMethod > secondMethod){return('yellow')}
                            }()) %>;"> 
                    <%= value %>
                    </font>
                </div>
                """
    formatter = HTMLTemplateFormatter(template=template)
    columns = [
        TableColumn(field="aptNo", title="AptNo"),
        TableColumn(field="roomNo", title="RoomNo"),
        TableColumn(field="peopleNo", title="PeopleNo"),
        TableColumn(field="electroFee", title="ElectroFee"),
        TableColumn(field="useElectro", title="UseElectro"),
        TableColumn(field="firstMethod",
                    title="FirstMethod",
                    formatter=formatter),
        TableColumn(field="secondMethod",
                    title="SecondMethod",
                    formatter=formatter),
        TableColumn(field="proposed", title="Proposed"),
    ]
    data_table = DataTable(source=source, columns=columns)

    return data_table
def data_table_formatter(selected_opt, table_source):
	# https://stackoverflow.com/questions/50996875/how-to-color-rows-and-or-cells-in-a-bokeh-datatable
	if selected_opt == 0:
		template = """
					<p style="color:<%=
						(function colorfromint(){
							if( subgroup == " ")
								{return('green')}
							}()) %>;">
						<%= value %>
					</p>
					"""
	elif selected_opt == 1:
		template = """
					<p style="color:<%=
						(function colorfromint(){
							count = (name.split("--").length - 1)
							if ((remap_spanning_reads > 0 || subgroup.includes('--')) && count < 2)
								{return('red')}
							}()) %>;">
						<%= value %>
					</p>
					"""
	elif selected_opt == 2:
		template = """
					<p style="color:<%=
						(function colorfromint(){
							if ( num_of_isoform > 0)
								{return('blue')}
							}()) %>;">
						<%= value %>
					</p>
					"""
	formatter = HTMLTemplateFormatter(template=template)
	columns = [TableColumn(field="name", title="Name", formatter=formatter, width=390),
			   TableColumn(field="subgroup", title="Subgroup Name", formatter=formatter, width=450),  ##ADDED
			   TableColumn(field="mapping_score", title="Map Score", formatter=formatter),
			   TableColumn(field="spanning_reads", title="Spanning Reads", formatter=formatter),
			   TableColumn(field='seq_agreement_near_breakpoint', title='Seq. Agreement', formatter=formatter),
			   TableColumn(field='num_of_isoform', title='Isoforms', formatter=formatter),
			   TableColumn(field='fraction_repetitive', title='Frac. Repetitive',
						   formatter=formatter)]
	data_table = DataTable(source=table_source, columns=columns, fit_columns=True, width=420, height_policy='auto',
						   editable=False,
						   reorderable=False, name='tableSource', sortable=True, row_height=30)
	return data_table
예제 #17
0
    def write_table(self, run_list=None, raft_list=None, type_list=None):
        data = dict(rafts=raft_list, runs=run_list, types=type_list)

        dashboard = ColumnDataSource(data)

        columns = [
            TableColumn(field="rafts", title="Raft"),
            TableColumn(field="types", title="Type"),
            TableColumn(field="runs",
                        title="Run",
                        formatter=HTMLTemplateFormatter(template="<a href= \
                'http://slac.stanford.edu/~richard/LSST/<%= rafts %>-<%= runs %>.html' \
                ><%= runs %></a>"))
        ]
        data_table = DataTable(source=dashboard,
                               columns=columns,
                               width=400,
                               height=280)

        return data_table
예제 #18
0
    def create_res_table(cls):
        template = """<div class="tooltip-parent"><div class="tooltipped"><%= value %></div><div class="tooltip-text"><%= value %></div></div>"""
        columns = [TableColumn(
            field=c,
            title=c,
            width=COL_WIDTHS[c],
            formatter=HTMLTemplateFormatter(template=template)
        ) for c in DISPLAYED_COLS]

        def _selected_handler(attr, old, new):
            cls.select_result_handler(new['1d']['indices'][0])

        source = ColumnDataSource(pd.DataFrame())
        source.on_change('selected', _selected_handler)

        cls.res_table = DataTable(
            source=source,
            columns=columns,
            width=PAGE_WIDTH,
            height=320,
            editable=True
        )
예제 #19
0
    def prepData(self, data):
        # TODO(Mike): handle dates
        fig = None
        alt = ['table']
        cols = {x: str(data[x].dtype) for x in data.columns}
        vals = data.values.tolist()

        # parse the available plots
        if any(self.getDType(k) == 'numeric' for k in cols):
            if (len(vals)) > 3:
                alt += ['hist']
            if sum([self.getDType(k) == 'numeric' for k in cols]) > 1:
                alt += ['scatter']
                for k in cols:
                    if self.getDType(k) == 'numeric':
                        if data[k].nunique() == data[k].count():
                            alt += ['line']
                            break
                        else:
                            for cat in cols:
                                #TODO(Mike): this only works for equally long data-series
                                if self.getDType(cat) != 'numeric' and all(
                                        data[data[cat] == v][k].nunique() ==
                                        data[data[cat] == v][k].count()
                                        for v in data[cat].unique()):
                                    alt += ['line']
                                    break

            for k in cols:
                if self.getDType(k) != 'numeric':
                    #TODO(Mike): do we want to distinguish stacked/unstacked data series?
                    if len(vals) > 2 and len(data[k].unique()) == len(
                            data[k]) and 'pie' not in alt:
                        alt += ['pie']
                    #if len(vals) > 2 and 'bar' not in alt:
                    #    alt += ['bar']
                    if all(data[data[k] == u].count()[0] == 1
                           for u in data[k].unique()):
                        if len(vals) > 2 and 'bar' not in alt:
                            alt += ['bar']
                    if any(opt['DTYPE'] == 'date' and dom in k
                           for dom, opt in self.aliases.items()):
                        if all((data[data[k] == u].count() == data[
                                data[k] == data[k].iloc[0]].count())[0]
                               for u in data[k].unique()):
                            if 'line' not in alt and len(vals) > 4:
                                alt += ['line']
        #TODO(Mike): Refine multi logic
        '''
        if len(cols) > 2:
            if 'line' in alt:
                alt.remove('line')
                alt += ['multi line']
            if sum([cols[k] == 'O' for k in cols]) > 1:
                if 'bar' in alt:
                    alt.remove('scatter')
                    alt += ['multi scatter']
                    alt.remove('bar')
                    alt += ['multi bar']
                    alt.remove('pie')
                    alt += ['multi pie']
            elif 'hist' in alt:
                alt.remove('hist')
                alt += ['multi hist']

            numericCols = [self.getDType(k) == 'numeric' for k in cols]
            if sum(numericCols) > 2:
                if 'scatter' in alt:
                    alt.remove('scatter')
                alt += ['size scatter', 'dbl axis line']
                if any(k1 != k2 and cols[k1] == cols[k2] for k1 in cols for k2 in cols):
                    alt += ['box', 'stacked bar']
        '''

        frmt = HTMLTemplateFormatter(
            template='<div style="font-size: 16px"><%= value %></div>')
        Columns = [
            TableColumn(field=col, title=col, formatter=frmt)
            for col in data.columns
        ]
        fig = DataTable(columns=Columns,
                        source=ColumnDataSource(data),
                        index_position=None,
                        width=10)

        lay = layout([fig], sizing_mode="stretch_both")
        script, div = components(lay)
        return {
            'html': script + div,
            'alt': alt,
            'data': [[x for x in cols]] + vals
        }
예제 #20
0
               PanTool(),
               BoxZoomTool(),
               TapTool(),
               BoxSelectTool(),
               LassoSelectTool(),
               ResetTool()
           ])
p.circle("x",
         "y",
         size=20,
         line_color="color",
         fill_color="color",
         fill_alpha=0.5,
         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())
예제 #21
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)
예제 #22
0
파일: navia.py 프로젝트: d-que/navia
#                     + open(os.path.join(os.getcwd(), 'JS_Functions', "showtab_cb.js")).read())
# aser_data.js_on_change('patching', show_tab_cb)
template="""
            <div style="background:<%= 
                (function colorfromint(){
                    return(Colour)
                    }()) %>; 
                color: <%= 
                    (function colorfromint(){
                        return(Colour)
                        }()) %>;"> 
                <%= value %>
                </font>
            </div>
            """
formatter =  HTMLTemplateFormatter(template=template)

columns_mass_table = [
        TableColumn(field="Colour", title="Colour", formatter=formatter, width=120),
        TableColumn(field="Series", title="Series"),
        TableColumn(field="Mass", title="Mass", formatter=NumberFormatter(format='0,0.00')),
        TableColumn(field="Uncertainty", title="Uncertainty", formatter=NumberFormatter(format='0,0.00')),
    ]
masses_table = DataTable(source=series_masses, name='Mass table', columns=columns_mass_table, width=370, height=300, index_position=None, editable=False)

n_complexes = 10

SU_act = AjaxDataSource(dict(name=[],mass=[],min=[],max=[], stride=[]))

columns_complex_table = [
        TableColumn(field="name", title="Subunit", width=250),
예제 #23
0
def create_table(status_dict):
    """Create interactive ``bokeh`` table containing the logfile status
    results.

    Parameters
    ----------
    status_dict : dict
        Nested dictionary with status results from all logfiles
    """
    # Rearrange the nested dictionary into a non-nested dict for the table
    filenames = []
    dates = []
    missings = []
    results = []
    for key in status_dict:
        filenames.append(status_dict[key]['logname'])
        dates.append(datetime.fromtimestamp(status_dict[key]['latest_time']))
        missings.append(str(status_dict[key]['missing_file']))
        results.append(status_dict[key]['status'])

    # div to color the boxes in the status column
    success_template = """
    <div style="background:<%=
        (function colorfromstr(){
            if(value == "success"){
                return("green")}
            else{return("red")}
            }()) %>;
        color: white">
    <%= value %></div>
    """

    # div to color the boxes in the column for possibly late logfiles
    missing_template = """
    <div style="background:<%=
        (function colorfrombool(){
            if(value == "True"){
                return("orange")}
            else{return("green")}
            }()) %>;
        color: white">
    <%= value %></div>
    """
    success_formatter = HTMLTemplateFormatter(template=success_template)
    missing_formatter = HTMLTemplateFormatter(template=missing_template)

    data = dict(name=list(status_dict.keys()),
                filename=filenames,
                date=dates,
                missing=missings,
                result=results)
    source = ColumnDataSource(data)

    datefmt = DateFormatter(format="RFC-2822")
    columns = [
        TableColumn(field="name", title="Monitor Name", width=200),
        TableColumn(field="filename", title="Most Recent File", width=350),
        TableColumn(field="date",
                    title="Most Recent Time",
                    width=200,
                    formatter=datefmt),
        TableColumn(field="missing",
                    title="Possible Missing File",
                    width=200,
                    formatter=missing_formatter),
        TableColumn(field="result",
                    title="Status",
                    width=100,
                    formatter=success_formatter),
    ]
    data_table = DataTable(source=source,
                           columns=columns,
                           width=800,
                           height=280,
                           index_position=None)

    # Get output directory for saving the table files
    output_dir = get_config()['outputs']
    output_filename = 'cron_status_table'

    # Save full html
    html_outfile = os.path.join(output_dir, 'monitor_cron_jobs',
                                '{}.html'.format(output_filename))
    output_file(html_outfile)
    save(data_table)
    try:
        set_permissions(html_outfile)
    except PermissionError:
        logging.warning(
            'Unable to set permissions for {}'.format(html_outfile))
    logging.info('Saved Bokeh full HTML file: {}'.format(html_outfile))
예제 #24
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)
예제 #25
0
def _create_ui_components() -> (Figure, ColumnDataSource):  # pylint: disable=too-many-statements
    global asp_table_source, asp_filter_src, op_table_source, op_filter_src
    global stats, aspects, tabs, lexicons_dropdown
    stats = pd.DataFrame(columns=['Quantity', 'Score'])
    aspects = pd.Series([])

    def new_col_data_src():
        return ColumnDataSource({'file_contents': [], 'file_name': []})

    large_text = HTMLTemplateFormatter(template='''<div><%= value %></div>''')

    def data_column(title):
        return TableColumn(field=title,
                           title='<span class="header">' + title + '</span>',
                           formatter=large_text)

    asp_table_columns = [
        data_column('Term'),
        data_column('Alias1'),
        data_column('Alias2'),
        data_column('Alias3')
    ]
    op_table_columns = [
        data_column('Term'),
        data_column('Score'),
        data_column('Polarity')
    ]

    asp_table_source = empty_table('Term', 'Alias1', 'Alias2', 'Alias3')
    asp_filter_src = empty_table('Term', 'Alias1', 'Alias2', 'Alias3')
    asp_src = new_col_data_src()

    op_table_source = empty_table('Term', 'Score', 'Polarity', 'Polarity')
    op_filter_src = empty_table('Term', 'Score', 'Polarity', 'Polarity')
    op_src = new_col_data_src()

    asp_table = DataTable(source=asp_table_source,
                          selectable='checkbox',
                          columns=asp_table_columns,
                          editable=True,
                          width=600,
                          height=500)
    op_table = DataTable(source=op_table_source,
                         selectable='checkbox',
                         columns=op_table_columns,
                         editable=True,
                         width=600,
                         height=500)

    asp_examples_box = _create_examples_table()
    op_examples_box = _create_examples_table()
    asp_layout = layout([[asp_table, asp_examples_box]])
    op_layout = layout([[op_table, op_examples_box]])
    asp_tab = Panel(child=asp_layout, title="Aspect Lexicon")
    op_tab = Panel(child=op_layout, title="Opinion Lexicon")
    tabs = Tabs(tabs=[asp_tab, op_tab], width=700, css_classes=['mytab'])

    lexicons_menu = [("Open", "open"), ("Save", "save")]
    lexicons_dropdown = Dropdown(label="Edit Lexicons",
                                 button_type="success",
                                 menu=lexicons_menu,
                                 width=140,
                                 height=31,
                                 css_classes=['mybutton'])

    train_menu = [("Parsed Data", "parsed"), ("Raw Data", "raw")]
    train_dropdown = Dropdown(label="Extract Lexicons",
                              button_type="success",
                              menu=train_menu,
                              width=162,
                              height=31,
                              css_classes=['mybutton'])

    inference_menu = [("Parsed Data", "parsed"), ("Raw Data", "raw")]
    inference_dropdown = Dropdown(label="Classify",
                                  button_type="success",
                                  menu=inference_menu,
                                  width=140,
                                  height=31,
                                  css_classes=['mybutton'])

    text_status = TextInput(value="Select training data",
                            title="Train Run Status:",
                            css_classes=['statusText'])
    text_status.visible = False

    train_src = new_col_data_src()
    infer_src = new_col_data_src()

    with open(join(dirname(__file__), "dropdown.js")) as f:
        args = dict(clicked=lexicons_dropdown,
                    asp_filter=asp_filter_src,
                    op_filter=op_filter_src,
                    asp_src=asp_src,
                    op_src=op_src,
                    tabs=tabs,
                    text_status=text_status,
                    train_src=train_src,
                    infer_src=infer_src,
                    train_clicked=train_dropdown,
                    infer_clicked=inference_dropdown,
                    opinion_lex_generic="")
        code = f.read()

    args['train_clicked'] = train_dropdown
    train_dropdown.js_on_change('value', CustomJS(args=args, code=code))

    args['train_clicked'] = inference_dropdown
    inference_dropdown.js_on_change('value', CustomJS(args=args, code=code))

    args['clicked'] = lexicons_dropdown
    lexicons_dropdown.js_on_change('value', CustomJS(args=args, code=code))

    def update_filter_source(table_source, filter_source):
        df = table_source.to_df()
        sel_inx = sorted(table_source.selected.indices)
        df = df.iloc[sel_inx, 1:]
        new_source = ColumnDataSource(df)
        filter_source.data = new_source.data

    def update_examples_box(data, examples_box, old, new):
        examples_box.source.data = {'Examples': []}
        unselected = list(set(old) - set(new))
        selected = list(set(new) - set(old))
        if len(selected) <= 1 and len(unselected) <= 1:
            examples_box.source.data.update({
                'Examples':
                [str(data.iloc[unselected[0], i])
                 for i in range(4, 24)] if len(unselected) != 0 else
                [str(data.iloc[selected[0], i]) for i in range(4, 24)]
            })

    def asp_selected_change(_, old, new):
        global asp_filter_src, asp_table_source, aspects_data
        update_filter_source(asp_table_source, asp_filter_src)
        update_examples_box(aspects_data, asp_examples_box, old, new)

    def op_selected_change(_, old, new):
        global op_filter_src, op_table_source, opinions_data
        update_filter_source(op_table_source, op_filter_src)
        update_examples_box(opinions_data, op_examples_box, old, new)

    def read_csv(file_src, headers=False, index_cols=False, readCSV=True):
        if readCSV:
            raw_contents = file_src.data['file_contents'][0]

            if len(raw_contents.split(",")) == 1:
                b64_contents = raw_contents
            else:
                # remove the prefix that JS adds
                b64_contents = raw_contents.split(",", 1)[1]
            file_contents = base64.b64decode(b64_contents)
            return pd.read_csv(io.BytesIO(file_contents),
                               encoding="ISO-8859-1",
                               keep_default_na=False,
                               na_values={None},
                               engine='python',
                               index_col=index_cols,
                               header=0 if headers else None)
        return file_src

    def read_parsed_files(file_content, file_name):
        try:
            # remove the prefix that JS adds
            b64_contents = file_content.split(",", 1)[1]
            file_content = base64.b64decode(b64_contents)
            with open(SENTIMENT_OUT / file_name, 'w') as json_file:
                data_dict = json.loads(file_content.decode("utf-8"))
                json.dump(data_dict, json_file)
        except Exception as e:
            print(str(e))

    # pylint: disable=unused-argument
    def train_file_callback(attr, old, new):
        global train_data
        SENTIMENT_OUT.mkdir(parents=True, exist_ok=True)
        train = TrainSentiment(parse=True, rerank_model=None)
        if len(train_src.data['file_contents']) == 1:
            train_data = read_csv(train_src, index_cols=0)
            file_name = train_src.data['file_name'][0]
            raw_data_path = SENTIMENT_OUT / file_name
            train_data.to_csv(raw_data_path, header=False)
            print(f'Running_SentimentTraining on data...')
            train.run(data=raw_data_path)
        else:
            f_contents = train_src.data['file_contents']
            f_names = train_src.data['file_name']
            raw_data_path = SENTIMENT_OUT / train_src.data['file_name'][
                0].split('/')[0]
            if not os.path.exists(raw_data_path):
                os.makedirs(raw_data_path)
            for f_content, f_name in zip(f_contents, f_names):
                read_parsed_files(f_content, f_name)
            print(f'Running_SentimentTraining on data...')
            train.run(parsed_data=raw_data_path)

        text_status.value = "Lexicon extraction completed"

        with io.open(AcquireTerms.acquired_aspect_terms_path, "r") as fp:
            aspect_data_csv = fp.read()
        file_data = base64.b64encode(str.encode(aspect_data_csv))
        file_data = file_data.decode("utf-8")
        asp_src.data = {
            'file_contents': [file_data],
            'file_name': ['nameFile.csv']
        }

        out_path = RerankTerms.out_dir / 'generated_opinion_lex_reranked.csv'
        with io.open(out_path, "r") as fp:
            opinion_data_csv = fp.read()
        file_data = base64.b64encode(str.encode(opinion_data_csv))
        file_data = file_data.decode("utf-8")
        op_src.data = {
            'file_contents': [file_data],
            'file_name': ['nameFile.csv']
        }

    def show_analysis() -> None:
        global stats, aspects, plot, source, tabs
        plot, source = _create_plot()
        events_table = _create_events_table()

        # pylint: disable=unused-argument
        def _events_handler(attr, old, new):
            _update_events(events_table, events_type.active)

        # Toggle display of in-domain / All aspect mentions
        events_type = RadioButtonGroup(
            labels=['All Events', 'In-Domain Events'], active=0)

        analysis_layout = layout([[plot], [events_table]])

        # events_type display toggle disabled
        # analysis_layout = layout([[plot],[events_type],[events_table]])

        analysis_tab = Panel(child=analysis_layout, title="Analysis")
        tabs.tabs.insert(2, analysis_tab)
        tabs.active = 2
        events_type.on_change('active', _events_handler)
        source.selected.on_change('indices', _events_handler)  # pylint: disable=no-member

    # pylint: disable=unused-argument
    def infer_file_callback(attr, old, new):

        # run inference on input data and current aspect/opinion lexicons in view
        global infer_data, stats, aspects

        SENTIMENT_OUT.mkdir(parents=True, exist_ok=True)

        df_aspect = pd.DataFrame.from_dict(asp_filter_src.data)
        aspect_col_list = ['Term', 'Alias1', 'Alias2', 'Alias3']
        df_aspect = df_aspect[aspect_col_list]
        df_aspect.to_csv(SENTIMENT_OUT / 'aspects.csv',
                         index=False,
                         na_rep="NaN")

        df_opinion = pd.DataFrame.from_dict(op_filter_src.data)
        opinion_col_list = ['Term', 'Score', 'Polarity', 'isAcquired']
        df_opinion = df_opinion[opinion_col_list]
        df_opinion.to_csv(SENTIMENT_OUT / 'opinions.csv',
                          index=False,
                          na_rep="NaN")

        solution = SentimentSolution()

        if len(infer_src.data['file_contents']) == 1:
            infer_data = read_csv(infer_src, index_cols=0)
            file_name = infer_src.data['file_name'][0]
            raw_data_path = SENTIMENT_OUT / file_name
            infer_data.to_csv(raw_data_path, header=False)
            print(f'Running_SentimentInference on data...')
            text_status.value = "Running classification on data..."
            stats = solution.run(data=raw_data_path,
                                 aspect_lex=SENTIMENT_OUT / 'aspects.csv',
                                 opinion_lex=SENTIMENT_OUT / 'opinions.csv')
        else:
            f_contents = infer_src.data['file_contents']
            f_names = infer_src.data['file_name']
            raw_data_path = SENTIMENT_OUT / infer_src.data['file_name'][
                0].split('/')[0]
            if not os.path.exists(raw_data_path):
                os.makedirs(raw_data_path)
            for f_content, f_name in zip(f_contents, f_names):
                read_parsed_files(f_content, f_name)
            print(f'Running_SentimentInference on data...')
            text_status.value = "Running classification on data..."
            stats = solution.run(parsed_data=raw_data_path,
                                 aspect_lex=SENTIMENT_OUT / 'aspects.csv',
                                 opinion_lex=SENTIMENT_OUT / 'opinions.csv')

        aspects = pd.read_csv(SENTIMENT_OUT / 'aspects.csv',
                              encoding='utf-8')['Term']
        text_status.value = "Classification completed"
        show_analysis()

    # pylint: disable=unused-argument
    def asp_file_callback(attr, old, new):
        global aspects_data, asp_table_source
        aspects_data = read_csv(asp_src, headers=True)
        # Replaces None values by empty string
        aspects_data = aspects_data.fillna('')
        new_source = ColumnDataSource(aspects_data)
        asp_table_source.data = new_source.data
        asp_table_source.selected.indices = list(range(len(aspects_data)))

    # pylint: disable=unused-argument
    def op_file_callback(attr, old, new):
        global opinions_data, op_table_source, lexicons_dropdown, df_opinion_generic
        df = read_csv(op_src, headers=True)
        # Replaces None values by empty string
        df = df.fillna('')
        # Placeholder for generic opinion lexicons from the given csv file
        df_opinion_generic = df[df['isAcquired'] == 'N']
        # Update the argument value for the callback customJS
        lexicons_dropdown.js_property_callbacks.get(
            'change:value')[0].args['opinion_lex_generic'] \
            = df_opinion_generic.to_dict(orient='list')
        opinions_data = df[df['isAcquired'] == 'Y']
        new_source = ColumnDataSource(opinions_data)
        op_table_source.data = new_source.data
        op_table_source.selected.indices = list(range(len(opinions_data)))

    # pylint: disable=unused-argument
    def txt_status_callback(attr, old, new):
        print("Previous label: " + old)
        print("Updated label: " + new)

    text_status.on_change("value", txt_status_callback)

    asp_src.on_change('data', asp_file_callback)
    # pylint: disable=no-member
    asp_table_source.selected.on_change('indices', asp_selected_change)

    op_src.on_change('data', op_file_callback)
    op_table_source.selected.on_change('indices', op_selected_change)  # pylint: disable=no-member

    train_src.on_change('data', train_file_callback)
    infer_src.on_change('data', infer_file_callback)

    return layout(
        [[_create_header(train_dropdown, inference_dropdown, text_status)],
         [tabs]])
예제 #26
0
def common__account_show():

    # TODO: This needs to be a decorator
    if not session.get('user_id', False): return redirect(COMMON_URL_LOGIN)
    user = User.get_by_id(session['user_id'])
    if user is None or not RolesUsers.user_has_role(user,
                                                    ["ADMIN", "ACCOUNT"]):
        # this should never happen... logout if it does...
        logger.error(
            "Unable to find user id {} or insufficient privileges".format(
                session['user_id']))
        session.pop('user_id', None)
        redirect(COMMON_URL_INDEX)

    users = User.get_username(None, True)
    data = {
        "username": [],
        "lname": [],
        "fname": [],
        "email": [],
        "roles": [],
        "_row_color": [],
    }
    for u in users:
        data["username"].append(u.username)
        data["lname"].append(u.lname)
        data["fname"].append(u.fname)
        data["email"].append(u.email)
        data["roles"].append(",".join([r.name for r in u.roles]))
        data["_row_color"].append(GUI.NOTICES_NORMAL)

    template = """<div style="background:<%=_row_color%>"; color="white";><%= value %></div>"""
    formatter = HTMLTemplateFormatter(template=template)
    hidden_columns = ["_row_color"]
    widths = {
        "username": 100,
        "lname": 100,
        "fname": 100,
        "email": 200,
        "roles": 380,
    }

    source = ColumnDataSource(data)

    columns = []
    for c in source.data.keys():
        if c not in hidden_columns:
            w = widths[c]
            columns.append(
                TableColumn(field=c, title=c, formatter=formatter, width=w))

    data_table = DataTable(source=source,
                           columns=columns,
                           width=900,
                           height=280,
                           fit_columns=False,
                           index_position=None)

    w = WrapBokeh(PAGE_URL, logger)

    w.init()

    # Create a dominate document, see https://github.com/Knio/dominate
    # this line should go after any "return redirect" statements
    w.dominate_document()
    url_page_css(w.dom_doc, PAGE_URL)

    args, _redirect_page_metrics = w.process_req(request)
    #if not args: return _redirect_page_metrics
    logger.info("{} : args {}".format(PAGE_URL, args))

    redir, url = toolbar_menu_redirect(args)
    if redir: return redirect(url)

    doc_layout = layout(sizing_mode='scale_width')
    page_toolbar_menu(w, doc_layout, args, user)

    doc_layout.children.append(data_table)

    return w.render(doc_layout)
예제 #27
0
                    
                    }
                }
            }
            filsource.change.emit();
        """)

    columns = [
        TableColumn(field="n_vote", title="Votes", width=20),
        TableColumn(field="vote",
                    title="Approbation",
                    width=20,
                    formatter=NumberFormatter(format='0.00')),
        TableColumn(field="title",
                    title="Titre",
                    formatter=HTMLTemplateFormatter(
                        template='<div><%= title %></div>')),
        TableColumn(field="body",
                    title="Corps",
                    formatter=HTMLTemplateFormatter(
                        template='<div><%= body %></div>')),
    ]

    p2 = DataTable(source=s2, columns=columns, width=1200)
    #    p2= DataTable(source=s2, columns=columns, width=wi, height=400)

    end_slider = max(df.n_vote)
    nvote_slider = Slider(start=0,
                          end=end_slider,
                          value=0,
                          step=10,
                          title="Nombre de votes minimum",
예제 #28
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"
예제 #29
0
def get_changed_parameters(ulog, plot_width):
    """
    get a bokeh column object with a table of the changed parameters
    :param initial_parameters: ulog.initial_parameters
    """
    param_names = []
    param_values = []
    param_defaults = []
    param_mins = []
    param_maxs = []
    param_descriptions = []
    param_colors = []
    default_params = get_default_parameters()
    initial_parameters = ulog.initial_parameters
    system_defaults = None
    airframe_defaults = None
    if ulog.has_default_parameters:
        system_defaults = ulog.get_default_parameters(0)
        airframe_defaults = ulog.get_default_parameters(1)

    for param_name in sorted(initial_parameters):
        param_value = initial_parameters[param_name]

        if param_name.startswith('RC') or param_name.startswith('CAL_'):
            continue

        system_default = None
        airframe_default = None
        is_airframe_default = True
        if system_defaults is not None:
            system_default = system_defaults.get(param_name, param_value)
        if airframe_defaults is not None:
            airframe_default = airframe_defaults.get(param_name, param_value)
            is_airframe_default = abs(
                float(airframe_default) - float(param_value)) < 0.00001

        try:
            if param_name in default_params:
                default_param = default_params[param_name]
                if system_default is None:
                    system_default = default_param['default']
                    airframe_default = default_param['default']
                if default_param['type'] == 'FLOAT':
                    is_default = abs(
                        float(system_default) - float(param_value)) < 0.00001
                    if 'decimal' in default_param:
                        param_value = round(param_value,
                                            int(default_param['decimal']))
                        airframe_default = round(float(airframe_default), int(default_param['decimal']))  #pylint: disable=line-too-long
                else:
                    is_default = int(system_default) == int(param_value)
                if not is_default:
                    param_names.append(param_name)
                    param_values.append(param_value)
                    param_defaults.append(airframe_default)
                    param_mins.append(default_param.get('min', ''))
                    param_maxs.append(default_param.get('max', ''))
                    param_descriptions.append(
                        default_param.get('short_desc', ''))
                    param_colors.append(
                        'black' if is_airframe_default else plot_color_red)
            else:
                # not found: add it as if it were changed
                param_names.append(param_name)
                param_values.append(param_value)
                param_defaults.append(
                    airframe_default if airframe_default else '')
                param_mins.append('')
                param_maxs.append('')
                param_descriptions.append('(unknown)')
                param_colors.append(
                    'black' if is_airframe_default else plot_color_red)
        except Exception as error:
            print(type(error), error)
    param_data = dict(names=param_names,
                      values=param_values,
                      defaults=param_defaults,
                      mins=param_mins,
                      maxs=param_maxs,
                      descriptions=param_descriptions,
                      colors=param_colors)
    source = ColumnDataSource(param_data)
    formatter = HTMLTemplateFormatter(
        template='<font color="<%= colors %>"><%= value %></font>')
    columns = [
        TableColumn(field="names",
                    title="Name",
                    width=int(plot_width * 0.2),
                    sortable=False),
        TableColumn(field="values",
                    title="Value",
                    width=int(plot_width * 0.15),
                    sortable=False,
                    formatter=formatter),
        TableColumn(field="defaults",
                    title="Frame Default" if airframe_defaults else "Default",
                    width=int(plot_width * 0.1),
                    sortable=False),
        TableColumn(field="mins",
                    title="Min",
                    width=int(plot_width * 0.075),
                    sortable=False),
        TableColumn(field="maxs",
                    title="Max",
                    width=int(plot_width * 0.075),
                    sortable=False),
        TableColumn(field="descriptions",
                    title="Description",
                    width=int(plot_width * 0.40),
                    sortable=False),
    ]
    data_table = DataTable(source=source,
                           columns=columns,
                           width=plot_width,
                           height=300,
                           sortable=False,
                           selectable=False,
                           autosize_mode='none')
    div = Div(
        text=
        """<b>Non-default Parameters</b> (except RC and sensor calibration)""",
        width=int(plot_width / 2))
    return column(div, data_table, width=plot_width)
예제 #30
0
파일: main.py 프로젝트: nhdr2020/bihmap
    def __init__(self, data):
        self.map_data = data
        p_wgs84 = pyproj.Proj(init='epsg:4326')
        p_web = pyproj.Proj(init='epsg:3857')

        self.map_data.shape_country['geometry'] = self.map_data.shape_country['geometry'].to_crs(epsg=3857)
        self.country_source = GeoJSONDataSource(
            geojson=self.map_data.shape_country.to_json()
        )
        self.priority_toggles = {}
        self.priority_groups = {}
        self.priority_groups_rect = {}

        self.priority_names = {
            10: 'High',
            20: 'Medium',
            30: 'Low'
        }

        self.map_width = 800
        self.map_height = 800

        tooltips_map = [
            ("Name", "@names"),
            ("POI", "@categories"),
        ]
        hover_map = HoverTool(tooltips=tooltips_map,
                              mode='mouse',
                              names=['marker']
                              )
        plot_options_map = dict(plot_height=self.map_height,
                                plot_width=self.map_width,
                                tools=["pan,wheel_zoom,reset,save", hover_map],
                                sizing_mode="fixed",
                                toolbar_location='above',
                                title='BiH'
                                )
        self.figure_map = figure(**plot_options_map)
        self.figure_map.xgrid.grid_line_color = None
        self.figure_map.ygrid.grid_line_color = None
        self.figure_map.xaxis.visible = False
        self.figure_map.yaxis.visible = False

        tile_provider = get_provider(Vendors.CARTODBPOSITRON)
        self.figure_map.add_tile(tile_provider)

        self.figure_map.multi_line('xs', 'ys',
                                   source=self.country_source,
                                   color='red',
                                   line_width=3
                                   )

        for shape in self.map_data.shape_municipalities:
            shape['geometry'] = shape['geometry'].to_crs(epsg=3857)
            source = GeoJSONDataSource(
                geojson=shape.to_json()
            )
            self.figure_map.patches('xs', 'ys',
                                    source=source,
                                    line_color='green',
                                    color='navy',
                                    alpha=0.1,
                                    line_width=2)

        for priority in map_data.priorities:
            df = self.map_data.data.loc[self.map_data.data['priority'] == priority]
            urls = ['BiH/static/symbols/' + str(icon) + '.png' for icon in df['icon'].tolist()]
            x = df['longitude'].tolist()
            y = df['latitude'].tolist()
            names = df['name'].tolist()

            categories = df['category'].tolist()

            x, y = pyproj.transform(p_wgs84, p_web, x, y)
            w = [32 for i in range(len(x))]
            h = [37 for i in range(len(x))]

            source_marker = ColumnDataSource(data={
                'urls': urls,
                'x': x,
                'y': y,
                'w': w,
                'h': h
            })
            self.priority_groups[priority] = self.figure_map.image_url(url='urls',
                                                                       x='x',
                                                                       y='y',
                                                                       w='w',
                                                                       h='h',
                                                                       h_units='screen',
                                                                       w_units='screen',
                                                                       anchor='center',
                                                                       source=source_marker)

            source_tooltip = ColumnDataSource(data={
                'x': x,
                'y': y,
                'names': names,
                'categories': categories,
                'w': w,
                'h': h
            })
            self.priority_groups_rect[priority] = self.figure_map.rect(
                x='x',
                y='y',
                width='w',
                height='h',
                fill_alpha=0,
                line_alpha=0,
                height_units='screen',
                width_units='screen',
                name='marker',
                source=source_tooltip)

        self.table_source = ColumnDataSource(data={
            'category': self.map_data.categories['category'],
            'icon': self.map_data.categories['icon'],
            'priority': self.map_data.categories['priority'],
            'priority_names': [self.priority_names[p] for p in self.map_data.categories['priority']]
        })
        columns = [TableColumn(field="icon",
                               title="Icon",
                               width=40,
                               formatter=HTMLTemplateFormatter(
                                   template='<img src="BiH/static/symbols/<%= value %>.png" height="37" width="32">'
                               )),
                   TableColumn(field="category", title="Category", width=180,
                               formatter=HTMLTemplateFormatter(
                                   template='<div style="position:relative;top:6px;font-size:12px;"><%= value %></div>'
                               )),
                   TableColumn(field="priority_names",
                               title="Priority",
                               width=80,
                               formatter=HTMLTemplateFormatter(
                                   template='<div style="position:relative;top:6px;font-size:12px;"><%= value %></div>'
                               )
                               )]

        data_view = CDSView(source=self.table_source, filters=[])

        self.table = DataTable(columns=columns,
                               source=self.table_source,
                               view=data_view,
                               sizing_mode='stretch_height',
                               index_position=None,
                               fit_columns=True,
                               width=300,
                               row_height=38,
                               selectable=False)

        for priority in self.map_data.priorities:
            toggle = Toggle(label=self.priority_names[priority], button_type='success', width=48)
            toggle.on_change("active", update_table)
            self.priority_toggles[priority] = toggle