예제 #1
0
파일: main.py 프로젝트: desihub/desilo
    def __init__(self):
        Report.__init__(self, 'OS')

        self.title = Div(
            text="DESI Nightly Intake - Observing Scientist",
            css_classes=['h1-title-style'],
            width=1000
        )  # width=800, style={'font-size':'24pt','font-style':'bold'})
        desc = """
        To begin, connect to the observing night Night Log using the list of Existing Night Logs. Add information about the Observers and press the 
        Update Tonight's Log. 
        Throughout the night, enter information about the exposures, problems that occur, and observing conditions. Complete the 
        OS Checklist at least once every hour. NOTE: If inputs are being made into a DNI for the OS at both KPNO and NERSC, the inputs
        made at KPNO for certain things (meta data, plan, milestones), will be prioritized over those made at NERSC.
        """
        self.instructions = Div(text=desc,
                                css_classes=['inst-style'],
                                width=500)

        self.page_logo = Div(text="<img src='OS_Report/static/logo.png'>",
                             width=350,
                             height=300)

        self.os_checklist = [
            "Did you check the weather?", "Did you check the guiding?",
            "Did you check the positioner temperatures?",
            "Did you check the FXC?",
            "Did you check the Spectrograph Cryostat?",
            "Did you check the FP Chiller?"
        ]
예제 #2
0
    def __init__(self):
        Report.__init__(self, 'DQS')

        self.title = Div(text="DESI Nightly Intake - Data QA Scientist",
                         css_classes=['h1-title-style'],
                         width=1000)
        inst = """
        The Data Quality Scientist (DQS) is responsible for analyzing all exposures for their quality.
        Submit problems as they arise throughout the night and complete the DQS checklist once an hour. Let the Lead Observer
        know if you encounter any issues. 
        """
        self.instructions = Div(text=inst,
                                css_classes=['inst-style'],
                                width=500)
        self.page_logo = Div(text="<img src='DQS_Report/static/logo.png'>",
                             width=350,
                             height=300)

        self.dqs_checklist = [
            "Are all images being transferred to Night Watch?",
            "Did you check the observing conditions?",
            "Did you check the guiding?"
        ]

        self.quality_list = ['Good', 'Not Sure', 'No Data', 'Bad']
        self.quality_btns = RadioButtonGroup(labels=self.quality_list,
                                             active=0)
예제 #3
0
파일: main_kh.py 프로젝트: desihub/desilo
 def plan_tab(self):
     self.plan_subtitle = Div(text="Night Plan", css_classes=['subt-style'])
     self.plan_inst = Div(text="Input the major elements of the Night Plan found at the link below in the order expected for their completion.", css_classes=['inst-style'], width=1000)
     self.plan_txt = Div(text='<a href="https://desi.lbl.gov/trac/wiki/DESIOperations/ObservingPlans/">Tonights Plan Here</a>', css_classes=['inst-style'], width=500)
     self.plan_order = TextInput(title ='Expected Order:', placeholder='1', value=None)
     self.plan_input = TextAreaInput(placeholder="description", rows=8, cols=3, title="Describe item of the night plan:",max_length=5000)
     self.plan_btn = Button(label='Add', css_classes=['add_button'])
     self.plan_alert = Div(text=' ', css_classes=['alert-style'])
    def __init__(self):
        # add a dummy element that will trigger the event for enabling/disabling the loading spinner
        self._loader_trigger = Div(text="1", visible=False)
        self._callback = CustomJS(code="")
        self._loader_trigger.js_on_change('text', self._callback)
        self._enabled = True

        self.layout = column(self._loader_trigger, name="loaderTrigger")
