Ejemplo n.º 1
0
    def __init__(self):

        self.per_capita = RadioGroup(
            labels=["Total", "Per Capita", "Logarithmic"],
            active=0,
            sizing_mode="stretch_width",
        )
        self.data_getter = RadioGroup(
            labels=["Cases", "Deaths", "Positivity"],
            active=0,
            sizing_mode="stretch_width",
        )
        self.date = DatePicker(title="Date", sizing_mode="stretch_width")
        self.save_files = CheckboxGroup(labels=["Save files"],
                                        sizing_mode="stretch_width")
        self.button = Button(label="► Play", sizing_mode="stretch_width")

        self.tooltips = [("Name", "@name"), ("Value", "@value")]

        self.src = None
        self.p = None

        self.callback = None
        self.counter = None

        self.tempdir = None
        self.filenames = None
Ejemplo n.º 2
0
 def initialize(self, widget_lst):
     self.radiobutton = RadioGroup(active=self.default_value,
                                   labels=self.label,
                                   inline=self.inline)
     widget_lst.append(self.radiobutton)
     if self.callback is not None:
         self.radiobutton.on_click(self.callback)
Ejemplo n.º 3
0
class radiobutton():
    def __init__(self, widget_lst, default_value, label, inline=True):
        self.widget_lst = widget_lst
        self.radiobutton = None
        self.initialize(default_value, label, inline)

    def initialize(self, default_value, label, inline):
        self.radiobutton = RadioGroup(active=default_value,
                                      labels=label,
                                      inline=inline)
        self.widget_lst.append(self.radiobutton)

    def add_callback(self, callback):
        self.radiobutton.on_click(callback)
Ejemplo n.º 4
0
def file_callback(attr, old, new):
    global raw_df, hist_df
    loaded_file_div.text = '<font color=#006699>' + "Loaded file" + ': </font>' + \
        file_source.data['file_name'][0]
    raw_contents = file_source.data['file_contents'][0]
    # remove the prefix that JS adds
    prefix, b64_contents = raw_contents.split(",", 1)
    file_contents = base64.b64decode(b64_contents).decode()
    # read in new rawdata
    raw_df = esp8266_aux.preprocess_csv_string(file_contents)
    MAC_list = esp8266_aux.get_MAC_list(raw_df)
    # replace old MAC list by a new list.
    mac_radio_group_column.children.pop()
    mac_radio_group = RadioGroup(labels=MAC_list, active=0)
    mac_radio_group.on_click(mac_radio_group_callback)
    mac_radio_group_column.children.append(mac_radio_group)
    # calculate histogram for the first MAC
    hist_df = time_series_histogram.histogram_of_time(
        raw_df, MAC_list[0], time_window_length=time_window)
    histogram_line.data_source.data = ColumnDataSource(hist_df).data
Ejemplo n.º 5
0
class radiobutton():
    def __init__(self, widget_lst, default_value, label, inline=True):
        self.label = label
        self.default_value = default_value
        self.inline = inline
        self.radiobutton = None
        self.callback = None
        # self.initialize(default_value, label, inline)
        widget_lst.append(self)

    def initialize(self, widget_lst):
        self.radiobutton = RadioGroup(active=self.default_value,
                                      labels=self.label,
                                      inline=self.inline)
        widget_lst.append(self.radiobutton)
        if self.callback is not None:
            self.radiobutton.on_click(self.callback)

    def add_callback(self, callback):
        self.callback = callback
        if self.radiobutton is not None:
            self.radiobutton.on_click(self.callback)
Ejemplo n.º 6
0
    def __init__(self, dataset=STATES):

        self.dataset = dataset

        self.state_selection = MultiSelect(
            title="States:",
            options=self.dataset,
            value=["New York", "Texas"],
            sizing_mode="stretch_both",
        )
        self.per_capita = RadioGroup(
            labels=["Total", "Per Capita"],
            active=0,
            sizing_mode="stretch_width",
        )
        self.data_getter = RadioGroup(
            labels=[
                "Cases",
                "Deaths",
                "Positivity",
                "Testing",
                "Constant Positivity",
                "Constant Testing",
            ],
            active=0,
            sizing_mode="stretch_width",
        )
        self.plot_type = RadioGroup(
            labels=["Linear", "Logarithmic"],
            active=0,
            sizing_mode="stretch_width",
        )

        self.constant_date = DatePicker(
            title="Constant Date",
            value=(datetime.today() - timedelta(days=1)).date(),
            sizing_mode="stretch_width",
        )

        self.show_total = CheckboxGroup(
            labels=["Show total"],
            sizing_mode="stretch_width",
        )

        self.total_only = CheckboxGroup(
            labels=["Total only"],
            sizing_mode="stretch_width",
        )

        self.src = None
        self.p = None
        self.logp = None

        self.tooltips = [("State", "@state")]
Ejemplo n.º 7
0
    def __init__(self):

        super().__init__()

        self.state = "New York, Washington"
        self.menu = COUNTIES

        self.state_selection = Dropdown(menu=self.menu,
                                        label=self.state,
                                        sizing_mode="stretch_width")

        self.data_getter = RadioGroup(
            labels=[
                "Cases",
                "Deaths",
            ],
            active=0,
            sizing_mode="stretch_width",
        )
Ejemplo n.º 8
0
    def __init__(self, renderer):
        self.file_input = Dropdown(label="Select dataset", menu=[])
        for dataset_name in SQLDBInformer(DbConn({})).get_all_schemas():
            if dataset_name in set(["information_schema", "performance_schema", "sys", "defaultDB", "mysql"]):
                continue
            if dataset_name[:3] == "pg_":
                continue
            self.file_input.menu.append(dataset_name)
        self.run_id_dropdown = Dropdown(label="select run id here", menu=[])
        self.ground_truth_id_dropdown = Dropdown(label="select ground truth id here", menu=[])
        self.score_slider = RangeSlider(start=0, end=1, value=(0, 1), step=.1, callback_policy='mouseup',
                                        title="score range")
        self.max_elements_slider = Slider(start=1000, end=100000, value=10000, step=1000,
                                          callback_policy='mouseup', title="max render")
        self.range_link_radio = RadioGroup(labels=["Link read plot to x-range", "Link read plot to y-range"],
                                           active=0, orientation="horizontal")
        self.full_render_button = Button(label="render without limit")
        self.render_mems_button = Button(label="render MEMs")
        self.delete_button = Button(label="Delete Dataset")
        self.force_read_id = TextInput(value="", title="Render reads with ids (comma seperated list):")

        self.file_input.on_change("value", lambda x,y,z: self.file_input_change(renderer))
        self.run_id_dropdown.on_change("value", lambda x,y,z: self.run_id_change(renderer))
        self.ground_truth_id_dropdown.on_change("value", lambda x,y,z: self.ground_id_change(renderer))
        self.score_slider.on_change("value_throttled", lambda x,y,z: self.slider_change(renderer))
        self.max_elements_slider.on_change("value_throttled", lambda x,y,z: self.slider_change(renderer))

        self.full_render_button.on_event(ButtonClick, lambda x: self.full_render(renderer))
        self.render_mems_button.on_event(ButtonClick, lambda x: self.render_mems_button_event(renderer))
        self.delete_button.on_event(ButtonClick, lambda x: self.delete_button_event(renderer))
        self.force_read_id.on_change("value", lambda x,y,z: self.forced_read_ids_change(renderer))

        self.spinner_div = Div(text=html_file("spinner"), sizing_mode="scale_both", visible=False)
        self.condition = threading.Condition()

        self.subset_buttons = CheckboxButtonGroup(labels=["Render false-positives", "Render false-negatives",
                                                          "Render true-positives", "Compute Stats"],
                                                          active=[0, 1, 2])
        self.subset_buttons.on_click(lambda x: self.forced_read_ids_change(renderer))
        self.blur_slider = Slider(start=0, end=500, value=100, step=1, callback_policy='mouseup',
                                        title="Blur")
        self.blur_slider.on_change("value_throttled", lambda x,y,z: self.slider_change(renderer))
Ejemplo n.º 9
0
    CustomJS(
        code="console.log('dropdown_disabled: ' + this.value, this.toString())"
    ))

#dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default")
#dropdown_split.on_click(lambda value: print('dropdown_split: %s' % value))
#dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())"))

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"],
                               active=[0, 1])
checkbox_group.on_click(lambda value: print('checkbox_group: %s' % value))
checkbox_group.js_on_click(
    CustomJS(
        code="console.log('checkbox_group: ' + this.active, this.toString())"))

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(lambda value: print('radio_group: %s' % value))
radio_group.js_on_click(
    CustomJS(
        code="console.log('radio_group: ' + this.active, this.toString())"))

checkbox_button_group = CheckboxButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(
    lambda value: print('checkbox_button_group: %s' % value))
checkbox_button_group.js_on_click(
    CustomJS(
        code=
        "console.log('checkbox_button_group: ' + this.active, this.toString())"
    ))
Ejemplo n.º 10
0
	def plotting(self):



		#Tools = [hover, TapTool(), BoxZoomTool(), BoxSelectTool(), PreviewSaveTool(), ResetTool()]
		TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave"


		tab_plots = []
		#output_file("test.html")
		self.all_elements = []
		self.elements_comparison = []

		for attr_id, i in zip(self.attribute_ids, range(len(self.attribute_ids))):
			
			"""
			create plots for each datafile and put them in a tab.
			"""
			list_of_datasets = getattr(self, attr_id)
			y_axis_units = [x["y_unit"] for x in list_of_datasets]
			x_axis_units = [x["x_unit"] for x in list_of_datasets]

			figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log",
			title = attr_id, tools = TOOLS)
			#figure_obj.axes.major_label_text_font_size("12pt")
			#figure_obj.major_label_text_font_size("12pt")
			
			setattr(self, attr_id+"_"+"figure_obj",figure_obj)

			figure_obj.yaxis.axis_label = y_axis_units[0]
			figure_obj.xaxis.axis_label = x_axis_units[0]

			if not all(x == y_axis_units[0] for x in y_axis_units):
				for unit, data in zip(y_axis_units, list_of_datasets): 
					if not unit == y_axis_units[0]:
						figure_obj.extra_y_ranges =  {"foo": Range1d(start = np.amin(data["data"]["y"]),
						end = np.amax(data["data"]["y"]))}
						figure_obj.add_layout(LogAxis(y_range_name = "foo", axis_label = unit), "right")
						break

			if not all(x == x_axis_units[0] for x in x_axis_units):
				for unit, data in zip(x_axis_units, list_of_datasets): 
					if not unit == x_axis_units[0]:
						figure_obj.extra_x_ranges =  {"bar": Range1d(start = np.amin(data["data"]["x"]),
						end = np.amax(data["data"]["x"]))}
						figure_obj.add_layout(LinearAxis(x_range_name = "bar", axis_label = unit), "above")
						break



			figure_obj.xaxis.axis_label = list_of_datasets[0]["x_unit"]
			colour_list = Spectral11 + RdPu9 + Oranges9
			colour_indices = [0, 2, 8, 10, 12, 14, 20, 22, 1, 3, 9, 11, 13, 15]

			list_of_elements = []

			for dataset, color_index in zip(list_of_datasets, colour_indices):

				self.all_elements.append(dataset["sample element"]) #strip isotope number 
				color = colour_list[color_index]

				source = ColumnDataSource(data = dataset["data"]) #Datastructure for source of plotting

				setattr(self, attr_id+"_"+dataset["sample element"]+"_source", source) #Source element generalized for all plotting				


				list_of_elements.append(dataset["sample element"])

				figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]
								+"_source"), line_width = 2, line_color = color, 
								legend = dataset["sample element"], name = dataset["sample element"],
								 )

			hover = figure_obj.select_one(HoverTool).tooltips = [("element", "@element"), ("(x,y)", "($x, $y)")]

			radio_group = RadioGroup(labels = list_of_elements, active=0)

			"""
			Need to fetch default variables from input file and replace DEFAULT

			Block of code produces the layout of buttons and callbacks
			"""

			
			#Calculations on the dataset
			text_input_rsf = TextInput(value = "default", title = "RSF (at/cm^3): ")
			do_integral_button = Button(label = "Calibration Integral")
			smoothing_button = Button(label = "Smoothing on selected curve")

			text_input_sputter = TextInput(value = "default", title = "Sputter speed: float unit")
			text_input_crater_depth = TextInput(value = "default", title = "Depth of crater in: float")
			

			radio_group.on_change("active", lambda attr, old, new: None)

			text_input_xval_integral = TextInput(value = "0", title = "x-value for calibration integral ")
			text_input_yval_integral = TextInput(value = "0", title = "y-value for calibration integral ")

			#Save files for later use
			save_flexDPE_button = Button(label = "Save element for FlexPDE")
			save_all_flexDPE_button = Button(label = "Save all elements for FlexPDE")


			#Pointers to methods on click / change handlers
			do_integral_button.on_click(lambda identity = self.attribute_ids[i], radio = radio_group, 
										x_box = text_input_xval_integral, y_box = text_input_yval_integral: 
										self.integrate(identity, radio, x_box, y_box))

			smoothing_button.on_click(lambda identity = self.attribute_ids[i], radio = radio_group: 
									self.smoothing(identity, radio) )

			save_flexDPE_button.on_click(lambda identity = self.attribute_ids[i], radio = radio_group: 
										self.write_to_flexPDE(identity, radio))

			save_all_flexDPE_button.on_click(lambda identity = self.attribute_ids[i], radio = radio_group:
											self.write_all_to_flexPDE(identity, radio))

			text_input_rsf.on_change("value", lambda attr, old, new, radio = radio_group, 
								identity = self.attribute_ids[i], text_input = text_input_rsf, which = "rsf":
								self.update_data(identity, radio, text_input, new, which))


			text_input_sputter.on_change("value", lambda attr, old, new, radio = radio_group, 
								identity = self.attribute_ids[i], text_input = text_input_sputter, which = "sputter":
								self.update_data(identity, radio, text_input, new, which))

			text_input_crater_depth.on_change("value", lambda attr, old, new, radio = radio_group, 
								identity = self.attribute_ids[i], text_input = text_input_crater_depth, which = "crater_depth":
								self.update_data(identity, radio, text_input, new, which))


			#Initialization of actual plotting. 
			tab_plots.append(Panel(child = hplot(figure_obj, 
										   vform(radio_group, save_flexDPE_button, save_all_flexDPE_button), 
										   vform(text_input_rsf, smoothing_button, text_input_sputter, text_input_crater_depth),
										   vform(text_input_xval_integral, text_input_yval_integral, do_integral_button)),
										   title = attr_id))


		"""
		Check to see if one or more element exists in the samples and creat a comparison plot for each 
		of those elements.
		"""
		
		for element in self.all_elements:
			checkers = list(self.all_elements)
			checkers.remove(element)
			if element in checkers and not element in self.elements_comparison:
				self.elements_comparison.append(element)

		"""create plots for each element that is to be compared """
	
		for comparison_element in self.elements_comparison: 

			colour_list = Spectral11 + RdPu9 + Oranges9
			colour_indices = [0, 2, 8, 10, 12, 14, 20, 22, 1, 3, 9, 11, 13, 15]
			figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log", title = comparison_element, tools = TOOLS)
			#figure_obj.xaxis.major_label_text_font_size("12pt")
			#figure_obj.yaxis.major_label_text_font_size("12pt")
			

			y_axis_units = []
			x_axis_units = []

			comparison_datasets = []


			for attr_id, color_index in zip(self.attribute_ids, colour_indices):

				list_of_datasets = getattr(self, attr_id)

				for dataset in list_of_datasets:

					if dataset["sample element"] == comparison_element:
						comparison_datasets.append(dataset)
						y_axis_units.append(dataset["y_unit"])
						x_axis_units.append(dataset["x_unit"])

			figure_obj.xaxis.axis_label = comparison_datasets[-1]["x_unit"]
			figure_obj.yaxis.axis_label = comparison_datasets[-1]["y_unit"]

			if not all(x == y_axis_units[-1] for x in y_axis_units):
				for unit, data in zip(y_axis_units, comparison_datasets): 
					if not unit == y_axis_units[-1]:
						figure_obj.extra_y_ranges =  {"foo": Range1d(start = np.amin(data["data"]["y"]),
						end = np.amax(data["data"]["y"]))}
						figure_obj.add_layout(LogAxis(y_range_name = "foo", axis_label = unit), "right")
						break

			if not all(x == x_axis_units[-1] for x in x_axis_units):
				for unit, data in zip(x_axis_units, comparison_datasets): 
					if not unit == x_axis_units[-1]:
						figure_obj.extra_x_ranges =  {"bar": Range1d(start = np.amin(data["data"]["x"]),
						end = np.amax(data["data"]["x"]))}
						figure_obj.add_layout(LinearAxis(x_range_name = "bar", axis_label = unit), "above")
						break


			for attr_id, color_index in zip(self.attribute_ids, colour_indices):

				list_of_datasets = getattr(self, attr_id)

				for dataset in list_of_datasets:

					if dataset["sample element"] == comparison_element:
						color = colour_list[color_index]

						"""
						Logic that ensures that plots get put with correspoinding axes. 
						"""
						if dataset["x_unit"] != x_axis_units[-1] or dataset["y_unit"] != y_axis_units[-1]:

							if dataset["x_unit"] != x_axis_units[-1] and dataset["y_unit"] != y_axis_units[-1]:

								figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]+"_source"), line_width = 2, 
								line_color = color, legend = attr_id, x_range_name = "bar", y_range_name = "foo")

							elif dataset["x_unit"] != x_axis_units[-1]:

								figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]+"_source"), line_width = 2, 
								line_color = color, legend = attr_id, x_range_name = "bar")

							else: 

								figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]+"_source"), line_width = 2, 
								line_color = color, legend = attr_id, y_range_name = "foo")

						else: 
							figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]+"_source"), line_width = 2, 
							line_color = color, legend = attr_id)
						


			tab_plots.append(Panel(child = figure_obj, title = comparison_element))	

		tabs = Tabs(tabs = tab_plots)

		session = push_session(curdoc())
		session.show()
		session.loop_until_closed()
