def test_append_display_data(): output = Output() # Try appending a Markdown object. output.append_display_data(Markdown("# snakes!")) expected = ({ 'output_type': 'display_data', 'data': { 'text/plain': '<IPython.core.display.Markdown object>', 'text/markdown': '# snakes!' }, 'metadata': {} }, ) assert output.outputs == expected, repr(output.outputs) # Now try appending an Image. image_data = b"foobar" image_data_b64 = image_data if sys.version_info[0] < 3 else 'Zm9vYmFy\n' output.append_display_data(Image(image_data, width=123, height=456)) expected += ({ 'output_type': 'display_data', 'data': { 'image/png': image_data_b64, 'text/plain': '<IPython.core.display.Image object>' }, 'metadata': { 'image/png': { 'width': 123, 'height': 456 } } }, ) assert output.outputs == expected, repr(output.outputs)
class AboutTab(object): def __init__(self): # self.tab = Output(layout={'height': '600px'}) # self.tab = Output(layout={'height': '500px'}) # self.tab = Output() self.tab = Output(layout={'height': 'auto'}) self.tab.append_display_data(HTML(filename='doc/about.html'))
class TerminalTab(object): def __init__(self): # self.tab = Output(layout={'height': '600px'}) self.tab = Output(layout={'height': 'auto'}) self.tab.append_display_data(HTML(filename='doc/about.html')) from ipywidgets import HTML, Tab, Layout
def remove_phase(self): # Remove phase information s_phaseless = np.fft.ifft(np.abs(np.fft.fft(self.s))).real plt.close('all') plt.figure('Removed phase', figsize=(8, 2.5)) plt.plot(np.linspace(0, len(self.s) / self.SF, len(self.s)), self.s, label='Original') plt.plot(np.linspace(0, len(s_phaseless) / self.SF, len(s_phaseless)), s_phaseless, label='Removed phase', alpha=0.7) plt.title('Sound wave') plt.xlabel('Time [s]') plt.tight_layout() plt.legend() plt.show() # Create audio widgets orig_sound = Output(layout={'width': '320px', 'height': '60px'}) orig_sound.append_display_data( IPython.display.Audio(self.s, rate=self.SF)) filt_sound = Output(layout={'width': '320px', 'height': '60px'}) filt_sound.append_display_data( IPython.display.Audio(s_phaseless, rate=self.SF)) display( HBox([ widgets.HTML('<h3>Original: </h3>'), orig_sound, widgets.HTML('<h3>Removed phase: </h3>'), filt_sound ]))
def load_audio_frame(filename, frame, context=1): output = Output(layout={ 'width': '100%', 'align-items': 'center', 'display': 'flex' }) output.append_display_data(load_audio_frame_raw(filename, frame, context)) return output
class AboutTab(object): def __init__(self): # self.tab = Output(layout={'height': '900px'}) # self.tab = Output(layout={height=’85%’,min_height=’350px’}) self.tab = Output(layout={'height': 'auto'}) # WHY? -good works; -bad, doesn't # self.tab.append_display_data(HTML(filename='doc/about-good.html')) self.tab.append_display_data(HTML(filename='doc/about-bad.html'))
class CodeTab(object): def __init__(self): # self.tab = Output(layout={'height': '600px'}) self.tab = Output(layout={'height': 'auto'}) # self.tab.append_display_data(HTML(filename='doc/code.html')) custom_code_file = open("src/custom_modules/custom.cpp", "r") code_str = custom_code_file.read() # print(code_str) self.tab.append_display_data( HTML('<textarea readonly rows="20" cols="110">' + code_str + '</textarea>'))
class AboutTab(object): def __init__(self): # self.tab = Output(layout={'height': '900px'}) # self.tab = Output(layout={height=’85%’,min_height=’350px’}) # self.background = Output(layout={'height': 'auto'}) # self.legend = Output(layout={'height': 'auto'}) self.tab = Output(layout={'height': 'auto'}) # self.tab.append_display_data(HTML(filename='doc/about-good.html')) # self.tab.append_display_data(HTML(filename='doc/about-bad.html')) # self.background.append_display_data(HTML(filename='doc/about_background.html')) # self.legend.append_display_data(HTML(filename='doc/about_legend.html')) self.tab.append_display_data(HTML(filename='doc/about.html'))
def modify_phase(self): # Create phase modification # ph = np.random.rand(len(self.s) // 2) * 2*np.pi * 1j # ph = np.concatenate(([0], ph, -ph[-2::-1])) ph = np.sin(np.linspace(0, 25000 * np.pi, len(self.s))) # Add the phase offset s_random_phase = np.fft.ifft(np.fft.fft(self.s) * np.exp(ph)).real plt.close('all') plt.figure('Modified phase', figsize=(8, 2.5)) plt.plot(np.linspace(0, len(self.s) / self.SF, len(self.s)), self.s, label='Original') plt.plot(np.linspace(0, len(s_random_phase) / self.SF, len(s_random_phase)), s_random_phase, label='Random phase', alpha=0.7) plt.title('Sound wave') plt.xlabel('Time [s]') plt.tight_layout() plt.legend() plt.show() # Create audio widgets orig_sound = Output(layout={'width': '320px', 'height': '60px'}) orig_sound.append_display_data( IPython.display.Audio(self.s, rate=self.SF)) filt_sound = Output(layout={'width': '320px', 'height': '60px'}) filt_sound.append_display_data( IPython.display.Audio(s_random_phase, rate=self.SF)) display( HBox([ widgets.HTML('<h3>Original: </h3>'), orig_sound, widgets.HTML('<h3>Random phase: </h3>'), filt_sound ]))
def test_append_display_data(): output = Output() # Try appending a Markdown object. output.append_display_data(Markdown("# snakes!")) expected = ( { 'output_type': 'display_data', 'data': { 'text/plain': '<IPython.core.display.Markdown object>', 'text/markdown': '# snakes!' }, 'metadata': {} }, ) assert output.outputs == expected, repr(output.outputs) # Now try appending an Image. image_data = b"foobar" image_data_b64 = image_data if sys.version_info[0] < 3 else 'Zm9vYmFy\n' output.append_display_data(Image(image_data, width=123, height=456)) expected += ( { 'output_type': 'display_data', 'data': { 'image/png': image_data_b64, 'text/plain': '<IPython.core.display.Image object>' }, 'metadata': { 'image/png': { 'width': 123, 'height': 456 } } }, ) assert output.outputs == expected, repr(output.outputs)
class FuryTab(object): def __init__(self): self.tab = Output(layout={'height': '650px'}) #self.tab = Output(layout={'height': 'auto'}) #self.tab.append_display_data(HTML(filename='doc/fury_client.html')) #self.tab.append_display_data(Javascript( # filename='doc/FuryWebClient.js')) html = \ """ <iframe src='http://fury.grg.sice.indiana.edu/tumor/' height='650' width='50%'> </iframe> """ html = \ """ <iframe src='doc/fury_client.html' height='650' width='50%'> </iframe> """ html = \ """ <iframe src='doc/fury_client.html' height='650' width='50%' align="left" id="fury_frame"> </iframe> <iframe src='https://fury-server.hubzero.org/tumor/' height='650' width='50%' align="right" id="nh_frame"> </iframe> """ html = \ """ <iframe src='https://fury-server.hubzero.org/tumor/' height='650' width='50%' id="nh_frame" style="-webkit-transform:scale(0.8);-moz-transform-scale(0.8); -moz-transform-origin: top left; -webkit-transform-origin: top left; -o-transform-origin: top left; -ms-transform-origin: top left; transform-origin: top left;"> </iframe> """ # Integrated client does not work on Chrome. # html = \ # """ # <iframe src='doc/fury_client.html' height='650' width='50%' # align="left" id="nh_frame"> # </iframe> # """ self.tab.append_display_data(HTML(html)) js = \ """ element.css({backgroundColor: "gray", margin: "0px", padding: "0px"}); element.height(100); element.width(100); element.html( $( "<div id='fury'></div>" ) ); const newScriptTag = document.createElement('script'); newScriptTag.type = 'text/javascript'; newScriptTag.src = 'doc/FuryWebClient.js'; document.body.appendChild(newScriptTag); """ # self.tab.append_display_data(Javascript(js)) # self.tab.append_display_data(Javascript(filename='doc/FuryWebClient.js')) def reset(self): """Send Event to clear the visualization.""" data = {'function': 'reset', 'folder': '', 'filename': ''} self.__send(data) def send_data(self, folder, filename): """Send Folder and filename to server.""" data = { 'function': 'update_view', 'folder': folder, 'filename': filename } self.__send(data) def __send(self, data): """Send information to Server via IFrame.""" s_data = json.dumps(data) # Send to both server js_call = \ """ var my_iframe = document.getElementById('fury_frame'); var nanohub_iframe = document.getElementById('nh_frame'); my_iframe.contentWindow.postMessage('{0}', '*'); nanohub_iframe.contentWindow.postMessage('{0}', '*'); """.format(s_data) # send to nanohub only js_call = \ """ var nanohub_iframe = document.getElementById('nh_frame'); nanohub_iframe.contentWindow.postMessage({0}, '*'); """.format(s_data) print(js_call) display(Javascript(js_call))
class AboutTab(object): def __init__(self): self.tab = Output(layout={'height': '350px'}) # Doesn't change the html window! # self.tab = Output(layout={'height': 'auto'}) self.tab.append_display_data(HTML(filename='doc/about.html'))
class InputSequence: """ Helper class for creating 'input sequences' i.e. a sequency of widgets that you fill in, and then click confirm. Parameters ---------- done_action : callable function to call when confirm is clicked. Each child (see next parameter!) is passed to done_action *children : ipywidget widgets to display in order. When confirm clicked, these widget objects are passed to done_action. """ stored_traits = ['value', 'disabled'] def __init__(self, done_action: Callable, *children: DOMWidget): self.done_action = done_action self.children = children self.initial_traits = {} self.confirm = Button(description="Confirm", disabled=True) self.new = Button(description="New") self.status = Output() self.output = Output(layout=Layout(width='auto')) self.confirm.on_click(self._do_done) self.new.on_click(self.reset) for child in self.children: child.layout.width = 'auto' child.style.description_width = '10%' self.initial_traits[child] = {k: v for k, v in child.get_state().items() if k in self.stored_traits} child.observe(self.child_updated, 'value') def reset(self, change): """ Reset the state of the InputSequence. Called when `new` button clicked. """ for child in self.children: child.open() traits = self.initial_traits[child] for k, v in traits.items(): setattr(child, k, v) self.confirm.disabled = True def child_updated(self, change): """ Called when a child is updated, meant to stop you pressing confirm until you've entered something into every widget... don't think it actually works tho! """ if all(map(lambda val: val is not None, self.children)): self.confirm.disabled = False def as_widget(self) -> DOMWidget: """ Build `self` into `ipywidget` Returns ------- widget : DOMWidget widget form of self. """ return VBox((*self.children, HBox((self.confirm, self.new)), self.status)) def display(self): """ Displays `self.as_widget()`. Returns ------- output : Output output widget which we displayed into... """ self.output.append_display_data(self.as_widget()) return self.output def _do_done(self, pressed): """ Internal function called when confirm clicked. """ values = [] self.confirm.disabled = True for child in self.children: child.disabled = True values.append(child.value) with self.output: self.done_action(*values)
class Filter_Demo(): def __init__(self, filename, filter_method='butter'): self.out = Output(layout={'width': '980px', 'height': '400px'}) self.axs = [] self.fill_color = 'lightgreen' self.filter_method = filter_method # Read the audio signal from file self.SF, self.s = wavfile.read(filename) self.t = np.linspace(0, len(self.s) / self.SF, len(self.s)) # Generate Fourier Transform of audio signal s_FT = np.abs(np.fft.fftshift(np.fft.fft(self.s))) self.s_FT = s_FT / s_FT.max() self.w_FT = np.linspace(-self.SF // 2, self.SF // 2, len(self.s)) # Filter types self.filter_types = { 'lowpass': 0, 'highpass': 1, 'bandpass': 2, 'bandstop': 3, 'notch': 4 } self.f_crit = self.SF // 6 self.filter = list(self.filter_types.keys())[0] self.filter_idx = self.filter_types[self.filter] self.s_filtered = None self.h = None self.w = None # Compute the initial filter self.update_filter(init=True) # Inizializate the figure self.init_figure() # Add audio players self.play_orig = Output(layout={'width': '320px', 'height': '60px'}) self.play_filt = Output(layout={'width': '320px', 'height': '60px'}) self.play_orig.append_display_data( IPython.display.Audio(self.s, rate=self.SF)) self.play_filt.append_display_data( IPython.display.Audio(self.s_filtered, rate=self.SF)) # Descriptive text self.text_orig = widgets.HTML(value="<h3>Original</h3>") self.text_filt = widgets.HTML(value="<h3>Filtered</h3>") # Add frequency sliders self.f0_slider = widgets.IntSlider( value=self.SF // 6, min=50, max=self.SF // 2 - 300, description='$\;f_0\,[Hz]$:', continuous_update=False, style={'description_width': 'initial'}) self.f0_slider.observe(self.f0_callback, names='value') self.f1_slider = widgets.IntSlider( value=2 * self.SF // 6, min=50, max=self.SF // 2 - 300, description='$\;f_1\,[Hz]$:', continuous_update=False, disabled=True, style={'description_width': 'initial'}) self.f1_slider.observe(self.f1_callback, names='value') self.apply_button = widgets.Button(description='Apply filter', layout=Layout(width='95%')) self.apply_button.on_click(self.apply_filter_callback) # Add dropdown menu for filter type self.filter_menu = widgets.Dropdown(options=self.filter_types.keys(), value=self.filter, description='Filter type:', layout=Layout(width='max-content')) self.filter_menu.observe(self.menu_callback, names='value') # Add dropdown menu for filter method self.method_menu = widgets.Dropdown( options=['butter', 'ellip', 'cheby'], value=self.filter_method, description='Filter method:', layout=Layout(width='max-content')) self.method_menu.observe(self.method_callback, names='value') display( VBox([ self.out, HBox([ VBox([self.filter_menu, self.method_menu]), VBox([self.f0_slider, self.f1_slider, self.apply_button]), VBox([ HBox([self.text_orig, self.play_orig]), HBox([self.text_filt, self.play_filt]) ]) ]) ])) plt.tight_layout(pad=0.1, w_pad=1.0, h_pad=0.1) self.apply_filter_callback() def init_figure(self): with self.out: self.fig = plt.figure('Types of filters demo', figsize=(8.5, 3.5)) self.gs = self.fig.add_gridspec(2, 2) # Plot the FT self.axs.append(self.fig.add_subplot(self.gs[:, 0])) self.axs[0].set_title("Filter and signal spectrum modulus") self.axs[0].plot(self.w_FT, self.s_FT, color='blue', linewidth=0.2) self.axs[0].plot(self.w, self.h, color=self.fill_color, linewidth=0.7) self.axs[0].set_xlabel('f [Hz]') self.axs[0].fill(self.w, self.h, facecolor=self.fill_color) self.axs[0].legend(['Signal', 'Filter'], loc='upper right') # Plot the original waveform self.axs.append(self.fig.add_subplot(self.gs[0, -1])) self.axs[1].set_title('Original signal') self.axs[1].plot(self.t, self.s, color='blue', linewidth=0.2) self.axs[1].set_xlabel('t [s]') self.axs[1].set_xlim([np.min(self.t), np.max(self.t)]) self.axs[1].set_ylim([np.min(self.s), np.max(self.s)]) self.axs[1].get_yaxis().set_visible(False) # Plot the filtered waveform self.axs.append(self.fig.add_subplot(self.gs[1, -1])) self.axs[2].set_title("Filtered signal") self.axs[2].plot(self.t, self.s_filtered, color='blue', linewidth=0.2) self.axs[2].set_xlabel('t [s]') self.axs[2].set_xlim([np.min(self.t), np.max(self.t)]) self.axs[2].set_ylim([np.min(self.s), np.max(self.s)]) self.axs[2].get_yaxis().set_visible(False) plt.show() def update_filter(self, init=False): # Ensure that the lower frequency is first f_crit = np.sort( self.f_crit) if np.ndim(self.f_crit) > 0 else self.f_crit # Constructing the filter if self.filter == 'notch': b, a = signal.iirnotch(w0=f_crit, Q=30, fs=self.SF) else: if self.filter_method == 'ellip': # Elliptic b, a = signal.ellip(N=5, rp=0.01, rs=100, Wn=f_crit, btype=self.filter, fs=self.SF) elif self.filter_method == 'cheby': # Chebychev b, a = signal.cheby1(N=5, rp=0.01, Wn=f_crit, btype=self.filter, fs=self.SF) else: # Butterworth b, a = signal.butter(N=5, Wn=f_crit, btype=self.filter, fs=self.SF) # Frequency response w, h = signal.freqz(b, a, whole=True, fs=self.SF) self.h = np.abs(np.fft.fftshift(h)) self.w = w - self.SF // 2 # Filtering self.s_filtered = signal.lfilter(b, a, self.s) if not init: self.axs[0].lines[1].set_data(self.w, self.h) x_lim = self.axs[0].get_xlim() y_lim = self.axs[0].get_ylim() # Clear the fill by over-filling with white self.axs[0].fill([-self.SF, -self.SF + 1, self.SF - 1, self.SF], [-1, 2, 2, -1], facecolor='white') # Create new fill if self.filter_idx % 2 == 1 or self.filter_idx == 4: self.axs[0].fill(self.w, np.concatenate([[0], self.h[1:-1], [0]]), facecolor=self.fill_color) else: self.axs[0].fill(self.w, self.h, facecolor=self.fill_color) self.axs[0].set_xlim(x_lim) self.axs[0].set_ylim(y_lim) def f0_callback(self, value): if self.filter_idx < 2 or self.filter_idx == 4: self.f_crit = value['new'] else: self.f_crit[0] = value['new'] self.update_filter() def f1_callback(self, value): if self.filter_idx > 1 and self.filter_idx != 4: self.f_crit[1] = value['new'] self.update_filter() def apply_filter_callback(self, value=None): self.axs[2].lines[0].set_data(self.t, self.s_filtered) self.play_filt.clear_output() self.play_filt.append_display_data( IPython.display.Audio(self.s_filtered, rate=self.SF)) def menu_callback(self, value): self.filter = value['new'] self.filter_idx = self.filter_types[self.filter] if self.filter_idx < 2 or self.filter_idx == 4: self.f1_slider.disabled = True self.f_crit = self.f0_slider.value else: self.f1_slider.disabled = False self.f_crit = [self.f0_slider.value, self.f1_slider.value] # In case of notch filter, disable the filter method dropdown menu if self.filter_idx == 4: self.method_menu.disabled = True else: self.method_menu.disabled = False self.update_filter() def method_callback(self, value): self.filter_method = value['new'] self.update_filter()