예제 #5
0
    def on_lvl_select(self, attr, old, new):
        """
        Callback for ``self.lvl_select``. The method re-searches the available geojson's and sets
        the options of ``self.id_select`` to the newly selected level, while trying to remain in the
        same dataset. If the dataset is not in the selected NUTS level, the selected and displayed
        dataset is changed.

        This method triggers a redraw of the map and the observation plot.

        :param attr: attribute that triggered this callback
        :param old: the old value of the attribute
        :param new: the new value of the attribute
        """
        eurostats = self.get_eurostats_geojson_list()

        # collect ID by level
        self.set_available_ids()
        old_selection = self.id_select.value
        self.id_select.options = self.available_ids[new]

        if old_selection in self.available_ids[new]:
            self.id_select.value = old_selection

        # TODO: Check empty cases!!
        if new == 'Custom':
            self.current_dataset = gpd.GeoDataFrame.from_file(
                self.dataset_path_custom_prefix + self.id_select.value + ".geojson")
        else:
            self.current_dataset = gpd.GeoDataFrame.from_file(
                self.dataset_path_prefix + "nuts_" + new[-1] + "/" + self.id_select.value + ".geojson")
        self.update_datasource(self.current_map_CDS, self.current_dataset, new, self.id_select.value, 10)

        style = {"font-size": "20px"}
        unit = self.current_map_CDS.data['unit'][0]
        mean = np.mean(self.current_map_CDS.data['observation'])
        deviation = np.std(self.current_map_CDS.data['observation'])

        p_mean_title = Div(text="Mean:", style=style)
        p_mean_value = Div(text="{:10,.3} {}".format(mean, unit), style=style)

        p_deviation_title = Paragraph(text="Standard Deviation:", style=style)
        p_deviation_value = Paragraph(text="{:10,.3} {}".format(deviation, unit), style=style)

        hist, edges = np.histogram(
            self.current_map_CDS.data['observation'],
            density=True,
            bins=30)
        p2 = figure(height=300)
        p2.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], color=PuBu[7][2])

        self.layout.children[2] = column(
            row(p_mean_title, p_mean_value),
            row(p_deviation_title, p_deviation_value),
            Spacer(height=46),
            p2,
            width=500)
예제 #6
0
파일: main.py 프로젝트: desihub/desilo
    def __init__(self):
        Report.__init__(self, 'Other')

        self.title = Div(text="DESI Nightly Intake Form - Non Observer",css_classes=['h1-title-style'], width=1000)
        desc = """This Night Log is for Non-Observers. It should mainly be used for observing the ongoing Night Log.
        In special circumstances, if a non-observer has an important comment about an exposure or problem, it can be added here.
        Before doing so, make sure to communicate with the Observing Scientist.
        """
        self.instructions = Div(text=desc+self.time_note.text, css_classes=['inst_style'], width=500)
        self.page_logo = Div(text="<img src='Other_Report/static/logo.png'>", width=350, height=300)
예제 #7
0
파일: main_kh.py 프로젝트: desihub/desilo
    def __init__(self):
        Report.__init__(self, 'OS')

        self.title = Div(text="DESI Nightly Intake - Operating Scientist", css_classes=['h1-title-style'], width=1000)# width=800, style={'font-size':'24pt','font-style':'bold'})
        desc = """
        The Operating Scientist (OS) is responsible for initializing the Night Log. Connect to an existing Night Log using the date or initialize tonight's log.
        Throughout the night, enter information about the exposures, weather, and problems. Complete the OS Checklist at least once every hour.
        """
        self.instructions = Div(text=desc+self.time_note.text, css_classes=['inst-style'], width=500)
        self.line = Div(text='-----------------------------------------------------------------------------------------------------------------------------', width=1000)
        self.line2 = Div(text='-----------------------------------------------------------------------------------------------------------------------------', width=1000)
        self.init_bt = Button(label="Initialize Tonight's Log", css_classes=['init_button'])
        self.LO = Select(title='Lead Observer', value='Choose One', options=self.lo_names)
        self.OA = Select(title='Observing Assistant', value='Choose One', options=self.oa_names)
        self.page_logo = Div(text="<img src='OS_Report/static/logo.png'>", width=350, height=300)

        self.contributer_list = TextAreaInput(placeholder='Contributer names (include all)', rows=2, cols=3, title='Names of all Contributers')
        self.contributer_btn = Button(label='Update Contributer List', css_classes=['add_button'], width=300)

        self.connect_hdr = Div(text="Connect to Existing Night Log", css_classes=['subt-style'], width=800)
        self.init_hdr = Div(text="Initialize Tonight's Night Log", css_classes=['subt-style'], width=800)
        self.check_subtitle = Div(text="OS Checklist", css_classes=['subt-style'])
        self.checklist_inst = Div(text="Every hour, the OS is expected to monitor several things. After completing these tasks, record at what time they were completed. Be honest please!", css_classes=['inst-style'], width=1000)
        self.checklist.labels = ["Did you check the weather?", "Did you check the guiding?", "Did you check the positioner temperatures?","Did you check the FXC?", "Did you check the Cryostat?", "Did you do a connectivity aliveness check?","Did you check the Spectrograph Chiller?"]

        self.nl_submit_btn = Button(label='Submit NightLog & Publish Nightsum', width=300, css_classes=['add_button'])
        self.header_options = ['Startup','Calibration (Arcs/Twilight)','Focus','Observation','Other Acquisition','Comment']
