value=0.0, description=r'$k_z$', continuous_update=False) Nk_path_slider = widgets.IntSlider(min=5, max=50, step=5, value=10, description=r'$N_k$', continuous_update=False) Nk_FS_slider = widgets.IntSlider(min=5, max=50, step=5, value=10, description=r'$N_{FS}$', continuous_update=False) reset_button = widgets.Button(description="Reset") def reset_values(b): ui.children[1].children[2].value = 10 ui.children[1].children[1].value = 10 ui.children[0].children[0].value = 0.0 ui.children[0].children[1].value = 0.0 ui.children[0].children[2].value = 1.0 ui.children[0].children[3].value = 1.0 ui.children[1].children[0].value = 0.0 reset_button.on_click(reset_values) out = widgets.interactive_output(
def true_false(option_1, bool_1, option_2, bool_2, option_3, bool_3, option_4, bool_4, button_text_1, button_text_2): #Convert string to HTMLMath so equations can be displayed TF_question_1 = widgets.HTMLMath(value=option_1) TF_question_2 = widgets.HTMLMath(value=option_2) TF_question_3 = widgets.HTMLMath(value=option_3) TF_question_4 = widgets.HTMLMath(value=option_4) #Create true and false bottons button1_1 = widgets.Button(description=button_text_1) button1_2 = widgets.Button(description=button_text_2) button2_1 = widgets.Button(description=button_text_1) button2_2 = widgets.Button(description=button_text_2) button3_1 = widgets.Button(description=button_text_1) button3_2 = widgets.Button(description=button_text_2) button4_1 = widgets.Button(description=button_text_1) button4_2 = widgets.Button(description=button_text_2) button1_1.style.button_color = 'Whitesmoke' button1_2.style.button_color = 'Whitesmoke' button2_1.style.button_color = 'Whitesmoke' button2_2.style.button_color = 'Whitesmoke' button3_1.style.button_color = 'Whitesmoke' button3_2.style.button_color = 'Whitesmoke' button4_1.style.button_color = 'Whitesmoke' button4_2.style.button_color = 'Whitesmoke' #Display buttons in front of each question container1 = widgets.HBox(children=[button1_1, button1_2, TF_question_1]) container2 = widgets.HBox(children=[button2_1, button2_2, TF_question_2]) container3 = widgets.HBox(children=[button3_1, button3_2, TF_question_3]) container4 = widgets.HBox(children=[button4_1, button4_2, TF_question_4]) #Place true or false questions in an array so they can be shuffled containers = [container1, container2, container3, container4] random.shuffle(containers) #Reassign containers and display container1 = containers[0] container2 = containers[1] container3 = containers[2] container4 = containers[3] display(container1, container2, container3, container4) print(" ", end='\r') def on_button1_1_clicked(b): if bool_1 == True: print("Correct! ", end='\r') button1_1.style.button_color = 'Moccasin' button1_2.style.button_color = 'Whitesmoke' else: print("Try again.", end='\r') button1_1.style.button_color = 'Lightgray' button1_2.style.button_color = 'Whitesmoke' def on_button1_2_clicked(b): if bool_1 == False: print("Correct! ", end='\r') button1_1.style.button_color = 'Whitesmoke' button1_2.style.button_color = 'Moccasin' else: print("Try again.", end='\r') button1_1.style.button_color = 'Whitesmoke' button1_2.style.button_color = 'Lightgray' def on_button2_1_clicked(b): if bool_2 == True: print("Correct! ", end='\r') button2_1.style.button_color = 'Moccasin' button2_2.style.button_color = 'Whitesmoke' else: print("Try again.", end='\r') button2_1.style.button_color = 'Lightgray' button2_2.style.button_color = 'Whitesmoke' def on_button2_2_clicked(b): if bool_2 == False: print("Correct! ", end='\r') button2_1.style.button_color = 'Whitesmoke' button2_2.style.button_color = 'Moccasin' else: print("Try again.", end='\r') button2_1.style.button_color = 'Whitesmoke' button2_2.style.button_color = 'Lightgray' def on_button3_1_clicked(b): if bool_3 == True: print("Correct! ", end='\r') button3_1.style.button_color = 'Moccasin' button3_2.style.button_color = 'Whitesmoke' else: print("Try again.", end='\r') button3_1.style.button_color = 'Lightgray' button3_2.style.button_color = 'Whitesmoke' def on_button3_2_clicked(b): if bool_3 == False: print("Correct! ", end='\r') button3_1.style.button_color = 'Whitesmoke' button3_2.style.button_color = 'Moccasin' else: print("Try again.", end='\r') button3_1.style.button_color = 'Whitesmoke' button3_2.style.button_color = 'Lightgray' def on_button4_1_clicked(b): if bool_4 == True: print("Correct! ", end='\r') button4_1.style.button_color = 'Moccasin' button4_2.style.button_color = 'Whitesmoke' else: print("Try again.", end='\r') button4_1.style.button_color = 'Lightgray' button4_2.style.button_color = 'Whitesmoke' def on_button4_2_clicked(b): if bool_4 == False: print("Correct! ", end='\r') button4_1.style.button_color = 'Whitesmoke' button4_2.style.button_color = 'Moccasin' else: print("Try again.", end='\r') button4_1.style.button_color = 'Whitesmoke' button4_2.style.button_color = 'Lightgray' button1_1.on_click(on_button1_1_clicked) button1_2.on_click(on_button1_2_clicked) button2_1.on_click(on_button2_1_clicked) button2_2.on_click(on_button2_2_clicked) button3_1.on_click(on_button3_1_clicked) button3_2.on_click(on_button3_2_clicked) button4_1.on_click(on_button4_1_clicked) button4_2.on_click(on_button4_2_clicked)
if choice == 0: edge_list = self.tests.free_edges elif choice == 1: edge_list = self._class_positive_set( random.choice(list(self.extractor.classes))) edge = random.choice(edge_list) self.current_case = edge classes = self.extractor.extract(edge) for cla in self.extractor.classes: self.class_to_check[cla].value = cla in classes with self.output: self.output.clear_output() print(self.tests.edge_to_text[edge]) print() print(str(edge)) def run(self, case=None, keywords=None): self.propose_case(case=case, keywords=keywords) checks_box = widgets.HBox(self.checkboxes) button = widgets.Button(description='Add Case') buttons_box = widgets.HBox([button]) def button_callback(b): classes = set(cla for cla in self.extractor.classes if self.class_to_check[cla].value) self.tests.add_case(self.current_case, classes) self.propose_case(keywords=keywords) button.on_click(button_callback) return widgets.VBox([self.output, checks_box, buttons_box])
def status(self, ohlcvs): """Strategy list widgets. Choose which strategy to implement on widgets GUI. Args: ohlcvs: A dataframe of symbol. Returns: widget GUI """ import ipywidgets as widgets ret = pd.DataFrame() full_results = [] for method in self._trading_methods: for symbol in method.symbols: ohlcv = ohlcvs[(symbol, method.freq)] result = method.strategy.backtest(ohlcv, method.variables, filters=method.filters, freq=method.freq) ret[method.name + '-' + symbol + '-' + method.freq] = result.cumulative_returns weight_btc = method.weight_btc if isinstance(weight_btc, dict): weight_btc = (weight_btc[symbol] if symbol in weight_btc else weight_btc['default']) full_results.append({ 'name': method.name, 'symbol': symbol, 'freq': method.freq, 'weight': weight_btc, 'portfolio': result, 'trading_method': method, 'signal': result.cash().iloc[-1] == 0, }) method_dropdown = widgets.Dropdown(options=[m.name + '-' + str(i) for i, m in enumerate(self._trading_methods)]) symbol_dropdown = widgets.Dropdown(options=[symbol + '-' + freq for symbol, freq in ohlcvs.keys()]) backtest_btn = widgets.Button(description='status') backtest_panel = widgets.Output() option_panel = widgets.Output() def plotly_df(df): """Display plot. """ # Plot fig = px.line() for sname, s in df.items(): fig.add_scatter(x=s.index, y=s.values, name=sname) # Not what is desired - need a line # fig.show() @backtest_panel.capture(clear_output=True) def backtest(_): """Display single strategy backtest result. """ method_id = int(method_dropdown.value.split('-')[-1]) history_id = tuple(symbol_dropdown.value.split('-')) ohlcv = ohlcvs[history_id] strategy = self._trading_methods[method_id].strategy svars = self._trading_methods[method_id].variables filters = self._trading_methods[method_id].filters strategy.backtest(ohlcv, variables=svars, filters=filters, freq=history_id[-1], plot=True) backtest_btn.on_click(backtest) dropdowns = widgets.HBox([method_dropdown, symbol_dropdown, backtest_btn]) with option_panel: plotly_df(ret) display(pd.DataFrame(full_results)) return widgets.VBox([option_panel, dropdowns, backtest_panel])
global nonosol, n, nonostate, sol_n nonostate = get_nono(change["new"]) n = Nonogram(nonostate) nonosol = a_star_search(n) #print(nonosol) def rhchange(change): global rhsol, b, rhstate, sol_b rhstate = get_rh(change["new"]) b = RushHour(rhstate) rhsol = a_star_search(b, gac=False) #print(rhsol) dropnono.observe(nonochange, names="value") droprh.observe(rhchange, names="value") button = widgets.Button(description="Replay Rush Hour-solution") nonobutton = widgets.Button(description="Replay Nonogram-solution") def on_button_clicked(button): sol_b = RushHour(rhstate) for s in rhsol: sol_b.set_state(s) time.sleep(0.1) #print(rhsol) def on_nonobutton_clicked(button): sol_n = Nonogram(nonostate) for s in nonosol: sol_n.set_state(s) sol_n.display_state() time.sleep(0.1)
def rotation_example(): #from plotly.offline import init_notebook_mode, iplot, plot #from ipywidgets import HBox import plotly.graph_objs as go #import numpy as np #import random from math import radians, cos, sin, sqrt, tan, atan import ipywidgets as widgets from IPython.display import Markdown, display, clear_output, HTML #init_notebook_mode(connected=True) square_clicked4 = True triangle_clicked4 = False clockwise_rotation = True counterclockwise_rotation = False current_point = 0 square_button4 = widgets.Button( description='Square', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', ) triangle_button4 = widgets.Button( description='Triangle', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', ) rotation_choice = widgets.Dropdown( options=[('', 0), ('Point A', 1), ('Point B', 2), ('Point C', 3), ('Point D', 4), ('Point E', 5), ('Origin', 6)], value=0, description='', ) clockwise_button = widgets.Button( description='Clockwise', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', ) counterclockwise_button = widgets.Button( description='Counter-Clockwise', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', ) text_widget4 = widgets.HTML("<strong>Object: </strong>") text2_widget4 = widgets.HTML("<strong>Rotation Direction: </strong>") text3_widget4 = widgets.HTML("<strong>Rotation Point: </strong>") choice_widget4 = widgets.HBox( children=[text_widget4, square_button4, triangle_button4]) rotation_widget4 = widgets.HBox( children=[text2_widget4, clockwise_button, counterclockwise_button]) point_widget4 = widgets.HBox(children=[text3_widget4, rotation_choice]) input_widget4 = widgets.VBox( children=[choice_widget4, rotation_widget4, point_widget4]) rotation_choice.layout.width = '150px' def rotation(p): point = p data4 = [] data4.append( dict(visible=True, line=dict(color='#00FF00', width=3), mode='lines+markers+text', name='Original', hoverinfo='x+y', text=['A', 'B', 'C', 'D', ''], textposition='top left', textfont=dict(color='#ff0000'), x=[1, 1, 4, 4, 1], y=[1, 4, 4, 1, 1])) data4.append( dict(visible=True, line=dict(color='#00CED1', width=3), mode='lines+markers+text', name='Translation', hoverinfo='x+y', text=['A', 'B', 'C', 'D', ''], textposition='top left', textfont=dict(color='#ff0000'), x=[1, 1, 4, 4, 1], y=[1, 4, 4, 1, 1])) temp_degrees = 0 rotationX = 0 rotationY = 0 x0 = 0 x1 = 0 x2 = 0 x3 = 0 y0 = 0 y1 = 0 y2 = 0 y3 = 0 steps4 = [] steps5 = [] for i in range(37): temp_degrees = radians((36 - i) * 10) if (point == 1): rotationX = 1 rotationY = 1 x0 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (1 - rotationX)**2 + (1 - rotationY)**2)) y0 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (1 - rotationX)**2 + (1 - rotationY)**2)) x1 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (1 - rotationX)**2 + (4 - rotationY)**2)) y1 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (1 - rotationX)**2 + (4 - rotationY)**2)) x2 = rotationX + cos(temp_degrees + atan( (4 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (4 - rotationY)**2)) y2 = rotationY + sin(temp_degrees + atan( (4 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (4 - rotationY)**2)) x3 = rotationX + cos(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) y3 = rotationY + sin(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) elif (point == 2): rotationX = 1 rotationY = 4 x0 = rotationX + cos(temp_degrees - 1.5707963268) * (sqrt( (1 - rotationX)**2 + (1 - rotationY)**2)) y0 = rotationY + sin(temp_degrees - 1.5707963268) * (sqrt( (1 - rotationX)**2 + (1 - rotationY)**2)) x1 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (1 - rotationX)**2 + (4 - rotationY)**2)) y1 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (1 - rotationX)**2 + (4 - rotationY)**2)) x2 = rotationX + cos(temp_degrees + atan( (4 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (4 - rotationY)**2)) y2 = rotationY + sin(temp_degrees + atan( (4 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (4 - rotationY)**2)) x3 = rotationX + cos(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) y3 = rotationY + sin(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) elif (point == 3): rotationX = 4 rotationY = 4 x0 = rotationX - cos(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) y0 = rotationY - sin(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) x1 = rotationX - cos(temp_degrees + atan( (4 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (4 - rotationY)**2)) y1 = rotationY - sin(temp_degrees + atan( (4 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (4 - rotationY)**2)) x2 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (4 - rotationX)**2 + (4 - rotationY)**2)) y2 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (4 - rotationX)**2 + (4 - rotationY)**2)) x3 = rotationX + cos(temp_degrees - 1.5707963268) * (sqrt( (4 - rotationX)**2 + (1 - rotationY)**2)) y3 = rotationY + sin(temp_degrees - 1.5707963268) * (sqrt( (4 - rotationX)**2 + (1 - rotationY)**2)) elif (point == 4): rotationX = 4 rotationY = 1 x0 = rotationX - cos(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) y0 = rotationY - sin(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) x1 = rotationX - cos(temp_degrees + atan( (4 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (4 - rotationY)**2)) y1 = rotationY - sin(temp_degrees + atan( (4 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (4 - rotationY)**2)) x2 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (4 - rotationX)**2 + (4 - rotationY)**2)) y2 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (4 - rotationX)**2 + (4 - rotationY)**2)) x3 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (4 - rotationX)**2 + (1 - rotationY)**2)) y3 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (4 - rotationX)**2 + (1 - rotationY)**2)) elif (point == 5): rotationX = (4 - 1) / 2 + 1 rotationY = (4 - 1) / 2 + 1 x0 = rotationX - cos(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) y0 = rotationY - sin(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) x1 = rotationX - cos(temp_degrees + atan( (4 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (4 - rotationY)**2)) y1 = rotationY - sin(temp_degrees + atan( (4 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (4 - rotationY)**2)) x2 = rotationX + cos(temp_degrees + atan( (4 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (4 - rotationY)**2)) y2 = rotationY + sin(temp_degrees + atan( (4 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (4 - rotationY)**2)) x3 = rotationX + cos(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) y3 = rotationY + sin(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) elif (point == 6): rotationX = 0 rotationY = 0 tempX = rotationX + cos(temp_degrees + atan( (2.5 - rotationY) / (2.5 - rotationX))) * (sqrt((2.5 - rotationX)**2 + (2.5 - rotationY)**2)) tempY = rotationY + sin(temp_degrees + atan( (2.5 - rotationY) / (2.5 - rotationX))) * (sqrt((2.5 - rotationX)**2 + (2.5 - rotationY)**2)) x0T = tempX - 1.5 y0T = tempY - 1.5 x1T = tempX - 1.5 y1T = tempY + 1.5 x2T = tempX + 1.5 y2T = tempY + 1.5 x3T = tempX + 1.5 y3T = tempY - 1.5 rotationX = tempX rotationY = tempY x0 = rotationX - cos(temp_degrees + atan( (y0T - rotationY) / (x0T - rotationX))) * (sqrt((x0T - rotationX)**2 + (y0T - rotationY)**2)) y0 = rotationY - sin(temp_degrees + atan( (y0T - rotationY) / (x0T - rotationX))) * (sqrt((x0T - rotationX)**2 + (y0T - rotationY)**2)) x1 = rotationX - cos(temp_degrees + atan( (y1T - rotationY) / (x1T - rotationX))) * (sqrt((x1T - rotationX)**2 + (y1T - rotationY)**2)) y1 = rotationY - sin(temp_degrees + atan( (y1T - rotationY) / (x1T - rotationX))) * (sqrt((x1T - rotationX)**2 + (y1T - rotationY)**2)) x2 = rotationX + cos(temp_degrees + atan( (y2T - rotationY) / (x2T - rotationX))) * (sqrt((x2T - rotationX)**2 + (y2T - rotationY)**2)) y2 = rotationY + sin(temp_degrees + atan( (y2T - rotationY) / (x2T - rotationX))) * (sqrt((x2T - rotationX)**2 + (y2T - rotationY)**2)) x3 = rotationX + cos(temp_degrees + atan( (y3T - rotationY) / (x3T - rotationX))) * (sqrt((x3T - rotationX)**2 + (y3T - rotationY)**2)) y3 = rotationY + sin(temp_degrees + atan( (y3T - rotationY) / (x3T - rotationX))) * (sqrt((x3T - rotationX)**2 + (y3T - rotationY)**2)) step = dict(method='update', args=[{ 'x[0]': [1, x0], 'x[1]': [1, x1], 'x[2]': [4, x2], 'x[3]': [4, x3], 'x[4]': [1, x0], 'y[0]': [1, y0], 'y[1]': [4, y1], 'y[2]': [4, y2], 'y[3]': [1, y3], 'y[4]': [1, y0] }], label=str(i * 10) + "°") steps4.append(step) step2 = dict(method='update', args=[{ 'x[0]': [1, x0], 'x[1]': [1, x1], 'x[2]': [4, x2], 'x[3]': [4, x3], 'x[4]': [1, x0], 'y[0]': [1, y0], 'y[1]': [4, y1], 'y[2]': [4, y2], 'y[3]': [1, y3], 'y[4]': [1, y0] }], label=str((36 - i) * 10) + "°") steps5.insert(0, step2) if (clockwise_rotation): sliders4 = [ dict(active=0, currentvalue={ "prefix": "Clockwise Rotation: ", }, pad={"t": 35}, steps=steps4) ] else: sliders4 = [ dict(active=0, currentvalue={ "prefix": "Counter-Clockwise Rotation: ", }, pad={"t": 35}, steps=steps5) ] title = '' if (point == 1): title = 'Rotation about Point A' elif (point == 2): title = 'Rotation about Point B' elif (point == 3): title = 'Rotation about Point C' elif (point == 4): title = 'Rotation about Point D' elif (point == 5): title = 'Rotation about Point E' elif (point == 6): title = 'Rotation about the Origin' layout4 = go.Layout( title=title, sliders=sliders4, showlegend=False, hovermode='closest', yaxis=dict( title='', ticklen=5, dtick=1, gridwidth=2, range=[-10, 10], showgrid=True, ), xaxis=dict( title='', ticklen=5, dtick=1, gridwidth=2, range=[-10, 10], showgrid=True, ), autosize=True, #width=750, height=725, annotations=[ dict( x=1.0, y=-0.10, showarrow=False, text='X Axis', xref='paper', yref='paper', font=dict(size=14, ), ), dict( x=-0.06, y=1.0, showarrow=False, text='Y Axis', textangle=-90, xref='paper', yref='paper', font=dict(size=14, ), ), ], ) fig4 = dict(data=data4, layout=layout4) if (not (point == 0)): clear_output() display(Markdown("<img src='images/pointplot2.png' align='left'>")) display(input_widget4) iplot(fig4, filename='filename') def rotationT(p): pointT = p dataT4 = [] dataT4.append( dict(visible=True, line=dict(color='#00FF00', width=3), mode='lines+markers+text', name='Original', hoverinfo='x+y', text=['A', 'B', 'C', ''], textposition='top left', textfont=dict(color='#ff0000'), x=[1, 2.5, 4, 1], y=[1, 4, 1, 1])) dataT4.append( dict(visible=True, line=dict(color='#00CED1', width=3), mode='lines+markers+text', name='Rotation', hoverinfo='x+y', text=['A', 'B', 'C', ''], textposition='top left', textfont=dict(color='#ff0000'), x=[1, 2.5, 4, 1], y=[1, 4, 1, 1])) temp_degrees = 0 rotationX = 0 rotationY = 0 xT0 = 0 xT1 = 0 xT2 = 0 yT0 = 0 yT1 = 0 yT2 = 0 stepsT4 = [] stepsT5 = [] for i in range(37): temp_degrees = radians((36 - i) * 10) if (pointT == 1): rotationX = 1 rotationY = 1 xT0 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (1 - rotationX)**2 + (1 - rotationY)**2)) yT0 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (1 - rotationX)**2 + (1 - rotationY)**2)) xT1 = rotationX + cos(temp_degrees + atan( (4 - rotationY) / (2.5 - rotationX))) * (sqrt((2.5 - rotationX)**2 + (4 - rotationY)**2)) yT1 = rotationY + sin(temp_degrees + atan( (4 - rotationY) / (2.5 - rotationX))) * (sqrt((2.5 - rotationX)**2 + (4 - rotationY)**2)) xT2 = rotationX + cos(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) yT2 = rotationY + sin(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) elif (pointT == 2): rotationX = 2.5 rotationY = 4 xT0 = rotationX - cos(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) yT0 = rotationY - sin(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) xT1 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (2.5 - rotationX)**2 + (4 - rotationY)**2)) yT1 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (2.5 - rotationX)**2 + (4 - rotationY)**2)) xT2 = rotationX + cos(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) yT2 = rotationY + sin(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) elif (pointT == 3): rotationX = 4 rotationY = 1 xT0 = rotationX - cos(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) yT0 = rotationY - sin(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) xT1 = rotationX - cos(temp_degrees + atan( (4 - rotationY) / (2.5 - rotationX))) * (sqrt((2.5 - rotationX)**2 + (4 - rotationY)**2)) yT1 = rotationY - sin(temp_degrees + atan( (4 - rotationY) / (2.5 - rotationX))) * (sqrt((2.5 - rotationX)**2 + (4 - rotationY)**2)) xT2 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (4 - rotationX)**2 + (1 - rotationY)**2)) yT2 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (4 - rotationX)**2 + (1 - rotationY)**2)) elif (pointT == 4): rotationX = (4 - 1) / 2 + 1 rotationY = (4 - 1) / 2 + 1 xT0 = rotationX - cos(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) yT0 = rotationY - sin(temp_degrees + atan( (1 - rotationY) / (1 - rotationX))) * (sqrt((1 - rotationX)**2 + (1 - rotationY)**2)) xT1 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (2.5 - rotationX)**2 + (4 - rotationY)**2)) yT1 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (2.5 - rotationX)**2 + (4 - rotationY)**2)) xT2 = rotationX + cos(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) yT2 = rotationY + sin(temp_degrees + atan( (1 - rotationY) / (4 - rotationX))) * (sqrt((4 - rotationX)**2 + (1 - rotationY)**2)) elif (pointT == 5): rotationX = 0 rotationY = 0 tempTX = rotationX + cos(temp_degrees + atan( (2.5 - rotationY) / (2.5 - rotationX))) * (sqrt((2.5 - rotationX)**2 + (2.5 - rotationY)**2)) tempTY = rotationY + sin(temp_degrees + atan( (2.5 - rotationY) / (2.5 - rotationX))) * (sqrt((2.5 - rotationX)**2 + (2.5 - rotationY)**2)) xT0T = tempTX - 1.5 yT0T = tempTY - 1.5 xT1T = tempTX yT1T = tempTY + 1.5 xT2T = tempTX + 1.5 yT2T = tempTY - 1.5 rotationX = tempTX rotationY = tempTY xT0 = rotationX - cos(temp_degrees + atan( (yT0T - rotationY) / (xT0T - rotationX))) * (sqrt((xT0T - rotationX)**2 + (yT0T - rotationY)**2)) yT0 = rotationY - sin(temp_degrees + atan( (yT0T - rotationY) / (xT0T - rotationX))) * (sqrt((xT0T - rotationX)**2 + (yT0T - rotationY)**2)) xT1 = rotationX + cos(temp_degrees + 1.5707963268) * (sqrt( (xT1T - rotationX)**2 + (yT1T - rotationY)**2)) yT1 = rotationY + sin(temp_degrees + 1.5707963268) * (sqrt( (xT1T - rotationX)**2 + (yT1T - rotationY)**2)) xT2 = rotationX + cos(temp_degrees + atan( (yT2T - rotationY) / (xT2T - rotationX))) * (sqrt((xT2T - rotationX)**2 + (yT2T - rotationY)**2)) yT2 = rotationY + sin(temp_degrees + atan( (yT2T - rotationY) / (xT2T - rotationX))) * (sqrt((xT2T - rotationX)**2 + (yT2T - rotationY)**2)) step = dict(method='update', args=[{ 'x[0]': [1, xT0], 'x[1]': [2.5, xT1], 'x[2]': [4, xT2], 'x[3]': [1, xT0], 'y[0]': [1, yT0], 'y[1]': [4, yT1], 'y[2]': [1, yT2], 'y[3]': [1, yT0] }], label=str(i * 10) + "°") stepsT4.append(step) step2 = dict(method='update', args=[{ 'x[0]': [1, xT0], 'x[1]': [2.5, xT1], 'x[2]': [4, xT2], 'x[3]': [1, xT0], 'y[0]': [1, yT0], 'y[1]': [4, yT1], 'y[2]': [1, yT2], 'y[3]': [1, yT0] }], label=str((36 - i) * 10) + "°") stepsT5.insert(0, step2) if (clockwise_rotation): slidersT4 = [ dict(active=0, currentvalue={ "prefix": "Clockwise Rotation: ", }, pad={"t": 35}, steps=stepsT4) ] else: slidersT4 = [ dict(active=0, currentvalue={ "prefix": "Counter-Clockwise Rotation: ", }, pad={"t": 35}, steps=stepsT5) ] title = '' if (pointT == 1): title = 'Rotation about Point A' elif (pointT == 2): title = 'Rotation about Point B' elif (pointT == 3): title = 'Rotation about Point C' elif (pointT == 4): title = 'Rotation about Point D' elif (pointT == 5): title = 'Rotation about the Origin' layoutT4 = go.Layout( title=title, sliders=slidersT4, showlegend=False, hovermode='closest', yaxis=dict( title='', ticklen=5, dtick=1, gridwidth=2, range=[-10, 10], showgrid=True, ), xaxis=dict( title='', ticklen=5, dtick=1, gridwidth=2, range=[-10, 10], showgrid=True, ), autosize=True, #width=750, height=725, annotations=[ dict( x=1.0, y=-0.10, showarrow=False, text='X Axis', xref='paper', yref='paper', font=dict(size=14, ), ), dict( x=-0.06, y=1.0, showarrow=False, text='Y Axis', textangle=-90, xref='paper', yref='paper', font=dict(size=14, ), ), ], ) figT4 = dict(data=dataT4, layout=layoutT4) if (not (pointT == 0)): clear_output() display(Markdown("<img src='images/pointplot4.png' align='left'>")) display(input_widget4) iplot(figT4, filename='filename') def graph_rotation(change): global current_point current_point = change.new if (square_clicked4): rotation(change.new) elif (triangle_clicked4): rotationT(change.new) def square_update4(change): global square_clicked4 global triangle_clicked4 if (not (square_clicked4)): square_clicked4 = True triangle_clicked4 = False square_button4.button_style = 'success' triangle_button4.button_style = '' rotation_choice.options = [('', 0), ('Point A', 1), ('Point B', 2), ('Point C', 3), ('Point D', 4), ('Point E', 5), ('Origin', 6)] rotation_choice.value = 0 clear_output() display(Markdown("<img src='images/pointplot2.png' align='left'>")) display(input_widget4) def triangle_update4(change): global square_clicked4 global triangle_clicked4 if (not (triangle_clicked4)): triangle_clicked4 = True square_clicked4 = False square_button4.button_style = '' triangle_button4.button_style = 'success' rotation_choice.options = options = [('', 0), ('Point A', 1), ('Point B', 2), ('Point C', 3), ('Point D', 4), ('Origin', 5)] rotation_choice.value = 0 clear_output() display(Markdown("<img src='images/pointplot4.png' align='left'>")) display(input_widget4) def clockwise_update(change): global clockwise_rotation global counterclockwise_rotation global current_point if (not (clockwise_rotation)): clockwise_rotation = True counterclockwise_rotation = False clockwise_button.button_style = "success" counterclockwise_button.button_style = "" clear_output() if (square_clicked4): display( Markdown("<img src='images/pointplot2.png' align='left'>")) if (current_point == 0): display(input_widget4) rotation(current_point) else: display( Markdown("<img src='images/pointplot4.png' align='left'>")) if (current_point == 0): display(input_widget4) rotationT(current_point) def counterclockwise_update(change): global clockwise_rotation global counterclockwise_rotation global current_point if (not (counterclockwise_rotation)): clockwise_rotation = False counterclockwise_rotation = True clockwise_button.button_style = "" counterclockwise_button.button_style = "success" clear_output() if (square_clicked4): display( Markdown("<img src='images/pointplot2.png' align='left'>")) if (current_point == 0): display(input_widget4) rotation(current_point) else: display( Markdown("<img src='images/pointplot4.png' align='left'>")) if (current_point == 0): display(input_widget4) rotationT(current_point) square_button4.on_click(square_update4) triangle_button4.on_click(triangle_update4) clockwise_button.on_click(clockwise_update) counterclockwise_button.on_click(counterclockwise_update) rotation_choice.observe(graph_rotation, names='value') display(Markdown("<img src='images/pointplot2.png' align='left'>")) display(input_widget4) rotation(0)
def __init__(self, file): self.filename = file self.noMaterials = 0 self.noObjects = 0 self.matAll = [] self.objAll = [] self.widgetList = [] self.objectList = [] self.wfList = [] self.wfAll = [] self.srcAll = [] self.rcAll = [] self.goList = [] self.goAll = [] self.rem = [] self.accNames = [ 'Space', 'Materials', 'Objects', 'Source/Receiver', 'Geometry Output' ] self.add_mat = wd.Button(value=False, description='Add material', disabled=False) self.widgetList = [ self.add_mat, wd.Label('free_space : Built-in identifier for air', layout=wd.Layout(width='30%', margin='-35px 0px 0px 200px')), wd.Label( 'pec : Built-in identifier for a perfect electric conductor', layout=wd.Layout(width='50%', margin='-10px 0px 10px 200px')) ] self.add_obj = wd.Button(value=False, description='Add object', disabled=False) self.rem_obj = wd.Button(value=False, description='Remove last object', disabled=False) self.objectList = [ wd.HBox([self.add_obj, self.rem_obj], layout=wd.Layout(margin='10px 0px 20px 0px')) ] self.wrFile = wd.Button(value=False, description='Write input file', disabled=False, layout=wd.Layout(height='30px', width='40%', margin='10px 0px 20px 20px')) self.dd = [ wd.Dropdown(options=[ ' ', 'Edge', 'Plate', 'Triangle', 'Box', 'Sphere', 'Cylinder' ], description='Object {}:'.format(i + 1), disabled=False, layout=wd.Layout(margin='20px 0px 10px -20px')) for i in range(20) ] self.ddwf = wd.Dropdown(options=[ ' ', 'gaussian', 'gaussiandot', 'gaussiandotnorm', 'gaussiandotdot', 'gaussiandotdotnorm', 'ricker', 'gaussianprime', 'gaussiandoubleprime', 'sine', 'contsine' ], description='Waveform: ', disabled=False, layout=wd.Layout(width='23%', margin='2px 5px 10px 0px')) self.ddsrc = wd.Dropdown(options=[ ' ', 'hertzian_dipole', 'voltage_source', 'magnetic_dipole' ], description='Source: ', disabled=False, layout=wd.Layout(width='23%', margin='2px 5px 10px 0px')) self.dom = [wd.Text(layout=wd.Layout(width='15%')) for i in range(3)] self.sp = [wd.Text(layout=wd.Layout(width='15%')) for i in range(3)] self.time_window = wd.Text(layout=wd.Layout(width='15%')) self.title = wd.Text(layout=wd.Layout(width='50%')) self.msg = wd.Text(layout=wd.Layout(width='15%')) self.intRes = wd.Text( layout=wd.Layout(width='11%', margin='10px 0px 0px 0px')) self.wfAll.append( [wd.Text(layout=wd.Layout(width='15%')) for i in range(3)]) self.srcAll.append( [wd.Text(layout=wd.Layout(width='13%')) for i in range(4)]) self.rcAll.append( [wd.Text(layout=wd.Layout(width='13%')) for i in range(3)]) self.steps = [wd.Text(layout=wd.Layout(width='15%')) for i in range(6)] self.goAll.append( [wd.Text(layout=wd.Layout(width='13%')) for i in range(9)]) self.goAll[0].append(wd.Text(layout=wd.Layout(width='25%'))) self.spaceList = [ wd.HBox([ wd.Label('Title: ', layout=wd.Layout(width='20%')), self.title ]), wd.HBox([ wd.Label('', layout=wd.Layout(width='25%')), wd.Label('X', layout=wd.Layout(width='15%')), wd.Label('Y', layout=wd.Layout(width='15%')), wd.Label('Z', layout=wd.Layout(width='15%')) ]), wd.HBox([ wd.Label('Domain: ', layout=wd.Layout(width='20%')), self.dom[0], self.dom[1], self.dom[2] ]), wd.HBox([ wd.Label('', layout=wd.Layout(width='25%')), wd.Label('dx', layout=wd.Layout(width='15%')), wd.Label('dy', layout=wd.Layout(width='15%')), wd.Label('dz', layout=wd.Layout(width='15%')) ]), wd.HBox([ wd.Label('Spacing: ', layout=wd.Layout(width='20%')), self.sp[0], self.sp[1], self.sp[2] ]), wd.HBox([ wd.Label('Time Window: ', layout=wd.Layout(width='20%')), self.time_window ]), wd.HBox([ wd.Label('Messages(y/n): ', layout=wd.Layout(width='20%')), self.msg ]) ] self.propLabels = wd.HBox([ wd.Label('', layout=wd.Layout(width='10%')), wd.Label('Relative Permittivity', layout=wd.Layout(width='15%')), wd.Label('\t\t\tConductivity', layout=wd.Layout(width='15%')), wd.Label('Relative Permeability', layout=wd.Layout(width='15%')), wd.Label('Magnetic Loss', layout=wd.Layout(width='15%')), wd.Label('Name', layout=wd.Layout(width='25%')) ]) self.srList = [ wd.HBox([ wd.Label(' ', layout=wd.Layout(width='12%')), wd.Label('Type', layout=wd.Layout(width='11.5%')), wd.Label('Scaling of max amplitude', layout=wd.Layout(width='17%')), wd.Label('Center frequency', layout=wd.Layout(width='17%')), wd.Label('Name', layout=wd.Layout(width='5%')) ], layout=wd.Layout(margin='10px 0px 10px 0px')), wd.HBox([ self.ddwf, self.wfAll[0][0], self.wfAll[0][1], self.wfAll[0][2] ]), wd.HBox([ wd.Label(' ', layout=wd.Layout(width='12%')), wd.Label('Type', layout=wd.Layout(width='11%')), wd.Label('Polarization (x,y or z)', layout=wd.Layout(width='19%')), wd.Label('X', layout=wd.Layout(width='12%')), wd.Label('Y', layout=wd.Layout(width='13%')), wd.Label('Z', layout=wd.Layout(width='15%')), ], layout=wd.Layout(margin='10px 0px 10px 0px')), wd.HBox([ self.ddsrc, self.srcAll[0][0], self.srcAll[0][1], self.srcAll[0][2], self.srcAll[0][3] ]), wd.HBox([ wd.Label( 'If voltage source specify internal resistance (Ohm):', layout=wd.Layout(width='30%', margin='10px 0px 0px 87px')), self.intRes ]), wd.HBox([ wd.Label(' ', layout=wd.Layout(width='14%')), wd.Label('X', layout=wd.Layout(width='13%')), wd.Label('Y', layout=wd.Layout(width='12%')), wd.Label('Z', layout=wd.Layout(width='9%')) ], layout=wd.Layout(margin='10px 0px 0px 0px')), wd.HBox([ wd.Label('Receiver: ', layout=wd.Layout(width='6.2%', margin='0px 0px 20px 25px')), self.rcAll[0][0], self.rcAll[0][1], self.rcAll[0][2] ]), wd.HBox([ wd.Label( 'For B-scan specify increments to move sources and receivers:', layout=wd.Layout(width='40%', margin='10px 0px 0px 5px')) ]), wd.HBox([ wd.Label(' ', layout=wd.Layout(width='17%')), wd.Label('x', layout=wd.Layout(width='15%')), wd.Label('y', layout=wd.Layout(width='15%')), wd.Label('z', layout=wd.Layout(width='15%')) ]), wd.HBox([ wd.Label('Source steps: ', layout=wd.Layout(width='10%')), self.steps[0], self.steps[1], self.steps[2] ]), wd.HBox([ wd.Label('Receiver steps: ', layout=wd.Layout(width='10%')), self.steps[3], self.steps[4], self.steps[5] ], layout=wd.Layout(margin='0px 0px 20px 0px')) ] self.goList = [ wd.HBox([ wd.Label(' ', layout=wd.Layout(width='5%')), wd.Label('X start', layout=wd.Layout(width='13%')), wd.Label('Y start', layout=wd.Layout(width='13%')), wd.Label('Z start', layout=wd.Layout(width='13%')), wd.Label('X end', layout=wd.Layout(width='13%')), wd.Label('Y end', layout=wd.Layout(width='13%')), wd.Label('Z end', layout=wd.Layout(width='9%')) ], layout=wd.Layout(margin='10px 0px 0px 0px')), wd.HBox([ wd.Label(' ', layout=wd.Layout(width='1%')), self.goAll[0][0], self.goAll[0][1], self.goAll[0][2], self.goAll[0][3], self.goAll[0][4], self.goAll[0][5] ]), wd.HBox([ wd.Label(' ', layout=wd.Layout(width='6%')), wd.Label('dx', layout=wd.Layout(width='13%')), wd.Label('dy', layout=wd.Layout(width='13%')), wd.Label('dz', layout=wd.Layout(width='9%')) ], layout=wd.Layout(margin='10px 0px 0px 0px')), wd.HBox([ wd.Label(' ', layout=wd.Layout(width='1%')), self.goAll[0][6], self.goAll[0][7], self.goAll[0][8] ]), wd.HBox([ wd.Label(' ', layout=wd.Layout(width='3%')), wd.Label('Geometry filename (no extension)', layout=wd.Layout(width='22%')) ], layout=wd.Layout(margin='10px 0px 0px 0px')), wd.HBox([ wd.Label(' ', layout=wd.Layout(width='1%')), self.goAll[0][9] ], layout=wd.Layout(margin='0px 0px 20px 0px')), self.wrFile ] self.add_mat.on_click(self.on_button_clicked) self.add_obj.on_click(self.on_button_clicked2) self.rem_obj.on_click(self.on_button_clicked3) self.wrFile.on_click(self.write_file) [self.dd[i].observe(self.on_change, 'value') for i in range(20)] self.gb = wd.GridBox( children=self.spaceList, layout=wd.Layout(grid_template_columns="repeat(1, 500px)")) self.gb2 = wd.GridBox( children=self.widgetList, layout=wd.Layout(grid_template_columns="repeat(1, 900px)")) self.gb3 = wd.GridBox( children=self.objectList, layout=wd.Layout(grid_template_columns="repeat(1, 1100px)")) self.gb4 = wd.GridBox( children=self.srList, layout=wd.Layout(grid_template_columns="repeat(1, 1000px)")) self.gb5 = wd.GridBox( children=self.goList, layout=wd.Layout(grid_template_columns="repeat(1, 900px)")) self.acc = wd.Accordion( children=[self.gb, self.gb2, self.gb3, self.gb4, self.gb5]) for i in range(5): self.acc.set_title(i, self.accNames[i]) display(self.acc)
def base_path(file_path, param, base_number): """!@brief Display base to Jupyter notebook given a file path This function displays the options for the base. If the @a file_path does not exist, this function displays nothing. @param file_path (str) Path to a file containing the 3D structure of the base molecule @param param (dict) @a options._options_dict['Base'] @param base_number The number of the new base @returns None; @a jupyter_widgets.input_options is modified in place @sa upload_base @sa input_options @sa options._options_dict @sa view_nglview """ if not os.path.isfile(file_path): # Check if the requested file is in the "pnab/data" directory file_path = os.path.join(__path__[0], 'data', file_path) if not os.path.isfile(file_path): # Unset the values for backbone parameters and return param['linker']['default'][0] = param['linker']['default'][1] = 1 return # Show molecule using NGLView with atom numbers num_atoms = view_nglview(file_path, label=True) # Display widgets for base-to-backbone connection linker1 = widgets.Dropdown(value=param['linker']['default'][0], options=range(1, num_atoms + 1), layout=widgets.Layout(width='100px')) linker2 = widgets.Dropdown(value=param['linker']['default'][1], options=range(1, num_atoms + 1), layout=widgets.Layout(width='100px')) # Add help box help_box = widgets.Button(description='?', tooltip=param['linker']['long_glossory'], layout=widgets.Layout(width='4%')) box = widgets.HBox([help_box, widgets.Label(param['linker']['glossory'], layout={'width': '400px'}), linker1, linker2]) # Display display(box) # Code code = widgets.Text(value=param['code']['default'], description=param['code']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['code']['long_glossory'], layout=widgets.Layout(width='4%')) box = widgets.HBox([help_box, code]) display(box) # Name name = widgets.Text(value=param['name']['default'], description=param['name']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['name']['long_glossory'], layout=widgets.Layout(width='4%')) box = widgets.HBox([help_box, name]) display(box) # Pair name pair_name = widgets.Text(value=param['pair_name']['default'], description=param['pair_name']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['pair_name']['long_glossory'], layout=widgets.Layout(width='4%')) box = widgets.HBox([help_box, pair_name]) display(box) # Align align = widgets.Checkbox(value=param['align']['default'], indent=False, description=param['align']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['align']['long_glossory'], layout=widgets.Layout(width='4%')) box = widgets.HBox([help_box, align]) display(box) # Add widgets to the widgets dictionary input_options['Base %i' %base_number] = {'file_path': file_path, 'linker': [linker1, linker2], 'code': code, 'name': name, 'pair_name': pair_name, 'align': align}
def helical_parameters(param): """ Display widgets for specifying helical parameters. It also displays an image illustrating the used helical parameters. @param param (dict) @a options._options_dict['HelicalParameters'] @returns None; @a jupyter_widgets.input_options is modified in place @sa input_options @sa display_options_widgets @sa options._options_dict """ display(widgets.HTML(value='<H3>Helical Parameters</H3>')) # Display an image showing the helical parameters for DNA and RNA display(Image(os.path.join(__path__[0], 'images', 'helical_parameters.jpg'), width=800)) param_dict = {} # Add widget to the widgets dictionary input_options['HelicalParameters'] = {} def helical_or_step(mode, param): if mode == 'Helical': excluded_parameters = ['shift', 'slide', 'rise', 'tilt', 'roll', 'twist'] input_options['HelicalParameters']['is_helical'] = True else: excluded_parameters = ['x_displacement', 'y_displacement', 'h_rise', 'inclination', 'tip', 'h_twist'] input_options['HelicalParameters']['is_helical'] = False for k in param: if k == 'is_helical' or k in excluded_parameters: continue param_dict[k] = [] default = [param[k]['default'][0], param[k]['default'][1], param[k]['default'][2]] # [beginning point, end point, number of steps] # Set angles if k in ['inclination', 'tip', 'h_twist', 'roll', 'tilt', 'twist', 'buckle', 'propeller', 'opening']: param_dict[k].append(widgets.FloatRangeSlider(value=[default[0], default[1]], min=-180, max=180, step=0.01, readout_format='.2f')) # Set distances else: # h_rise, x-displacement, y-displacement, rise, slide, shift, stretch, shear, stagger # limit maxium and minimum distance values to be between -20 and 20 and 0.01 Angstrom step size param_dict[k].append(widgets.FloatRangeSlider(value=[default[0], default[1]], min=-20, max=20, step=0.01, readout_format='.3f')) # Add the number of steps widgets param_dict[k].append(widgets.BoundedIntText(value=default[2], min=1, max=1000, step=1, description='Steps')) help_box = widgets.Button(description='?', tooltip=param[k]['long_glossory'], layout=widgets.Layout(width='3%')) box = widgets.HBox([help_box, widgets.Label(param[k]['glossory'], layout={'width': '200px'}), param_dict[k][0], param_dict[k][1]]) display(box) # Add widgets for helical parameter k to the widgets dictionary input_options['HelicalParameters'][k] = [param_dict[k][0], param_dict[k][1]] default = 'Helical' if param['is_helical']['default'] else 'Step' help_box = widgets.Button(description='?', tooltip=param['is_helical']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, widgets.interactive(helical_or_step, mode=widgets.Dropdown(value=default, options=['Helical', 'Step'], description="Base step scheme", style={'description_width': 'initial'}, #layout={'width': '75%'} ), param=widgets.fixed(param))]))
def state_problem(self): # show title and statement super().state_problem() # show expressions used in problem if len(self.expression) == 1: if type(self.expression[0] == str): display(Markdown(self.expression[0])) else: display(Math(latex(self.expression[0]))) if len(self.expression) > 1: for i in range(len(self.expression)): if type(self.expression[i] == str): display( Markdown("**(" + str(i + 1) + ")** " + self.expression[i])) else: display( Math("**(" + str(i + 1) + ")** \quad" + latex(self.expression[i]))) if self.input_widget: # if input_widget flag is set and multiple inputs required, # display instructions if self.num_inputs > 1: display(Markdown("*Separate multiple answers by comma(s).*")) # next create text widget and button # Setup text input field self.input_field = widgets.Text(value='', placeholder='Type here', description='Answer: ', continuous_update=False, disabled=False) self.input_field.observe(self.on_enter, names='value') # Submit button self.submit_button = widgets.Button( description='Submit', disabled=False, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Check answer', ) self.submit_button.on_click(self.on_submit) # Put widgets in box display(widgets.Box([self.input_field, self.submit_button])) else: #if not, display cell instructions display(Markdown("*Enter the answer(s) in the cell below.*")) if self.output_widget: # Add dedicated output area self.out = widgets.Output() display(self.out)
def display_gui(wti_index, corpus): compute_callback = compute_most_discriminating_terms display_callback = display_most_discriminating_terms lw = lambda w: widgets.Layout(width=w) include_pos_tags = [ 'ADJ', 'VERB', 'NUM', 'ADV', 'NOUN', 'PROPN' ] normalize_options = { 'Lemma': spacy.attrs.LEMMA, 'Lower': spacy.attrs.LOWER, 'Orth': spacy.attrs.ORTH } party_preset_options = wti_index.get_party_preset_options() parties_options = [ x for x in wti_index.get_countries_list() if x not in ['ALL', 'ALL OTHER'] ] signed_years = { d._.meta['signed_year'] for d in corpus } period_default = (min(signed_years), max(signed_years)) gui = types.SimpleNamespace( progress=widgets.IntProgress(value=0, min=0, max=5, step=1, description='', layout=lw('90%')), group1=widgets.SelectMultiple(description='Group 1', options=parties_options, value=[], rows=7, layout=lw('250px')), group2=widgets.SelectMultiple(description='Group 2', options=parties_options, value=[], rows=7, layout=lw('250px')), group1_preset=widgets_config.dropdown('Presets', party_preset_options, None, layout=lw('250px')), group2_preset=widgets_config.dropdown('Presets', party_preset_options, None, layout=lw('250px')), top_n_terms=widgets.IntSlider(description='#terms', min=10, max=1000, value=100, tooltip='The total number of most discriminating terms to return for each group'), max_n_terms=widgets.IntSlider(description='#top', min=1, max=2000, value=2000, tooltip='Only consider terms whose document frequency is within the top # terms out of all terms'), include_pos=widgets.SelectMultiple(description='POS', options=include_pos_tags, value=include_pos_tags, rows=7, layout=lw('150px')), period1=widgets.IntRangeSlider(description='Period', min=period_default[0], max=period_default[1], value=period_default, layout=lw('250px')), period2=widgets.IntRangeSlider(description='Period', min=period_default[0], max=period_default[1], value=period_default, layout=lw('250px')), closed_region=widgets.ToggleButton(description='Closed regions', icon='check', value=True, disabled=False, layout=lw('140px')), sync_period=widgets.ToggleButton(description='Sync period', icon='check', value=False, disabled=False, layout=lw('140px'), tooltop='HEJ'), normalize=widgets.Dropdown(description='Normalize', options=normalize_options, value=spacy.attrs.LEMMA, layout=lw('200px')), compute=widgets.Button(description='Compute', icon='', button_style='Success', layout=lw('120px')), output=widgets.Output(layout={'border': '1px solid black'}) ) boxes = widgets.VBox([ widgets.HBox([ widgets.VBox([ gui.group1, gui.group1_preset, gui.period1 ]), widgets.VBox([ gui.group2, gui.group2_preset, gui.period2 ]), widgets.VBox([ gui.include_pos, gui.closed_region, gui.sync_period, ], layout=widgets.Layout(align_items='flex-end')), widgets.VBox([ gui.top_n_terms, gui.max_n_terms, gui.normalize, gui.compute ],layout=widgets.Layout(align_items='flex-end')), # layout=widgets.Layout(align_items='flex-end')), # widgets.VBox([ # gui.compute, # widgets.HTML( # '<b>#terms</b> is the number of most discriminating<br>terms to return for each group.<br>' + # '<b>#top</b> Consider only terms with a frequency<br>within the top #top terms out of all terms<br>' # '<b>Closed region</b> If checked, then <u>both</u> treaty parties<br>must be within selected region' # ) # ]) ]), gui.output ]) display(boxes) def on_group1_preset_change(change): if gui.group1_preset.value is None: return gui.group1.value = gui.group1.options if 'ALL' in gui.group1_preset.value else gui.group1_preset.value def on_group2_preset_change(change): if gui.group2_preset.value is None: return gui.group2.value = gui.group2.options if 'ALL' in gui.group2_preset.value else gui.group2_preset.value def on_period1_change(change): if gui.sync_period.value: gui.period2.value = gui.period1.value def on_period2_change(change): if gui.sync_period.value: gui.period1.value = gui.period2.value gui.group1_preset.observe(on_group1_preset_change, names='value') gui.group2_preset.observe(on_group2_preset_change, names='value') gui.period1.observe(on_period1_change, names='value') gui.period2.observe(on_period2_change, names='value') def compute_callback_handler(*_args): gui.output.clear_output() with gui.output: try: gui.compute.disabled = True df = compute_callback( wti_index=wti_index, corpus=corpus, group1=gui.group1.value, group2=gui.group2.value, top_n_terms=gui.top_n_terms.value, max_n_terms=gui.max_n_terms.value, include_pos=gui.include_pos.value, period1=gui.period1.value, period2=gui.period2.value, closed_region=gui.closed_region.value, normalize=gui.normalize.value ) if df is not None: display_callback(df) else: logger.info('No data for selected groups or periods.') except Exception as ex: logger.error(ex) finally: gui.compute.disabled = False gui.compute.on_click(compute_callback_handler) return gui
def set_button_launcher(desc): button = widgets.Button( description=desc, layout={"width": "max-content"}, ) return button
def plot(dset, **kwargs): defaults = {'name': '', 'show_comment': False, 'show_title': True, 'auto_copy': True, 'cmap': 'plasma', 'reverse': False, 'auto_scale': True, 'offset': 0., 'xlog': False, 'ylog': False} defaults.update(kwargs) if isinstance(dset, xr.DataArray): dset = xr.Dataset({dset.name:dset}) # We must use a weak reference to hdf so that it can be released properly # when not used, since otherwise ipywidgets.interact captures all the arguments. dset_ref = weakref.ref(dset) data_keys = dset.data_vars.keys() name = defaults['name'] if name not in data_keys: name = data_keys[-1] name_widget = ip.Dropdown(options=data_keys, description='name', value=name) show_comment = ip.ToggleButton(description='show note', value=defaults['show_comment']) show_title = ip.Checkbox(description='show title', value=defaults['show_title']) auto_copy = ip.Checkbox(description='auto copy', value=defaults['auto_copy']) comment_widget = ip.HTML(value='<pre><code>{0}</code></pre>'.format(dset.attrs.get("comment", ''))) comment_widget.layout.display = 'none' def __show_comment_changed(change): comment_widget.layout.display = '' if show_comment.value else 'none' __show_comment_changed(None) show_comment.observe(__show_comment_changed, 'value') copy_position_button = ip.Button(description='Copy (x, y)') copy_distance_button = ip.Button(description='Copy (dx, dy)') copy_position_button.layout.width = copy_distance_button.layout.width = '300px' def __copy_val(btn): try: text = str(btn.value).decode('utf8') win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT) win32clipboard.CloseClipboard() except: # Ignore errors pass copy_distance_button.on_click(__copy_val) copy_position_button.on_click(__copy_val) sub_widgets = [] plot_widgets = [] plot_fig = [] def _plot_2D(data, facet_dict, fname, data_label): maps = [cm for cm in plt.colormaps() if not cm.endswith("_r")] for k in ('magma', 'inferno', 'plasma', 'viridis'): maps.remove(k) maps.insert(0, k) #maps.sort() cmap_widget = ip.Dropdown(description='cmap', options=maps, value=defaults['cmap']) reverse_widget = ip.Checkbox(description='reverse', value=defaults['reverse']) robust_widget = ip.Checkbox(description='auto scale', value=defaults['auto_scale']) min_v, max_v = np.min(data), np.max(data) scale_widget = ip.FloatRangeSlider(min=min_v, max=max_v, step=(max_v-min_v)/100., value=(min_v, max_v), continuous_update=False) scale_widget.layout.visibility = 'hidden' def __robust_changed(change): scale_widget.layout.visibility = 'hidden' if robust_widget.value else '' robust_widget.observe(__robust_changed, 'value') def __replot(change): cmap = cmap_widget.value if reverse_widget.value: cmap += '_r' if not facet_dict: plt.figure(figsize=(6,4.5)) if robust_widget.value: data.plot(cmap=cmap, robust=True, **facet_dict) else: min_v, max_v = scale_widget.value data.plot(cmap=cmap, vmin=min_v, vmax=max_v, **facet_dict) plt.gca().collections[-1].colorbar.set_label(data_label) ws = [cmap_widget, reverse_widget, robust_widget, scale_widget] return ws, __replot def _plot_1D(data_list, fname, data_label): offset_widget = ip.FloatText(description='offset', value=defaults['offset']) def __replot(change): offset = offset_widget.value for i in range(len(data_list)): (data_list[i] + offset * i).plot() plt.ylabel(data_label) ws = [offset_widget] return ws, __replot def _update_plot(change): if plot_widgets: plot_widgets.pop().close() dset = dset_ref() facets = [] idx = [] for c in sub_widgets[0].children: if c.value == 'facet': facets.append(len(idx)) idx.append(slice(None)) else: idx.append(c.value) data = dset[name_widget.value][tuple(idx)] faceted_dims = len(data.shape) - len(facets) if faceted_dims > 2 and len(facets) < 2: for i in range(len(data.shape)): if i not in facets: facets.append(i) faceted_dims -= 1 if faceted_dims == 2 or len(facets) == 2: break try: units = dset[name_widget.value].units data_label = '{0} ({1})'.format(name_widget.value, units) except: data_label = name_widget.value fname = dset.attrs.get('filename', '') if faceted_dims == 2: # 2D plot facet_dict = {} if facets: facet_dict['col'] = data.dims[facets[-1]] if len(facets) == 2: facet_dict['row'] = data.dims[facets[0]] widgets, plot_func = _plot_2D(data, facet_dict, fname, data_label) else: # Make stacked line plots s = list(data.shape) i = len(s) - 1 while i > 0: if i not in facets: break i -= 1 s[i] = 1 dl = [] for idx in np.ndindex(tuple(s)): j = list(idx) j[i] = slice(None) dl.append(data[tuple(j)]) widgets, plot_func = _plot_1D(dl, fname, data_label) xscale_widget = ip.Checkbox(description='xlog', value=defaults['xlog']) yscale_widget = ip.Checkbox(description='ylog', value=defaults['ylog']) padding_widget = ip.FloatSlider(description='pad', min=0., max=1.0, step=0.1, value=0.2, continuous_update=False) widgets.extend([xscale_widget, yscale_widget, padding_widget]) def __plot_wrapper(change): if plot_fig: plt.close(plot_fig.pop()) clear_output(wait=True) plot_func(change) fig = plt.gcf() plot_fig.append(fig) if show_title.value: fig.suptitle(fname, fontsize=16, y=1.02) # Workaround for tha lack of png transparency support in Windows fig.patch.set_facecolor('white') fig.patch.set_alpha(1.0) if xscale_widget.value: plt.gca().set_xscale('log') if yscale_widget.value: plt.gca().set_yscale('log') # Adjust axis formatters for ax in fig.axes: for xyax in [ax.xaxis, ax.yaxis]: if type(xyax.get_major_formatter()) == ScalarFormatter: fmt = ScalarFormatter(useMathText=True, useOffset=False) fmt.set_powerlimits((-3, 3)) xyax.set_major_formatter(fmt) cid = [] prev_clicked = [0, 0] def __adjust(event): # Adjust figure padding to accomodate the suptitle and axis labels # Call this only once after the figure is displayed fig.canvas.mpl_disconnect(cid[0]) bb = fig.bbox_inches.padded(padding_widget.value) adjust_bbox(fig, bb) fig.set_size_inches(bb.bounds[2], bb.bounds[3], forward=True) if auto_copy.value: copy2clipboard(fig, pad_inches=padding_widget.value) def __clicked(event): copy_position_button.value = (event.xdata, event.ydata) copy_position_button.description = 'Copy (x,y)=(%f,%f)' % copy_position_button.value copy_distance_button.value = (event.xdata - prev_clicked[0], event.ydata - prev_clicked[1]) copy_distance_button.description = 'Copy (dx,dy)=(%f,%f)' % copy_distance_button.value prev_clicked[0] = event.xdata prev_clicked[1] = event.ydata cid.append(fig.canvas.mpl_connect('draw_event', __adjust)) fig.canvas.mpl_connect('button_press_event', __clicked) for w in widgets: w.observe(__plot_wrapper, 'value') plot_widgets.append(ip.HBox(widgets)) display(plot_widgets[0]) __plot_wrapper(None) def _update(change): if sub_widgets: sub_widgets.pop().close() dset = dset_ref() index_widgets = [] for dim in dset[name_widget.value].dims: coord = dset[name_widget.value].coords[dim] indexes = OrderedDict({':': slice(None)}) indexes['facet'] = 'facet' for i in range(len(coord)): indexes[float(coord[i])] = i drop = ip.Dropdown(description=dim, options=indexes) drop.observe(_update_plot, 'value') index_widgets.append(drop) sub_widgets.append(ip.HBox(index_widgets)) display(sub_widgets[0]) _update_plot(None) for w in [name_widget, show_title]: w.observe(_update, 'value') display(comment_widget) display(ip.HBox([name_widget, show_comment, show_title, auto_copy])) _update(None) display(ip.HBox([copy_position_button, copy_distance_button]))
for key, column_names in columns.items(): visible = key in selections for c in column_names: try: glyphs[c].visible = visible except AttributeError: for glyph in glyphs[c]: glyph.visible = visible push_notebook(handle=pn) ## next_store = widgets.Button( description='Next store', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', icon='check') store_text = widgets.Text(value=str(stores.min() - 1), placeholder='Type something', description='Store:', disabled=False) def update_store_text(*args): s = int(store_text.value) if s < stores.max(): store_text.value = str(s + 1)
def polynomial_regression(): """Polynomial regression example""" regression_config = {"degree": 1} sc_x = LinearScale(min=-100, max=100) sc_y = LinearScale(min=-100, max=100) scat = Scatter( x=[], y=[], scales={"x": sc_x, "y": sc_y}, colors=["orange"], enable_move=True ) lin = Lines( x=[], y=[], scales={"x": sc_x, "y": sc_y}, line_style="dotted", colors=["blue"] ) def update_line(change=None): if len(scat.x) == 0 or len(scat.y) == 0 or scat.x.shape != scat.y.shape: lin.x = [] lin.y = [] return pipe = make_pipeline( PolynomialFeatures(degree=regression_config["degree"]), LinearRegression() ) pipe.fit(scat.x.reshape(-1, 1), scat.y) with lin.hold_sync(): if len(lin.x) == 0: lin.x = np.linspace(sc_x.min, sc_x.max) lin.y = pipe.predict(np.linspace(sc_x.min, sc_x.max).reshape(-1, 1)) update_line() # update line on change of x or y of scatter scat.observe(update_line, names=["x", "y"]) with scat.hold_sync(): scat.enable_move = False scat.interactions = {"click": "add"} ax_x = Axis(scale=sc_x, tick_format="0.0f", label="x") ax_y = Axis(scale=sc_y, tick_format="0.0f", orientation="vertical", label="y") fig = Figure(marks=[scat, lin], axes=[ax_x, ax_y]) # reset reset_button reset_button = widgets.Button(description="Reset") def on_button_clicked(change=None): with scat.hold_sync(): scat.x = [] scat.y = [] dropdown_w.value = None reset_button.on_click(on_button_clicked) # polynomial degree slider degree = widgets.IntSlider( value=regression_config["degree"], min=1, max=5, step=1, description="Degree" ) def degree_change(change): regression_config["degree"] = change["new"] update_line() degree.observe(degree_change, names="value") # dropdown for dataset selection dropdown_w = widgets.Dropdown( options=fake_datasets(ndim=2), value=None, description="Dataset:" ) def dropdown_on_change(change): if change["type"] == "change" and change["name"] == "value": if change["new"] is not None: x, y = fake_datasets(name=change["new"]) with scat.hold_sync(): scat.x = x.flatten() scat.y = y.flatten() dropdown_w.observe(dropdown_on_change) return VBox( ( widgets.HTML("<h1>Polynomial regression</h1>"), reset_button, dropdown_w, degree, fig, ) )
def algorithm(chosen_algorithm, param): """!@brief Display search parameters based on the chosen algorithm There are six search algorithms and each one has a set of input parameters. The search algorithms are: - Systematic Search: Requires specifying the dihedral angle step size, @a dihedral_step. - Monte Carlo Search: Requires specifying the number of steps, @a num_steps, and the Monte Carlo temperature, @a monte_carlo_temperature. - Weighted Monte Carlo Search: Also requires specifying the weighting temperature, @a weighting_temperature. - Random Search: Requires specifying the number of steps, @a num_steps. - Weighted Random Search: Also requires specifying the weighting temperature, @a weighting_temperature. - Genetic Algorithm Search: Requires specifying the number of generations, @a num_steps, the population size, @a population_size, the mutation_rate, @a mutation_rate, and the crossover rate, @a crossover_rate. @param chosen_algorithm (str) The chosen algorithm @param param (dict) @a options._options_dict['RuntimeParameters'] @returns None; @a jupyter_widgets.input_options is modified in place @sa runtime_parameters @sa input_options @sa options._options_dict """ chosen_algorithm = chosen_algorithm.lower() # Add widget to the widgets dictionary input_options['RuntimeParameters']['search_algorithm'] = chosen_algorithm # Systematic search algorithm needs a dihedral step size if chosen_algorithm == 'systematic search': dihedral_step = widgets.BoundedFloatText(value=param['dihedral_step']['default'], min=0.0, max=360.0, description=param['dihedral_step']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['dihedral_step']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, dihedral_step])) input_options['RuntimeParameters']['dihedral_step'] = dihedral_step # The other five algorithms require specifying the random number seed and the number of steps or generation else: # Random number generator seed seed = widgets.BoundedIntText(value=param['seed']['default'], min=0, max=2**32-1, description=param['seed']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['seed']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, seed])) input_options['RuntimeParameters']['seed'] = seed # Number of steps or generations num_steps = widgets.BoundedIntText(value=param['num_steps']['default'], min=1, max=1e100, description=param['num_steps']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['num_steps']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, num_steps])) input_options['RuntimeParameters']['num_steps'] = num_steps # If the algorithm weights the dihedral angle probability profile, we need to specify the temperature # used in the weighting if "weighted" in chosen_algorithm: weighting_temperature = widgets.BoundedFloatText(value=param['weighting_temperature']['default'], min=1, max=1e100, description=param['weighting_temperature']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['weighting_temperature']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, weighting_temperature])) input_options['RuntimeParameters']['weighting_temperature'] = weighting_temperature # Specify the temperature for the Monte Carlo procedure if "monte carlo search" in chosen_algorithm: monte_carlo_temperature = widgets.BoundedFloatText(value=param['monte_carlo_temperature']['default'], min=1, max=1e100, description=param['monte_carlo_temperature']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['monte_carlo_temperature']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, monte_carlo_temperature])) input_options['RuntimeParameters']['monte_carlo_temperature'] = monte_carlo_temperature # Specify population size, mutation rate, and crossover rate for genetic algorithm if 'genetic algorithm search' in chosen_algorithm: population_size = widgets.BoundedIntText(value=param['population_size']['default'], min=1, max=1e100, description=param['population_size']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['population_size']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, population_size])) input_options['RuntimeParameters']['population_size'] = population_size mutation_rate = widgets.BoundedFloatText(value=param['mutation_rate']['default'], min=0, max=1, description=param['mutation_rate']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['mutation_rate']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, mutation_rate])) input_options['RuntimeParameters']['mutation_rate'] = mutation_rate crossover_rate = widgets.BoundedFloatText(value=param['crossover_rate']['default'], min=0, max=1, description=param['crossover_rate']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['crossover_rate']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, crossover_rate])) input_options['RuntimeParameters']['crossover_rate'] = crossover_rate
import ipywidgets as widgets from IPython.display import display, HTML button = widgets.Button(description="Submit Solution") name_box = widgets.Text(value='', description='Name:') email_box = widgets.Text(value='', description='Email:') js = """ <script> alert('asdf'); function findCellsByTag(tagName) { return Jupyter.notebook.get_cells().filter( ({metadata: {tags}}) => tags && tags.includes(tagName)); } </script> """ display(HTML(js)) def on_clicked(b): name = name_box.value email = email_box.value print(name, email) js = """ <script> console.log('here'); var submit_cell = findCellsByTag('code')[0]; var text = submit_cell.get_text(); alert(text); </script> """ display(HTML(js))
def runtime_parameters(param): """!@brief Runtime parameter widget for use in Jupyter notebook Displays widgets for specifying runtime parameters. @param param (dict) @a options._options_dict['RuntimeParameters'] @returns None; @a jupyter_widgets.input_options is modified in place @sa algorithm @sa input_options @sa display_options_widgets @sa options._options_dict """ display(widgets.HTML(value='<H3>Runtime Parameters</H3>')) input_options['RuntimeParameters'] = {} # Search algorithm display(widgets.HTML(value='<H4>Search Algorithm</H4>')) dropdown = widgets.Dropdown(value=param['search_algorithm']['default'].title(), options=['Weighted Monte Carlo Search', 'Monte Carlo Search', 'Weighted Random Search', 'Random Search', 'Genetic Algorithm Search', 'Systematic Search'], description=param['search_algorithm']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) search_algorithm = widgets.interactive_output(algorithm, {'chosen_algorithm':dropdown, 'param':widgets.fixed(param)}) help_box = widgets.Button(description='?', tooltip=param['search_algorithm']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, dropdown])) display(search_algorithm) # Maximum number of accepted candidates num_candidates = widgets.BoundedIntText(value=param['num_candidates']['default'], min=1, max=2**32-1, description=param['num_candidates']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['num_candidates']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, num_candidates])) input_options['RuntimeParameters']['num_candidates'] = num_candidates display(widgets.HTML(value='<H4>Distance and Energy Thresholds</H4>')) # Distance and energy thresholds # Threshold for the distance max_distance = widgets.BoundedFloatText(value=param['max_distance']['default'], min=0.0, description=param['max_distance']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['max_distance']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, max_distance])) input_options['RuntimeParameters']['max_distance'] = max_distance # Force field ff_type = widgets.Dropdown(value=param['ff_type']['default'], options=['GAFF', 'MMFF94', 'MMFF94s', 'UFF', 'GHEMICAL'], description=param['ff_type']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['ff_type']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, ff_type])) input_options['RuntimeParameters']['ff_type'] = ff_type # Energy filters input_options['RuntimeParameters']['energy_filter'] = [] for i in range(5): minimum = 0 if i < 3 else -1e10 # Put the minimum value to zero for bonded terms label = param['energy_filter']['glossory'].split('\n')[i] energy_filter = widgets.BoundedFloatText(value=param['energy_filter']['default'][i], min=minimum, max=1e10, description=label, style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['energy_filter']['long_glossory'].split('\n')[i], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, energy_filter])) input_options['RuntimeParameters']['energy_filter'].append(energy_filter) display(widgets.HTML(value='<H4>Structural Parameters</H4>')) # Base sequence strand = widgets.Text(value=''.join(param['strand']['default']), description=param['strand']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['strand']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, strand])) input_options['RuntimeParameters']['strand'] = strand # Pair adenine with uracil? Default is A-T base pair pair_A_U = widgets.Checkbox(value=param['pair_A_U']['default'], indent=False, description=param['pair_A_U']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['pair_A_U']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, pair_A_U])) input_options['RuntimeParameters']['pair_A_U'] = pair_A_U # Is hexad is_hexad = widgets.Checkbox(value=param['is_hexad']['default'], indent=False, description=param['is_hexad']['glossory'], style={'description_width': 'initial'}, layout={'width': '75%'}) help_box = widgets.Button(description='?', tooltip=param['is_hexad']['long_glossory'], layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, is_hexad])) input_options['RuntimeParameters']['is_hexad'] = is_hexad # Build strand input_options['RuntimeParameters']['build_strand'] = [] help_box = widgets.Button(description='?', tooltip=param['build_strand']['long_glossory'], layout=widgets.Layout(width='3%')) box = [help_box, widgets.Label(param['build_strand']['glossory'])] for i in range(6): build_strand = widgets.Checkbox(value=param['build_strand']['default'][i], indent=False, layout={'width': '50px'}) input_options['RuntimeParameters']['build_strand'].append(build_strand) box.append(build_strand) box = widgets.HBox(box, layout={'width':'100%'}) display(box) # Orientation of each strand in the hexad input_options['RuntimeParameters']['strand_orientation'] = [] help_box = widgets.Button(description='?', tooltip=param['strand_orientation']['long_glossory'], layout=widgets.Layout(width='3%')) box = [help_box, widgets.Label(param['strand_orientation']['glossory'])] for i in range(6): strand_orientation = widgets.Checkbox(value=param['strand_orientation']['default'][i], indent=False, layout={'width': '50px'}) input_options['RuntimeParameters']['strand_orientation'].append(strand_orientation) box.append(strand_orientation) box = widgets.HBox(box, layout={'width':'100%'}) display(box)
def render_create_interface(cloud_list, cloud_index): service = cloud_list[cloud_index] if not service.check_setup(): instances = [] else: instances = service.get_instances_info() group_list = ["Create Group"] for instance in instances: group_name = instance['Group Name'] if group_name not in group_list and group_name != '': group_list.append(group_name) group_list.sort(key=str.lower) group_dropdown = widgets.Dropdown( options=group_list, description="Group: ", ) new_group_text = widgets.Text(value='', placeholder='New Group Name', disabled=False) def on_change(change): if (group_dropdown.value == "Create Group"): new_group_text.disabled = False else: new_group_text.disabled = True group_dropdown.observe(on_change) name_row_arr = [group_dropdown, new_group_text] name_row = widgets.HBox(name_row_arr) size_list = service.get_size_list() value = service.get_default_size() size_dropdown = widgets.Dropdown( options=size_list, description="Size: ", value=value, ) num_instances = widgets.BoundedIntText(value=1, min=1, max=20, step=1, description='How Many?', disabled=False) create_button = widgets.Button(description='Create Instance') def create_button_clicked(b): if (new_group_text.value == '' and group_dropdown.value == 'Create Group'): print("Please enter a group name") else: # def create_instance(self,group,size,region): group = group_dropdown.value if (group == "Create Group"): group = new_group_text.value service.create_instance(group, size_dropdown.value, num_instances.value) create_button.on_click(create_button_clicked) size_region_row = [size_dropdown, num_instances] sr_row = widgets.HBox(size_region_row) if service.check_setup(): display(name_row) display(sr_row) display(create_button) else: fn = "./src/plugins/" + service.name + "Service/" + service.name + "Setup.txt" html_as_str = open(fn, 'r').read() setup = widgets.HTML(value=html_as_str) display(setup)
def display_options_widgets(param, input_file, uploaded=False): """!@brief Display all widgets in Jupyter notebook given an input file If @a input_file is provided, then it updates the default options in @a options._options_dict to display the user-defined options. If @a input_file is "Upload file", then an ipywidgets.FileUpload widget is displayed. This function also displays a widget for running the program after the user defines all the options. @param param (dict) @a options._options_dict @param input_file (str) Input file @param uploaded (bool) Whether a file is uploaded by the user or not @returns None @sa backbone @sa bases @sa helical_parameters @sa runtime_parameters @sa upload_input @sa run @sa user_input_file @sa options._options_dict """ if input_file == "Upload file": # Display a widget for uploading input file w = widgets.interactive(upload_input, param=widgets.fixed(param), f=widgets.FileUpload(accept='', multiple=False, description="Input File")) help_box = widgets.Button(description='?', tooltip='Upload your input file here. The file will be copied to the current folder.', layout=widgets.Layout(width='4%')) display(widgets.HBox([help_box, w])) return # If the file is not uploaded, then we are using one of the example files # in the pnab/data directory if not uploaded: input_file = os.path.join(__path__[0], 'data', input_file) options = yaml.load(open(input_file, 'r'), yaml.FullLoader) # Clean dictionary from additional bases if they are not defined in the options # This is necessary when the user switches from an input file that has additional bases to one that does not num_defined_bases = len([k for k in param if 'Base' in k]) - 1 # Subtract the item from the main options for i in range(1, num_defined_bases + 1): param.pop('Base %i' %i) input_options.pop('Base %i' %i) # Update the default options to display those provided by the user for k1, v1 in options.items(): if 'Base' in k1: param[k1] = copy.deepcopy(param['Base']) for k2, v2 in options[k1].items(): param[k1][k2]['default'] = options[k1][k2] # Display all options widgets backbone(param['Backbone']) bases_param = {k:val for k, val in param.items() if 'Base' in k} bases(bases_param) helical_parameters(param['HelicalParameters']) runtime_parameters(param['RuntimeParameters']) # Display run widget button = widgets.Button(description='Run', tooltip='Click here to run the program with the provided options. Once the program finishes, the results will be displayed below.') button.on_click(run) display(button)
start_func=run_sim_func, done_func=run_done_func, cachename='pc4cancerimmune', showcache=False, outcb=outcb) else: if (hublib_flag): run_button = RunCommand(start_func=run_sim_func, done_func=run_done_func, cachename='pc4cancerimmune', showcache=False, outcb=outcb) else: run_button = widgets.Button( description='Run', button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Run a simulation', ) run_button.on_click(run_button_cb) if nanoHUB_flag or hublib_flag: read_config = widgets.Dropdown( description='Load Config', options=get_config_files(), tooltip='Config File or Previous Run', ) read_config.style = { 'description_width': '%sch' % str(len(read_config.description) + 1) } read_config.observe(read_config_cb, names='value')
from __future__ import print_function import ipywidgets as widgets from IPython.display import display button = widgets.Button(description="Tip resonance shape") display(button) def on_button_clicked(b): print( "[SWE] Titta på https://en.wikipedia.org/wiki/Resonance_(particle_physics)" ) print( "[ENG] Check out https://en.wikipedia.org/wiki/Resonance_(particle_physics)" ) button.on_click(on_button_clicked)
# In[2]: import ipywidgets as widgets from IPython.display import display # In[3]: #Basic styling # In[4]: button = widgets.Button( description='Hello World!', width=100, # Integers are interpreted as pixel measurements. height='2em', # em is valid HTML unit of measurement. color='lime', # Colors can be set by name, background_color='#0022FF', # and also by color code. border_color='cyan') display(button) # In[5]: #Parent/child relationships # In[6]: from IPython.display import display float_range = widgets.FloatSlider() string = widgets.Text(value='hi')
def create_ui(self): # Create the active UI components. Height and width are specified in 'em' units. This is # a html size specification, size relative to current font size. self.viewing_checkbox = widgets.RadioButtons( description='Mode:', options=['edit', 'drag', 'rotate'], value='edit') self.viewing_checkbox.observe(self.draw_centroid) self.noise_button = widgets.Button(description='Add Noise', width='7em', height='3em') self.noise_button.on_click(self.noise) self.outlier_button = widgets.Button(description='Add Outlier', width='7em', height='3em') self.outlier_button.on_click(self.outlier) self.bias1_button = widgets.Button(description='Bias (FRE<TRE)', width='7em', height='3em') self.bias1_button.on_click(self.bias_1) self.bias2_button = widgets.Button(description='Bias (FRE>TRE)', width='7em', height='3em') self.bias2_button.on_click(self.bias_2) self.clear_fiducial_button = widgets.Button( description='Clear Fiducials', width='7em', height='3em') self.clear_fiducial_button.on_click(self.clear_fiducials) self.clear_target_button = widgets.Button(description='Clear Targets', width='7em', height='3em') self.clear_target_button.on_click(self.clear_targets) self.reset_button = widgets.Button(description='Reset', width='7em', height='3em') self.reset_button.on_click(self.reset_indexes) self.register_button = widgets.Button(description='Register', width='7em', height='3em') self.register_button.on_click(self.register) # Layout of UI components. This is pure ugliness because we are not using a UI toolkit. Layout is done # using the box widget and padding so that the visible UI components are spaced nicely. bx0 = widgets.Box(padding=2, children=[self.viewing_checkbox]) bx1 = widgets.Box(padding=15, children=[self.noise_button]) bx2 = widgets.Box(padding=15, children=[self.outlier_button]) bx3 = widgets.Box(padding=15, children=[self.bias1_button]) bx4 = widgets.Box(padding=15, children=[self.bias2_button]) bx5 = widgets.Box(padding=15, children=[self.clear_fiducial_button]) bx6 = widgets.Box(padding=15, children=[self.clear_target_button]) bx7 = widgets.Box(padding=15, children=[self.reset_button]) bx8 = widgets.Box(padding=15, children=[self.register_button]) return widgets.HBox(children=[ bx0, widgets.VBox(children=[ widgets.HBox([bx1, bx2, bx3, bx4]), widgets.HBox(children=[bx5, bx6, bx7, bx8]) ]) ])
import ipywidgets as widgets from pytube import YouTube from IPython.display import display text=widgets.Label("Youtube Downloader") Link=widgets.Text(placeholder="Enter the Link here",description='Link') Button=widgets.Button(description='HQ VIDEO',icon='fa-youtube-square') #font_awesome is used for the icon Button1=widgets.Button(description='AUDIO',icon='fa-music') display(text,Link,Button,Button1) def Download_Video(a): link=str(Link.value) obj=YouTube(link) video=obj.streams.filter(progressive=True,file_extension='mp4') for mp4 in video: video.get_highest_resolution().download(output_path="#path need to be saved") #getting highest resolution print("Downloaded Succesfully in path") def Download_Audio(a): link=str(Link.value) obj=YouTube(link) obj.streams.get_audio_only().download(output_path="#path need to be saved") #getting only auido print("Downloaded Succesfully in path") Button.on_click(Download_Video) Button1.on_click(Download_Audio)
def _make_widgets(self): self._main_label = widgets.HTML("<b>PyDSS Data Viewer</b>") text_layout_long = widgets.Layout(width="400px") text_layout_med = widgets.Layout(width="200px") text_layout_short = widgets.Layout(width="100px") button_layout = widgets.Layout(width="200px") path = "" if self._defaults[ "project_path"] is None else self._defaults["project_path"] self._project_path_text = widgets.Text( path, description="Project Path", layout=text_layout_long, placeholder="pydss_projects/project1/", ) self._load_project_btn = widgets.Button(description="Load project", layout=button_layout) self._load_project_btn.on_click(self._on_load_project_click) self._scenario_label = widgets.HTML("Scenario", layout=text_layout_med) self._elem_class_label = widgets.HTML("Element Class", layout=text_layout_med) self._elem_prop_label = widgets.HTML("Element Property", layout=text_layout_med) self._prop_available_options_label = widgets.HTML("Options") self._prop_options_label = widgets.HTML("Element Property Options", layout=text_layout_med) self._num_elems_label = widgets.HTML("Number of Elements", layout=text_layout_med) self._elem_regex_label = widgets.HTML("Element Name Regex", layout=text_layout_med) self._start_time_label = widgets.HTML("Start Time", layout=text_layout_med) self._end_time_label = widgets.HTML("End Time", layout=text_layout_med) self._resolution_label = widgets.HTML("Resolution", layout=text_layout_med) self._moving_avg_cb = widgets.Checkbox(value=False, description="Moving Average", disabled=True) self._window_label = widgets.HTML("Moving Average Window", layout=text_layout_med) self._window_text = widgets.Text(value="4") self._scenario_dd = widgets.Dropdown( options=self._scenario_names, value=self._scenario_names[0], disabled=True, ) self._scenario_dd.observe(self._on_scenario_change, names="value") self._elem_class_dd = widgets.Dropdown( options=self._element_classes, value=self._element_classes[0], disabled=True, ) self._elem_class_dd.observe(self._on_elem_class_change, names="value") self._elem_prop_dd = widgets.Dropdown( options=self._element_props, value=self._element_props[0], disabled=True, ) self._elem_prop_dd.observe(self._on_elem_prop_change, names="value") self._prop_available_options_text = widgets.Text(disabled=True) self._prop_options_text = widgets.Text(disabled=True) self._num_elems_text = widgets.Text(disabled=True) self._elem_regex_text = widgets.Text(disabled=True, placeholder="p1udt.*") self._elem_names_select = widgets.SelectMultiple( options=[""], value=[""], rows=5, description="Elements", disabled=True, ) self._start_time_text = widgets.Text(disabled=True) self._end_time_text = widgets.Text(disabled=True) self._resolution_text = widgets.Text(disabled=True) self._load_dataframe_btn = widgets.Button( description="Load DataFrame", layout=button_layout, disabled=True, tooltip="Load DataFrame into `app.df`", ) self._load_dataframe_btn.on_click(self._on_load_dataframe_click) self._plot_btn = widgets.Button(description="Plot", layout=button_layout) self._plot_btn.on_click(self._on_plot_click) self._aggregation_label = widgets.HTML("Aggregation", layout=text_layout_short) self._aggregation_dd = widgets.Dropdown( options=["None", "Min/Mean/Max", "Sum"], value="None", disabled=True, ) self._real_only_cb = widgets.Checkbox( value=True, description="Exclude imaginary parts", disabled=True) self._reset_btn = widgets.Button(description="Reset", layout=button_layout) self._reset_btn.on_click(self._on_reset_click) self._plot_output = widgets.Output()
def multiple_choice(option_1, option_2, option_3, option_4): option_list = [option_1, option_2, option_3, option_4] answer = option_list[0] letters = ["<b>(A)</b> ", "<b>(B)</b> ", "<b>(C)</b> ", "<b>(D)</b> "] #Randomly shuffle the options random.shuffle(option_list) #Print the letters (A) to (D) in sequence with randomly chosen options for i in range(4): option_text = option_list.pop() option_text_2 = letters[i] + option_text option_output = widgets.HTMLMath(value=option_text_2) display(option_output) #Stores the correct answer if option_text == answer: letter_answer = letters[i] button1 = widgets.Button(description="(A)") button2 = widgets.Button(description="(B)") button3 = widgets.Button(description="(C)") button4 = widgets.Button(description="(D)") button1.style.button_color = 'Whitesmoke' button2.style.button_color = 'Whitesmoke' button3.style.button_color = 'Whitesmoke' button4.style.button_color = 'Whitesmoke' container = widgets.HBox(children=[button1, button2, button3, button4]) display(container) print(" ", end='\r') def on_button1_clicked(b): if "<b>(A)</b> " == letter_answer: print("Correct! ", end='\r') button1.style.button_color = 'Moccasin' button2.style.button_color = 'Whitesmoke' button3.style.button_color = 'Whitesmoke' button4.style.button_color = 'Whitesmoke' else: print("Try again.", end='\r') button1.style.button_color = 'Lightgray' button2.style.button_color = 'Whitesmoke' button3.style.button_color = 'Whitesmoke' button4.style.button_color = 'Whitesmoke' def on_button2_clicked(b): if "<b>(B)</b> " == letter_answer: print("Correct! ", end='\r') button1.style.button_color = 'Whitesmoke' button2.style.button_color = 'Moccasin' button3.style.button_color = 'Whitesmoke' button4.style.button_color = 'Whitesmoke' else: print("Try again.", end='\r') button1.style.button_color = 'Whitesmoke' button2.style.button_color = 'Lightgray' button3.style.button_color = 'Whitesmoke' button4.style.button_color = 'Whitesmoke' def on_button3_clicked(b): if "<b>(C)</b> " == letter_answer: print("Correct! ", end='\r') button1.style.button_color = 'Whitesmoke' button2.style.button_color = 'Whitesmoke' button3.style.button_color = 'Moccasin' button4.style.button_color = 'Whitesmoke' else: print("Try again.", end='\r') button1.style.button_color = 'Whitesmoke' button2.style.button_color = 'Whitesmoke' button3.style.button_color = 'Lightgray' button4.style.button_color = 'Whitesmoke' def on_button4_clicked(b): if "<b>(D)</b> " == letter_answer: print("Correct! ", end='\r') button1.style.button_color = 'Whitesmoke' button2.style.button_color = 'Whitesmoke' button3.style.button_color = 'Whitesmoke' button4.style.button_color = 'Moccasin' else: print("Try again.", end='\r') button1.style.button_color = 'Whitesmoke' button2.style.button_color = 'Whitesmoke' button3.style.button_color = 'Whitesmoke' button4.style.button_color = 'Lightgray' button1.on_click(on_button1_clicked) button2.on_click(on_button2_clicked) button3.on_click(on_button3_clicked) button4.on_click(on_button4_clicked)
def build(self): '''Create user interface widgets''' tabs = []; # Tab 1: Welcome ====================================================== content = [] content.append(self.section(self.WELCOME1_TITLE,self.WELCOME1_TEXT)) content.append(self.section(self.WELCOME2_TITLE,self.WELCOME2_TEXT)) tabs.append(ui.VBox(content)) # Tab 2: Samples ====================================================== content = [] # CSS (stle) and start the table table = '''<style> .sample_cell {padding-right: 32px } .sample_even {background : White } .sample_odd {background : Gainsboro} </style><table>''' samp_hdrs,samp_data = self.model.get_samples() for item in samp_hdrs: table += '<th class="sample_cell">' + item + '</th>' for i,line in enumerate(samp_data): if i % 2 == 0: table += '<tr class="sample_even">' else: table += '<tr class="sample_odd">' for item in line: table += '<td class="sample_cell">' + item + '</td>' table += '</tr>' table += '</table>' widgets = [] widgets.append(ui.HTML(value=table)) content.append(self.section(self.SAMPLES1_TITLE,widgets)) tabs.append(ui.VBox(content)) # Tab 3: Filter ====================================================== self.filter_txt_gene = ui.Text(description='',value='',placeholder=self.FILTER1_HINT ) # Test: Sevir.9G584100/5G108900 self.filter_txt_func = ui.Text(description='',value='',placeholder=self.FILTER2_HINT ) self.filter_txt_tpm = ui.Text(description=self.FILTER6_TEXT,value=self.DEFAULT_TPM ,placeholder='NA') self.filter_txt_pval = ui.Text(description=self.FILTER8_TEXT,value=self.DEFAULT_PVAL,placeholder='NA') self.filter_txt_fdr = ui.Text(description=self.FILTER9_TEXT,value=self.DEFAULT_FDR ,placeholder='NA') self.filter_conditons = [] # Created in loop below self.filter_btn_apply = ui.Button(description=self.FILTER_APPLY,icon='filter',layout=self.LO20) self.filter_ddn_ndisp = ui.Dropdown(options=['25','50','100',self.ALL],layout=self.LO10) self.filter_html_output = ui.HTML(self.EMPTY_LIST_MSG) self.filter_btn_refexp = ui.Button(description=self.FILTER_REFEXP,icon='download',layout=self.LO20) content = [] widgets = [] widgets.append(ui.HTML(value=self.FILTER1_TEXT)) widgets.append(ui.HTML(value=self.FILTER1_TEXT_2)) widgets.append(self.filter_txt_gene) content.append(self.section(self.FILTER1_TITLE,widgets)) widgets = [] widgets.append(ui.HTML(value=self.FILTER2_TEXT)) widgets.append(self.filter_txt_func) content.append(self.section(self.FILTER2_TITLE,widgets)) widgets = [] widgets.append(ui.HTML(value=self.FILTER5_TEXT)) widgets.append(self.filter_txt_tpm) widgets.append(ui.HTML(value=self.FILTER7_TEXT)) widgets.append(self.filter_txt_pval) widgets.append(self.filter_txt_fdr ) # Conditions ("Set expressions tests..."): matrix of 3-state buttons # Title widgets.append(ui.HTML(value=self.FILTER_CONDS_TITLE)) # Column headers (2 rows of headers) widgets.append(ui.HTML('<style> .ctrhdr {text-align: center; font-weight: bold;} </style>')) div = '<div class="ctrhdr">' vid = '</div>' row = [] row.append(ui.Label(value='' ,layout=self.LO15 )) row.append(ui.HTML(div+self.FILTER_CONDS_MIN_HDR1+vid,layout=ui.Layout(width=self.FILTER_CONDS_COL_WIDTH))) row.append(ui.HTML(div+self.FILTER_CONDS_DIF_HDR1+vid,layout=ui.Layout(width=self.FILTER_CONDS_COL_DBLWI))) widgets.append(ui.HBox(row)) row = [] row.append(ui.HTML( self.FILTER_CONDS_CON_HDR ,layout=self.LO15 )) row.append(ui.HTML(div+self.FILTER_CONDS_MIN_HDR2 +vid,layout=ui.Layout(width=self.FILTER_CONDS_COL_WIDTH))) row.append(ui.HTML(div+self.FILTER_CONDS_DIF_HDR2O+vid,layout=ui.Layout(width=self.FILTER_CONDS_COL_WIDTH))) row.append(ui.HTML(div+self.FILTER_CONDS_DIF_HDR2U+vid,layout=ui.Layout(width=self.FILTER_CONDS_COL_WIDTH))) widgets.append(ui.HBox(row)) # Buttons for item in self.model.cond: row = [] row.append(ui.Label(value=item ,layout=self.LO15 )) row.append(ui.Button(icon=self.FILT_CLR,layout=ui.Layout(width=self.FILTER_CONDS_COL_WIDTH))) row.append(ui.Button(icon=self.FILT_CLR,layout=ui.Layout(width=self.FILTER_CONDS_COL_WIDTH))) row.append(ui.Button(icon=self.FILT_CLR,layout=ui.Layout(width=self.FILTER_CONDS_COL_WIDTH))) self.filter_conditons.append((row[1],row[2],row[3])) widgets.append(ui.HBox(row)) content.append(self.section(self.FILTER3_TITLE,widgets)) # "Filtered gene list" widgets = [] row = [] row.append(self.filter_btn_apply) row.append(ui.HTML('<div style="text-align: right;">'+self.FILTER15_TEXT+'</div>',layout=self.LO15)) row.append(self.filter_ddn_ndisp) row.append(ui.HTML('<div style="text-align: left;">' +self.FILTER16_TEXT+'</div>',layout=self.LO10)) widgets.append(ui.HBox(row)) widgets.append(ui.HBox([self.filter_html_output],layout={'width':'90vw'})) # Cause horiz. scrollbar (was: 1200) content.append(self.section(self.FILTER4_TITLE,widgets)) # "Export" self.filter_out_export = ui.Output(layout={'border': '1px solid black'}) row = self.section(self.FILTER24_TITLE,[ui.VBox([self.filter_btn_refexp,self.filter_out_export])]) #row.selected_index = None content.append(row) tabs.append(ui.VBox(content)) # Tab 4: Plot-experiment ====================================================== content = [] content.append(self.section(self.PLOTEX1_TITLE,self.PLOTEX1_TEXT)) # Plot line graphs --- self.plotex_ddn_selex_lg = ui.Dropdown(options=[self.EMPTY]+self.model.exps,value=None,disabled=True) widgets = [] row = [] row.append(ui.HTML(value=self.PLOTEX2_TEXT)) row.append(ui.Label(value='',layout=ui.Layout(width='60%'))) # Cheat: spacer widgets.append(ui.HBox(row)) widgets.append(self.plotex_ddn_selex_lg) widgets.append(self.ctrl.plotter.line_plot) # Use widget from plotter content.append(self.section(self.PLOTEX2_TITLE,widgets)) # Plot heatmaps --- self.plotex_ddn_selex_hm = ui.Dropdown(options=[self.EMPTY,self.ALL]+self.model.exps,value=None,disabled=True) self.plotex_img_dispp_hm = ui.Output() self.ctrl.plotter.out_plot_msg(self.plotex_img_dispp_hm,self.ctrl.plotter.HEAT_INIT_TITLE) widgets = [] row = [] row.append(ui.HTML(value=self.PLOTEX3_TEXT)) row.append(ui.Label(value='',layout=ui.Layout(width='60%'))) # Cheat: spacer widgets.append(ui.HBox(row)) widgets.append(self.plotex_ddn_selex_hm) widgets.append(self.plotex_img_dispp_hm) content.append(self.section(self.PLOTEX3_TITLE,widgets)) tabs.append(ui.VBox(content)) # Tab 5: Plot-coexpression ====================================================== # Get list of networks and sort them using inline function that parses out numeric portion of network name networks = sorted(self.model.get_networks(),key=lambda x: int(x.split('_')[1])) # Build display/value pairs as list of tuples for use in dropdown menu disp_vals = [] for i,net in enumerate(networks): #disp_vals.append((net.replace('_',' '),net) ) disp_vals.append((net.split('_')[1],net) ) self.plotco_ddn_netw = ui.Dropdown(options=[(self.EMPTY,self.EMPTY)]+disp_vals,value=None,disabled=True) # Download button self.plotco_btn_modu = ui.Button(description=self.FILTER_REFEXP,icon='download',layout=self.LO20) # Create a fixed width data selection widet self.plotco_sel_modu = ui.Select(rows=10,options=[],value=None,layout={'width':'99%'}) self.plotco_sel_modu.add_class('selmono') # Use JavaScript to spec fixed-width font (see custom CSS) # Module selection # NOTE If using latest ver of Jupyter, consider using grid widet instead of fixed font select widget # Create a fixed width header widget that will match data widget header = [self.MODULE_HEADER[0][:-2],self.MODULE_HEADER[1][:-2]] # Hide last 2 cols, tho they're used in export/download header = self.columnize(self.MODULE_HEADER[0][:-2],header) header = ui.Select(options=header,disabled=True,value=None,layout=ui.Layout(height='3em',width='99%')) header.add_class('selmono') # Use JavaScript to spec fixed-width font (see custom CSS) content = [] # Image with open('images/DecayRates.png','rb') as handle: image = handle.read() widgets = [] widgets.append(ui.HTML(self.PLOTCO1_TEXT_A)) widgets.append(ui.Image(value=image,format='png',width=500,height=259)) widgets.append(ui.HTML(self.PLOTCO1_TEXT_B)) content.append(self.section(self.PLOTEX1_TITLE,widgets)) # Select Network Graph widgets = [] widgets.append(ui.HTML(value=self.PLOTCO1_LABEL)) widgets.append(self.plotco_ddn_netw) row = [] row.append(ui.HTML(value=self.PLOTCO3_TEXT)) row.append(ui.Label(value='',layout=ui.Layout(width='60%'))) # Cheat: spacer widgets.append(ui.HBox(row)) widgets.append(ui.HBox([ui.VBox([header,self.plotco_sel_modu],layout={'width':'100%'})])) # was: ,layout={'width':'90vw'} content.append(self.section(self.PLOTCO1_TITLE,widgets)) # "Export" self.plotco_out_export = ui.Output(layout={'border': '1px solid black'}) row = self.section(self.FILTER24_TITLE,[ui.VBox([self.plotco_btn_modu,self.plotco_out_export])]) row.selected_index = None content.append(row) # Network Graph of Selected Module NOTE Uses widget created by plotter content.append(self.section(self.PLOTCO2_TITLE,[self.ctrl.plotter.net_plot])) tabs.append(ui.VBox(content)) # Tab 6: Plot-differentialy ====================================================== content = [] content.append(self.section(self.PLOTEX1_TITLE,self.PLOTDE1_TEXT)) self.plotdif_sel_title = ui.HTML(value=self.PLOTDE4_TEXT,layout={'width':'99%'}) self.plotdif_sel_genes = ui.SelectMultiple(rows=10,options=[],value=[],layout={'width':'99%'}) self.plotdif_img_disp = ui.Output() self.plotdif_btn_plot = ui.Button(description=self.PLOTDE2_TEXT,icon='bar-chart',layout=self.LO20) self.ctrl.plotter.out_plot_msg(self.plotdif_img_disp,self.ctrl.plotter.DIF_INIT_TITLE) widgets = [] widgets.append(self.plotdif_sel_title) widgets.append(self.plotdif_sel_genes) widgets.append(self.plotdif_btn_plot) widgets.append(ui.Label(value='',layout=ui.Layout(width='60%'))) # Cheat: spacer widgets.append(self.plotdif_img_disp) widgets.append(ui.Label(value='',layout=ui.Layout(width='60%'))) # Cheat: spacer content.append(self.section(self.PLOTDE3_TEXT,widgets)) tabs.append(ui.VBox(content)) # Tab bar ====================================================== self.tabs = ui.Tab() for i in range(len(self.TABS)): self.tabs.set_title(i,self.TABS[i]) self.tabs.children = tuple(tabs)
def __init__(self, **kwargs): computer_image = ipw.HTML( '<img width="200px" src="./miscellaneous/images/computer.png">') # Computer ssh settings self._inp_username = ipw.Text(description="SSH username:"******"350px"), style=STYLE) self._inp_password = ipw.Password(description="SSH password:"******"130px"), style=STYLE) self._inp_computer_hostname = ipw.Text( description="Computer name:", layout=ipw.Layout(width="350px"), style=STYLE) # Proxy ssh settings self._use_proxy = ipw.Checkbox(value=False, description='Use proxy') self._use_proxy.observe(self.on_use_proxy_change, names='value') self._inp_proxy_address = ipw.Text(description="Proxy server address:", layout=ipw.Layout(width="350px"), style=STYLE) self._use_diff_proxy_username = ipw.Checkbox( value=False, description='Use different username and password', layout={'width': 'initial'}) self._use_diff_proxy_username.observe( self.on_use_diff_proxy_username_change, names='value') self._inp_proxy_username = ipw.Text( value='', description="Proxy server username:"******"350px"), style=STYLE) self._inp_proxy_password = ipw.Password( value='', description="Proxy server password:"******"138px"), style=STYLE) # Setup ssh button and output self._btn_setup_ssh = ipw.Button(description="Setup ssh") self._btn_setup_ssh.on_click(self.on_setup_ssh) self._setup_ssh_out = ipw.Output() # Check whether some settings were already provided predefine_settings(self, **kwargs) # Defining widgets positions computer_ssh_box = ipw.VBox([ self._inp_computer_hostname, self._inp_username, self._inp_password, self._use_proxy ], layout=ipw.Layout(width="400px")) self._proxy_user_password_box = ipw.VBox( [self._inp_proxy_username, self._inp_proxy_password], layout={'visibility': 'hidden'}) self._proxy_ssh_box = ipw.VBox([ self._inp_proxy_address, self._use_diff_proxy_username, self._proxy_user_password_box ], layout={ 'visibility': 'hidden', 'width': '400px' }) children = [ ipw.HBox([computer_image, computer_ssh_box, self._proxy_ssh_box]), self._btn_setup_ssh, self._setup_ssh_out ] super(SshComputerSetup, self).__init__(children, **kwargs)
def single_run(data_dir="", id=""): if not os.path.exists(data_dir): raise FileNotFoundError("No directory found named: " + data_dir) run_summary = RunSummary(data_dir=data_dir, id=id) sedov_solution = SedovSolution(E_0, run_summary.overview.background_density, run_summary.overview.metallicity) #### PASS TO PLOTTER #### num_checkpoints = len(run_summary.filenames) # log_R_max = round(np.log10(run_summary.df["Radius"].max()), 2) # log_R_min = max(log_R_max-4, # round(np.log10(run_summary.df["Radius"].min()), 2)+1) R_min = run_summary.df["Radius"].min() R_min = 0 R_max = run_summary.df["Radius"].max() if type(single_run.previous_widget) is widgets.Box: single_run.previous_widget.close() w = interactive( plotter, run_summary=fixed(run_summary), sedov_solution=fixed(sedov_solution), xlim=FloatRangeSlider( min=R_min, max=R_max, step=0.01 * (R_max - R_min), value=(R_min, R_max), ), checkpoint_index=IntSlider(min=0, max=num_checkpoints - 1, step=0, value=num_checkpoints - 1), y_axis_variable=Dropdown(options=cols_plot, value="Density"), x_axis_variable=RadioButtons(options=["Radius", "M_int", "zones"]), label=fixed("numeric"), density_in_mH_cm3=fixed(False), verbose=fixed(True), ) w1 = widgets.Button(description=u"\u23EA") def show_first(b): checkpoint_slider = w.children[5] checkpoint_slider.value = checkpoint_slider.min w1.on_click(show_first) wl = widgets.Button(description=u"\u276E") def show_prev(b): checkpoint_slider = w.children[5] if checkpoint_slider.value > checkpoint_slider.min: checkpoint_slider.value -= 1 wl.on_click(show_prev) w2 = widgets.Button(description=u"\u25BA") # w2.stop = False def play(b): checkpoint_slider = w.children[5] for i in range(checkpoint_slider.value + 1, checkpoint_slider.max + 1): plt.gcf() checkpoint_slider.value = i # plt.show() # time.sleep(.1) # if b.stop: # break w2.on_click(play) # wp = widgets.Button(description=u"p") # def pause(b): # w2.stop=True # wp.on_click(pause) wr = widgets.Button(description=u"\u276F") def show_next(b): checkpoint_slider = w.children[5] if checkpoint_slider.value < checkpoint_slider.max: checkpoint_slider.value += 1 wr.on_click(show_next) w3 = widgets.Button(description=u"\u23E9") def show_last(b): checkpoint_slider = w.children[5] checkpoint_slider.value = checkpoint_slider.max w3.on_click(show_last) w_buttons = widgets.HBox(children=[w1, wl, w2, wr, w3]) w.children = tuple([_w for _w in w.children] + [w_buttons]) single_run.previous_widget = w display(w) # display(w_buttons) return run_summary