def confusion_matrix(truths, predictions, sampling_rate=1): from IPython.html.widgets import interact, fixed assert len(truths) == len(predictions) if sampling_rate < 1: n = len(truths) indices = random.sample(range(n), int(n * sampling_rate)) truths = [truths[i] for i in indices] predictions = [predictions[i] for i in indices] interact(_show_confusion_matrix, threshold=(0.0, 1.0, 0.01), truths=fixed(truths), predictions=fixed(predictions))
def InteractNosiy(noisyDataFile, noisyTimeFile): noisy = interactive(NoisyNMOWidget, t0=FloatSlider(min=0.1, max=0.6, step=0.01, continuous_update=False), v=FloatSlider(min=800., max=2500., step=100., continuous_update=False), syndat=fixed(noisyDataFile), timdat=fixed(noisyTimeFile)) return noisy
def InteractClean(cleanDataFile, cleanTimeFile): clean = interactive(CleanNMOWidget, t0=FloatSlider(min=0.2, max=0.8, step=0.01, continuous_update=False), v=FloatSlider(min=1000., max=5000., step=100., continuous_update=False), syndat=fixed(cleanDataFile), timdat=fixed(cleanTimeFile)) return clean
def paramsFromFile(filter1, filter2, filter3, filename): params, filters_dict = readCSV(filter1, filter2, filter3, filename) plotParams = dict( z=FloatSliderWidget(min=0.15, max=2, step=0.01, value=params['z']), x0=FloatSliderWidget(min=0, max=1e-5, step=0.1*1e-5, value=params['x0']), x1=FloatSliderWidget(min=-3, max=2, step=0.1, value=params['x1']), c=FloatSliderWidget(min=-0.4, max=0.4, step=0.01, value=params['c']), hostebv_cc=FloatSliderWidget(min=-0.1, max=0.65, step=0.1, value=0), phase=FloatSliderWidget(min=-50, max=150, step=1, value=0), dates=fixed([filters_dict[filter1]['time'], filters_dict[filter2]['time'], filters_dict[filter3]['time']]), filters=fixed([filter1, filter2, filter3]), data_flux_filter1=fixed(filters_dict[filter1]['flux']), data_flux_filter1_err=fixed(filters_dict[filter1]['flux_error']), data_flux_filter2=fixed(filters_dict[filter2]['flux']), data_flux_filter2_err=fixed(filters_dict[filter2]['flux_error']), data_flux_filter3=fixed(filters_dict[filter3]['flux']), data_flux_filter3_err=fixed(filters_dict[filter3]['flux_error'])) return plotParams
def interactA(): widH = widgets.IntSliderWidget(min=0,max=1000,step=1,value=100) widZ = widgets.IntSliderWidget(min=0,max=1000,step=1,value=1) wida = widgets.FloatSliderWidget(min=0.01,max=1,step=0.01,value=0.05) widb = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.3) widz = widgets.FloatSliderWidget(min=0.01,max=0.5,step=0.01,value=0.2) interact(graficaSolucionA,humanos=widH, zombies=widZ, muertos=fixed(0), a=wida, b=(0.1,1,0.05), z=(0.01,0.5,0.01));
def draw_2D_slice_notebook(self, p_vals, x_variable, y_variable, range_x, range_y, slider_ranges, image_container=None, **kwargs): plot_widget = interactive(make_2D_slice, ds=fixed(self), p_vals=fixed(p_vals), x_variable=fixed(x_variable), y_variable=fixed(y_variable), range_x=fixed(range_x), range_y=fixed(range_y), intersections={'Single':[1], 'Single and Triple':[1,3], 'Triple':[3], 'All':range(1, 100)}, highlight=Text(value=''), image_widget=fixed(image_container), **{i:FloatSlider(min=log10(slider_ranges[i][0]), max=log10(slider_ranges[i][1]), step=log10(slider_ranges[i][1]/slider_ranges[i][0])/20, value=log10(p_vals[i])) for i in slider_ranges } ) make_2D_slice(ds=self, p_vals=p_vals, x_variable=x_variable, y_variable=y_variable, range_x=range_x, range_y=range_y, intersections=range(1, 100), image_widget=image_container, highlight='') return plot_widget
def interact_with_plot_all_outputs(sa_dict, demo=False, manual=True): """ This function adds the ability to interactively adjust all of the plotting.make_plot() arguments. Parameters ---------- sa_dict : dict a dictionary with all the sensitivity analysis results. demo : bool, optional plot only few outcomes for demo purpose. Returns ------- Interactive widgets to control plot """ min_val_box = BoundedFloatText(value=0.01, min=0, max=1, description='Min value:') top_box = IntText(value=20, description='Show top:') stacks = Checkbox( description='Show stacked plots:', value=True, ) error_bars = Checkbox(description='Show error bars:', value=True) log_axis = Checkbox(description='Use log axis:', value=True) # get a list of all the parameter options key = sa_dict.keys()[0] param_options = list(sa_dict[key][0].Parameter.values) highlighted = SelectMultiple(description="Choose parameters to highlight", options=param_options, value=[]) return interact(plot_all_outputs, sa_dict=fixed(sa_dict), demo=fixed(demo), min_val=min_val_box, top=top_box, stacked=stacks, error_bars=error_bars, log_axis=log_axis, highlighted_parameters=highlighted, __manual=manual)
def test_fixed(): c = interactive(f, a=widgets.fixed(5), b='text') nt.assert_equal(len(c.children), 1) w = c.children[0] check_widget(w, cls=widgets.Text, value='text', description='b', )
def interactB(): widH = widgets.IntSliderWidget(min=0,max=1000,step=1,value=100) widZ = widgets.IntSliderWidget(min=0,max=1000,step=1,value=1) widI = widgets.IntSliderWidget(min=0,max=10,step=1,value=0) wida = widgets.FloatSliderWidget(min=0.01,max=1,step=0.01,value=0.05) widb = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.6) widz = widgets.FloatSliderWidget(min=0.01,max=0.5,step=0.01,value=0.2) widr = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.9) interact(solucionB,humanos=widH, infectados=widI, zombies=widZ, muertos=fixed(0), a=wida, b=widb, z=widz, r=widr);
def interactC(): widH = widgets.IntSliderWidget(min=0,max=1000,step=1,value=100) widZ = widgets.IntSliderWidget(min=0,max=1000,step=1,value=1) widI = widgets.IntSliderWidget(min=0,max=10,step=1,value=0) wida = widgets.FloatSliderWidget(min=0.01,max=1,step=0.01,value=0.05) widb = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.85) widz = widgets.FloatSliderWidget(min=0.01,max=0.5,step=0.01,value=0.09) widr = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.8) widk = widgets.FloatSliderWidget(min=0.1,max=1,step=0.1,value=0.3) wids = widgets.FloatSliderWidget(min=0.01,max=0.5,step=0.01,value=0.01) widg = widgets.FloatSliderWidget(min=0.1,max=1,step=0.1,value=0.6) interact(solucionC,humanos=widH, infectados=widI, zombies=widZ, muertos=fixed(0), cuarentena=fixed(0), a=wida, b=widb, z=widz, r=widr, k=widk, s=wids, g=widg);
def interact_with_plot_all_outputs(sa_dict, demo=False, manual=True): """ This function adds the ability to interactively adjust all of the plotting.make_plot() arguments. Parameters ---------- sa_dict : dict a dictionary with all the sensitivity analysis results. demo : bool, optional plot only few outcomes for demo purpose. Returns ------- Interactive widgets to control plot """ min_val_box = BoundedFloatText(value=0.01, min=0, max=1, description='Min value:') top_box = IntText(value=20, description='Show top:') stacks = Checkbox(description='Show stacked plots:', value=True,) error_bars = Checkbox(description='Show error bars:', value=True) log_axis = Checkbox(description='Use log axis:', value=True) # get a list of all the parameter options key = sa_dict.keys()[0] param_options = list(sa_dict[key][0].Parameter.values) highlighted = SelectMultiple(description="Choose parameters to highlight", options=param_options, value=[]) return interact(plot_all_outputs, sa_dict=fixed(sa_dict), demo = fixed(demo), min_val=min_val_box, top=top_box, stacked=stacks, error_bars=error_bars, log_axis=log_axis, highlighted_parameters=highlighted, __manual=manual )
def simulate(transitions, input='10101', unary=False, input_unary=12, pause=0.05, step_from=0, step_to=100, step_slack=100): """loads widget to simulate a given TM""" # widgets to specify the range of steps to simulate from_w = widgets.IntText(value=step_from, description="simulate from step") to_w = widgets.IntText(value=step_to, description="simulate to step") pause_w = widgets.FloatText(value=pause, description="pause between steps"); # widget to indicate current step steps_w = widgets.IntSlider(min=0, max=step_to + step_slack, value=0, description="current step") # subroutine to animate the simulation def animate(x): steps_w.max = to_w.value + step_slack for steps in range(from_w.value, to_w.value+1): steps_w.value = steps sleep(pause_w.value) # button to start animated simulation simulate_w = widgets.Button(description='simulate') simulate_w.on_click(animate) input_w = widgets.Text(value=input, description="input") unary_w = widgets.Checkbox(value=unary, description='unary?') input_unary_w = widgets.IntText(value=input_unary, description='input number') def update(): if unary_w.value: input_w.disabled = True input_unary_w.visible = True input_w.value = '1' * input_unary_w.value else: input_w.disabled = False input_unary_w.visible = False update() unary_w.on_trait_change(update) input_unary_w.on_trait_change(update) # display control widgets box = widgets.VBox(children=[simulate_w, from_w, to_w, pause_w, unary_w, input_unary_w]) display(box) # widgets to display simulation interact(display_wrap(run), transitions=fixed(transitions), input=input_w, steps=steps_w)
def interactA(): widH = widgets.IntSliderWidget(min=0, max=1000, step=1, value=100) widZ = widgets.IntSliderWidget(min=0, max=1000, step=1, value=1) wida = widgets.FloatSliderWidget(min=0.01, max=1, step=0.01, value=0.05) widb = widgets.FloatSliderWidget(min=0.1, max=1, step=0.05, value=0.3) widz = widgets.FloatSliderWidget(min=0.01, max=0.5, step=0.01, value=0.2) interact(graficaSolucionA, humanos=widH, zombies=widZ, muertos=fixed(0), a=wida, b=(0.1, 1, 0.05), z=(0.01, 0.5, 0.01))
def interactC(): widH = widgets.IntSliderWidget(min=0, max=1000, step=1, value=100) widZ = widgets.IntSliderWidget(min=0, max=1000, step=1, value=1) widI = widgets.IntSliderWidget(min=0, max=10, step=1, value=0) wida = widgets.FloatSliderWidget(min=0.01, max=1, step=0.01, value=0.05) widb = widgets.FloatSliderWidget(min=0.1, max=1, step=0.05, value=0.85) widz = widgets.FloatSliderWidget(min=0.01, max=0.5, step=0.01, value=0.09) widr = widgets.FloatSliderWidget(min=0.1, max=1, step=0.05, value=0.8) widk = widgets.FloatSliderWidget(min=0.1, max=1, step=0.1, value=0.3) wids = widgets.FloatSliderWidget(min=0.01, max=0.5, step=0.01, value=0.01) widg = widgets.FloatSliderWidget(min=0.1, max=1, step=0.1, value=0.6) interact(solucionC, humanos=widH, infectados=widI, zombies=widZ, muertos=fixed(0), cuarentena=fixed(0), a=wida, b=widb, z=widz, r=widr, k=widk, s=wids, g=widg)
def interactB(): widH = widgets.IntSliderWidget(min=0, max=1000, step=1, value=100) widZ = widgets.IntSliderWidget(min=0, max=1000, step=1, value=1) widI = widgets.IntSliderWidget(min=0, max=10, step=1, value=0) wida = widgets.FloatSliderWidget(min=0.01, max=1, step=0.01, value=0.05) widb = widgets.FloatSliderWidget(min=0.1, max=1, step=0.05, value=0.6) widz = widgets.FloatSliderWidget(min=0.01, max=0.5, step=0.01, value=0.2) widr = widgets.FloatSliderWidget(min=0.1, max=1, step=0.05, value=0.9) interact(solucionB, humanos=widH, infectados=widI, zombies=widZ, muertos=fixed(0), a=wida, b=widb, z=widz, r=widr)
def paramsFromHand(filter1, filter2, filter3): plotParams = dict( z=FloatSliderWidget(min=0.15, max=2, step=0.01, value=1.00), x1=FloatSliderWidget(min=-3, max=2, step=0.1, value=1.), c=FloatSliderWidget(min=-0.4, max=0.4, step=0.01, value=0), hostebv_cc=FloatSliderWidget(min=-0.1, max=0.65, step=0.1, value=0), phase=FloatSliderWidget(min=-50, max=150, step=1, value=0), dates=np.asarray([[0, 32], [0, 32], [0, 32]]), filters=fixed([filter1, filter2, filter3]), data_flux_filter1=fixed([0.0, 4.93]), data_flux_filter1_err=fixed([0.26, 0.23]), data_flux_filter2=fixed([0.0, 5.08]), data_flux_filter2_err=fixed([0.2, 0.2]), data_flux_filter3=fixed([0, 1.15]), data_flux_filter3_err=fixed([0.3, 0.3])) return plotParams
require(["leaflet"], function(leaflet) { var map = window._my_maps['i3c9fe247-096f-4df2-b6d7-291bb6d3b0e1'] console.log(map.getCenter()); }); # <codecell> from IPython.html import widgets from IPython.html.widgets import interact, fixed zoom_widget = widgets.IntSliderWidget(min=1, max=18, step=1) zoom_widget.value = 12 interact (leaflet, leaflet_api_key=fixed(LEAFLET_KEY), lat=fixed(37.8717), long=fixed(-122.2728),height=fixed(500), zoom=zoom_widget) # <headingcell level=1> # Doing more with a map # <codecell> %%javascript console.log(IPython.notebook.get_cells()); # <codecell> %%javascript require(["leaflet"], function(leaflet) {
def plot_line(ax, intercept): plt.figure(figsize=(12, 12)) ax = plt.gca() ax.set_xlim([0.0, 1.0]) ax.set_ylim([0.0, 1.0]) make_roc("gnb", clfgnb, ytest, Xtest, ax, labe=60) make_roc("dt", clfdt, ytest, Xtest, ax, labe=1) ax.plot(z1, slope * z1 + intercept, 'k-') # In[48]: from IPython.html.widgets import interact, fixed interact(plot_line, ax=fixed(ax), intercept=(0.0, 1.0, 0.02)) # In[50]: def percentage(tpr, fpr, priorp, priorn): perc = tpr * priorp + fpr * priorn return perc def av_cost2(tpr, fpr, cost, priorp, priorn): profit = priorp * (cost[1][1] * tpr + cost[1][0] * (1. - tpr)) + priorn * (cost[0][0] * (1. - fpr) + cost[0][1] * fpr) return profit
def simulate(transitions, input='10101', unary=False, input_unary=12, pause=0.05, step_from=0, step_to=100, step_slack=100): """loads widget to simulate a given TM""" # widgets to specify the range of steps to simulate from_w = widgets.IntText(value=step_from, description="simulate from step") to_w = widgets.IntText(value=step_to, description="simulate to step") pause_w = widgets.FloatText(value=pause, description="pause between steps") # widget to indicate current step steps_w = widgets.IntSlider(min=0, max=step_to + step_slack, value=0, description="current step") # subroutine to animate the simulation def animate(x): steps_w.max = to_w.value + step_slack for steps in range(from_w.value, to_w.value + 1): steps_w.value = steps sleep(pause_w.value) # button to start animated simulation simulate_w = widgets.Button(description='simulate') simulate_w.on_click(animate) input_w = widgets.Text(value=input, description="input") unary_w = widgets.Checkbox(value=unary, description='unary?') input_unary_w = widgets.IntText(value=input_unary, description='input number') def update(): if unary_w.value: input_w.disabled = True input_unary_w.visible = True input_w.value = '1' * input_unary_w.value else: input_w.disabled = False input_unary_w.visible = False update() unary_w.on_trait_change(update) input_unary_w.on_trait_change(update) # display control widgets box = widgets.VBox( children=[simulate_w, from_w, to_w, pause_w, unary_w, input_unary_w]) display(box) # widgets to display simulation interact(display_wrap(run), transitions=fixed(transitions), input=input_w, steps=steps_w)
import thinkplot # import warnings # warnings.filterwarnings('ignore') from IPython.html.widgets import interact, fixed from IPython.display import display wave = thinkdsp.read_wave('170255__dublie__trumpet.wav') wave.normalize() wave.make_audio() wave.plot() #Interactive Version def filter_wave(wave, start, duration, cutoff): segment = wave.segment(start, duration) spectrum = segment.make_spectrum() spectrum.plot(high=5000, color='0.7') spectrum.low_pass(cutoff) spectrum.plot(high=5000, color='#045a8d') thinkplot.config(xlabel='Frequency (Hz)') audio = spectrum.make_wave().make_audio() display(audio) interact(filter_wave, wave=fixed(wave), start=(0, 5, 0.1), duration=(0, 5, 0.1), cutoff=(0, 5000, 100));
# ## Fully Interactive # # One of the nice pieces of the IPython notebook is the ability to quickly create interactive visualizations. Unfortunately this only works when you're viewing the notebook live (i.e. a static HTML view on a blog post won't give you any interaction). If you're reading this on my blog or on nbviewer, then you can [download the notebook](http://jakevdp.github.io/downloads/notebooks/HipsterEffect.ipynb) and run it with IPython to see these features. # # What we'll do is to call IPython's interactive tools on our Python function, which will create javascript sliders allowing us to explore the parameter space of this hipster conformity model. I'd encourage you to download the notebook and try it out! # In[9]: from IPython.html.widgets import interact, fixed interact(plot_results, hipster_frac=(0.0, 1.0), delay=(1, 50), initial_state_frac=(0.0, 1.0), log10_beta=(-2.0, 2.0), Npeople=fixed(500), Nsteps=fixed(200), rseed=fixed(42)) # Again, unless you [download the notebook](http://jakevdp.github.io/downloads/notebooks/HipsterEffect.ipynb) and run it on a local Python kernel, all you'll see is a static graphic above. But with the interactive version, you can really start to see how these various parameters affect the system. # ## Conclusion # # This has been a lot of fun, and if you've read this far I hope this helped you understand the mathematics of Hipster-dom! For more information and analysis, go [read the paper](http://arxiv.org/abs/1410.8001). It goes much deeper than the rough, discrete approximation I've used here. # # For further ideas, I'd love to see a simulation of how this looks if we add-in spatial information, and create a delay related to that information. Would you start to see pockets of people adapting similar styles? My guess is yes, but I'm not entirely sure... there's only one way to find out. # # Happy coding! # <small> # This post was written entirely in the IPython notebook. You can
segment = wave.segment(start, duration) spectrum = segment.make_spectrum() spectrum.plot(high=5000, color='0.7') spectrum.low_pass(cutoff) spectrum.plot(high=5000, color='#045a8d') thinkplot.config(xlabel='Frequency (Hz)') audio = spectrum.make_wave().make_audio() display(audio) # In[14]: interact(filter_wave, wave=fixed(wave), start=(0, 5, 0.1), duration=(0, 5, 0.1), cutoff=(0, 5000, 100)) # ### Exercise # # Synthesize a compound signal by creating SinSignal and CosSignal # objects and adding them up. Evaluate the signal to get a Wave, # and listen to it. Compute its Spectrum and plot it. # What happens if you add frequency # components that are not multiples of the fundamental? # ### Solution # # Here are some arbitrary components I chose. It makes an interesting waveform!
) if show_javascript: display(widgets.PopupWidget(children=(widgets.HTMLWidget(value='<div style="width:600px; height: 400px; overflow:scroll;"><pre>{}</pre></div>'.format(rendered_template)),))) display(Javascript(rendered_template)) # In[27]: values = { record['STUSAB']: "{0} - {1}".format(record['STUSAB'], record['STATE_NAME']) for record in state[['STUSAB', 'STATE_NAME']].sort('STUSAB').to_dict(outtype='records') } i = interact( display_chart_d3, data=widgets.fixed(sub_est_2012_df_by_state), show_javascript=widgets.CheckboxWidget(value=False), states=MultipleSelectWidget( value=['CA', 'NY'], values=values, values_order=sorted(values.keys()) ), div=widgets.HTMLWidget(value='<div id="chart_d3_interactive"></div>') ) # We've also added a show_javascript checkbox to display the generated code on a pop-up. # Although D3 is capable of creating [incredible charts](https://github.com/mbostock/d3/wiki/Gallery), it has a steep learning curve and it can be overkill if what you want are just simple charts. Let us explore simpler alternatives. # ## Part 2 - Embedding Chart.js
# You can also set both of these explicitly in the ``imshow`` command: # In[8]: plt.imshow(R, cmap='gray', interpolation='nearest') # ## Interactive demo: interpolation and color maps # In[9]: from IPython.html.widgets import interact, fixed from matplotlib import cm as colormaps @interact( image=fixed(face), cmap=sorted([c for c in colormaps.datad.keys() if not c.endswith('_r')], key=lambda x: x.lower()), interpolation=[ 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos' ]) def imshow_params(image, cmap='jet', interpolation='bicubic'): fig, axes = plt.subplots(1, 5, figsize=(15, 4)) axes[0].imshow(image, cmap='gray', interpolation='nearest') axes[0].set_title('Original') axes[1].imshow(image[:5, :5], cmap='gray', interpolation='nearest') axes[1].set_title('Top 5x5 block')
def InteractClean(cleanDataFile, cleanTimeFile): clean = interactive(CleanNMOWidget, t0 = (0.2, 0.8, 0.01), v = (1000., 5000., 100.), syndat = fixed(cleanDataFile), timdat = fixed(cleanTimeFile)) return clean
def InteractNosiy(noisyDataFile, noisyTimeFile): noisy = interactive(NoisyNMOWidget, t0 = (0.1, 0.6, 0.01), v = (800., 2500., 100.), syndat = fixed(noisyDataFile), timdat = fixed(noisyTimeFile)) return noisy