예제 #8
0
파일: main_kh.py 프로젝트: desihub/desilo
 def milestone_tab(self):
     self.milestone_subtitle = Div(text="Milestones & Major Accomplishments", css_classes=['subt-style'])
     self.milestone_inst = Div(text="Record any major milestones or accomplishments that occur throughout a night and the exposure numbers that correspond to it. If applicable, indicate the ID of exposures to ignore in a series.", css_classes=['inst-style'],width=1000)
     self.milestone_input = TextAreaInput(placeholder="Description", rows=10, cols=3, max_length=5000)
     self.milestone_exp_start = TextInput(title ='Exposure Start', placeholder='12345', value=None)
     self.milestone_exp_end = TextInput(title='Exposure End', placeholder='12345', value=None)
     self.milestone_exp_excl = TextInput(title='Excluded Exposures', placeholder='12346', value=None)
     self.milestone_btn = Button(label='Add Milestone', css_classes=['add_button'])
     self.milestone_alert = Div(text=' ', css_classes=['alert-style'])
     self.summary = TextAreaInput(rows=6, title='End of Night Summary',max_length=5000)
     self.summary_btn = Button(label='Add Summary', css_classes=['add_button'], width=300)
예제 #9
0
 def set_layout(self, doc):
     env = Environment(loader=FileSystemLoader('templates'))
     template = env.get_template('frameing.html')
     doc.template = template;
     
     user_str = doc.session_context.id
     layout = row([Div(), Div(), Div()], width=1700)
     # menu
     doc.template_variables["menu"] = self._menu
     print(self._menu)
     doc.add_root(layout)
     return layout
예제 #10
0
파일: main_kh.py 프로젝트: desihub/desilo
    def exp_tab(self):
        self.exp_subtitle = Div(text="Nightly Progress", css_classes=['subt-style'])
        self.exp_inst = Div(text="Throughout the night record the progress, including comments on Calibrations and Exposures. All exposures are recorded in the eLog, so only enter information that can provide additional information.", width=800, css_classes=['inst-style'])
        self.hdr_type = Select(title="Observation Type", value='Observation', options=self.header_options)
        self.hdr_btn = Button(label='Select', css_classes=['add_button'])

        self.add_image = TextInput(title="Add Image", placeholder='Pictures/image.png', value=None)

        self.exp_script = TextInput(title='Script Name', placeholder='dithering.json', value=None)
        self.exp_time_end = TextInput(title='Time End', placeholder='20:07', value=None)
        self.exp_focus_trim = TextInput(title='Trim from Focus', placeholder='54', value=None)
        self.exp_tile = TextInput(title='Tile Number', placeholder='68001', value=None)
        self.exp_tile_type = Select(title="Tile Type", value=None, options=['None','QSO','LRG','ELG','BGS','MW'])
        self.exp_input_layout = layout([])
예제 #11
0
    def draw(self):
        try:

            referenceLayout = self.createReferenceLayout()
            peakPickingLayout = self.createPeakPickingLayout()
            integrationLayout = self.createIntegrationLayout()
            multipletManagerLayout = self.createMultipletManagerLayout()

            referenceTab = Panel(child=referenceLayout, title="Reference")
            peakPickingTab = Panel(child=peakPickingLayout,
                                   title="Peak Picking")
            integrationTab = Panel(child=integrationLayout,
                                   title="Integration")
            multipletAnalysisTab = Panel(child=multipletManagerLayout,
                                         title="Multiplet Analysis")

            tabs = self.createTabs([
                referenceTab, peakPickingTab, integrationTab,
                multipletAnalysisTab
            ])

            curdoc().add_root(
                row(
                    column(
                        row(self.plot),
                        row(Div(text=self.compound, id="compoundContainer"))),
                    column(row(tabs))))
            curdoc().title = "NMR Analysis Tool - " + str(self.id)
        except NameError:
            print("Please create plot first")
예제 #12
0
    def create_display(self):
        """Create a display of the data. The display returned is a Boekh row with a
        data table on the left and a bar chart on the right. This may be displayed with
        Bokeh show().
        """
        # Create Bokeh datatable from self._display_data df
        # bokeh columns
        source = ColumnDataSource(self._df)
        Columns = [
            TableColumn(field=f, title=t)
            for f, t in zip(self._df.columns, self._column_display_names)
            if t is not None
        ]
        data_table = DataTable(columns=Columns,
                               source=source,
                               min_height=500,
                               height_policy='auto',
                               index_position=None,
                               scroll_to_selection=True)  # bokeh table

        # Create and display bar chart
        fig = self._create_plot(
            x_range=list(self._df[self._x_major_name].unique()),
            s_data=source,
            x_minor_values=self._df[self._x_minor_name].unique(),
            colors=self._colors,
            chart_title=None,
            x_title=self._x_title,
            y_title=self._y_title)
        fig.min_border_left = 60
        msg = Div(text='<h4>{}</h4>'.format(self._title))
        r = layout([[msg], [data_table, fig]], sizing_mode='stretch_both')

        return r
