def improved_euler_example():

    col_layout = Layout(display='flex',
                        flex_flow='row-wrap',
                        width="90%",
                        justify_content='center',
                        align_items='stretch')

    items = [
        FloatSlider(value=7.00,
                    description='steps',
                    min=0.25,
                    max=9,
                    step=0.25),
        Checkbox(False, description='Euler')
    ]

    hbox = HBox(items, layout=col_layout)

    improved_euler_step = improved_euler_step_adhoc

    w = interactive(improved_euler_step, step=items[0], euler=items[1])

    hbox.on_displayed(improved_euler_step(step=7.00, euler=False))
    display(hbox)
def euler_example():

    col_layout = Layout(display='flex',
                        flex_flow='row-wrap',
                        width="90%",
                        justify_content='space-around',
                        align_items='stretch')

    items = [
        FloatSlider(value=0.5, description='steps', min=0.5, max=10, step=0.5),
        FloatSlider(value=0.1, description='$h$', min=0.02, max=0.2, step=0.02)
    ]

    hbox = HBox(items, layout=col_layout)

    w = interactive(euler_step, step=items[0], h=items[1])

    hbox.on_displayed(euler_step(step=0.5, h=0.1))
    display(hbox)
Beispiel #3
0
class SoundPlotter3:
    def __init__(self, recorder=None, limits=(0, 100), log_y=False):
        self.limits = limits
        self.log_y = log_y

        # Default values
        if recorder is None:
            self.rate = 44100              # sampling rate (Hz)
            self.seconds = 1
            self.noframes = int((self.rate * self.seconds) / self.framesize)  # number of frames needed
            sound = 2**13 * np.random.rand(NOFRAMES * FRAMESIZE) - 2**13/2
        self.sound = recorder.sound
        self.rate = recorder.rate
        
        # signal length
        self.n = len(self.sound)
        self.midpoint = int(self.n / 2)
        
        # slider names
        names = ['zoom', 'location']
        
        # Make widgets
        self.widgets = [
            FloatSlider(
                min=limits[0],
                max=limits[1],
                step=0.1,
                description=names[idx],
                disabled=False,
                continuous_update=False,
                orientation='horizontal',
                readout=True,
                readout_format='.1f',
            )
            for idx in range(2)
        ]


        # Make widget box
        self.box = HBox(self.widgets)

        # Set fields
        self.fig = self.ax1 = None

        # Make figure when widgets are shown
        self.box.on_displayed(self.plot_function)

        
        # Make widgets pass data to plotting function
        for widget in self.widgets:
            widget.observe(self.plot_function)

    def plot_function(self, _=None):

        # Initialize figure
        if self.ax1 is None:
            self.fig, (self.ax1, self.ax2, self.ax3) = plt.subplots(3, 1)
        else:
            self.ax1.cla()
            self.ax2.cla()
            self.ax3.cla()
            # self.cb.remove()
            
        ############################
        # Window size and location #
        ############################
            
        # Change slider values to percentages
        val0 = self.widgets[0].value / 100
        val1 = self.widgets[1].value / 100
            
        # Window size, can go from full signal to 2**9
        # if slider is at 0, full signal
        window_size = self.n - int((self.n - 2**9) * val0)
        
        # Window location, depending on slider an window size
        # if slider is at 0, location is far left
        window_location = int(window_size / 2) + int((self.n - window_size) * val1)
        
        xmin_sample = window_location - int(window_size / 2)
        xmax_sample = window_location + int(window_size / 2)
        
        # from samples to milli seconds
        xmin = (xmin_sample / self.rate) * 1000  
        xmax = (xmax_sample / self.rate) * 1000
        
        ############################
        # Signals                  #
        ############################
        
        s = self.sound
        f, fft = signal.periodogram(self.sound[xmin_sample: xmax_sample], self.rate, scaling='spectrum')
        
        ############################
        # Plot settings            #
        ############################
            
        # Y limit
        ylim = np.max(np.abs(self.sound)) 

        # Set axes
        self.ax1.set_ylim(-ylim, ylim)

        # Title and labels
        self.ax1.set_title("Sound, window size {0:4d} samples".format(window_size))
        self.ax1.set_xlabel('Time [ms]')
        self.ax1.set_ylabel('Amplitude')
        self.ax1.set_xlim(0, (self.n / self.rate) * 1000)
        
        self.ax2.set_xlabel('Frequency [Hz]')
        self.ax2.set_ylabel('Power')
        # self.ax2.yaxis.set_visible(False)
        self.ax2.set_title('Frequency spectrum of window')
        self.ax2.set_xlim(f[0], f[-1])
        
        self.ax3.set_ylabel('Frequency [Hz]')
        self.ax3.set_xlabel('Time [ms]')
        self.ax3.set_title('Frequency spectrum of window, shown as colors')
        
        # Plot
        self.ax1.plot(np.linspace(0, (self.n / self.rate) * 1000, self.n), s, linestyle='-') 
        self.ax1.plot([xmin, xmin], [-ylim, ylim], 'orange')
        self.ax1.plot([xmax, xmax], [-ylim, ylim], 'orange')
        self.ax1.plot([xmin, xmax], [-ylim, -ylim], 'orange')
        self.ax1.plot([xmin, xmax], [ylim, ylim], 'orange')
        
        if self.log_y:
            self.ax2.semilogy(f, fft)
            
            spec = np.zeros((len(fft), self.n))
            spec[:, xmin_sample:xmin_sample + window_size] = np.asarray([fft] * window_size).transpose()
            extent = (0, (self.n / self.rate) * 1000, f[-1], f[0])
            im = self.ax3.imshow(spec, aspect='auto', extent=extent,
                    cmap = 'jet', norm = LogNorm(vmin=10**-12,vmax=10**-6))
            plt.gca().invert_yaxis()
            
            # make sure axis labels and titles do not overlap
            plt.tight_layout()
            
        else:
            self.ax2.plot(f, fft)
            
            spec = np.zeros((len(fft), self.n))
            spec[:, xmin_sample:xmin_sample + window_size] = np.asarray([fft] * window_size).transpose()
            extent = (0, (self.n / self.rate) * 1000, f[-1], f[0])
            im = self.ax3.imshow(spec, aspect='auto', extent=extent,
                    cmap = 'jet', norm = LogNorm(vmin=10**-12,vmax=10**-6))
            plt.gca().invert_yaxis()

            # make sure axis labels and titles do not overlap
            plt.tight_layout()
        
        # self.cb = self.fig.colorbar(im, ax=[self.ax3])
            
    def start(self):
        return self.box
