def run_game(game): ''' Runs the given game. This game engine supports turn based play. In each turn, the player chooses first chooses an option for an input named `a`, and then chooses an option for `c`. The image and the possible options for each input can be altered based on the inputs given. ''' input_a = widgets.ToggleButtons(options=game.options_a) input_c = widgets.ToggleButtons(options=['']) boxes = widgets.VBox([input_a,input_c]) display(boxes) def given_a(obs_a): if input_a.value not in ['',input_a.options[0]] and (input_a.value in input_a.options): game.given_a(input_a.value) input_c.options = game.options_c def given_c(obs_c): if (input_c.value not in ['',input_c.options[0]]) and (input_c.value in input_c.options): game.given_c(input_c.value) input_a.options = game.options_a input_c.options = [''] input_a.observe(given_a) input_c.observe(given_c)
def displayOptions(self): clear_output() self.html = widgets.HTML( '<h4>Sqlite database "%s" exists, do you want to overwrite?</h4>' '<h4>choose <b>yes</b> will <span style="color:red"><b>clear all the data</b></span> in that database file</h4>' % self.dbpath) self.toggle = widgets.ToggleButtons( options=['Yes', 'No'], description='', disabled=False, value='No', button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Replace the old database', 'Append data to the old database'], layout=widgets.Layout(width='70%') # icons=['check'] * 3 ) self.toggle.observe(self.on_click, 'value') self.html2 = widgets.HTML( '<h4>Do you want to import new data?</h4>') self.toggle2 = widgets.ToggleButtons( options=['Yes', 'No'], description='', disabled=False, value='No', button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Add new data to db', 'Use existing data in db'], layout=widgets.Layout(width='70%') ) # pad the descriptions list if it is shorter than options list self.resetParameters() self.box = self.updateBox() display(self.box) pass
def InteractiveDipoleDecay( self, xyz_loc, Field, compvalue, sig=1e-2, Tmin=1e-5, Tmax=1e-2, Waveform="stepoff" ): ntime = 200 srcLoc = np.r_[0.0, 0.0, 0.0] # orientation = "z" def foo(Component, Sigma, Scale): # , Waveform="stepoff"): orientation = "z" # vals = [] if Field == "E": unit = " (V/m)" elif Field == "H": unit = " (A/m)" elif Field == "dHdt": unit = " (A/m-s)" elif Field == "J": unit = " (A/m $^2$)" label = Field + Component + "-field " + unit t = np.logspace(np.log10(Tmin), np.log10(Tmax), ntime) valx, valy, valz = self.dataview.eval_TD( xyz_loc, srcLoc, np.r_[Sigma], t, orientation, self.dataview.func2D ) if Component == "x" or Component == "X": val = valx.copy() elif Component == "y" or Component == "Y": val = valy.copy() elif Component == "z" or Component == "Z": val = valz.copy() plt.figure(figsize=(7, 5)) ax = plt.subplot(111) if Scale == "log": valp, valn = DisPosNegvalues(val) ax.plot(t, valp, "k-") ax.plot(t, valn, "k--") elif Scale == "linear": ax.plot(t, val, "k-") ax.set_xscale("log") ax.set_yscale(Scale) ax.set_ylabel(label) ax.set_xlabel("Time (sec)") ax.grid(True) plt.show() Q3 = widgetify( foo, Component=widgets.ToggleButtons( options=["x", "y", "z"], value=compvalue, description="Comp." ), Sigma=widgets.FloatText( value=sig, continuous_update=False, description="$\sigma$ (S/m)" ), Scale=widgets.ToggleButtons(options=["log", "linear"]) # ,Waveform=widgets.ToggleButtons(options=['stepoff','stepon','rampoff'], value='stepoff') ) return Q3
def InteractivePlaneProfile(): nRx = 100 def foo(Field, Sigma, Scale, Time): plt.figure(figsize=(8, 4)) ax1 = plt.subplot(111) r = np.linspace(-1000.0, 0.0, nRx) val_ex, val_hy = PlaneEHfield(r, t=Time, sig=Sigma) if Field == "Ex": val = val_ex.flatten() label = "Ex-field (V/m)" elif Field == "Hy": val = val_hy.flatten() label = "Hy-field (A/m)" if Scale == "log": val_p, val_n = DisPosNegvalues(val) ax1.plot(r, val_p, "k-", lw=2) ax1.plot(r, val_n, "k--", lw=2) ax1.set_yscale(Scale) elif Scale == "linear": ax1.plot(r, val, "k-", lw=2) ax1.set_yscale(Scale) y = ax1.yaxis.get_majorticklocs() yticksa = np.linspace(y.min(), y.max(), 3) ax1.yaxis.set_ticks(yticksa) ax1.yaxis.set_major_formatter(ticker.FormatStrFormatter("%.1e")) ax1.set_xlim(0, -1000) ax1.set_ylabel(label, color="k") ax1.set_xlabel("Z (m)") ax1.grid(True) plt.show() Q2 = widgets.interactive( foo, Field=widgets.ToggleButtons(options=["Ex", "Hy"], value="Ex"), Sigma=widgets.FloatText(value=1, continuous_update=False, description="$\sigma$ (S/m)"), Scale=widgets.ToggleButtons(options=["log", "linear"], value="linear"), Time=widgets.FloatSlider(min=0.01, max=1.0, step=0.01, value=0.0, description="$t$ (s)"), ) return Q2
def __init__(self): super(PassGenGUI, self).__init__() self._helpful_title = widgets.HTML('Generated password is:') self._password_text = widgets.HTML('', placeholder='No password generated yet') self._password_text.layout.margin = '0 0 0 20px' self._password_length = widgets.IntSlider(description='Length of password', min=8, max=20, style={'description_width': 'initial'}) self._numbers = widgets.Checkbox(description='Include numbers in password', style={'description_width': 'initial'}) self._label = widgets.Label('Choose special characters to include') self._toggles = widgets.ToggleButtons(description='', options=[',./;[', '!@#~%', '^&*()'], style={'description_width': 'initial'}) # Set the margins to control the indentation. # The order is top right bottom left self._toggles.layout.margin = '0 0 0 20px' children = [self._helpful_title, self._password_text, self._password_length, self._label, self._toggles, self._numbers] self.children = children self.model = PassGen() traitlets.link((self.model, 'password'), (self._password_text, 'value')) traitlets.link((self.model, 'length'), (self._password_length, 'value')) traitlets.link((self.model, 'special_character_groups'), (self._toggles, 'value')) traitlets.link((self.model, 'include_numbers'), (self._numbers, 'value'))
def make_submission_output(text, student_id, store, studentRepository=None): """Creates the display of the submitted text with a toggle button to update whether the student receives credit """ bval = 'Credit' if student_id in store.credit else 'No credit' credit_button = widgets.ToggleButtons(options=['Credit', 'No credit'], value=bval, description='', disabled=False) student_name = '' if studentRepository: student_name = studentRepository.get_student_name(student_id) ta = make_text_display(student_id, text, student_name) def on_value_change(change): """The relevant callback NB the use of scope to define student_id""" v = change['new'] print(v, student_id) try: if v == 'Credit': store.assign_student_credit(student_id) elif v == 'No credit': store.assign_student_no_credit(student_id) except ValueError: pass credit_button.observe(on_value_change, names='value') display(widgets.VBox([ta, credit_button]))
def updateBox(self): rows = [self.title, self.text_area] exist_types = set(item.strip() for item in self.text_area.value.split("\n") if len(item.strip()) > 0) if self.workflow.dataset_id.endswith( '_sents' ) and AnnotationTypeDef.neutral_type not in exist_types: print('added') desc = widgets.HTML( value= 'You choose sentences dataset, adding an additional type "Irrelevant"' ' is recommended. Because in most of cases, you will likely to sample a ' 'sentence that does not fall into the types that you defined. Do you want to add it? ' ) self.addIrrelevant = widgets.ToggleButtons(options=['Yes', 'No']) rows += self.addSeparator(top='10px') rows.append(desc) rows.append(self.addIrrelevant) rows += self.addSeparator(top='10px') + [ self.addPreviousNext(self.show_previous, self.show_next) ] vbox = widgets.VBox(rows, layout=widgets.Layout(display='flex', flex_grown='column')) return vbox
def __init__(self, name=None): super().__init__(name) self.dao = None self.dbpath = '' self.remove_old = False self.dataset_name = 'orig' self.whoosh_root = ConfigReader.getValue("whoosh/root_path") self.html1 = widgets.HTML('<h4>Give a name for this dataset: </h4>') self.dataset_name_input = None self.html2 = None self.toggle = widgets.ToggleButtons( options=['TextBlob_Splitter', 'PyRuSh', 'Not_To_Split'], description='', disabled=False, value='Not_To_Split', button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Use TextBlob sentence splitter', 'Use PyRuSH to split sentences', 'don\'t split' ], layout=widgets.Layout(width='70%') # icons=['check'] * 3 ) self.data_step = None pass
def hidecode(): toggle = widgets.ToggleButtons( options=['Hide Code', 'Show Code'], disabled=False, ) display(toggle) def on_value_change(change): if change['new'] == 'Hide Code': display( Javascript( "Jupyter.toolbar.actions.call('jupyter-notebook:hide-toolbar')" )) display( Javascript( "Jupyter.toolbar.actions.call('jupyter-notebook:hide-header')" )) display(Javascript("$('div.input').hide();")) elif change['new'] == 'Show Code': display( Javascript( "Jupyter.toolbar.actions.call('jupyter-notebook:show-toolbar')" )) display( Javascript( "Jupyter.toolbar.actions.call('jupyter-notebook:show-header')" )) display(Javascript("$('div.input').show();")) toggle.observe(on_value_change, names='value')
def main(self): self.media_wid = widgets.ToggleButtons(options=['Lif', 'Images'], description='Media Input', value='Lif') self.media_wid.observe(self.media_update, ['value']) # self.mode_wid = widgets.ToggleButtons(options=['multi', 'single'], description='Tracking mode',tooltips=['Multiple frame tracking', 'Single frame tracking. Which singles must be specified']) # self.mode_wid.observe(self.mode_update, ['value']) self.fmt = widgets.Dropdown(options=['.tif', '.png', '.jpg'], description='Frame format') self.initial_frame = widgets.IntText(description='Initial frame') self.nframes = widgets.IntText(description='Z Frames', value=5) self.k = widgets.FloatSlider(min=1, max=10, step=0.2, description='k (Blur)', value=1.6) self.edge_cutoff = widgets.FloatText(description='Edge cut') self.plot = widgets.Checkbox(description='Show plots', value=True) self.options.children = [self.media_wid]
def make_selection( self, rowiter) -> Union[widgets.ToggleButtons, widgets.Select]: """ Construct buttons/selection to choose a label""" row = rowiter[1] # set value of selector from label column if label column was set if self.label_col is not None and row[self.label_col] in self.options: value = row[self.label_col] else: # set value of selector from target column if the value # in the target column is one of the labels if row[self.target_col] in self.options: value = row[self.target_col] else: value = None if self.button_type == 'button': sel = widgets.ToggleButtons(options=self.options, value=value, layout=Layout(width='100%')) else: sel = widgets.Select(options=self.options, value=value) self.active_selections.append((rowiter, sel)) return sel
def InteractivePlanes(planevalue="XZ", offsetvalue=0.0): def foo(Plane, Offset, nRx): X0, Y0, Z0 = -20, -50, -50 X2, Y2, Z2 = X0 + 100.0, Y0 + 100.0, Z0 + 100.0 return plotObj3D( offset_plane=Offset, X1=X0, X2=X2, Y1=Y0, Y2=Y2, Z1=Z0, Z2=Z2, nRx=nRx, plane=Plane, ) out = widgetify( foo, Offset=widgets.FloatSlider(min=-100, max=100, step=5.0, value=offsetvalue, continuous_update=False), # ,X0=widgets.FloatText(value=-20) \ # ,Y0=widgets.FloatText(value=-50.) \ # ,Z0=widgets.FloatText(value=-50.) \ nRx=widgets.IntSlider(min=4, max=200, step=2, value=40, continuous_update=False), Plane=widgets.ToggleButtons(options=["XZ", "YZ"], value=planevalue), ) return out
def create_qubit_and_plot_choice_widgets(self): """Creates all the widgets that controls which qubit or plot the user can choose from. """ self.qubit_and_plot_choice_widgets = { "qubit_buttons": widgets.ToggleButtons( options=self.supported_qubits, description="Qubits:", layout=widgets.Layout(width="800px"), ), "plot_buttons": widgets.ToggleButtons( options=self.plot_choices, description="Plot:", button_style="info", ), "show_qubitinfo_checkbox": widgets.Checkbox( value=False, description="qubit info", disabled=False ), } self.qubit_and_plot_choice_widgets["qubit_buttons"].observe( self.qubit_buttons_eventhandler, names="value" )
def FieldTypeSelect(ann, field_name): """ Form field type edit widget """ field_types = ann.field_schema.types field_types_inv = ann.field_schema.types_inv tp = ann.fields[field_name] type_select = widgets.ToggleButtons( options=list(field_types.keys()), value=field_types_inv[tp], ) def on_change(name, value): ann.fields[field_name] = field_types[value] type_select.on_trait_change(on_change, 'value') return type_select
def __init__(self, description='', name=str(Step.global_id + 1), sampler_cls: type = KeywordStratefiedSampler): super().__init__(name=name) self.toggle = widgets.ToggleButtons( options=sample_options, value=sample_options[-1], description='What to do with previously sampled data? ', style=dict(description_width='initial'), button_style='info') self.toggle.observe(self.onPreviousSampleHandleChange) self.sample_size_input = widgets.BoundedIntText( value=0, min=0, max=0, step=1, description='Total documents you want to sample:', style=dict(description_width='initial')) self.sample_size_input.observe(self.onSampleConfigChange) self.sampler_cls = sampler_cls self.sampled_summary = widgets.HTML(value='') self.percent_slider = widgets.IntSlider(value=70, min=0, max=100, step=5, description='', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') self.percent_slider.observe(self.onSampleConfigChange) # save DOC_IDs that contain or not contain keywords filters (used in sampling strategy) self.samples = {"contain": [], "notcontain": []} self.box = None self.data = {'docs': [], 'annos': OrderedDict()} self.ready = False # reset, continue, addmore, self.move_next_option = '' self.total = None self.total_contains = None self.un_reviewed = 0 self.sampler = None self.samples = dict() self.current_stats = dict() self.max_threshold = ConfigReader.getValue("review/rb_model_threshold") self.sample_sizes = dict()
def create_toggle_buttons(**kwargs): """ Initialize a ToggleButtons widget, in such a way that its buttons are sized proportionally to the text content, when possible. Parameters: ----------- **kwargs: keyword arguments Arguments to be passed to the ToggleButtons constructor """ t = widgets.ToggleButtons(**kwargs) # Set the style attribute of the widgets, so that buttons # automatically adapt to the size of their content if ipywidgets_version >= 7: t.style.button_width = 'initial' return (t)
def FormTypeSelect(ann): """ Form type edit widget """ form_types = ann.form_schema.types tp = ann.info['forms'][ann.index] type_select = widgets.ToggleButtons( options=list(form_types.keys()), value=ann.form_schema.types_inv[tp], padding=4, description='form type:', ) def on_change(name, value): ann.info['forms'][ann.index] = form_types[value] type_select.on_trait_change(on_change, 'value') return type_select
def __init__(self, on_interact=None, output=None, overwrite_previous_output=True, feedback=False, run=True, action_kws={}, *args, **kwargs): super().__init__(on_interact=on_interact, output=output, overwrite_previous_output=overwrite_previous_output, feedback=feedback, action_kws=action_kws) self.widget = widgets.ToggleButtons(*args, **kwargs) if run: self.run()
def readDB(self): task_names = [] task_name_id = dict() with self.workflow.dao.create_session() as session: records = session.query(Task) for record in records: task_names.append(record.TASK_NAME) task_name_id[record.TASK_NAME] = record.ID self.task_list = widgets.ToggleButtons( options=task_names, description='', disabled=False, value=None if len(task_names) == 0 else task_names[0], button_style='', # 'success', 'info', 'warning', 'danger' or '' layout=widgets.Layout(width='70%') # icons=['check'] * 3 ) self.updateBox() pass
def __init__(self, to_code, categories): ''' Creates an instance of codingTool keyword arguments: to_code -- An iterable object (e.g. list) with elements to code categories -- An iterable object with coding categories ''' self.coded = dict() self.to_code = list(to_code) self.at_item = 0 self.categories = list(categories) self.options = widgets.ToggleButtons( options= self.categories, value = None, description= '', disabled=False, button_style='', tooltips=['Description of slow', 'Description of regular', 'Description of fast'] ) self.options.layout.align_self = 'center' self.item = widgets.Label(value = self.to_code[0]) self.item.layout.align_self = 'center' self.next = widgets.Button(description = 'Next') self.next.on_click(self.next_clicked) self.previous = widgets.Button(description = 'Previous') self.previous.on_click(self.previous_clicked) self.stop = widgets.Button(description = 'Stop coding') self.stop.on_click(self.stop_clicked) bottom_rule = widgets.HBox([self.previous,self.next,self.stop]) bottom_rule.layout.justify_content = 'space-between' self.tool = widgets.VBox([self.item,self.options,bottom_rule]) self.tool.layout.justify_content = 'space-around'
def ToggleButtons(question, options=['Slow', 'Regular', 'Fast']): start_time = time.time() widget = widgets.ToggleButtons( options=options, description='Speed:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Description of slow', 'Description of regular', 'Description of fast' ], # icons=['check'] * 3 ) display(widget) def on_value_change(change): # Appends to the dictionary answer Answer_Dict[question].append(change["new"]) widget.observe(on_value_change, names='value') button(question, start_time)
def run_widget(): roll = widgets.ToggleButtons( options=['Keep All', 'Drop Lowest Roll'], value='Drop Lowest Roll', description='Roll Modifications:', style={'description_width': 'initial'}, disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['', ''], ) drop_roll = widgets.IntSlider( value=1, min=0, max=3, step=1, description='If Dropping Rolls, How Many?:', style={'description_width': 'initial'}, layout=Layout(width='50%'), disabled=False, ) stat = widgets.ToggleButtons( options=['Keep All', 'Drop Lowest Stat', 'Replace Lowest Stat'], value='Drop Lowest Stat', description='Stat Modifications:', style={'description_width': 'initial'}, disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['', ''], ) drop_stat = widgets.IntSlider( value=1, min=0, max=3, step=1, description='If Dropping Stats, How Many?:', style={'description_width': 'initial'}, layout=Layout(width='50%'), disabled=False, ) replace_stat = widgets.IntSlider( value=18, min=1, max=20, step=1, description='If Replacing Lowest Stat, With What?:', style={'description_width': 'initial'}, layout=Layout(width='50%'), disabled=False, ) name = widgets.Textarea( value='Roll 1d12 + 2d6 Drop Lowest Roll x 7 Drop Lowest Stat', placeholder='Type something', description='Name of Variant:', disabled=False, style={ 'description_width': 'initial', 'width': '10%' }, layout=Layout(width='50%')) n = widgets.Textarea(value='1\n2', placeholder='Type something', description='Number of each Dice', disabled=False, style={'description_width': 'initial'}, layout=Layout(width='50%', height='100px')) s = widgets.Textarea(value='1,2,3,4,5,6,7,8,9,10,11,12\n1,2,3,4,5,6', placeholder='Type something', description='Sides of each Dice ', disabled=False, style={ 'description_width': 'initial', 'width': '10%' }, layout=Layout(width='50%', height='100px')) interact_manual(runRoller, name=name, n=n, s=s, roll=roll, drop_roll=drop_roll, stat=stat, drop_stat=drop_stat, replace_stat=replace_stat)
def InteractiveDipoleBH( self, nRx=20, npts2D=50, scale="log", offset_plane=50.0, X1=-20, X2=80, Y1=-50, Y2=50, Z1=-50, Z2=50, plane="YZ", SrcType="ED", fieldvalue="E", compvalue="z", ): # x1, x2, y1, y2 = offset_rx, offset_rx, Z1, Z2 self.xmin, self.xmax = X1, X2 self.ymin, self.ymax = Y1, Y2 self.zmin, self.zmax = Z1, Z2 def foo( Field, AmpDir, Component, Time, Sigma, Offset, Scale, Slider, TimeLog, SigLog, SrcType=SrcType, ): if Slider is True: t = np.r_[10**TimeLog] sig = np.r_[10**SigLog] else: t = np.r_[Time] sig = np.r_[Sigma] if plane == "XZ": normal = "Y" self.offset_rx = 50.0 elif plane == "YZ": normal = "X" self.offset_rx = 0.0 x1, x2, y1, y2 = self.offset_rx, self.offset_rx, Z1, Z2 if AmpDir == "Direction": Component = "vec" elif AmpDir == "Amp": Component = "amp" if SrcType == "ED": Field = Field + "_from_ED" elif SrcType == "MD": Field = Field + "_from_MD" return self.Dipole2Dviz( x1, y1, x2, y2, npts2D, nRx, sig, t, srcLoc=np.r_[0.0, 0.0, 0.0], orientation="z", view=Component, normal=normal, functype=Field, loc=Offset, scale=Scale, ) out = widgetify( foo, Field=widgets.ToggleButtons(options=["E", "H", "dHdt", "J"], value=fieldvalue), AmpDir=widgets.ToggleButtons(options=["None", "Amp", "Direction"], value="Direction"), Component=widgets.ToggleButtons(options=["x", "y", "z"], value=compvalue, description="Comp."), Time=widgets.FloatText(value=1e-7, continuous_update=False, description="t (sec)"), Sigma=widgets.FloatText(value=0.01, continuous_update=False, description="$\sigma$ (S/m)"), Offset=widgets.FloatText(value=offset_plane, continuous_update=False), Scale=widgets.ToggleButtons(options=["log", "linear"], value="log"), Slider=widgets.widget_bool.Checkbox(value=False), TimeLog=widgets.FloatSlider(min=-7, max=0, step=0.2, value=-7, continuous_update=False), SigLog=widgets.FloatSlider(min=-3, max=3, step=0.5, value=-2, continuous_update=False), SrcType=fixed(SrcType), ) return out
def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=None, shots=1024,mode='circle',verbose=False): """ initialize List of gates applied to the initial 00 state to get the starting state of the puzzle. Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'. Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit. success_condition Values for pauli observables that must be obtained for the puzzle to declare success. allowed_gates For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch'). Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times. vi Some visualization information as a three element list. These specify: * which qubits are hidden (empty list if both shown). * whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). * whether the correlation circles (the four in the middle) are shown. qubit_names The two qubits are always called '0' and '1' from the programming side. But for the player, we can display different names. eps=0.1 How close the expectation values need to be to the targets for success to be declared. backend=Aer.get_backend('aer_simulator') Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle'), or the extended one (mode='y') or the alternative line based one (mode='line'). y_boxes = False Whether to show expectation values involving y. verbose=False """ def get_total_gate_list(): # Get a text block describing allowed gates. total_gate_list = "" for qubit in allowed_gates: gate_list = "" for gate in allowed_gates[qubit]: if required_gates[qubit][gate] > 0 : gate_list += ' ' + gate+" (use "+str(required_gates[qubit][gate])+" time"+"s"*(required_gates[qubit][gate]>1)+")" elif allowed_gates[qubit][gate]==0: gate_list += ' '+gate + ' ' if gate_list!="": if qubit=="both" : gate_list = "\nAllowed symmetric operations:" + gate_list else : gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list total_gate_list += gate_list +"\n" return total_gate_list def get_success(required_gates): # Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used. success = True grid.get_rho() if verbose: print(grid.rho) for pauli in success_condition: success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps) for qubit in required_gates: for gate in required_gates[qubit]: success = success and (required_gates[qubit][gate]==0) return success def show_circuit(): gates = get_total_gate_list def get_command(gate,qubit): # For a given gate and qubit, return the string describing the corresoinding Qiskit string. if qubit=='both': qubit = '1' qubit_name = qubit_names[qubit] for name in qubit_names.values(): if name!=qubit_name: other_name = name # then make the command (both for the grid, and for printing to screen) if gate in ['x','y','z','h']: real_command = 'grid.qc.'+gate+'(grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+qubit_name+')' elif gate in ['ry(pi/4)','ry(-pi/4)']: real_command = 'grid.qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])' clean_command = 'qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,'+qubit_name+')' elif gate in ['rx(pi/4)','rx(-pi/4)']: real_command = 'grid.qc.rx('+'-'*(gate=='rx(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])' clean_command = 'qc.rx('+'-'*(gate=='rx(-pi/4)')+'np.pi/4,'+qubit_name+')' elif gate in ['cz','cx','swap']: real_command = 'grid.qc.'+gate+'(grid.qr['+'0'*(qubit=='1')+'1'*(qubit=='0')+'],grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+other_name+','+qubit_name+')' return [real_command,clean_command] bloch = [None] # set up initial state and figure if mode=='y': grid = pauli_grid(backend=backend,shots=shots,mode='circle',y_boxes=True) else: grid = pauli_grid(backend=backend,shots=shots,mode=mode) for gate in initialize: eval( get_command(gate[0],gate[1])[0] ) required_gates = copy.deepcopy(allowed_gates) # determine which qubits to show in figure if allowed_gates['0']=={} : # if no gates are allowed for qubit 0, we know to only show qubit 1 shown_qubit = 1 elif allowed_gates['1']=={} : # and vice versa shown_qubit = 0 else : shown_qubit = 2 # show figure grid_view = _img() grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list(),output=grid_view) display(grid_view.widget) description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']} all_allowed_gates_raw = [] for q in ['0','1','both']: all_allowed_gates_raw += list(allowed_gates[q]) all_allowed_gates_raw = list(set(all_allowed_gates_raw)) all_allowed_gates = [] for g in ['bloch','unbloch']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in ['x','y','z','h','cz','cx']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in all_allowed_gates_raw: if g not in all_allowed_gates: all_allowed_gates.append( g ) gate = widgets.ToggleButtons(options=description['gate']+all_allowed_gates) qubit = widgets.ToggleButtons(options=['']) action = widgets.ToggleButtons(options=['']) boxes = widgets.VBox([gate,qubit,action]) display(boxes) self.program = [] def given_gate(a): # Action to be taken when gate is chosen. This sets up the system to choose a qubit. if gate.value: if gate.value in allowed_gates['both']: qubit.options = description['qubit'] + ["not required"] qubit.value = "not required" else: allowed_qubits = [] for q in ['0','1']: if (gate.value in allowed_gates[q]) or (gate.value in allowed_gates['both']): allowed_qubits.append(q) allowed_qubit_names = [] for q in allowed_qubits: allowed_qubit_names += [qubit_names[q]] qubit.options = description['qubit'] + allowed_qubit_names def given_qubit(b): # Action to be taken when qubit is chosen. This sets up the system to choose an action. if qubit.value not in ['',description['qubit'][0],'Success!']: action.options = description['action']+['Apply operation'] def given_action(c): # Action to be taken when user confirms their choice of gate and qubit. # This applied the command, updates the visualization and checks whether the puzzle is solved. if action.value not in ['',description['action'][0]]: # apply operation if action.value=='Apply operation': if qubit.value not in ['',description['qubit'][0],'Success!']: # translate bit gates to qubit gates if gate.value=='NOT': q_gate = 'x' elif gate.value=='CNOT': q_gate = 'cx' else: q_gate = gate.value if qubit.value=="not required": q = qubit_names['1'] else: q = qubit.value q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required") if q_gate in ['bloch','unbloch']: if q_gate=='bloch': bloch[0] = q01 else: bloch[0] = None else: command = get_command(q_gate,q01) eval(command[0]) self.program.append( command[1] ) if required_gates[q01][gate.value]>0: required_gates[q01][gate.value] -= 1 grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list(),output=grid_view) success = get_success(required_gates) if success: gate.options = ['Success!'] qubit.options = ['Success!'] action.options = ['Success!'] plt.close(grid.fig) else: gate.value = description['gate'][0] qubit.options = [''] action.options = [''] gate.observe(given_gate) qubit.observe(given_qubit) action.observe(given_action)
return para["fo_grd_dir"] = fo_grd_dir_dict[model_name][value_type][ model_level] para["max_dh"] = max_dh para["update_hours"] = model_update_hours_dict[model_name] para["id"] = [id_lon_lat_dict[station_id][0]] para["lon"] = [id_lon_lat_dict[station_id][1]] para["lat"] = [id_lon_lat_dict[station_id][2]] para[ "title"] = model_name + "_" + model_level + "_" + value_type + "_" + "观测" + ob_element + "(" + station_id + ")" meteva.nmc_vf_product.gds_ob_multi_time_fo(para) tb_ob_element = widgets.ToggleButtons( options=value_type_dict.keys(), description='观测要素:', disabled=False, ) tb_model_name = widgets.ToggleButtons( options=fo_grd_dir_dict.keys(), description='模式:', disabled=False, ) tb_model_level = widgets.ToggleButtons( options=['850hPa', '800hPa', '700hPa', "10M", "2M"], description='模式层次:', disabled=False, ) tb_station_id = widgets.ToggleButtons( options=id_lon_lat_dict.keys(),
dd['λ'] = wdg.IntRangeSlider(value=(xlim[0], xlim[1]), min=xlim[0], max=xlim[1], step=5, description='λ', continuous_update=False) dd['pts'] = wdg.IntSlider(value=50000, min=10, max=100000, step=100, description='Points:', continuous_update=False) dd['pts'].add_class("osa_wavelength") dd['scan'] = wdg.ToggleButtons(options=['Single', 'Repeat', 'Stop'], value='Stop', description='Scan:', disabled=False, button_style='info') dd['scan'].add_class("osa_scan_button") dd['trace'] = wdg.Dropdown( options=['Trace A', 'Trace B', 'Trace C', 'Trace D'], value='Trace A', description='Trace:') dd['res'] = wdg.Dropdown( options=['Norm/Hold', 'Norm/Auto', 'Mid', 'High 1', 'High 2', 'High 3'], description='Resolution:') Bdwt_val = { 0.02: '0.02 nm',
def slider(self, figsize=(10, 10), **kw): """ Navigate the simulation using a slider Parameters : ------------ figsize: tuple Size of the figures kw: dict Extra arguments to pass to matplotlib's imshow """ # ----------------------- # Define useful functions # ----------------------- def refresh_field(force=False): "Refresh the current field figure" # Determine whether to do the refresh do_refresh = False if (self.avail_fields is not None): if force == True or fld_refresh_toggle.value == True: do_refresh = True # Do the refresh if do_refresh == True: plt.figure(fld_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if fld_use_button.value == True: i_power = fld_magnitude_button.value vmin = fld_range_button.value[0] * 10**i_power vmax = fld_range_button.value[1] * 10**i_power else: vmin = None vmax = None self.get_field(t=self.current_t, output=False, plot=True, field=fieldtype_button.value, coord=coord_button.value, m=convert_to_int(mode_button.value), slicing=slicing_button.value, theta=theta_button.value, slicing_dir=slicing_dir_button.value, vmin=vmin, vmax=vmax, cmap=fld_color_button.value) def refresh_ptcl(force=False): "Refresh the current particle figure" # Determine whether to do the refresh do_refresh = False if self.avail_species is not None: if force == True or ptcl_refresh_toggle.value == True: do_refresh = True # Do the refresh if do_refresh == True: plt.figure(ptcl_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if ptcl_use_button.value == True: i_power = ptcl_magnitude_button.value vmin = ptcl_range_button.value[0] * 10**i_power vmax = ptcl_range_button.value[1] * 10**i_power else: vmin = None vmax = None if ptcl_yaxis_button.value == 'None': # 1D histogram self.get_particle(t=self.current_t, output=False, var_list=[ptcl_xaxis_button.value], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value) else: # 2D histogram self.get_particle(t=self.current_t, output=False, var_list=[ ptcl_xaxis_button.value, ptcl_yaxis_button.value ], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value) def refresh_ptcl_now(b): "Refresh the particles immediately" refresh_ptcl(force=True) def refresh_fld_now(b): "Refresh the fields immediately" refresh_field(force=True) def change_t(name, value): "Plot the result at the required time" self.current_t = 1.e-15 * value refresh_field() refresh_ptcl() def step_fw(b): "Plot the result one iteration further" if self.current_i < len(self.t) - 1: self.current_t = self.t[self.current_i + 1] else: print("Reached last iteration.") self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 def step_bw(b): "Plot the result one iteration before" if self.current_t > 0: self.current_t = self.t[self.current_i - 1] else: print("Reached first iteration.") self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 # --------------- # Define widgets # --------------- # Slider slider = widgets.FloatSlider( min=math.ceil(1.e15 * self.tmin), max=math.ceil(1.e15 * self.tmax), step=math.ceil(1.e15 * (self.tmax - self.tmin)) / 20., description="t (fs)") slider.on_trait_change(change_t, 'value') # Forward button button_p = widgets.Button(description="+") button_p.on_click(step_fw) # Backward button button_m = widgets.Button(description="-") button_m.on_click(step_bw) # Display the time widgets container = widgets.HBox(children=[button_m, button_p, slider]) display(container) # Field widgets # ------------- if (self.avail_fields is not None): # Field type # ---------- # Field button fieldtype_button = widgets.ToggleButtons( description='Field:', options=sorted(self.avail_fields.keys())) fieldtype_button.on_trait_change(refresh_field) # Coord button if self.geometry == "thetaMode": coord_button = widgets.ToggleButtons( description='Coord:', options=['x', 'y', 'z', 'r', 't']) elif self.geometry in ["2dcartesian", "3dcartesian"]: coord_button = widgets.ToggleButtons(description='Coord:', options=['x', 'y', 'z']) coord_button.on_trait_change(refresh_field) # Mode and theta button (for thetaMode) mode_button = widgets.ToggleButtons(description='Mode:', options=self.avail_circ_modes) mode_button.on_trait_change(refresh_field) theta_button = widgets.FloatSlider(width=140, value=0., description=r'Theta:', min=-math.pi / 2, max=math.pi / 2) theta_button.on_trait_change(refresh_field) # Slicing buttons (for 3D) slicing_dir_button = widgets.ToggleButtons( value='y', description='Slicing direction:', options=['x', 'y', 'z']) slicing_dir_button.on_trait_change(refresh_field) slicing_button = widgets.FloatSlider(width=150, description='Slicing:', min=-1., max=1., value=0.) slicing_button.on_trait_change(refresh_field) # Plotting options # ---------------- # Figure number fld_figure_button = widgets.IntText(description='Figure ', value=0, width=50) # Range of values fld_range_button = widgets.FloatRangeSlider(min=-10, max=10, width=220) fld_range_button.on_trait_change(refresh_field) # Order of magnitude fld_magnitude_button = widgets.IntText(description='x 10^', value=9, width=50) fld_magnitude_button.on_trait_change(refresh_field) # Use button fld_use_button = widgets.Checkbox(description=' Use this range', value=False) fld_use_button.on_trait_change(refresh_field) # Colormap button fld_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), height=50, width=200, value='jet') fld_color_button.on_trait_change(refresh_field) # Resfresh buttons fld_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) fld_refresh_button = widgets.Button(description='Refresh now!') fld_refresh_button.on_click(refresh_fld_now) # Containers # ---------- # Field type container if self.geometry == "thetaMode": container_fields = widgets.VBox(width=260, children=[ fieldtype_button, coord_button, mode_button, theta_button ]) elif self.geometry == "2dcartesian": container_fields = widgets.VBox( width=260, children=[fieldtype_button, coord_button]) elif self.geometry == "3dcartesian": container_fields = widgets.VBox(width=260, children=[ fieldtype_button, coord_button, slicing_dir_button, slicing_button ]) # Plotting options container container_fld_plots = widgets.VBox(width=260, children=[ fld_figure_button, fld_range_button, widgets.HBox(children=[ fld_magnitude_button, fld_use_button ], height=50), fld_color_button ]) # Accordion for the field widgets accord1 = widgets.Accordion( children=[container_fields, container_fld_plots]) accord1.set_title(0, 'Field type') accord1.set_title(1, 'Plotting options') # Complete field container container_fld = widgets.VBox( width=300, children=[ accord1, widgets.HBox( children=[fld_refresh_toggle, fld_refresh_button]) ]) # Particle widgets # ---------------- if (self.avail_species is not None): # Particle quantities # ------------------- # Species selection ptcl_species_button = widgets.Dropdown(width=250, options=self.avail_species) ptcl_species_button.on_trait_change(refresh_ptcl) # Remove charge and mass (less interesting) avail_ptcl_quantities = [ q for q in self.avail_ptcl_quantities \ if (q in ['charge', 'mass'])==False ] # Particle quantity on the x axis ptcl_xaxis_button = widgets.ToggleButtons( value='z', options=avail_ptcl_quantities) ptcl_xaxis_button.on_trait_change(refresh_ptcl) # Particle quantity on the y axis ptcl_yaxis_button = widgets.ToggleButtons( value='x', options=avail_ptcl_quantities + ['None']) ptcl_yaxis_button.on_trait_change(refresh_ptcl) # Particle selection # ------------------ # 3 selection rules at maximum ptcl_select_widget = ParticleSelectWidget(3, avail_ptcl_quantities, refresh_ptcl) # Plotting options # ---------------- # Figure number ptcl_figure_button = widgets.IntText(description='Figure ', value=1, width=50) # Number of bins ptcl_bins_button = widgets.IntSlider(description='nbins:', min=50, max=300, value=100, width=150) ptcl_bins_button.on_trait_change(refresh_ptcl) # Colormap button ptcl_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), height=50, width=200, value='Blues') ptcl_color_button.on_trait_change(refresh_ptcl) # Range of values ptcl_range_button = widgets.FloatRangeSlider(min=0, max=10, width=220, value=(0, 5)) ptcl_range_button.on_trait_change(refresh_ptcl) # Order of magnitude ptcl_magnitude_button = widgets.IntText(description='x 10^', value=9, width=50) ptcl_magnitude_button.on_trait_change(refresh_ptcl) # Use button ptcl_use_button = widgets.Checkbox(description=' Use this range', value=False) ptcl_use_button.on_trait_change(refresh_ptcl) # Resfresh buttons ptcl_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) ptcl_refresh_button = widgets.Button(description='Refresh now!') ptcl_refresh_button.on_click(refresh_ptcl_now) # Containers # ---------- # Particle quantity container container_ptcl_quantities = widgets.VBox(width=310, children=[ ptcl_species_button, ptcl_xaxis_button, ptcl_yaxis_button ]) # Particle selection container container_ptcl_select = ptcl_select_widget.to_container() # Plotting options container container_ptcl_plots = widgets.VBox(width=310, children=[ ptcl_figure_button, ptcl_bins_button, ptcl_range_button, widgets.HBox(children=[ ptcl_magnitude_button, ptcl_use_button ], height=50), ptcl_color_button ]) # Accordion for the field widgets accord2 = widgets.Accordion(children=[ container_ptcl_quantities, container_ptcl_select, container_ptcl_plots ]) accord2.set_title(0, 'Particle quantities') accord2.set_title(1, 'Particle selection') accord2.set_title(2, 'Plotting options') # Complete particle container container_ptcl = widgets.VBox( width=370, children=[ accord2, widgets.HBox( children=[ptcl_refresh_toggle, ptcl_refresh_button]) ]) # Global container if (self.avail_fields is not None) and \ (self.avail_species is not None): global_container = widgets.HBox( children=[container_fld, container_ptcl]) display(global_container) elif self.avail_species is None: display(container_fld) elif self.avail_fields is None: display(container_ptcl)
def InteractiveData_Sphere(self, fieldvalue="B", compvalue="z", z=0.0): frequency = np.logspace(2, 5, 31) self.simulate(self.srcLoc, self.rxLoc, frequency) def foo(Field, Component, Scale): # Printout for null cases if (Field == "B") & (Component == "y") | (Field == "Bsec") & ( Component == "y"): print( "Think about the problem geometry. There is NO By in this case." ) elif (Field == "E") & (Component == "x") | (Field == "E") & ( Component == "z"): print( "Think about the problem geometry. There is NO Ex or Ez in this case. Only Ey." ) else: plt.figure() ax = plt.subplot(111) bType = "b" if (Field == "Bsec") or (Field == "B"): if Field == "Bsec": bType = "bSecondary" Field = "B" self.getData(bType=bType) label = "Magnetic field (T)" if Component == "x": title = "Bx" valr = self.Bx.real vali = self.Bx.imag elif Component == "z": title = "Bz" valr = self.Bz.real vali = self.Bz.imag else: # ax.imshow(self.im) ax.set_xticks([]) ax.set_yticks([]) print( "Think about the problem geometry. There is NO By in this case." ) elif Field == "E": self.getData(bType=bType) label = "Electric field (V/m)" title = "Ey" if Component == "y": valr = self.Ey.real vali = self.Ey.imag else: # ax.imshow(self.im) ax.set_xticks([]) ax.set_yticks([]) print( "Think about the problem geometry. There is NO Ex or Ez in this case." ) elif Field == "J": print( "The conductivity at the location is 0. Therefore there is no electrical current here." ) if Scale == "log": valr_p, valr_n = DisPosNegvalues(valr) vali_p, vali_n = DisPosNegvalues(vali) ax.plot(frequency, valr_p, "k-") ax.plot(frequency, valr_n, "k--") ax.plot(frequency, vali_p, "r-") ax.plot(frequency, vali_n, "r--") ax.legend(("Re (+)", "Re (-)", "Im (+)", "Im (-)"), loc=4, fontsize=10) else: ax.plot(frequency, valr, "k.-") ax.plot(frequency, vali, "r.-") ax.legend(("Re", "Im"), loc=4, fontsize=10) ax.set_xscale("log") ax.set_yscale(Scale) ax.set_xlabel("Frequency (Hz)") ax.set_ylabel(label) ax.set_title(title) ax.grid(True) plt.show() out = widgetify( foo, Field=widgets.ToggleButtons(options=["E", "B", "Bsec"], value=fieldvalue), Component=widgets.ToggleButtons(options=["x", "y", "z"], value=compvalue, description="Comp."), Scale=widgets.ToggleButtons(options=["log", "linear"], value="log"), ) return out
def InteractivePlane_Sphere(self, scale="log", fieldvalue="B", compvalue="z"): def foo( Field, AmpDir, Component, ComplexNumber, Sigma0, Sigmab, Sigma1, Sigma2, Sus, d1, h, d2, R, Scale, rxOffset, z, ifreq, Geometry=True, ): Frequency = 10**((ifreq - 1.0) / 3.0 - 2.0) if ComplexNumber == "Re": ComplexNumber = "real" elif ComplexNumber == "Im": ComplexNumber = "imag" elif ComplexNumber == "Amp": ComplexNumber = "amplitude" elif ComplexNumber == "Phase": ComplexNumber = "phase" if AmpDir == "Direction (B or Bsec)": # ComplexNumber = "real" Component = "vec" if Field == "Bsec": bType = "bSecondary" Field = "B" else: bType = "b" self.setLayerSphereParam( d1=d1, h=h, d2=d2, R=R, sig0=Sigma0, sigb=Sigmab, sig1=Sigma1, sig2=Sigma2, chi=Sus, ) srcLoc = np.array([0.0, 0.0, z]) rxLoc = np.array([[rxOffset, 0.0, z]]) self.simulate(srcLoc, rxLoc, np.r_[Frequency]) if Field != "Model": self.getFields(bType=bType) return self.plotField( Field=Field, ComplexNumber=ComplexNumber, Frequency=Frequency, view=Component, scale=Scale, Geometry=Geometry, Scenario="Sphere", ) out = widgetify( foo, Field=widgets.ToggleButtons( options=["E", "B", "Bsec", "J", "Model"], value="E"), AmpDir=widgets.ToggleButtons( options=["None", "Direction (B or Bsec)"], value="None"), Component=widgets.ToggleButtons(options=["x", "y", "z"], value="y", description="Comp."), ComplexNumber=widgets.ToggleButtons( options=["Re", "Im", "Amp", "Phase"], value="Re", description="Re/Im"), Sigma0=widgets.FloatText(value=1e-8, continuous_update=False, description="$\sigma_0$ (S/m)"), Sigmab=widgets.FloatText(value=0.01, continuous_update=False, description="$\sigma_b$ (S/m)"), Sigma1=widgets.FloatText(value=0.01, continuous_update=False, description="$\sigma_1$ (S/m)"), Sigma2=widgets.FloatText(value=0.01, continuous_update=False, description="$\sigma_2$ (S/m)"), Sus=widgets.FloatText(value=0.0, continuous_update=False, description="$\chi$"), d1=widgets.FloatSlider( min=0.0, max=50.0, step=2.0, value=0.0, continuous_update=False, description="$d_1$ (m)", ), h=widgets.FloatSlider( min=2.0, max=20.0, step=2.0, value=10.0, continuous_update=False, description="$h$ (m)", ), d2=widgets.FloatSlider( min=10.0, max=50.0, step=2.0, value=30.0, continuous_update=False, description="$d_2$ (m)", ), R=widgets.FloatSlider( min=2.0, max=20.0, step=2.0, value=10.0, continuous_update=False, description="$R$ (m)", ), Scale=widgets.ToggleButtons(options=["log", "linear"], value="linear"), rxOffset=widgets.FloatSlider( min=0.0, max=50.0, step=2.0, value=10.0, continuous_update=False, description="$\Delta x$(m)", ), z=widgets.FloatSlider( min=0.0, max=50.0, step=2.0, value=0.0, continuous_update=False, description="$\Delta z$ (m)", ), ifreq=widgets.IntSlider( min=1, max=31, step=1, value=16, continuous_update=False, description="f index", ), ) return out
def InteractiveDipoleProfileTD(self, Sigma, Field, compvalue, Scale): srcLoc = np.r_[0.0, 0.0, 0.0] # orientation = "z" nRx = 100 # def foo(Component, Profile, Scale, F1, F2, F3): def foo(Component, Profile, Sigma, T1, T2, T3, Scale, irx): # Scale = "log" orientation = "z" vals = [] if Field == "E": unit = " (V/m)" elif Field == "H": unit = " (A/m)" elif Field == "dHdt": unit = " (A/m-s)" elif Field == "J": unit = " (A/m $^2$)" labelr = Field + Component + "-field " + unit T = [T1, T2, T3] if Component == "x": icomp = 0 elif Component == "y": icomp = 1 elif Component == "z": icomp = 2 if Profile == "TxProfile": xyz_line = np.c_[np.linspace(-20.0, 80.0, nRx), np.zeros(nRx), np.zeros(nRx)] r = xyz_line[:, 0] plt.figure(figsize=(18 * 1.5, 3.4 * 1.5)) gs1 = gridspec.GridSpec(2, 7) gs1.update(left=0.05, right=0.48, wspace=0.05) ax1 = plt.subplot(gs1[:2, :3]) else: if Profile == "Rxhole": xyz_line = self.dataview.xyz_line.copy() elif Profile == "Txhole": xyz_line = self.dataview.xyz_line.copy() xyz_line[:, 0] = 0.0 else: raise NotImplementedError() r = xyz_line[:, 2] plt.figure(figsize=(18 * 1.0, 3.4 * 1.5)) gs1 = gridspec.GridSpec(2, 7) gs1.update(left=0.05, right=0.48, wspace=0.05) ax1 = plt.subplot(gs1[:2, :3]) for ifreq, t in enumerate(T): vals.append( self.dataview.eval_TD( xyz_line, srcLoc, np.r_[Sigma], np.r_[t], orientation, self.dataview.func2D, )) # for ifreq, f in enumerate(F): valr = vals[ifreq][icomp] if Scale == "log": valr_p, valr_n = DisPosNegvalues(valr) if Profile == "Rxhole" or Profile == "Txhole": ax1.plot(valr_p, r, "k-") ax1.plot(valr_n, r, "k--") ax1.plot(abs(valr)[irx], r[irx], "ro") ax1.plot(abs(valr), r, "k.", ms=2) elif Profile == "TxProfile": ax1.plot(r, valr_p, "k-") ax1.plot(r, valr_n, "k--") ax1.plot(r[irx], abs(valr)[irx], "ro") ax1.plot(r, abs(valr), "k.", ms=2) elif Scale == "linear": if Profile == "Rxhole" or Profile == "Txhole": ax1.plot(valr, r, "k-") ax1.plot(abs(valr)[irx], r[irx], "ro") ax1.plot(abs(valr), r, "k.", ms=2) elif Profile == "TxProfile": ax1.plot(r, valr, "k-") ax1.plot(r[irx], abs(valr)[irx], "ro") ax1.plot(r, abs(valr), "k.", ms=2) if Profile == "Rxhole" or Profile == "Txhole": ax1.set_xscale(Scale) ax1.set_ylim(-50, 50) ax1.set_xlabel(labelr, color="k") ax1.set_ylabel("Z (m)") elif Profile == "TxProfile": ax1.set_yscale(Scale) ax1.set_xlim(-20, 80) ax1.set_ylabel(labelr, color="k") ax1.set_xlabel("X (m)") if Scale == "linear": if Profile == "Rxhole" or Profile == "Txhole": # xticksa = np.linspace(valr.min(), valr.max(), 3) x = ax1.xaxis.get_majorticklocs() xticksa = np.linspace(x.min(), x.max(), 3) ax1.xaxis.set_ticks(xticksa) ax1.xaxis.set_major_formatter( ticker.FormatStrFormatter("%.0e")) elif Profile == "TxProfile": # yticksa = np.linspace(valr.min(), valr.max(), 3) y = ax1.yaxis.get_majorticklocs() yticksa = np.linspace(y.min(), y.max(), 3) ax1.yaxis.set_ticks(yticksa) ax1.yaxis.set_major_formatter( ticker.FormatStrFormatter("%.0e")) ax1.grid(True) plt.show() Q2 = widgetify( foo, Profile=widgets.ToggleButtons( options=["Rxhole", "Txhole", "TxProfile"], value="Rxhole"), Component=widgets.ToggleButtons(options=["x", "y", "z"], value=compvalue, description="Comp."), Sigma=widgets.FloatText(value=Sigma, continuous_update=False, description="$\sigma$ (S/m)"), Scale=widgets.ToggleButtons(options=["log", "linear"], value=Scale), T1=widgets.FloatText(value=1e-5, continuous_update=False, description="$t_1$ (sec)"), T2=widgets.FloatText(value=1e-4, continuous_update=False, description="$t_2$ (sec)"), T3=widgets.FloatText(value=1e-3, continuous_update=False, description="$t_3$ (sec)"), irx=widgets.IntSlider( min=0, max=int(nRx), step=1, value=0, continuous_update=False, description="Rx#", ), ) return Q2