예제 #13
0
파일: plot.py 프로젝트: henryrobbins/vinal
def _get_create_divs(plot: Figure,
                     cost_txt: str = '0.0',
                     click_txt: str = '[]') -> Tuple[Div]:
    """Return the Divs shown by plots in which a tour or tree is created.

    Args:
        plot (Figure): The plot to which these Divs are added.
        cost_text (str, optional): Current cost of solution. Defaults to '0.0'.
        clicked_text (str, optional): Clicked objects. Defaults to '[]'.
    """
    cost = Div(text=cost_txt, width=int(plot.plot_width / 3), align='center')
    clicked = Div(text=click_txt,
                  width=int(plot.plot_width / 3),
                  align='center')
    error_msg = Div(text='', width=int(plot.plot_width / 3), align='center')
    return (cost, clicked, error_msg)
예제 #14
0
    def _init_sample_buttons(self):
        lg.info('-- SET SAMPLE BUTTONS')

        def next_sample():
            lg.info('>> NEXT SAMPLE')
            if self.s < self.ns:
                self.env.doc.hold('collect')
                self.s += 1
                self.sample_div.text = ' {} / {}'.format(self.s, self.ns)
                self.env.cur_nearby_prof = None  # to reset the extra stt profile to plot
                self.env.dt_next_sample = True
                self._update_dt_sample()
                self.env.doc.unhold()

        def previous_sample():
            lg.info('>> PREVIOUS SAMPLE')
            if self.s > 1:
                self.env.doc.hold('collect')
                self.s -= 1
                self.sample_div.text = ' {} / {}'.format(self.s, self.ns)
                self.env.cur_nearby_prof = None
                self.env.dt_previous_sample = True
                self._update_dt_sample()
                self.env.doc.unhold()

        self.next_bt = Button(label=">", button_type="success", width=30)
        self.sample_div = Div(
            text='0 / 0',
            width=100,
            height=30,
            css_classes=['sample_div'],
        )
        self.previous_bt = Button(label="<", button_type="success", width=30)
        self.next_bt.on_click(next_sample)
        self.previous_bt.on_click(previous_sample)
    def debug_div(self):
        from bokeh.models.widgets.markups import Div

        if self._debug_div is None:
            self._debug_div = Div(text='', width=300, height=100)

        return self._debug_div
    def cursor(self, values):
        from bokeh.models.widgets.markups import Div

        if self._cursor_dims is None:
            try:
                self._cursor_dims = list(self.arr.dims)
            except AttributeError:
                pass

        self._cursor = values
        if self._cursor_info is None:
            self._cursor_info = Div(text='')
            self._horiz_cursor_x = list(self.data_range['x'])
            self._horiz_cursor_y = [0, 0]
            self._vert_cursor_x = [0, 0]
            self._vert_cursor_y = list(self.data_range['y'])
        else:
            self._vert_cursor_x[0] = self._vert_cursor_x[1] = self.cursor[0]
            self._horiz_cursor_y[0] = self._horiz_cursor_y[1] = self.cursor[1]

        self._cursor_info.text = '<h2>Cursor:</h2><span>({})</span>'.format(
            ', '.join("{0:.3f}".format(c) for c in self.cursor))

        if self._cursor_lines is not None:
            self._cursor_lines.data_source.data = {
                'xs': [self._horiz_cursor_x, self._vert_cursor_x],
                'ys': [self._horiz_cursor_y, self._vert_cursor_y],
            }

        try:
            self.app_context['cursor_dict'] = dict(
                zip(self._cursor_dims, self.cursor))
            #self.app_context['full_cursor'] =
        except AttributeError:
            pass