Beispiel #4
0
class SoundPlotter:
    def __init__(self, recorder=None, limits=(1, 100)):
        self.limits = limits

        # Default values
        if recorder is None:
            self.rate = 44100              
            self.framesize = 2**13         
            self.seconds = 1
            self.noframes = int((self.rate * self.seconds) / self.framesize)  # number of frames needed
            self.sound = 2**13 * np.random.rand(NOFRAMES * FRAMESIZE) - 2**13/2
        else:
            self.sound = recorder.sound
            self.rate = recorder.rate
        
        # signal length
        self.n = len(self.sound)
        
        # slider names
        names = ['window zoom', 'location']
        
        # Make widgets
        self.widgets = [
            FloatSlider(
                min=limits[0],
                max=limits[1],
                step=0.1,
                description=names[idx],
                disabled=False,
                continuous_update=False,
                orientation='horizontal',
                readout=True,
                readout_format='.1f',
            )
            for idx in range(2)
        ]

        # Make widget box
        self.box = HBox(self.widgets)

        # Set fields
        self.fig = self.ax = None

        # Make figure when widgets are shown
        self.box.on_displayed(self.plot_function)
        
        # Make widgets pass data to plotting function
        for widget in self.widgets:
            widget.observe(self.plot_function)

    def plot_function(self, _=None):

        # Initialize figure
        if self.ax is None:
            self.fig = plt.figure()
            self.ax = plt.gca()
        else:
            self.ax.cla()
            
        # Chage slider values to percentages
        val0 = self.widgets[0].value / 100
        val1 = self.widgets[1].value / 100
            
        # Window size, can go from full signal to 2**9
        # if slider is at 1, full signal
        window_size = self.n - int((self.n - 2**7) * val0)
        
        # Window location, depending on slider an window size
        # if slider is at 1, location is far left
        window_location = int(window_size / 2) + int((self.n - window_size) * val1)
            
        # Find relevant zoom
        xmin = window_location - int(window_size / 2)
        xmax = window_location + int(window_size / 2)
        ylim = np.max(np.abs(self.sound[xmin:xmax]))

        # Set axes
        # self.ax.set_xlim(xmin/RATE, xmax/RATE)
        self.ax.set_ylim(-ylim, ylim)

        # Title and labels
        self.ax.set_title("Sound")
        self.ax.set_xlabel('Time [ms]')
        
        # Plot 
        s = self.sound[xmin: xmax]
        plotrange = xmax - xmin
        if plotrange < 2**11:
            # plot with markers
            self.ax.plot(np.linspace(0, (len(s)/self.rate) * 1000, len(s)), s, linestyle='-', marker='o', markersize=2)
        else:
            # plot without markers
            self.ax.plot(np.linspace(0, (len(s)/self.rate) * 1000, len(s)), s)
            
    def start(self):
        return self.box