# use the css_classes to reference this object in /templates/styles.css
example_slider = LatexSlider(title="\\text{example}=",
                             value_unit="\\frac{Sv}{m \\cdot kg}",
                             value=initial_value,
                             start=start_value,
                             end=end_value,
                             step=0.5,
                             width=400,
                             css_classes=["slider"])
example_slider.on_change(
    'value', slider_cb_fun)  # callback function is called when value changes

# radio button: round and only one active selection per group allowed
# active=0 to select the the first button by default
# inline=True to place the buttons horizontally
radio_group_01 = RadioGroup(labels=["1", "2"], active=0, inline=True)
radio_group_02 = RadioGroup(labels=["3", "4"])
radio_group_01.on_change("active", radio_cb_fun)
radio_group_02.on_change("active", radio_cb_fun_2)

# radio button group: buttons that are merged next to each other, only one active selection per group allowed
radio_button_group = RadioButtonGroup(labels=["Item 1", "Item 2", "Item 3"],
                                      active=0,
                                      width=200)

##################################
#         Costum Objects         #
##################################

# build a new object
my_object = TA_example_class(42)
Ejemplo n.º 12
0
from datetime import date
from random import randint
import string

refresh = Button(label="Refresh")
btnGroupTitle = RadioButtonGroup(
    name='title',
    labels=["begins with...", "...contains...", "...ends with"],
    active=1)
btnGroupDept = RadioButtonGroup(
    name='dept',
    labels=["begins with...", "...contains...", "...ends with"],
    active=1)
paragraph = Paragraph(text="option")
optionGroup = RadioGroup(labels=["and", "or"],
                         active=0,
                         width=100,
                         inline=True)
btnGroupLetters = RadioButtonGroup(labels=list(string.ascii_uppercase),
                                   active=-1)
title_input = TextInput(value="", title="Title:", placeholder="contains....")
dept_input = TextInput(value="",
                       title="Department:",
                       placeholder="contains....")