예제 #17
0
    def _init_profile_nav(self):
        def next_profile():
            if self.nearby_prof_cb:
                lg.info('-- NEXT PROFILE')
                s = self.env.stations
                next_pos = s.index(self.env.cur_nearby_prof) + 1
                if next_pos < len(self.env.stations):
                    if s[next_pos] == self.env.stt_to_select:
                        next_pos = next_pos + 1
                if next_pos < len(self.env.stations):
                    self.env.cur_nearby_prof = s[next_pos]
                    self.env.bk_sources._upd_prof_srcs(force_selection=True)
                    self.nearby_prof_div.text = str(
                        int(self.env.cur_nearby_prof))

                    # adjust disabled buttons
                    if next_pos + 1 == len(self.env.stations):
                        self.next_prof_bt.disabled = True
                    self.previous_prof_bt.disabled = False

        def previous_profile():
            lg.info('-- PREVIOUS PROFILE')
            if self.nearby_prof_cb:
                s = self.env.stations
                previous_pos = s.index(self.env.cur_nearby_prof) - 1
                if previous_pos >= 0:
                    if s[previous_pos] == self.env.stt_to_select:
                        previous_pos = previous_pos - 1
                if previous_pos >= 0:
                    self.env.cur_nearby_prof = s[previous_pos]
                    self.env.bk_sources._upd_prof_srcs(force_selection=True)
                    self.nearby_prof_div.text = str(
                        int(self.env.cur_nearby_prof))

                    # adjust disabled buttons
                    if previous_pos == 0:
                        self.previous_prof_bt.disabled = True
                    self.next_prof_bt.disabled = False

        self.next_prof_bt = Button(
            width=30,
            disabled=True,
            label=">",
            button_type="success",
        )
        self.nearby_prof_div = Div(
            width=100,
            height=30,
            text='None',
            css_classes=['cur_stt'],
        )
        self.previous_prof_bt = Button(
            width=30,
            disabled=True,
            label="<",
            button_type="success",
        )
        self.next_prof_bt.on_click(next_profile)
        self.previous_prof_bt.on_click(previous_profile)
예제 #18
0
def test_get_screenshot_as_png_with_unicode_unminified(webdriver):
    layout = Div(text="유니 코드 지원을위한 작은 테스트")

    png = bie.get_screenshot_as_png(layout,
                                    driver=webdriver,
                                    resources=Resources(mode="inline",
                                                        minified=False))
    assert len(png.tobytes()) > 0
예제 #19
0
    def _init_flags_control_header(self):
        lg.info('-- FLAGS CONTROL HEADER')
        self.all_flags_vb_bt = Button(
            name='all_flags_bt',
            label='',
            width=30,
            css_classes=['eye_bt'],
        )

        def all_flags_vb_bt_callback():
            lg.info('-- ALL FLAGS VISIBLE CALLBACK')
            self.env.bk_bridge.call_js({
                'object': 'tools',
                'function': 'show_wait_cursor',
            })
            all_flags_bt = self.env.doc.select_one(dict(name='all_flags_bt'))
            eye_slash_bt = True if 'eye_slash_bt' in all_flags_bt.css_classes else False
            if eye_slash_bt:
                self.env.doc.set_select(selector=dict(tags=['vb_bt']),
                                        updates=dict(css_classes=['eye_bt']))
            else:
                self.env.doc.set_select(
                    selector=dict(tags=['vb_bt']),
                    updates=dict(css_classes=['eye_slash_bt']))

            new_visible_flags = []
            if 'eye_bt' in all_flags_bt.css_classes:
                all_flags_bt.css_classes = ['eye_slash_bt']
            else:
                new_visible_flags = self.all_flags_list
                all_flags_bt.css_classes = ['eye_bt']
            lg.info('>> NEW VISIBLE FLAGS: {}'.format(new_visible_flags))
            self._update_visible_flags(new_visible_flags)
            self.env.bk_bridge.call_js({
                'object': 'tools',
                'function': 'show_default_cursor',
            })

        self.all_flags_vb_bt.on_click(all_flags_vb_bt_callback)

        # TODO: replace this div with the flag selection dropdown
        #       or maybe there would be too many control on one place

        flag_controls_title_div = Div(
            name='flag_controls_title',
            text='All the flags',
            width=100,
            height=25,
            css_classes=['flag_controls_title'],
        )

        self.flags_control_header_row = row(
            children=[self.all_flags_vb_bt, flag_controls_title_div],
            width=200,
            height=25,
        )
예제 #20
0
파일: main_kh.py 프로젝트: desihub/desilo
    def weather_tab(self):
        data = pd.DataFrame(columns = ['time','desc','temp','wind','humidity'])
        self.weather_source = ColumnDataSource(data)

        self.weather_subtitle = Div(text="Weather", css_classes=['subt-style'])

        columns = [TableColumn(field='time', title='Time (local)', width=75),
                   TableColumn(field='desc', title='Description', width=200, editor=StringEditor()),
                   TableColumn(field='temp', title='Temperature (C)', width=100, editor=NumberEditor()),
                   TableColumn(field='wind', title='Wind Speed (mph)', width=120, editor=NumberEditor()),
                   TableColumn(field='humidity', title='Humidity (%)', width=100, editor=PercentEditor())]
        self.weather_inst = Div(text="Every hour include a description of the weather and any other relevant information, as well as fill in all the fields below.  Click the Update Night Log button after every hour's entry. To update a cell: double click in it, record the information, click out of the cell.", width=1000, css_classes=['inst-style'])
        self.weather_time = TextInput(placeholder='17:00', value=None, width=100) #title='Time in Kitt Peak local time', 
        self.weather_desc = TextInput(title='Description', placeholder='description', value=None)
        self.weather_temp = TextInput(title='Temperature (C)', placeholder='50', value=None)
        self.weather_wind = TextInput(title='Wind Speed (mph)', placeholder='10', value=None)
        self.weather_humidity = TextInput(title='Humidity (%)', placeholder='5', value=None)
        self.weather_table = DataTable(source=self.weather_source, columns=columns)
        self.weather_btn = Button(label='Add Weather', css_classes=['add_button'])