class ProjectionPlotter:
    def __init__(self, starting_values=None, limits=(-3.0, 5.0), linewidth=3):
        self.linewidth = linewidth
        self.starting_values = starting_values
        self.limits = limits

        # Default values
        if starting_values is None:
            starting_values = [[1, 2], [3, 1]]

        # Make widgets
        self.widgets = [
            FloatSlider(
                value=val,
                min=limits[0],
                max=limits[1],
                step=0.1,
                description='${}_{{{}}}$'.format(["v", "w"][nr], d),
                disabled=False,
                continuous_update=True,
                orientation='vertical',
                readout=True,
                readout_format='.1f',
            ) for nr, vector in enumerate(starting_values)
            for d, val in enumerate(vector)
        ]

        # Make widget box
        self.box = HBox(self.widgets)

        # Set fields
        self.fig = self.ax = None

        # Make figure when widgets are shown
        self.box.on_displayed(self.plot_function)

        # Make widgets pass data to plotting function
        for widget in self.widgets:
            widget.observe(self.plot_function)

    def plot_function(self, _=None):
        v1 = np.array([self.widgets[0].value, self.widgets[1].value])
        v2 = np.array([self.widgets[2].value, self.widgets[3].value])

        # Try to do projection
        with warnings.catch_warnings(record=True) as warn:
            warnings.simplefilter("always")
            projection = v1.dot(v2) * v2 / v2.dot(v2)

            # Check if we succeeded
            if len(warn) > 0 and issubclass(warn[-1].category, RuntimeWarning):
                projection = np.array([0, 0])

        # Initialize figure
        if self.ax is None:
            self.fig = plt.figure()
            self.ax = plt.gca()
        else:
            self.ax.cla()

        # Range of plot
        plot_range = self.limits[1] - self.limits[0]

        # Arrow settings
        arrow_settings = [
            (v1, "$v$", "b", self.linewidth),
            (v2, "$w$", "k", self.linewidth),
            (projection, "$p$", "g", self.linewidth),
        ]

        # Make arrows
        arrows = []
        names = []
        for vector, name, color, linewidth in arrow_settings:
            if sum([abs(val) for val in vector]) >= 0.1:
                arrows.append(
                    self.ax.arrow(
                        0,
                        0,
                        vector[0],
                        vector[1],
                        head_width=0.02 * plot_range,
                        head_length=0.03 * plot_range,
                        fc=color,
                        ec=color,
                        linewidth=linewidth,
                    ))
                arrows[-1].set_capstyle('round')
                names.append(name)

        # Set axes
        self.ax.set_xlim(*self.limits)
        self.ax.set_ylim(*self.limits)
        self.ax.set_aspect("equal")

        # Title and legend
        self.ax.set_title("Projections")
        self.ax.legend(arrows, names, loc="lower left")

    def start(self):
        return self.box