layout_query = layout([
    [widgetbox(btnGroupLetters, width=1000)],
    [widgetbox(btnGroupTitle),
     widgetbox(btnGroupDept)],
    [
        widgetbox(title_input),
        widgetbox(paragraph, optionGroup, width=100),
Ejemplo n.º 13
0
def first_tab_create(filterData):
    ########method1: create data source for plots

    # dummy data that will be replaced by button values once we get those implemented (right now only granulaity button is implemented)

    all_min_date = filterData.groupby('dataid').agg(min)["time"]
    all_max_date = filterData.groupby('dataid').agg(max)["time"]

    dummy_daterange = ['2019-05-01', '2019-08-20']
    dummy_home_id = 27
    dummy_data_type = 'car1'
    dummy_granularity = '15 Minutes'

    def plot1_data(house, daterange=dummy_daterange, data=dummy_data_type, xaxis=dummy_granularity):

        # house is an integer number ex. 27
        # daterange is an array with 2 strings, start date and end date. ex. ['2019-05-01','2019-08-09']
        # weekdays is an ordered list 0-6 of integers ex. [1,4,6] (these are the days we want to exclude)
        # data is a string ex. 'car1'
        # xaxis is also a string ex. 'hour'

        houseData = filterData[filterData['dataid'] == house].sort_values('time', ascending=True)[[data, 'time']]
        # that cuts the house, sorts by ascending time, and pulls out only the type of data that was requested
        houseData.index = houseData['time']  # reindex by the datetime
        houseData = houseData.loc[daterange[0]:daterange[1], :]  # cut to the days requested

        # Now we get into the xaxis user options #
        if xaxis == '15 Minutes':
            houseData = houseData.drop(columns="time")

        if xaxis == 'Hour':
            houseData = houseData.resample('1h').mean()
            houseData[data]=houseData[data]*3600/3600

        if xaxis == 'Day':
            houseData = houseData.resample('1d').mean()
            houseData[data] = houseData[data] * 3600 / 3600 * 24

        if xaxis == 'Week':
            houseData = houseData.resample('1w').mean()
            houseData[data] = houseData[data] * 3600 / 3600 *24 * 7

        if xaxis == 'Month':
            houseData = houseData.resample('1m').mean()
            houseData[data] = houseData[data] * 3600 / 3600 *24 * 7 * 30 ############this computation is wrong because n stadard month but just go with it for now
        # if none of these, 15 Minutes is implied and passed through
        return ColumnDataSource(houseData)


    def plot2_data(house,daterange=dummy_daterange,weekdays = [],data=dummy_data_type,xaxis=dummy_granularity):
             houseData = filterData[filterData['dataid'] == house].sort_values('time', ascending = True)[[data,'time']]
            #  that cuts the house, sorts by ascending time, and pulls out only the type of data that was requested
             houseData.index = houseData['time'] # reindex by the datetime
             houseData = houseData.loc[daterange[0]:daterange[1],:] # cut to the days requested

             for i in weekdays:
                 houseData = houseData[houseData['time'].dt.dayofweek != i] # cut out days we dont want

             if xaxis == 'avgday':
                 houseData = houseData.resample('1d').sum() ####chjange to mean
                 houseData['time'] = houseData.index
                 houseData = houseData.groupby(houseData['time'].dt.dayofweek)[data].mean()
                 houseData.index = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
                 


             if xaxis == 'avghour':
                 houseData = houseData.resample('1h').mean()
                 houseData['time'] = houseData.index
                 houseData = houseData.groupby(houseData['time'].dt.hour)[data].mean() # Does not account for UTC change!
    

             houseData = pd.DataFrame(data = houseData)
             houseData['axis'] = houseData.index

           
             return ColumnDataSource(houseData) 

    # now we need to set up our plot axis

    ##########method2: create plots

    def plot1_plot(src):
        # create the plot every time  a change occurs
        plot1 = figure(title="Energy Consumption Per Period", x_axis_type="datetime", x_axis_label="Date",
                       y_axis_label="Energy Consumption [kWh]")
        plot1.line('time', "grid", source=src, )  # simple line plot   #data_type_available[data_type_selector.active]

        return plot1  # plot object type

    def plot2_plot(src):
        plot2 = figure(x_range = (0,23), y_range=(-7,2), title='Average Power Consumption For Hours in a Day') # gotta do the ranges as mins and maxes
        plot2.vbar(x='axis', top = 'grid', width=1, source=src) 
        plot2.yaxis.axis_label = 'Power Consumption [kW]'
        plot2.xaxis.axis_label = 'Hour of the Day'
        #plot2 = figure(title = 'PLOT2')
        #plot2.line('axis','grid', source = src)

        return plot2

    #########Method3: Update App

    def update(attr, old, new):  # still a little unsure how the update function gets values passed in implicitly
        # these values to be replaced with button/user inputs

        home_id_to_plot = 27
        daterange_to_plot = ['2019-05-01', '2019-08-20']
        data_type_to_plot = 'grid'
        exclude_days_to_plot = []
        avg_to_plot = 'avghour'


        # home_id_to_plot = int(home_id_selector.value)
        # print(attr, old, new)

        #         if home_id_selector.value == new:

        #             daterange_to_plot = [all_min_date[home_id_to_plot].strftime("%Y-%m-%d"), all_max_date[home_id_to_plot].strftime("%Y-%m-%d")]
        #             date_range_slider.start=all_min_date[home_id_to_plot]
        #             date_range_slider.end=all_max_date[home_id_to_plot]
        #             date_range_slider.value=(all_min_date[home_id_to_plot],all_max_date[home_id_to_plot])

        #             print("if 1 truth")
        #         else:
        daterange_raw = list(date_range_slider.value_as_datetime)
        daterange_to_plot = [daterange_raw[0].strftime("%Y-%m-%d"), daterange_raw[1].strftime("%Y-%m-%d")]
        #         print("falsyy")

        # date_range_slider.update(start=all_min_date[home_id_to_plot], end=all_max_date[home_id_to_plot],
        #                          value=(all_min_date[home_id_to_plot], all_max_date[home_id_to_plot]))

        #         print("after:",new)

        #         print(attr,old,new)

        #         daterange_to_plot=list(string_date1,string_date2)

        #         daterange_to_plot=dummy_daterange

        data_type_to_plot = "grid"  # data_type_available[data_type_selector.active]


        # only working button call so far
        granularity_to_plot = granularity_1.labels[granularity_1.active]

        #         granularity_to_plot= [granularity_1.labels[i] for i in granularity_1.active]
        print("before data create")
        # create a new data source
        new_src1 = plot1_data(home_id_to_plot, daterange=daterange_to_plot, data=data_type_to_plot,
                              xaxis=granularity_to_plot)


        new_src2 = plot2_data(home_id_to_plot, daterange=daterange_to_plot, 
                weekdays=exclude_days_to_plot, data=data_type_to_plot,xaxis=avg_to_plot)


        print("before data update")

        # push new data  to the source data the rest of the app is usig for plot1
    
        src1.data.update(new_src1.data)

        src2.data.update(new_src2.data)

        print("updated data")

    #     def new_home(attr,old,new):
    #         return


      
    ############# Add widgets

    # only the granularity implemented so far
    granularity_1 = RadioGroup(
        labels=["15 Minutes", "Hour", "Day", "Week", "Month"], active=0)

    granularity_1.on_change('active',
                            update)  # not sure exactly how this works but runs update on the change of the button and passes through the value of the button

    home_ids_available = np.unique(filterData['dataid'])

    home_ids_available= list(map(str, home_ids_available))
    home_id_selector = Dropdown(label="Home ID to Plot", button_type="warning", menu=home_ids_available)

    home_ids_available = list(map(str, home_ids_available))
    home_id_selector = Dropdown(label="Home ID to Plot", button_type="warning", menu=home_ids_available, value="27")


    # home_id_selector.on_change('value', update) #############put back in later!!!!1

    date_range_slider = DateRangeSlider(title="Date Range: ", start=date(2019, 5, 1), end=date(2019, 8, 20),
                                        value=(date(2019, 5, 1), date(2019, 8, 20)), step=1, callback_policy = 'mouseup')
    date_range_slider.on_change("value", update)

    # data_type_selector = RadioButtonGroup(labels=["Net Home Consumption","Solar Generation","EV Consumption"],active=0)

    # data_type_selector.on_change('active',update)
    # data_type_available=["grid","solar","car1"]

    ############ Initialize opening plot and data
    src1 = plot1_data(int(home_ids_available[0]), ['2019-05-01', '2019-08-20'], 'grid',
                      '15 Minutes')  # start with a data range we know is correct
    plot1 = plot1_plot(src1)

    src2 = plot2_data(27,['2019-05-01', '2019-08-20'],[],'grid','avghour')
    plot2 = plot2_plot(src2)

    ##### Formatting of the app screen

    # Put controls in a single element (add more later to format)
    controls = WidgetBox(granularity_1, home_id_selector, date_range_slider)  # data_type_selector)

    # Create a row layout

    layout = row(controls, column(plot1,plot2))


    # Make a tab with the layout
    tab = Panel(child=layout, title='First Tab')


    return tab
Ejemplo n.º 14
0
class DVHs:
    def __init__(self, sources, time_series, correlation, regression,
                 custom_title, data_tables):
        self.sources = sources
        self.time_series = time_series
        self.correlation = correlation
        self.regression = regression

        self.dvh_review_rois = []
        self.query = None

        self.temp_dvh_info = Temp_DICOM_FileSet()
        self.dvh_review_mrns = self.temp_dvh_info.mrn
        if self.dvh_review_mrns[0] != '':
            self.dvh_review_rois = self.temp_dvh_info.get_roi_names(
                self.dvh_review_mrns[0]).values()
            self.dvh_review_mrns.append('')
        else:
            self.dvh_review_rois = ['']

        # Add Current row to source
        self.add_endpoint_row_button = Button(label="Add Endpoint",
                                              button_type="primary",
                                              width=200)
        self.add_endpoint_row_button.on_click(self.add_endpoint)

        self.ep_row = Select(value='', options=[''], width=50, title="Row")
        self.ep_options = [
            "Dose (Gy)", "Dose (%)", "Volume (cc)", "Volume (%)"
        ]
        self.select_ep_type = Select(value=self.ep_options[0],
                                     options=self.ep_options,
                                     width=180,
                                     title="Output")
        self.select_ep_type.on_change('value', self.select_ep_type_ticker)
        self.ep_text_input = TextInput(value='',
                                       title="Input Volume (cc):",
                                       width=180)
        self.ep_text_input.on_change('value', self.ep_text_input_ticker)
        self.ep_units_in = RadioButtonGroup(labels=["cc", "%"],
                                            active=0,
                                            width=100)
        self.ep_units_in.on_change('active', self.ep_units_in_ticker)
        self.delete_ep_row_button = Button(label="Delete",
                                           button_type="warning",
                                           width=100)
        self.delete_ep_row_button.on_click(self.delete_ep_row)

        tools = "pan,wheel_zoom,box_zoom,reset,crosshair,save"
        self.plot = figure(plot_width=1050,
                           plot_height=500,
                           tools=tools,
                           logo=None,
                           active_drag="box_zoom")
        self.plot.min_border_left = options.MIN_BORDER
        self.plot.min_border_bottom = options.MIN_BORDER
        self.plot.add_tools(
            HoverTool(show_arrow=False,
                      line_policy='next',
                      tooltips=[('Label', '@mrn @roi_name'), ('Dose', '$x'),
                                ('Volume', '$y')]))
        self.plot.xaxis.axis_label_text_font_size = options.PLOT_AXIS_LABEL_FONT_SIZE
        self.plot.yaxis.axis_label_text_font_size = options.PLOT_AXIS_LABEL_FONT_SIZE
        self.plot.xaxis.major_label_text_font_size = options.PLOT_AXIS_MAJOR_LABEL_FONT_SIZE
        self.plot.yaxis.major_label_text_font_size = options.PLOT_AXIS_MAJOR_LABEL_FONT_SIZE
        self.plot.yaxis.axis_label_text_baseline = "bottom"
        self.plot.lod_factor = options.LOD_FACTOR  # level of detail during interactive plot events

        # Add statistical plots to figure
        stats_median_1 = self.plot.line(
            'x',
            'median',
            source=sources.stats_1,
            line_width=options.STATS_1_MEDIAN_LINE_WIDTH,
            color=options.GROUP_1_COLOR,
            line_dash=options.STATS_1_MEDIAN_LINE_DASH,
            alpha=options.STATS_1_MEDIAN_ALPHA)
        stats_mean_1 = self.plot.line(
            'x',
            'mean',
            source=sources.stats_1,
            line_width=options.STATS_1_MEAN_LINE_WIDTH,
            color=options.GROUP_1_COLOR,
            line_dash=options.STATS_1_MEAN_LINE_DASH,
            alpha=options.STATS_1_MEAN_ALPHA)
        stats_median_2 = self.plot.line(
            'x',
            'median',
            source=sources.stats_2,
            line_width=options.STATS_2_MEDIAN_LINE_WIDTH,
            color=options.GROUP_2_COLOR,
            line_dash=options.STATS_2_MEDIAN_LINE_DASH,
            alpha=options.STATS_2_MEDIAN_ALPHA)
        stats_mean_2 = self.plot.line(
            'x',
            'mean',
            source=sources.stats_2,
            line_width=options.STATS_2_MEAN_LINE_WIDTH,
            color=options.GROUP_2_COLOR,
            line_dash=options.STATS_2_MEAN_LINE_DASH,
            alpha=options.STATS_2_MEAN_ALPHA)

        # Add all DVHs, but hide them until selected
        self.plot.multi_line('x',
                             'y',
                             source=sources.dvhs,
                             selection_color='color',
                             line_width=options.DVH_LINE_WIDTH,
                             alpha=0,
                             line_dash=options.DVH_LINE_DASH,
                             nonselection_alpha=0,
                             selection_alpha=1)

        # Shaded region between Q1 and Q3
        iqr_1 = self.plot.patch('x_patch',
                                'y_patch',
                                source=sources.patch_1,
                                alpha=options.IQR_1_ALPHA,
                                color=options.GROUP_1_COLOR)
        iqr_2 = self.plot.patch('x_patch',
                                'y_patch',
                                source=sources.patch_2,
                                alpha=options.IQR_2_ALPHA,
                                color=options.GROUP_2_COLOR)

        # Set x and y axis labels
        self.plot.xaxis.axis_label = "Dose (Gy)"
        self.plot.yaxis.axis_label = "Normalized Volume"

        # Set the legend (for stat dvhs only)
        legend_stats = Legend(items=[("Median", [stats_median_1]),
                                     ("Mean", [stats_mean_1]),
                                     ("IQR", [iqr_1]),
                                     ("Median", [stats_median_2]),
                                     ("Mean", [stats_mean_2]),
                                     ("IQR", [iqr_2])],
                              location=(25, 0))

        # Add the layout outside the plot, clicking legend item hides the line
        self.plot.add_layout(legend_stats, 'right')
        self.plot.legend.click_policy = "hide"

        self.download_endpoints_button = Button(label="Download Endpoints",
                                                button_type="default",
                                                width=150)
        self.download_endpoints_button.callback = CustomJS(
            args=dict(source=sources.endpoint_calcs),
            code=open(join(dirname(__file__), "download_endpoints.js")).read())

        # Setup axis normalization radio buttons
        self.radio_group_dose = RadioGroup(
            labels=["Absolute Dose", "Relative Dose (Rx)"],
            active=0,
            width=200)
        self.radio_group_dose.on_change('active', self.radio_group_ticker)
        self.radio_group_volume = RadioGroup(
            labels=["Absolute Volume", "Relative Volume"], active=1, width=200)
        self.radio_group_volume.on_change('active', self.radio_group_ticker)

        # Setup selectors for dvh review
        self.select_reviewed_mrn = Select(title='MRN to review',
                                          value='',
                                          options=self.dvh_review_mrns,
                                          width=300)
        self.select_reviewed_mrn.on_change('value',
                                           self.update_dvh_review_rois)

        self.select_reviewed_dvh = Select(title='ROI to review',
                                          value='',
                                          options=[''],
                                          width=360)
        self.select_reviewed_dvh.on_change('value',
                                           self.select_reviewed_dvh_ticker)

        self.review_rx = TextInput(value='', title="Rx Dose (Gy):", width=170)
        self.review_rx.on_change('value', self.review_rx_ticker)

        if options.LITE_VIEW:
            self.layout = column(
                Div(text="<b>DVH Analytics v%s</b>" % options.VERSION),
                row(self.radio_group_dose,
                    self.radio_group_volume), self.add_endpoint_row_button,
                row(self.ep_row, Spacer(width=10), self.select_ep_type,
                    self.ep_text_input, Spacer(width=20),
                    self.ep_units_in, self.delete_ep_row_button,
                    Spacer(width=50), self.download_endpoints_button),
                data_tables.ep)
        else:
            self.layout = column(
                Div(text="<b>DVH Analytics v%s</b>" % options.VERSION),
                row(custom_title['1']['dvhs'], Spacer(width=50),
                    custom_title['2']['dvhs']),
                row(self.radio_group_dose, self.radio_group_volume),
                row(self.select_reviewed_mrn, self.select_reviewed_dvh,
                    self.review_rx), self.plot,
                Div(text="<b>DVHs</b>", width=1200), data_tables.dvhs,
                Div(text="<hr>", width=1050),
                Div(text="<b>Define Endpoints</b>",
                    width=1000), self.add_endpoint_row_button,
                row(self.ep_row, Spacer(width=10), self.select_ep_type,
                    self.ep_text_input, Spacer(width=20),
                    self.ep_units_in, self.delete_ep_row_button,
                    Spacer(width=50), self.download_endpoints_button),
                data_tables.ep, Div(text="<b>DVH Endpoints</b>",
                                    width=1200), data_tables.endpoints)

    def add_endpoint(self):
        if self.sources.endpoint_defs.data['row']:
            temp = self.sources.endpoint_defs.data

            for key in list(temp):
                temp[key].append('')
            temp['row'][-1] = len(temp['row'])
            self.sources.endpoint_defs.data = temp

            new_options = [str(x + 1) for x in range(len(temp['row']))]
            self.ep_row.options = new_options
            self.ep_row.value = new_options[-1]
        else:
            self.ep_row.options = ['1']
            self.ep_row.value = '1'
            self.sources.endpoint_defs.data = dict(row=['1'],
                                                   output_type=[''],
                                                   input_type=[''],
                                                   input_value=[''],
                                                   label=[''],
                                                   units_in=[''],
                                                   units_out=[''])
            if not self.ep_text_input.value:
                self.ep_text_input.value = '1'

        self.update_ep_source()

        clear_source_selection(self.sources, 'endpoint_defs')

    def update_ep_source(self):
        if self.ep_row.value:

            r = int(self.ep_row.value) - 1

            if 'Dose' in self.select_ep_type.value:
                input_type, output_type = 'Volume', 'Dose'
                if '%' in self.select_ep_type.value:
                    units_out = '%'
                else:
                    units_out = 'Gy'
                units_in = ['cc', '%'][self.ep_units_in.active]
                label = "D_%s%s" % (self.ep_text_input.value, units_in)
            else:
                input_type, output_type = 'Dose', 'Volume'
                if '%' in self.select_ep_type.value:
                    units_out = '%'
                else:
                    units_out = 'cc'
                units_in = ['Gy', '%'][self.ep_units_in.active]
                label = "V_%s%s" % (self.ep_text_input.value, units_in)

            try:
                input_value = float(self.ep_text_input.value)
            except:
                input_value = 1

            patch = {
                'output_type': [(r, output_type)],
                'input_type': [(r, input_type)],
                'input_value': [(r, input_value)],
                'label': [(r, label)],
                'units_in': [(r, units_in)],
                'units_out': [(r, units_out)]
            }

            self.sources.endpoint_defs.patch(patch)
            self.update_source_endpoint_calcs()

    def ep_units_in_ticker(self, attr, old, new):
        if self.query.allow_source_update:
            self.update_ep_text_input_title()
            self.update_ep_source()

    def update_ep_text_input_title(self):
        if 'Dose' in self.select_ep_type.value:
            self.ep_text_input.title = "Input Volume (%s):" % [
                'cc', '%'
            ][self.ep_units_in.active]
        else:
            self.ep_text_input.title = "Input Dose (%s):" % [
                'Gy', '%'
            ][self.ep_units_in.active]

    def select_ep_type_ticker(self, attr, old, new):
        if self.query.allow_source_update:
            if 'Dose' in new:
                self.ep_units_in.labels = ['cc', '%']
            else:
                self.ep_units_in.labels = ['Gy', '%']

            self.update_ep_text_input_title()
            self.update_ep_source()

    def ep_text_input_ticker(self, attr, old, new):
        if self.query.allow_source_update:
            self.update_ep_source()

    def delete_ep_row(self):
        if self.ep_row.value:
            new_ep_source = self.sources.endpoint_defs.data
            index_to_delete = int(self.ep_row.value) - 1
            new_source_length = len(
                self.sources.endpoint_defs.data['output_type']) - 1

            if new_source_length == 0:
                clear_source_data(self.sources, 'endpoint_defs')
                self.ep_row.options = ['']
                self.ep_row.value = ''
            else:
                for key in list(new_ep_source):
                    new_ep_source[key].pop(index_to_delete)

                for i in range(index_to_delete, new_source_length):
                    new_ep_source['row'][i] -= 1

                self.ep_row.options = [
                    str(x + 1) for x in range(new_source_length)
                ]
                if self.ep_row.value not in self.ep_row.options:
                    self.ep_row.value = self.ep_row.options[-1]
                self.sources.endpoint_defs.data = new_ep_source

            self.update_source_endpoint_calcs(
            )  # not efficient, but still relatively quick
            clear_source_selection(self.sources, 'endpoint_defs')

    def update_ep_row_on_selection(self, attr, old, new):
        self.query.allow_source_update = False

        if new:
            data = self.sources.endpoint_defs.data
            r = min(new)

            # update row
            self.ep_row.value = self.ep_row.options[r]

            # update input value
            self.ep_text_input.value = str(data['input_value'][r])

            # update input units radio button
            if '%' in data['units_in'][r]:
                self.ep_units_in.active = 1
            else:
                self.ep_units_in.active = 0

            # update output
            if 'Dose' in data['output_type'][r]:
                if '%' in data['units_in'][r]:
                    self.select_ep_type.value = self.ep_options[1]
                else:
                    self.select_ep_type.value = self.ep_options[0]
            else:
                if '%' in data['units_in'][r]:
                    self.select_ep_type.value = self.ep_options[3]
                else:
                    self.select_ep_type.value = self.ep_options[2]

        self.query.allow_source_update = True

    def update_source_endpoint_calcs(self):

        if self.query.current_dvh:
            group_1_constraint_count, group_2_constraint_count = group_constraint_count(
                self.sources)

            ep = {'mrn': ['']}
            ep_group = {'1': {}, '2': {}}

            table_columns = []

            ep['mrn'] = self.query.current_dvh.mrn
            ep['uid'] = self.query.current_dvh.study_instance_uid
            ep['group'] = self.sources.dvhs.data['group']
            ep['roi_name'] = self.sources.dvhs.data['roi_name']

            table_columns.append(TableColumn(field='mrn', title='MRN'))
            table_columns.append(TableColumn(field='group', title='Group'))
            table_columns.append(
                TableColumn(field='roi_name', title='ROI Name'))

            data = self.sources.endpoint_defs.data
            for r in range(len(data['row'])):
                ep_name = str(data['label'][r])
                table_columns.append(
                    TableColumn(field=ep_name,
                                title=ep_name,
                                formatter=NumberFormatter(format="0.00")))
                x = data['input_value'][r]

                if '%' in data['units_in'][r]:
                    endpoint_input = 'relative'
                    x /= 100.
                else:
                    endpoint_input = 'absolute'

                if '%' in data['units_out'][r]:
                    endpoint_output = 'relative'
                else:
                    endpoint_output = 'absolute'

                if 'Dose' in data['output_type'][r]:
                    ep[ep_name] = self.query.current_dvh.get_dose_to_volume(
                        x,
                        volume_scale=endpoint_input,
                        dose_scale=endpoint_output)
                    for g in GROUP_LABELS:
                        if self.time_series.current_dvh_group[g]:
                            ep_group[g][
                                ep_name] = self.time_series.current_dvh_group[
                                    g].get_dose_to_volume(
                                        x,
                                        volume_scale=endpoint_input,
                                        dose_scale=endpoint_output)

                else:
                    ep[ep_name] = self.query.current_dvh.get_volume_of_dose(
                        x,
                        dose_scale=endpoint_input,
                        volume_scale=endpoint_output)
                    for g in GROUP_LABELS:
                        if self.time_series.current_dvh_group[g]:
                            ep_group[g][
                                ep_name] = self.time_series.current_dvh_group[
                                    g].get_volume_of_dose(
                                        x,
                                        dose_scale=endpoint_input,
                                        volume_scale=endpoint_output)

                if group_1_constraint_count and group_2_constraint_count:
                    ep_1_stats = calc_stats(ep_group['1'][ep_name])
                    ep_2_stats = calc_stats(ep_group['2'][ep_name])
                    stats = []
                    for i in range(len(ep_1_stats)):
                        stats.append(ep_1_stats[i])
                        stats.append(ep_2_stats[i])
                    ep[ep_name].extend(stats)
                else:
                    ep[ep_name].extend(calc_stats(ep[ep_name]))

            self.sources.endpoint_calcs.data = ep

            # Update endpoint calc from review_dvh, if available
            if self.sources.dvhs.data['y'][0] != []:
                review_ep = {}
                rx = float(self.sources.dvhs.data['rx_dose'][0])
                volume = float(self.sources.dvhs.data['volume'][0])
                data = self.sources.endpoint_defs.data
                for r in range(len(data['row'])):
                    ep_name = str(data['label'][r])
                    x = data['input_value'][r]

                    if '%' in data['units_in'][r]:
                        endpoint_input = 'relative'
                        x /= 100.
                    else:
                        endpoint_input = 'absolute'

                    if '%' in data['units_out'][r]:
                        endpoint_output = 'relative'
                    else:
                        endpoint_output = 'absolute'

                    if 'Dose' in data['output_type'][r]:
                        if endpoint_input == 'relative':
                            current_ep = dose_to_volume(y, x)
                        else:
                            current_ep = dose_to_volume(y, x / volume)
                        if endpoint_output == 'relative' and rx != 0:
                            current_ep = current_ep / rx

                    else:
                        if endpoint_input == 'relative':
                            current_ep = volume_of_dose(y, x * rx)
                        else:
                            current_ep = volume_of_dose(y, x)
                        if endpoint_output == 'absolute' and volume != 0:
                            current_ep = current_ep * volume

                    review_ep[ep_name] = [(0, current_ep)]

                review_ep['mrn'] = [(0, self.select_reviewed_mrn.value)]
                self.sources.endpoint_calcs.patch(review_ep)

            self.update_endpoint_view()

        if not options.LITE_VIEW:
            self.time_series.update_options()

    def update_endpoint_view(self):
        if self.query.current_dvh:
            rows = len(self.sources.endpoint_calcs.data['mrn'])
            ep_view = {
                'mrn': self.sources.endpoint_calcs.data['mrn'],
                'group': self.sources.endpoint_calcs.data['group'],
                'roi_name': self.sources.endpoint_calcs.data['roi_name']
            }
            for i in range(1, options.ENDPOINT_COUNT + 1):
                ep_view["ep%s" %
                        i] = [''] * rows  # filling table with empty strings

            for r in range(len(self.sources.endpoint_defs.data['row'])):
                if r < options.ENDPOINT_COUNT:  # limiting UI to ENDPOINT_COUNT for efficiency
                    key = self.sources.endpoint_defs.data['label'][r]
                    ep_view["ep%s" %
                            (r + 1)] = self.sources.endpoint_calcs.data[key]

            self.sources.endpoint_view.data = ep_view

            if not options.LITE_VIEW:
                self.correlation.update_or_add_endpoints_to_correlation()
                categories = list(self.correlation.data['1'])
                categories.sort()

                self.regression.x.options = [''] + categories
                self.regression.y.options = [''] + categories

                self.correlation.validate_data()
                self.correlation.update_correlation_matrix()
                self.regression.update_data()

    def update_source_endpoint_view_selection(self, attr, old, new):
        if new:
            self.sources.endpoint_view.selected.indices = new

    def update_dvh_table_selection(self, attr, old, new):
        if new:
            self.sources.dvhs.selected.indices = new

    def update_dvh_review_rois(self, attr, old, new):
        if self.select_reviewed_mrn.value:
            if new != '':
                self.dvh_review_rois = self.temp_dvh_info.get_roi_names(
                    new).values()
                self.select_reviewed_dvh.options = self.dvh_review_rois
                self.select_reviewed_dvh.value = self.dvh_review_rois[0]
            else:
                self.select_reviewed_dvh.options = ['']
                self.select_reviewed_dvh.value = ['']

        else:
            self.select_reviewed_dvh.options = ['']
            self.select_reviewed_dvh.value = ''
            patches = {
                'x': [(0, [])],
                'y': [(0, [])],
                'roi_name': [(0, '')],
                'volume': [(0, '')],
                'min_dose': [(0, '')],
                'mean_dose': [(0, '')],
                'max_dose': [(0, '')],
                'mrn': [(0, '')],
                'rx_dose': [(0, '')]
            }
            self.sources.dvhs.patch(patches)

    def calculate_review_dvh(self):
        global x, y

        patches = {
            'x': [(0, [])],
            'y': [(0, [])],
            'roi_name': [(0, '')],
            'volume': [(0, 1)],
            'min_dose': [(0, '')],
            'mean_dose': [(0, '')],
            'max_dose': [(0, '')],
            'mrn': [(0, '')],
            'rx_dose': [(0, 1)]
        }

        try:
            if not self.sources.dvhs.data['x']:
                self.query.update_data()

            else:
                file_index = self.temp_dvh_info.mrn.index(
                    self.select_reviewed_mrn.value)
                roi_index = self.dvh_review_rois.index(
                    self.select_reviewed_dvh.value)
                structure_file = self.temp_dvh_info.structure[file_index]
                plan_file = self.temp_dvh_info.plan[file_index]
                dose_file = self.temp_dvh_info.dose[file_index]
                key = list(
                    self.temp_dvh_info.get_roi_names(
                        self.select_reviewed_mrn.value))[roi_index]

                rt_st = dicomparser.DicomParser(structure_file)
                rt_structures = rt_st.GetStructures()
                review_dvh = dvhcalc.get_dvh(structure_file, dose_file, key)
                dicompyler_plan = dicomparser.DicomParser(plan_file).GetPlan()

                roi_name = rt_structures[key]['name']
                volume = review_dvh.volume
                min_dose = review_dvh.min
                mean_dose = review_dvh.mean
                max_dose = review_dvh.max
                if not self.review_rx.value:
                    rx_dose = float(dicompyler_plan['rxdose']) / 100.
                    self.review_rx.value = str(round(rx_dose, 2))
                else:
                    rx_dose = round(float(self.review_rx.value), 2)

                x = review_dvh.bincenters
                if max(review_dvh.counts):
                    y = np.divide(review_dvh.counts, max(review_dvh.counts))
                else:
                    y = review_dvh.counts

                if self.radio_group_dose.active == 1:
                    f = 5000
                    bin_count = len(x)
                    new_bin_count = int(bin_count * f / (rx_dose * 100.))

                    x1 = np.linspace(0, bin_count, bin_count)
                    x2 = np.multiply(
                        np.linspace(0, new_bin_count, new_bin_count),
                        rx_dose * 100. / f)
                    y = np.interp(x2, x1, review_dvh.counts)
                    y = np.divide(y, np.max(y))
                    x = np.divide(np.linspace(0, new_bin_count, new_bin_count),
                                  f)

                if self.radio_group_volume.active == 0:
                    y = np.multiply(y, volume)

                patches = {
                    'x': [(0, x)],
                    'y': [(0, y)],
                    'roi_name': [(0, roi_name)],
                    'volume': [(0, volume)],
                    'min_dose': [(0, min_dose)],
                    'mean_dose': [(0, mean_dose)],
                    'max_dose': [(0, max_dose)],
                    'mrn': [(0, self.select_reviewed_mrn.value)],
                    'rx_dose': [(0, rx_dose)]
                }

        except:
            pass

        self.sources.dvhs.patch(patches)

        self.update_source_endpoint_calcs()

    def select_reviewed_dvh_ticker(self, attr, old, new):
        self.calculate_review_dvh()

    def review_rx_ticker(self, attr, old, new):
        if self.radio_group_dose.active == 0:
            self.sources.dvhs.patch(
                {'rx_dose': [(0, round(float(self.review_rx.value), 2))]})
        else:
            self.calculate_review_dvh()

    def radio_group_ticker(self, attr, old, new):
        if self.sources.dvhs.data['x'] != '':
            self.query.update_data()
            self.calculate_review_dvh()

    def add_query_link(self, query):
        self.query = query
Ejemplo n.º 15
0
def compare():
    # if proj among arguments, show this tree first.
    try:
        proj_a = int(request.args.get('proj_a', None))
        proj_b = int(request.args.get('proj_b', None))
    except (TypeError, ValueError):
        proj_a = proj_b = None
    include = request.args.get('include', None)

    # list of projects (and proj_names) used to create dropdown project selector
    upload_list = UserFile.query.filter_by(user_id=current_user.id).\
        filter_by(run_complete=True).order_by(UserFile.file_id).all()

    if len(upload_list) > 1:
        # Use specified project from args or highest file_id as CURRENT PROJECT
        current_proj = upload_list[-1]  # override if valid proj specified
        if proj_a and proj_b:
            current_temp_a = [u for u in upload_list if u.file_id == proj_a]
            current_temp_b = [u for u in upload_list if u.file_id == proj_b]
            # if not among user's finished projects, use highest file_id
            if len(current_temp_a) == 1 and len(current_temp_b) == 1:
                current_proj_a = current_temp_a[0]
                current_proj_b = current_temp_b[0]
            else:
                current_proj_a = upload_list[-2]
                current_proj_b = upload_list[-1]
        else:
            current_proj_a = upload_list[-2]
            current_proj_b = upload_list[-1]
        detail_path1 = naming_rules.get_detailed_path(current_proj_a)
        detail_path2 = naming_rules.get_detailed_path(current_proj_b)
        js_name1 = naming_rules.get_js_name(current_proj_a)
        js_name2 = naming_rules.get_js_name(current_proj_b)
        xlabel = u"Effect size ({})".format(current_proj_a.get_fancy_filename())
        ylabel = u"Effect size ({})".format(current_proj_b.get_fancy_filename())

        # load pathways with 1+ mutation in 1+ patients,
        # ignoring ones with 'cancer' etc in name
        all_paths1 = load_pathway_list_from_file(detail_path1)
        all_paths2 = load_pathway_list_from_file(detail_path2)

        # IDs with p<0.05 and +ve effect
        sig_p = OrderedDict(
            [(i.path_id, i.nice_name) for i in all_paths1 if i.gene_set])
        sig_pids1 = [i for i in sig_p]
        sig_p2 = OrderedDict(
            [(i.path_id, i.nice_name) for i in all_paths2 if i.gene_set])
        sig_pids2 = [i for i in sig_p2]
        sig_p.update(sig_p2)  # ORDERED by proj1 effect size

        # BUILD DATAFRAME WITH ALL sig PATHWAYS, proj1 object order.
        pway_names = sig_p.values()  # order important
        columns = ['path_id', 'pname', 'ind1', 'ind2', 'e1', 'e2', 'e1_only',
                   'e2_only', 'q1', 'q2']
        df = pd.DataFrame(index=sig_p.keys(), data={'pname': pway_names},
                          columns=columns)
        for path_group, evar, qvar, ind, sigs in \
                [(all_paths1, 'e1', 'q1', 'ind1', sig_pids1),
                 (all_paths2, 'e2', 'q2', 'ind2', sig_pids2)]:
            for path in path_group:
                path_id = path.path_id
                if path_id not in sig_p:
                    continue
                df.loc[path_id, evar] = get_effect(path)
                df.loc[path_id, qvar] = get_q(path)
                temp_ind = sigs.index(path_id) if path_id in sigs else -1
                df.loc[path_id, ind] = temp_ind
        df.ind1.fillna(-1, inplace=True)
        df.ind2.fillna(-1, inplace=True)
        df.e1_only = df.where(df.e2.isnull())['e1']
        df.e2_only = df.where(df.e1.isnull())['e2']

        inds1 = list(df.ind1)
        inds2 = list(df.ind2)

        source = ColumnDataSource(data=df)
        source_full = ColumnDataSource(data=df)
        source.name, source_full.name = 'data_visible', 'data_full'
        # SET UP FIGURE
        minx = df.e1.min()
        minx *= 1 - minx / abs(minx) * 0.2
        miny = df.e2.min()
        miny *= 1 - miny/abs(miny) * 0.2
        maxx = df.e1.max() * 1.2
        maxy = df.e2.max() * 1.2
        TOOLS = "lasso_select,box_select,hover,crosshair,pan,wheel_zoom,"\
                "box_zoom,reset,tap,help" # poly_select,lasso_select, previewsave

        # SUPLOTS
        p = figure(plot_width=DIM_COMP_W, plot_height=DIM_COMP_H, tools=TOOLS,
                   title=None, logo=None, toolbar_location="above",
                   x_range=Range1d(minx, maxx), y_range=Range1d(miny, maxy),
                   x_axis_type="log", y_axis_type="log"
                   )
        pb = figure(plot_width=DIM_COMP_SM, plot_height=DIM_COMP_H, tools=TOOLS,
                    y_range=p.y_range, x_axis_type="log", y_axis_type="log")
        pa = figure(plot_width=DIM_COMP_W, plot_height=DIM_COMP_SM, tools=TOOLS,
                    x_range=p.x_range, x_axis_type="log", y_axis_type="log")
        pp = figure(plot_width=DIM_COMP_SM, plot_height=DIM_COMP_SM,
                    tools=TOOLS, outline_line_color=None)

        # SPANS
        p.add_layout(plot_fns.get_span(1, 'height'))
        p.add_layout(plot_fns.get_span(1, 'width'))
        pa.add_layout(plot_fns.get_span(1, 'height'))
        pb.add_layout(plot_fns.get_span(1, 'width'))

        # STYLE
        for ax in [p, pa, pb]:
            ax.grid.visible = False
            ax.outline_line_width = 2
            ax.background_fill_color = 'whitesmoke'
        for ax in [pa, pb]:
            ax.xaxis.visible = False
            ax.yaxis.visible = False

        pa.title.text = xlabel
        pb.title.text = ylabel
        pa.title_location, pa.title.align = 'below', 'center'
        pb.title_location, pb.title.align = 'left', 'center'

        # WIDGETS
        q_input = TextInput(value='', title="P* cutoff",
                            placeholder='e.g. 0.05')
        gene_input = TextInput(value='', title="Gene list",
                               placeholder='e.g. TP53,BRAF')
        radio_include = RadioGroup(labels=["Include", "Exclude"], active=0)
        widgets = widgetbox(q_input, gene_input, radio_include, width=200,
                            css_classes=['widgets_sg'])

        grid = gridplot([[pb, p, widgets],
                         [Spacer(width=DIM_COMP_SM), pa, Spacer()]],
                        sizing_mode='fixed')

        cb_inclusion = CustomJS(args=dict(genes=gene_input), code="""
            var gene_str = genes.value
            if (!gene_str)
                return;
            var include = cb_obj.active == 0 ? true : false
            selectPathwaysByGenes(gene_str, include);
            """)
        cb_genes = CustomJS(args=dict(radio=radio_include), code="""
            var gene_str = cb_obj.value
            if (!gene_str)
                return;
            var include = radio.active == 0 ? true : false
            selectPathwaysByGenes(gene_str, include);
            """)
        radio_include.js_on_change('active', cb_inclusion)
        gene_input.js_on_change('value', cb_genes)

        # SCATTER
        p.circle("e1", "e2", source=source, **SCATTER_KW)
        pa.circle('e1_only', 1, source=source, **SCATTER_KW)
        pb.circle(1, 'e2_only', source=source, **SCATTER_KW)

        # HOVER
        for hover in grid.select(dict(type=HoverTool)):
            hover.tooltips = OrderedDict([
                ("name", "@pname"),
                ("effects", "(@e1, @e2)"),
                ("P*", ("(@q1, @q2)"))
            ])

        # ADD Q FILTERING CALLBACK
        callback = CustomJS(args=dict(source=source, full=source_full), code="""
            // get old selection indices, if any
            var prv_selected = source.selected['1d'].indices;
            var prv_select_full = []
            for(var i=0; i<prv_selected.length; i++){
                prv_select_full.push(scatter_array[prv_selected[i]])
            }
            var new_selected = []
            var q_val = cb_obj.value;
            if(q_val == '')
                q_val = 1
            var fullset = full.data;
            var n_total = fullset['e1'].length;
            // Convert float64arrays to array
            var col_names = %s ;
            col_names.forEach(function(col_name){
                source.data[col_name] = [].slice.call(source.data[col_name])
                source.data[col_name].length = 0
            })
            scatter_array.length = 0;
            var j = -1;  // new glyph indices
            for (i = 0; i < n_total; i++) {
                this_q1 = fullset['q1'][i];
                this_q2 = fullset['q2'][i];
                if(this_q1 <= q_val || this_q2 <= q_val){
                    j++; // preserve previous selection if still visible
                    col_names.forEach(function(col){
                        source.data[col].push(fullset[col][i]);
                    })
                    scatter_array.push(i)
                    if($.inArray(i, prv_select_full) > -1){
                        new_selected.push(j);
                    }
                }
            }
            source.selected['1d'].indices = new_selected;
            source.trigger('change');
            updateIfSelectionChange_afterWait();
            """ % columns)

        q_input.js_on_change('value', callback)
        script, div = plot_fns.get_bokeh_components(grid)

        proj_dir_a = naming_rules.get_project_folder(current_proj_a)
        proj_dir_b = naming_rules.get_project_folder(current_proj_b)
        if os.path.exists(os.path.join(proj_dir_a, 'matrix_svg_cnv')) and \
                os.path.exists(os.path.join(proj_dir_b, 'matrix_svg_cnv')):
            has_cnv = True
        else:
            has_cnv = False

    else:  # not enough projects yet!
        flash("Two completed projects are required for a comparison.",
              "warning")
        return redirect(url_for('.index'))

    return render_template('pway/compare.html',
                           current_projs=[current_proj_a, current_proj_b],
                           inds_use=[inds1, inds2],
                           has_cnv=has_cnv,
                           js_name_a=js_name1,
                           js_name_b=js_name2,
                           projects=upload_list,
                           bokeh_script=script,
                           bokeh_div=div, include_genes=include,
                           resources=plot_fns.resources)
Ejemplo n.º 16
0
	def plotting(self):

		if self.debug:
			self.debug_file = open("debug_output.txt", "w")
			self.debug_file.write("Initialized plotting subroutine \n")
			 

		TOOLS="pan,wheel_zoom,box_zoom,reset,hover,previewsave"

		tab_plots = []
		self.all_elements = []
		self.elements_comparison = []

		for filename in self.filenames:
			if "ITO" in filename:
				tab_plots.append(self.mass_plotting(filename))
				continue
	
			data_dict = self.data_generation(filename)
			self.data_test(data_dict)

			name_check = data_dict["gen_info"]["DATA FILES"]
			attr_id = name_check[1][4][:-3] + "_" + name_check[2][2]
			self.attribute_ids.append(attr_id)

			attr_extra_y_ranges = False
			attr_extra_x_ranges = False

			local_source_line = []

			"""
			create plots for each datafile and put them in a tab.
			"""

			y_axis_units = [x["y_unit"] for x in data_dict["data"]]
			x_axis_units = [x["x_unit"] for x in data_dict["data"]]

			figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log",
			title = attr_id, tools = TOOLS)
			#figure_obj.axes.major_label_text_font_size("12pt")
			#figure_obj.major_label_text_font_size("12pt")

			hover = figure_obj.select(dict(type = HoverTool))
			hover.tooltips = [
							("Element:", "@element"),
							("(x, y):", "($x, $y)")]

			self.figure_data.append((figure_obj, data_dict))
		
			figure_obj.yaxis.axis_label = y_axis_units[0]
			figure_obj.xaxis.axis_label = x_axis_units[0]

			if not all(x == y_axis_units[0] for x in y_axis_units):
				for unit, dataset in zip(y_axis_units, data_dict["data"]): 
					if not unit == y_axis_units[0]:
						
						extra_y_ranges_exists = attr_extra_y_ranges
						extra_y_ranges_exists = True

						if self.debug:
							  
							self.debug_file.write("Added extra y-axis for file_id: %s, element: %s | New length %g \n" 
								%(attr_id, dataset["sample_element"], len(figure_obj.yaxis)))
							 

						figure_obj.extra_y_ranges =  {"foo": Range1d(start = np.amin(dataset["y"]),
						end = np.amax(dataset["y"]))}
						figure_obj.add_layout(LogAxis(y_range_name = "foo", axis_label = unit), "right")
						break

			if not all(x == x_axis_units[0] for x in x_axis_units):
				for unit, dataset in zip(x_axis_units, data_dict["data"]): 
					if not unit == x_axis_units[0]:
						
						extra_x_ranges_exists = attr_extra_x_ranges
						extra_x_ranges_exists = True
						
						if self.debug:
							  
							self.debug_file.write("Added extra x-axis for file_id: %s, element: %s. | New length %g \n" 
								%(attr_id, dataset["sample_element"], len(figure_obj.yaxis)))
							 
			
						figure_obj.extra_x_ranges =  {"bar": Range1d(start = np.amin(dataset["x"]),
						end = np.amax(dataset["x"]))}
						figure_obj.add_layout(LinearAxis(x_range_name = "bar", axis_label = unit), "above")
						break

			figure_obj.xaxis.axis_label = x_axis_units[0]
			colour_list = Spectral11 + RdPu9 + Oranges9
			colour_indices = [0, 2, 8, 10, 12, 14, 20, 22, 1, 3, 9, 11, 13, 15]


			list_of_elements = []
			source_list = []
			line_list = []

			for dataset, color_index in zip(data_dict["data"], colour_indices):

				self.all_elements.append(dataset["sample_element"]) #strip isotope number 
				color = colour_list[color_index]

				source = ColumnDataSource(data = dataset) #Datastructure for source of plotting

				self.source_test(source)

				list_of_elements.append(dataset["sample_element"])
				line_glyph = figure_obj.line("x", "y", source = source, 
							line_width = 2,
							line_color = color, 
							legend = dataset["sample_element"])

				if self.debug:
					self.debug_file.write("Create line object on figure %s  at %s \n" %(id(figure_obj), id(line_glyph)))
					 

				line_list.append(line_glyph)
				source_list.append(source)

			local_source_line.append([[source, line] for source, line in zip(source_list, line_list)])
			self.source_line.append(local_source_line)

			#Calculations on the dataset
			text_input_rsf = TextInput(value = "default", title = "RSF or SF (at/cm^3): ")
			do_integral_button = Button(label = "Calibration integral")
			smoothing_button = Button(label = "smth selct elem")
			matplot_button = Button(label = "Create matplotlib fig")

			text_input_sputter = TextInput(value = "default", title = "Sputter speed: number unit")
			text_input_crater_depth = TextInput(value = "default", title = "Depth of crater in: number unit")
			


			radio_group = RadioGroup(labels = list_of_elements, active=0)


			text_input_xval_integral = TextInput(value = "0", title = "x-delimiter ")
			text_input_dose = TextInput(value = "0", title = "Dose[cm^-2] ")

			#Save files for later use
			save_flexDPE_button = Button(label = "Save element for FlexPDE")
			save_all_flexDPE_button = Button(label = "Save all elements for FlexPDE")
			save_textfile_button = Button(label = "Sava Data in textfile")

			#Pointers to methods on click / change handlers
			radio_group.on_change("active", lambda attr, old, new: None)

			matplot_button.on_click(lambda source_list = source_list:
										self.matplotlib_export(source_list))
			
			do_integral_button.on_click(lambda 
											source_list = source_list, 
											line_list = line_list, 
											source_line = self.source_line,
											figure_data = self.figure_data,
											data_dict = data_dict,
											radio = radio_group,
											x_box = text_input_xval_integral, 
											dose = text_input_dose,
											extra_y_ranges = attr_extra_y_ranges: 
										self.integrate(data_dict, source_list, line_list, source_line, figure_data, radio, x_box, dose, extra_y_ranges))

			smoothing_button.on_click(lambda 
										source_list = source_list,
										radio = radio_group, 
										data_dict = data_dict,
										x_box = text_input_xval_integral: 
									self.smoothing(source_list, data_dict, radio, x_box) )

			save_flexDPE_button.on_click(lambda 
											source_list = source_list,
											attrname = attr_id,
											radio = radio_group: 
										self.write_to_flexPDE(source_list, attrname, radio))

			save_all_flexDPE_button.on_click(lambda 
												source_list = source_list, 
												attrname = attr_id:
												self.write_all_to_flexPDE(source_list, attrname))

			save_textfile_button.on_click(lambda 
											data_dict = data_dict, 
											source_list = source_list,
											attrname = attr_id,
											radio = radio_group:
											self.write_new_datafile(data_dict, source_list, attrname,radio))


			text_input_rsf.on_change("value", lambda attr, old, new, 
												radio = radio_group, 
												data_dict = data_dict,
												figure = figure_obj,
												source_list = source_list,
												text_input = text_input_rsf,
												line_list = line_list,
												which = "rsf":
												self.update_data(line_list, data_dict, source_list, figure, radio, text_input, new, which))


			text_input_sputter.on_change("value", lambda attr, old, new, 
													radio = radio_group, 
													data_dict = data_dict,
													figure = figure_obj,
													source_list = source_list, 
													text_input = text_input_sputter,
													which = "sputter":
													self.update_data(data_dict, source_list, figure, radio, text_input, new, which))

			text_input_crater_depth.on_change("value", lambda attr, old, new, 
														radio = radio_group, 
														data_dict = data_dict,
														source_list = source_list,
														figure = figure_obj,
														text_input = text_input_crater_depth, 
														which = "crater_depth":
														self.update_data(data_dict, source_list, figure, radio, text_input, new, which))


			#Initialization of actual plotting. 
			tab_plots.append(Panel(child = hplot(figure_obj, 
										   vform(
										   vform(radio_group, save_flexDPE_button, save_all_flexDPE_button, save_textfile_button, matplot_button), 
										   vform(text_input_rsf, smoothing_button, text_input_sputter, text_input_crater_depth)
										   ),
										   vform(text_input_xval_integral, text_input_dose, do_integral_button)),
										   title = attr_id))



		"""
		Check to see if one or more element exists in the samples and creat a comparison plot for each 
		of those elements.
		"""
		
		for element in self.all_elements:
			checkers = list(self.all_elements)
			checkers.remove(element)
			if element in checkers and not element in self.elements_comparison:
				self.elements_comparison.append(element)

		"""create plots for each element that is to be compared """
	
		for comparison_element in self.elements_comparison: 

			figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log", title = comparison_element, tools = TOOLS)
			#figure_obj.xaxis.major_label_text_font_size("12pt")
			#figure_obj.yaxis.major_label_text_font_size("12pt")
			
			y_axis_units = []
			x_axis_units = []

			comparison_datasets = []

			for data_dict_iter in self.column(self.figure_data, 1):

				for dataset in data_dict_iter["data"]:

					if dataset["sample_element"] == comparison_element:
						comparison_datasets.append(dataset)
						y_axis_units.append(dataset["y_unit"])
						x_axis_units.append(dataset["x_unit"])

			figure_obj.xaxis.axis_label = comparison_datasets[-1]["x_unit"]
			figure_obj.yaxis.axis_label = comparison_datasets[-1]["y_unit"]

			if not all(x == y_axis_units[-1] for x in y_axis_units):
				for unit, data in zip(y_axis_units, comparison_datasets): 
					if not unit == y_axis_units[-1]:
						figure_obj.extra_y_ranges =  {"foo": Range1d(start = np.amin(data["y"]),
						end = np.amax(data["y"]))}
						figure_obj.add_layout(LogAxis(y_range_name = "foo", axis_label = unit), "right")
						break

			if not all(x == x_axis_units[-1] for x in x_axis_units):
				for unit, data in zip(x_axis_units, comparison_datasets): 
					if not unit == x_axis_units[-1]:
						figure_obj.extra_x_ranges =  {"bar": Range1d(start = np.amin(data["x"]),
						end = np.amax(data["x"]))}
						figure_obj.add_layout(LinearAxis(x_range_name = "bar", axis_label = unit), "above")
						break

			active_sources = []
			for data_dict, source_line_nested, attr_id, color_index  in zip(self.column(self.figure_data, 1), self.source_line,  self.attribute_ids,  colour_indices):

				for dataset, source_lis_coup, in zip(data_dict["data"], source_line_nested[0]):
					
					source_local = source_lis_coup[0]
					active_sources.append(source_local)

					self.source_test(source_local)
					self.source_dataset_test(source_local, dataset)

					if dataset["sample_element"] == comparison_element:
						color = colour_list[color_index]

						"""
						Logic that ensures that plots get put with correspoinding axes. 
						"""
						if dataset["x_unit"] != x_axis_units[-1] or dataset["y_unit"] != y_axis_units[-1]:

							if dataset["x_unit"] != x_axis_units[-1] and dataset["y_unit"] != y_axis_units[-1]:
								name_check = data_dict["gen_info"]["DATA FILES"]
								attr_id = name_check[1][4][:-3] + "_" + name_check[2][2]

								figure_obj.line("x", "y", source = source_local,
								line_width = 2, 
								line_color = color, 
								legend = attr_id,
								x_range_name = "bar", 
								y_range_name = "foo")

							elif dataset["x_unit"] != x_axis_units[-1]:

								figure_obj.line("x", "y", source = source_local,
								line_width = 2, 
								line_color = color, 
								legend = attr_id, 
								x_range_name = "bar")

							else: 

								figure_obj.line("x", "y", source = source_local,
								line_width = 2, 
								line_color = color, 
								legend = attr_id, 
								y_range_name = "foo")

						else: 
							figure_obj.line("x", "y", source = source_local,
							line_width = 2, 
							line_color = color, 
							legend = attr_id)


			matplot_button = Button(label = "Create matplotlib fig")
			save_all_flexDPE_button = Button(label = "Save all elements for FlexPDE")

			matplot_button.on_click(lambda source_list = active_sources:
							self.matplotlib_export(source_list))	

			save_all_flexDPE_button.on_click(lambda 
									source_list = active_sources, 
									attrname = comparison_element:
									self.write_all_to_flexPDE(source_list, attrname))


			tab_plots.append(Panel(child = hplot(figure_obj, vform(save_all_flexDPE_button, matplot_button)), 
				title = comparison_element))	


		tabs = Tabs(tabs = tab_plots)
		#curdoc().add_root(tabs)
		session = push_session(curdoc())
		session.show()
		session.loop_until_closed()
Ejemplo n.º 17
0
menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")]

dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
dropdown.js_on_click(CustomJS(code="console.log('dropdown: ' + this.value, this.toString())"))

dropdown_disabled = Dropdown(label="Dropdown button (disabled)", button_type="warning", disabled=True, menu=menu)
dropdown_disabled.js_on_click(CustomJS(code="console.log('dropdown_disabled: ' + this.value, this.toString())"))

#dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default")
#dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())"))

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: ' + this.active, this.toString())"))

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.js_on_click(CustomJS(code="console.log('radio_group: ' + this.active, this.toString())"))

checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.js_on_click(CustomJS(code="console.log('checkbox_button_group: ' + this.active, this.toString())"))

radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.js_on_click(CustomJS(code="console.log('radio_button_group: ' + this.active, this.toString())"))

widget_box = WidgetBox(children=[
    button, button_disabled,
    toggle_inactive, toggle_active,
    dropdown, dropdown_disabled, #dropdown_split,
    checkbox_group, radio_group,
    checkbox_button_group, radio_button_group,
])
Ejemplo n.º 18
0
dropdown.on_click(lambda value: print('dropdown: %s' % value))
dropdown.js_on_click(CustomJS(code="console.log('dropdown: ' + this.value, this.toString())"))

dropdown_disabled = Dropdown(label="Dropdown button (disabled)", button_type="warning", menu=menu)
dropdown_disabled.on_click(lambda value: print('dropdown_disabled: %s' % value))
dropdown_disabled.js_on_click(CustomJS(code="console.log('dropdown_disabled: ' + this.value, this.toString())"))

#dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default")
#dropdown_split.on_click(lambda value: print('dropdown_split: %s' % value))
#dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())"))

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_group.on_click(lambda value: print('checkbox_group: %s' % value))
checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: ' + this.active, this.toString())"))

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(lambda value: print('radio_group: %s' % value))
radio_group.js_on_click(CustomJS(code="console.log('radio_group: ' + this.active, this.toString())"))

checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(lambda value: print('checkbox_button_group: %s' % value))
checkbox_button_group.js_on_click(CustomJS(code="console.log('checkbox_button_group: ' + this.active, this.toString())"))

radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.on_click(lambda value: print('radio_button_group: %s' % value))
radio_button_group.js_on_click(CustomJS(code="console.log('radio_button_group: ' + this.active, this.toString())"))

widgetBox = WidgetBox(children=[
    button, button_disabled,
    toggle_inactive, toggle_active,
    dropdown, dropdown_disabled, #dropdown_split,
Ejemplo n.º 19
0
from bokeh.plotting import figure

x=[3,4,6,12,10,1,5,6,3,8]
y=[7,1,3,4,1,6,10,4,10,3]
label=['Red', 'Orange', 'Red', 'Orange','Red', 'Orange','Red', 'Orange','Red', 'Orange',]

df=pd.DataFrame({'x':x,'y':y,'label':label})

source = ColumnDataSource(data=dict(x=df.x, y=df.y,label=df.label))

plot_figure = figure(title='Radio Group',plot_height=450, plot_width=600,
              tools="save,reset", toolbar_location="below")

plot_figure.scatter('x', 'y',color='label', source=source, size=10)

radio_group = RadioGroup(labels=["Red", "Orange"])

def radiogroup_click(attr,old,new):
    active_radio=radio_group.active ##Getting radio button value

    # filter the dataframe with value in radio-button
    if active_radio==0:
        selected_df = df[df['label'] == 'Red']
    elif active_radio==1:
        selected_df = df[df['label'] == "Orange"]

    source.data=dict(x=selected_df.x, y=selected_df.y,label=selected_df.label)


radio_group.on_change('active',radiogroup_click)
Ejemplo n.º 20
0
    def __init__(self):

        self.grepolis = Grepolis()

        imgRessource = []
        for v in ["Bois", "Pierre", "Argent"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgRessource.append(Image(d))
        colRess = column(*[img.figure for img in imgRessource])
        self.inputRess = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Bois", "Pierre", "Argent"]
        ]
        colinputRess = column(*self.inputRess)

        imgDieu = []
        for v in ["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDieu.append(Image(d, multiplier=3))
        rowDieu = [HFill(5)]
        for img in imgDieu:
            rowDieu.append(HFill(5))
            rowDieu.append(img.figure)
        rowDieu = row(*rowDieu)

        imgAtt = []
        for v in ["Att_hack", "Att_sharp", "Att_distance"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgAtt.append(Image(d))
        colAtt = column(*[img.figure for img in imgAtt])
        self.inputAtt = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Contondantes", "Blanches", "De Jet"]
        ]
        colinputAtt = column(*self.inputAtt)

        imgDef = []
        for v in ["Def_hack", "Def_sharp", "Def_distance"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDef.append(Image(d))
        colDef = column(*[img.figure for img in imgDef])

        self.inputDef = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Contondantes", "Blanches", "De Jet"]
        ]
        rowinputDef = column(*self.inputDef)

        imgOther = []
        for v in ["Vitesse", "Butin", "Faveur"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgOther.append(Image(d))

        colOther = column(*[img.figure for img in imgOther])

        self.inputFavBut = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Vitesse", "Butin", "Faveur"]
        ]
        self.inputOther = column(*self.inputFavBut)

        self.imgUnit = []
        for v in [
                "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier",
                "Char", "Envoye", "Centaure", "Pegase"
        ]:
            r = "static/" + v + ".jpg"
            d = dict(url=[r])
            self.imgUnit.append(Image(d, multiplier=2))
        rowUnit = row(HFill(10), *[img.figure for img in self.imgUnit])

        imgDefAtt = []
        for v in ["Pop", "Attaque", "Defense"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDefAtt.append(Image(d))

        rowInputUnit = [HFill(10)]
        self.unitInput = [
            TextInput(value="", title=el + " :", width=80) for el in [
                "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier",
                "Char", "Envoye", "Centaure", "Pegase"
            ]
        ]
        for inp in self.unitInput:
            rowInputUnit.append(inp)
            rowInputUnit.append(HFill(30))
        rowInputUnit = row(HFill(10), *rowInputUnit)

        self.selectUnit = CheckboxButtonGroup(labels=[
            "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier", "Char",
            "Envoye", "Centaure", "Pegase"
        ],
                                              active=[i for i in range(9)])
        self.selectUnit.on_change("active", self.updateSelectUnit)
        self.Dieu = RadioButtonGroup(
            labels=["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"],
            active=0,
            width=1110)
        self.Dieu.on_change('active', self.updateUnit)

        self.attdef = RadioButtonGroup(labels=["Attaque", "Defense"],
                                       active=0,
                                       width=200)
        self.attdef.on_change('active', self.switchAttDef)

        self.typeAtt = RadioGroup(
            labels=["Armes Contondantes", "Armes Blanches", "Armes de Jet"],
            active=0,
            width=150)
        self.typeAtt.on_change('active', self.process2)
        self.imgFaveur = Image(dict(url=["static/" + "Faveur" + ".png"]))

        self.launch = Button(label="Lancer")
        self.launch.on_click(self.process)

        self.inputPop = TextInput(value="1500",
                                  title="Population : ",
                                  width=120)
        self.inputPop.on_change("value", self.process2)

        self.inputFav = TextInput(value="1500",
                                  title="Faveur Max : ",
                                  width=120)
        self.inputFav.on_change("value", self.process2)

        rowPop = row(HFill(10), self.typeAtt, imgDefAtt[1].figure, self.attdef,
                     HFill(30), imgDefAtt[2].figure, HFill(50),
                     imgDefAtt[0].figure, self.inputPop, HFill(50),
                     self.imgFaveur.figure, self.inputFav, HFill(50))
        self.doc = column(
            rowDieu, self.Dieu, VFill(20), rowPop, VFill(20), self.selectUnit,
            rowUnit, rowInputUnit, VFill(20),
            row(HFill(50), colRess, colinputRess,
                HFill(40), colAtt, colinputAtt, HFill(40), colDef, rowinputDef,
                HFill(40), colOther, self.inputOther))
        #curdoc().add_root(column(rowDieu,self.Dieu,VFill(20),rowPop,VFill(20),self.selectUnit,rowUnit,rowInputUnit,VFill(20),row(HFill(50),colRess,colinputRess,HFill(40),colAtt,colinputAtt,HFill(40),colDef,rowinputDef,HFill(40),colOther,self.inputOther)))
        self.process(None)
Ejemplo n.º 21
0
def select_battype_handler(attr, old, new):
  settings['bat_type'] = new
select_battype.on_change('value', select_battype_handler)

select_chrg_type = Select(title="Charge Type", value="Charge", options=["Charge", "Discharge", "Cycle", "Re-Peak", "AutoCharge", "Balance Charge", "Fast Charge", "Storage"])
def select_chrg_type_handler(attr, old, new):
  settings['chrg_type'] = new

select_chrg_type.on_change('value', select_chrg_type_handler)

maxmah_slider = Slider(start=50, end=24000, value=1, step=50, title="Bat. Specified Capacity, mah")
def maxmah_handler(attr, old, new):
  settings['nominal_mah'] = new
maxmah_slider.on_change('value', maxmah_handler)

DC_radio_group = RadioGroup(labels=["Discharge/Charge", "Charge/Discharge"], active=0)
def DC_radio_handler(new):
  settings['DC'] = new  
DC_radio_group.on_click(DC_radio_handler)

select_cells = Select(title = "No. of Cells", value ="4", options = [str(i) for i in range(1,13)])
def select_cells_handler(attr, old, new):
  settings['cells'] = new
select_cells.on_change('value', select_cells_handler)

#imax discharge/charge # of cycles; imax limit is 5
#no way to read this from imax only shows up in set up packet
select_cycles = Select(title = "Cycles", value ="1", options = [str(i) for i in range(1,6)])
def select_cycles_handler(attr, old, new):
  settings['cycles'] = new
select_cycles.on_change('value', select_cycles_handler)
Ejemplo n.º 22
0
    def __init__(self, sources, time_series, correlation, regression,
                 custom_title, data_tables):
        self.sources = sources
        self.time_series = time_series
        self.correlation = correlation
        self.regression = regression

        self.dvh_review_rois = []
        self.query = None

        self.temp_dvh_info = Temp_DICOM_FileSet()
        self.dvh_review_mrns = self.temp_dvh_info.mrn
        if self.dvh_review_mrns[0] != '':
            self.dvh_review_rois = self.temp_dvh_info.get_roi_names(
                self.dvh_review_mrns[0]).values()
            self.dvh_review_mrns.append('')
        else:
            self.dvh_review_rois = ['']

        # Add Current row to source
        self.add_endpoint_row_button = Button(label="Add Endpoint",
                                              button_type="primary",
                                              width=200)
        self.add_endpoint_row_button.on_click(self.add_endpoint)

        self.ep_row = Select(value='', options=[''], width=50, title="Row")
        self.ep_options = [
            "Dose (Gy)", "Dose (%)", "Volume (cc)", "Volume (%)"
        ]
        self.select_ep_type = Select(value=self.ep_options[0],
                                     options=self.ep_options,
                                     width=180,
                                     title="Output")
        self.select_ep_type.on_change('value', self.select_ep_type_ticker)
        self.ep_text_input = TextInput(value='',
                                       title="Input Volume (cc):",
                                       width=180)
        self.ep_text_input.on_change('value', self.ep_text_input_ticker)
        self.ep_units_in = RadioButtonGroup(labels=["cc", "%"],
                                            active=0,
                                            width=100)
        self.ep_units_in.on_change('active', self.ep_units_in_ticker)
        self.delete_ep_row_button = Button(label="Delete",
                                           button_type="warning",
                                           width=100)
        self.delete_ep_row_button.on_click(self.delete_ep_row)

        tools = "pan,wheel_zoom,box_zoom,reset,crosshair,save"
        self.plot = figure(plot_width=1050,
                           plot_height=500,
                           tools=tools,
                           logo=None,
                           active_drag="box_zoom")
        self.plot.min_border_left = options.MIN_BORDER
        self.plot.min_border_bottom = options.MIN_BORDER
        self.plot.add_tools(
            HoverTool(show_arrow=False,
                      line_policy='next',
                      tooltips=[('Label', '@mrn @roi_name'), ('Dose', '$x'),
                                ('Volume', '$y')]))
        self.plot.xaxis.axis_label_text_font_size = options.PLOT_AXIS_LABEL_FONT_SIZE
        self.plot.yaxis.axis_label_text_font_size = options.PLOT_AXIS_LABEL_FONT_SIZE
        self.plot.xaxis.major_label_text_font_size = options.PLOT_AXIS_MAJOR_LABEL_FONT_SIZE
        self.plot.yaxis.major_label_text_font_size = options.PLOT_AXIS_MAJOR_LABEL_FONT_SIZE
        self.plot.yaxis.axis_label_text_baseline = "bottom"
        self.plot.lod_factor = options.LOD_FACTOR  # level of detail during interactive plot events

        # Add statistical plots to figure
        stats_median_1 = self.plot.line(
            'x',
            'median',
            source=sources.stats_1,
            line_width=options.STATS_1_MEDIAN_LINE_WIDTH,
            color=options.GROUP_1_COLOR,
            line_dash=options.STATS_1_MEDIAN_LINE_DASH,
            alpha=options.STATS_1_MEDIAN_ALPHA)
        stats_mean_1 = self.plot.line(
            'x',
            'mean',
            source=sources.stats_1,
            line_width=options.STATS_1_MEAN_LINE_WIDTH,
            color=options.GROUP_1_COLOR,
            line_dash=options.STATS_1_MEAN_LINE_DASH,
            alpha=options.STATS_1_MEAN_ALPHA)
        stats_median_2 = self.plot.line(
            'x',
            'median',
            source=sources.stats_2,
            line_width=options.STATS_2_MEDIAN_LINE_WIDTH,
            color=options.GROUP_2_COLOR,
            line_dash=options.STATS_2_MEDIAN_LINE_DASH,
            alpha=options.STATS_2_MEDIAN_ALPHA)
        stats_mean_2 = self.plot.line(
            'x',
            'mean',
            source=sources.stats_2,
            line_width=options.STATS_2_MEAN_LINE_WIDTH,
            color=options.GROUP_2_COLOR,
            line_dash=options.STATS_2_MEAN_LINE_DASH,
            alpha=options.STATS_2_MEAN_ALPHA)

        # Add all DVHs, but hide them until selected
        self.plot.multi_line('x',
                             'y',
                             source=sources.dvhs,
                             selection_color='color',
                             line_width=options.DVH_LINE_WIDTH,
                             alpha=0,
                             line_dash=options.DVH_LINE_DASH,
                             nonselection_alpha=0,
                             selection_alpha=1)

        # Shaded region between Q1 and Q3
        iqr_1 = self.plot.patch('x_patch',
                                'y_patch',
                                source=sources.patch_1,
                                alpha=options.IQR_1_ALPHA,
                                color=options.GROUP_1_COLOR)
        iqr_2 = self.plot.patch('x_patch',
                                'y_patch',
                                source=sources.patch_2,
                                alpha=options.IQR_2_ALPHA,
                                color=options.GROUP_2_COLOR)

        # Set x and y axis labels
        self.plot.xaxis.axis_label = "Dose (Gy)"
        self.plot.yaxis.axis_label = "Normalized Volume"

        # Set the legend (for stat dvhs only)
        legend_stats = Legend(items=[("Median", [stats_median_1]),
                                     ("Mean", [stats_mean_1]),
                                     ("IQR", [iqr_1]),
                                     ("Median", [stats_median_2]),
                                     ("Mean", [stats_mean_2]),
                                     ("IQR", [iqr_2])],
                              location=(25, 0))

        # Add the layout outside the plot, clicking legend item hides the line
        self.plot.add_layout(legend_stats, 'right')
        self.plot.legend.click_policy = "hide"

        self.download_endpoints_button = Button(label="Download Endpoints",
                                                button_type="default",
                                                width=150)
        self.download_endpoints_button.callback = CustomJS(
            args=dict(source=sources.endpoint_calcs),
            code=open(join(dirname(__file__), "download_endpoints.js")).read())

        # Setup axis normalization radio buttons
        self.radio_group_dose = RadioGroup(
            labels=["Absolute Dose", "Relative Dose (Rx)"],
            active=0,
            width=200)
        self.radio_group_dose.on_change('active', self.radio_group_ticker)
        self.radio_group_volume = RadioGroup(
            labels=["Absolute Volume", "Relative Volume"], active=1, width=200)
        self.radio_group_volume.on_change('active', self.radio_group_ticker)

        # Setup selectors for dvh review
        self.select_reviewed_mrn = Select(title='MRN to review',
                                          value='',
                                          options=self.dvh_review_mrns,
                                          width=300)
        self.select_reviewed_mrn.on_change('value',
                                           self.update_dvh_review_rois)

        self.select_reviewed_dvh = Select(title='ROI to review',
                                          value='',
                                          options=[''],
                                          width=360)
        self.select_reviewed_dvh.on_change('value',
                                           self.select_reviewed_dvh_ticker)

        self.review_rx = TextInput(value='', title="Rx Dose (Gy):", width=170)
        self.review_rx.on_change('value', self.review_rx_ticker)

        if options.LITE_VIEW:
            self.layout = column(
                Div(text="<b>DVH Analytics v%s</b>" % options.VERSION),
                row(self.radio_group_dose,
                    self.radio_group_volume), self.add_endpoint_row_button,
                row(self.ep_row, Spacer(width=10), self.select_ep_type,
                    self.ep_text_input, Spacer(width=20),
                    self.ep_units_in, self.delete_ep_row_button,
                    Spacer(width=50), self.download_endpoints_button),
                data_tables.ep)
        else:
            self.layout = column(
                Div(text="<b>DVH Analytics v%s</b>" % options.VERSION),
                row(custom_title['1']['dvhs'], Spacer(width=50),
                    custom_title['2']['dvhs']),
                row(self.radio_group_dose, self.radio_group_volume),
                row(self.select_reviewed_mrn, self.select_reviewed_dvh,
                    self.review_rx), self.plot,
                Div(text="<b>DVHs</b>", width=1200), data_tables.dvhs,
                Div(text="<hr>", width=1050),
                Div(text="<b>Define Endpoints</b>",
                    width=1000), self.add_endpoint_row_button,
                row(self.ep_row, Spacer(width=10), self.select_ep_type,
                    self.ep_text_input, Spacer(width=20),
                    self.ep_units_in, self.delete_ep_row_button,
                    Spacer(width=50), self.download_endpoints_button),
                data_tables.ep, Div(text="<b>DVH Endpoints</b>",
                                    width=1200), data_tables.endpoints)
Ejemplo n.º 23
0
                                               )
                                          )
                                          for l in new_relative_source.columns.tolist()]
    for old, new in zip(abs_point_sources, new_abs_point_sources):
        old.data.update(new.data)
    for old, new in zip(rel_point_sources, new_rel_point_sources):
        old.data.update(new.data)

# Create Input controls
timegroupoptionsmapper = {0:"A", 1:"M", 2:"D"}
trendingoptionsmapper = {0:False, 1:True}
timegroupoptions = ["Year", "Month", "Day"]

top_n = Slider(title="Number of top-n items to display", value=10, start=1, end=10, step=1)
dictchooser = Select(title="dictionaries", options=dictionaries, value=dictionaries[-2])
timegroup = RadioGroup(labels=timegroupoptions, active=0)
trending_chooser = RadioGroup(labels=["absolute counts", "period-to-period change"], active=0)

initial_subset = get_subset(dictchooser.value)
abs_sources = [ColumnDataSource(dict(date=initial_subset[0].index, y=initial_subset[0][l])) for l in initial_subset[0].columns.tolist()[:top_n.value]]
rel_sources = [ColumnDataSource(dict(date=initial_subset[1].index, y=initial_subset[1][l])) for l in initial_subset[1].columns.tolist()[:top_n.value]]
abs_point_sources = [ColumnDataSource(dict(date=[initial_subset[0][l].idxmax()],
                                           y=[initial_subset[0][l].max()],
                                           text=[str(int(initial_subset[0][l].max()))]
                                           )
                                      )
                                      for l in initial_subset[0].columns.tolist()[:top_n.value]]
rel_point_sources = [ColumnDataSource(dict(date=[initial_subset[1][l].idxmax()],
                                           y=[initial_subset[1][l].max()],
                                           text=[str(int(initial_subset[0][l].max()))]
                                           )
Ejemplo n.º 24
0
                    x_axis_type="datetime",
                    tools=[HoverTool(),
                           ResetTool(),
                           BoxZoomTool()])
line1 = plot_trend.line(x=dates, y=counts, line_width=2)
line1_datasource = line1.data_source
plot_trend.xaxis.axis_label = "Date"
plot_trend.yaxis.axis_label = "Relevant Tweet Count"

# Widgets - Search, button
button_go = Button(label="Search Revelant Tweets", button_type="success")
button_go.on_click(bt_compare_click)

rad_text = PreText(text="Choose Word Embedding :")
radio_group = RadioGroup(labels=["WordNet Synset", "Word2Vec"],
                         inline=True,
                         active=1)
user_text = PreText(text="")

################################

src = ColumnDataSource(data=dict(Lat=[], Long=[], CreatedAt=[], tweet_text=[]))
# separate latitude and longitude points for the borders of the states.
state_xs = [us_states[code]["lons"] for code in us_states]
state_ys = [us_states[code]["lats"] for code in us_states]

hover2 = HoverTool(tooltips=[("Tweet", "@tweet_text")])

# init figure
plot_tweet = figure(
    title="Origin of Tweets",
Ejemplo n.º 25
0
                                view=view1,
                                columns=table_columns,
                                width=500,
                                selectable=True,
                                scroll_to_selection=True,
                                css_classes=['filter_topics_table'])
filter_custom_table_source = ColumnDataSource(data={})
filter_custom_table = DataTable(source=filter_custom_table_source,
                                columns=table_columns,
                                width=500,
                                selectable=True,
                                css_classes=['filter_custom_table'])
radio_group_area = RadioGroup(labels=[
    "All", "Top Topics", "Trends", "Trend Clustering", "Custom Trends",
    "Topic Clustering", "Filter"
],
                              active=0,
                              inline=True,
                              width=400)
n_menu = [("5", "5"), ("10", "10"), ("20", "20"), ("30", "30")]
n_clusters_menu = [("20", "20"), ("50", "50"), ("100", "100"), ("300", "300"),
                   ("500", "500")]
scores = [("0", "0"), ("0.1", "0.1"), ("0.25", "0.25"), ("0.5", "0.5"),
          ("1", "1")]
top_n_dropdown = Dropdown(label="Show Top 10 Phrases",
                          button_type="warning",
                          menu=n_menu,
                          value="10")
top_n_clusters_dropdown = Dropdown(label="Show Top 100 Clusters",
                                   button_type="warning",
                                   menu=n_clusters_menu,
Ejemplo n.º 26
0
toggle = Toggle(label="Toggle button", type="success")
toggle.on_click(toggle_handler)

menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")]
dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu)
dropdown.on_click(dropdown_handler)

menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")]
split = Dropdown(label="Split button", type="danger", menu=menu, default_action="baz")
split.on_click(split_handler)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_group.on_click(checkbox_group_handler)

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(radio_group_handler)

checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(checkbox_button_group_handler)

radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.on_click(radio_button_group_handler)

vbox = VBox(children=[button, toggle, dropdown, split, checkbox_group, radio_group, checkbox_button_group, radio_button_group])

document.add(vbox)
session.store_document(document)

if __name__ == "__main__":
    link = session.object_link(document.context)
Ejemplo n.º 27
0
menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")]
dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu)
dropdown.on_click(dropdown_handler)

menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")]
split = Dropdown(label="Split button",
                 type="danger",
                 menu=menu,
                 default_value="baz")
split.on_click(split_handler)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"],
                               active=[0, 1])
checkbox_group.on_click(checkbox_group_handler)

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(radio_group_handler)

checkbox_button_group = CheckboxButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(checkbox_button_group_handler)

radio_button_group = RadioButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.on_click(radio_button_group_handler)

vbox = VBox(children=[
    button, toggle, dropdown, split, checkbox_group, radio_group,
    checkbox_button_group, radio_button_group
])
Ejemplo n.º 28
0
import pandas as pd
import matplotlib as plt
import numpy as np
from datetime import datetime, timedelta as dt
from pathlib import Path
from bokeh.plotting import figure, output_file, show, curdoc
from bokeh.layouts import row, widgetbox, gridplot
from bokeh.models import HoverTool
from bokeh.models.widgets import Select, RangeSlider, RadioGroup

my_data = pd.DataFrame()  # initialize empty data frame
my_folder = pd.DataFrame()

radio_group = RadioGroup(
    labels=["Demo Sensor 1", "Demo Sensor 2", "Eng Sensor 1", "Eng Sensor 2"],
    active=0)

folder_name = ['Demo1', 'Demo2', 'Eng1', 'Eng2']
for name in folder_name:
    print('Current Folder: ', name)
    my_input = name
    pathlist = Path(my_input).glob('**/*.csv')  # gather all files in folder
    # iterate through the provided folder and load all files to my_data
    for path in pathlist:
        path_in_str = str(path)
        my_file = pd.read_csv(path,
                              parse_dates=[
                                  'Timestamp for sample frequency every 15 min'
                              ])  # read in data from chosen folder
        my_file.set_index(keys='Timestamp for sample frequency every 15 min',
Ejemplo n.º 29
0
 def initialize(self, default_value, label, inline):
     self.radiobutton = RadioGroup(active=default_value,
                                   labels=label,
                                   inline=inline)
     self.widget_lst.append(self.radiobutton)
Ejemplo n.º 30
0
def release_tab(src_csv):

    # Make Dataset for all States per Year
    def make_dataset(state):
        new_src = src_csv.query('STATEID ==' + state + 'and YEAR >= 1983')
        return ColumnDataSource(new_src)

    # draw the plot
    def make_plot(src):
        print('draw plot')
        m = figure(plot_width=800,
                   plot_height=600,
                   title="National Prisoner Release Statistics",
                   x_axis_label='Year',
                   y_axis_label='Number of Prisoners')

        # Male
        # RLUNEXPM: UNCONDITIONAL RELEASE EXPIRATIONS OF SENTENCE, MALE
        rm = m.circle(src.data['YEAR'],
                      src.data['RLUNEXPM'],
                      size=7,
                      color='navy',
                      alpha=0.5,
                      hover_fill_alpha=1.0,
                      hover_fill_color='navy')

        # RLCOSUPM: SUPERVISED MANDATORY RELEASE, MALE
        sm = m.circle(src.data['YEAR'],
                      src.data['RLCOSUPM'],
                      size=7,
                      color='red',
                      alpha=0.5,
                      hover_fill_alpha=1.0,
                      hover_fill_color='red')

        # RLCODPM: DISCRETIONARY PAROLE, MALE
        pm = m.circle(src.data['YEAR'],
                      src.data['RLCODPM'],
                      size=7,
                      color='green',
                      alpha=0.5,
                      hover_fill_alpha=1.0,
                      hover_fill_color='green')

        # Female
        # RLUNEXPM: UNCONDITIONAL RELEASE EXPIRATIONS OF SENTENCE, FEMALE
        rf = m.square(src.data['YEAR'],
                      src.data['RLUNEXPF'],
                      size=7,
                      color='navy',
                      alpha=0.5,
                      hover_fill_alpha=1.0,
                      hover_fill_color='navy')

        # RLCOSUPM: SUPERVISED MANDATORY RELEASE, FEMALE
        sf = m.square(src.data['YEAR'],
                      src.data['RLCOSUPF'],
                      size=7,
                      color='red',
                      alpha=0.5,
                      hover_fill_alpha=1.0,
                      hover_fill_color='red')

        # RLCODPM: DISCRETIONARY PAROLE, FEMALE
        pf = m.square(src.data['YEAR'],
                      src.data['RLCODPF'],
                      size=7,
                      color='green',
                      alpha=0.5,
                      hover_fill_alpha=1.0,
                      hover_fill_color='green')

        # adding tooltips
        h = HoverTool(tooltips=[('Year', '@x'), ('# of Prisoners', '@y')])

        m.add_tools(h)

        # Legend
        legendm = Legend(items=[(
            'Male, Unconditional Release',
            [rm]), ('Male, Supervised Release',
                    [sm]), ('Male, Parole',
                            [pm]), ('Female, Unconditional Release',
                                    [rf]), ('Female, Supervised Release',
                                            [sf]), ('Female, Parole', [pf])])

        m.add_layout(legendm, 'right')
        m.legend.click_policy = 'hide'

        return m

    # update function
    def update(attr, old, new):
        # get list of variables to update
        state = state_select.active
        print(str(state + 1))
        # update the dataset
        new_src = make_dataset(str(state + 1))
        src.data = make_dataset(str(state + 1))

    # Widgets
    state_select = RadioGroup(labels=['Alabama', 'Alaska'], active=0)
    state_select.on_change('active', update)

    src = make_dataset('1')
    p = make_plot(src)

    # add the controls
    controls = WidgetBox(state_select)

    # create a layout
    layout = row(controls, p)

    # add a tab
    tab = Panel(child=layout, title='Prison Releases')
    print('release')
    return tab
Ejemplo n.º 31
0
    def __init__(self, protocol):

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

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

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

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

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

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

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

        self.mrn_input_count = 0
        self.toxicity_grade_input_count = 0

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

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

        self.update_physicians()

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

        self.layout = column(
            self.protocol_select, row(self.display_by, self.physician,
                                      self.roi),
            row(
                self.table, Spacer(width=50),
                column(note, self.update_button,
                       self.clear_source_selection_button,
                       row(self.mrn_input, self.toxicity_grade_input))))
Ejemplo n.º 32
0
def html_postages(coord=None, idx=None, veto=None, info=None, layer_list=None, BoxSize=40):


    plots = {}
    sources = []
    layers = []

    RA, DEC = coord[0], coord[1]
    scale_unit='pixscale'
    scale=0.262
    boxsize = BoxSize #2*m*radius*3600
    radius = BoxSize/(2 * 3600)
    size = int(round(boxsize/scale))
    figsize = int(128)
    #print('BoxSize', boxsize)
    #print('Size', size)

    idx_list = idx #random.sample(list(idx), rows*cols)

    if info is None:
        info = {'RA':RA, 'DEC':DEC}

    if veto is None:
        veto = {'all':np.ones_like(RA, dtype=bool)}

    if layer_list is None:

        layer_list = ['dr9f-south', 'dr9f-south-model', 'dr9f-south-resid', 'dr9g-south', 'dr9g-south-model', 'dr9g-south-resid',
                 'dr9f-north', 'dr9f-north-model', 'dr9f-north-resid', 'dr9g-north', 'dr9g-north-model', 'dr9g-north-resid']


    for idx in idx_list:

        RAidx = RA[idx]
        DECidx = DEC[idx]

        ramin, ramax = RAidx-radius, RAidx+radius
        decmin, decmax = DECidx-radius, DECidx+radius
        dra = (ramax - ramin)/40
        ddec = (decmax - decmin)/40
        mask = (RA > ramin + dra) & (RA < ramax - dra) & (DEC > decmin + ddec) & (DEC < decmax - ddec)

        TOOLTIPS = []

        for key in info.keys():
            TOOLTIPS.append((key, '@'+key))

        p = figure(plot_width=2*figsize, plot_height=2*figsize, tooltips=TOOLTIPS, tools="tap, save, zoom_in, zoom_out, crosshair")
        p.axis.visible = False
        p.toolbar.logo = None
        p.toolbar_location = None
        #p.min_border = 0

        layers2 = []
        for layer in layer_list:

            source='https://www.legacysurvey.org/viewer-dev/jpeg-cutout/?ra=%.12f&dec=%.12f&%s=%g&layer=%s&size=%g' % (RAidx, DECidx, scale_unit, scale, layer, size)
            url='https://www.legacysurvey.org/viewer-dev?ra=%.12f&dec=%.12f&layer=%s&zoom=15' %(RAidx, DECidx, layer)
            imfig_source = ColumnDataSource(data=dict(url=[source], txt=[source]))
            image1 = ImageURL(url="url", x=0, y=1, w=size, h=size, anchor='bottom_left')
            img_source = p.add_glyph(imfig_source, image1)

            layers2.append(img_source)

        taptool = p.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

        colors = ['green', 'red', 'blue', 'cyan', 'yellow']
        circle_i = []
        for color, key, val in zip(colors, veto.keys(), veto.values()):

            ravpix, decvpix = coordtopix(center=[RAidx, DECidx], coord=[RA[(mask) & (val)], DEC[(mask) & (val)]], size=size, scale=scale)

            data = {}
            data['x'] = ravpix
            data['y'] = decvpix
            for info_key, info_val in zip(info.keys(), info.values()):
                if isinstance(info_val[0], (bytes, bytearray)):
                    data[info_key] = np.array(info_val)[(mask) & (val)].astype('U13')
                else:
                    data[info_key] = np.array(info_val)[(mask) & (val)]

            sourceCirc = ColumnDataSource(data=data)

            circle = p.circle('x', 'y', source=sourceCirc, size=15, fill_color=None, line_color=color, line_width=3)
            circle_i.append(circle)

        lineh = Span(location=size/2, dimension='height', line_color='white', line_dash='solid', line_width=1)
        linew = Span(location=size/2, dimension='width', line_color='white', line_dash='solid', line_width=1)

        p.add_layout(lineh)
        p.add_layout(linew)
        p.background_fill_color = "black"
        #p.outline_line_width = 15
        #p.outline_line_alpha = 0.7

        p.xgrid.grid_line_color = None
        p.ygrid.grid_line_color = None

        plots[str(idx)] = p

        sources.append(circle_i)
        layers.append(layers2)


    checkbox = CheckboxGroup(labels=list(veto.keys()), active=list(np.arange(len(veto))))
    iterable = [elem for part in [[('_'.join(['line',str(figid),str(lineid)]),line) for lineid,line in enumerate(elem)] for figid,elem in enumerate(sources)] for elem in part]
    checkbox_code = ''.join([elem[0]+'.visible=checkbox.active.includes('+elem[0].split('_')[-1]+');' for elem in iterable])
    callback = CustomJS(args={key:value for key,value in iterable+[('checkbox',checkbox)]}, code=checkbox_code)

    # print('===== plots ======')
    # print(checkbox_code)
    # print('====')
    # print({key:value for key,value in iterable+[('checkbox',checkbox)]})

    checkbox.js_on_click(callback)

    #script, div = components(plots)
    #print(div)

    radio = RadioGroup(labels=layer_list, active=len(layer_list)-1)
    iterable2 = [elem for part in [[('_'.join(['line',str(figid),str(lineid)]),line) for lineid,line in enumerate(elem)] for figid,elem in enumerate(layers)] for elem in part]
    #
    N = len(layer_list)
    text = []
    for elem in iterable2[::N]:
        for n in range(N):
            text.append('%s%s.visible=false;' %(elem[0][:-1], str(n)))
        for n in range(N):
            if n == 0: text.append('if (cb_obj.active == 0) {%s%s.visible = true;}' %(elem[0][:-1], str(0)))
            if n != 0: text.append('else if (cb_obj.active == %s) {%s%s.visible = true;}' %(str(n), elem[0][:-1], str(n)))

    radiogroup_code = ''.join(text)

    callback2 = CustomJS(args={key:value for key,value in iterable2+[('radio',radio)]}, code=radiogroup_code)
    radio.js_on_change('active', callback2)


    # for key,val in zip(plots.keys(), plots.values()):
    #     print(key, '\t', val)

    #script, div = components(plots)
    #controls = WidgetBox(radio, checkbox)
    #plots['controls'] = components(radio)
    #script_2, div_2 = components(controls)

    #print('===== plots ======')
    plots['checkbox'] = checkbox
    plots['radio'] = radio

    return components(plots)
         source=runs_cds,
         line_width=4,
         line_color="blue")
fig.line(x='Match_ID',
         y='shots',
         source=shots_cds,
         line_width=4,
         line_color="Orange")
fig.xaxis.major_label_orientation = "vertical"

slider = Slider(start=min(bats_man_data.Year_bats),
                end=max(bats_man_data.Year_bats),
                step=1,
                value=min(bats_man_data.Year_bats),
                title='Year of Play')
radiogroup_batsman = RadioGroup(labels=bats_man_name_list, active=0)
run_type = RadioButtonGroup(labels=['Number of 4s', 'Number of 6s'], active=0)
radiogroup_oppo = RadioGroup(labels=opposition_list, active=0)


def update(attr, old, new):
    yr1 = slider.value
    print('Slider Value is : ', yr1)

    selected_batsman = bats_man_name_list[radiogroup_batsman.active]
    print('Selected batsman is : ', selected_batsman)

    selected_oppo = opposition_list[radiogroup_oppo.active]
    print('Selected Opposition Team is : ', selected_oppo)

    button_value = run_type.active
Ejemplo n.º 34
0
class Toxicity:
    def __init__(self, protocol):

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

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

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

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

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

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

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

        self.mrn_input_count = 0
        self.toxicity_grade_input_count = 0

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

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

        self.update_physicians()

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

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

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

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

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

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

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

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

        condition = ' AND '.join(condition)

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

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

        self.clean_toxicity_grades()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.validate_toxicity_grade_input(toxicity_grades)

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

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

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

    def validate_toxicity_grade_input(self, toxicity_grades):

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

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

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

    def clear_source_selection(self):
        self.source.selected.indices = []
Ejemplo n.º 35
0
menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"),
        ("Item 3", "item_3_value")]
dropdown = Dropdown(label="Dropdown button",
                    button_type="warning",
                    menu=menu,
                    default_value="item_1_value")

split_menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None,
              ("Item 3", "item_3_value")]