예제 #21
0
def create_explainer(color_dict, ent_dict):

    explainer = """<b>Left:</b> Both BERT and spaCy found this entity <br>
        <b>Right:</b> Only one of BERT or spaCy found this entity <br><br>"""

    for ent_type in ent_dict:
        dark, light = color_dict[ent_dict[ent_type]]
        ent_html = f"""<b><span style="color: {dark}">{ent_type}</span>
        <span style="color: {light}">{ent_type}</span></b><br>"""
        explainer += ent_html

    return Div(text=explainer, width=500)
예제 #22
0
파일: app.py 프로젝트: wplohrmann/projects
def get_recording_info(path_to_recording):
    data, samplerate = sf.read(path_to_recording)
    nperseg = int(samplerate * 20e-3) # 20ms
    f, t, spectrogram = signal.spectrogram(data, samplerate, nperseg=nperseg)
    spectrogram  = np.log(spectrogram+1e-9)
    print(spectrogram)
    p = figure()
    div = Div(text=f"<h3>{path_to_recording}<h3>")
    p.image(image=[spectrogram], x=0, y=0, dw=t[1]-t[0], dh=f[1]-f[0], palette=Inferno[256])

    return column(div, p)

    print("hello")
예제 #23
0
def test_get_screenshot_as_png_with_unicode_unminified():
    layout = Div(text="유니 코드 지원을위한 작은 테스트")

    driver = create_webdriver()
    try:
        png = bie.get_screenshot_as_png(layout,
                                        driver=driver,
                                        resources=Resources(mode="inline",
                                                            minified=False))
    finally:
        # Have to manually clean up the driver session
        terminate_webdriver(driver)
    assert len(png.tobytes()) > 0
예제 #24
0
파일: plot.py 프로젝트: henryrobbins/vinal
def _graph_plot(G: nx.Graph,
                edges: List[Tuple[int]],
                cost: float = None,
                show_all_edges: bool = True,
                show_labels: bool = True,
                **kw) -> GridBox:
    """Return a plot of the graph G with given edges highlighted.

    Args:
        G (nx.Graph): Graph to be plotted.
        edges (List[Tuple[int]]): Edges to be highlighted.
        cost (float, optional): Cost to be displayed. Defaults to None.
        show_all_edges (bool, optional): True iff all edges should be shown.
        show_labels (bool, optional): True iff labels should be shown.

    Returns:
        GridBox: Plot of the graph G with given edges highlighted.
    """
    G = G.copy()
    plot = _blank_plot(G, **kw)

    _set_edge_positions(G)
    _set_graph_colors(G)

    nodes_src, nodes_glyph = _add_nodes(G, plot)
    if show_all_edges:
        edges_src, edges_glyph = _add_edges(G, plot, show_labels=show_labels)

    if len(edges) > 0:
        xs, ys = _edge_positions(G, edges)
        plot.multi_line(xs=xs,
                        ys=ys,
                        line_cap='round',
                        line_width=LINE_WIDTH,
                        line_color=TERTIARY_DARK_COLOR,
                        level=EDGE_LEVEL)

    cost_txt = '' if cost is None else ('%.1f' % cost)
    cost = Div(text=cost_txt, width=int(plot.plot_width / 2), align='center')

    plot.add_tools(
        HoverTool(tooltips=[("Index", "$index"), ("Name", "@name")],
                  renderers=[nodes_glyph]))
    grid = gridplot([[plot], [row(cost)]],
                    plot_width=plot.plot_width,
                    plot_height=plot.plot_height,
                    toolbar_location=None,
                    toolbar_options={'logo': None})

    return grid
