From 0fba72a915fb6f75a9e9ceea3cf89c62ca51025c Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Wed, 22 Jul 2020 14:25:57 +0200 Subject: [PATCH 01/22] Initial support for loading NLD/GSF from disk --- ompy/extractor.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/ompy/extractor.py b/ompy/extractor.py index af744c74..130acd06 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -5,6 +5,7 @@ from contextlib import redirect_stdout from uncertainties import unumpy import os +import fnmatch from pathlib import Path from typing import Optional, Union, Any, Tuple, List @@ -557,6 +558,33 @@ def __getstate__(self): pass return state + @staticmethod + def load(path: Union[str, Path]): + """ Load an ensemble of from disk. + Args: + path: Path to folder with ensemble + Returns: + extractor object with gSF and NLD set. + """ + if path is None: + raise ValueError("path must be given") + path = Path(path) + + # Count number of files with name gsf_*.npy + num_gsf = len(fnmatch.filter(next(os.walk(path))[2], 'gsf_*.npy')) + num_nld = len(fnmatch.filter(next(os.walk(path))[2], 'nld_*.npy')) + + assert num_gsf == num_nld, \ + "The number of gsf files and nld files should be the same." + extractor = Extractor(path=path) + for i in range(num_gsf): + gsf_path = path / f'gsf_{i}.npy' + extractor.gsf.append(Vector(path=gsf_path)) + for i in range(num_nld): + nld_path = path / f'nld_{i}.npy' + extractor.nld.append(Vector(path=nld_path)) + return extractor + def normalize(mat: Matrix, std: Optional[Matrix]) -> Tuple[np.ndarray, np.ndarray]: From 3f7340ca8bc7317742a8d2a040504c09cfcdd2d9 Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Thu, 13 Aug 2020 12:41:55 +0200 Subject: [PATCH 02/22] New draft Modified the load functunality to conform with `Matrix()` and `Vector()` --- ompy/extractor.py | 126 +++--- ompy/normalizer_disc.py | 753 +++++++++++++++++++++++++++++++ tests/not_a_vector_or_matrix.tar | Bin 0 -> 20480 bytes 3 files changed, 819 insertions(+), 60 deletions(-) create mode 100644 ompy/normalizer_disc.py create mode 100644 tests/not_a_vector_or_matrix.tar diff --git a/ompy/extractor.py b/ompy/extractor.py index 130acd06..497c67ad 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -7,6 +7,7 @@ import os import fnmatch +import fnmatch from pathlib import Path from typing import Optional, Union, Any, Tuple, List from scipy.optimize import minimize @@ -66,16 +67,13 @@ class Extractor: it is not created. This is a very common pattern. Consider superclassing the disk book-keeping. """ - def __init__(self, ensemble: Optional[Ensemble] = None, - trapezoid: Optional[Action] = None, - path: Optional[Union[str, Path]] = - 'saved_run/extractor'): + def __init__(self, + path: Optional[Union[str, Path]] = None): """ ensemble (Ensemble, optional): see above trapezoid (Action[Matrix], optional): see above path (Path or str, optional): see above """ - self.ensemble = ensemble self.regenerate = False self.method = 'Powell' self.options = {'disp': True, 'ftol': 1e-3, 'maxfev': None} @@ -83,9 +81,11 @@ def __init__(self, ensemble: Optional[Ensemble] = None, self.gsf: List[Vector] = [] self.trapezoid = trapezoid - if path is None: - self.path = None + if path is not None: + self.path = Path(path) + self.load(self.path) else: + self.path = 'saved_run/extractor' self.path = Path(path) self.path.mkdir(exist_ok=True, parents=True) @@ -97,12 +97,11 @@ def __init__(self, ensemble: Optional[Ensemble] = None, self.extend_fit_by_resolution: bool = False self.resolution_Ex = 150 # keV - def __call__(self, ensemble: Optional[Ensemble] = None, - trapezoid: Optional[Action] = None): + def __call__(self, ensemble: Ensemble, trapezoid: Action): return self.extract_from(ensemble, trapezoid) - def extract_from(self, ensemble: Optional[Ensemble] = None, - trapezoid: Optional[Action] = None, + def extract_from(self, ensemble: Ensemble, + trapezoid: Action = None, regenerate: Optional[bool] = None): """Decompose each first generation matrix in an Ensemble @@ -122,14 +121,7 @@ def extract_from(self, ensemble: Optional[Ensemble] = None, Raises: ValueError: If no Ensemble instance is provided here or earlier. """ - if ensemble is not None: - self.ensemble = ensemble - elif self.ensemble is None: - raise ValueError("ensemble must be given") - if trapezoid is not None: - self.trapezoid = trapezoid - elif self.trapezoid is None: - raise ValueError("A 'trapezoid' cut must be given'") + if regenerate is None: regenerate = self.regenerate self.path = Path(self.path) @@ -154,39 +146,51 @@ def extract_from(self, ensemble: Optional[Ensemble] = None, self.nld = nlds self.gsf = gsfs - def step(self, num: int) -> Tuple[Vector, Vector]: - """ Wrapper around _extract in order to be consistent with other classes + def step(self, ensemble: Ensemble, trapezoid: Action, + num: int) -> Tuple[Vector, Vector]: + """ Wrapper around _extract in order to be consistent with other + classes Args: + ensemble (Ensemble): The ensemble to extract nld and gsf + from. Can be provided in when initializing instead. + trapezoid (Action): An Action describing the cut to apply + to the matrices to obtain the desired region for extracting nld + and gsf. num: Number of the fg matrix to extract """ nld, gsf = self._extract(num) return nld, gsf - def _extract(self, num: int) -> Tuple[Vector, Vector]: + def _extract(self, ensemble: Ensemble, trapezoid: Action, + num: int) -> Tuple[Vector, Vector]: """ Extract nld and gsf from matrix number i from Ensemble Args: + ensemble (Ensemble): The ensemble to extract nld and gsf + from. Can be provided in when initializing instead. + trapezoid (Action): An Action describing the cut to apply + to the matrices to obtain the desired region for extracting nld + and gsf. num: Number of the fg matrix to extract Returns: The nld and gsf as Vectors """ - assert self.ensemble is not None - assert self.trapezoid is not None - matrix = self.ensemble.get_firstgen(num).copy() - std = self.ensemble.std_firstgen.copy() + + matrix = ensemble.get_firstgen(num).copy() + std = ensemble.std_firstgen.copy() # following lines might be superfluous now: # ensure same cuts for all ensemble members if Eg_max is not given # (thus auto-determined) in the trapezoid. if num == 0: - self.trapezoid.act_on(matrix) - self.trapezoid.curry(Eg_max=matrix.Eg[-1]) - self.trapezoid.act_on(std) + trapezoid.act_on(matrix) + trapezoid.curry(Eg_max=matrix.Eg[-1]) + trapezoid.act_on(std) else: - self.trapezoid.act_on(matrix) - self.trapezoid.act_on(std) - nld, gsf = self.decompose(matrix, std) + trapezoid.act_on(matrix) + trapezoid.act_on(std) + nld, gsf = decompose(matrix, std) return nld, gsf def decompose(self, matrix: Matrix, @@ -353,6 +357,34 @@ def guess_initial_values(self, E_nld: np.ndarray, matrix: Matrix, assert np.isfinite(x0).all return x0 + def load(self, path: Union[str, Path]): + """Load an ensemble of from disk. + + Args: + path: Path to folder with ensemble + + Returns: + extractor object with gSF and NLD set. + Raises: + RuntimeError if the number of NLD and GSF doesn't match. + """ + + path = Path(path) + + # Count number of files with name gsf_*.npy and nld_*.npy + # in the folder where these are stored. + num_gsf = len(fnmatch.filter(next(os.walk(path))[2], 'gsf_*.npy')) + num_nld = len(fnmatch.filter(next(os.walk(path))[2], 'nld_*.npy')) + + if num_gsf != num_nld: + raise RuntimeError("The number of GSF and NLD files doesn't match") + for i in range(num_gsf): + gsf_path = path / f'gsf_{i}.npy' + self.gsf.append(Vector(path=gsf_path)) + for i in range(num_nld): + nld_path = path / f'nld_{i}.npy' + self.nld.append(Vector(path=nld_path)) + @staticmethod def x0_BSFG(E_nld: np.ndarray, E0: float = -.2, a: float = 15): """ Initial guess that resembles Backshifted Fermi-gas solution @@ -477,7 +509,8 @@ def diagonal_resolution(self, matrix: Matrix) -> np.ndarray: @staticmethod def resolution_Eg(matrix: Matrix) -> np.ndarray: - """Resolution along Eg axis for each Ex. Defaults in this class are for OSCAR. + """Resolution along Eg axis for each Ex. Defaults in this class are for + OSCAR. Args: matrix (Matrix): Matrix for which the sesoluton shall be calculated @@ -558,33 +591,6 @@ def __getstate__(self): pass return state - @staticmethod - def load(path: Union[str, Path]): - """ Load an ensemble of from disk. - Args: - path: Path to folder with ensemble - Returns: - extractor object with gSF and NLD set. - """ - if path is None: - raise ValueError("path must be given") - path = Path(path) - - # Count number of files with name gsf_*.npy - num_gsf = len(fnmatch.filter(next(os.walk(path))[2], 'gsf_*.npy')) - num_nld = len(fnmatch.filter(next(os.walk(path))[2], 'nld_*.npy')) - - assert num_gsf == num_nld, \ - "The number of gsf files and nld files should be the same." - extractor = Extractor(path=path) - for i in range(num_gsf): - gsf_path = path / f'gsf_{i}.npy' - extractor.gsf.append(Vector(path=gsf_path)) - for i in range(num_nld): - nld_path = path / f'nld_{i}.npy' - extractor.nld.append(Vector(path=nld_path)) - return extractor - def normalize(mat: Matrix, std: Optional[Matrix]) -> Tuple[np.ndarray, np.ndarray]: diff --git a/ompy/normalizer_disc.py b/ompy/normalizer_disc.py new file mode 100644 index 00000000..1b697b6b --- /dev/null +++ b/ompy/normalizer_disc.py @@ -0,0 +1,753 @@ +import numpy as np +import copy +import logging +import termtables as tt +import json +import pymultinest +import matplotlib.pyplot as plt +import warnings +from contextlib import redirect_stdout +from numpy import ndarray +from scipy.optimize import differential_evolution, curve_fit +from typing import Optional, Tuple, Any, Union, Callable, Dict +from pathlib import Path + +from scipy.stats import truncnorm +from .vector import Vector +from .library import self_if_none +from .spinfunctions import SpinFunctions +from .filehandling import load_discrete +from .models import ResultsNormalized, NormalizationParameters +from .abstract_normalizer import AbstractNormalizer + +TupleDict = Dict[str, Tuple[float, float]] + + +class NormalizerDISC(AbstractNormalizer): + """ Normalizes NLD to empirical data + + Normalizes nld/gsf according to:: + + nld' = nld * A * np.exp(alpha * Ex), and + + This is the transformation eq (3), Schiller2000 + + Takes empirical data in form of an array of discrete levels, + neutron separation energy Sn, a model to estimate what the + NLD is at Sn, and several parameters for the model as well + as bounds on normalization parameters. + + As a consequence of a complex problem, this class has a complex + interface. Much of the book-keeping associated with normalization + has been automated, but there is still a lot of settings and + parameters for the user to take care of. Some default values + has been seen, but the user must be _EXTREMELY_ careful when + evaluating the output. + + Attributes: + discrete (Vector): The discrete NLD at lower energies. [MeV] + nld (Vector): The NLD to normalize. Gets converted to [MeV] from [keV]. + norm_pars (NormalizationParameters): Normalization parameters like + experimental D₀, and spin(-cut) model + bounds (Dict[str, Tuple[float, float]): The bounds on each of + the parameters. Its keys are 'A', 'alpha', 'T', and 'D0'. The + values are on the form (min, max). + model (Callable[..., ndarray]): The model to use at high energies + to estimate the NLD. Defaults to constant temperature model. + multinest_path (Path): Where to save the multinest output. + defaults to 'multinest'. + multinest_kwargs (dict): Additional keywords to multinest. Defaults to + `{"seed": 65498, "resume": False}` + res (ResultsNormalized): Results of the normalization + smooth_levels_fwhm (float): FWHM with which the discrete levels shall + be smoothed when loading from file. Defaults to 0.1 MeV. + path (Path): The path save the results. + + """ + LOG = logging.getLogger(__name__) # overwrite parent variable + logging.captureWarnings(True) + + def __init__(self, *, + nld: Optional[Vector] = None, + discrete: Optional[Union[str, Vector]] = None, + path: Optional[Union[str, Path]] = 'saved_run/normalizers', + regenerate: bool = False, + norm_pars: Optional[NormalizationParameters] = None) -> None: + """ Normalizes nld ang gSF. + + Note: + The prefered syntax is `Normalizer(nld=...)` + If neither is given, the nld (and other parameters) can be + explicity + be set later by:: + + `normalizer.normalize(..., nld=...)` + + or:: + + `normalizer.nld = ...` + + In the later case you *might* have to send in a copy if it's a + mutable to ensure it is not changed. + + Args: + extractor: see above + nld: see above + discrete: see above + path: see above + norm_pars: see above + TODO: + - parameter to limit the number of multinest samples to store. Note + that the samples should be shuffled to retain some "random" + samples from the pdf (not the importance weighted) + + """ + super().__init__(regenerate) + + # Create the private variables + self._discrete = None + self._cumulative = None + self._discrete_path = None + self._D0 = None + self._smooth_levels_fwhm = None + self.norm_pars = norm_pars + self.bounds = {'A': [0.1, 1e3], 'alpha': [1e-1, 20], 'T': [0.1, 1], + 'Eshift': [-5, 5]} # D0 bounds set later + self.model: Optional[Callable[..., ndarray]] = self.const_temperature + # self.curried_model = lambda *arg: None + self.multinest_path = Path('multinest') + self.multinest_kwargs: dict = {"seed": 65498, "resume": False} + + # Handle the method parameters + self.smooth_levels_fwhm = 0.1 + self.nld = None if nld is None else nld.copy() + self.discrete = discrete + + self.res = ResultsNormalized(name="Results NLD") + + self.limit_low = None + self.limit_high = None + self.std_fake = None # See `normalize` + + if path is None: + self.path = None + else: + self.path = Path(path) + self.path.mkdir(exist_ok=True, parents=True) + + def __call__(self, *args, **kwargs) -> None: + """ Wrapper around normalize """ + self.normalize(*args, **kwargs) + + def normalize(self, *, limit_low: Optional[Tuple[float, float]] = None, + limit_high: Optional[Tuple[float, float]] = None, + nld: Optional[Vector] = None, + discrete: Optional[Vector] = None, + bounds: Optional[TupleDict] = None, + norm_pars: Optional[NormalizationParameters] = None, + num: int = 0) -> None: + """ Normalize NLD to a low and high energy region + + Args: + limit_low: The limits (start, stop) where to normalize + to discrete levels. + limit_high: The limits (start, stop) where to normalize to + a theoretical model and neutron separation energy at high + energies. + nld: The nuclear level density vector to normalize. + discrete: The discrete level density at low energies to + normalize to. + bounds: The bounds of the parameters + norm_pars (NormalizationParameters): Normalization parameters like + experimental D₀, and spin(-cut) model + num (optional): Loop number, defauts to 0 + regenerate: Whether to use already generated files (False) or + generate them all anew (True). + + """ + if not self.regenerate: + try: + self.load() + return + except FileNotFoundError: + pass + + # Update internal state + self.limit_low = self.self_if_none(limit_low) + limit_low = self.limit_low + + self.limit_high = self.self_if_none(limit_high) + limit_high = self.limit_high + + discrete = self.self_if_none(discrete) + discrete.to_MeV() + nld = self.self_if_none(nld) + + self.norm_pars = self.self_if_none(norm_pars) + self.norm_pars.is_changed(include=["D0", "Sn", "spincutModel", + "spincutPars"]) # check that set + + self.bounds = self.self_if_none(bounds) + + # ensure that it's updated if running again + self.res = ResultsNormalized(name="Results NLD") + + self.LOG.info(f"\n\n---------\nNormalizing nld #{num}") + nld = nld.copy() + self.LOG.debug("Setting NLD, convert to MeV") + nld.to_MeV() + + # Need to give some sort of standard deviation for sensible results + # Otherwise deviations at higher level density will have an + # uncreasonably high weight. + if self.std_fake is None: + self.std_fake = False + if self.std_fake or nld.std is None: + self.std_fake = True + nld.std = nld.values * 0.3 # x% is an arb. choice + self.nld = nld + + # Use DE to get an inital guess before optimizing + args, guess = self.initial_guess(limit_low, limit_high) + # Optimize using multinest + popt, samples = self.optimize(num, args, guess) + + transformed = nld.transform(popt['A'][0], popt['alpha'][0], + inplace=False) + if self.std_fake: + nld.std = None + transformed.std = None + + self.res.nld = transformed + self.res.pars = popt + self.res.samples = samples + + nld_high = transformed.cut(*limit_high, inplace=False) + + popt, cov = self.optimize_CT(nld_high) + + self.res.pars['T'] = [popt[0], np.sqrt(np.diag(cov))[0]] + self.res.pars['Eshift'] = [popt[1], np.sqrt(np.diag(cov))[1]] + + ext_model = lambda E: self.model(E, T=popt['T'][0], + Eshift=popt['Eshift'][1]) + ext_model_err = lambda E: self.const_temperature_err(E, + T=popt[0], + Eshift=popt[1], + cov=cov) + self.res.nld_model = ext_model + self.res.nld_model_err = ext_model_err + + self.save() # save instance + + + def initial_guess(self, limit_low: Optional[Tuple[float, float]] = None, + limit_high: Optional[Tuple[float, float]] = None + ) -> Tuple[Tuple[float, float, float, float], + Dict[str, float]]: + """ Find an inital guess for the constant, α, T and D₀ + + Uses differential evolution to perform the guessing. + + Args: + limits: The limits (start, stop) where to normalize + to discrete levels. + + Returns: + The arguments used for chi^2 minimization and the + minimizer. + """ + limit_low = self.self_if_none(limit_low) + limit_high = self.self_if_none(limit_high) + + #bounds = list(self.bounds.values()) + bounds = [self.bounds['A'], self.bounds['alpha']] + spinParsstring = json.dumps(self.norm_pars.spincutPars, indent=4, + sort_keys=True) + + self.LOG.debug("Using bounds %s", bounds) + self.LOG.debug("Using spincutModel %s", self.norm_pars.spincutModel) + self.LOG.debug("Using spincutPars %s", spinParsstring) + + nld_low = self.nld.cut(*limit_low, inplace=False) + nld_high = self.nld.cut(*limit_high, inplace=False) + discrete = self.discrete.cut(*limit_low, inplace=False) + + def neglnlike(*args, **kwargs): + return - self.lnlike(*args, **kwargs) + args = (nld_low, discrete) + res = differential_evolution(neglnlike, bounds=bounds, args=args) + + self.LOG.info("DE results:\n%s", tt.to_string([res.x.tolist()], + header=['A', 'α [MeV⁻¹]'])) + + p0 = dict(zip(["A", "alpha"], (res.x).T)) + + return args, p0 + + + def optimize_CT(self, vec): + + vec_fit = vec.copy() + vec_fit.values = np.log(vec_fit.values) + if vec.std is not None: + vec_fit.std = vec.std/vec.values + p, cov = LeastSquares_linear(vec_fit) + popt = [1/p[0], np.log(p[0])/p[0] - p[1]/p[0]] + L = np.array([[1/p[0], 0],[np.log(p[0])/p[0], -1]])/p[0] + cov_trans = cov @ L.T + cov_trans = L @ cov_trans + cov=cov_trans + + T = popt[0] + Terr = np.sqrt(np.diag(cov))[0] + Eshift = popt[1] + Eshifterr = np.sqrt(np.diag(cov))[1] + + vals = [] + i = max(0, int(-np.floor(np.log10(Terr))) + 1) + fmt = '%%.%df' % i + fmts = '\t'.join([fmt + " ± " + fmt]) + vals.append(fmts % (T, Terr)) + i = max(0, int(-np.floor(np.log10(Eshifterr))) + 1) + fmt = '%%.%df' % i + fmts = '\t'.join([fmt + " ± " + fmt]) + vals.append(fmts % (Eshift, Eshifterr)) + + self.LOG.info("Model results\n%s", tt.to_string([vals], + header=['T [MeV]', 'Eshift [MeV]'])) + + return np.array([T, Eshift]), cov + + + def optimize(self, num: int, args, + guess: Dict[str, float]) -> Tuple[Dict[str, float], Dict[str, float]]: + """Find parameters given model constraints and an initial guess + + Employs Multinest + + Args: + num (int): Loop number + args_nld (Iterable): Additional arguments for the nld lnlike + guess (Dict[str, float]): The initial guess of the parameters + + Returns: + Tuple: + - popt (Dict[str, Tuple[float, float]]): Median and 1sigma of the + parameters + - samples (Dict[str, List[float]]): Multinest samplesø. + Note: They are still importance weighted, not random draws + from the posterior. + + Raises: + ValueError: Invalid parameters for automatix prior + """ + if guess['alpha'] < 0: + raise ValueError("Prior selection not implemented for α < 0") + alpha_exponent = np.log10(guess['alpha']) + + A = guess['A'] + + # truncations from absolute values + lower_A, upper_A = 0., np.inf + mu_A, sigma_A = A, 10*A + a_A = (lower_A - mu_A) / sigma_A + b_A = (upper_A - mu_A) / sigma_A + + def prior(cube, ndim, nparams): + # NOTE: You may want to adjust this for your case! + # truncated normal prior + cube[0] = truncnorm.ppf(cube[0], a_A, b_A, loc=mu_A, + scale=sigma_A) + # log-uniform prior + # if alpha = 1e2, it's between 1e1 and 1e3 + cube[1] = 10**(cube[1]*2 + (alpha_exponent-1)) + + if np.isinf(cube[3]): + self.LOG.debug("Encountered inf in cube[3]:\n%s", cube[3]) + + def loglike(cube, ndim, nparams): + return self.lnlike(cube, *args) + + self.multinest_path.mkdir(exist_ok=True) + path = self.multinest_path / f"nld_norm_{num}_" + assert len(str(path)) < 60, "Total path length too long for multinest" + + self.LOG.info("Starting multinest") + self.LOG.debug("with following keywords %s:", self.multinest_kwargs) + # Hack where stdout from Multinest is redirected as info messages + self.LOG.write = lambda msg: (self.LOG.info(msg) if msg != '\n' + else None) + with redirect_stdout(self.LOG): + pymultinest.run(loglike, prior, len(guess), + outputfiles_basename=str(path), + **self.multinest_kwargs) + + # Save parameters for analyzer + names = list(guess.keys()) + json.dump(names, open(str(path) + 'params.json', 'w')) + analyzer = pymultinest.Analyzer(len(guess), + outputfiles_basename=str(path)) + + stats = analyzer.get_stats() + + samples = analyzer.get_equal_weighted_posterior()[:, :-1] + samples = dict(zip(names, samples.T)) + + # Format the output + popt = dict() + vals = [] + for name, m in zip(names, stats['marginals']): + lo, hi = m['1sigma'] + med = m['median'] + sigma = (hi - lo) / 2 + popt[name] = (med, sigma) + i = max(0, int(-np.floor(np.log10(sigma))) + 1) + fmt = '%%.%df' % i + fmts = '\t'.join([fmt + " ± " + fmt]) + vals.append(fmts % (med, sigma)) + + self.LOG.info("Multinest results:\n%s", tt.to_string([vals], + header=['A', 'α [MeV⁻¹]'])) + + return popt, samples + + def plot(self, *, ax: Any = None, + add_label: bool = True, + results: Optional[ResultsNormalized] = None, + add_figlegend: bool = True, + plot_fitregion: bool = True, + reset_color_cycle: bool = True, + **kwargs) -> Tuple[Any, Any]: + """Plot the NLD, discrete levels and result of normalization + + Args: + ax (optional): The matplotlib axis to plot onto. Creates axis + is not provided + add_label (bool, optional): Defaults to `True`. + add_figlegend (bool, optional):Defaults to `True`. + results (ResultsNormalized, optional): If provided, nld and model + are taken from here instead. + plot_fitregion (Optional[bool], optional): Defaults to `True`. + reset_color_cycle (Optional[bool], optional): Defaults to `True` + **kwargs: Description + + Returns: + fig, ax + """ + if ax is None: + fig, ax = plt.subplots() + else: + fig = ax.figure + + if reset_color_cycle: + ax.set_prop_cycle(None) + + res = self.res if results is None else results + pars = res.pars + nld = res.nld + + labelNld = '_exp.' + labelNldSn = None + labelModel = "_model" + labelDiscrete = "_known levels" + if add_label: + labelNld = 'exp.' + labelNldSn = r'$\rho(S_n)$' + labelModel = 'model' + labelDiscrete = "known levels" + nld.plot(ax=ax, label=labelNld, **kwargs) + + self.discrete.plot(ax=ax, kind='step', c='k', label=labelDiscrete) + + nldSn = np.array(self.res.nld_model_err(self.norm_pars.Sn[0])) + + ax.errorbar(self.norm_pars.Sn[0], nldSn[0], yerr=nldSn[1], + label=labelNldSn, fmt="ks", markerfacecolor='none') + + x = np.linspace(self.limit_high[0], self.norm_pars.Sn[0]) + model, modelerr = self.res.nld_model_err(x) + + ax.plot(x, model, "--", label=labelModel, markersize=0, + c='g', **kwargs) + + ax.fill_between(x, model-modelerr, + model+modelerr, color='g', alpha=0.2) + + if plot_fitregion: + ax.axvspan(self.limit_low[0], self.limit_low[1], color='grey', + alpha=0.1, label="fit limits") + ax.axvspan(self.limit_high[0], self.limit_high[1], color='grey', + alpha=0.1) + + ax.set_yscale('log') + ax.set_ylabel(r"Level density $\rho(E_x)~[\mathrm{MeV}^{-1}]$") + ax.set_xlabel(r"Excitation energy $E_x~[\mathrm{MeV}]$") + ax.set_ylim(bottom=0.5/(nld.E[1]-nld.E[0])) + + if fig is not None and add_figlegend: + fig.legend(loc=9, ncol=3, frameon=False) + + return fig, ax + + @staticmethod + def lnlike(x: Tuple[float, float], nld_low: Vector, + discrete: Vector) -> float: + """ Compute log likelihood of the normalization fitting + + This is the result up a, which is irrelevant for the maximization + + Args: + x: The arguments ordered as A, alpha, T and Eshift + nld_low: The lower region where discrete levels will be + fitted. + nld_high: The upper region to fit to model. + discrete: The discrete levels to be used in fitting the + lower region + model: The model to use when fitting the upper region. + Must support the keyword arguments + ``model(E=..., T=..., Eshift=...) -> ndarray`` + + Returns: + lnlike: log likelihood + """ + A, alpha = x[:2] # slicing needed for multinest? + transformed_low = nld_low.transform(A, alpha, inplace=False) + + err_low = transformed_low.error(discrete) + + ln_stds = ( np.log(transformed_low.std).sum() ) + + return -0.5*(err_low + ln_stds) + + @staticmethod + def const_temperature(E: ndarray, T: float, Eshift: float) -> ndarray: + """ Constant Temperature NLD""" + ct = np.exp((E - Eshift) / T) / T + return ct + + @staticmethod + def const_temperature_err(E: ndarray, T: float, Eshift: float, cov: ndarray) -> ndarray: + """ Constant Temperature NLD with errors""" + ct = np.exp((E - Eshift) / T) / T + cterr = np.sqrt(cov[0,0]*((E-Eshift)/T + 1)**2 + cov[1,1] + + 2*cov[0,1]*((E-Eshift)/T + 1))/T + return ct, cterr*ct + + @staticmethod + def nldSn_from_D0(D0: Union[float, Tuple[float, float]], + Sn: Union[float, Tuple[float, float]], Jtarget: float, + spincutModel: str, spincutPars: Dict[str, Any], + **kwargs) -> Tuple[float, float]: + """Calculate nld(Sn) from D0 + + + 1/D0 = nld(Sn) * ( g(Jtarget+1/2, pi_target) + + g(Jtarget1/2, pi_target) ) + Here we assume equal parity, g(J,pi) = g(J)/2 and + nld(Sn) = 1/D0 * 2/(g(Jtarget+1/2) + g(Jtarget-1/2)) + For the case Jtarget = 0, the g(Jtarget-1/2) = 0 + + Parameters: + D0 (float or [float, float]): + Average resonance spacing from s waves [eV]. If a tuple, + it is assumed that it is of the form `[value, uncertainty]`. + Sn (float or [float, float]): + Separation energy [MeV]. If a tuple, it is assumed that it is of + the form `[value, uncertainty]`. + Jtarget (float): + Target spin + spincutModel (str): + Model to for the spincut + spincutPars Dict[str, Any]: + Additional parameters necessary for the spin cut model + **kwargs: Description + + + Returns: + nld: Ex=Sn and nld at Sn [MeV, 1/MeV] + """ + + D0 = np.atleast_1d(D0)[0] + Sn = np.atleast_1d(Sn)[0] + + def g(J): + return SpinFunctions(Ex=Sn, J=J, + model=spincutModel, + pars=spincutPars).distibution() + + if Jtarget == 0: + summe = 1 / 2 * g(Jtarget + 1 / 2) + else: + summe = 1 / 2 * (g(Jtarget - 1 / 2) + g(Jtarget + 1 / 2)) + + nld = 1 / (summe * D0 * 1e-6) + return [Sn, nld] + + @staticmethod + def D0_from_nldSn(nld_model: Callable[..., Any], + Sn: Union[float, Tuple[float, float]], Jtarget: float, + spincutModel: str, spincutPars: Dict[str, Any], + **kwargs) -> Tuple[float, float]: + """Calculate D0 from nld(Sn), assuming equiparity. + + This is the inverse of `nldSn_from_D0` + + Parameters: + nld_model (Callable[..., Any]): Model for nld above data of the + from `y = nld_model(E)` in 1/MeV. + Sn (float or [float, float]): + Separation energy [MeV]. If a tuple, it is assumed that it is of + the form `[value, uncertainty]`. + Jtarget (float): + Target spin + spincutModel (str): + Model to for the spincut + spincutPars Dict[str, Any]: + Additional parameters necessary for the spin cut model + **kwargs: Description + + + Returns: + D0: D0 in eV + """ + + Sn = np.atleast_1d(Sn)[0] + nld = nld_model(Sn) + + def g(J): + return SpinFunctions(Ex=Sn, J=J, + model=spincutModel, + pars=spincutPars).distibution() + + if Jtarget == 0: + summe = 1 / 2 * g(Jtarget + 1 / 2) + else: + summe = 1 / 2 * (g(Jtarget - 1 / 2) + g(Jtarget + 1 / 2)) + + D0 = 1 / (summe * nld * 1e-6) + return D0 + + @property + def discrete(self) -> Optional[Vector]: + return self._discrete + + @property + def cumulative(self): + return self._cumulative + + @discrete.setter + def discrete(self, value: Optional[Union[Path, str, Vector]]) -> None: + if value is None: + self._discretes = None + self.LOG.debug("Set `discrete` to None") + elif isinstance(value, (str, Path)): + if self.nld is None: + raise ValueError(f"`nld` must be set before loading levels") + nld = self.nld.copy() + nld.to_MeV() + self.LOG.debug("Set `discrete` levels from file with FWHM %s", + self.smooth_levels_fwhm) + self._discrete = load_levels_smooth(value, nld.E, + self.smooth_levels_fwhm) + self._discrete.units = "MeV" + self._discrete_path = value + self._cumulative = load_cumulative_discrete(value) + + elif isinstance(value, Vector): + if self.nld is not None and np.any(self.nld.E != value.E): + raise ValueError("`nld` and `discrete` must" + " have same energy binning") + self._discrete = value + self._cumulative = value.to_cumulative(factor='de', inplace=False) + self.LOG.debug("Set `discrete` by Vector") + else: + raise ValueError(f"Value {value} is not supported" + " for discrete levels") + + @property + def smooth_levels_fwhm(self) -> Optional[float]: + return self._smooth_levels_fwhm + + @smooth_levels_fwhm.setter + def smooth_levels_fwhm(self, value: float) -> None: + self._smooth_levels_fwhm = value + if self._discrete_path is not None: + self.discrete = self._discrete_path + + def self_if_none(self, *args, **kwargs): + """ wrapper for lib.self_if_none """ + return self_if_none(self, *args, **kwargs) + +def LeastSquares_linear(vec): + if vec.std is None: + w = np.ones(len(vec.values))*(2./len(vec.values)) + else: + w = 2./vec.std + + alpha = np.sum(w*vec.E**2) + beta = np.sum(w) + gamma = np.sum(w*vec.E) + p = np.sum(w*vec.E*vec.values) + q = np.sum(w*vec.values) + + mo = (beta*p - gamma*q)/(alpha*beta - gamma**2) + co = (alpha*q - gamma*p)/(alpha*beta - gamma**2) + + cov = np.array([[beta, -gamma],[-gamma, alpha]])*2/(alpha*beta - gamma) + + if vec.std is None: + S = 1/(len(vec.values) - 1)*sum((mo*vec.E + co - vec.values)**2) + w = np.ones(len(vec.values))*(2./S) + alpha = np.sum(w*vec.E**2) + beta = np.sum(w) + gamma = np.sum(w*vec.E) + p = np.sum(w*vec.E*vec.values) + q = np.sum(w*vec.values) + cov = np.array([[beta, -gamma],[-gamma, alpha]])*2/(alpha*beta - gamma) + return np.array([mo, co, S]), cov + return np.array([mo, co]), cov + +def load_cumulative_discrete(path: Union[str, Path]) -> Vector: + """ Load the cumulative number of levels without smoothing. + Args: + path: The file to load + Returns: + A vector with the cumulative number of levels. + """ + + energies = np.loadtxt(path) + energies /= 1e3 # convert to MeV + num = np.cumsum(np.ones(energies.shape)) + return Vector(values=num, E=energies) + +def load_levels_discrete(path: Union[str, Path], energy: ndarray) -> Vector: + """ Load discrete levels without smoothing + + Assumes linear equdistant binning + + Args: + path: The file to load + energy: The binning to use + Returns: + A vector describing the levels + """ + histogram, _ = load_discrete(path, energy, 0.1) + return Vector(values=histogram, E=energy) + + +def load_levels_smooth(path: Union[str, Path], energy: ndarray, + resolution: float = 0.1) -> Vector: + """ Load discrete levels with smoothing + + Assumes linear equdistant binning + + Args: + path: The file to load + energy: The binning to use in MeV + resolution: The resolution (FWHM) of the smoothing to use in MeV + Returns: + A vector describing the smoothed levels + """ + histogram, smoothed = load_discrete(path, energy, resolution) + return Vector(values=smoothed if resolution > 0 else histogram, E=energy) diff --git a/tests/not_a_vector_or_matrix.tar b/tests/not_a_vector_or_matrix.tar new file mode 100644 index 0000000000000000000000000000000000000000..5c158847e5c74c1c071f610f296c613abcf37f8d GIT binary patch literal 20480 zcmeI2c~n$K7Kd2`6j9mt%@sw22AWmiUN9&+sE8UgK>@MZM3$zJZuZsV2JXfk7oxk=uofoH@_mk7eNersdt3jKL(R^7Kko+7L#^=0i!dqhG$|+N&9k0oH%LG ztqT?8xk?ahoNj-8aTR&K8fJC)DPMVgiu7{^T-fI8YDj-)!E8t5k+WldB>kQTjc3c2 zSC`h3{x3q>m-tPzBE^cKRU1*WpyKWia;THzCRxVE+uPOShx-^m*0)<$@>fm7an$GrP(gxf>lk80^u zS^1Fgdk9wFx9wYP*-kjNgE==m?Sy9sjAollItbSeFlE!zo zi}4B(orHHMsJgKZJto{A!(cYtPqWq>GG07f9ELZc_K$ieX9hAJu;!=szbO z-_F+N{nFfX$wzzca{{dXv+j@j&ql_S>c5^(kG|G_AzYEeM&(oA_%zC)Z_&sX&c588O2sn!(7K-8mQ;ql{%0T)`C;{MDlMqVQK0;9xHY(@dr>eLi(des&^{QBVo-L{<)xB!y5j$S9 z*h39dt8O@aouY;%T%cXOti7%by1oRy10)ESeN95E=u*Q9?1_qWUcaY^+=xRAxm9fUZ3QPK5}Ly z`Xq1kvFkBg^hy30pj7`GkUTQLn+)Zu8wRM&<&z=K;u6vj*KnW>@l1L+L)sAKxco9g zS0>s_7b6sNd1i!1S^0a!h~%3Qa>F~;nB<)?vRUiC+nD5^F>>K*nvgs+LC)+d6OxZ6 zD4qGHr0%(Ofa*WG|M%hkpA*l{+R>Wozn+_Q{ikPE|Jn3M{bx({UvFedU+celLX{Cb z^F(m><|}*d%!Dcar|V`L3&Bs^m2e_46TI`H4J^De;apN&=-P%1SUatK!57Vo!S=a4`AO z=j0oOCvF3^6Ef1$f}!@jf7i+2i2xnh6YF*fA#YH0_eRYOIN5w-(eM#5kbEFT(JDFy zd=)?KSACmp*Sov0hBjaTj>PNg4*)^ z;spiXP*_@Oc*rgthF3m&Giq-JI3)NLybMo=0P%8Dxur?quNJab&ejc{R3|Iuzl;Ij zvdTr-uK+@SRZTL>7eLO8>_KIo9`JM9rkI=8!$Gp&urALp4e}a`t~*sE0VbWDysl~q zG{4w(`uR2qG?)G$|I9-Kg&S0q7Fmg*c5q#Uwq**`h+G~;>dk>w&Lf*n=lVlz_0e?Q zUl5e%ug$2~7!LtvqR?XsAyBhj>zwt~K&V|Y%sp<@B*=NY-u`v*T)4YkGgli7VEg>C zZ8=W^!MLF%HCd7d1-^n8^1cD!9(=%{yFvsF(}Zh^VuPTz=!eP6_AG?94UI1C+Nn_T zxWYWA+!+?_f0?!4ITJPvJ))Z!n+3Q1D?)ZxN+8Mad*6|15m30`YgOGziQs>{EM!bY zJhXn1`kmyH47k(~Z!v$R2ohWmTJ2z-E86!Y!TDe&><}F>+7_1lf3pAg{#y|H6-fI1 zm-+uszyJ398^Ff#AHV-H`p@3ciEaS)JpI16!0JES{;2=>RR8rxcJ#IWqx*k!|1X*D z|Iz)wzdQd!&;Rwt+RxhfXXpQ%c=k3t2fF{)TVv3dc3Az#?~nS=j_SYO$cw(#fA3mn}4*X1SkPYfD)htC;>`<5}*Vq0ZM=ppaduZN`Mle1SkPYfD)ht UC;>`<5}*Vq0ZM=p_}?b*H?wDUW&i*H literal 0 HcmV?d00001 From dbf6f01d11b90fe0b2f17aae3d436e067f09364c Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Thu, 13 Aug 2020 13:02:46 +0200 Subject: [PATCH 03/22] Remove files Two files was added by accident! --- ompy/normalizer_disc.py | 753 ------------------------------- tests/not_a_vector_or_matrix.tar | Bin 20480 -> 0 bytes 2 files changed, 753 deletions(-) delete mode 100644 ompy/normalizer_disc.py delete mode 100644 tests/not_a_vector_or_matrix.tar diff --git a/ompy/normalizer_disc.py b/ompy/normalizer_disc.py deleted file mode 100644 index 1b697b6b..00000000 --- a/ompy/normalizer_disc.py +++ /dev/null @@ -1,753 +0,0 @@ -import numpy as np -import copy -import logging -import termtables as tt -import json -import pymultinest -import matplotlib.pyplot as plt -import warnings -from contextlib import redirect_stdout -from numpy import ndarray -from scipy.optimize import differential_evolution, curve_fit -from typing import Optional, Tuple, Any, Union, Callable, Dict -from pathlib import Path - -from scipy.stats import truncnorm -from .vector import Vector -from .library import self_if_none -from .spinfunctions import SpinFunctions -from .filehandling import load_discrete -from .models import ResultsNormalized, NormalizationParameters -from .abstract_normalizer import AbstractNormalizer - -TupleDict = Dict[str, Tuple[float, float]] - - -class NormalizerDISC(AbstractNormalizer): - """ Normalizes NLD to empirical data - - Normalizes nld/gsf according to:: - - nld' = nld * A * np.exp(alpha * Ex), and - - This is the transformation eq (3), Schiller2000 - - Takes empirical data in form of an array of discrete levels, - neutron separation energy Sn, a model to estimate what the - NLD is at Sn, and several parameters for the model as well - as bounds on normalization parameters. - - As a consequence of a complex problem, this class has a complex - interface. Much of the book-keeping associated with normalization - has been automated, but there is still a lot of settings and - parameters for the user to take care of. Some default values - has been seen, but the user must be _EXTREMELY_ careful when - evaluating the output. - - Attributes: - discrete (Vector): The discrete NLD at lower energies. [MeV] - nld (Vector): The NLD to normalize. Gets converted to [MeV] from [keV]. - norm_pars (NormalizationParameters): Normalization parameters like - experimental D₀, and spin(-cut) model - bounds (Dict[str, Tuple[float, float]): The bounds on each of - the parameters. Its keys are 'A', 'alpha', 'T', and 'D0'. The - values are on the form (min, max). - model (Callable[..., ndarray]): The model to use at high energies - to estimate the NLD. Defaults to constant temperature model. - multinest_path (Path): Where to save the multinest output. - defaults to 'multinest'. - multinest_kwargs (dict): Additional keywords to multinest. Defaults to - `{"seed": 65498, "resume": False}` - res (ResultsNormalized): Results of the normalization - smooth_levels_fwhm (float): FWHM with which the discrete levels shall - be smoothed when loading from file. Defaults to 0.1 MeV. - path (Path): The path save the results. - - """ - LOG = logging.getLogger(__name__) # overwrite parent variable - logging.captureWarnings(True) - - def __init__(self, *, - nld: Optional[Vector] = None, - discrete: Optional[Union[str, Vector]] = None, - path: Optional[Union[str, Path]] = 'saved_run/normalizers', - regenerate: bool = False, - norm_pars: Optional[NormalizationParameters] = None) -> None: - """ Normalizes nld ang gSF. - - Note: - The prefered syntax is `Normalizer(nld=...)` - If neither is given, the nld (and other parameters) can be - explicity - be set later by:: - - `normalizer.normalize(..., nld=...)` - - or:: - - `normalizer.nld = ...` - - In the later case you *might* have to send in a copy if it's a - mutable to ensure it is not changed. - - Args: - extractor: see above - nld: see above - discrete: see above - path: see above - norm_pars: see above - TODO: - - parameter to limit the number of multinest samples to store. Note - that the samples should be shuffled to retain some "random" - samples from the pdf (not the importance weighted) - - """ - super().__init__(regenerate) - - # Create the private variables - self._discrete = None - self._cumulative = None - self._discrete_path = None - self._D0 = None - self._smooth_levels_fwhm = None - self.norm_pars = norm_pars - self.bounds = {'A': [0.1, 1e3], 'alpha': [1e-1, 20], 'T': [0.1, 1], - 'Eshift': [-5, 5]} # D0 bounds set later - self.model: Optional[Callable[..., ndarray]] = self.const_temperature - # self.curried_model = lambda *arg: None - self.multinest_path = Path('multinest') - self.multinest_kwargs: dict = {"seed": 65498, "resume": False} - - # Handle the method parameters - self.smooth_levels_fwhm = 0.1 - self.nld = None if nld is None else nld.copy() - self.discrete = discrete - - self.res = ResultsNormalized(name="Results NLD") - - self.limit_low = None - self.limit_high = None - self.std_fake = None # See `normalize` - - if path is None: - self.path = None - else: - self.path = Path(path) - self.path.mkdir(exist_ok=True, parents=True) - - def __call__(self, *args, **kwargs) -> None: - """ Wrapper around normalize """ - self.normalize(*args, **kwargs) - - def normalize(self, *, limit_low: Optional[Tuple[float, float]] = None, - limit_high: Optional[Tuple[float, float]] = None, - nld: Optional[Vector] = None, - discrete: Optional[Vector] = None, - bounds: Optional[TupleDict] = None, - norm_pars: Optional[NormalizationParameters] = None, - num: int = 0) -> None: - """ Normalize NLD to a low and high energy region - - Args: - limit_low: The limits (start, stop) where to normalize - to discrete levels. - limit_high: The limits (start, stop) where to normalize to - a theoretical model and neutron separation energy at high - energies. - nld: The nuclear level density vector to normalize. - discrete: The discrete level density at low energies to - normalize to. - bounds: The bounds of the parameters - norm_pars (NormalizationParameters): Normalization parameters like - experimental D₀, and spin(-cut) model - num (optional): Loop number, defauts to 0 - regenerate: Whether to use already generated files (False) or - generate them all anew (True). - - """ - if not self.regenerate: - try: - self.load() - return - except FileNotFoundError: - pass - - # Update internal state - self.limit_low = self.self_if_none(limit_low) - limit_low = self.limit_low - - self.limit_high = self.self_if_none(limit_high) - limit_high = self.limit_high - - discrete = self.self_if_none(discrete) - discrete.to_MeV() - nld = self.self_if_none(nld) - - self.norm_pars = self.self_if_none(norm_pars) - self.norm_pars.is_changed(include=["D0", "Sn", "spincutModel", - "spincutPars"]) # check that set - - self.bounds = self.self_if_none(bounds) - - # ensure that it's updated if running again - self.res = ResultsNormalized(name="Results NLD") - - self.LOG.info(f"\n\n---------\nNormalizing nld #{num}") - nld = nld.copy() - self.LOG.debug("Setting NLD, convert to MeV") - nld.to_MeV() - - # Need to give some sort of standard deviation for sensible results - # Otherwise deviations at higher level density will have an - # uncreasonably high weight. - if self.std_fake is None: - self.std_fake = False - if self.std_fake or nld.std is None: - self.std_fake = True - nld.std = nld.values * 0.3 # x% is an arb. choice - self.nld = nld - - # Use DE to get an inital guess before optimizing - args, guess = self.initial_guess(limit_low, limit_high) - # Optimize using multinest - popt, samples = self.optimize(num, args, guess) - - transformed = nld.transform(popt['A'][0], popt['alpha'][0], - inplace=False) - if self.std_fake: - nld.std = None - transformed.std = None - - self.res.nld = transformed - self.res.pars = popt - self.res.samples = samples - - nld_high = transformed.cut(*limit_high, inplace=False) - - popt, cov = self.optimize_CT(nld_high) - - self.res.pars['T'] = [popt[0], np.sqrt(np.diag(cov))[0]] - self.res.pars['Eshift'] = [popt[1], np.sqrt(np.diag(cov))[1]] - - ext_model = lambda E: self.model(E, T=popt['T'][0], - Eshift=popt['Eshift'][1]) - ext_model_err = lambda E: self.const_temperature_err(E, - T=popt[0], - Eshift=popt[1], - cov=cov) - self.res.nld_model = ext_model - self.res.nld_model_err = ext_model_err - - self.save() # save instance - - - def initial_guess(self, limit_low: Optional[Tuple[float, float]] = None, - limit_high: Optional[Tuple[float, float]] = None - ) -> Tuple[Tuple[float, float, float, float], - Dict[str, float]]: - """ Find an inital guess for the constant, α, T and D₀ - - Uses differential evolution to perform the guessing. - - Args: - limits: The limits (start, stop) where to normalize - to discrete levels. - - Returns: - The arguments used for chi^2 minimization and the - minimizer. - """ - limit_low = self.self_if_none(limit_low) - limit_high = self.self_if_none(limit_high) - - #bounds = list(self.bounds.values()) - bounds = [self.bounds['A'], self.bounds['alpha']] - spinParsstring = json.dumps(self.norm_pars.spincutPars, indent=4, - sort_keys=True) - - self.LOG.debug("Using bounds %s", bounds) - self.LOG.debug("Using spincutModel %s", self.norm_pars.spincutModel) - self.LOG.debug("Using spincutPars %s", spinParsstring) - - nld_low = self.nld.cut(*limit_low, inplace=False) - nld_high = self.nld.cut(*limit_high, inplace=False) - discrete = self.discrete.cut(*limit_low, inplace=False) - - def neglnlike(*args, **kwargs): - return - self.lnlike(*args, **kwargs) - args = (nld_low, discrete) - res = differential_evolution(neglnlike, bounds=bounds, args=args) - - self.LOG.info("DE results:\n%s", tt.to_string([res.x.tolist()], - header=['A', 'α [MeV⁻¹]'])) - - p0 = dict(zip(["A", "alpha"], (res.x).T)) - - return args, p0 - - - def optimize_CT(self, vec): - - vec_fit = vec.copy() - vec_fit.values = np.log(vec_fit.values) - if vec.std is not None: - vec_fit.std = vec.std/vec.values - p, cov = LeastSquares_linear(vec_fit) - popt = [1/p[0], np.log(p[0])/p[0] - p[1]/p[0]] - L = np.array([[1/p[0], 0],[np.log(p[0])/p[0], -1]])/p[0] - cov_trans = cov @ L.T - cov_trans = L @ cov_trans - cov=cov_trans - - T = popt[0] - Terr = np.sqrt(np.diag(cov))[0] - Eshift = popt[1] - Eshifterr = np.sqrt(np.diag(cov))[1] - - vals = [] - i = max(0, int(-np.floor(np.log10(Terr))) + 1) - fmt = '%%.%df' % i - fmts = '\t'.join([fmt + " ± " + fmt]) - vals.append(fmts % (T, Terr)) - i = max(0, int(-np.floor(np.log10(Eshifterr))) + 1) - fmt = '%%.%df' % i - fmts = '\t'.join([fmt + " ± " + fmt]) - vals.append(fmts % (Eshift, Eshifterr)) - - self.LOG.info("Model results\n%s", tt.to_string([vals], - header=['T [MeV]', 'Eshift [MeV]'])) - - return np.array([T, Eshift]), cov - - - def optimize(self, num: int, args, - guess: Dict[str, float]) -> Tuple[Dict[str, float], Dict[str, float]]: - """Find parameters given model constraints and an initial guess - - Employs Multinest - - Args: - num (int): Loop number - args_nld (Iterable): Additional arguments for the nld lnlike - guess (Dict[str, float]): The initial guess of the parameters - - Returns: - Tuple: - - popt (Dict[str, Tuple[float, float]]): Median and 1sigma of the - parameters - - samples (Dict[str, List[float]]): Multinest samplesø. - Note: They are still importance weighted, not random draws - from the posterior. - - Raises: - ValueError: Invalid parameters for automatix prior - """ - if guess['alpha'] < 0: - raise ValueError("Prior selection not implemented for α < 0") - alpha_exponent = np.log10(guess['alpha']) - - A = guess['A'] - - # truncations from absolute values - lower_A, upper_A = 0., np.inf - mu_A, sigma_A = A, 10*A - a_A = (lower_A - mu_A) / sigma_A - b_A = (upper_A - mu_A) / sigma_A - - def prior(cube, ndim, nparams): - # NOTE: You may want to adjust this for your case! - # truncated normal prior - cube[0] = truncnorm.ppf(cube[0], a_A, b_A, loc=mu_A, - scale=sigma_A) - # log-uniform prior - # if alpha = 1e2, it's between 1e1 and 1e3 - cube[1] = 10**(cube[1]*2 + (alpha_exponent-1)) - - if np.isinf(cube[3]): - self.LOG.debug("Encountered inf in cube[3]:\n%s", cube[3]) - - def loglike(cube, ndim, nparams): - return self.lnlike(cube, *args) - - self.multinest_path.mkdir(exist_ok=True) - path = self.multinest_path / f"nld_norm_{num}_" - assert len(str(path)) < 60, "Total path length too long for multinest" - - self.LOG.info("Starting multinest") - self.LOG.debug("with following keywords %s:", self.multinest_kwargs) - # Hack where stdout from Multinest is redirected as info messages - self.LOG.write = lambda msg: (self.LOG.info(msg) if msg != '\n' - else None) - with redirect_stdout(self.LOG): - pymultinest.run(loglike, prior, len(guess), - outputfiles_basename=str(path), - **self.multinest_kwargs) - - # Save parameters for analyzer - names = list(guess.keys()) - json.dump(names, open(str(path) + 'params.json', 'w')) - analyzer = pymultinest.Analyzer(len(guess), - outputfiles_basename=str(path)) - - stats = analyzer.get_stats() - - samples = analyzer.get_equal_weighted_posterior()[:, :-1] - samples = dict(zip(names, samples.T)) - - # Format the output - popt = dict() - vals = [] - for name, m in zip(names, stats['marginals']): - lo, hi = m['1sigma'] - med = m['median'] - sigma = (hi - lo) / 2 - popt[name] = (med, sigma) - i = max(0, int(-np.floor(np.log10(sigma))) + 1) - fmt = '%%.%df' % i - fmts = '\t'.join([fmt + " ± " + fmt]) - vals.append(fmts % (med, sigma)) - - self.LOG.info("Multinest results:\n%s", tt.to_string([vals], - header=['A', 'α [MeV⁻¹]'])) - - return popt, samples - - def plot(self, *, ax: Any = None, - add_label: bool = True, - results: Optional[ResultsNormalized] = None, - add_figlegend: bool = True, - plot_fitregion: bool = True, - reset_color_cycle: bool = True, - **kwargs) -> Tuple[Any, Any]: - """Plot the NLD, discrete levels and result of normalization - - Args: - ax (optional): The matplotlib axis to plot onto. Creates axis - is not provided - add_label (bool, optional): Defaults to `True`. - add_figlegend (bool, optional):Defaults to `True`. - results (ResultsNormalized, optional): If provided, nld and model - are taken from here instead. - plot_fitregion (Optional[bool], optional): Defaults to `True`. - reset_color_cycle (Optional[bool], optional): Defaults to `True` - **kwargs: Description - - Returns: - fig, ax - """ - if ax is None: - fig, ax = plt.subplots() - else: - fig = ax.figure - - if reset_color_cycle: - ax.set_prop_cycle(None) - - res = self.res if results is None else results - pars = res.pars - nld = res.nld - - labelNld = '_exp.' - labelNldSn = None - labelModel = "_model" - labelDiscrete = "_known levels" - if add_label: - labelNld = 'exp.' - labelNldSn = r'$\rho(S_n)$' - labelModel = 'model' - labelDiscrete = "known levels" - nld.plot(ax=ax, label=labelNld, **kwargs) - - self.discrete.plot(ax=ax, kind='step', c='k', label=labelDiscrete) - - nldSn = np.array(self.res.nld_model_err(self.norm_pars.Sn[0])) - - ax.errorbar(self.norm_pars.Sn[0], nldSn[0], yerr=nldSn[1], - label=labelNldSn, fmt="ks", markerfacecolor='none') - - x = np.linspace(self.limit_high[0], self.norm_pars.Sn[0]) - model, modelerr = self.res.nld_model_err(x) - - ax.plot(x, model, "--", label=labelModel, markersize=0, - c='g', **kwargs) - - ax.fill_between(x, model-modelerr, - model+modelerr, color='g', alpha=0.2) - - if plot_fitregion: - ax.axvspan(self.limit_low[0], self.limit_low[1], color='grey', - alpha=0.1, label="fit limits") - ax.axvspan(self.limit_high[0], self.limit_high[1], color='grey', - alpha=0.1) - - ax.set_yscale('log') - ax.set_ylabel(r"Level density $\rho(E_x)~[\mathrm{MeV}^{-1}]$") - ax.set_xlabel(r"Excitation energy $E_x~[\mathrm{MeV}]$") - ax.set_ylim(bottom=0.5/(nld.E[1]-nld.E[0])) - - if fig is not None and add_figlegend: - fig.legend(loc=9, ncol=3, frameon=False) - - return fig, ax - - @staticmethod - def lnlike(x: Tuple[float, float], nld_low: Vector, - discrete: Vector) -> float: - """ Compute log likelihood of the normalization fitting - - This is the result up a, which is irrelevant for the maximization - - Args: - x: The arguments ordered as A, alpha, T and Eshift - nld_low: The lower region where discrete levels will be - fitted. - nld_high: The upper region to fit to model. - discrete: The discrete levels to be used in fitting the - lower region - model: The model to use when fitting the upper region. - Must support the keyword arguments - ``model(E=..., T=..., Eshift=...) -> ndarray`` - - Returns: - lnlike: log likelihood - """ - A, alpha = x[:2] # slicing needed for multinest? - transformed_low = nld_low.transform(A, alpha, inplace=False) - - err_low = transformed_low.error(discrete) - - ln_stds = ( np.log(transformed_low.std).sum() ) - - return -0.5*(err_low + ln_stds) - - @staticmethod - def const_temperature(E: ndarray, T: float, Eshift: float) -> ndarray: - """ Constant Temperature NLD""" - ct = np.exp((E - Eshift) / T) / T - return ct - - @staticmethod - def const_temperature_err(E: ndarray, T: float, Eshift: float, cov: ndarray) -> ndarray: - """ Constant Temperature NLD with errors""" - ct = np.exp((E - Eshift) / T) / T - cterr = np.sqrt(cov[0,0]*((E-Eshift)/T + 1)**2 + cov[1,1] + - 2*cov[0,1]*((E-Eshift)/T + 1))/T - return ct, cterr*ct - - @staticmethod - def nldSn_from_D0(D0: Union[float, Tuple[float, float]], - Sn: Union[float, Tuple[float, float]], Jtarget: float, - spincutModel: str, spincutPars: Dict[str, Any], - **kwargs) -> Tuple[float, float]: - """Calculate nld(Sn) from D0 - - - 1/D0 = nld(Sn) * ( g(Jtarget+1/2, pi_target) - + g(Jtarget1/2, pi_target) ) - Here we assume equal parity, g(J,pi) = g(J)/2 and - nld(Sn) = 1/D0 * 2/(g(Jtarget+1/2) + g(Jtarget-1/2)) - For the case Jtarget = 0, the g(Jtarget-1/2) = 0 - - Parameters: - D0 (float or [float, float]): - Average resonance spacing from s waves [eV]. If a tuple, - it is assumed that it is of the form `[value, uncertainty]`. - Sn (float or [float, float]): - Separation energy [MeV]. If a tuple, it is assumed that it is of - the form `[value, uncertainty]`. - Jtarget (float): - Target spin - spincutModel (str): - Model to for the spincut - spincutPars Dict[str, Any]: - Additional parameters necessary for the spin cut model - **kwargs: Description - - - Returns: - nld: Ex=Sn and nld at Sn [MeV, 1/MeV] - """ - - D0 = np.atleast_1d(D0)[0] - Sn = np.atleast_1d(Sn)[0] - - def g(J): - return SpinFunctions(Ex=Sn, J=J, - model=spincutModel, - pars=spincutPars).distibution() - - if Jtarget == 0: - summe = 1 / 2 * g(Jtarget + 1 / 2) - else: - summe = 1 / 2 * (g(Jtarget - 1 / 2) + g(Jtarget + 1 / 2)) - - nld = 1 / (summe * D0 * 1e-6) - return [Sn, nld] - - @staticmethod - def D0_from_nldSn(nld_model: Callable[..., Any], - Sn: Union[float, Tuple[float, float]], Jtarget: float, - spincutModel: str, spincutPars: Dict[str, Any], - **kwargs) -> Tuple[float, float]: - """Calculate D0 from nld(Sn), assuming equiparity. - - This is the inverse of `nldSn_from_D0` - - Parameters: - nld_model (Callable[..., Any]): Model for nld above data of the - from `y = nld_model(E)` in 1/MeV. - Sn (float or [float, float]): - Separation energy [MeV]. If a tuple, it is assumed that it is of - the form `[value, uncertainty]`. - Jtarget (float): - Target spin - spincutModel (str): - Model to for the spincut - spincutPars Dict[str, Any]: - Additional parameters necessary for the spin cut model - **kwargs: Description - - - Returns: - D0: D0 in eV - """ - - Sn = np.atleast_1d(Sn)[0] - nld = nld_model(Sn) - - def g(J): - return SpinFunctions(Ex=Sn, J=J, - model=spincutModel, - pars=spincutPars).distibution() - - if Jtarget == 0: - summe = 1 / 2 * g(Jtarget + 1 / 2) - else: - summe = 1 / 2 * (g(Jtarget - 1 / 2) + g(Jtarget + 1 / 2)) - - D0 = 1 / (summe * nld * 1e-6) - return D0 - - @property - def discrete(self) -> Optional[Vector]: - return self._discrete - - @property - def cumulative(self): - return self._cumulative - - @discrete.setter - def discrete(self, value: Optional[Union[Path, str, Vector]]) -> None: - if value is None: - self._discretes = None - self.LOG.debug("Set `discrete` to None") - elif isinstance(value, (str, Path)): - if self.nld is None: - raise ValueError(f"`nld` must be set before loading levels") - nld = self.nld.copy() - nld.to_MeV() - self.LOG.debug("Set `discrete` levels from file with FWHM %s", - self.smooth_levels_fwhm) - self._discrete = load_levels_smooth(value, nld.E, - self.smooth_levels_fwhm) - self._discrete.units = "MeV" - self._discrete_path = value - self._cumulative = load_cumulative_discrete(value) - - elif isinstance(value, Vector): - if self.nld is not None and np.any(self.nld.E != value.E): - raise ValueError("`nld` and `discrete` must" - " have same energy binning") - self._discrete = value - self._cumulative = value.to_cumulative(factor='de', inplace=False) - self.LOG.debug("Set `discrete` by Vector") - else: - raise ValueError(f"Value {value} is not supported" - " for discrete levels") - - @property - def smooth_levels_fwhm(self) -> Optional[float]: - return self._smooth_levels_fwhm - - @smooth_levels_fwhm.setter - def smooth_levels_fwhm(self, value: float) -> None: - self._smooth_levels_fwhm = value - if self._discrete_path is not None: - self.discrete = self._discrete_path - - def self_if_none(self, *args, **kwargs): - """ wrapper for lib.self_if_none """ - return self_if_none(self, *args, **kwargs) - -def LeastSquares_linear(vec): - if vec.std is None: - w = np.ones(len(vec.values))*(2./len(vec.values)) - else: - w = 2./vec.std - - alpha = np.sum(w*vec.E**2) - beta = np.sum(w) - gamma = np.sum(w*vec.E) - p = np.sum(w*vec.E*vec.values) - q = np.sum(w*vec.values) - - mo = (beta*p - gamma*q)/(alpha*beta - gamma**2) - co = (alpha*q - gamma*p)/(alpha*beta - gamma**2) - - cov = np.array([[beta, -gamma],[-gamma, alpha]])*2/(alpha*beta - gamma) - - if vec.std is None: - S = 1/(len(vec.values) - 1)*sum((mo*vec.E + co - vec.values)**2) - w = np.ones(len(vec.values))*(2./S) - alpha = np.sum(w*vec.E**2) - beta = np.sum(w) - gamma = np.sum(w*vec.E) - p = np.sum(w*vec.E*vec.values) - q = np.sum(w*vec.values) - cov = np.array([[beta, -gamma],[-gamma, alpha]])*2/(alpha*beta - gamma) - return np.array([mo, co, S]), cov - return np.array([mo, co]), cov - -def load_cumulative_discrete(path: Union[str, Path]) -> Vector: - """ Load the cumulative number of levels without smoothing. - Args: - path: The file to load - Returns: - A vector with the cumulative number of levels. - """ - - energies = np.loadtxt(path) - energies /= 1e3 # convert to MeV - num = np.cumsum(np.ones(energies.shape)) - return Vector(values=num, E=energies) - -def load_levels_discrete(path: Union[str, Path], energy: ndarray) -> Vector: - """ Load discrete levels without smoothing - - Assumes linear equdistant binning - - Args: - path: The file to load - energy: The binning to use - Returns: - A vector describing the levels - """ - histogram, _ = load_discrete(path, energy, 0.1) - return Vector(values=histogram, E=energy) - - -def load_levels_smooth(path: Union[str, Path], energy: ndarray, - resolution: float = 0.1) -> Vector: - """ Load discrete levels with smoothing - - Assumes linear equdistant binning - - Args: - path: The file to load - energy: The binning to use in MeV - resolution: The resolution (FWHM) of the smoothing to use in MeV - Returns: - A vector describing the smoothed levels - """ - histogram, smoothed = load_discrete(path, energy, resolution) - return Vector(values=smoothed if resolution > 0 else histogram, E=energy) diff --git a/tests/not_a_vector_or_matrix.tar b/tests/not_a_vector_or_matrix.tar deleted file mode 100644 index 5c158847e5c74c1c071f610f296c613abcf37f8d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 20480 zcmeI2c~n$K7Kd2`6j9mt%@sw22AWmiUN9&+sE8UgK>@MZM3$zJZuZsV2JXfk7oxk=uofoH@_mk7eNersdt3jKL(R^7Kko+7L#^=0i!dqhG$|+N&9k0oH%LG ztqT?8xk?ahoNj-8aTR&K8fJC)DPMVgiu7{^T-fI8YDj-)!E8t5k+WldB>kQTjc3c2 zSC`h3{x3q>m-tPzBE^cKRU1*WpyKWia;THzCRxVE+uPOShx-^m*0)<$@>fm7an$GrP(gxf>lk80^u zS^1Fgdk9wFx9wYP*-kjNgE==m?Sy9sjAollItbSeFlE!zo zi}4B(orHHMsJgKZJto{A!(cYtPqWq>GG07f9ELZc_K$ieX9hAJu;!=szbO z-_F+N{nFfX$wzzca{{dXv+j@j&ql_S>c5^(kG|G_AzYEeM&(oA_%zC)Z_&sX&c588O2sn!(7K-8mQ;ql{%0T)`C;{MDlMqVQK0;9xHY(@dr>eLi(des&^{QBVo-L{<)xB!y5j$S9 z*h39dt8O@aouY;%T%cXOti7%by1oRy10)ESeN95E=u*Q9?1_qWUcaY^+=xRAxm9fUZ3QPK5}Ly z`Xq1kvFkBg^hy30pj7`GkUTQLn+)Zu8wRM&<&z=K;u6vj*KnW>@l1L+L)sAKxco9g zS0>s_7b6sNd1i!1S^0a!h~%3Qa>F~;nB<)?vRUiC+nD5^F>>K*nvgs+LC)+d6OxZ6 zD4qGHr0%(Ofa*WG|M%hkpA*l{+R>Wozn+_Q{ikPE|Jn3M{bx({UvFedU+celLX{Cb z^F(m><|}*d%!Dcar|V`L3&Bs^m2e_46TI`H4J^De;apN&=-P%1SUatK!57Vo!S=a4`AO z=j0oOCvF3^6Ef1$f}!@jf7i+2i2xnh6YF*fA#YH0_eRYOIN5w-(eM#5kbEFT(JDFy zd=)?KSACmp*Sov0hBjaTj>PNg4*)^ z;spiXP*_@Oc*rgthF3m&Giq-JI3)NLybMo=0P%8Dxur?quNJab&ejc{R3|Iuzl;Ij zvdTr-uK+@SRZTL>7eLO8>_KIo9`JM9rkI=8!$Gp&urALp4e}a`t~*sE0VbWDysl~q zG{4w(`uR2qG?)G$|I9-Kg&S0q7Fmg*c5q#Uwq**`h+G~;>dk>w&Lf*n=lVlz_0e?Q zUl5e%ug$2~7!LtvqR?XsAyBhj>zwt~K&V|Y%sp<@B*=NY-u`v*T)4YkGgli7VEg>C zZ8=W^!MLF%HCd7d1-^n8^1cD!9(=%{yFvsF(}Zh^VuPTz=!eP6_AG?94UI1C+Nn_T zxWYWA+!+?_f0?!4ITJPvJ))Z!n+3Q1D?)ZxN+8Mad*6|15m30`YgOGziQs>{EM!bY zJhXn1`kmyH47k(~Z!v$R2ohWmTJ2z-E86!Y!TDe&><}F>+7_1lf3pAg{#y|H6-fI1 zm-+uszyJ398^Ff#AHV-H`p@3ciEaS)JpI16!0JES{;2=>RR8rxcJ#IWqx*k!|1X*D z|Iz)wzdQd!&;Rwt+RxhfXXpQ%c=k3t2fF{)TVv3dc3Az#?~nS=j_SYO$cw(#fA3mn}4*X1SkPYfD)htC;>`<5}*Vq0ZM=ppaduZN`Mle1SkPYfD)ht UC;>`<5}*Vq0ZM=p_}?b*H?wDUW&i*H From dd10550b7eb2d93ffd57d3b28b63f96bd54c235a Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Thu, 13 Aug 2020 13:15:38 +0200 Subject: [PATCH 04/22] Forgot to remove trapezoid attribute --- ompy/extractor.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ompy/extractor.py b/ompy/extractor.py index 497c67ad..f766c301 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -79,7 +79,6 @@ def __init__(self, self.options = {'disp': True, 'ftol': 1e-3, 'maxfev': None} self.nld: List[Vector] = [] self.gsf: List[Vector] = [] - self.trapezoid = trapezoid if path is not None: self.path = Path(path) From 4a829c528df0b03afb7be4751e563ca931a3715c Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Fri, 14 Aug 2020 15:29:11 +0200 Subject: [PATCH 05/22] Added `save()` method I've added a dedicated save method and refactored the `extract_from()` method --- ompy/extractor.py | 80 ++++++++++++++++++++++++++++------------- tests/test_extractor.py | 7 ++++ 2 files changed, 63 insertions(+), 24 deletions(-) create mode 100644 tests/test_extractor.py diff --git a/ompy/extractor.py b/ompy/extractor.py index f766c301..233bb56f 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -66,6 +66,7 @@ class Extractor: - If path is given, it tries to load. If path is later set, it is not created. This is a very common pattern. Consider superclassing the disk book-keeping. + - Add proper unit test """ def __init__(self, path: Optional[Union[str, Path]] = None): @@ -116,9 +117,6 @@ def extract_from(self, ensemble: Ensemble, and gsf. regenerate (bool, optional): Whether to regenerate all nld and gsf even if they are found on disk. - - Raises: - ValueError: If no Ensemble instance is provided here or earlier. """ if regenerate is None: @@ -127,20 +125,23 @@ def extract_from(self, ensemble: Ensemble, nlds = [] gsfs = [] + + if regenerate: + try: # If successfully loaded, we are done! + LOG.debug(f"loading from {path}") + self.load(self.path) + return None + except RuntimeError: # We still need to do some number crunching + LOG.debug(f"Error loading, regenerating NLD and GSF") + pass + np.random.seed(self.seed) # seed also in `__init__` for i in tqdm(range(self.ensemble.size)): - nld_path = self.path / f'nld_{i}.npy' - gsf_path = self.path / f'gsf_{i}.npy' - if nld_path.exists() and gsf_path.exists() and not regenerate: - LOG.debug(f"loading from {nld_path} and {gsf_path}") - nlds.append(Vector(path=nld_path)) - gsfs.append(Vector(path=gsf_path)) - else: - nld, gsf = self.step(i) - nld.save(nld_path) - gsf.save(gsf_path) - nlds.append(nld) - gsfs.append(gsf) + nld, gsf = self.step(i) + nld.save(nld_path) + gsf.save(gsf_path) + nlds.append(nld) + gsfs.append(gsf) self.nld = nlds self.gsf = gsfs @@ -356,16 +357,42 @@ def guess_initial_values(self, E_nld: np.ndarray, matrix: Matrix, assert np.isfinite(x0).all return x0 + def save(self, path: Union[str, Path]): + """Save an ensemble of extracted NLD & GSF from disk. + + Args: + path: Path to folder to save the ensemble + + Raises: + RuntimeError if no NLD and GSF are set. + AssertionError if the number NLD and GSF are unequal. + """ + + path = Path(path) + + assert len(self.nld) == len(self.gsf), \ + "Number of NLD files doesn't match the number of GSF files." + + # Due to the assertion above, we are sure that NLD and GSF have + # the same length. We only need to check one of them! + if len(self.nld) <= 0: + raise RuntimeError("No NLD or GSF set") + + for (i, (nld, gsf)) in enumerate(zip(self.nld, self.gsf)): + nld_path = self.path / f'nld_{i}.npy' + gsf_path = self.path / f'gsf_{i}.npy' + nld.save(nld_path) + gsf.save(gsf_path) + def load(self, path: Union[str, Path]): - """Load an ensemble of from disk. + """Load an ensemble of extracted NLD & GSF from disk. Args: path: Path to folder with ensemble - Returns: - extractor object with gSF and NLD set. Raises: - RuntimeError if the number of NLD and GSF doesn't match. + RuntimeError if there are no NLD & GSF files in the provided path. + AssertionError if the number NLD and GSF are unequal. """ path = Path(path) @@ -375,13 +402,18 @@ def load(self, path: Union[str, Path]): num_gsf = len(fnmatch.filter(next(os.walk(path))[2], 'gsf_*.npy')) num_nld = len(fnmatch.filter(next(os.walk(path))[2], 'nld_*.npy')) - if num_gsf != num_nld: - raise RuntimeError("The number of GSF and NLD files doesn't match") - for i in range(num_gsf): + assert num_gsf == num_nld, \ + "Number of NLD files doesn't match the number of GSF files." + + num = num_gsf + + if num_gsf == num_nld == 0: + raise RuntimeError("No NLD and GSF files found.") + + for i in range(num): gsf_path = path / f'gsf_{i}.npy' - self.gsf.append(Vector(path=gsf_path)) - for i in range(num_nld): nld_path = path / f'nld_{i}.npy' + self.gsf.append(Vector(path=gsf_path)) self.nld.append(Vector(path=nld_path)) @staticmethod diff --git a/tests/test_extractor.py b/tests/test_extractor.py new file mode 100644 index 00000000..c1575f89 --- /dev/null +++ b/tests/test_extractor.py @@ -0,0 +1,7 @@ +import pytest +import numpy as np +import ompy as om + + +def test_extractor(): + om.Extractor() From 3c9c7ad727003541c22efbe8df4e2987e2aba10a Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Fri, 14 Aug 2020 15:35:20 +0200 Subject: [PATCH 06/22] Added release notes --- release_note.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/release_note.md b/release_note.md index b2d4382c..54b482f2 100644 --- a/release_note.md +++ b/release_note.md @@ -3,6 +3,9 @@ ## [Unreleased] Changes: - Fixed a bug where the `std` attribute of `Vector` was not saved to file. +- Changed the way the `Extractor` class are called. The ensamble and trapezoid are no longer given in the + constructor, but are mandatory arguments in the `extract_from()` method. The class also now uses the same + convention for loading and saving from file as the `Vector` and `Matrix` classes. ## v.1.1.0 Most important changes: From 981488d1cf217893cb34ed95aaace33bcd6f2ddc Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Fri, 14 Aug 2020 15:41:35 +0200 Subject: [PATCH 07/22] Bugfix --- ompy/extractor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ompy/extractor.py b/ompy/extractor.py index 233bb56f..bdba0a8f 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -86,7 +86,7 @@ def __init__(self, self.load(self.path) else: self.path = 'saved_run/extractor' - self.path = Path(path) + self.path = Path(self.path) self.path.mkdir(exist_ok=True, parents=True) self.x0 = None From 235b836507bc7a9e068847bf221461c8053864ef Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Fri, 14 Aug 2020 15:43:15 +0200 Subject: [PATCH 08/22] Argh... Another fix Guess this is why you want unit tests... --- ompy/extractor.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ompy/extractor.py b/ompy/extractor.py index bdba0a8f..4ec51607 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -121,7 +121,7 @@ def extract_from(self, ensemble: Ensemble, if regenerate is None: regenerate = self.regenerate - self.path = Path(self.path) + path = Path(self.path) nlds = [] gsfs = [] @@ -136,7 +136,7 @@ def extract_from(self, ensemble: Ensemble, pass np.random.seed(self.seed) # seed also in `__init__` - for i in tqdm(range(self.ensemble.size)): + for i in tqdm(range(ensemble.size)): nld, gsf = self.step(i) nld.save(nld_path) gsf.save(gsf_path) From c133e438147ba2b19ff5ed35a547a3bdc0ce61d6 Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Fri, 14 Aug 2020 15:45:53 +0200 Subject: [PATCH 09/22] Urg... I should test my code before committing more... I know... I know... Btw, does anyone read these? --- ompy/extractor.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ompy/extractor.py b/ompy/extractor.py index 4ec51607..587310b4 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -137,14 +137,13 @@ def extract_from(self, ensemble: Ensemble, np.random.seed(self.seed) # seed also in `__init__` for i in tqdm(range(ensemble.size)): - nld, gsf = self.step(i) - nld.save(nld_path) - gsf.save(gsf_path) + nld, gsf = self.step(ensemble, trapezoid, i) nlds.append(nld) gsfs.append(gsf) self.nld = nlds self.gsf = gsfs + self.save(self.path) def step(self, ensemble: Ensemble, trapezoid: Action, num: int) -> Tuple[Vector, Vector]: @@ -159,7 +158,7 @@ def step(self, ensemble: Ensemble, trapezoid: Action, and gsf. num: Number of the fg matrix to extract """ - nld, gsf = self._extract(num) + nld, gsf = self._extract(ensemble, trapezoid, num) return nld, gsf def _extract(self, ensemble: Ensemble, trapezoid: Action, @@ -190,7 +189,7 @@ def _extract(self, ensemble: Ensemble, trapezoid: Action, else: trapezoid.act_on(matrix) trapezoid.act_on(std) - nld, gsf = decompose(matrix, std) + nld, gsf = self.decompose(matrix, std) return nld, gsf def decompose(self, matrix: Matrix, From d1111bc03f75fb52f223f8f09b44cf3dd9290d9c Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Fri, 14 Aug 2020 15:49:21 +0200 Subject: [PATCH 10/22] Updated getting started notebook I've updated the getting started notebook to reflect the change in syntax. --- notebooks/getting_started.ipynb | 20108 ++++++++++++++---------------- 1 file changed, 9376 insertions(+), 10732 deletions(-) diff --git a/notebooks/getting_started.ipynb b/notebooks/getting_started.ipynb index 6e496c44..36f27fd2 100644 --- a/notebooks/getting_started.ipynb +++ b/notebooks/getting_started.ipynb @@ -38,7 +38,7 @@ { "data": { "text/plain": [ - "'1.0.0.dev0+694b2ea'" + "'1.1.0.dev0+c133e43'" ] }, "execution_count": 3, @@ -96,36 +96,38 @@ "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", "window.mpl = {};\n", "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", + " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", " }\n", " }\n", "\n", @@ -140,11 +142,11 @@ "\n", " this.image_mode = 'full';\n", "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", "\n", - " $(parent_element).append(this.root);\n", + " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", @@ -154,281 +156,325 @@ "\n", " this.waiting = false;\n", "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", " }\n", + " fig.send_message('refresh', {});\n", + " };\n", "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", "\n", - " this.imageObj.onunload = function() {\n", + " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", - " }\n", + " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", + "};\n", "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", - "}\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", - "mpl.figure.prototype._init_canvas = function() {\n", + "mpl.figure.prototype._init_canvas = function () {\n", " var fig = this;\n", "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", " }\n", "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", " });\n", + " resizeObserver.observe(canvas_div);\n", "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", " }\n", "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", + " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", - " mouse_event_fn(event);\n", + " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", - "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", - "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", - "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", "\n", " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", " return false;\n", " });\n", "\n", - " function set_focus () {\n", + " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", + "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", " }\n", "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", - " // put a spacer in here.\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", "\n", " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", " });\n", - "}\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", + " el.setAttribute('tabindex', 0);\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", + " } else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", + "};\n", "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", + " if (!manager) {\n", " manager = IPython.keyboard_manager;\n", + " }\n", "\n", " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", + " if (event.shiftKey && event.which === 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " fig.ondownload(fig, null);\n", - "}\n", - "\n", + "};\n", "\n", - "mpl.find_output_cell = function(html_output) {\n", + "mpl.find_output_cell = function (html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", - " if (data['text/html'] == html_output) {\n", + " if (data['text/html'] === html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", - "}\n", + "};\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", "}\n" ], "text/plain": [ @@ -1733,7 +1999,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -1764,36 +2030,38 @@ "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", "window.mpl = {};\n", "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", + " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", " }\n", " }\n", "\n", @@ -1808,11 +2076,11 @@ "\n", " this.image_mode = 'full';\n", "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", "\n", - " $(parent_element).append(this.root);\n", + " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", @@ -1822,281 +2090,325 @@ "\n", " this.waiting = false;\n", "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", " }\n", + " fig.send_message('refresh', {});\n", + " };\n", "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", "\n", - " this.imageObj.onunload = function() {\n", + " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", - " }\n", + " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", + "};\n", "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", - "}\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", - "mpl.figure.prototype._init_canvas = function() {\n", + "mpl.figure.prototype._init_canvas = function () {\n", " var fig = this;\n", "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", " }\n", "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", + " this.context = canvas.getContext('2d');\n", "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", " });\n", + " resizeObserver.observe(canvas_div);\n", "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", " }\n", "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", + " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", - " mouse_event_fn(event);\n", + " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", - "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", - "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", - "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", "\n", " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", " return false;\n", " });\n", "\n", - " function set_focus () {\n", + " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", + "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", " }\n", "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", - " // put a spacer in here.\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", "\n", " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", " });\n", - "}\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", + " el.setAttribute('tabindex', 0);\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", + " } else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", + "};\n", "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", + " if (!manager) {\n", " manager = IPython.keyboard_manager;\n", + " }\n", "\n", " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", + " if (event.shiftKey && event.which === 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " fig.ondownload(fig, null);\n", - "}\n", - "\n", + "};\n", "\n", - "mpl.find_output_cell = function(html_output) {\n", + "mpl.find_output_cell = function (html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", - " if (data['text/html'] == html_output) {\n", + " if (data['text/html'] === html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", - "}\n", + "};\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", "}\n" ], "text/plain": [ @@ -3393,7 +3925,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -3449,44 +3981,46 @@ "name": "stdout", "output_type": "stream", "text": [ - "2020-04-04 16:20:37,716 - ompy.response - INFO - Note: Spectra outside of 200.0 and 20000.0 are extrapolation only.\n", - "2020-04-04 16:20:42,807 - ompy.response - INFO - Note: Spectra outside of 200.0 and 20000.0 are extrapolation only.\n" + "2020-08-14 15:47:56,002 - ompy.response - INFO - Note: Spectra outside of 200.0 and 20000.0 are extrapolation only.\n", + "2020-08-14 15:48:03,029 - ompy.response - INFO - Note: Spectra outside of 200.0 and 20000.0 are extrapolation only.\n" ] }, { "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", "window.mpl = {};\n", "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", + " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", " }\n", " }\n", "\n", @@ -3501,11 +4035,11 @@ "\n", " this.image_mode = 'full';\n", "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", "\n", - " $(parent_element).append(this.root);\n", + " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", @@ -3515,281 +4049,325 @@ "\n", " this.waiting = false;\n", "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", " }\n", + " fig.send_message('refresh', {});\n", + " };\n", "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", "\n", - " this.imageObj.onunload = function() {\n", + " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", - " }\n", + " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", + "};\n", "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", - "}\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", - "mpl.figure.prototype._init_canvas = function() {\n", + "mpl.figure.prototype._init_canvas = function () {\n", " var fig = this;\n", "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", " }\n", "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", " });\n", + " resizeObserver.observe(canvas_div);\n", "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", " }\n", "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", + " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", - " mouse_event_fn(event);\n", + " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", - "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", - "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", - "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", "\n", " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", " return false;\n", " });\n", "\n", - " function set_focus () {\n", + " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", + "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", " }\n", "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", - " // put a spacer in here.\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", "\n", " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", " });\n", - "}\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", + " el.setAttribute('tabindex', 0);\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", + " } else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", + "};\n", "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", + " if (!manager) {\n", " manager = IPython.keyboard_manager;\n", + " }\n", "\n", " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", + " if (event.shiftKey && event.which === 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " fig.ondownload(fig, null);\n", - "}\n", - "\n", + "};\n", "\n", - "mpl.find_output_cell = function(html_output) {\n", + "mpl.find_output_cell = function (html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", - " if (data['text/html'] == html_output) {\n", + " if (data['text/html'] === html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", - "}\n", + "};\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", "}\n" ], "text/plain": [ @@ -5056,7 +5854,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -5103,36 +5901,38 @@ "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", "window.mpl = {};\n", "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", + " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", " }\n", " }\n", "\n", @@ -5147,11 +5947,11 @@ "\n", " this.image_mode = 'full';\n", "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", "\n", - " $(parent_element).append(this.root);\n", + " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", @@ -5161,281 +5961,325 @@ "\n", " this.waiting = false;\n", "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", " }\n", + " fig.send_message('refresh', {});\n", + " };\n", "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", "\n", - " this.imageObj.onunload = function() {\n", + " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", - " }\n", + " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", + "};\n", "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", - "}\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", - "\n", - "}\n", - "\n", - "mpl.figure.prototype._init_canvas = function() {\n", - " var fig = this;\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", "\n", - " var canvas_div = $('
');\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", - " }\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", + " this.context = canvas.getContext('2d');\n", "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", + " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", "\n", - " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", " });\n", + " resizeObserver.observe(canvas_div);\n", "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", " }\n", "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", + " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", - " mouse_event_fn(event);\n", + " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", - "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", - "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", - "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", "\n", " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", " return false;\n", " });\n", "\n", - " function set_focus () {\n", + " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", + "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", " }\n", "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", - " // put a spacer in here.\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", "\n", " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", " });\n", - "}\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", + " el.setAttribute('tabindex', 0);\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", + " } else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", + "};\n", "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", + " if (!manager) {\n", " manager = IPython.keyboard_manager;\n", + " }\n", "\n", " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", + " if (event.shiftKey && event.which === 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " fig.ondownload(fig, null);\n", - "}\n", - "\n", + "};\n", "\n", - "mpl.find_output_cell = function(html_output) {\n", + "mpl.find_output_cell = function (html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", - " if (data['text/html'] == html_output) {\n", + " if (data['text/html'] === html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", - "}\n", + "};\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", "}\n" ], "text/plain": [ @@ -6782,7 +7846,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -6795,36 +7859,38 @@ "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", "window.mpl = {};\n", "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", + " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", " }\n", " }\n", "\n", @@ -6839,11 +7905,11 @@ "\n", " this.image_mode = 'full';\n", "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", "\n", - " $(parent_element).append(this.root);\n", + " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", @@ -6853,281 +7919,325 @@ "\n", " this.waiting = false;\n", "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", " }\n", + " fig.send_message('refresh', {});\n", + " };\n", "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", "\n", - " this.imageObj.onunload = function() {\n", + " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", - " }\n", + " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", + "};\n", "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", - "}\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", - "mpl.figure.prototype._init_canvas = function() {\n", + "mpl.figure.prototype._init_canvas = function () {\n", " var fig = this;\n", "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", " }\n", "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", + " this.context = canvas.getContext('2d');\n", "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", " });\n", + " resizeObserver.observe(canvas_div);\n", "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", " }\n", "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", + " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", - " mouse_event_fn(event);\n", + " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", - "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", - "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", - "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", "\n", " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", " return false;\n", " });\n", "\n", - " function set_focus () {\n", + " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", + "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", " }\n", "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", - " // put a spacer in here.\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", "\n", " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", " });\n", - "}\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", + " el.setAttribute('tabindex', 0);\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", + " } else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", + "};\n", "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", + " if (!manager) {\n", " manager = IPython.keyboard_manager;\n", + " }\n", "\n", " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", + " if (event.shiftKey && event.which === 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " fig.ondownload(fig, null);\n", - "}\n", - "\n", + "};\n", "\n", - "mpl.find_output_cell = function(html_output) {\n", + "mpl.find_output_cell = function (html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", - " if (data['text/html'] == html_output) {\n", + " if (data['text/html'] === html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", - "}\n", + "};\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", "}\n" ], "text/plain": [ @@ -8449,7 +9779,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -8464,7 +9794,7 @@ "trapezoid_cut = om.Action('matrix')\n", "trapezoid_cut.trapezoid(Ex_min=4000, Ex_max=7000, Eg_min=1000, Eg_max=7000+200, inplace=True)\n", "extractor = om.Extractor()\n", - "extractor.trapezoid = trapezoid_cut\n", + "\n", "# Running the lines below directy, would most probably \n", "# result in a error like\n", "# The AssertionError: Ex and Eg must have the same step size\n", @@ -8493,33 +9823,11 @@ "cell_type": "code", "execution_count": 21, "metadata": { - "scrolled": true + "scrolled": false }, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "7cfb576bcf15465d8913ac6a0995340e", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "HBox(children=(IntProgress(value=0, max=10), HTML(value='')))" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], + "outputs": [], "source": [ - "extractor.extract_from(ensemble, regenerate=True)" + "extractor.extract_from(ensemble, trapezoid_cut, regenerate=True)" ] }, { @@ -8538,36 +9846,38 @@ "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", "window.mpl = {};\n", "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", + " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", " }\n", " }\n", "\n", @@ -8582,11 +9892,11 @@ "\n", " this.image_mode = 'full';\n", "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", "\n", - " $(parent_element).append(this.root);\n", + " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", @@ -8596,281 +9906,325 @@ "\n", " this.waiting = false;\n", "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", " }\n", + " fig.send_message('refresh', {});\n", + " };\n", "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", "\n", - " this.imageObj.onunload = function() {\n", + " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", - " }\n", + " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", + "};\n", "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", - "}\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", - "mpl.figure.prototype._init_canvas = function() {\n", + "mpl.figure.prototype._init_canvas = function () {\n", " var fig = this;\n", "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", " }\n", "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", + " this.context = canvas.getContext('2d');\n", "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", " });\n", + " resizeObserver.observe(canvas_div);\n", "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", " }\n", "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", + " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", - " mouse_event_fn(event);\n", + " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", - "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", - "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", - "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", "\n", " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", " return false;\n", " });\n", "\n", - " function set_focus () {\n", + " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", + "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", " }\n", "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", - " // put a spacer in here.\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", "\n", " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", " });\n", - "}\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", + " el.setAttribute('tabindex', 0);\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", + " } else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", + "};\n", "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", + " if (!manager) {\n", " manager = IPython.keyboard_manager;\n", + " }\n", "\n", " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", + " if (event.shiftKey && event.which === 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " fig.ondownload(fig, null);\n", - "}\n", - "\n", + "};\n", "\n", - "mpl.find_output_cell = function(html_output) {\n", + "mpl.find_output_cell = function (html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", - " if (data['text/html'] == html_output) {\n", + " if (data['text/html'] === html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", - "}\n", + "};\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", "}\n" ], "text/plain": [ @@ -10135,7 +11709,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -10147,8 +11721,8 @@ { "data": { "text/plain": [ - "(,\n", - " ,\n", + "(,\n", + " ,\n", "
)" ] }, @@ -10196,36 +11770,38 @@ "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", "window.mpl = {};\n", "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", + " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", " }\n", " }\n", "\n", @@ -10240,11 +11816,11 @@ "\n", " this.image_mode = 'full';\n", "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", "\n", - " $(parent_element).append(this.root);\n", + " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", @@ -10254,281 +11830,325 @@ "\n", " this.waiting = false;\n", "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", " }\n", + " fig.send_message('refresh', {});\n", + " };\n", "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", "\n", - " this.imageObj.onunload = function() {\n", + " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", - " }\n", + " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", + "};\n", "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", - "}\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", - "mpl.figure.prototype._init_canvas = function() {\n", + "mpl.figure.prototype._init_canvas = function () {\n", " var fig = this;\n", "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", " }\n", "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", + " this.context = canvas.getContext('2d');\n", "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", " });\n", + " resizeObserver.observe(canvas_div);\n", "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", " }\n", "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", + " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", - " mouse_event_fn(event);\n", + " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", - "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", - "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", - "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", "\n", " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", " return false;\n", " });\n", "\n", - " function set_focus () {\n", + " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", + "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", " }\n", "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", - " // put a spacer in here.\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", "\n", " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", " });\n", - "}\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", + " el.setAttribute('tabindex', 0);\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", + " } else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", + "};\n", "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", + " if (!manager) {\n", " manager = IPython.keyboard_manager;\n", + " }\n", "\n", " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", + " if (event.shiftKey && event.which === 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " fig.ondownload(fig, null);\n", - "}\n", - "\n", + "};\n", "\n", - "mpl.find_output_cell = function(html_output) {\n", + "mpl.find_output_cell = function (html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", - " if (data['text/html'] == html_output) {\n", + " if (data['text/html'] === html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", - "}\n", + "};\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", "}\n" ], "text/plain": [ @@ -11799,7 +13638,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -11812,9 +13651,8 @@ "data": { "text/plain": [ "(
,\n", - " array([,\n", - " ],\n", - " dtype=object))" + " array([,\n", + " ], dtype=object))" ] }, "execution_count": 25, @@ -11869,36 +13707,38 @@ "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", "window.mpl = {};\n", "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", + " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", " }\n", " }\n", "\n", @@ -11913,11 +13753,11 @@ "\n", " this.image_mode = 'full';\n", "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", "\n", - " $(parent_element).append(this.root);\n", + " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", @@ -11927,281 +13767,325 @@ "\n", " this.waiting = false;\n", "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", " }\n", + " fig.send_message('refresh', {});\n", + " };\n", "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", "\n", - " this.imageObj.onunload = function() {\n", + " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", - " }\n", + " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", + "};\n", "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", - "}\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", - "mpl.figure.prototype._init_canvas = function() {\n", + "mpl.figure.prototype._init_canvas = function () {\n", " var fig = this;\n", "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", " }\n", "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", + " this.context = canvas.getContext('2d');\n", "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", " });\n", + " resizeObserver.observe(canvas_div);\n", "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", " }\n", "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", + " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", - " mouse_event_fn(event);\n", + " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", - "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", - "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", - "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", "\n", " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", " return false;\n", " });\n", "\n", - " function set_focus () {\n", + " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", + "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", " }\n", "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", - " // put a spacer in here.\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", "\n", " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", " });\n", - "}\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", + " el.setAttribute('tabindex', 0);\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", + " } else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", + "};\n", "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", + " if (!manager) {\n", " manager = IPython.keyboard_manager;\n", + " }\n", "\n", " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", + " if (event.shiftKey && event.which === 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " fig.ondownload(fig, null);\n", - "}\n", - "\n", + "};\n", "\n", - "mpl.find_output_cell = function(html_output) {\n", + "mpl.find_output_cell = function (html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", - " if (data['text/html'] == html_output) {\n", + " if (data['text/html'] === html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", - "}\n", + "};\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", "}\n" ], "text/plain": [ @@ -13579,7 +15683,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -13637,44 +15741,46 @@ "name": "stdout", "output_type": "stream", "text": [ - "2020-04-04 16:21:38,498 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:21:38,507 - ompy.normalizer_gsf - INFO - Saving to saved_run/normalizers/NormalizerGSF.pkl\n" + "2020-08-14 15:48:38,832 - ompy.normalizer_gsf - INFO - Normalizing #0\n", + "2020-08-14 15:48:38,837 - ompy.normalizer_gsf - INFO - Saving to saved_run/normalizers/NormalizerGSF.pkl\n" ] }, { "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", "window.mpl = {};\n", "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", "\n", " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", + " var warnings = document.getElementById('mpl-warnings');\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", " }\n", " }\n", "\n", @@ -13689,11 +15795,11 @@ "\n", " this.image_mode = 'full';\n", "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", "\n", - " $(parent_element).append(this.root);\n", + " parent_element.appendChild(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", @@ -13703,281 +15809,325 @@ "\n", " this.waiting = false;\n", "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", " }\n", + " fig.send_message('refresh', {});\n", + " };\n", "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", "\n", - " this.imageObj.onunload = function() {\n", + " this.imageObj.onunload = function () {\n", " fig.ws.close();\n", - " }\n", + " };\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", + "};\n", "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", "\n", - "}\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", "\n", - "mpl.figure.prototype._init_canvas = function() {\n", + "mpl.figure.prototype._init_canvas = function () {\n", " var fig = this;\n", "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", " }\n", "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", + " this.context = canvas.getContext('2d');\n", "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", " });\n", + " resizeObserver.observe(canvas_div);\n", "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", " }\n", "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", + " canvas_div.addEventListener('wheel', function (event) {\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", - " mouse_event_fn(event);\n", + " on_mouse_event_closure('scroll')(event);\n", " });\n", "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", - "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", - "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", - "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", "\n", " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", " return false;\n", " });\n", "\n", - " function set_focus () {\n", + " function set_focus() {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", + "mpl.figure.prototype._init_toolbar = function () {\n", " var fig = this;\n", "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", " }\n", "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", - " // put a spacer in here.\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", " continue;\n", " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", " }\n", "\n", " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", "\n", " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", " });\n", - "}\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", + " el.setAttribute('tabindex', 0);\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", + " } else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", + "};\n", "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", + " if (!manager) {\n", " manager = IPython.keyboard_manager;\n", + " }\n", "\n", " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", + " if (event.shiftKey && event.which === 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", - "}\n", + "};\n", "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", " fig.ondownload(fig, null);\n", - "}\n", - "\n", + "};\n", "\n", - "mpl.find_output_cell = function(html_output) {\n", + "mpl.find_output_cell = function (html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", - " if (data['text/html'] == html_output) {\n", + " if (data['text/html'] === html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", - "}\n", + "};\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", "}\n" ], "text/plain": [ @@ -15249,7 +17619,7 @@ { "data": { "text/html": [ - "" + "
" ], "text/plain": [ "" @@ -15261,7 +17631,7 @@ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "eb4b6632cae44785ba38343a7e1fda3a", + "model_id": "ce90736802144ce2b046f5821e9cb055", "version_major": 2, "version_minor": 0 }, @@ -15287,7 +17657,7 @@ }, { "cell_type": "code", - "execution_count": 34, + "execution_count": null, "metadata": { "scrolled": false }, @@ -15296,28 +17666,20 @@ "name": "stdout", "output_type": "stream", "text": [ - "2020-04-04 16:21:40,222 - ompy.normalizer_nld - INFO - DE results:\n", - "┌───────────────────┬───────────────────┬────────────────────┬─────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞═══════════════════╪═══════════════════╪════════════════════╪═════════════════════╡\n", - "│ 1.287759290975031 │ 1.309826762269522 │ 0.5397650548336684 │ 0.03316120211583037 │\n", - "└───────────────────┴───────────────────┴────────────────────┴─────────────────────┘\n", - "2020-04-04 16:21:40,260 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:21:40,264 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌───────────────────┬───────────────────┬────────────────────┬─────────────────────┬───────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═══════════════════╪═══════════════════╪════════════════════╪═════════════════════╪═══════════════════╡\n", - "│ 1.287759290975031 │ 1.309826762269522 │ 0.5397650548336684 │ 0.03316120211583037 │ 52.81452126553078 │\n", - "└───────────────────┴───────────────────┴────────────────────┴─────────────────────┴───────────────────┘\n", - "2020-04-04 16:21:40,264 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - " analysing data from multinest/sim_norm_0_.txt\n", - "2020-04-04 16:22:44,880 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.35 ± 0.17 │ 1.282 ± 0.053 │ 0.534 ± 0.016 │ 0.13 ± 0.24 │ 64 ± 20 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - "2020-04-04 16:22:44,883 - ompy.normalizer_simultan - INFO - Saving to saved_run/normalizers/NormalizerSimultan.pkl\n" + "2020-08-14 15:48:40,143 - ompy.normalizer_nld - INFO - DE results:\n", + "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╡\n", + "│ 1.3041657754481422 │ 1.3047666835840441 │ 0.5397053066859719 │ 0.033943533839594545 │\n", + "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┘\n", + "2020-08-14 15:48:40,186 - ompy.normalizer_gsf - INFO - Normalizing #0\n", + "2020-08-14 15:48:40,190 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", + "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┬────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", + "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╪════════════════════╡\n", + "│ 1.3041657754481422 │ 1.3047666835840441 │ 0.5397053066859719 │ 0.033943533839594545 │ 53.252395120263344 │\n", + "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┴────────────────────┘\n", + "2020-08-14 15:48:40,191 - ompy.normalizer_simultan - INFO - Starting multinest: \n" ] } ], @@ -15335,3822 +17697,104 @@ }, { "cell_type": "code", - "execution_count": 35, + "execution_count": null, "metadata": { "scrolled": false }, - "outputs": [ - { - "data": { - "application/javascript": [ - "/* Put everything inside the global mpl namespace */\n", - "window.mpl = {};\n", - "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", - " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", - " return MozWebSocket;\n", - " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", - "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", - " this.id = figure_id;\n", - "\n", - " this.ws = websocket;\n", - "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", - "\n", - " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", - " if (warnings) {\n", - " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", - " }\n", - " }\n", - "\n", - " this.imageObj = new Image();\n", - "\n", - " this.context = undefined;\n", - " this.message = undefined;\n", - " this.canvas = undefined;\n", - " this.rubberband_canvas = undefined;\n", - " this.rubberband_context = undefined;\n", - " this.format_dropdown = undefined;\n", - "\n", - " this.image_mode = 'full';\n", - "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", - "\n", - " $(parent_element).append(this.root);\n", - "\n", - " this._init_header(this);\n", - " this._init_canvas(this);\n", - " this._init_toolbar(this);\n", - "\n", - " var fig = this;\n", - "\n", - " this.waiting = false;\n", - "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", - " }\n", - "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", - "\n", - " this.imageObj.onunload = function() {\n", - " fig.ws.close();\n", - " }\n", - "\n", - " this.ws.onmessage = this._make_on_message_function(this);\n", - "\n", - " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", - "\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", - "\n", - "}\n", - "\n", - "mpl.figure.prototype._init_canvas = function() {\n", - " var fig = this;\n", - "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", - "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", - " }\n", - "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", - "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", - "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", - "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", - "\n", - " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", - "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " });\n", - "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", - " }\n", - "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", - " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", - "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", - "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", - " if (event.deltaY < 0) {\n", - " event.step = 1;\n", - " } else {\n", - " event.step = -1;\n", - " }\n", - " mouse_event_fn(event);\n", - " });\n", - "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", - "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", - "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", - "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", - "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", - "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", - "\n", - " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", - " return false;\n", - " });\n", - "\n", - " function set_focus () {\n", - " canvas.focus();\n", - " canvas_div.focus();\n", - " }\n", - "\n", - " window.setTimeout(set_focus, 100);\n", - "}\n", - "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", - " var fig = this;\n", - "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", - "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", - " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", - " }\n", - "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", - " var name = mpl.toolbar_items[toolbar_ind][0];\n", - " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", - " var image = mpl.toolbar_items[toolbar_ind][2];\n", - " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", - "\n", - " if (!name) {\n", - " // put a spacer in here.\n", - " continue;\n", - " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", - " }\n", - "\n", - " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", - "\n", - " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", - " });\n", - "}\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", - " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", - " // reach out to IPython and tell the keyboard manager to turn it's self\n", - " // off when our div gets focus\n", - "\n", - " // location in version 3\n", - " if (IPython.notebook.keyboard_manager) {\n", - " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", - " // location in version 2\n", - " IPython.keyboard_manager.register_events(el);\n", - " }\n", - "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", - " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", - " manager = IPython.keyboard_manager;\n", - "\n", - " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", - " this.canvas_div.blur();\n", - " // select the cell after this one\n", - " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", - " IPython.notebook.select(index + 1);\n", - " }\n", - "}\n", - "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", - " fig.ondownload(fig, null);\n", - "}\n", - "\n", - "\n", - "mpl.find_output_cell = function(html_output) {\n", - " // Return the cell and output element which can be found *uniquely* in the notebook.\n", - " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", - " // IPython event is triggered only after the cells have been serialised, which for\n", - " // our purposes (turning an active figure into a static one), is too late.\n", - " var cells = IPython.notebook.get_cells();\n", - " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", - " data = data.data;\n", - " }\n", - " if (data['text/html'] == html_output) {\n", - " return [cell, data, j];\n", - " }\n", - " }\n", - " }\n", - " }\n", - "}\n", - "\n", - "// Register the function which deals with the matplotlib target/channel.\n", - "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", - "}\n" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "ensemblenorm_seq.plot();" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Simultaneous normalization" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "metadata": { - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2020-04-04 16:24:23,599 - ompy.ensembleNormalizer - INFO - Start normalization with 3 cpus\n", - "2020-04-04 16:24:23,647 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #0\n" - ] - }, - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "c9ca865cac3b49c4808a414a3071a9fd", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "HBox(children=(IntProgress(value=0, max=10), HTML(value='')))" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2020-04-04 16:24:23,679 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #1\n", - "2020-04-04 16:24:23,709 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #2\n", - "2020-04-04 16:24:25,193 - ompy.normalizer_nld - INFO - DE results:\n", - "┌───────────────────┬────────────────────┬────────────────────┬───────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞═══════════════════╪════════════════════╪════════════════════╪═══════════════════════╡\n", - "│ 2.343440499461769 │ 1.1926117576347586 │ 0.5451333360784656 │ -0.047199636305156854 │\n", - "└───────────────────┴────────────────────┴────────────────────┴───────────────────────┘\n", - "2020-04-04 16:24:25,257 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:24:25,267 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌───────────────────┬────────────────────┬────────────────────┬───────────────────────┬───────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═══════════════════╪════════════════════╪════════════════════╪═══════════════════════╪═══════════════════╡\n", - "│ 2.343440499461769 │ 1.1926117576347586 │ 0.5451333360784656 │ -0.047199636305156854 │ 44.49796642232815 │\n", - "└───────────────────┴────────────────────┴────────────────────┴───────────────────────┴───────────────────┘\n", - "2020-04-04 16:24:25,270 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - "2020-04-04 16:24:25,397 - ompy.normalizer_nld - INFO - DE results:\n", - "┌────────────────────┬────────────────────┬────────────────────┬─────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞════════════════════╪════════════════════╪════════════════════╪═════════════════════╡\n", - "│ 1.2877590247288375 │ 1.3098273145123471 │ 0.5397651139680743 │ 0.03315942561089273 │\n", - "└────────────────────┴────────────────────┴────────────────────┴─────────────────────┘\n", - "2020-04-04 16:24:25,442 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:24:25,448 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌────────────────────┬────────────────────┬────────────────────┬─────────────────────┬───────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞════════════════════╪════════════════════╪════════════════════╪═════════════════════╪═══════════════════╡\n", - "│ 1.2877590247288375 │ 1.3098273145123471 │ 0.5397651139680743 │ 0.03315942561089273 │ 52.81442541677153 │\n", - "└────────────────────┴────────────────────┴────────────────────┴─────────────────────┴───────────────────┘\n", - "2020-04-04 16:24:25,451 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - "2020-04-04 16:24:25,625 - ompy.normalizer_nld - INFO - DE results:\n", - "┌────────────────────┬────────────────────┬───────────────────┬─────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞════════════════════╪════════════════════╪═══════════════════╪═════════════════════╡\n", - "│ 1.5746639389074824 │ 1.2808663762719936 │ 0.544487593866304 │ -0.0377093976977122 │\n", - "└────────────────────┴────────────────────┴───────────────────┴─────────────────────┘\n", - "2020-04-04 16:24:25,669 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:24:25,676 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌────────────────────┬────────────────────┬───────────────────┬─────────────────────┬────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞════════════════════╪════════════════════╪═══════════════════╪═════════════════════╪════════════════════╡\n", - "│ 1.5746639389074824 │ 1.2808663762719936 │ 0.544487593866304 │ -0.0377093976977122 │ 40.509954749962596 │\n", - "└────────────────────┴────────────────────┴───────────────────┴─────────────────────┴────────────────────┘\n", - "2020-04-04 16:24:25,679 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - " analysing data from multinest/sim_norm_2_.txt\n", - "2020-04-04 16:25:44,422 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 2.44 ± 0.29 │ 1.169 ± 0.053 │ 0.541 ± 0.019 │ 0.03 ± 0.27 │ 84 ± 27 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - "2020-04-04 16:25:44,436 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #3\n", - "2020-04-04 16:25:45,899 - ompy.normalizer_nld - INFO - DE results:\n", - "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╡\n", - "│ 1.3616560185453892 │ 1.3055160639605388 │ 0.5442968879528234 │ -0.03574570998749427 │\n", - "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┘\n", - "2020-04-04 16:25:45,954 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:25:45,960 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┬───────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╪═══════════════════╡\n", - "│ 1.3616560185453892 │ 1.3055160639605388 │ 0.5442968879528234 │ -0.03574570998749427 │ 43.45466444343041 │\n", - "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┴───────────────────┘\n", - "2020-04-04 16:25:45,961 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - " analysing data from multinest/sim_norm_0_.txt\n", - "2020-04-04 16:25:57,504 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.36 ± 0.17 │ 1.286 ± 0.054 │ 0.535 ± 0.019 │ 0.12 ± 0.27 │ 63 ± 21 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - "2020-04-04 16:25:57,547 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #4\n", - " analysing data from multinest/sim_norm_1_.txt\n", - "2020-04-04 16:25:58,258 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.65 ± 0.20 │ 1.255 ± 0.051 │ 0.540 ± 0.017 │ 0.04 ± 0.25 │ 54 ± 16 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - "2020-04-04 16:25:58,268 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #5\n", - "2020-04-04 16:25:59,575 - ompy.normalizer_nld - INFO - DE results:\n", - "┌────────────────────┬────────────────────┬────────────────────┬───────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞════════════════════╪════════════════════╪════════════════════╪═══════════════════════╡\n", - "│ 1.6109973754356604 │ 1.2492750454340034 │ 0.5429339254671807 │ -0.015268639789714654 │\n", - "└────────────────────┴────────────────────┴────────────────────┴───────────────────────┘\n", - "2020-04-04 16:25:59,624 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:25:59,630 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌────────────────────┬────────────────────┬────────────────────┬───────────────────────┬───────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞════════════════════╪════════════════════╪════════════════════╪═══════════════════════╪═══════════════════╡\n", - "│ 1.6109973754356604 │ 1.2492750454340034 │ 0.5429339254671807 │ -0.015268639789714654 │ 38.93411251696435 │\n", - "└────────────────────┴────────────────────┴────────────────────┴───────────────────────┴───────────────────┘\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2020-04-04 16:25:59,634 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - "2020-04-04 16:26:00,333 - ompy.normalizer_nld - INFO - DE results:\n", - "┌───────────────────┬───────────────────┬────────────────────┬──────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞═══════════════════╪═══════════════════╪════════════════════╪══════════════════════╡\n", - "│ 1.644506926775518 │ 1.362697925641007 │ 0.5477140673424018 │ -0.08656331207395147 │\n", - "└───────────────────┴───────────────────┴────────────────────┴──────────────────────┘\n", - "2020-04-04 16:26:00,378 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:26:00,384 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌───────────────────┬───────────────────┬────────────────────┬──────────────────────┬───────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═══════════════════╪═══════════════════╪════════════════════╪══════════════════════╪═══════════════════╡\n", - "│ 1.644506926775518 │ 1.362697925641007 │ 0.5477140673424018 │ -0.08656331207395147 │ 47.64850809785776 │\n", - "└───────────────────┴───────────────────┴────────────────────┴──────────────────────┴───────────────────┘\n", - "2020-04-04 16:26:00,385 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - " analysing data from multinest/sim_norm_3_.txt\n", - "2020-04-04 16:27:06,957 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.43 ± 0.18 │ 1.286 ± 0.054 │ 0.540 ± 0.017 │ 0.03 ± 0.26 │ 52 ± 17 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - "2020-04-04 16:27:06,971 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #6\n", - "2020-04-04 16:27:09,064 - ompy.normalizer_nld - INFO - DE results:\n", - "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╡\n", - "│ 1.3423817552927328 │ 1.3365322130516186 │ 0.5458196352271024 │ -0.05805297817697355 │\n", - "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┘\n", - "2020-04-04 16:27:09,129 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:27:09,137 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┬────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╪════════════════════╡\n", - "│ 1.3423817552927328 │ 1.3365322130516186 │ 0.5458196352271024 │ -0.05805297817697355 │ 50.241008133263655 │\n", - "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┴────────────────────┘\n", - "2020-04-04 16:27:09,139 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - " analysing data from multinest/sim_norm_4_.txt\n", - "2020-04-04 16:27:38,928 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.68 ± 0.22 │ 1.225 ± 0.051 │ 0.538 ± 0.017 │ 0.07 ± 0.25 │ 58 ± 18 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - "2020-04-04 16:27:38,938 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #7\n", - "2020-04-04 16:27:40,883 - ompy.normalizer_nld - INFO - DE results:\n", - "┌───────────────────┬───────────────────┬────────────────────┬──────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞═══════════════════╪═══════════════════╪════════════════════╪══════════════════════╡\n", - "│ 1.514041521660149 │ 1.329021837405266 │ 0.5483836488235186 │ -0.09653453978147153 │\n", - "└───────────────────┴───────────────────┴────────────────────┴──────────────────────┘\n", - "2020-04-04 16:27:40,950 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:27:40,957 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌───────────────────┬───────────────────┬────────────────────┬──────────────────────┬───────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═══════════════════╪═══════════════════╪════════════════════╪══════════════════════╪═══════════════════╡\n", - "│ 1.514041521660149 │ 1.329021837405266 │ 0.5483836488235186 │ -0.09653453978147153 │ 57.51900547217029 │\n", - "└───────────────────┴───────────────────┴────────────────────┴──────────────────────┴───────────────────┘\n", - "2020-04-04 16:27:40,962 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - " analysing data from multinest/sim_norm_5_.txt\n", - "2020-04-04 16:27:59,830 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.72 ± 0.21 │ 1.339 ± 0.051 │ 0.544 ± 0.017 │ -0.02 ± 0.25 │ 47 ± 15 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - "2020-04-04 16:27:59,845 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #8\n", - "2020-04-04 16:28:01,863 - ompy.normalizer_nld - INFO - DE results:\n", - "┌───────────────────┬────────────────────┬────────────────────┬───────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞═══════════════════╪════════════════════╪════════════════════╪═══════════════════════╡\n", - "│ 1.581439934709933 │ 1.2714799801037198 │ 0.5438757438980426 │ -0.028998475826839978 │\n", - "└───────────────────┴────────────────────┴────────────────────┴───────────────────────┘\n", - "2020-04-04 16:28:01,934 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:28:01,942 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌───────────────────┬────────────────────┬────────────────────┬───────────────────────┬───────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═══════════════════╪════════════════════╪════════════════════╪═══════════════════════╪═══════════════════╡\n", - "│ 1.581439934709933 │ 1.2714799801037198 │ 0.5438757438980426 │ -0.028998475826839978 │ 49.38927228768871 │\n", - "└───────────────────┴────────────────────┴────────────────────┴───────────────────────┴───────────────────┘\n", - "2020-04-04 16:28:01,946 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - " analysing data from multinest/sim_norm_7_.txt\n", - "2020-04-04 16:29:06,297 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.58 ± 0.19 │ 1.307 ± 0.048 │ 0.545 ± 0.017 │ -0.04 ± 0.25 │ 63 ± 20 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - "2020-04-04 16:29:06,310 - ompy.ensembleNormalizer - INFO - \n", - "\n", - "---------\n", - "Normalizing #9\n", - "2020-04-04 16:29:08,731 - ompy.normalizer_nld - INFO - DE results:\n", - "┌────────────────────┬────────────────────┬───────────────────┬──────────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", - "╞════════════════════╪════════════════════╪═══════════════════╪══════════════════════╡\n", - "│ 1.0743755457988782 │ 1.3488545650018056 │ 0.543990353565045 │ -0.02957622991865004 │\n", - "└────────────────────┴────────────────────┴───────────────────┴──────────────────────┘\n", - "2020-04-04 16:29:08,801 - ompy.normalizer_gsf - INFO - Normalizing #0\n", - "2020-04-04 16:29:08,809 - ompy.normalizer_simultan - INFO - DE results/initial guess:\n", - "┌────────────────────┬────────────────────┬───────────────────┬──────────────────────┬───────────────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞════════════════════╪════════════════════╪═══════════════════╪══════════════════════╪═══════════════════╡\n", - "│ 1.0743755457988782 │ 1.3488545650018056 │ 0.543990353565045 │ -0.02957622991865004 │ 47.91535961735755 │\n", - "└────────────────────┴────────────────────┴───────────────────┴──────────────────────┴───────────────────┘\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2020-04-04 16:29:08,814 - ompy.normalizer_simultan - INFO - Starting multinest: \n", - " analysing data from multinest/sim_norm_6_.txt\n", - "2020-04-04 16:29:10,259 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.40 ± 0.18 │ 1.316 ± 0.054 │ 0.542 ± 0.018 │ 0.01 ± 0.26 │ 54 ± 18 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - " analysing data from multinest/sim_norm_8_.txt\n", - "2020-04-04 16:29:36,053 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.66 ± 0.20 │ 1.248 ± 0.052 │ 0.540 ± 0.017 │ 0.03 ± 0.26 │ 68 ± 21 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - " analysing data from multinest/sim_norm_9_.txt\n", - "2020-04-04 16:30:03,554 - ompy.normalizer_simultan - INFO - Multinest results:\n", - "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", - "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", - "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", - "│ 1.15 ± 0.14 │ 1.304 ± 0.044 │ 0.533 ± 0.014 │ 0.15 ± 0.20 │ 57 ± 15 │\n", - "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", - "\n", - "2020-04-04 16:30:03,593 - ompy.ensembleNormalizer - INFO - Saving to saved_run/normalizers/EnsembleNormalizer.pkl\n" - ] - } - ], - "source": [ - "ensemblenorm_sim = om.EnsembleNormalizer(extractor=extractor, normalizer_simultan=simnorm,\n", - " regenerate=True)\n", - "\n", - "ensemblenorm_sim.normalize()" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "metadata": { - "scrolled": false - }, - "outputs": [ - { - "data": { - "application/javascript": [ - "/* Put everything inside the global mpl namespace */\n", - "window.mpl = {};\n", - "\n", - "\n", - "mpl.get_websocket_type = function() {\n", - " if (typeof(WebSocket) !== 'undefined') {\n", - " return WebSocket;\n", - " } else if (typeof(MozWebSocket) !== 'undefined') {\n", - " return MozWebSocket;\n", - " } else {\n", - " alert('Your browser does not have WebSocket support. ' +\n", - " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", - " 'Firefox 4 and 5 are also supported but you ' +\n", - " 'have to enable WebSockets in about:config.');\n", - " };\n", - "}\n", - "\n", - "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", - " this.id = figure_id;\n", - "\n", - " this.ws = websocket;\n", - "\n", - " this.supports_binary = (this.ws.binaryType != undefined);\n", - "\n", - " if (!this.supports_binary) {\n", - " var warnings = document.getElementById(\"mpl-warnings\");\n", - " if (warnings) {\n", - " warnings.style.display = 'block';\n", - " warnings.textContent = (\n", - " \"This browser does not support binary websocket messages. \" +\n", - " \"Performance may be slow.\");\n", - " }\n", - " }\n", - "\n", - " this.imageObj = new Image();\n", - "\n", - " this.context = undefined;\n", - " this.message = undefined;\n", - " this.canvas = undefined;\n", - " this.rubberband_canvas = undefined;\n", - " this.rubberband_context = undefined;\n", - " this.format_dropdown = undefined;\n", - "\n", - " this.image_mode = 'full';\n", - "\n", - " this.root = $('
');\n", - " this._root_extra_style(this.root)\n", - " this.root.attr('style', 'display: inline-block');\n", - "\n", - " $(parent_element).append(this.root);\n", - "\n", - " this._init_header(this);\n", - " this._init_canvas(this);\n", - " this._init_toolbar(this);\n", - "\n", - " var fig = this;\n", - "\n", - " this.waiting = false;\n", - "\n", - " this.ws.onopen = function () {\n", - " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", - " fig.send_message(\"send_image_mode\", {});\n", - " if (mpl.ratio != 1) {\n", - " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", - " }\n", - " fig.send_message(\"refresh\", {});\n", - " }\n", - "\n", - " this.imageObj.onload = function() {\n", - " if (fig.image_mode == 'full') {\n", - " // Full images could contain transparency (where diff images\n", - " // almost always do), so we need to clear the canvas so that\n", - " // there is no ghosting.\n", - " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", - " }\n", - " fig.context.drawImage(fig.imageObj, 0, 0);\n", - " };\n", - "\n", - " this.imageObj.onunload = function() {\n", - " fig.ws.close();\n", - " }\n", - "\n", - " this.ws.onmessage = this._make_on_message_function(this);\n", - "\n", - " this.ondownload = ondownload;\n", - "}\n", - "\n", - "mpl.figure.prototype._init_header = function() {\n", - " var titlebar = $(\n", - " '
');\n", - " var titletext = $(\n", - " '
');\n", - " titlebar.append(titletext)\n", - " this.root.append(titlebar);\n", - " this.header = titletext[0];\n", - "}\n", - "\n", - "\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", - "\n", - "}\n", - "\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", - "\n", - "}\n", - "\n", - "mpl.figure.prototype._init_canvas = function() {\n", - " var fig = this;\n", - "\n", - " var canvas_div = $('
');\n", - "\n", - " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", - "\n", - " function canvas_keyboard_event(event) {\n", - " return fig.key_event(event, event['data']);\n", - " }\n", - "\n", - " canvas_div.keydown('key_press', canvas_keyboard_event);\n", - " canvas_div.keyup('key_release', canvas_keyboard_event);\n", - " this.canvas_div = canvas_div\n", - " this._canvas_extra_style(canvas_div)\n", - " this.root.append(canvas_div);\n", - "\n", - " var canvas = $('');\n", - " canvas.addClass('mpl-canvas');\n", - " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", - "\n", - " this.canvas = canvas[0];\n", - " this.context = canvas[0].getContext(\"2d\");\n", - "\n", - " var backingStore = this.context.backingStorePixelRatio ||\n", - "\tthis.context.webkitBackingStorePixelRatio ||\n", - "\tthis.context.mozBackingStorePixelRatio ||\n", - "\tthis.context.msBackingStorePixelRatio ||\n", - "\tthis.context.oBackingStorePixelRatio ||\n", - "\tthis.context.backingStorePixelRatio || 1;\n", - "\n", - " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", - "\n", - " var rubberband = $('');\n", - " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", - "\n", - " var pass_mouse_events = true;\n", - "\n", - " canvas_div.resizable({\n", - " start: function(event, ui) {\n", - " pass_mouse_events = false;\n", - " },\n", - " resize: function(event, ui) {\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " stop: function(event, ui) {\n", - " pass_mouse_events = true;\n", - " fig.request_resize(ui.size.width, ui.size.height);\n", - " },\n", - " });\n", - "\n", - " function mouse_event_fn(event) {\n", - " if (pass_mouse_events)\n", - " return fig.mouse_event(event, event['data']);\n", - " }\n", - "\n", - " rubberband.mousedown('button_press', mouse_event_fn);\n", - " rubberband.mouseup('button_release', mouse_event_fn);\n", - " // Throttle sequential mouse events to 1 every 20ms.\n", - " rubberband.mousemove('motion_notify', mouse_event_fn);\n", - "\n", - " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", - " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", - "\n", - " canvas_div.on(\"wheel\", function (event) {\n", - " event = event.originalEvent;\n", - " event['data'] = 'scroll'\n", - " if (event.deltaY < 0) {\n", - " event.step = 1;\n", - " } else {\n", - " event.step = -1;\n", - " }\n", - " mouse_event_fn(event);\n", - " });\n", - "\n", - " canvas_div.append(canvas);\n", - " canvas_div.append(rubberband);\n", - "\n", - " this.rubberband = rubberband;\n", - " this.rubberband_canvas = rubberband[0];\n", - " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", - " this.rubberband_context.strokeStyle = \"#000000\";\n", - "\n", - " this._resize_canvas = function(width, height) {\n", - " // Keep the size of the canvas, canvas container, and rubber band\n", - " // canvas in synch.\n", - " canvas_div.css('width', width)\n", - " canvas_div.css('height', height)\n", - "\n", - " canvas.attr('width', width * mpl.ratio);\n", - " canvas.attr('height', height * mpl.ratio);\n", - " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", - "\n", - " rubberband.attr('width', width);\n", - " rubberband.attr('height', height);\n", - " }\n", - "\n", - " // Set the figure to an initial 600x600px, this will subsequently be updated\n", - " // upon first draw.\n", - " this._resize_canvas(600, 600);\n", - "\n", - " // Disable right mouse context menu.\n", - " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", - " return false;\n", - " });\n", - "\n", - " function set_focus () {\n", - " canvas.focus();\n", - " canvas_div.focus();\n", - " }\n", - "\n", - " window.setTimeout(set_focus, 100);\n", - "}\n", - "\n", - "mpl.figure.prototype._init_toolbar = function() {\n", - " var fig = this;\n", - "\n", - " var nav_element = $('
');\n", - " nav_element.attr('style', 'width: 100%');\n", - " this.root.append(nav_element);\n", - "\n", - " // Define a callback function for later on.\n", - " function toolbar_event(event) {\n", - " return fig.toolbar_button_onclick(event['data']);\n", - " }\n", - " function toolbar_mouse_event(event) {\n", - " return fig.toolbar_button_onmouseover(event['data']);\n", - " }\n", - "\n", - " for(var toolbar_ind in mpl.toolbar_items) {\n", - " var name = mpl.toolbar_items[toolbar_ind][0];\n", - " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", - " var image = mpl.toolbar_items[toolbar_ind][2];\n", - " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", - "\n", - " if (!name) {\n", - " // put a spacer in here.\n", - " continue;\n", - " }\n", - " var button = $('');\n", - " button.click(method_name, toolbar_event);\n", - " button.mouseover(tooltip, toolbar_mouse_event);\n", - " nav_element.append(button);\n", - " }\n", - "\n", - " // Add the status bar.\n", - " var status_bar = $('');\n", - " nav_element.append(status_bar);\n", - " this.message = status_bar[0];\n", - "\n", - " // Add the close button to the window.\n", - " var buttongrp = $('
');\n", - " var button = $('');\n", - " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", - " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", - " buttongrp.append(button);\n", - " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", - " titlebar.prepend(buttongrp);\n", - "}\n", - "\n", - "mpl.figure.prototype._root_extra_style = function(el){\n", - " var fig = this\n", - " el.on(\"remove\", function(){\n", - "\tfig.close_ws(fig, {});\n", - " });\n", - "}\n", - "\n", - "mpl.figure.prototype._canvas_extra_style = function(el){\n", - " // this is important to make the div 'focusable\n", - " el.attr('tabindex', 0)\n", - " // reach out to IPython and tell the keyboard manager to turn it's self\n", - " // off when our div gets focus\n", - "\n", - " // location in version 3\n", - " if (IPython.notebook.keyboard_manager) {\n", - " IPython.notebook.keyboard_manager.register_events(el);\n", - " }\n", - " else {\n", - " // location in version 2\n", - " IPython.keyboard_manager.register_events(el);\n", - " }\n", - "\n", - "}\n", - "\n", - "mpl.figure.prototype._key_event_extra = function(event, name) {\n", - " var manager = IPython.notebook.keyboard_manager;\n", - " if (!manager)\n", - " manager = IPython.keyboard_manager;\n", - "\n", - " // Check for shift+enter\n", - " if (event.shiftKey && event.which == 13) {\n", - " this.canvas_div.blur();\n", - " // select the cell after this one\n", - " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", - " IPython.notebook.select(index + 1);\n", - " }\n", - "}\n", - "\n", - "mpl.figure.prototype.handle_save = function(fig, msg) {\n", - " fig.ondownload(fig, null);\n", - "}\n", - "\n", - "\n", - "mpl.find_output_cell = function(html_output) {\n", - " // Return the cell and output element which can be found *uniquely* in the notebook.\n", - " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", - " // IPython event is triggered only after the cells have been serialised, which for\n", - " // our purposes (turning an active figure into a static one), is too late.\n", - " var cells = IPython.notebook.get_cells();\n", - " var ncells = cells.length;\n", - " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", - " data = data.data;\n", - " }\n", - " if (data['text/html'] == html_output) {\n", - " return [cell, data, j];\n", - " }\n", - " }\n", - " }\n", - " }\n", - "}\n", - "\n", - "// Register the function which deals with the matplotlib target/channel.\n", - "// The kernel may be null if the page has been refreshed.\n", - "if (IPython.notebook.kernel != null) {\n", - " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", - "}\n" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "outputs": [], + "source": [ + "simnorm.plot();" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. Normalization the whole ensemble\n", + "We have now also developed the tool-set to normalize each member of the extractor ensemble separately. This should provide a statistically more sound and robust normalization. \n", + "\n", + "Why so? As the $\\chi^2$ error function is degenerate, a good minimizer should return sets of (nld, gsf) that need to be normalized with different coefficients $A$, $B$ and $\\alpha$. Thus we should normalize each of these sets independently, and build up an uncertainty band only after the normalization. (Instead of the *traditional* approach of normalizing the mean of the sets)\n", + "\n", + "Again, you decide whether you normalize sequentially, or, as we **recommend**, to normalize simultaneously.\n", + "\n", + "Note that this will this may take several minutes!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Sequential normalization" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "scrolled": true + }, + "outputs": [], + "source": [ + "normlog = om.introspection.get_logger('ensembleNormalizer', 'INFO')\n", + "ensemblenorm_seq = om.EnsembleNormalizer(extractor=extractor, normalizer_nld=nldnorm,\n", + " normalizer_gsf=gsfnorm, regenerate=True)\n", + "ensemblenorm_seq.normalize()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ensemblenorm_seq.plot();" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Simultaneous normalization" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "scrolled": true + }, + "outputs": [], + "source": [ + "ensemblenorm_sim = om.EnsembleNormalizer(extractor=extractor, normalizer_simultan=simnorm,\n", + " regenerate=True)\n", + "\n", + "ensemblenorm_sim.normalize()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "scrolled": false + }, + "outputs": [], + "source": [ + "ensemblenorm_sim.plot();" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Does this particular set of random sample look very strange (by \"accident\" i.e. a bad seed?) \n", + "Try to look at some others, like here. If the problem persists, you should look at earlier stages of the analysis." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "ensemblenorm_sim.plot(n_plot=5, random_state=np.random.default_rng(65546645));" ] @@ -19164,7 +17808,7 @@ }, { "cell_type": "code", - "execution_count": 41, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -19193,7 +17837,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.3" + "version": "3.8.1" }, "varInspector": { "cols": { From bd3abf7eabfa8edc377ab28624bbab04e481762d Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Fri, 14 Aug 2020 15:55:40 +0200 Subject: [PATCH 11/22] Now the notebook is fully ran as well :+1: --- notebooks/getting_started.ipynb | 4044 ++++++++++++++++++++++++++++++- 1 file changed, 3998 insertions(+), 46 deletions(-) diff --git a/notebooks/getting_started.ipynb b/notebooks/getting_started.ipynb index 36f27fd2..fef3dedc 100644 --- a/notebooks/getting_started.ipynb +++ b/notebooks/getting_started.ipynb @@ -1005,7 +1005,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -1999,7 +1999,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -2939,7 +2939,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -3925,7 +3925,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -4898,7 +4898,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -5854,7 +5854,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -6810,7 +6810,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -7846,7 +7846,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -8768,7 +8768,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -9779,7 +9779,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -10755,7 +10755,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -11709,7 +11709,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -12679,7 +12679,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -13638,7 +13638,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -14616,7 +14616,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -15683,7 +15683,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -16658,7 +16658,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -17619,7 +17619,7 @@ { "data": { "text/html": [ - "
" + "" ], "text/plain": [ "" @@ -17657,7 +17657,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 34, "metadata": { "scrolled": false }, @@ -17679,7 +17679,15 @@ "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╪════════════════════╡\n", "│ 1.3041657754481422 │ 1.3047666835840441 │ 0.5397053066859719 │ 0.033943533839594545 │ 53.252395120263344 │\n", "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┴────────────────────┘\n", - "2020-08-14 15:48:40,191 - ompy.normalizer_simultan - INFO - Starting multinest: \n" + "2020-08-14 15:48:40,191 - ompy.normalizer_simultan - INFO - Starting multinest: \n", + " analysing data from multinest/sim_norm_0_.txt\n", + "2020-08-14 15:49:28,285 - ompy.normalizer_simultan - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┬─────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │ B │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╪═════════╡\n", + "│ 1.37 ± 0.16 │ 1.277 ± 0.053 │ 0.535 ± 0.018 │ 0.11 ± 0.26 │ 65 ± 21 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┴─────────┘\n", + "2020-08-14 15:49:28,287 - ompy.normalizer_simultan - INFO - Saving to saved_run/normalizers/NormalizerSimultan.pkl\n" ] } ], @@ -17697,11 +17705,934 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 35, "metadata": { "scrolled": false }, - "outputs": [], + "outputs": [ + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " resizeObserver.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / mpl.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n", + " var x1 = msg['x1'] / mpl.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / mpl.ratio,\n", + " fig.canvas.height / mpl.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * mpl.ratio;\n", + " var y = canvas_pos.y * mpl.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / mpl.ratio;\n", + " fig.root.removeEventListener('remove', this._remove_fig_handler);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / mpl.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "simnorm.plot();" ] @@ -17729,11 +18660,277 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 36, "metadata": { - "scrolled": true + "scrolled": false }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2020-08-14 15:49:28,397 - ompy.ensembleNormalizer - INFO - Start normalization with 7 cpus\n", + "2020-08-14 15:49:28,446 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #0\n", + "2020-08-14 15:49:28,464 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #1\n" + ] + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "cb6c5d51548144e1be0896d9e22ea70c", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "HBox(children=(FloatProgress(value=0.0, max=10.0), HTML(value='')))" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2020-08-14 15:49:28,483 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #2\n", + "2020-08-14 15:49:28,495 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #3\n", + "2020-08-14 15:49:28,509 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #4\n", + "2020-08-14 15:49:28,528 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #0\n", + "2020-08-14 15:49:28,527 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #5\n", + "2020-08-14 15:49:28,547 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #6\n", + "2020-08-14 15:49:28,568 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #1\n", + "2020-08-14 15:49:28,592 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #2\n", + "2020-08-14 15:49:28,603 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #3\n", + "2020-08-14 15:49:28,627 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #4\n", + "2020-08-14 15:49:28,636 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #5\n", + "2020-08-14 15:49:28,642 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #6\n", + "2020-08-14 15:49:30,155 - ompy.normalizer_nld - INFO - DE results:\n", + "┌────────────────────┬───────────────────┬────────────────────┬──────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞════════════════════╪═══════════════════╪════════════════════╪══════════════════════╡\n", + "│ 1.5871245485170797 │ 1.277531999540582 │ 0.5443702115284879 │ -0.03606314684967083 │\n", + "└────────────────────┴───────────────────┴────────────────────┴──────────────────────┘\n", + "2020-08-14 15:49:30,160 - ompy.normalizer_nld - INFO - Starting multinest\n", + "2020-08-14 15:49:30,260 - ompy.normalizer_nld - INFO - DE results:\n", + "┌──────────────────┬────────────────────┬────────────────────┬─────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞══════════════════╪════════════════════╪════════════════════╪═════════════════════╡\n", + "│ 1.30416632533281 │ 1.3047667275502741 │ 0.5397054197859917 │ 0.03394182576715534 │\n", + "└──────────────────┴────────────────────┴────────────────────┴─────────────────────┘\n", + "2020-08-14 15:49:30,269 - ompy.normalizer_nld - INFO - Starting multinest\n", + "2020-08-14 15:49:30,271 - ompy.normalizer_nld - INFO - DE results:\n", + "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╡\n", + "│ 2.3698138602378567 │ 1.1883051972279886 │ 0.5449561863611344 │ -0.04458534577542578 │\n", + "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┘\n", + "2020-08-14 15:49:30,277 - ompy.normalizer_nld - INFO - Starting multinest\n", + "2020-08-14 15:49:30,301 - ompy.normalizer_nld - INFO - DE results:\n", + "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╡\n", + "│ 1.6624292590519252 │ 1.3584196968235676 │ 0.5476167975924897 │ -0.08521883880688466 │\n", + "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┘\n", + "2020-08-14 15:49:30,304 - ompy.normalizer_nld - INFO - Starting multinest\n", + "2020-08-14 15:49:30,357 - ompy.normalizer_nld - INFO - DE results:\n", + "┌───────────────────┬────────────────────┬────────────────────┬───────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═══════════════════╪════════════════════╪════════════════════╪═══════════════════════╡\n", + "│ 1.623438443685708 │ 1.2459904109748934 │ 0.5427809029950444 │ -0.013084223625805903 │\n", + "└───────────────────┴────────────────────┴────────────────────┴───────────────────────┘\n", + "2020-08-14 15:49:30,366 - ompy.normalizer_nld - INFO - Starting multinest\n", + "2020-08-14 15:49:30,471 - ompy.normalizer_nld - INFO - DE results:\n", + "┌────────────────────┬────────────────────┬────────────────────┬───────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞════════════════════╪════════════════════╪════════════════════╪═══════════════════════╡\n", + "│ 1.3793529196161032 │ 1.3005363396680412 │ 0.5440955986032406 │ -0.032796452735360894 │\n", + "└────────────────────┴────────────────────┴────────────────────┴───────────────────────┘\n", + "2020-08-14 15:49:30,474 - ompy.normalizer_nld - INFO - Starting multinest\n", + "2020-08-14 15:49:30,511 - ompy.normalizer_nld - INFO - DE results:\n", + "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╡\n", + "│ 1.3572545331918433 │ 1.3326837674671945 │ 0.5456909277036783 │ -0.05621286185647593 │\n", + "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┘\n", + "2020-08-14 15:49:30,514 - ompy.normalizer_nld - INFO - Starting multinest\n", + " analysing data from multinest/nld_norm_1_.txt\n", + "2020-08-14 15:50:00,836 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 1.64 ± 0.20 │ 1.268 ± 0.054 │ 0.544 ± 0.018 │ -0.03 ± 0.27 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n", + "2020-08-14 15:50:00,908 - ompy.normalizer_gsf - INFO - Normalizing #1\n", + "2020-08-14 15:50:00,935 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #7\n", + "2020-08-14 15:50:01,024 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #7\n", + " analysing data from multinest/nld_norm_3_.txt\n", + " analysing data from multinest/nld_norm_0_.txt\n", + "2020-08-14 15:50:01,311 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 1.43 ± 0.18 │ 1.292 ± 0.054 │ 0.545 ± 0.018 │ -0.04 ± 0.26 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n", + "2020-08-14 15:50:01,374 - ompy.normalizer_gsf - INFO - Normalizing #3\n", + " analysing data from multinest/nld_norm_6_.txt2020-08-14 15:50:01,406 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #8\n", + "\n", + "2020-08-14 15:50:01,502 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #8\n", + "2020-08-14 15:50:01,548 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 1.35 ± 0.17 │ 1.293 ± 0.055 │ 0.540 ± 0.018 │ 0.05 ± 0.26 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n", + "2020-08-14 15:50:01,609 - ompy.normalizer_gsf - INFO - Normalizing #0\n", + "2020-08-14 15:50:01,632 - ompy.ensembleNormalizer - INFO - \n", + "\n", + "---------\n", + "Normalizing #9\n", + "2020-08-14 15:50:01,658 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 1.40 ± 0.17 │ 1.328 ± 0.050 │ 0.547 ± 0.017 │ -0.07 ± 0.25 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n", + " analysing data from multinest/nld_norm_5_.txt\n", + "2020-08-14 15:50:01,731 - ompy.normalizer_nld - INFO - \n", + "\n", + "---------\n", + "Normalizing nld #9\n", + "2020-08-14 15:50:01,732 - ompy.normalizer_gsf - INFO - Normalizing #6\n", + "2020-08-14 15:50:01,929 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 1.71 ± 0.21 │ 1.349 ± 0.051 │ 0.547 ± 0.017 │ -0.08 ± 0.25 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n", + "2020-08-14 15:50:01,988 - ompy.normalizer_gsf - INFO - Normalizing #5\n", + " analysing data from multinest/nld_norm_2_.txt\n", + "2020-08-14 15:50:02,376 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 2.44 ± 0.30 │ 1.181 ± 0.051 │ 0.545 ± 0.018 │ -0.04 ± 0.26 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2020-08-14 15:50:02,421 - ompy.normalizer_gsf - INFO - Normalizing #2\n", + "2020-08-14 15:50:02,911 - ompy.normalizer_nld - INFO - DE results:\n", + "┌────────────────────┬────────────────────┬────────────────────┬──────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞════════════════════╪════════════════════╪════════════════════╪══════════════════════╡\n", + "│ 1.5254673827250624 │ 1.3266829916886003 │ 0.5485375330527495 │ -0.09893683083330262 │\n", + "└────────────────────┴────────────────────┴────────────────────┴──────────────────────┘\n", + "2020-08-14 15:50:02,914 - ompy.normalizer_nld - INFO - Starting multinest\n", + "2020-08-14 15:50:03,183 - ompy.normalizer_nld - INFO - DE results:\n", + "┌───────────────────┬────────────────────┬────────────────────┬───────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═══════════════════╪════════════════════╪════════════════════╪═══════════════════════╡\n", + "│ 1.602610276198652 │ 1.2666476180459745 │ 0.5438230544628038 │ -0.028265496901487157 │\n", + "└───────────────────┴────────────────────┴────────────────────┴───────────────────────┘\n", + "2020-08-14 15:50:03,186 - ompy.normalizer_nld - INFO - Starting multinest\n", + "2020-08-14 15:50:03,523 - ompy.normalizer_nld - INFO - DE results:\n", + "┌────────────────────┬────────────────────┬────────────────────┬───────────────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞════════════════════╪════════════════════╪════════════════════╪═══════════════════════╡\n", + "│ 1.0907962225250785 │ 1.3432444026759196 │ 0.5438427950877733 │ -0.027475318559451005 │\n", + "└────────────────────┴────────────────────┴────────────────────┴───────────────────────┘\n", + "2020-08-14 15:50:03,526 - ompy.normalizer_nld - INFO - Starting multinest\n", + " analysing data from multinest/nld_norm_4_.txt\n", + "2020-08-14 15:50:04,077 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 1.63 ± 0.18 │ 1.264 ± 0.040 │ 0.553 ± 0.012 │ -0.14 ± 0.17 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n", + "2020-08-14 15:50:04,119 - ompy.normalizer_gsf - INFO - Normalizing #4\n", + " analysing data from multinest/nld_norm_8_.txt\n", + "2020-08-14 15:50:17,945 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 1.65 ± 0.20 │ 1.262 ± 0.050 │ 0.546 ± 0.017 │ -0.05 ± 0.24 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n", + "2020-08-14 15:50:17,979 - ompy.normalizer_gsf - INFO - Normalizing #8\n", + " analysing data from multinest/nld_norm_7_.txt\n", + "2020-08-14 15:50:18,119 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 1.57 ± 0.21 │ 1.319 ± 0.052 │ 0.549 ± 0.017 │ -0.10 ± 0.25 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n", + "2020-08-14 15:50:18,148 - ompy.normalizer_gsf - INFO - Normalizing #7\n", + " analysing data from multinest/nld_norm_9_.txt\n", + "2020-08-14 15:50:18,390 - ompy.normalizer_nld - INFO - Multinest results:\n", + "┌─────────────┬───────────────┬───────────────┬──────────────┐\n", + "│ A │ α [MeV⁻¹] │ T [MeV] │ Eshift [MeV] │\n", + "╞═════════════╪═══════════════╪═══════════════╪══════════════╡\n", + "│ 1.13 ± 0.14 │ 1.336 ± 0.052 │ 0.544 ± 0.017 │ -0.02 ± 0.25 │\n", + "└─────────────┴───────────────┴───────────────┴──────────────┘\n", + "2020-08-14 15:50:18,425 - ompy.normalizer_gsf - INFO - Normalizing #9\n", + "\n", + "2020-08-14 15:50:18,451 - ompy.ensembleNormalizer - INFO - Saving to saved_run/normalizers/EnsembleNormalizer.pkl\n" + ] + } + ], "source": [ "normlog = om.introspection.get_logger('ensembleNormalizer', 'INFO')\n", "ensemblenorm_seq = om.EnsembleNormalizer(extractor=extractor, normalizer_nld=nldnorm,\n", @@ -17743,9 +18940,932 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 37, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " resizeObserver.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / mpl.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n", + " var x1 = msg['x1'] / mpl.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / mpl.ratio,\n", + " fig.canvas.height / mpl.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * mpl.ratio;\n", + " var y = canvas_pos.y * mpl.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / mpl.ratio;\n", + " fig.root.removeEventListener('remove', this._remove_fig_handler);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / mpl.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "ensemblenorm_seq.plot();" ] @@ -17759,25 +19879,934 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "scrolled": true - }, - "outputs": [], - "source": [ - "ensemblenorm_sim = om.EnsembleNormalizer(extractor=extractor, normalizer_simultan=simnorm,\n", - " regenerate=True)\n", - "\n", - "ensemblenorm_sim.normalize()" - ] - }, - { - "cell_type": "code", - "execution_count": null, + "execution_count": 39, "metadata": { "scrolled": false }, - "outputs": [], + "outputs": [ + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " resizeObserver.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / mpl.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n", + " var x1 = msg['x1'] / mpl.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / mpl.ratio,\n", + " fig.canvas.height / mpl.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * mpl.ratio;\n", + " var y = canvas_pos.y * mpl.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / mpl.ratio;\n", + " fig.root.removeEventListener('remove', this._remove_fig_handler);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / mpl.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "ensemblenorm_sim.plot();" ] @@ -17792,9 +20821,932 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 40, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "application/javascript": [ + "/* Put everything inside the global mpl namespace */\n", + "/* global mpl */\n", + "window.mpl = {};\n", + "\n", + "mpl.get_websocket_type = function () {\n", + " if (typeof WebSocket !== 'undefined') {\n", + " return WebSocket;\n", + " } else if (typeof MozWebSocket !== 'undefined') {\n", + " return MozWebSocket;\n", + " } else {\n", + " alert(\n", + " 'Your browser does not have WebSocket support. ' +\n", + " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", + " 'Firefox 4 and 5 are also supported but you ' +\n", + " 'have to enable WebSockets in about:config.'\n", + " );\n", + " }\n", + "};\n", + "\n", + "mpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n", + " this.id = figure_id;\n", + "\n", + " this.ws = websocket;\n", + "\n", + " this.supports_binary = this.ws.binaryType !== undefined;\n", + "\n", + " if (!this.supports_binary) {\n", + " var warnings = document.getElementById('mpl-warnings');\n", + " if (warnings) {\n", + " warnings.style.display = 'block';\n", + " warnings.textContent =\n", + " 'This browser does not support binary websocket messages. ' +\n", + " 'Performance may be slow.';\n", + " }\n", + " }\n", + "\n", + " this.imageObj = new Image();\n", + "\n", + " this.context = undefined;\n", + " this.message = undefined;\n", + " this.canvas = undefined;\n", + " this.rubberband_canvas = undefined;\n", + " this.rubberband_context = undefined;\n", + " this.format_dropdown = undefined;\n", + "\n", + " this.image_mode = 'full';\n", + "\n", + " this.root = document.createElement('div');\n", + " this.root.setAttribute('style', 'display: inline-block');\n", + " this._root_extra_style(this.root);\n", + "\n", + " parent_element.appendChild(this.root);\n", + "\n", + " this._init_header(this);\n", + " this._init_canvas(this);\n", + " this._init_toolbar(this);\n", + "\n", + " var fig = this;\n", + "\n", + " this.waiting = false;\n", + "\n", + " this.ws.onopen = function () {\n", + " fig.send_message('supports_binary', { value: fig.supports_binary });\n", + " fig.send_message('send_image_mode', {});\n", + " if (mpl.ratio !== 1) {\n", + " fig.send_message('set_dpi_ratio', { dpi_ratio: mpl.ratio });\n", + " }\n", + " fig.send_message('refresh', {});\n", + " };\n", + "\n", + " this.imageObj.onload = function () {\n", + " if (fig.image_mode === 'full') {\n", + " // Full images could contain transparency (where diff images\n", + " // almost always do), so we need to clear the canvas so that\n", + " // there is no ghosting.\n", + " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", + " }\n", + " fig.context.drawImage(fig.imageObj, 0, 0);\n", + " };\n", + "\n", + " this.imageObj.onunload = function () {\n", + " fig.ws.close();\n", + " };\n", + "\n", + " this.ws.onmessage = this._make_on_message_function(this);\n", + "\n", + " this.ondownload = ondownload;\n", + "};\n", + "\n", + "mpl.figure.prototype._init_header = function () {\n", + " var titlebar = document.createElement('div');\n", + " titlebar.classList =\n", + " 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n", + " var titletext = document.createElement('div');\n", + " titletext.classList = 'ui-dialog-title';\n", + " titletext.setAttribute(\n", + " 'style',\n", + " 'width: 100%; text-align: center; padding: 3px;'\n", + " );\n", + " titlebar.appendChild(titletext);\n", + " this.root.appendChild(titlebar);\n", + " this.header = titletext;\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n", + "\n", + "mpl.figure.prototype._init_canvas = function () {\n", + " var fig = this;\n", + "\n", + " var canvas_div = (this.canvas_div = document.createElement('div'));\n", + " canvas_div.setAttribute(\n", + " 'style',\n", + " 'border: 1px solid #ddd;' +\n", + " 'box-sizing: content-box;' +\n", + " 'clear: both;' +\n", + " 'min-height: 1px;' +\n", + " 'min-width: 1px;' +\n", + " 'outline: 0;' +\n", + " 'overflow: hidden;' +\n", + " 'position: relative;' +\n", + " 'resize: both;'\n", + " );\n", + "\n", + " function on_keyboard_event_closure(name) {\n", + " return function (event) {\n", + " return fig.key_event(event, name);\n", + " };\n", + " }\n", + "\n", + " canvas_div.addEventListener(\n", + " 'keydown',\n", + " on_keyboard_event_closure('key_press')\n", + " );\n", + " canvas_div.addEventListener(\n", + " 'keyup',\n", + " on_keyboard_event_closure('key_release')\n", + " );\n", + "\n", + " this._canvas_extra_style(canvas_div);\n", + " this.root.appendChild(canvas_div);\n", + "\n", + " var canvas = (this.canvas = document.createElement('canvas'));\n", + " canvas.classList.add('mpl-canvas');\n", + " canvas.setAttribute('style', 'box-sizing: content-box;');\n", + "\n", + " this.context = canvas.getContext('2d');\n", + "\n", + " var backingStore =\n", + " this.context.backingStorePixelRatio ||\n", + " this.context.webkitBackingStorePixelRatio ||\n", + " this.context.mozBackingStorePixelRatio ||\n", + " this.context.msBackingStorePixelRatio ||\n", + " this.context.oBackingStorePixelRatio ||\n", + " this.context.backingStorePixelRatio ||\n", + " 1;\n", + "\n", + " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", + "\n", + " var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n", + " 'canvas'\n", + " ));\n", + " rubberband_canvas.setAttribute(\n", + " 'style',\n", + " 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n", + " );\n", + "\n", + " var resizeObserver = new ResizeObserver(function (entries) {\n", + " var nentries = entries.length;\n", + " for (var i = 0; i < nentries; i++) {\n", + " var entry = entries[i];\n", + " var width, height;\n", + " if (entry.contentBoxSize) {\n", + " width = entry.contentBoxSize.inlineSize;\n", + " height = entry.contentBoxSize.blockSize;\n", + " } else {\n", + " width = entry.contentRect.width;\n", + " height = entry.contentRect.height;\n", + " }\n", + "\n", + " // Keep the size of the canvas and rubber band canvas in sync with\n", + " // the canvas container.\n", + " canvas.setAttribute('width', width * mpl.ratio);\n", + " canvas.setAttribute('height', height * mpl.ratio);\n", + " canvas.setAttribute(\n", + " 'style',\n", + " 'width: ' + width + 'px; height: ' + height + 'px;'\n", + " );\n", + "\n", + " rubberband_canvas.setAttribute('width', width);\n", + " rubberband_canvas.setAttribute('height', height);\n", + "\n", + " // And update the size in Python. We ignore the initial 0/0 size\n", + " // that occurs as the element is placed into the DOM, which should\n", + " // otherwise not happen due to the minimum size styling.\n", + " if (width != 0 && height != 0) {\n", + " fig.request_resize(width, height);\n", + " }\n", + " }\n", + " });\n", + " resizeObserver.observe(canvas_div);\n", + "\n", + " function on_mouse_event_closure(name) {\n", + " return function (event) {\n", + " return fig.mouse_event(event, name);\n", + " };\n", + " }\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mousedown',\n", + " on_mouse_event_closure('button_press')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseup',\n", + " on_mouse_event_closure('button_release')\n", + " );\n", + " // Throttle sequential mouse events to 1 every 20ms.\n", + " rubberband_canvas.addEventListener(\n", + " 'mousemove',\n", + " on_mouse_event_closure('motion_notify')\n", + " );\n", + "\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseenter',\n", + " on_mouse_event_closure('figure_enter')\n", + " );\n", + " rubberband_canvas.addEventListener(\n", + " 'mouseleave',\n", + " on_mouse_event_closure('figure_leave')\n", + " );\n", + "\n", + " canvas_div.addEventListener('wheel', function (event) {\n", + " if (event.deltaY < 0) {\n", + " event.step = 1;\n", + " } else {\n", + " event.step = -1;\n", + " }\n", + " on_mouse_event_closure('scroll')(event);\n", + " });\n", + "\n", + " canvas_div.appendChild(canvas);\n", + " canvas_div.appendChild(rubberband_canvas);\n", + "\n", + " this.rubberband_context = rubberband_canvas.getContext('2d');\n", + " this.rubberband_context.strokeStyle = '#000000';\n", + "\n", + " this._resize_canvas = function (width, height, forward) {\n", + " if (forward) {\n", + " canvas_div.style.width = width + 'px';\n", + " canvas_div.style.height = height + 'px';\n", + " }\n", + " };\n", + "\n", + " // Disable right mouse context menu.\n", + " this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n", + " return false;\n", + " });\n", + "\n", + " function set_focus() {\n", + " canvas.focus();\n", + " canvas_div.focus();\n", + " }\n", + "\n", + " window.setTimeout(set_focus, 100);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'mpl-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'mpl-button-group';\n", + " continue;\n", + " }\n", + "\n", + " var button = (fig.buttons[name] = document.createElement('button'));\n", + " button.classList = 'mpl-widget';\n", + " button.setAttribute('role', 'button');\n", + " button.setAttribute('aria-disabled', 'false');\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + "\n", + " var icon_img = document.createElement('img');\n", + " icon_img.src = '_images/' + image + '.png';\n", + " icon_img.srcset = '_images/' + image + '_large.png 2x';\n", + " icon_img.alt = tooltip;\n", + " button.appendChild(icon_img);\n", + "\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " var fmt_picker = document.createElement('select');\n", + " fmt_picker.classList = 'mpl-widget';\n", + " toolbar.appendChild(fmt_picker);\n", + " this.format_dropdown = fmt_picker;\n", + "\n", + " for (var ind in mpl.extensions) {\n", + " var fmt = mpl.extensions[ind];\n", + " var option = document.createElement('option');\n", + " option.selected = fmt === mpl.default_extension;\n", + " option.innerHTML = fmt;\n", + " fmt_picker.appendChild(option);\n", + " }\n", + "\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "};\n", + "\n", + "mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n", + " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n", + " // which will in turn request a refresh of the image.\n", + " this.send_message('resize', { width: x_pixels, height: y_pixels });\n", + "};\n", + "\n", + "mpl.figure.prototype.send_message = function (type, properties) {\n", + " properties['type'] = type;\n", + " properties['figure_id'] = this.id;\n", + " this.ws.send(JSON.stringify(properties));\n", + "};\n", + "\n", + "mpl.figure.prototype.send_draw_message = function () {\n", + " if (!this.waiting) {\n", + " this.waiting = true;\n", + " this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " var format_dropdown = fig.format_dropdown;\n", + " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n", + " fig.ondownload(fig, format);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_resize = function (fig, msg) {\n", + " var size = msg['size'];\n", + " if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n", + " fig._resize_canvas(size[0], size[1], msg['forward']);\n", + " fig.send_message('refresh', {});\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_rubberband = function (fig, msg) {\n", + " var x0 = msg['x0'] / mpl.ratio;\n", + " var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n", + " var x1 = msg['x1'] / mpl.ratio;\n", + " var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n", + " x0 = Math.floor(x0) + 0.5;\n", + " y0 = Math.floor(y0) + 0.5;\n", + " x1 = Math.floor(x1) + 0.5;\n", + " y1 = Math.floor(y1) + 0.5;\n", + " var min_x = Math.min(x0, x1);\n", + " var min_y = Math.min(y0, y1);\n", + " var width = Math.abs(x1 - x0);\n", + " var height = Math.abs(y1 - y0);\n", + "\n", + " fig.rubberband_context.clearRect(\n", + " 0,\n", + " 0,\n", + " fig.canvas.width / mpl.ratio,\n", + " fig.canvas.height / mpl.ratio\n", + " );\n", + "\n", + " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_figure_label = function (fig, msg) {\n", + " // Updates the figure title.\n", + " fig.header.textContent = msg['label'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_cursor = function (fig, msg) {\n", + " var cursor = msg['cursor'];\n", + " switch (cursor) {\n", + " case 0:\n", + " cursor = 'pointer';\n", + " break;\n", + " case 1:\n", + " cursor = 'default';\n", + " break;\n", + " case 2:\n", + " cursor = 'crosshair';\n", + " break;\n", + " case 3:\n", + " cursor = 'move';\n", + " break;\n", + " }\n", + " fig.rubberband_canvas.style.cursor = cursor;\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_message = function (fig, msg) {\n", + " fig.message.textContent = msg['message'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_draw = function (fig, _msg) {\n", + " // Request the server to send over a new figure.\n", + " fig.send_draw_message();\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_image_mode = function (fig, msg) {\n", + " fig.image_mode = msg['mode'];\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n", + " for (var key in msg) {\n", + " if (!(key in fig.buttons)) {\n", + " continue;\n", + " }\n", + " fig.buttons[key].disabled = !msg[key];\n", + " fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n", + " if (msg['mode'] === 'PAN') {\n", + " fig.buttons['Pan'].classList.add('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " } else if (msg['mode'] === 'ZOOM') {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.add('active');\n", + " } else {\n", + " fig.buttons['Pan'].classList.remove('active');\n", + " fig.buttons['Zoom'].classList.remove('active');\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Called whenever the canvas gets updated.\n", + " this.send_message('ack', {});\n", + "};\n", + "\n", + "// A function to construct a web socket function for onmessage handling.\n", + "// Called in the figure constructor.\n", + "mpl.figure.prototype._make_on_message_function = function (fig) {\n", + " return function socket_on_message(evt) {\n", + " if (evt.data instanceof Blob) {\n", + " /* FIXME: We get \"Resource interpreted as Image but\n", + " * transferred with MIME type text/plain:\" errors on\n", + " * Chrome. But how to set the MIME type? It doesn't seem\n", + " * to be part of the websocket stream */\n", + " evt.data.type = 'image/png';\n", + "\n", + " /* Free the memory for the previous frames */\n", + " if (fig.imageObj.src) {\n", + " (window.URL || window.webkitURL).revokeObjectURL(\n", + " fig.imageObj.src\n", + " );\n", + " }\n", + "\n", + " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n", + " evt.data\n", + " );\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " } else if (\n", + " typeof evt.data === 'string' &&\n", + " evt.data.slice(0, 21) === 'data:image/png;base64'\n", + " ) {\n", + " fig.imageObj.src = evt.data;\n", + " fig.updated_canvas_event();\n", + " fig.waiting = false;\n", + " return;\n", + " }\n", + "\n", + " var msg = JSON.parse(evt.data);\n", + " var msg_type = msg['type'];\n", + "\n", + " // Call the \"handle_{type}\" callback, which takes\n", + " // the figure and JSON message as its only arguments.\n", + " try {\n", + " var callback = fig['handle_' + msg_type];\n", + " } catch (e) {\n", + " console.log(\n", + " \"No handler for the '\" + msg_type + \"' message type: \",\n", + " msg\n", + " );\n", + " return;\n", + " }\n", + "\n", + " if (callback) {\n", + " try {\n", + " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n", + " callback(fig, msg);\n", + " } catch (e) {\n", + " console.log(\n", + " \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n", + " e,\n", + " e.stack,\n", + " msg\n", + " );\n", + " }\n", + " }\n", + " };\n", + "};\n", + "\n", + "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n", + "mpl.findpos = function (e) {\n", + " //this section is from http://www.quirksmode.org/js/events_properties.html\n", + " var targ;\n", + " if (!e) {\n", + " e = window.event;\n", + " }\n", + " if (e.target) {\n", + " targ = e.target;\n", + " } else if (e.srcElement) {\n", + " targ = e.srcElement;\n", + " }\n", + " if (targ.nodeType === 3) {\n", + " // defeat Safari bug\n", + " targ = targ.parentNode;\n", + " }\n", + "\n", + " // pageX,Y are the mouse positions relative to the document\n", + " var boundingRect = targ.getBoundingClientRect();\n", + " var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n", + " var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n", + "\n", + " return { x: x, y: y };\n", + "};\n", + "\n", + "/*\n", + " * return a copy of an object with only non-object keys\n", + " * we need this to avoid circular references\n", + " * http://stackoverflow.com/a/24161582/3208463\n", + " */\n", + "function simpleKeys(original) {\n", + " return Object.keys(original).reduce(function (obj, key) {\n", + " if (typeof original[key] !== 'object') {\n", + " obj[key] = original[key];\n", + " }\n", + " return obj;\n", + " }, {});\n", + "}\n", + "\n", + "mpl.figure.prototype.mouse_event = function (event, name) {\n", + " var canvas_pos = mpl.findpos(event);\n", + "\n", + " if (name === 'button_press') {\n", + " this.canvas.focus();\n", + " this.canvas_div.focus();\n", + " }\n", + "\n", + " var x = canvas_pos.x * mpl.ratio;\n", + " var y = canvas_pos.y * mpl.ratio;\n", + "\n", + " this.send_message(name, {\n", + " x: x,\n", + " y: y,\n", + " button: event.button,\n", + " step: event.step,\n", + " guiEvent: simpleKeys(event),\n", + " });\n", + "\n", + " /* This prevents the web browser from automatically changing to\n", + " * the text insertion cursor when the button is pressed. We want\n", + " * to control all of the cursor setting manually through the\n", + " * 'cursor' event from matplotlib */\n", + " event.preventDefault();\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (_event, _name) {\n", + " // Handle any extra behaviour associated with a key event\n", + "};\n", + "\n", + "mpl.figure.prototype.key_event = function (event, name) {\n", + " // Prevent repeat events\n", + " if (name === 'key_press') {\n", + " if (event.which === this._key) {\n", + " return;\n", + " } else {\n", + " this._key = event.which;\n", + " }\n", + " }\n", + " if (name === 'key_release') {\n", + " this._key = null;\n", + " }\n", + "\n", + " var value = '';\n", + " if (event.ctrlKey && event.which !== 17) {\n", + " value += 'ctrl+';\n", + " }\n", + " if (event.altKey && event.which !== 18) {\n", + " value += 'alt+';\n", + " }\n", + " if (event.shiftKey && event.which !== 16) {\n", + " value += 'shift+';\n", + " }\n", + "\n", + " value += 'k';\n", + " value += event.which.toString();\n", + "\n", + " this._key_event_extra(event, name);\n", + "\n", + " this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n", + " return false;\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onclick = function (name) {\n", + " if (name === 'download') {\n", + " this.handle_save(this, null);\n", + " } else {\n", + " this.send_message('toolbar_button', { name: name });\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n", + " this.message.textContent = tooltip;\n", + "};\n", + "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n", + "\n", + "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n", + "\n", + "mpl.default_extension = \"png\";/* global mpl */\n", + "\n", + "var comm_websocket_adapter = function (comm) {\n", + " // Create a \"websocket\"-like object which calls the given IPython comm\n", + " // object with the appropriate methods. Currently this is a non binary\n", + " // socket, so there is still some room for performance tuning.\n", + " var ws = {};\n", + "\n", + " ws.close = function () {\n", + " comm.close();\n", + " };\n", + " ws.send = function (m) {\n", + " //console.log('sending', m);\n", + " comm.send(m);\n", + " };\n", + " // Register the callback with on_msg.\n", + " comm.on_msg(function (msg) {\n", + " //console.log('receiving', msg['content']['data'], msg);\n", + " // Pass the mpl event to the overridden (by mpl) onmessage function.\n", + " ws.onmessage(msg['content']['data']);\n", + " });\n", + " return ws;\n", + "};\n", + "\n", + "mpl.mpl_figure_comm = function (comm, msg) {\n", + " // This is the function which gets called when the mpl process\n", + " // starts-up an IPython Comm through the \"matplotlib\" channel.\n", + "\n", + " var id = msg.content.data.id;\n", + " // Get hold of the div created by the display call when the Comm\n", + " // socket was opened in Python.\n", + " var element = document.getElementById(id);\n", + " var ws_proxy = comm_websocket_adapter(comm);\n", + "\n", + " function ondownload(figure, _format) {\n", + " window.open(figure.canvas.toDataURL());\n", + " }\n", + "\n", + " var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n", + "\n", + " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n", + " // web socket which is closed, not our websocket->open comm proxy.\n", + " ws_proxy.onopen();\n", + "\n", + " fig.parent_element = element;\n", + " fig.cell_info = mpl.find_output_cell(\"
\");\n", + " if (!fig.cell_info) {\n", + " console.error('Failed to find cell for figure', id, fig);\n", + " return;\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_close = function (fig, msg) {\n", + " var width = fig.canvas.width / mpl.ratio;\n", + " fig.root.removeEventListener('remove', this._remove_fig_handler);\n", + "\n", + " // Update the output cell to use the data from the current canvas.\n", + " fig.push_to_output();\n", + " var dataURL = fig.canvas.toDataURL();\n", + " // Re-enable the keyboard manager in IPython - without this line, in FF,\n", + " // the notebook keyboard shortcuts fail.\n", + " IPython.keyboard_manager.enable();\n", + " fig.parent_element.innerHTML =\n", + " '';\n", + " fig.close_ws(fig, msg);\n", + "};\n", + "\n", + "mpl.figure.prototype.close_ws = function (fig, msg) {\n", + " fig.send_message('closing', msg);\n", + " // fig.ws.close()\n", + "};\n", + "\n", + "mpl.figure.prototype.push_to_output = function (_remove_interactive) {\n", + " // Turn the data on the canvas into data in the output cell.\n", + " var width = this.canvas.width / mpl.ratio;\n", + " var dataURL = this.canvas.toDataURL();\n", + " this.cell_info[1]['text/html'] =\n", + " '';\n", + "};\n", + "\n", + "mpl.figure.prototype.updated_canvas_event = function () {\n", + " // Tell IPython that the notebook contents must change.\n", + " IPython.notebook.set_dirty(true);\n", + " this.send_message('ack', {});\n", + " var fig = this;\n", + " // Wait a second, then push the new image to the DOM so\n", + " // that it is saved nicely (might be nice to debounce this).\n", + " setTimeout(function () {\n", + " fig.push_to_output();\n", + " }, 1000);\n", + "};\n", + "\n", + "mpl.figure.prototype._init_toolbar = function () {\n", + " var fig = this;\n", + "\n", + " var toolbar = document.createElement('div');\n", + " toolbar.classList = 'btn-toolbar';\n", + " this.root.appendChild(toolbar);\n", + "\n", + " function on_click_closure(name) {\n", + " return function (_event) {\n", + " return fig.toolbar_button_onclick(name);\n", + " };\n", + " }\n", + "\n", + " function on_mouseover_closure(tooltip) {\n", + " return function (event) {\n", + " if (!event.currentTarget.disabled) {\n", + " return fig.toolbar_button_onmouseover(tooltip);\n", + " }\n", + " };\n", + " }\n", + "\n", + " fig.buttons = {};\n", + " var buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " var button;\n", + " for (var toolbar_ind in mpl.toolbar_items) {\n", + " var name = mpl.toolbar_items[toolbar_ind][0];\n", + " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", + " var image = mpl.toolbar_items[toolbar_ind][2];\n", + " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", + "\n", + " if (!name) {\n", + " /* Instead of a spacer, we start a new button group. */\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + " buttonGroup = document.createElement('div');\n", + " buttonGroup.classList = 'btn-group';\n", + " continue;\n", + " }\n", + "\n", + " button = fig.buttons[name] = document.createElement('button');\n", + " button.classList = 'btn btn-default';\n", + " button.href = '#';\n", + " button.title = name;\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', on_click_closure(method_name));\n", + " button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n", + " buttonGroup.appendChild(button);\n", + " }\n", + "\n", + " if (buttonGroup.hasChildNodes()) {\n", + " toolbar.appendChild(buttonGroup);\n", + " }\n", + "\n", + " // Add the status bar.\n", + " var status_bar = document.createElement('span');\n", + " status_bar.classList = 'mpl-message pull-right';\n", + " toolbar.appendChild(status_bar);\n", + " this.message = status_bar;\n", + "\n", + " // Add the close button to the window.\n", + " var buttongrp = document.createElement('div');\n", + " buttongrp.classList = 'btn-group inline pull-right';\n", + " button = document.createElement('button');\n", + " button.classList = 'btn btn-mini btn-primary';\n", + " button.href = '#';\n", + " button.title = 'Stop Interaction';\n", + " button.innerHTML = '';\n", + " button.addEventListener('click', function (_evt) {\n", + " fig.handle_close(fig, {});\n", + " });\n", + " button.addEventListener(\n", + " 'mouseover',\n", + " on_mouseover_closure('Stop Interaction')\n", + " );\n", + " buttongrp.appendChild(button);\n", + " var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n", + " titlebar.insertBefore(buttongrp, titlebar.firstChild);\n", + "};\n", + "\n", + "mpl.figure.prototype._remove_fig_handler = function () {\n", + " this.close_ws(this, {});\n", + "};\n", + "\n", + "mpl.figure.prototype._root_extra_style = function (el) {\n", + " el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n", + " el.addEventListener('remove', this._remove_fig_handler);\n", + "};\n", + "\n", + "mpl.figure.prototype._canvas_extra_style = function (el) {\n", + " // this is important to make the div 'focusable\n", + " el.setAttribute('tabindex', 0);\n", + " // reach out to IPython and tell the keyboard manager to turn it's self\n", + " // off when our div gets focus\n", + "\n", + " // location in version 3\n", + " if (IPython.notebook.keyboard_manager) {\n", + " IPython.notebook.keyboard_manager.register_events(el);\n", + " } else {\n", + " // location in version 2\n", + " IPython.keyboard_manager.register_events(el);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype._key_event_extra = function (event, _name) {\n", + " var manager = IPython.notebook.keyboard_manager;\n", + " if (!manager) {\n", + " manager = IPython.keyboard_manager;\n", + " }\n", + "\n", + " // Check for shift+enter\n", + " if (event.shiftKey && event.which === 13) {\n", + " this.canvas_div.blur();\n", + " // select the cell after this one\n", + " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", + " IPython.notebook.select(index + 1);\n", + " }\n", + "};\n", + "\n", + "mpl.figure.prototype.handle_save = function (fig, _msg) {\n", + " fig.ondownload(fig, null);\n", + "};\n", + "\n", + "mpl.find_output_cell = function (html_output) {\n", + " // Return the cell and output element which can be found *uniquely* in the notebook.\n", + " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", + " // IPython event is triggered only after the cells have been serialised, which for\n", + " // our purposes (turning an active figure into a static one), is too late.\n", + " var cells = IPython.notebook.get_cells();\n", + " var ncells = cells.length;\n", + " for (var i = 0; i < ncells; i++) {\n", + " var cell = cells[i];\n", + " if (cell.cell_type === 'code') {\n", + " for (var j = 0; j < cell.output_area.outputs.length; j++) {\n", + " var data = cell.output_area.outputs[j];\n", + " if (data.data) {\n", + " // IPython >= 3 moved mimebundle to data attribute of output\n", + " data = data.data;\n", + " }\n", + " if (data['text/html'] === html_output) {\n", + " return [cell, data, j];\n", + " }\n", + " }\n", + " }\n", + " }\n", + "};\n", + "\n", + "// Register the function which deals with the matplotlib target/channel.\n", + "// The kernel may be null if the page has been refreshed.\n", + "if (IPython.notebook.kernel !== null) {\n", + " IPython.notebook.kernel.comm_manager.register_target(\n", + " 'matplotlib',\n", + " mpl.mpl_figure_comm\n", + " );\n", + "}\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "ensemblenorm_sim.plot(n_plot=5, random_state=np.random.default_rng(65546645));" ] @@ -17808,7 +21760,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 41, "metadata": {}, "outputs": [], "source": [ From 68b0b463bf4881d6d09dff79af2bbcbccfa6a33e Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Fri, 14 Aug 2020 16:08:31 +0200 Subject: [PATCH 12/22] Updated docstring and slight modification to the code --- ompy/extractor.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/ompy/extractor.py b/ompy/extractor.py index 587310b4..45dd180e 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -49,7 +49,9 @@ class Extractor: trapezoid (Action[Matrix]): The Action cutting the matrices of the Ensemble into the desired shape where from the nld and gsf will be extracted from. - path (path): The path to save and/or load nld and gsf to/from. + path (path): The path to save and/or load nld and gsf to/from. If given + the class will load nld and gsf if such files are found. + Defaults to 'saved_run/extractor' if nothing is given. extend_diagonal_by_resolution (bool, optional): If `True`, the fit will be extended beyond Ex=Eg by the (FWHM) of the resolution. Remember to set the resolution according to your @@ -83,10 +85,13 @@ def __init__(self, if path is not None: self.path = Path(path) - self.load(self.path) + try: + self.load(self.path) + except ValueError: # Error given if no folder exist + self.path.mkdir(exist_ok=True, parents=True) else: - self.path = 'saved_run/extractor' - self.path = Path(self.path) + path = 'saved_run/extractor' + self.path = Path(path) self.path.mkdir(exist_ok=True, parents=True) self.x0 = None @@ -390,12 +395,16 @@ def load(self, path: Union[str, Path]): path: Path to folder with ensemble Raises: + ValueError if path isn't a folder or doesn't exist. RuntimeError if there are no NLD & GSF files in the provided path. AssertionError if the number NLD and GSF are unequal. """ path = Path(path) + if not path.isdir(): + raise ValueError(f"Path '{path}' does not exist.") + # Count number of files with name gsf_*.npy and nld_*.npy # in the folder where these are stored. num_gsf = len(fnmatch.filter(next(os.walk(path))[2], 'gsf_*.npy')) From 5fb12e136363d7221710daa4f0b96e86262e7ae5 Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Mon, 17 Aug 2020 11:11:09 +0200 Subject: [PATCH 13/22] Fixed a small bug --- ompy/extractor.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ompy/extractor.py b/ompy/extractor.py index 45dd180e..27c5f396 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -5,8 +5,6 @@ from contextlib import redirect_stdout from uncertainties import unumpy import os -import fnmatch - import fnmatch from pathlib import Path from typing import Optional, Union, Any, Tuple, List @@ -68,7 +66,7 @@ class Extractor: - If path is given, it tries to load. If path is later set, it is not created. This is a very common pattern. Consider superclassing the disk book-keeping. - - Add proper unit test + - Add unit tests """ def __init__(self, path: Optional[Union[str, Path]] = None): @@ -402,8 +400,9 @@ def load(self, path: Union[str, Path]): path = Path(path) - if not path.isdir(): - raise ValueError(f"Path '{path}' does not exist.") + if not path.is_dir(): + raise ValueError(f"Path '{path}' does not exist \ + or is not a folder.") # Count number of files with name gsf_*.npy and nld_*.npy # in the folder where these are stored. From e8e3de714758f5bdc799d8f05797eea29fb482c9 Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Mon, 17 Aug 2020 11:11:31 +0200 Subject: [PATCH 14/22] Added an abstract superclass for loading and storing of objects to disk --- ompy/abstract_load_saver.py | 70 +++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 ompy/abstract_load_saver.py diff --git a/ompy/abstract_load_saver.py b/ompy/abstract_load_saver.py new file mode 100644 index 00000000..6b1e7948 --- /dev/null +++ b/ompy/abstract_load_saver.py @@ -0,0 +1,70 @@ +import warnings +import logging +from pathlib import Path +from typing import Optional, Union, Any, Tuple, List + + +class abstract_load_saver: + """ An abstract super class to define the standard + way for derived classes to save and load data from disk. + """ + + def __init__(self, path: Union[Union[str, Path], None], is_dir: bool = True): + """ Set the default save position at this point. + Args: + path: Where to save and/or load from disk. + is_dir: If the target path is a folder or a file. + """ + + if path is None: + self.path = None + else: + self.path = Path(path) + self.is_dir = is_dir + + try: + self.load(self.path) + except ValueError: + if is_dir: + self.path.mkdir(exist_ok=True, parents=True) + else: + pass + + def try_load(self): + """ Tries to load from file or folder set in self.path. + """ + + if is_dir: + try: + self.load(self.path) + except ValueError: + self.path.mkdir(exist_ok=True, parents=True) + else: # For files the exception should be handled elsewhere. + self.load(self.path) + + def load(self, path: Union[str, Path], + filetype: Optional[str] = None): + """ Method for loading the file or folder. To be implemented + by the subclasses. + + Args: + path: Path to where to find the object(s). + filetype: Type of the file to load. Will be deduced the + filetype from suffix if not given. Only applicable for + subclasses that loads a single file. + """ + raise NotImplemented + + def save(self, path: Union[str, Path], + filetype: Optional[str] = None, + **kwargs): + """ Method for saving to file or folder. to be implemented + by the subclasses. + + Args: + path: Path to where to store the object(s). + filetype: Type of the file to store. Will be deduced the + filetype from suffix if not given. Only applicable for + subclasses that saves a single file. + """ + raise NotImplemented From 4ba11faf66b97f9101cee8be1bf297db90276f0e Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Mon, 17 Aug 2020 13:40:33 +0200 Subject: [PATCH 15/22] Small bugfix --- ompy/extractor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ompy/extractor.py b/ompy/extractor.py index 27c5f396..bd2736a3 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -129,7 +129,7 @@ def extract_from(self, ensemble: Ensemble, nlds = [] gsfs = [] - if regenerate: + if not regenerate: try: # If successfully loaded, we are done! LOG.debug(f"loading from {path}") self.load(self.path) From aaa8c4f6ec0dd182458ed40e521550ce515b5d02 Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Mon, 17 Aug 2020 17:09:55 +0200 Subject: [PATCH 16/22] Fixes --- ompy/abstract_load_saver.py | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/ompy/abstract_load_saver.py b/ompy/abstract_load_saver.py index 6b1e7948..0a7ca39f 100644 --- a/ompy/abstract_load_saver.py +++ b/ompy/abstract_load_saver.py @@ -9,7 +9,8 @@ class abstract_load_saver: way for derived classes to save and load data from disk. """ - def __init__(self, path: Union[Union[str, Path], None], is_dir: bool = True): + def __init__(self, path: Union[Union[str, Path], None], + is_dir: bool = True): """ Set the default save position at this point. Args: path: Where to save and/or load from disk. @@ -21,25 +22,12 @@ def __init__(self, path: Union[Union[str, Path], None], is_dir: bool = True): else: self.path = Path(path) self.is_dir = is_dir - - try: - self.load(self.path) - except ValueError: - if is_dir: - self.path.mkdir(exist_ok=True, parents=True) - else: - pass - - def try_load(self): - """ Tries to load from file or folder set in self.path. - """ - if is_dir: try: self.load(self.path) except ValueError: self.path.mkdir(exist_ok=True, parents=True) - else: # For files the exception should be handled elsewhere. + else: self.load(self.path) def load(self, path: Union[str, Path], @@ -53,7 +41,7 @@ def load(self, path: Union[str, Path], filetype from suffix if not given. Only applicable for subclasses that loads a single file. """ - raise NotImplemented + raise NotImplementedError def save(self, path: Union[str, Path], filetype: Optional[str] = None, @@ -67,4 +55,4 @@ def save(self, path: Union[str, Path], filetype from suffix if not given. Only applicable for subclasses that saves a single file. """ - raise NotImplemented + raise NotImplementedError From c1aab186db21418e25bae5c67605c58fa6643c8f Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Mon, 17 Aug 2020 17:33:46 +0200 Subject: [PATCH 17/22] Added object as superclass --- ompy/abstract_load_saver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ompy/abstract_load_saver.py b/ompy/abstract_load_saver.py index 0a7ca39f..52359a70 100644 --- a/ompy/abstract_load_saver.py +++ b/ompy/abstract_load_saver.py @@ -4,7 +4,7 @@ from typing import Optional, Union, Any, Tuple, List -class abstract_load_saver: +class abstract_load_saver(object): """ An abstract super class to define the standard way for derived classes to save and load data from disk. """ From 4539cb2cb433535ad1eb3c074f785b706e965377 Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Mon, 17 Aug 2020 17:44:14 +0200 Subject: [PATCH 18/22] Updated ensemble to use the abstract_load_saver --- ompy/extractor.py | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/ompy/extractor.py b/ompy/extractor.py index bd2736a3..c96594e9 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -14,6 +14,7 @@ from .vector import Vector from .decomposition import chisquare_diagonal, nld_T_product from .action import Action +from .abstract_load_saver import abstract_load_saver if 'JPY_PARENT_PID' in os.environ: from tqdm import tqdm_notebook as tqdm @@ -23,7 +24,7 @@ LOG = logging.getLogger(__name__) -class Extractor: +class Extractor(abstract_load_saver): """Extracts nld and γSF from an Ensemble or a Matrix Basically a wrapper around a minimization routine with bookeeping. @@ -75,22 +76,15 @@ def __init__(self, trapezoid (Action[Matrix], optional): see above path (Path or str, optional): see above """ + self.regenerate = False self.method = 'Powell' self.options = {'disp': True, 'ftol': 1e-3, 'maxfev': None} self.nld: List[Vector] = [] self.gsf: List[Vector] = [] - if path is not None: - self.path = Path(path) - try: - self.load(self.path) - except ValueError: # Error given if no folder exist - self.path.mkdir(exist_ok=True, parents=True) - else: + if path is None: path = 'saved_run/extractor' - self.path = Path(path) - self.path.mkdir(exist_ok=True, parents=True) self.x0 = None self.randomize_initial_values: bool = True @@ -100,6 +94,8 @@ def __init__(self, self.extend_fit_by_resolution: bool = False self.resolution_Ex = 150 # keV + super(Extractor, self).__init__(path, True) + def __call__(self, ensemble: Ensemble, trapezoid: Action): return self.extract_from(ensemble, trapezoid) @@ -406,22 +402,18 @@ def load(self, path: Union[str, Path]): # Count number of files with name gsf_*.npy and nld_*.npy # in the folder where these are stored. - num_gsf = len(fnmatch.filter(next(os.walk(path))[2], 'gsf_*.npy')) - num_nld = len(fnmatch.filter(next(os.walk(path))[2], 'nld_*.npy')) - - assert num_gsf == num_nld, \ - "Number of NLD files doesn't match the number of GSF files." + gsfs = list(path.glob("gsf_[0-9]*.*")) + nlds = list(path.glob("nld_[0-9]*.*")) - num = num_gsf + assert len(gsfs) == len(nlds), \ + "Ensemble NLD/GSF corrupt" - if num_gsf == num_nld == 0: + if len(gsfs) == 0: raise RuntimeError("No NLD and GSF files found.") - for i in range(num): - gsf_path = path / f'gsf_{i}.npy' - nld_path = path / f'nld_{i}.npy' - self.gsf.append(Vector(path=gsf_path)) - self.nld.append(Vector(path=nld_path)) + for (gsf, nld) in zip(gsfs, nlds): + self.gsf.append(Vector(path=gsf)) + self.nld.append(Vector(path=nld)) @staticmethod def x0_BSFG(E_nld: np.ndarray, E0: float = -.2, a: float = 15): From abdb60e6ff02a2d973e5794e8352e33c4afd0257 Mon Sep 17 00:00:00 2001 From: Vetle Wegner Ingeberg Date: Mon, 17 Aug 2020 17:51:16 +0200 Subject: [PATCH 19/22] Added notes in the release_notes --- release_note.md | 1 + 1 file changed, 1 insertion(+) diff --git a/release_note.md b/release_note.md index 54b482f2..ad296089 100644 --- a/release_note.md +++ b/release_note.md @@ -6,6 +6,7 @@ Changes: - Changed the way the `Extractor` class are called. The ensamble and trapezoid are no longer given in the constructor, but are mandatory arguments in the `extract_from()` method. The class also now uses the same convention for loading and saving from file as the `Vector` and `Matrix` classes. +- Initial work to unify the way objects are saved/loaded from disk. ## v.1.1.0 Most important changes: From fa1a2b1a157c8140355d1bb8ad5cab104a07e8ae Mon Sep 17 00:00:00 2001 From: fzeiser Date: Tue, 18 Aug 2020 09:05:36 +0200 Subject: [PATCH 20/22] Normalize NamingConvention and docs --- ompy/abstract_load_saver.py | 2 +- ompy/extractor.py | 25 +++++++++++-------------- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/ompy/abstract_load_saver.py b/ompy/abstract_load_saver.py index 52359a70..5d5b5dce 100644 --- a/ompy/abstract_load_saver.py +++ b/ompy/abstract_load_saver.py @@ -4,7 +4,7 @@ from typing import Optional, Union, Any, Tuple, List -class abstract_load_saver(object): +class AbstractLoadSaver(object): """ An abstract super class to define the standard way for derived classes to save and load data from disk. """ diff --git a/ompy/extractor.py b/ompy/extractor.py index c96594e9..2bb6f67c 100644 --- a/ompy/extractor.py +++ b/ompy/extractor.py @@ -14,7 +14,7 @@ from .vector import Vector from .decomposition import chisquare_diagonal, nld_T_product from .action import Action -from .abstract_load_saver import abstract_load_saver +from .abstract_load_saver import AbstractLoadSaver if 'JPY_PARENT_PID' in os.environ: from tqdm import tqdm_notebook as tqdm @@ -24,7 +24,7 @@ LOG = logging.getLogger(__name__) -class Extractor(abstract_load_saver): +class Extractor(AbstractLoadSaver): """Extracts nld and γSF from an Ensemble or a Matrix Basically a wrapper around a minimization routine with bookeeping. @@ -32,7 +32,8 @@ class Extractor(abstract_load_saver): the desired shape, nuclear level density (nld) and gamma strength function (gsf/γSF) are extracted. The results are exposed in the attributes self.nld and self.gsf, as well as saved to disk. The saved results are - used if filenames match, or can be loaded manually with `load()`. + used if filenames match (and `regenerate` is `False`, or can be loaded + manually with `load()`. The method `decompose(matrix, [std])` extracts the nld and gsf from a single Matrix. @@ -72,9 +73,8 @@ class Extractor(abstract_load_saver): def __init__(self, path: Optional[Union[str, Path]] = None): """ - ensemble (Ensemble, optional): see above - trapezoid (Action[Matrix], optional): see above - path (Path or str, optional): see above + Args: + path (Path or str, optional): see above """ self.regenerate = False @@ -100,7 +100,7 @@ def __call__(self, ensemble: Ensemble, trapezoid: Action): return self.extract_from(ensemble, trapezoid) def extract_from(self, ensemble: Ensemble, - trapezoid: Action = None, + trapezoid: Action, regenerate: Optional[bool] = None): """Decompose each first generation matrix in an Ensemble @@ -109,9 +109,8 @@ def extract_from(self, ensemble: Ensemble, attributes self.nld and self.gsf. Args: - ensemble (Ensemble, optional): The ensemble to extract nld and gsf - from. Can be provided in when initializing instead. - trapezoid (Action, optional): An Action describing the cut to apply + ensemble (Ensembl): The ensemble to extract nld and gsf from. + trapezoid (Action): An Action describing the cut to apply to the matrices to obtain the desired region for extracting nld and gsf. regenerate (bool, optional): Whether to regenerate all nld and gsf @@ -150,8 +149,7 @@ def step(self, ensemble: Ensemble, trapezoid: Action, classes Args: - ensemble (Ensemble): The ensemble to extract nld and gsf - from. Can be provided in when initializing instead. + ensemble (Ensemble): The ensemble to extract nld and gsf from. trapezoid (Action): An Action describing the cut to apply to the matrices to obtain the desired region for extracting nld and gsf. @@ -165,8 +163,7 @@ def _extract(self, ensemble: Ensemble, trapezoid: Action, """ Extract nld and gsf from matrix number i from Ensemble Args: - ensemble (Ensemble): The ensemble to extract nld and gsf - from. Can be provided in when initializing instead. + ensemble (Ensemble): The ensemble to extract nld and gsf from. trapezoid (Action): An Action describing the cut to apply to the matrices to obtain the desired region for extracting nld and gsf. From f5f8803e9940578f219e09333f23cd48e14fef42 Mon Sep 17 00:00:00 2001 From: fzeiser Date: Tue, 18 Aug 2020 09:18:26 +0200 Subject: [PATCH 21/22] fixed typehint --- ompy/abstract_load_saver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ompy/abstract_load_saver.py b/ompy/abstract_load_saver.py index 5d5b5dce..e7f4b326 100644 --- a/ompy/abstract_load_saver.py +++ b/ompy/abstract_load_saver.py @@ -9,7 +9,7 @@ class AbstractLoadSaver(object): way for derived classes to save and load data from disk. """ - def __init__(self, path: Union[Union[str, Path], None], + def __init__(self, path: Optional[Union[str, Path]], is_dir: bool = True): """ Set the default save position at this point. Args: From 579d12d9985aaf700beccf49a4420528bad2abe4 Mon Sep 17 00:00:00 2001 From: fzeiser Date: Tue, 18 Aug 2020 09:27:21 +0200 Subject: [PATCH 22/22] Small fix previous commit + try to reduce complexity --- ompy/abstract_load_saver.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/ompy/abstract_load_saver.py b/ompy/abstract_load_saver.py index e7f4b326..87bd2628 100644 --- a/ompy/abstract_load_saver.py +++ b/ompy/abstract_load_saver.py @@ -9,26 +9,24 @@ class AbstractLoadSaver(object): way for derived classes to save and load data from disk. """ - def __init__(self, path: Optional[Union[str, Path]], + def __init__(self, path: Optional[Union[str, Path]] = None, is_dir: bool = True): """ Set the default save position at this point. Args: path: Where to save and/or load from disk. - is_dir: If the target path is a folder or a file. + is_dir: If the target path is a folder or a file. Defaults to + True. """ - if path is None: self.path = None else: self.path = Path(path) self.is_dir = is_dir - if is_dir: - try: - self.load(self.path) - except ValueError: - self.path.mkdir(exist_ok=True, parents=True) - else: + try: self.load(self.path) + except ValueError: + if is_dir: + self.path.mkdir(exist_ok=True, parents=True) def load(self, path: Union[str, Path], filetype: Optional[str] = None):