split = Dropdown(label="Split button", button_type="danger", menu=split_menu)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"],
                               active=[0, 1])

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)

checkbox_button_group = CheckboxButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])

radio_button_group = RadioButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=0)

text_input = TextInput(placeholder="Enter value ...")

autocomplete_input = AutocompleteInput()

select = Select(options=["Option 1", "Option 2", "Option 3"])

multi_select = MultiSelect(options=["Option %d" % (i + 1) for i in range(16)],
                           size=6)
Ejemplo n.º 36
0
dropdown_split.js_on_click(
    CustomJS(code="console.log('dropdown(split): click ' + this.toString())"))
dropdown_split.js_on_event(
    "menu_item_click",
    CustomJS(
        code="console.log('dropdown(split): ' + this.item, this.toString())"))

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"],
                               active=[0, 1])
checkbox_group.js_on_click(
    CustomJS(
        code=
        "console.log('checkbox_group: active=' + this.active, this.toString())"
    ))

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.js_on_click(
    CustomJS(
        code=
        "console.log('radio_group: active=' + this.active, this.toString())"))

checkbox_button_group = CheckboxButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.js_on_click(
    CustomJS(
        code=
        "console.log('checkbox_button_group: active=' + this.active, this.toString())"
    ))

radio_button_group = RadioButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=0)
Ejemplo n.º 37
0
class Interface:
    def __init__(self):

        self.grepolis = Grepolis()

        imgRessource = []
        for v in ["Bois", "Pierre", "Argent"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgRessource.append(Image(d))
        colRess = column(*[img.figure for img in imgRessource])
        self.inputRess = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Bois", "Pierre", "Argent"]
        ]
        colinputRess = column(*self.inputRess)

        imgDieu = []
        for v in ["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDieu.append(Image(d, multiplier=3))
        rowDieu = [HFill(5)]
        for img in imgDieu:
            rowDieu.append(HFill(5))
            rowDieu.append(img.figure)
        rowDieu = row(*rowDieu)

        imgAtt = []
        for v in ["Att_hack", "Att_sharp", "Att_distance"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgAtt.append(Image(d))
        colAtt = column(*[img.figure for img in imgAtt])
        self.inputAtt = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Contondantes", "Blanches", "De Jet"]
        ]
        colinputAtt = column(*self.inputAtt)

        imgDef = []
        for v in ["Def_hack", "Def_sharp", "Def_distance"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDef.append(Image(d))
        colDef = column(*[img.figure for img in imgDef])

        self.inputDef = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Contondantes", "Blanches", "De Jet"]
        ]
        rowinputDef = column(*self.inputDef)

        imgOther = []
        for v in ["Vitesse", "Butin", "Faveur"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgOther.append(Image(d))

        colOther = column(*[img.figure for img in imgOther])

        self.inputFavBut = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Vitesse", "Butin", "Faveur"]
        ]
        self.inputOther = column(*self.inputFavBut)

        self.imgUnit = []
        for v in [
                "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier",
                "Char", "Envoye", "Centaure", "Pegase"
        ]:
            r = "static/" + v + ".jpg"
            d = dict(url=[r])
            self.imgUnit.append(Image(d, multiplier=2))
        rowUnit = row(HFill(10), *[img.figure for img in self.imgUnit])

        imgDefAtt = []
        for v in ["Pop", "Attaque", "Defense"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDefAtt.append(Image(d))

        rowInputUnit = [HFill(10)]
        self.unitInput = [
            TextInput(value="", title=el + " :", width=80) for el in [
                "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier",
                "Char", "Envoye", "Centaure", "Pegase"
            ]
        ]
        for inp in self.unitInput:
            rowInputUnit.append(inp)
            rowInputUnit.append(HFill(30))
        rowInputUnit = row(HFill(10), *rowInputUnit)

        self.selectUnit = CheckboxButtonGroup(labels=[
            "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier", "Char",
            "Envoye", "Centaure", "Pegase"
        ],
                                              active=[i for i in range(9)])
        self.selectUnit.on_change("active", self.updateSelectUnit)
        self.Dieu = RadioButtonGroup(
            labels=["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"],
            active=0,
            width=1110)
        self.Dieu.on_change('active', self.updateUnit)

        self.attdef = RadioButtonGroup(labels=["Attaque", "Defense"],
                                       active=0,
                                       width=200)
        self.attdef.on_change('active', self.switchAttDef)

        self.typeAtt = RadioGroup(
            labels=["Armes Contondantes", "Armes Blanches", "Armes de Jet"],
            active=0,
            width=150)
        self.typeAtt.on_change('active', self.process2)
        self.imgFaveur = Image(dict(url=["static/" + "Faveur" + ".png"]))

        self.launch = Button(label="Lancer")
        self.launch.on_click(self.process)

        self.inputPop = TextInput(value="1500",
                                  title="Population : ",
                                  width=120)
        self.inputPop.on_change("value", self.process2)

        self.inputFav = TextInput(value="1500",
                                  title="Faveur Max : ",
                                  width=120)
        self.inputFav.on_change("value", self.process2)

        rowPop = row(HFill(10), self.typeAtt, imgDefAtt[1].figure, self.attdef,
                     HFill(30), imgDefAtt[2].figure, HFill(50),
                     imgDefAtt[0].figure, self.inputPop, HFill(50),
                     self.imgFaveur.figure, self.inputFav, HFill(50))
        self.doc = column(
            rowDieu, self.Dieu, VFill(20), rowPop, VFill(20), self.selectUnit,
            rowUnit, rowInputUnit, VFill(20),
            row(HFill(50), colRess, colinputRess,
                HFill(40), colAtt, colinputAtt, HFill(40), colDef, rowinputDef,
                HFill(40), colOther, self.inputOther))
        #curdoc().add_root(column(rowDieu,self.Dieu,VFill(20),rowPop,VFill(20),self.selectUnit,rowUnit,rowInputUnit,VFill(20),row(HFill(50),colRess,colinputRess,HFill(40),colAtt,colinputAtt,HFill(40),colDef,rowinputDef,HFill(40),colOther,self.inputOther)))
        self.process(None)
        #curdoc().title = "Grepolis"

    def updateUnit(self, attrname, old, new):
        L = ["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"]
        print(self.selectUnit.active)
        if L[new] == "Poseidon":
            self.imgUnit[-1].figure.visible = False
            self.unitInput[-1].visible = False
            self.selectUnit.active = [1, 2, 3, 4, 5, 6, 7]
        else:
            self.imgUnit[-1].figure.visible = True
            self.unitInput[-1].visible = True
            self.selectUnit.active = [1, 2, 3, 4, 5, 6, 7, 8]
        self.grepolis.setDieu(L[new])
        unit = Add(L[new])
        self.selectUnit.labels = [
            "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier", "Char",
            "Envoye"
        ] + unit
        for i, v in enumerate(unit):
            r = "static/" + v + ".jpg"
            d = dict(url=[r])
            self.imgUnit[-2 + i].update(d)
            self.unitInput[-2 + i].title = v + " : "
        self.process(None)

    def process2(self, attrname, old, new):
        self.process(None)

    def switchAttDef(self, attrname, old, new):
        if self.attdef.active == 0:
            self.typeAtt.disabled = False
        else:
            self.typeAtt.disabled = True
        self.process(None)

    def updateSelectUnit(self, attrname, old, new):
        N = len(self.selectUnit.labels)
        active = self.selectUnit.active
        zeros = [i for i in range(N) if i not in active]
        for inp in [self.unitInput[i] for i in zeros]:
            inp.value = str(0)
        self.process(None)

    def process(self, attrname):
        try:
            pop = int(self.inputPop.value)
            favmax = int(self.inputFav.value)
            active = self.selectUnit.active
            type = self.typeAtt.active
            if self.attdef.active == 0:
                X, Att, Def, Prix, Speed, Pops, butin = self.grepolis.optimAttaque(
                    pop=pop, favmax=favmax, active=active, type=type)

            else:
                X, Att, Def, Prix, Speed, Pops, butin = self.grepolis.optimDefense(
                    pop=pop, favmax=favmax, active=active)
            for v, inp in zip(X, [self.unitInput[i] for i in active]):
                inp.value = str(v)
            for v, inp in zip(Att, self.inputAtt):
                inp.value = str(v) + " /u - " + str(int(v * pop))
            for v, inp in zip(Def, self.inputDef):
                inp.value = str(v) + " /u - " + str(int(v * pop))
            for v, inp in zip(Prix, self.inputRess):
                inp.value = str(v) + " /u - " + str(int(v * pop))
            for i, (v, inp) in enumerate(
                    zip([Speed, butin, Prix[3]], self.inputFavBut)):
                #add = ""
                #if i > 0:
                #    add = + " /u - " +str(int(v*pop))
                #print(v,add)
                inp.value = str(v) + " /u - " + str(int(
                    v * pop)) if i != 0 else str(v)
        except:
            pass
Ejemplo n.º 38
0
                             button_type="success",
                             width=300)
solve_system_button.on_click(solve_system)

##################################### (2) #####################################
mass_input = TextInput(value="10000", title="Mass [kg]", width=300)

##################################### (3) #####################################
stiffness_input = TextInput(value="10000000",
                            title="Stiffness [N*m"
                            u"\u00B2]",
                            width=300)

##################################### (4) #####################################
Erdbebenzonen_text = Div(text="""<b>Earthquake Zones</b>""")
Erdbebenzonen_choices = RadioGroup(labels=["Zone 1", "Zone 2", "Zone 3"],
                                   active=0)
Bedeutungsbeiwert_text = Div(text="""<b>Importance Coefficient</b>""")
Bedeutungsbeiwert_choices = RadioGroup(labels=[
    "Residential Building", "School or Residential Complexes", "Hospital"
],
                                       active=0)
untergrundParamter_text = Div(text="""<b>Underground Parameter</b>""")
untergrundParamter_choices = RadioGroup(
    labels=["A-R", "B-R", "C-R", "B-T", "C-T", "C-S"], active=0)


def calculate_ERS():
    # re-assign "Erdbebenzonen" value
    a = 0
    value1 = Erdbebenzonen_choices.active
    if value1 == 0:
Ejemplo n.º 39
0
fig.xaxis.axis_label = 'Year'

fig.rect(x='year',
         y='reform',
         source=sources['static'],
         angle=pi/2,
         width=5,
         height=1,
         color=DARK_GRAY)


# create components --------------
title_div = Div(text='Revenue Impact of a 4% Surtax on Taxpayers with Adjusted Gross Income over $5 Million', height=30)

radio_group_text = Div(text="Include Additional Capital Gains Behavior.")
radio_group = RadioGroup(labels=["Without", "With"], active=0)
sources['radio_group'] = radio_group

elasticity_text = Div(text="Elasticity of Taxable Income")
elasticity_option = RadioButtonGroup(labels=sources['capital_gains_no'].data['labels'], active=0)
sources['elasticity_option'] = elasticity_option


# create callbacks ---------------
radio_group.callback = CustomJS(args=sources, code="""
  var capitalGainsType = radio_group.active === 0 ? capital_gains_no : capital_gains_yes;
  elasticity_option.set('labels', capitalGainsType.data.labels);

  while (elasticity_option.active > capitalGainsType.data.source_ids.length - 1) {
    elasticity_option.active = elasticity_option.active - 1;
  }