예제 #25
0
파일: app.py 프로젝트: wplohrmann/projects
def get_species_table(metadata, labels):
    species_info = {x["primary_label"]:x["common_name"] for i, x in metadata.drop_duplicates("primary_label").iterrows()}

    source = ColumnDataSource({"primary_label": list(species_info.keys()), "common_name": list(species_info.values())})

    columns = [
            TableColumn(field="primary_label", title="Label"),
            TableColumn(field="common_name", title="Common name"),
            ]

    div = Div(text=f"<h3>All species in short-audio train set<h3>")
    table = DataTable(source=source, columns=columns)

    return column(div, table)
예제 #26
0
파일: app.py 프로젝트: wplohrmann/projects
def get_recordings_table(metadata, label):
    recordings = os.listdir(os.path.join(short_audio_path, label))
    data = metadata[metadata["primary_label"]==label]
    source = ColumnDataSource(data)
    columns = [
            TableColumn(field="filename", title="Filename"),
            TableColumn(field="rating", title="Rating"),
            TableColumn(field="time", title="Time"),
            TableColumn(field="secondary_labels", title="Other birds")
            ]
    div = Div(text=f"<h3>Recordings for {label}<h3>")
    table = DataTable(source=source, columns=columns)


    return column(div, table)
class LoadingSpinner:
    def __init__(self):
        # add a dummy element that will trigger the event for enabling/disabling the loading spinner
        self._loader_trigger = Div(text="1", visible=False)
        self._callback = CustomJS(code="")
        self._loader_trigger.js_on_change('text', self._callback)
        self._enabled = True

        self.layout = column(self._loader_trigger, name="loaderTrigger")

    @property
    def enabled(self):
        return self._enabled

    @enabled.setter
    def enabled(self, value: bool):
        """enable/disable loading mode """
        self._enabled = value
        visibility = 'visible' if value else 'hidden'
        self._callback.code = f"""
            document.getElementById('loadingSpinnerInvoker').style.visibility = '{visibility}';
        """
        logger.debug(f"Loading spinner is {visibility}")
        self._loader_trigger.text = str(int(self._loader_trigger.text) + 1)
예제 #28
0
    def refresh_plots(self):
        """Main function used to create all plots."""
        zipcode = Select(
            title="Postnummer:",
            value=self.selected_zipcode,
            options=self.zipcodes,
        )
        zipcode.on_change(
            'value',
            self.zipcode_handler,
        )
        search = column(children=[zipcode])
        if self.selected_zipcode is not None:
            road = Select(
                title="Vej:",
                value=self.selected_road,
                options=sorted(list(self.roads)),
            )
            road.on_change(
                'value',
                self.road_handler,
            )
            search.children.append(road)
            if self.selected_road is not None:

                address = Select(
                    title="Addresse:",
                    value=self.selected_address,
                    options=sorted(list(self.addresses)),
                )
                address.on_change(
                    'value',
                    self.address_handler,
                )
                search.children.append(address)
                if self.selected_address is not None:
                    prediction = (
                        self.addresses[self.selected_address]['prediction'])
                    formatted_price = (f'{round(prediction):,}'.format(
                        ',', '.'))
                    predicted_price = Div(text=(
                        f"<p>Predicted price: {formatted_price} DKK</p>"))
                    search.children.append(predicted_price)

        self.layout.children = [
            search,
            self.map.layout,
        ]
예제 #29
0
    def init_bokeh_layout(self):
        # ---------------------- DATATABLE ----------------------- #

        sample_control = row(
            children=[
                self.env.bk_table.previous_bt,
                self.env.bk_table.sample_div,
                self.env.bk_table.next_bt,
            ],
            css_classes=['sample_control'],
        )

        # ---------------------- CONTROLS ------------------------- #

        be = self.env.bk_events
        prof_nav = row(
            children=[
                be.previous_prof_bt,
                be.nearby_prof_div,
                be.next_prof_bt,
            ],
            css_classes=['prof_nav']
        )

        sidebar_col = self.env.doc.select_one({'name': 'sidebar_col'})
        sidebar_col.children.clear()
        sidebar_col.children = [
            self.env.flagger_select,
            self.env.flags_control_col,

            be.cb_prof_invsbl_points,
            be.nearby_prof_cb,
            prof_nav,

            Div(width=200, height=15, text='<u><b>Selected Samples</b></u>'),
            sample_control,
            self.env.bk_table.data_table,
            self.env.wmts_map,
        ]

        tabs_widget_col = self.env.doc.select_one({'name': 'tabs_widget_col'})
        tabs_widget_spacer = tabs_widget_col.select_one({'type': Spacer})

        if tabs_widget_spacer in tabs_widget_col.children:  # TODO: check why when reloading bokeh spacer is not in the doc
            tabs_widget_col.children.remove(tabs_widget_spacer)
        tabs_widget_col.children.insert(0, self.env.tabs_widget)
