def interactive(): """ interactive call of `main` """ interact( main, alpha=FloatSlider(min=0.01, max=24, step=0.01, value=0.4, description='Birth Rate of Prey', style=style, layout=slider_layout), beta=FloatSlider(min=0.01, max=24, step=0.01, value=0.04, description='Death Rate of Prey', style=style, layout=slider_layout), gamma=FloatSlider(min=0.01, max=24, step=0.01, value=0.02, description='Birth Rate of Predator', style=style, layout=slider_layout), delta=FloatSlider(min=0.01, max=24, step=0.01, value=2., description='Death Rate of Predator', style=style, layout=slider_layout), y0_0=FloatSlider(min=0.01, max=200, step=0.01, value=105., description='Initial population Prey', style=style, layout=slider_layout), y0_1=FloatSlider(min=0.01, max=100, step=0.01, value=8., description='Initial population Predator', style=style, layout=slider_layout), my_range=IntRangeSlider(min=0, max=50, step=1, value=[0, 15], description='time interval', style=style, layout=slider_layout), )
def display_profile(self): [roi_left, roi_top, roi_width, roi_height] = self.roi _rebin = self.rebin pixel_range = np.arange(roi_top, roi_height-roi_top, _rebin) def plot_profile(file_index): data_1d = self.profile_1d[file_index] data_2d = self.sample_data[file_index] fig = plt.figure(figsize=(5, 5)) ax_plt = plt.subplot(211) ax_plt.plot(pixel_range, data_1d) plt.xlabel("Pixel") plt.ylabel("Transmission") ax_plt.set_title(os.path.basename(self.list_data_files[file_index])) ax_img = plt.subplot(212) ax_img.imshow(data_2d, cmap='rainbow', interpolation=None) ax_img.add_patch(patches.Rectangle((roi_left, roi_top), roi_width, roi_height, fill=False)) number_of_files = len(self.sample_data) _ = interact(plot_profile, file_index=widgets.IntSlider(min=0, max=number_of_files - 1, value=0, step=1, description="Image Index", continuous_update=False))
def preview(self): #figure, axis = plt.subplots() [height, width] = np.shape(self.images_array[0]) text_y = 0.1 * height text_x = 0.6 * width def display_selected_image(index, text_x, text_y, pre_text, post_text, color): font = { 'family': 'serif', 'color': color, 'weight': 'normal', 'size': 16 } fig = plt.figure(figsize=(15, 10)) gs = gridspec.GridSpec(1, 1) ax = plt.subplot(gs[0, 0]) im = ax.imshow(self.images_array[index], interpolation='nearest') plt.title("image index {}".format(index)) plt.text(text_x, text_y, "{} {:.2f}{}".format(pre_text, self.list_time_offset[index], post_text), fontdict=font) fig.colorbar(im) plt.show() return { 'text_x': text_x, 'text_y': text_y, 'pre_text': pre_text, 'post_text': post_text, 'color': color } self.preview = interact( display_selected_image, index=widgets.IntSlider(min=0, max=len(self.list_files), continuous_update=False), text_x=widgets.IntSlider(min=0, max=width, value=text_x, description='Text x_offset', continuous_update=False), text_y=widgets.IntSlider(min=0, max=height, value=text_y, description='Text y_offset', continuous_upadte=False), pre_text=widgets.Text(value='Time Offset', description='Pre text'), post_text=widgets.Text(value='(s)', description='Post text'), color=widgets.RadioButtons( options=['red', 'blue', 'white', 'black', 'yellow'], value='red', description='Text Color'))
def display_images_pretty(self): _data = self.data _clean_data = self.clean_data _files = self.list_files _full_statistics = self.full_statistics [height, width] = np.shape(self.data[0]) def _plot_images(index): _file_name = _files[index] fig = plt.figure(figsize=(7,7)) ax0 = plt.subplot(111) ax0.set_title(os.path.basename(_file_name)) cax0 = ax0.imshow(_clean_data[index], cmap='viridis', interpolation=None) tmp2 = fig.colorbar(cax0, ax=ax0) # colorbar fig.tight_layout() tmp3 = widgets.interact(_plot_images, index=widgets.IntSlider(min=0, max=len(self.list_files) - 1, step=1, value=0, description='File Index', continuous_update=False), )
def interactive_slider(image, title): # Makes an interactive slider from ipywidgets import widgets import matplotlib.pyplot as plt # For making figures def slice_through_images(image): def slice_step(i_step): fig, axes = plt.subplots(figsize=(10, 5)) axes.imshow(image[:, :, i_step], cmap='gray') plt.title(title) plt.colorbar plt.show() return slice_step stepper = slice_through_images(image) widgets.interact(stepper, i_step=(0, image.shape[2] - 1))
def select_profile(self, roi_left=0, roi_top=0, roi_height=-1, roi_width=-1): self.integrated_data = self.__calculate_integrated_data() self.image_dimension = np.shape(self.integrated_data) [self.height, self.width] = self.image_dimension if roi_height == -1: roi_height = self.height - 1 if roi_width == -1: roi_width = self.width - 1 def plot_images_with_roi(x_left, y_top, width, height, contrast_min, contrast_max): plt.figure(figsize=(5, 5)) ax_img = plt.subplot(111) ax_img.imshow(self.integrated_data, cmap='rainbow', interpolation=None, vmin = contrast_min, vmax = contrast_max) ax_img.add_patch(patches.Rectangle((x_left, y_top), width, height, fill=False)) return [x_left, y_top, width, height] self.profile = interact(plot_images_with_roi, x_left=widgets.IntSlider(min=0, max=self.width - 1, step=1, value=roi_left, continuous_update=False), y_top=widgets.IntSlider(min=0, max=self.height - 1, step=1, value=roi_top, continuous_update=False), width=widgets.IntSlider(min=0, max=self.width - 1, step=1, value=roi_width, continuous_update=False), height=widgets.IntSlider(min=0, max=self.height - 1, step=1, value=roi_height, continuous_update=False), contrast_min=widgets.FloatSlider(min=0, max=1, step=0.1, value=0, continuous_update=False), contrast_max=widgets.FloatSlider(min=0, max=2, value=1, step=0.1, continuous_update=False))
def show_spectrum(node: Spectrum, **kwargs) -> widgets.Widget: check_spectrum(node) data = node.power if "power" in node.fields else node.phase if len(data.shape) == 2: no_channels = data.shape[1] else: no_channels = 1 freqs_all = np.asarray(node.frequencies) channel_slider = widgets.IntRangeSlider( min=1, max=no_channels, step=1, description="Channel Range:", disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format="d", ) freq_slider = widgets.IntRangeSlider( min=0, max=freqs_all[-1], step=1, description="Frequency Range:", disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format="d", ) out = widgets.Output() with out: widgets.interact( lambda channel_range, frequency_range: plot_spectrum_figure( node, channel_range, frequency_range), channel_range=channel_slider, frequency_range=freq_slider, ) return out
def update(self): xl, xh = (widgets.IntSlider(description="Lower Bound Scaling", min=0, max=len(self.txs)-1, value=0, step=1.0), widgets.IntSlider(description="Upper Bound Scaling", min=0, max=len(self.txs)-1, value=len(self.txs)-1, step=1.0)) dl = widgets.jsdlink((xl, 'value'), (xh, 'min')) w = widgets.interact(self.plotting, xl=xl, xh=xh)
def update(self): xl, xh = (widgets.IntSlider(description="Lower Bound Scaling", min=0, max=len(self.txs) - 1, value=0, step=1.0), widgets.IntSlider(description="Upper Bound Scaling", min=0, max=len(self.txs) - 1, value=len(self.txs) - 1, step=1.0)) dl = widgets.jsdlink((xl, 'value'), (xh, 'min')) w = widgets.interact(self.plotting, xl=xl, xh=xh)
def sigmoid(): np.random.seed(0) fig, ax = plt.subplots() plt.xlabel('Distance from the boundary') plt.ylabel('Probability of being blue') ax.set_xlim(-5, 5) ax.set_ylim(-0.1, 1.1) x = np.linspace(-5, 5, 300) def f(sigma): return 1 / (1 + np.exp(-sigma * x)) line, = ax.plot(x, f(1), lw=1, color='k', alpha=0.6) def update_s(s=1): line.set_ydata(f(s)) interact(update_s, s=(0, 10, 0.01)) plt.tight_layout()
def plot_images(self, data_type='sample'): sample_array = self.get_data(data_type=data_type) def _plot_images(index): _ = plt.figure(num=data_type, figsize=(5, 5)) ax_img = plt.subplot(111) my_imshow = ax_img.imshow(sample_array[index], cmap='viridis') plt.colorbar(my_imshow) _ = widgets.interact( _plot_images, index=widgets.IntSlider( min=0, max=len(self.get_data(data_type=data_type)) - 1, step=1, value=0, description='{} Index'.format(data_type), continuous_update=False))
def display(self): _data = self.data _files = self.list_files def _plot_images(index): fig, ax_img = plt.subplots() plt.title(os.path.basename(_files[index])) cax = ax_img.imshow(_data[index], cmap='viridis', interpolation=None) # add colorbar cbar = fig.colorbar(cax) _ = widgets.interact(_plot_images, index=widgets.IntSlider(min=0, max=len(self.list_files) - 1, step=1, value=0, description='File Index', continuous_update=False))
def __preview(self): metadata_profile = {} _metadata_array = np.array(self.file_name_vs_metadata['Metadata']) _time_array = np.array(self.file_name_vs_metadata['time']) for _index, _file in enumerate( np.array(self.file_name_vs_metadata['file_name'])): metadata_profile[_file] = {} metadata_profile[_file]['metadata'] = _metadata_array[_index] metadata_profile[_file]['time'] = _time_array[_index] self.metadata_profile = metadata_profile self.metadata_array = _metadata_array self.time_array = _time_array def plot_images_and_profile(file_index=0): fig = plt.figure(figsize=(15, 10)) gs = gridspec.GridSpec(1, 2) _short_file = os.path.basename(self.images_list[file_index]) _time = metadata_profile[_short_file]['time'] #_metadata = metadata_profile[_short_file]['metadata'] ax_img = plt.subplot(gs[0, 0]) ax_img.imshow(self.images_array[file_index]) plt.title("{}".format(_short_file)) ax_plot = plt.subplot(gs[0, 1]) ax_plot.plot(_time_array, _metadata_array, '*') ax_plot.axvline(x=_time, color='r') plt.xlabel('Time (s)') plt.ylabel(self.metadata_name) plt.show() preview = interact(plot_images_and_profile, file_index=widgets.IntSlider( min=0, max=self.nbr_images - 1, description='Image Index', continuous_update=False))
def display_water_intake_vs_profile(self): self.retrieve_data_and_metadata() self.calculate_water_intake_peak() water_intake_peak = self.water_intake_peak list_files = self.list_files metadata = self.files_metadata def display_intake_vs_profile(file_index): plt.figure(figsize=(5,5)) ax_img = plt.subplot(111) _file = list_files[file_index] _data = self.files_data[_file]['counts'].values _peak = float(water_intake_peak[file_index]) _metadata = metadata[_file] _rebin = float(_metadata['Rebin in y direction']) _metadata_entry = _metadata['ROI selected (y0, x0, height, width)'] m = re.match(r"\((?P<y0>\d*), (?P<x0>\d*), (?P<height>\d*), (?P<width>\d*)\)", _metadata_entry) y0 = float(m.group('y0')) height = float(m.group('height')) _real_peak = (_peak + y0) * _rebin _real_axis = np.arange(y0, height, _rebin) ax_img.plot(_real_axis, _data, '.') plt.title(os.path.basename(_file)) ax_img.axvline(x=_real_peak, color='r') _ = interact(display_intake_vs_profile, file_index = widgets.IntSlider(min=0, max=len(list_files)-1, value=0, description='File Index'))
def find_best_decision_bondary2(): np.random.seed(0) fig, ax = plt.subplots() ax.set_aspect('equal') x1 = np.random.normal(2, 2.1, 25) x2 = np.random.normal(-2, 2.1, 25) y1 = np.random.normal(2, 2.1, 25) y2 = np.random.normal(-2, 2.1, 25) ax.scatter(x1, y1, alpha=0.6) ax.scatter(x2, y2, alpha=0.6) plt.xlabel('Feature 1') plt.ylabel('Feature 2') ax.set_title("Title x") ax.set_xlim(-5, 5) ax.set_ylim(-5, 5) ax.set_xticks([]) ax.set_yticks([]) x = np.linspace(-5, 5, 100) line, = ax.plot(x, x, lw=1, ls='--', color='k', alpha=0.4) class Line: def __init__(self, a, b): self.a = a self.b = b self.m = None self.fill1 = None self.fill2 = None self.n = len(x1) + len(x2) self.set_y() def set_y(self): self.m = np.tan(self.b * np.pi / 180) self.y = self.a + self.m * x line.set_ydata(self.y) if self.fill1 is not None: self.fill1.remove() self.fill2.remove() if self.b > 90 or self.b < -90: self.fill1 = ax.fill_between(x, -5, self.y, color='#1f77b4', alpha=0.3) self.fill2 = ax.fill_between(x, self.y, 5, color='#ff7f0e', alpha=0.3) else: self.fill1 = ax.fill_between(x, -5, self.y, color='#ff7f0e', alpha=0.3) self.fill2 = ax.fill_between(x, self.y, 5, color='#1f77b4', alpha=0.3) def accuracy(self): if self.b > 90 or self.b < -90: return ((y2 > self.a + self.m * x2).sum() + (y1 < self.a + self.m * x1).sum()) / self.n else: return ((y1 > self.a + self.m * x1).sum() + (y2 < self.a + self.m * x2).sum()) / self.n def set_title(self, title): ax.set_title(title) theLine = Line(1, 45) def update(): theLine.set_y() ac = f'accuracy = {theLine.accuracy() * 100:.0f}%' theLine.set_title(ac) def update_a(a=0): theLine.a = a update() def update_b(b=45): theLine.b = b update() interact(update_a, a=(-10, 10, 0.001)) interact(update_b, b=(-180, 180, 0.01)) plt.tight_layout()
def make_graph_1(): global w, t np.random.seed(11) fig, ax = plt.subplots() n_dogs = 70 n_cats = 50 X, y = _gen_data(n_dogs, n_cats) ax.scatter(X[:n_dogs, 0], X[:n_dogs, 1], label='Dogs', alpha=0.6) ax.scatter(X[n_dogs:, 0], X[n_dogs:, 1], label='Cats', alpha=0.6) plt.legend() plt.xlabel('Weight (kg)') plt.ylabel('Tail length (cm)') w, t = 0, 0 point, = plt.plot([55], [22], marker='o', linewidth=0, color='#1f77b4', alpha=0.6) colors = ['#ff7f0e', '#1f77b4'] data = np.zeros((n_cats + n_dogs, 3)) data[:, :2] = X data[:, 2] = y def get_dists(x, y): dists = ((data[:, 0] - x)**2 + (data[:, 1] - y)**2)**0.5 sortd = np.argsort(dists)[:5] return data[sortd, :] lines = [] d0 = get_dists(55, 22) lines = [ plt.plot([22, d0[i, 0]], [55, d0[i, 1]], color=colors[int(d0[i, 2])], alpha=0.3)[0] for i in range(5) ] def update(): global w, t new_dists = get_dists(w, t) for i, line in enumerate(lines): line.set_xdata([w, new_dists[i, 0]]) line.set_ydata([t, new_dists[i, 1]]) line.set_color(colors[int(new_dists[i, 2])]) if new_dists[:, 2].sum() > 2.5: point.set_color(colors[1]) ax.set_title('Predict a dog') else: point.set_color(colors[0]) ax.set_title('Predict a cat') def update_weight(weight=15.5): global w, t w = weight point.set_xdata([weight]) update() def update_tail(tail=47): global w, t t = tail point.set_ydata([tail]) update() interact(update_weight, weight=(0, 70, 0.01)) interact(update_tail, tail=(10, 70, 0.01))
def AudioAligner(original, sample, search_start=0.0, search_end=15.0, xmax=60, manual=False, reduce_orig_volume=1): """ This function pull up an interactive console to find the offsets between two audios. Args: original: path to original audio file (e.g. '../audios/original.wav') sample: path to the sample audio file (e.g. '../audios/sample.wav') search_start(float): start range for slider to search for offset search_end(float): end range for slider to search for offset xmax(int): Range of audio to plot from beginning manual(bool): set to True to turn off auto-refresh reduce_orig_volume(int or float): Original wav sounds are often larger so divide the volume by this number. """ import scipy.io.wavfile as wav from IPython.display import Audio from IPython.display import display from ipywidgets import widgets orig_r, orig = wav.read(original) # volume is often louder on original so you can reduce it orig = orig / reduce_orig_volume # take one channel of target audio. probably not optimal if np.ndim(orig) > 1: orig = orig[:, 0] # grab one channel of sample audio tomatch_r, tomatch = wav.read(sample) if np.ndim(tomatch) > 1: tomatch = tomatch[:, 0] fs = 44100 def audwidg(offset, play_start): allshift = play_start samplesize = 30 tomatchcopy = tomatch[int((allshift + offset) * tomatch_r):int((allshift + offset) * tomatch_r) + fs * samplesize] shape = tomatchcopy.shape[0] origcopy = orig[int((allshift) * tomatch_r):int((allshift) * tomatch_r) + fs * samplesize] # when target audio is shorter, pad difference with zeros if origcopy.shape[0] < tomatchcopy.shape[0]: diff = tomatchcopy.shape[0] - origcopy.shape[0] origcopy = np.pad(origcopy, pad_width=(0, diff), mode='constant') toplay = origcopy + tomatchcopy display(Audio(data=toplay, rate=fs)) def Plot_Audios(offset, x_min, x_max): # print('Precise offset : ' + str(offset)) fig, ax = plt.subplots(figsize=(20, 3)) ax.plot(orig[int(fs * x_min):int(fs * x_max)], linewidth=.5, alpha=.8, color='r') ax.plot(tomatch[int(fs * x_min) + int(fs * offset):int(fs * x_max) + int(fs * offset)], linewidth=.5, alpha=.8) ax.set_xticks([(tick - x_min) * fs for tick in range(int(x_min), int(x_max + 1))]) ax.set_xticklabels( [tick for tick in range(int(x_min), int(x_max) + 1)]) ax.set_xlim([(x_min - x_min) * fs, (x_max - x_min) * fs]) ax.set_ylabel('Audio') ax.set_xlabel('Target Audio Time') audwidg(offset, x_min) plt.show() widgets.interact( Plot_Audios, offset=widgets.FloatSlider(value=0.5 * (search_start + search_end), readout_format='.3f', min=float(search_start), max=float(search_end), step=0.001, description='Adjusted offset: ', layout=widgets.Layout(width='90%')), x_min=widgets.FloatSlider(description='Min X on audio plot', value=0.0, min=0.0, max=xmax, step=0.1, layout=widgets.Layout(width='50%')), x_max=widgets.FloatSlider(description='Max X on audio plot', value=xmax, min=0.0, max=xmax, step=0.1, layout=widgets.Layout(width='50%')), __manual=manual)
x = np.arange(-3, 3, delta) y = np.ones_like(x) * y0 z = (x**2) + np.sin(y**2) ax_3d.plot(x, y, z, color='green', linestyle='--', linewidth=2) # change the viewing angle of the 3D plot ax_3d.view_init(55, 65) plt.draw() # show the plot plt.show() # try it out interact(plot_surface_problem3, x0=FloatSlider(min=-3, max=3, step=0.1, continuous_update=False), y0=FloatSlider(min=-3, max=3, step=0.1, continuous_update=False)) # ## 3.4) What is the partial derivative with respect to x? # What is the partial derivative of $f(x, y)$ with respect to $x$? # # Answer: # # $$ # \frac{\partial}{\partial x} f(x, y) = 2x # $$ # # ## 3.5) Plot the partial derivative with respect to x # Now plot the partial derivative $\partial f/\partial x$ (in 2D).
def mandelbrot_plot(f=None, **kwds): r""" Plot of the Mandelbrot set for a one parameter family of polynomial maps. The family `f_c(z)` must have parent ``R`` of the form ``R.<z,c> = CC[]``. REFERENCE: [Dev2005]_ INPUT: - ``f`` -- map (optional - default: ``z^2 + c``), polynomial family used to plot the Mandelbrot set. - ``parameter`` -- variable (optional - default: ``c``), parameter variable used to plot the Mandelbrot set. - ``x_center`` -- double (optional - default: ``-1.0``), Real part of center point. - ``y_center`` -- double (optional - default: ``0.0``), Imaginary part of center point. - ``image_width`` -- double (optional - default: ``4.0``), width of image in the complex plane. - ``max_iteration`` -- long (optional - default: ``500``), maximum number of iterations the map ``f_c(z)``. - ``pixel_count`` -- long (optional - default: ``500``), side length of image in number of pixels. - ``base_color`` -- RGB color (optional - default: ``[40, 40, 40]``) color used to determine the coloring of set. - ``level_sep`` -- long (optional - default: 1) number of iterations between each color level. - ``number_of_colors`` -- long (optional - default: 30) number of colors used to plot image. - ``interact`` -- boolean (optional - default: ``False``), controls whether plot will have interactive functionality. OUTPUT: 24-bit RGB image of the Mandelbrot set in the complex plane. EXAMPLES: :: sage: mandelbrot_plot() 500x500px 24-bit RGB image :: sage: mandelbrot_plot(pixel_count=1000) 1000x1000px 24-bit RGB image :: sage: mandelbrot_plot(x_center=-1.11, y_center=0.2283, image_width=1/128, # long time ....: max_iteration=2000, number_of_colors=500, base_color=[40, 100, 100]) 500x500px 24-bit RGB image To display an interactive plot of the Mandelbrot in the Notebook, set ``interact`` to ``True``. (This is only implemented for ``z^2 + c``):: sage: mandelbrot_plot(interact=True) interactive(children=(FloatSlider(value=0.0, description=u'Real center', max=1.0, min=-1.0, step=1e-05), FloatSlider(value=0.0, description=u'Imag center', max=1.0, min=-1.0, step=1e-05), FloatSlider(value=4.0, description=u'Width', max=4.0, min=1e-05, step=1e-05), IntSlider(value=500, description=u'Iterations', max=1000), IntSlider(value=500, description=u'Pixels', max=1000, min=10), IntSlider(value=1, description=u'Color sep', max=20, min=1), IntSlider(value=30, description=u'# Colors', min=1), ColorPicker(value='#ff6347', description=u'Base color'), Output()), _dom_classes=(u'widget-interact',)) :: sage: mandelbrot_plot(interact=True, x_center=-0.75, y_center=0.25, ....: image_width=1/2, number_of_colors=75) interactive(children=(FloatSlider(value=-0.75, description=u'Real center', max=1.0, min=-1.0, step=1e-05), FloatSlider(value=0.25, description=u'Imag center', max=1.0, min=-1.0, step=1e-05), FloatSlider(value=0.5, description=u'Width', max=4.0, min=1e-05, step=1e-05), IntSlider(value=500, description=u'Iterations', max=1000), IntSlider(value=500, description=u'Pixels', max=1000, min=10), IntSlider(value=1, description=u'Color sep', max=20, min=1), IntSlider(value=75, description=u'# Colors', min=1), ColorPicker(value='#ff6347', description=u'Base color'), Output()), _dom_classes=(u'widget-interact',)) Polynomial maps can be defined over a multivariate polynomial ring or a univariate polynomial ring tower:: sage: R.<z,c> = CC[] sage: f = z^2 + c sage: mandelbrot_plot(f) 500x500px 24-bit RGB image :: sage: B.<c> = CC[] sage: R.<z> = B[] sage: f = z^5 + c sage: mandelbrot_plot(f) 500x500px 24-bit RGB image When the polynomial is defined over a multivariate polynomial ring it is necessary to specify the parameter variable (default parameter is ``c``):: sage: R.<a,b> = CC[] sage: f = a^2 + b^3 sage: mandelbrot_plot(f, parameter=b) 500x500px 24-bit RGB image Interact functionality is not implemented for general polynomial maps:: sage: R.<z,c> = CC[] sage: f = z^3 + c sage: mandelbrot_plot(f, interact=True) Traceback (most recent call last): ... NotImplementedError: Interact only implemented for z^2 + c """ parameter = kwds.pop("parameter", None) x_center = kwds.pop("x_center", 0.0) y_center = kwds.pop("y_center", 0.0) image_width = kwds.pop("image_width", 4.0) max_iteration = kwds.pop("max_iteration", None) pixel_count = kwds.pop("pixel_count", 500) level_sep = kwds.pop("level_sep", 1) number_of_colors = kwds.pop("number_of_colors", 30) interacts = kwds.pop("interact", False) base_color = kwds.pop("base_color", Color('tomato')) # Check if user specified maximum number of iterations given_iterations = True if max_iteration is None: # Set default to 500 for z^2 + c map max_iteration = 500 given_iterations = False from ipywidgets.widgets import FloatSlider, IntSlider, ColorPicker, interact widgets = dict( x_center=FloatSlider(min=-1.0, max=1.0, step=EPS, value=x_center, description="Real center"), y_center=FloatSlider(min=-1.0, max=1.0, step=EPS, value=y_center, description="Imag center"), image_width=FloatSlider(min=EPS, max=4.0, step=EPS, value=image_width, description="Width"), max_iteration=IntSlider(min=0, max=1000, value=max_iteration, description="Iterations"), pixel_count=IntSlider(min=10, max=1000, value=pixel_count, description="Pixels"), level_sep=IntSlider(min=1, max=20, value=level_sep, description="Color sep"), color_num=IntSlider(min=1, max=100, value=number_of_colors, description="# Colors"), base_color=ColorPicker(value=Color(base_color).html_color(), description="Base color"), ) if f is None: # Quadratic map f = z^2 + c if interacts: return interact(**widgets).widget(fast_mandelbrot_plot) else: return fast_mandelbrot_plot(x_center, y_center, image_width, max_iteration, pixel_count, level_sep, number_of_colors, base_color) else: if parameter is None: c = var('c') parameter = c P = f.parent() if P.base_ring() is CC or P.base_ring() is CDF: if is_FractionField(P): raise NotImplementedError( "coefficients must be polynomials in the parameter") gen_list = list(P.gens()) parameter = gen_list.pop(gen_list.index(parameter)) variable = gen_list.pop() elif P.base_ring().base_ring() is CC or P.base_ring().base_ring( ) is CDF: if is_FractionField(P.base_ring()): raise NotImplementedError( "coefficients must be polynomials in the parameter") phi = P.flattening_morphism() f = phi(f) gen_list = list(f.parent().gens()) parameter = gen_list.pop(gen_list.index(parameter)) variable = gen_list.pop() elif P.base_ring() in FunctionFields(): raise NotImplementedError( "coefficients must be polynomials in the parameter") else: raise ValueError("base ring must be a complex field") if f == variable**2 + parameter: # Quadratic map f = z^2 + c if interacts: return interact(**widgets).widget(fast_mandelbrot_plot) else: return fast_mandelbrot_plot(x_center, y_center, image_width, max_iteration, pixel_count, level_sep, number_of_colors, base_color) else: if interacts: raise NotImplementedError( "Interact only implemented for z^2 + c") else: # Set default of max_iteration to 50 for general polynomial maps # This prevents the function from being very slow by default if not given_iterations: max_iteration = 50 # Mandelbrot of General Polynomial Map return polynomial_mandelbrot(f, parameter, x_center, y_center, \ image_width, max_iteration, pixel_count, level_sep, \ number_of_colors, base_color)
def make_graph_2(): global w, t np.random.seed(0) fig, ax = plt.subplots() weight_dogs = 0.45 * (np.random.gamma(7.5, 10, 50)) weight_cats = 0.45 * (3 + np.random.gamma(7.5, 1, 50)) tail_cats = np.random.normal(45, 1.5, 50) tail_dogs = weight_dogs + np.random.normal(10, 10, 50) ax.scatter(weight_dogs, tail_dogs, label='Dogs', alpha=0.6) ax.scatter(weight_cats, tail_cats, label='Cats', alpha=0.6) plt.legend() plt.xlabel('Weight (kg)') plt.ylabel('Tail length (cm)') w, t = 0, 0 point, = plt.plot([55], [22], marker='o', linewidth=0, color='#1f77b4', alpha=0.6) colors = ['#ff7f0e', '#1f77b4'] data = np.zeros((100, 3)) data[:50, 0] = weight_dogs data[:50, 1] = tail_dogs data[:50, 2] = 1 data[50:, 0] = weight_cats data[50:, 1] = tail_cats data[50:, 2] = 0 def get_dists(x, y): dists = ((data[:, 0] - x)**2 + (data[:, 1] - y)**2)**0.5 sortd = np.argsort(dists)[:5] return data[sortd, :] lines = [] d0 = get_dists(55, 22) lines = [ plt.plot([22, d0[i, 0]], [55, d0[i, 1]], color=colors[int(d0[i, 2])], alpha=0.3)[0] for i in range(5) ] def update(): global w, t new_dists = get_dists(w, t) for i, line in enumerate(lines): line.set_xdata([w, new_dists[i, 0]]) line.set_ydata([t, new_dists[i, 1]]) line.set_color(colors[int(new_dists[i, 2])]) if new_dists[:, 2].sum() > 2.5: point.set_color(colors[1]) ax.set_title('Predict a dog') else: point.set_color(colors[0]) ax.set_title('Predict a cat') def update_weight(weight=22): global w, t w = weight point.set_xdata([weight]) update() def update_tail(tail=55): global w, t t = tail point.set_ydata([tail]) update() interact(update_weight, weight=(0, 70, 0.01)) interact(update_tail, tail=(10, 70, 0.01))
def make_graph_2(): global fill, p, text fig, ax = plt.subplots() plt.plot([0, 0, 2, 2], [0, 0.5, 0.5, 0]) ax.set_ylim(0, 0.55) a, = ax.plot([0.2, 0.2], [0, 0.5], ls='--', color='k', alpha=0.5) b, = ax.plot([0.5, 0.5], [0, 0.5], ls='--', color='k', alpha=0.5) fill = ax.fill_between([0.2, 0.5], [0, 0], [0.5, 0.5], alpha=0.5, color='#1f77b4') p = [0.2, 1.5] ax.set_title( f'Probability of being between {0.2:.2f} and {0.5:.2f} is {0.65}') text = ax.text((p[1] + p[0]) / 2, 0.25, f'Area = {0.65}', horizontalalignment='center') def update_a(A=0.2): global p, fill, text a.set_xdata([A, A]) p[0] = A fig.canvas.draw_idle() fill.remove() fill = ax.fill_between([A, p[1]], [0, 0], [0.5, 0.5], alpha=0.5, color='#1f77b4') ax.set_title( f'Probability of being between {A:.2f} and {p[1]:.2f} is {abs(A - p[1])/2:.2f}' ) text.set_x((p[1] + p[0]) / 2) text.set_text(f'Area = {abs(p[0]- p[1])/2:.2f}') def update_b(B=1.5): global p, fill, text b.set_xdata([B, B]) p[1] = B fig.canvas.draw_idle() fill.remove() fill = ax.fill_between([p[0], B], [0, 0], [0.5, 0.5], alpha=0.5, color='#1f77b4') ax.set_title( f'Probability of being between {p[0]:.2f} and {B:.2f} is {abs(p[1] - p[0])/2:.2f}' ) text.set_x((p[1] + p[0]) / 2) text.set_text(f'Area = {abs(p[0] - p[1])/2:.2f}') plt.ylabel('Probability Density') plt.xlabel('$x$') interact(update_a, A=(0, 2, 0.001)) interact(update_b, B=(0, 2, 0.001))
def interactive_backtest(): widgets.interact(display_backtest, time_till_close_position=(5, 60, 5), sentiment_cutoff=(0, 1.00, 0.05))
country.append('') act_coords = [] for box in coordinates: actual_coord_x = (box[0][0][0]+box[0][1][0]+box[0][2][0]+box[0][3][0])/4 actual_coord_y = (box[0][0][1]+box[0][1][1]+box[0][2][1]+box[0][3][1])/4 act_coords.append([actual_coord_x,actual_coord_y]) df['city'] = name df['country'] = country df['full_name'] = full_name df['coordinates'] = act_coords df['x_p'] = df['coordinates'].apply(lambda x: x[0]) df['y_p'] = df['coordinates'].apply(lambda x: x[1]) ax = plt.axes(projection=ccrs.PlateCarree()) # shapename = 'admin_1_states_provinces_lakes_shp' # states_shp = shpreader.natural_earth(resolution='110m',category='cultural', name=shapename) ax.coastlines() def plotLocation(Hour): plt.scatter(df.x[df['Hour']==Hour],df.y[df['Hour']==Hour],color='r') plt.scatter(df.x_p[df['Hour']==Hour],df.y_p[df['Hour']==Hour],color='g') Hour = widgets.IntSlider(min=0, max=23, value=10) widgets.interact(plotLocation,Hour=Hour) plt.show()
def make_graph_4(): global fill, p, text fig, ax = plt.subplots() lamda = np.log(2) / 5700 x = np.linspace(0, 40000, 1001) def f(x): if isinstance(x, np.ndarray): return lamda * np.exp(-lamda * x[x >= 0]) else: if x > 0: return lamda * np.exp(-lamda * x) else: return 0 def F(x): if isinstance(x, np.ndarray): return 1 - np.exp(-lamda * x[x >= 0]) else: if x > 0: return 1 - np.exp(-lamda * x) else: return 0 def P(a, b): return abs(F(b) - F(a)) y = f(x) plt.plot(x, y) ax.set_ylim(0, 0.00013) a0 = 5000 b0 = 10000 a, = ax.plot([a0, a0], [0, f(a0)], ls='--', color='k', alpha=0.5) b, = ax.plot([b0, b0], [0, f(b0)], ls='--', color='k', alpha=0.5) fill = ax.fill_between(np.linspace(a0, b0, 250), np.zeros(250), f(np.linspace(a0, b0, 250)), alpha=0.5, color='#1f77b4') p = [a0, b0] ax.set_title( f'Probability of decay between {a0:.0f} and {b0:.0f}y is {P(a0, b0):.2f}' ) text = ax.text((p[1] + p[0]) / 2, max(f(p[1]), f(p[0])) / 3, f'Area = {P(a0, b0):.2f}', horizontalalignment='center') def update_a(t1=5000): global p, fill, text a.set_xdata([t1, t1]) a.set_ydata([0, f(t1)]) p[0] = t1 fig.canvas.draw_idle() fill.remove() xax = np.linspace(p[0], p[1], 250) fax = f(xax) fill = ax.fill_between(xax, np.zeros(250), fax, alpha=0.5, color='#1f77b4') ax.set_title( f'Probability of decay between {p[0]:.0f} and {p[1]:.0f}y is {P(p[0], p[1]):.2f}' ) text.set_x((p[1] + p[0]) / 2) text.set_y(fax.max() / 3) text.set_text(f'Area = {P(p[0], p[1]):.2f}') def update_b(t2=9000): global p, fill, text b.set_xdata([t2, t2]) b.set_ydata([0, f(t2)]) p[1] = t2 fig.canvas.draw_idle() fill.remove() xax = np.linspace(p[0], p[1], 250) fax = f(xax) fill = ax.fill_between(xax, np.zeros(250), fax, alpha=0.5, color='#1f77b4') ax.set_title( f'Probability of decay between {p[0]:.0f} and {p[1]:.0f}y is {P(p[0], p[1]):.2f}' ) text.set_x((p[1] + p[0]) / 2) text.set_y(fax.max() / 3) text.set_text(f'Area = {P(p[0], p[1]):.2f}') plt.ylabel('Probability Density') plt.xlabel('Time, years') plt.tight_layout() interact(update_a, t1=(0, 40000, 100)) interact(update_b, t2=(0, 40000, 100))
# In[ ]: def mix_bdfex_2all(alpha, beta, plot=False): res = stab_region(bdf2, (1. - alpha - beta) * ex2 + alpha * ex3 + beta * ex4, plot=plot) if plot: print("The eigenvalue for BDF/EX-2,3({},{}) is {}".format( alpha, beta, res)) return res # In[ ]: interact(mix_bdfex_23, alpha=.667, beta=.48, plot=True) # In[ ]: interact(mix_bdfex_2all, alpha=.667, beta=.1, plot=True) # We can maximize the stability constraint. The constraint $\alpha \ge 0$ must be added, because $\alpha < 0$ consistently results in instability (I don't know why). # In[ ]: def wrap(x): return -mix_bdfex_23(x[0], x[1]) def accept(f_new, x_new, f_old, x_old):
def give_statistics(self): data = self.data list_files = self.list_files def __give_statistics(index): def get_statistics_of_roi_cleaned(data): _data = data _result = np.where(_data < 0) nbr_negative = len(_result[0]) total = np.size(_data) percentage_negative = (nbr_negative / total) * 100 _result_inf = np.where(np.isinf(_data)) nbr_inf = len(_result_inf[0]) percentage_inf = (nbr_inf / total) * 100 nan_values = np.where(np.isnan(_data)) nbr_nan = len(nan_values[0]) percentage_nan = (nbr_nan / total) * 100 stat = self.Statistics(total_pixels=total, nbr_negative=nbr_negative, percentage_negative=percentage_negative, nbr_infinite=nbr_inf, percentage_infinite=percentage_inf, nbr_nan=nbr_nan, percentage_nan=percentage_nan) return stat _file = os.path.basename(list_files[index]) _data = data[index] stat = get_statistics_of_roi_cleaned(_data) number_of_pixels = stat.total_pixels negative_values = stat.nbr_negative negative_percentage = stat.percentage_negative infinite_values = stat.nbr_infinite infinite_percentage = stat.percentage_infinite nan_values = stat.nbr_nan nan_percentage = stat.percentage_nan box1 = widgets.HBox([ widgets.Label("File Name:"), widgets.Label(_file, layout=widgets.Layout(width='80%')) ]) box2 = widgets.HBox([ widgets.Label("Total number of pixels:", layout=widgets.Layout(width='15%')), widgets.Label(str(number_of_pixels)) ]) box3 = widgets.HBox([ widgets.Label("Negative values:", layout=widgets.Layout(width='30%')), widgets.Label("{} pixels ({:.3}%)".format( negative_values, negative_percentage), layout=widgets.Layout(width='15%')) ]) box4 = widgets.HBox([ widgets.Label("Infinite values:", layout=widgets.Layout(width='30%')), widgets.Label("{} pixels ({:.3}%)".format( infinite_values, infinite_percentage), layout=widgets.Layout(width='15%')) ]) box5 = widgets.HBox([ widgets.Label("NaN values:", layout=widgets.Layout(width='30%')), widgets.Label("{} pixels ({:.3}%)".format( nan_values, nan_percentage), layout=widgets.Layout(width='15%')) ]) vertical_box = widgets.VBox([box1, box2, box3, box4, box5]) display(vertical_box) tmp3 = widgets.interact( __give_statistics, index=widgets.IntSlider(min=0, max=len(list_files) - 1, step=1, value=0, description='File Index', continuous_update=False), )
def find_best_graded_decision_bondary(): fig, ax = plt.subplots() np.random.seed(0) x1 = np.random.normal(2, 2.1, 25) x2 = np.random.normal(-2, 2.1, 25) y1 = np.random.normal(2, 2.1, 25) y2 = np.random.normal(-2, 2.1, 25) ax.scatter(x1, y1, alpha=0.6) ax.scatter(x2, y2, alpha=0.6) plt.xlabel('Feature 1') plt.ylabel('Feature 2') ax.set_aspect('equal') ax.set_xlim(-5, 5) ax.set_ylim(-5, 5) X, Y = np.meshgrid(np.linspace(-5, 5, 100), np.linspace(-5, 5, 100)) X = np.vstack([X.reshape(-1), Y.reshape(-1)]).T cmap = matplotlib.colors.LinearSegmentedColormap.from_list( "", ["#1f77b4", "#ffffff", "#ff7f0e"]) def f(a, m, s, x, y): return 1 / (1 + np.exp(-s * d(a, m, x, y))) def d(a, m, x, y): return (m * x - y + a) / (m**2 + 1)**0.5 im = ax.imshow(f(0, -1, 0.1, X[:, 0], X[:, 1]).reshape(100, 100), origin='lower', interpolation='bicubic', extent=[-5, 5, -5, 5], cmap=cmap, vmin=0, vmax=1, alpha=0.7) class Line: def __init__(self): self.a = 0 self.b = 45 self.s = 1 def update(self): m = np.tan(self.b * np.pi / 180) if self.b > 90 or self.b < -90: im.set_array( f(self.a, m, self.s, X[:, 0], X[:, 1]).reshape(100, 100)) else: im.set_array( 1 - f(self.a, m, self.s, X[:, 0], X[:, 1]).reshape(100, 100)) ax.set_title(f'Average difference = {self.av_loss():.3f}') def av_loss(self): m = np.tan(self.b * np.pi / 180) return (np.abs(f(self.a, m, self.s, x1, y1)).sum() + np.abs(f(self.a, m, self.s, x2, y2) - 1).sum()) / ( len(x1) + len(x2)) line = Line() def update_a(a=0): line.a = a line.update() def update_b(b=45): line.b = b line.update() def update_s(s=1): line.s = s line.update() interact(update_a, a=(-10, 10, 0.001)) interact(update_b, b=(-180, 180, 0.01)) interact(update_s, s=(0.5, 5, 0.01)) plt.tight_layout()
def mandelbrot_plot(x_center=-1.0, y_center=0.0, image_width=4.0, max_iteration=500, pixel_count=500, base_color='steelblue', iteration_level=1, number_of_colors=30, interact=False): r""" Interactive plot of the Mandelbrot set for the map `Q_c(z) = z^2 + c`. ALGORITHM: Let each pixel in the image be a point `c \in \mathbb{C}` and define the map `Q_c(z) = z^2 + c`. If `|Q_{c}^{k}(c)| > 2` for some `k \geq 0`, it follows that `Q_{c}^{n}(c) \to \infty`. Let `N` be the maximum number of iterations. Compute the first `N` points on the orbit of `0` under `Q_c`. If for any `k < N`, `|Q_{c}^{k}(0)| > 2`, we stop the iteration and assign a color to the point `c` based on how quickly `0` escaped to infinity under iteration of `Q_c`. If `|Q_{c}^{i}(0)| \leq 2` for all `i \leq N`, we assume `c` is in the Mandelbrot set and assign the point `c` the color black. REFERENCE: [Dev2005]_ INPUT: - ``x_center`` -- double (optional - default: ``-1.0``), Real part of center point. - ``y_center`` -- double (optional - default: ``0.0``), Imaginary part of center point. - ``image_width`` -- double (optional - default: ``4.0``), width of image in the complex plane. - ``max_iteration`` -- long (optional - default: ``500``), maximum number of iterations the map ``Q_c(z)``. - ``pixel_count`` -- long (optional - default: ``500``), side length of image in number of pixels. - ``base_color`` -- RGB color (optional - default: ``'steelblue'``) color used to determine the coloring of set (any valid input for Color). - ``iteration_level`` -- long (optional - default: 1) number of iterations between each color level. - ``number_of_colors`` -- long (optional - default: 30) number of colors used to plot image. - ``interact`` -- boolean (optional - default: ``False``), controls whether plot will have interactive functionality. OUTPUT: 24-bit RGB image of the Mandelbrot set in the complex plane. EXAMPLES: :: sage: mandelbrot_plot() 500x500px 24-bit RGB image :: sage: mandelbrot_plot(pixel_count=1000) 1000x1000px 24-bit RGB image :: sage: mandelbrot_plot(x_center=-1.11, y_center=0.2283, image_width=1/128, ....: max_iteration=2000, number_of_colors=500, base_color=[40, 100, 100]) 500x500px 24-bit RGB image To display an interactive plot of the Mandelbrot set in the Jupyter Notebook, set ``interact`` to ``True``:: sage: mandelbrot_plot(interact=True) interactive(children=(FloatSlider(value=-1.0, description=u'Real center'... :: sage: mandelbrot_plot(interact=True, x_center=-0.75, y_center=0.25, ....: image_width=1/2, number_of_colors=75) interactive(children=(FloatSlider(value=-0.75, description=u'Real center'... """ base_color = Color(base_color) if interact: from ipywidgets.widgets import FloatSlider, IntSlider, ColorPicker, interact widgets = dict( x_center = FloatSlider(min=-1.0, max=1.0, step=EPS, value=x_center, description="Real center"), y_center = FloatSlider(min=-1.0, max=1.0, step=EPS, value=y_center, description="Imag center"), image_width = FloatSlider(min=EPS, max=4.0, step=EPS, value=image_width, description="Image width"), max_iteration = IntSlider(min=0, max=600, value=max_iteration, description="Iterations"), pixel_count = IntSlider(min=10, max=600, value=pixel_count, description="Pixels"), level_sep = IntSlider(min=1, max=20, value=iteration_level, description="Color sep"), color_num = IntSlider(min=1, max=100, value=number_of_colors, description="# Colors"), base_color = ColorPicker(value=base_color.html_color(), description="Base color"), ) return interact(**widgets).widget(fast_mandelbrot_plot) return fast_mandelbrot_plot(x_center, y_center, image_width, max_iteration, pixel_count, iteration_level, number_of_colors, base_color)
def select_sample_roi(self): if self.with_or_without_radio_button.value == 'no': label2 = widgets.Label( "-> You chose not to select any ROI! Next step: Normalization") display(label2) return label2 = widgets.Label( "-> Make sure your selection do not overlap your sample!") display(label2) if self.integrated_sample == []: self.calculate_integrated_sample() _integrated_sample = self.integrated_sample [height, width] = np.shape(_integrated_sample) def plot_roi(x_left, y_top, width, height): _ = plt.figure(figsize=(5, 5)) ax_img = plt.subplot(111) ax_img.imshow(_integrated_sample, cmap='viridis', interpolation=None) _rectangle = patches.Rectangle((x_left, y_top), width, height, edgecolor='white', linewidth=2, fill=False) ax_img.add_patch(_rectangle) return [x_left, y_top, width, height] self.roi_selection = widgets.interact( plot_roi, x_left=widgets.IntSlider(min=0, max=width, step=1, value=0, description='X Left', continuous_update=False), y_top=widgets.IntSlider(min=0, max=height, value=0, step=1, description='Y Top', continuous_update=False), width=widgets.IntSlider(min=0, max=width - 1, step=1, value=60, description="Width", continuous_update=False), height=widgets.IntSlider(min=0, max=height - 1, step=1, value=100, description='Height', continuous_update=False))
def display_images(self): _data = self.data _clean_data = self.clean_data _files = self.list_files _full_statistics = self.full_statistics [height, width] = np.shape(self.data[0]) def _plot_images(index, x_left, y_top, width, height): _file_name = _files[index] fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(10, 5), num=os.path.basename(_file_name)) _stat = _full_statistics[index] #plt.title(os.path.basename(_files[index])) cax0 = ax0.imshow(_data[index], cmap='viridis', interpolation=None) ax0.set_title("Before Correction") tmp1 = fig.colorbar(cax0, ax=ax0) # colorbar _rectangle1 = patches.Rectangle((x_left, y_top), width, height, edgecolor='white', linewidth=2, fill=False) ax1.add_patch(_rectangle1) cax1 = ax1.imshow(_clean_data[index], cmap='viridis', interpolation=None) ax1.set_title("After Correction") tmp2 = fig.colorbar(cax1, ax=ax1) # colorbar _rectangle2 = patches.Rectangle((x_left, y_top), width, height, edgecolor='white', linewidth=2, fill=False) ax0.add_patch(_rectangle2) fig.tight_layout() print("STATISTICS of FULL REGION") print("-> Number of pixels corrected: {}".format(_stat.nbr_pixel_modified)) print("-> Total number of pixels: {}".format(_stat.total_pixels)) print("-> Percentage of pixels corrected: {:.3}%".format(_stat.percentage_pixel_modified)) print("") _stat_roi = self.get_statistics_of_roi_cleaned(x_left, y_top, height, width, _data[index]) print("STATISTICS of SELECTED REGION") print("-> Number of pixels corrected: {}".format(_stat_roi.nbr_pixel_modified)) print("-> Total number of pixels: {}".format(_stat_roi.total_pixels)) print("-> Percentage of pixels corrected: {:.3}%".format(_stat_roi.percentage_pixel_modified)) tmp3 = widgets.interact(_plot_images, index=widgets.IntSlider(min=0, max=len(self.list_files) - 1, step=1, value=0, description='File Index', continuous_update=False), x_left=widgets.IntSlider(min=0, max=width - 1, step=1, value=0, description='X Left', continuous_update=False), y_top=widgets.IntSlider(min=0, max=height - 1, value=0, step=1, description='Y Top', continuous_update=False), width=widgets.IntSlider(min=0, max=width - 1, step=1, value=60, description="Width", continuous_update=False), height=widgets.IntSlider(min=0, max=height - 1, step=1, value=100, description='Height', continuous_update=False) )
# In[ ]: def mix_bdfex_2all(alpha, beta, plot=False): res = stab_region(bdf2, (1.-alpha-beta)*ex2+alpha*ex3+beta*ex4, plot=plot); if plot: print("The eigenvalue for BDF/EX-2,3({},{}) is {}".format(alpha, beta, res)) return res # In[ ]: interact(mix_bdfex_23, alpha=.667, beta=.48, plot=True); # In[ ]: interact(mix_bdfex_2all, alpha=.667, beta=.1, plot=True); # We can maximize the stability constraint. The constraint $\alpha \ge 0$ must be added, because $\alpha < 0$ consistently results in instability (I don't know why). # In[ ]: def wrap(x): return -mix_bdfex_23(x[0], x[1]) def accept(f_new, x_new, f_old, x_old): if x_new[0] < 0:
def julia_plot(f=None, **kwds): r""" Plots the Julia set of a given polynomial ``f``. Users can specify whether they would like to display the Mandelbrot side by side with the Julia set with the ``mandelbrot`` argument. If ``f`` is not specified, this method defaults to `f(z) = z^2-1`. The Julia set of a polynomial ``f`` is the set of complex numbers `z` for which the function `f(z)` is bounded under iteration. The Julia set can be visualized by plotting each point in the set in the complex plane. Julia sets are examples of fractals when plotted in the complex plane. ALGORITHM: Let `R_c = \bigl(1 + \sqrt{1 + 4|c|}\bigr)/2` if the polynomial is of the form `f(z) = z^2 + c`; otherwise, let `R_c = 2`. For every `p \in \mathbb{C}`, if `|f^{k}(p)| > R_c` for some `k \geq 0`, then `f^{n}(p) \to \infty`. Let `N` be the maximum number of iterations. Compute the first `N` points on the orbit of `p` under `f`. If for any `k < N`, `|f^{k}(p)| > R_c`, we stop the iteration and assign a color to the point `p` based on how quickly `p` escaped to infinity under iteration of `f`. If `|f^{i}(p)| \leq R_c` for all `i \leq N`, we assume `p` is in the Julia set and assign the point `p` the color black. INPUT: - ``f`` -- input polynomial (optional - default: ``z^2 - 1``). - ``period`` -- list (optional - default: ``None``), returns the Julia set for a random `c` value with the given (formal) cycle structure. - ``mandelbrot`` -- boolean (optional - default: ``True``), when set to ``True``, an image of the Mandelbrot set is appended to the right of the Julia set. - ``point_color`` -- RGB color (optional - default: ``'tomato'``), color of the point `c` in the Mandelbrot set (any valid input for Color). - ``x_center`` -- double (optional - default: ``-1.0``), Real part of center point. - ``y_center`` -- double (optional - default: ``0.0``), Imaginary part of center point. - ``image_width`` -- double (optional - default: ``4.0``), width of image in the complex plane. - ``max_iteration`` -- long (optional - default: ``500``), maximum number of iterations the map `f(z)`. - ``pixel_count`` -- long (optional - default: ``500``), side length of image in number of pixels. - ``base_color`` -- hex color (optional - default: ``'steelblue'``), color used to determine the coloring of set (any valid input for Color). - ``level_sep`` -- long (optional - default: 1), number of iterations between each color level. - ``number_of_colors`` -- long (optional - default: 30), number of colors used to plot image. - ``interact`` -- boolean (optional - default: ``False``), controls whether plot will have interactive functionality. OUTPUT: 24-bit RGB image of the Julia set in the complex plane. .. TODO:: Implement the side-by-side Mandelbrot-Julia plots for general one-parameter families of polynomials. EXAMPLES: The default ``f`` is `z^2 - 1`:: sage: julia_plot() 1001x500px 24-bit RGB image To display only the Julia set, set ``mandelbrot`` to ``False``:: sage: julia_plot(mandelbrot=False) 500x500px 24-bit RGB image :: sage: R.<z> = CC[] sage: f = z^3 - z + 1 sage: julia_plot(f) 500x500px 24-bit RGB image To display an interactive plot of the Julia set in the Notebook, set ``interact`` to ``True``. (This is only implemented for polynomials of the form ``f = z^2 + c``):: sage: julia_plot(interact=True) interactive(children=(FloatSlider(value=-1.0, description=u'Real c'... :: sage: R.<z> = CC[] sage: f = z^2 + 1/2 sage: julia_plot(f,interact=True) interactive(children=(FloatSlider(value=0.5, description=u'Real c'... To return the Julia set of a random `c` value with (formal) cycle structure `(2,3)`, set ``period = [2,3]``:: sage: julia_plot(period=[2,3]) 1001x500px 24-bit RGB image To return all of the Julia sets of `c` values with (formal) cycle structure `(2,3)`:: sage: period = [2,3] # not tested ....: R.<c> = QQ[] ....: P.<x,y> = ProjectiveSpace(R,1) ....: f = DynamicalSystem([x^2+c*y^2, y^2]) ....: L = f.dynatomic_polynomial(period).subs({x:0,y:1}).roots(ring=CC) ....: c_values = [k[0] for k in L] ....: for c in c_values: ....: julia_plot(c) Polynomial maps can be defined over a polynomial ring or a fraction field, so long as ``f`` is polynomial:: sage: R.<z> = CC[] sage: f = z^2 - 1 sage: julia_plot(f) 1001x500px 24-bit RGB image :: sage: R.<z> = CC[] sage: K = R.fraction_field(); z = K.gen() sage: f = z^2-1 sage: julia_plot(f) 1001x500px 24-bit RGB image Interact functionality is not implemented if the polynomial is not of the form `f = z^2 + c`:: sage: R.<z> = CC[] sage: f = z^3 + 1 sage: julia_plot(f, interact=True) Traceback (most recent call last): ... NotImplementedError: The interactive plot is only implemented for ... """ # extract keyword arguments period = kwds.pop("period", None) mandelbrot = kwds.pop("mandelbrot", True) point_color = kwds.pop("point_color", 'tomato') x_center = kwds.pop("x_center", 0.0) y_center = kwds.pop("y_center", 0.0) image_width = kwds.pop("image_width", 4.0) max_iteration = kwds.pop("max_iteration", 500) pixel_count = kwds.pop("pixel_count", 500) base_color = kwds.pop("base_color", 'steelblue') level_sep = kwds.pop("level_sep", 1) number_of_colors = kwds.pop("number_of_colors", 30) interacts = kwds.pop("interact", False) f_is_default_after_all = None if period: # pick a random c with the specified period R = PolynomialRing(CC, 'c') c = R.gen() x, y = ProjectiveSpace(R, 1, 'x,y').gens() F = DynamicalSystem([x**2 + c * y**2, y**2]) L = F.dynatomic_polynomial(period).subs({x: 0, y: 1}).roots(ring=CC) c = L[randint(0, len(L) - 1)][0] base_color = Color(base_color) point_color = Color(point_color) EPS = 0.00001 if f is not None and period is None: # f user-specified and no period given # try to coerce f to live in a polynomial ring S = PolynomialRing(CC, names='z') z = S.gen() try: f_poly = S(f) except TypeError: R = f.parent() if not (R.is_integral_domain() and (CC.is_subring(R) or CDF.is_subring(R))): raise ValueError('Given `f` must be a complex polynomial.') else: raise NotImplementedError( 'Julia sets not implemented for rational functions.') if (f_poly - z * z) in CC: # f is specified and of the form z^2 + c. f_is_default_after_all = True c = f_poly - z * z else: # f is specified and not of the form z^2 + c if interacts: raise NotImplementedError( "The interactive plot is only implemented for " "polynomials of the form f = z^2 + c.") else: return general_julia(f_poly, x_center, y_center, image_width, max_iteration, pixel_count, level_sep, number_of_colors, base_color) # otherwise we can use fast_julia_plot for z^2 + c if f_is_default_after_all or f is None or period is not None: # specify default c = -1 value if f and period were not specified if not f_is_default_after_all and period is None: c = -1 c = CC(c) c_real = c.real() c_imag = c.imag() if interacts: # set widgets from ipywidgets.widgets import FloatSlider, IntSlider, \ ColorPicker, interact widgets = dict( c_real=FloatSlider(min=-2.0, max=2.0, step=EPS, value=c_real, description="Real c"), c_imag=FloatSlider(min=-2.0, max=2.0, step=EPS, value=c_imag, description="Imag c"), x_center=FloatSlider(min=-1.0, max=1.0, step=EPS, value=x_center, description="Real center"), y_center=FloatSlider(min=-1.0, max=1.0, step=EPS, value=y_center, description="Imag center"), image_width=FloatSlider(min=EPS, max=4.0, step=EPS, value=image_width, description="Width"), max_iteration=IntSlider(min=0, max=1000, value=max_iteration, description="Iterations"), pixel_count=IntSlider(min=10, max=1000, value=pixel_count, description="Pixels"), level_sep=IntSlider(min=1, max=20, value=level_sep, description="Color sep"), color_num=IntSlider(min=1, max=100, value=number_of_colors, description="# Colors"), base_color=ColorPicker(value=base_color.html_color(), description="Base color"), ) if mandelbrot: widgets["point_color"] = ColorPicker( value=point_color.html_color(), description="Point color") return interact(**widgets).widget(julia_helper) else: return interact(**widgets).widget(fast_julia_plot) elif mandelbrot: # non-interactive with mandelbrot return julia_helper(c_real, c_imag, x_center, y_center, image_width, max_iteration, pixel_count, level_sep, number_of_colors, base_color, point_color) else: # non-interactive without mandelbrot return fast_julia_plot(c_real, c_imag, x_center, y_center, image_width, max_iteration, pixel_count, level_sep, number_of_colors, base_color)
def make_graph_3(): global X1, X2, Y1, Y2 fig, ax = plt.subplots() plt.xlabel('x') plt.ylabel('y') ax.set_ylim(0, 5) ax.set_xlim(0, 5) ax.set_yticks(np.arange(5)) ax.set_xticks(np.arange(5)) ax.grid(alpha=0.5) X1, X2, Y1, Y2 = 1.5, 1.5, 3.5, 3.5 points, = ax.plot([X1, X2], [Y1, Y2], marker='o', linewidth=0, color='#1f77b4') line, = ax.plot([X1, X2], [Y1, Y2], alpha=0.7) line_x, = ax.plot([X1, X2], [Y1, Y1], ls='--', color='k', alpha=0.5) line_y, = ax.plot([X2, X2], [Y1, Y2], ls='--', color='k', alpha=0.5) def update(): global X1, X2, Y1, Y2 points.set_xdata([X1, X2]) line.set_xdata([X1, X2]) line_x.set_xdata([X1, X2]) line_y.set_xdata([min((Y1, X2), (Y2, X1), key=lambda x: x[0])[1]] * 2) points.set_ydata([Y1, Y2]) line.set_ydata([Y1, Y2]) line_x.set_ydata([min(Y1, Y2)] * 2) line_y.set_ydata([Y1, Y2]) d = ((X2 - X1)**2 + (Y2 - Y1)**2)**0.5 s = '({:.2f} - {:.2f})^2 + ({:.2f} - {:.2f})^2'.format(X2, X1, Y2, Y1) ax.set_title('$d = \sqrt{' + s + '}' + f'={d:.2f}' + '$') def update_x1(x1=1.5): global X1 X1 = x1 update() def update_x2(x2=3.5): global X2 X2 = x2 update() def update_y1(y1=1.5): global Y1 Y1 = y1 update() def update_y2(y2=3.5): global Y2 Y2 = y2 update() interact(update_x1, x1=(0, 5, 0.001)) interact(update_y1, y1=(0, 5, 0.001)) interact(update_x2, x2=(0, 5, 0.001)) interact(update_y2, y2=(0, 5, 0.001))
rotation=0, position=label_position_option, ha='right', bbox=dict(boxstyle='square', fc='w')) # Secondo grafico xx = day_df.index yy = day_df['Pot_dc'] mappable_graph = ax2.scatter(xx, yy, s=20, c=day_df['Tmod'], cmap='plasma') #, edgecolor='k') ax2_irr.scatter(xx, day_df['Irr'], s=5, c='k') #, edgecolor='k') time_span1 = widgets.interact( day_analysis, day=widgets.FloatSlider(value=1, min=1, max=31, step=1), month=widgets.FloatSlider(value=6, min=1, max=12, step=1), year=widgets.FloatSlider(value=2019, min=2016, max=2019, step=1), ) # In[ ]: # # Preparazione dati # * **Imposto il nuovo database:** # In[27]: IV_set = df.copy() IV_set.head(5) # In[28]:
def julia_plot(c=-1, x_center=0.0, y_center=0.0, image_width=4.0, max_iteration=500, pixel_count=500, base_color='steelblue', iteration_level=1, number_of_colors=50, point_color='yellow', interact=False, mandelbrot=True, period=None): r""" Plots the Julia set of a given complex `c` value. Users can specify whether they would like to display the Mandelbrot side by side with the Julia set. The Julia set of a given `c` value is the set of complex numbers for which the function `Q_c(z)=z^2+c` is bounded under iteration. The Julia set can be visualized by plotting each point in the set in the complex plane. Julia sets are examples of fractals when plotted in the complex plane. ALGORITHM: Define the map `Q_c(z) = z^2 + c` for some `c \in \mathbb{C}`. For every `p \in \mathbb{C}`, if `|Q_{c}^{k}(p)| > 2` for some `k \geq 0`, then `Q_{c}^{n}(p) \to \infty`. Let `N` be the maximum number of iterations. Compute the first `N` points on the orbit of `p` under `Q_c`. If for any `k < N`, `|Q_{c}^{k}(p)| > 2`, we stop the iteration and assign a color to the point `p` based on how quickly `p` escaped to infinity under iteration of `Q_c`. If `|Q_{c}^{i}(p)| \leq 2` for all `i \leq N`, we assume `p` is in the Julia set and assign the point `p` the color black. INPUT: - ``c`` -- complex (optional - default: ``-1``), complex point `c` that determines the Julia set. - ``period`` -- list (optional - default: ``None``), returns the Julia set for a random `c` value with the given (formal) cycle structure. - ``mandelbrot`` -- boolean (optional - default: ``True``), when set to ``True``, an image of the Mandelbrot set is appended to the right of the Julia set. - ``point_color`` -- RGB color (optional - default: ``'tomato'``), color of the point `c` in the Mandelbrot set (any valid input for Color). - ``x_center`` -- double (optional - default: ``-1.0``), Real part of center point. - ``y_center`` -- double (optional - default: ``0.0``), Imaginary part of center point. - ``image_width`` -- double (optional - default: ``4.0``), width of image in the complex plane. - ``max_iteration`` -- long (optional - default: ``500``), maximum number of iterations the map `Q_c(z)`. - ``pixel_count`` -- long (optional - default: ``500``), side length of image in number of pixels. - ``base_color`` -- RGB color (optional - default: ``'steelblue'``), color used to determine the coloring of set (any valid input for Color). - ``iteration_level`` -- long (optional - default: 1), number of iterations between each color level. - ``number_of_colors`` -- long (optional - default: 30), number of colors used to plot image. - ``interact`` -- boolean (optional - default: ``False``), controls whether plot will have interactive functionality. OUTPUT: 24-bit RGB image of the Julia set in the complex plane. EXAMPLES:: sage: julia_plot() 1001x500px 24-bit RGB image To display only the Julia set, set ``mandelbrot`` to ``False``:: sage: julia_plot(mandelbrot=False) 500x500px 24-bit RGB image To display an interactive plot of the Julia set in the Notebook, set ``interact`` to ``True``:: sage: julia_plot(interact=True) interactive(children=(FloatSlider(value=-1.0, description=u'Real c'... To return the Julia set of a random `c` value with (formal) cycle structure `(2,3)`, set ``period = [2,3]``:: sage: julia_plot(period=[2,3]) 1001x500px 24-bit RGB image To return all of the Julia sets of `c` values with (formal) cycle structure `(2,3)`:: sage: period = [2,3] # not tested ....: R.<c> = QQ[] ....: P.<x,y> = ProjectiveSpace(R,1) ....: f = DynamicalSystem([x^2+c*y^2, y^2]) ....: L = f.dynatomic_polynomial(period).subs({x:0,y:1}).roots(ring=CC) ....: c_values = [k[0] for k in L] ....: for c in c_values: ....: julia_plot(c) """ if period is not None: R = PolynomialRing(QQ, 'c') c = R.gen() x, y = ProjectiveSpace(R, 1, 'x,y').gens() f = DynamicalSystem([x**2 + c * y**2, y**2]) L = f.dynatomic_polynomial(period).subs({x: 0, y: 1}).roots(ring=CC) c = L[randint(0, len(L) - 1)][0] c = CC(c) c_real = c.real() c_imag = c.imag() base_color = Color(base_color) point_color = Color(point_color) if interact: from ipywidgets.widgets import FloatSlider, IntSlider, ColorPicker, interact widgets = dict( c_real = FloatSlider(min=-2.0, max=2.0, step=EPS, value=c_real, description="Real c"), c_imag = FloatSlider(min=-2.0, max=2.0, step=EPS, value=c_imag, description="Imag c"), x_center = FloatSlider(min=-1.0, max=1.0, step=EPS, value=x_center, description="Real center"), y_center = FloatSlider(min=-1.0, max=1.0, step=EPS, value=y_center, description="Imag center"), image_width = FloatSlider(min=EPS, max=4.0, step=EPS, value=image_width, description="Image width"), max_iteration = IntSlider(min=0, max=600, value=max_iteration, description="Iterations"), pixel_count = IntSlider(min=10, max=600, value=pixel_count, description="Pixels"), level_sep = IntSlider(min=1, max=20, value=iteration_level, description="Color sep"), color_num = IntSlider(min=1, max=100, value=number_of_colors, description="# Colors"), base_color = ColorPicker(value=base_color.html_color(), description="Base color"), ) if mandelbrot: widgets["point_color"] = ColorPicker(value=point_color.html_color(), description="Point color") return interact(**widgets).widget(julia_helper) else: return interact(**widgets).widget(fast_julia_plot) if mandelbrot: return julia_helper(c_real, c_imag, x_center, y_center, image_width, max_iteration, pixel_count, iteration_level, number_of_colors, base_color, point_color) else: return fast_julia_plot(c_real, c_imag, x_center, y_center, image_width, max_iteration, pixel_count, iteration_level, number_of_colors, base_color)