def test_ignore_type(): warnings.simplefilter("error") with ignore_warning(category=UserWarning): warnsA() warnsC() with ignore_warning(category=DeprecationWarning): warnsB()
def test_ignore_full_message(): warnings.simplefilter("error") with ignore_warning(message="Warning A!"): warnsA() with ignore_warning(message="Warning B!"): warnsB() with ignore_warning(message="Warning C!"): warnsC()
def test_ignore_type(): with all_warnings(): warnings.simplefilter("error") with ignore_warning(category=UserWarning): warnsA() warnsC() with ignore_warning(category=DeprecationWarning): warnsB()
def test_ignore_full_message(): with all_warnings(): warnings.simplefilter("error") with ignore_warning(message="Warning A!"): warnsA() with ignore_warning(message="Warning B!"): warnsB() with ignore_warning(message="Warning C!"): warnsC()
def update(self, force_replot=False, render_figure=True): """Update the current spectrum figure""" if force_replot is True: self.close() self.plot(data_function_kwargs=self.data_function_kwargs, norm=self.norm) ydata = self._get_data() old_xaxis = self.line.get_xdata() if len(old_xaxis) != self.axis.size or \ np.any(np.not_equal(old_xaxis, self.axis.axis)): self.line.set_data(self.axis.axis, ydata) else: self.line.set_ydata(ydata) if 'x' in self.autoscale: self.ax.set_xlim(self.axis.axis[0], self.axis.axis[-1]) if 'v' in self.autoscale: self.ax.relim() y1, y2 = np.searchsorted(self.axis.axis, self.ax.get_xbound()) y2 += 2 y1, y2 = np.clip((y1, y2), 0, len(ydata - 1)) clipped_ydata = ydata[y1:y2] with ignore_warning(category=RuntimeWarning): # In case of "All-NaN slices" y_max, y_min = (np.nanmax(clipped_ydata), np.nanmin(clipped_ydata)) if self._plot_imag: # Add real plot yreal = self._get_data(real_part=True) clipped_yreal = yreal[y1:y2] with ignore_warning(category=RuntimeWarning): # In case of "All-NaN slices" y_min = min(y_min, np.nanmin(clipped_yreal)) y_max = max(y_max, np.nanmin(clipped_yreal)) if y_min == y_max: # To avoid matplotlib UserWarning when calling `set_ylim` y_min, y_max = y_min - 0.1, y_max + 0.1 if not np.isfinite(y_min): y_min = None # data are -inf or all NaN if not np.isfinite(y_max): y_max = None # data are inf or all NaN self.ax.set_ylim(y_min, y_max) if self.plot_indices is True: self.text.set_text(self.axes_manager.indices) if render_figure: if self.ax.figure.canvas.supports_blit: self.ax.hspy_fig._update_animated() else: self.ax.figure.canvas.draw_idle()
def test_ignore_regex_message(): with all_warnings(): warnings.simplefilter("error") with ignore_warning(message="Warning .?!"): warnsA() warnsB() warnsC()
def _calculate_vmin_max(self, data, auto_contrast=False, vmin=None, vmax=None): # Calculate vmin and vmax using `utils.contrast_stretching` when: # - auto_contrast is True # - self.vmin or self.vmax is of tpye str if (auto_contrast and (isinstance(self.vmin, str) or isinstance(self.vmax, str))): with ignore_warning(category=RuntimeWarning): # In case of "All-NaN slices" vmin, vmax = utils.contrast_stretching(data, self.vmin, self.vmax) else: vmin, vmax = self._vmin_numeric, self._vmax_numeric # provided vmin, vmax override the calculated value if isinstance(vmin, (int, float)): vmin = vmin if isinstance(vmax, (int, float)): vmax = vmax if vmin == np.nan: vmin = None if vmax == np.nan: vmax = None return vmin, vmax
def test_ignore_partial_message(): with all_warnings(): warnings.simplefilter("error") with ignore_warning(message="Warning"): warnsA() warnsB() warnsC()
def test_quant_zeros(self): intens = np.array([[0.5, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0], [0.5, 0.0, 0.0]]).T with ignore_warning(message="divide by zero encountered", category=RuntimeWarning): quant = utils_eds.quantification_cliff_lorimer(intens, [1, 1, 3]).T np.testing.assert_allclose( quant, np.array([[0.2, 0.2, 0.6], [0.0, 0.25, 0.75], [0.25, 0.0, 0.75], [0.5, 0.5, 0.0], [1.0, 0.0, 0.0]]) )
def test_ignore_type_fails(): warnings.simplefilter("error") with ignore_warning(category=UserWarning): try: warnsB() except DeprecationWarning as e: assert str(e) == "Warning B!" else: raise ValueError("Expected warning to give error!")
def test_ignore_type_fails(): with all_warnings(): warnings.simplefilter("error") with ignore_warning(category=UserWarning): try: warnsB() except DeprecationWarning as e: nt.assert_equal(str(e), "Warning B!") else: raise ValueError("Expected warning to give error!")
def test_quant_zeros(self): intens = np.array([[0.5, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0], [0.5, 0.0, 0.0]]).T with ignore_warning(message="divide by zero encountered", category=RuntimeWarning): quant = utils_eds.quantification_cliff_lorimer(intens, [1, 1, 3]).T np.testing.assert_allclose( quant, np.array([[0.2, 0.2, 0.6], [0.0, 0.25, 0.75], [0.25, 0.0, 0.75], [0.5, 0.5, 0.0], [1.0, 0.0, 0.0]]))
def optimize_contrast(self, data): if (self._vmin_user is not None and self._vmax_user is not None): return with ignore_warning(category=RuntimeWarning): # In case of "All-NaN slices" vmin, vmax = utils.contrast_stretching(data, self.saturated_pixels) if vmin == np.nan: vmin = None if vmax == np.nan: vmax = None self._vmin_auto, self._vmax_auto = vmin, vmax
def test_ignore_message_fails(): warnings.simplefilter("error") with ignore_warning(message="Warning [AB]!"): warnsA() warnsB() try: warnsC() except UserWarning as e: assert str(e) == "Warning C!" else: raise ValueError("Expected warning to give error!") warnings.simplefilter("error") with ignore_warning(message="Warning A! Too much"): try: warnsA() except UserWarning as e: assert str(e) == "Warning A!" else: raise ValueError("Expected warning to give error!")
def setup_method(self, method): np.random.seed(1) s = hs.signals.Signal1D(np.arange(10, 100, 0.1)) s.axes_manager[0].scale = 0.1 s.axes_manager[0].offset = 10 m = s.create_model() with ignore_warning(message="The API of the `Polynomial` component"): m.append(hs.model.components1D.Polynomial(1)) m.append(hs.model.components1D.Offset()) self.s = s self.m = m
def test_pattern_binned_signal_unbinned(self): s = self.s s1 = self.pattern s.metadata.Signal.binned = False s1.metadata.Signal.binned = True m = s.create_model() fp = hs.model.components1D.ScalableFixedPattern(s1) m.append(fp) with ignore_warning(message="invalid value encountered in sqrt", category=RuntimeWarning): m.fit() assert abs(fp.yscale.value - 10) <= .1
def test_pattern_unbinned_signal_binned(self): s = self.s s1 = self.pattern s.metadata.Signal.binned = True s1.metadata.Signal.binned = False m = s.create_model() fp = hs.model.components.ScalableFixedPattern(s1) m.append(fp) with ignore_warning(message="invalid value encountered in sqrt", category=RuntimeWarning): m.fit() nt.assert_almost_equal(fp.yscale.value, 1000, delta=1)
def test_both_unbinned(self): s = self.s s1 = self.pattern s.axes_manager[-1].is_binned = False s1.axes_manager[-1].is_binned = False m = s.create_model() fp = hs.model.components1D.ScalableFixedPattern(s1) m.append(fp) with ignore_warning(message="invalid value encountered in sqrt", category=RuntimeWarning): m.fit() assert abs(fp.yscale.value - 100) <= 0.1
def test_ignore_message_fails(): with all_warnings(): warnings.simplefilter("error") with ignore_warning(message="Warning [AB]!"): warnsA() warnsB() try: warnsC() except UserWarning as e: nt.assert_equal(str(e), "Warning C!") else: raise ValueError("Expected warning to give error!") with all_warnings(): warnings.simplefilter("error") with ignore_warning(message="Warning A! Too much"): try: warnsA() except UserWarning as e: nt.assert_equal(str(e), "Warning A!") else: raise ValueError("Expected warning to give error!")
def test_both_binned(self, uniform): s = self.s s1 = self.pattern s.axes_manager[-1].is_binned = True s1.axes_manager[-1].is_binned = True if not uniform: s.axes_manager[0].convert_to_non_uniform_axis() s1.axes_manager[0].convert_to_non_uniform_axis() m = s.create_model() fp = hs.model.components1D.ScalableFixedPattern(s1) m.append(fp) with ignore_warning(message="invalid value encountered in sqrt", category=RuntimeWarning): m.fit() assert abs(fp.yscale.value - 100) <= 0.1
def add_polynomial_background(self, order=6): """ Add a polynomial background. the background is added to self.background_components Parameters ---------- order: int The order of the polynomial """ with ignore_warning(message="The API of the `Polynomial` component"): background = create_component.Polynomial(order=order, legacy=False) background.name = 'background_order_' + str(order) background.isbackground = True self.append(background) self.background_components.append(background)
def test_see_fit(): # Component parameter values A = 10 Phi = 2.5 B = 0.5 offset, scale, size = 0, 0.1, 100 x = np.linspace(offset, scale * size, size) s = hs.signals.Signal1D(SEE(A=A, Phi=Phi, B=B).function(x)) axis = s.axes_manager[0] axis.offset, axis.scale = offset, scale s.add_gaussian_noise(0.1, random_state=1) m = s.create_model() see = SEE(A=1, Phi=1.5, B=0.5) m.append(see) with ignore_warning(message="divide by zero", category=RuntimeWarning): m.fit(grad='analytical') np.testing.assert_allclose(see.A.value, A, rtol=0.1) np.testing.assert_allclose(see.Phi.value, Phi, rtol=0.1) np.testing.assert_allclose(see.B.value, B, rtol=0.1)
def update(self, force_replot=False, render_figure=True, update_ylimits=False): """Update the current spectrum figure Parameters ---------- force_replot : bool If True, close and open the figure. Default is False. render_figure : bool If True, render the figure. Useful to avoid firing matplotlib drawing events too often. Default is True. update_ylimits : bool If True, update the y-limits. This is useful to avoid the figure flickering when different lines update the y-limits consecutively, in which case, this is done in `Signal1DFigure.update`. Default is False. """ if force_replot is True: self.close() self.plot(data_function_kwargs=self.data_function_kwargs, norm=self.norm) self._y_min, self._y_max = self.ax.get_ylim() ydata = self._get_data() # If axis is a DataAxis instance, take the axis attribute axis = getattr(self.axis, 'axis', self.axis) if not np.array_equiv(self.line.get_xdata(), axis): self.line.set_data(axis, ydata) else: self.line.set_ydata(ydata) # Don't change xlim if axis has 0 length (unnecessary) if 'x' in self.autoscale and len(axis) > 0: x_min, x_max = axis[0], axis[-1] if x_min == x_max: # To avoid matplotlib UserWarning when calling `set_ylim` x_min, x_max = (x_min - 0.1, x_min + 0.1) self.ax.set_xlim(x_min, x_max) # Don't change ymin if data has 0 length (unnecessary) if 'v' in self.autoscale and len(ydata) > 0: self.ax.relim() # Based on the current zoom of the x axis, find the corresponding # y range of data and calculate the y_min, y_max accordingly i1, i2 = np.searchsorted(axis, self.ax.get_xbound()) # Make interval wider on both side and clip to allowed range i1, i2 = np.clip((i1 - 1, i2 + 1), 0, len(ydata - 1)) ydata = ydata[i1:i2] with ignore_warning(category=RuntimeWarning): # In case of "All-NaN slices" y_max, y_min = np.nanmax(ydata), np.nanmin(ydata) if self._plot_imag: # Add real plot yreal = self._get_data(real_part=True)[i1:i2] with ignore_warning(category=RuntimeWarning): # In case of "All-NaN slices" y_min = min(y_min, np.nanmin(yreal)) y_max = max(y_max, np.nanmin(yreal)) if y_min == y_max: # To avoid matplotlib UserWarning when calling `set_ylim` y_min, y_max = y_min - 0.1, y_max + 0.1 if not np.isfinite(y_min): y_min = None # data are -inf or all NaN if not np.isfinite(y_max): y_max = None # data are inf or all NaN if y_min is not None: self._y_min = y_min if y_max is not None: self._y_max = y_max if update_ylimits: # Most of the time, we don't want to call `set_ylim` now to # avoid flickering of the figure. However, we use the values # `self._y_min` and `self._y_max` in `Signal1DFigure.update` self.ax.set_ylim(self._y_min, self._y_max) if self.plot_indices is True: self.text.set_text(self.axes_manager.indices) if render_figure: self.ax.hspy_fig.render_figure()
def update(self, force_replot=False, render_figure=True, update_ylimits=False): """Update the current spectrum figure Parameters ---------- force_replot : bool If True, close and open the figure. Default is False. render_figure : bool If True, render the figure. Useful to avoid firing matplotlib drawing events too often. Default is True. update_ylimits : bool If True, update the y-limits. This is useful to avoid the figure flickering when different lines update the y-limits consecutively, in which case, this is done in `Signal1DFigure.update`. Default is False. """ if force_replot is True: self.close() self.plot(data_function_kwargs=self.data_function_kwargs, norm=self.norm) self._y_min, self._y_max = self.ax.get_ylim() ydata = self._get_data() # If axis is a DataAxis instance, take the axis attribute axis = getattr(self.axis, 'axis', self.axis) if not np.array_equiv(self.line.get_xdata(), axis): self.line.set_data(axis, ydata) else: self.line.set_ydata(ydata) if 'x' in self.autoscale: self.ax.set_xlim(axis[0], axis[-1]) if 'v' in self.autoscale: self.ax.relim() y1, y2 = np.searchsorted(axis, self.ax.get_xbound()) y2 += 2 y1, y2 = np.clip((y1, y2), 0, len(ydata - 1)) clipped_ydata = ydata[y1:y2] with ignore_warning(category=RuntimeWarning): # In case of "All-NaN slices" y_max, y_min = (np.nanmax(clipped_ydata), np.nanmin(clipped_ydata)) if self._plot_imag: # Add real plot yreal = self._get_data(real_part=True) clipped_yreal = yreal[y1:y2] with ignore_warning(category=RuntimeWarning): # In case of "All-NaN slices" y_min = min(y_min, np.nanmin(clipped_yreal)) y_max = max(y_max, np.nanmin(clipped_yreal)) if y_min == y_max: # To avoid matplotlib UserWarning when calling `set_ylim` y_min, y_max = y_min - 0.1, y_max + 0.1 if not np.isfinite(y_min): y_min = None # data are -inf or all NaN if not np.isfinite(y_max): y_max = None # data are inf or all NaN if y_min is not None: self._y_min = y_min if y_max is not None: self._y_max = y_max if update_ylimits: # Most of the time, we don't want to call `set_ylim` now to # avoid flickering of the figure. However, we use the values # `self._y_min` and `self._y_max` in `Signal1DFigure.update` self.ax.set_ylim(self._y_min, self._y_max) if self.plot_indices is True: self.text.set_text(self.axes_manager.indices) if render_figure: self.ax.hspy_fig.render_figure()