예제 #30
0
파일: plot.py 프로젝트: frdwhite24/frewpy
    def plot(self):
        output_file(self.file_name, title=self.titles["JobTitle"])
        for stage in range(self.num_stages):
            stage_name: str = self.stage_names[stage]

            # Create the plot title
            fig_title: str = self.get_title(stage, stage_name, bokeh=True)
            title_div = Div(
                text=f"<h1>{fig_title}</h1>",
                style={
                    "color": "#fff",
                    "width": f"{self.plot_wid*3}px",
                    "font-size": "10px",
                    "background-color": "#222222",
                    "text-align": "center",
                },
            )

            # Get data to plot
            plot_lists = self.get_data(self.wall_results, stage)
            num_cases: int = len(self.cases)
            node_list: List[int] = list(range(1, len(self.node_levels) + 1))
            colors = cc.palette["glasbey_bw"][0:num_cases]

            # Create a list of 3 Bokeh figures
            self.figs = []
            for _ in range(3):
                self.figs.append(
                    figure(
                        plot_width=self.plot_wid,
                        plot_height=self.plot_hgt,
                    ))

            # Set up the plot properties
            for x_label, y_label, fig in zip(self.x_labels, self.y_labels,
                                             self.figs):
                if y_label:
                    fig.yaxis.axis_label = y_label
                if x_label:
                    fig.xaxis.axis_label = x_label

                # Manipulate strings to create hovertool information
                if not y_label:
                    y_label = "Level (m)"

                x_info = re.sub(r"\(.+\)", "", x_label)
                y_info = re.sub(r"\(.+\)", "", y_label)
                x_unit = re.findall(r"\(([^)]+)\)", x_label)[0]
                y_unit = re.findall(r"\(([^)]+)\)", y_label)[0]

                ht = HoverTool()
                ht.tooltips = [
                    ("Name", "$name"),
                    ("Node", "@node_num"),
                    (f"{x_info}", "$x{0.2f} " + x_unit),
                    (f"{y_info}", "$y{0.2f} " + y_unit),
                ]
                fig.add_tools(ht)
                fig.add_tools(CrosshairTool())

            # Plot values
            node_source = ColumnDataSource({
                "xs": [0] * len(self.node_levels),
                "ys": self.node_levels,
                "node_num": node_list,
            })
            for fig, plot_list, plot_type in zip(self.figs, plot_lists,
                                                 self.plot_types):
                for i, (case_data, color) in enumerate(zip(plot_list, colors)):
                    # Plot node geometry
                    fig.circle(
                        x="xs",
                        y="ys",
                        size=3.5,
                        color="black",
                        alpha=0.5,
                        source=node_source,
                        legend_label="Wall",
                        name="Wall",
                    )
                    fig.line(
                        x="xs",
                        y="ys",
                        color="black",
                        source=node_source,
                        legend_label="Wall",
                        name="Wall",
                        line_width=2,
                    )

                    # Plot results
                    res_source = ColumnDataSource({
                        "xs": case_data,
                        "ys": self.node_levels,
                        "node_num": node_list,
                    })
                    fig.line(
                        x="xs",
                        y="ys",
                        color=color,
                        source=res_source,
                        legend_label=self.cases[i],
                        name=self.cases[i],
                        line_width=2,
                    )

                    # Plot max envelope
                    max_evenlope_xs = self.envelopes[
                        self.cases[i]]["maximum"][plot_type]
                    max_source = ColumnDataSource({
                        "xs": max_evenlope_xs,
                        "ys": self.node_levels,
                        "node_num": node_list,
                    })
                    fig.line(
                        x="xs",
                        y="ys",
                        color=color,
                        line_dash="dashed",
                        source=max_source,
                        legend_label=f"{self.cases[i]} envelope",
                        name=f"{self.cases[i]} envelope",
                        line_width=2,
                    )

                    # Plot min envelope
                    min_evenlope_xs = self.envelopes[
                        self.cases[i]]["minimum"][plot_type]
                    min_source = ColumnDataSource({
                        "xs": min_evenlope_xs,
                        "ys": self.node_levels,
                        "node_num": node_list,
                    })
                    fig.line(
                        x="xs",
                        y="ys",
                        color=color,
                        line_dash="dashed",
                        source=min_source,
                        legend_label=f"{self.cases[i]} envelope",
                        name=f"{self.cases[i]} envelope",
                        line_width=2,
                    )

                fig.legend.click_policy: str = "hide"
                fig.legend.location: str = "bottom_left"

            lay = layout([[title_div], [[self.figs]]])
            self.tabs.append(Panel(child=lay, title=f"Stage {stage}"))
        show(Tabs(tabs=self.tabs))