id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
22,800
QInfer/python-qinfer
src/qinfer/smc.py
SMCUpdater.expected_information_gain
def expected_information_gain(self, expparams): r""" Calculates the expected information gain for each hypothetical experiment. :param expparams: The experiments at which to compute expected information gain. :type expparams: :class:`~numpy.ndarray` of dtype given by the current model's :attr:`~qinfer.abstract_model.Simulatable.expparams_dtype` property, and of shape ``(n,)`` :return float: The expected information gain for each hypothetical experiment in ``expparams``. """ # This is a special case of the KL divergence estimator (see below), # in which the other distribution is guaranteed to share support. # for models whose outcome number changes with experiment, we # take the easy way out and for-loop over experiments n_eps = expparams.size if n_eps > 1 and not self.model.is_n_outcomes_constant: risk = np.empty(n_eps) for idx in range(n_eps): risk[idx] = self.expected_information_gain(expparams[idx, np.newaxis]) return risk # number of outcomes for the first experiment os = self.model.domain(expparams[0,np.newaxis])[0].values # compute the hypothetical weights, likelihoods and normalizations for # every possible outcome and expparam # the likelihood over outcomes should sum to 1, so don't compute for last outcome w_hyp, L, N = self.hypothetical_update( os[:-1], expparams, return_normalization=True, return_likelihood=True ) w_hyp_last_outcome = (1 - L.sum(axis=0)) * self.particle_weights[np.newaxis, :] N = np.concatenate([N[:,:,0], np.sum(w_hyp_last_outcome[np.newaxis,:,:], axis=2)], axis=0) w_hyp_last_outcome = w_hyp_last_outcome / N[-1,:,np.newaxis] w_hyp = np.concatenate([w_hyp, w_hyp_last_outcome[np.newaxis,:,:]], axis=0) # w_hyp.shape == (n_out, n_eps, n_particles) # N.shape == (n_out, n_eps) # compute the Kullback-Liebler divergence for every experiment and possible outcome # KLD.shape == (n_out, n_eps) KLD = np.sum(w_hyp * np.log(w_hyp / self.particle_weights), axis=2) # return the expected KLD (ie expected info gain) for every experiment return np.sum(N * KLD, axis=0)
python
def expected_information_gain(self, expparams): r""" Calculates the expected information gain for each hypothetical experiment. :param expparams: The experiments at which to compute expected information gain. :type expparams: :class:`~numpy.ndarray` of dtype given by the current model's :attr:`~qinfer.abstract_model.Simulatable.expparams_dtype` property, and of shape ``(n,)`` :return float: The expected information gain for each hypothetical experiment in ``expparams``. """ # This is a special case of the KL divergence estimator (see below), # in which the other distribution is guaranteed to share support. # for models whose outcome number changes with experiment, we # take the easy way out and for-loop over experiments n_eps = expparams.size if n_eps > 1 and not self.model.is_n_outcomes_constant: risk = np.empty(n_eps) for idx in range(n_eps): risk[idx] = self.expected_information_gain(expparams[idx, np.newaxis]) return risk # number of outcomes for the first experiment os = self.model.domain(expparams[0,np.newaxis])[0].values # compute the hypothetical weights, likelihoods and normalizations for # every possible outcome and expparam # the likelihood over outcomes should sum to 1, so don't compute for last outcome w_hyp, L, N = self.hypothetical_update( os[:-1], expparams, return_normalization=True, return_likelihood=True ) w_hyp_last_outcome = (1 - L.sum(axis=0)) * self.particle_weights[np.newaxis, :] N = np.concatenate([N[:,:,0], np.sum(w_hyp_last_outcome[np.newaxis,:,:], axis=2)], axis=0) w_hyp_last_outcome = w_hyp_last_outcome / N[-1,:,np.newaxis] w_hyp = np.concatenate([w_hyp, w_hyp_last_outcome[np.newaxis,:,:]], axis=0) # w_hyp.shape == (n_out, n_eps, n_particles) # N.shape == (n_out, n_eps) # compute the Kullback-Liebler divergence for every experiment and possible outcome # KLD.shape == (n_out, n_eps) KLD = np.sum(w_hyp * np.log(w_hyp / self.particle_weights), axis=2) # return the expected KLD (ie expected info gain) for every experiment return np.sum(N * KLD, axis=0)
[ "def", "expected_information_gain", "(", "self", ",", "expparams", ")", ":", "# This is a special case of the KL divergence estimator (see below),", "# in which the other distribution is guaranteed to share support.", "# for models whose outcome number changes with experiment, we ", "# take th...
r""" Calculates the expected information gain for each hypothetical experiment. :param expparams: The experiments at which to compute expected information gain. :type expparams: :class:`~numpy.ndarray` of dtype given by the current model's :attr:`~qinfer.abstract_model.Simulatable.expparams_dtype` property, and of shape ``(n,)`` :return float: The expected information gain for each hypothetical experiment in ``expparams``.
[ "r", "Calculates", "the", "expected", "information", "gain", "for", "each", "hypothetical", "experiment", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L614-L663
22,801
QInfer/python-qinfer
src/qinfer/smc.py
SMCUpdater.posterior_marginal
def posterior_marginal(self, idx_param=0, res=100, smoothing=0, range_min=None, range_max=None): """ Returns an estimate of the marginal distribution of a given model parameter, based on taking the derivative of the interpolated cdf. :param int idx_param: Index of parameter to be marginalized. :param int res1: Resolution of of the axis. :param float smoothing: Standard deviation of the Gaussian kernel used to smooth; same units as parameter. :param float range_min: Minimum range of the output axis. :param float range_max: Maximum range of the output axis. .. seealso:: :meth:`SMCUpdater.plot_posterior_marginal` """ # We need to sort the particles to get cumsum to make sense. # interp1d would do it anyways (using argsort, too), so it's not a waste s = np.argsort(self.particle_locations[:,idx_param]) locs = self.particle_locations[s,idx_param] # relevant axis discretization r_min = np.min(locs) if range_min is None else range_min r_max = np.max(locs) if range_max is None else range_max ps = np.linspace(r_min, r_max, res) # interpolate the cdf of the marginal distribution using cumsum interp = scipy.interpolate.interp1d( np.append(locs, r_max + np.abs(r_max-r_min)), np.append(np.cumsum(self.particle_weights[s]), 1), #kind='cubic', bounds_error=False, fill_value=0, assume_sorted=True ) # get distribution from derivative of cdf, and smooth it pr = np.gradient(interp(ps), ps[1]-ps[0]) if smoothing > 0: gaussian_filter1d(pr, res*smoothing/(np.abs(r_max-r_min)), output=pr) del interp return ps, pr
python
def posterior_marginal(self, idx_param=0, res=100, smoothing=0, range_min=None, range_max=None): # We need to sort the particles to get cumsum to make sense. # interp1d would do it anyways (using argsort, too), so it's not a waste s = np.argsort(self.particle_locations[:,idx_param]) locs = self.particle_locations[s,idx_param] # relevant axis discretization r_min = np.min(locs) if range_min is None else range_min r_max = np.max(locs) if range_max is None else range_max ps = np.linspace(r_min, r_max, res) # interpolate the cdf of the marginal distribution using cumsum interp = scipy.interpolate.interp1d( np.append(locs, r_max + np.abs(r_max-r_min)), np.append(np.cumsum(self.particle_weights[s]), 1), #kind='cubic', bounds_error=False, fill_value=0, assume_sorted=True ) # get distribution from derivative of cdf, and smooth it pr = np.gradient(interp(ps), ps[1]-ps[0]) if smoothing > 0: gaussian_filter1d(pr, res*smoothing/(np.abs(r_max-r_min)), output=pr) del interp return ps, pr
[ "def", "posterior_marginal", "(", "self", ",", "idx_param", "=", "0", ",", "res", "=", "100", ",", "smoothing", "=", "0", ",", "range_min", "=", "None", ",", "range_max", "=", "None", ")", ":", "# We need to sort the particles to get cumsum to make sense.", "# i...
Returns an estimate of the marginal distribution of a given model parameter, based on taking the derivative of the interpolated cdf. :param int idx_param: Index of parameter to be marginalized. :param int res1: Resolution of of the axis. :param float smoothing: Standard deviation of the Gaussian kernel used to smooth; same units as parameter. :param float range_min: Minimum range of the output axis. :param float range_max: Maximum range of the output axis. .. seealso:: :meth:`SMCUpdater.plot_posterior_marginal`
[ "Returns", "an", "estimate", "of", "the", "marginal", "distribution", "of", "a", "given", "model", "parameter", "based", "on", "taking", "the", "derivative", "of", "the", "interpolated", "cdf", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L672-L716
22,802
QInfer/python-qinfer
src/qinfer/smc.py
SMCUpdater.plot_posterior_marginal
def plot_posterior_marginal(self, idx_param=0, res=100, smoothing=0, range_min=None, range_max=None, label_xaxis=True, other_plot_args={}, true_model=None ): """ Plots a marginal of the requested parameter. :param int idx_param: Index of parameter to be marginalized. :param int res1: Resolution of of the axis. :param float smoothing: Standard deviation of the Gaussian kernel used to smooth; same units as parameter. :param float range_min: Minimum range of the output axis. :param float range_max: Maximum range of the output axis. :param bool label_xaxis: Labels the :math:`x`-axis with the model parameter name given by this updater's model. :param dict other_plot_args: Keyword arguments to be passed to matplotlib's ``plot`` function. :param np.ndarray true_model: Plots a given model parameter vector as the "true" model for comparison. .. seealso:: :meth:`SMCUpdater.posterior_marginal` """ res = plt.plot(*self.posterior_marginal( idx_param, res, smoothing, range_min, range_max ), **other_plot_args) if label_xaxis: plt.xlabel('${}$'.format(self.model.modelparam_names[idx_param])) if true_model is not None: true_model = true_model[0, idx_param] if true_model.ndim == 2 else true_model[idx_param] old_ylim = plt.ylim() plt.vlines(true_model, old_ylim[0] - 0.1, old_ylim[1] + 0.1, color='k', linestyles='--') plt.ylim(old_ylim) return res
python
def plot_posterior_marginal(self, idx_param=0, res=100, smoothing=0, range_min=None, range_max=None, label_xaxis=True, other_plot_args={}, true_model=None ): res = plt.plot(*self.posterior_marginal( idx_param, res, smoothing, range_min, range_max ), **other_plot_args) if label_xaxis: plt.xlabel('${}$'.format(self.model.modelparam_names[idx_param])) if true_model is not None: true_model = true_model[0, idx_param] if true_model.ndim == 2 else true_model[idx_param] old_ylim = plt.ylim() plt.vlines(true_model, old_ylim[0] - 0.1, old_ylim[1] + 0.1, color='k', linestyles='--') plt.ylim(old_ylim) return res
[ "def", "plot_posterior_marginal", "(", "self", ",", "idx_param", "=", "0", ",", "res", "=", "100", ",", "smoothing", "=", "0", ",", "range_min", "=", "None", ",", "range_max", "=", "None", ",", "label_xaxis", "=", "True", ",", "other_plot_args", "=", "{"...
Plots a marginal of the requested parameter. :param int idx_param: Index of parameter to be marginalized. :param int res1: Resolution of of the axis. :param float smoothing: Standard deviation of the Gaussian kernel used to smooth; same units as parameter. :param float range_min: Minimum range of the output axis. :param float range_max: Maximum range of the output axis. :param bool label_xaxis: Labels the :math:`x`-axis with the model parameter name given by this updater's model. :param dict other_plot_args: Keyword arguments to be passed to matplotlib's ``plot`` function. :param np.ndarray true_model: Plots a given model parameter vector as the "true" model for comparison. .. seealso:: :meth:`SMCUpdater.posterior_marginal`
[ "Plots", "a", "marginal", "of", "the", "requested", "parameter", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L718-L754
22,803
QInfer/python-qinfer
src/qinfer/smc.py
SMCUpdater.plot_covariance
def plot_covariance(self, corr=False, param_slice=None, tick_labels=None, tick_params=None): """ Plots the covariance matrix of the posterior as a Hinton diagram. .. note:: This function requires that mpltools is installed. :param bool corr: If `True`, the covariance matrix is first normalized by the outer product of the square root diagonal of the covariance matrix such that the correlation matrix is plotted instead. :param slice param_slice: Slice of the modelparameters to be plotted. :param list tick_labels: List of tick labels for each component; by default, these are drawn from the model itself. """ if mpls is None: raise ImportError("Hinton diagrams require mpltools.") if param_slice is None: param_slice = np.s_[:] tick_labels = ( list(range(len(self.model.modelparam_names[param_slice]))), tick_labels if tick_labels is not None else list(map(u"${}$".format, self.model.modelparam_names[param_slice])) ) cov = self.est_covariance_mtx(corr=corr)[param_slice, param_slice] retval = mpls.hinton(cov) plt.xticks(*tick_labels, **(tick_params if tick_params is not None else {})) plt.yticks(*tick_labels, **(tick_params if tick_params is not None else {})) plt.gca().xaxis.tick_top() return retval
python
def plot_covariance(self, corr=False, param_slice=None, tick_labels=None, tick_params=None): if mpls is None: raise ImportError("Hinton diagrams require mpltools.") if param_slice is None: param_slice = np.s_[:] tick_labels = ( list(range(len(self.model.modelparam_names[param_slice]))), tick_labels if tick_labels is not None else list(map(u"${}$".format, self.model.modelparam_names[param_slice])) ) cov = self.est_covariance_mtx(corr=corr)[param_slice, param_slice] retval = mpls.hinton(cov) plt.xticks(*tick_labels, **(tick_params if tick_params is not None else {})) plt.yticks(*tick_labels, **(tick_params if tick_params is not None else {})) plt.gca().xaxis.tick_top() return retval
[ "def", "plot_covariance", "(", "self", ",", "corr", "=", "False", ",", "param_slice", "=", "None", ",", "tick_labels", "=", "None", ",", "tick_params", "=", "None", ")", ":", "if", "mpls", "is", "None", ":", "raise", "ImportError", "(", "\"Hinton diagrams ...
Plots the covariance matrix of the posterior as a Hinton diagram. .. note:: This function requires that mpltools is installed. :param bool corr: If `True`, the covariance matrix is first normalized by the outer product of the square root diagonal of the covariance matrix such that the correlation matrix is plotted instead. :param slice param_slice: Slice of the modelparameters to be plotted. :param list tick_labels: List of tick labels for each component; by default, these are drawn from the model itself.
[ "Plots", "the", "covariance", "matrix", "of", "the", "posterior", "as", "a", "Hinton", "diagram", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L756-L792
22,804
QInfer/python-qinfer
src/qinfer/smc.py
SMCUpdater.posterior_mesh
def posterior_mesh(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01): """ Returns a mesh, useful for plotting, of kernel density estimation of a 2D projection of the current posterior distribution. :param int idx_param1: Parameter to be treated as :math:`x` when plotting. :param int idx_param2: Parameter to be treated as :math:`y` when plotting. :param int res1: Resolution along the :math:`x` direction. :param int res2: Resolution along the :math:`y` direction. :param float smoothing: Standard deviation of the Gaussian kernel used to smooth the particle approximation to the current posterior. .. seealso:: :meth:`SMCUpdater.plot_posterior_contour` """ # WARNING: fancy indexing is used here, which means that a copy is # made. locs = self.particle_locations[:, [idx_param1, idx_param2]] p1s, p2s = np.meshgrid( np.linspace(np.min(locs[:, 0]), np.max(locs[:, 0]), res1), np.linspace(np.min(locs[:, 1]), np.max(locs[:, 1]), res2) ) plot_locs = np.array([p1s, p2s]).T.reshape((np.prod(p1s.shape), 2)) pr = np.sum( # <- sum over the particles in the SMC approximation. np.prod( # <- product over model parameters to get a multinormal # Evaluate the PDF at the plotting locations, with a normal # located at the particle locations. scipy.stats.norm.pdf( plot_locs[:, np.newaxis, :], scale=smoothing, loc=locs ), axis=-1 ) * self.particle_weights, axis=1 ).reshape(p1s.shape) # Finally, reshape back into the same shape as the mesh. return p1s, p2s, pr
python
def posterior_mesh(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01): # WARNING: fancy indexing is used here, which means that a copy is # made. locs = self.particle_locations[:, [idx_param1, idx_param2]] p1s, p2s = np.meshgrid( np.linspace(np.min(locs[:, 0]), np.max(locs[:, 0]), res1), np.linspace(np.min(locs[:, 1]), np.max(locs[:, 1]), res2) ) plot_locs = np.array([p1s, p2s]).T.reshape((np.prod(p1s.shape), 2)) pr = np.sum( # <- sum over the particles in the SMC approximation. np.prod( # <- product over model parameters to get a multinormal # Evaluate the PDF at the plotting locations, with a normal # located at the particle locations. scipy.stats.norm.pdf( plot_locs[:, np.newaxis, :], scale=smoothing, loc=locs ), axis=-1 ) * self.particle_weights, axis=1 ).reshape(p1s.shape) # Finally, reshape back into the same shape as the mesh. return p1s, p2s, pr
[ "def", "posterior_mesh", "(", "self", ",", "idx_param1", "=", "0", ",", "idx_param2", "=", "1", ",", "res1", "=", "100", ",", "res2", "=", "100", ",", "smoothing", "=", "0.01", ")", ":", "# WARNING: fancy indexing is used here, which means that a copy is", "# ...
Returns a mesh, useful for plotting, of kernel density estimation of a 2D projection of the current posterior distribution. :param int idx_param1: Parameter to be treated as :math:`x` when plotting. :param int idx_param2: Parameter to be treated as :math:`y` when plotting. :param int res1: Resolution along the :math:`x` direction. :param int res2: Resolution along the :math:`y` direction. :param float smoothing: Standard deviation of the Gaussian kernel used to smooth the particle approximation to the current posterior. .. seealso:: :meth:`SMCUpdater.plot_posterior_contour`
[ "Returns", "a", "mesh", "useful", "for", "plotting", "of", "kernel", "density", "estimation", "of", "a", "2D", "projection", "of", "the", "current", "posterior", "distribution", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L795-L838
22,805
QInfer/python-qinfer
src/qinfer/smc.py
SMCUpdater.plot_posterior_contour
def plot_posterior_contour(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01): """ Plots a contour of the kernel density estimation of a 2D projection of the current posterior distribution. :param int idx_param1: Parameter to be treated as :math:`x` when plotting. :param int idx_param2: Parameter to be treated as :math:`y` when plotting. :param int res1: Resolution along the :math:`x` direction. :param int res2: Resolution along the :math:`y` direction. :param float smoothing: Standard deviation of the Gaussian kernel used to smooth the particle approximation to the current posterior. .. seealso:: :meth:`SMCUpdater.posterior_mesh` """ return plt.contour(*self.posterior_mesh(idx_param1, idx_param2, res1, res2, smoothing))
python
def plot_posterior_contour(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01): return plt.contour(*self.posterior_mesh(idx_param1, idx_param2, res1, res2, smoothing))
[ "def", "plot_posterior_contour", "(", "self", ",", "idx_param1", "=", "0", ",", "idx_param2", "=", "1", ",", "res1", "=", "100", ",", "res2", "=", "100", ",", "smoothing", "=", "0.01", ")", ":", "return", "plt", ".", "contour", "(", "*", "self", ".",...
Plots a contour of the kernel density estimation of a 2D projection of the current posterior distribution. :param int idx_param1: Parameter to be treated as :math:`x` when plotting. :param int idx_param2: Parameter to be treated as :math:`y` when plotting. :param int res1: Resolution along the :math:`x` direction. :param int res2: Resolution along the :math:`y` direction. :param float smoothing: Standard deviation of the Gaussian kernel used to smooth the particle approximation to the current posterior. .. seealso:: :meth:`SMCUpdater.posterior_mesh`
[ "Plots", "a", "contour", "of", "the", "kernel", "density", "estimation", "of", "a", "2D", "projection", "of", "the", "current", "posterior", "distribution", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L840-L858
22,806
QInfer/python-qinfer
src/qinfer/tomography/plotting_tools.py
plot_rebit_prior
def plot_rebit_prior(prior, rebit_axes=REBIT_AXES, n_samples=2000, true_state=None, true_size=250, force_mean=None, legend=True, mean_color_index=2 ): """ Plots rebit states drawn from a given prior. :param qinfer.tomography.DensityOperatorDistribution prior: Distribution over rebit states to plot. :param list rebit_axes: List containing indices for the :math:`x` and :math:`z` axes. :param int n_samples: Number of samples to draw from the prior. :param np.ndarray true_state: State to be plotted as a "true" state for comparison. """ pallette = plt.rcParams['axes.color_cycle'] plot_rebit_modelparams(prior.sample(n_samples), c=pallette[0], label='Prior', rebit_axes=rebit_axes ) if true_state is not None: plot_rebit_modelparams(true_state, c=pallette[1], label='True', marker='*', s=true_size, rebit_axes=rebit_axes ) if hasattr(prior, '_mean') or force_mean is not None: mean = force_mean if force_mean is not None else prior._mean plot_rebit_modelparams( prior._basis.state_to_modelparams(mean)[None, :], edgecolors=pallette[mean_color_index], s=250, facecolors='none', linewidth=3, label='Mean', rebit_axes=rebit_axes ) plot_decorate_rebits(prior.basis, rebit_axes=rebit_axes ) if legend: plt.legend(loc='lower left', ncol=3, scatterpoints=1)
python
def plot_rebit_prior(prior, rebit_axes=REBIT_AXES, n_samples=2000, true_state=None, true_size=250, force_mean=None, legend=True, mean_color_index=2 ): pallette = plt.rcParams['axes.color_cycle'] plot_rebit_modelparams(prior.sample(n_samples), c=pallette[0], label='Prior', rebit_axes=rebit_axes ) if true_state is not None: plot_rebit_modelparams(true_state, c=pallette[1], label='True', marker='*', s=true_size, rebit_axes=rebit_axes ) if hasattr(prior, '_mean') or force_mean is not None: mean = force_mean if force_mean is not None else prior._mean plot_rebit_modelparams( prior._basis.state_to_modelparams(mean)[None, :], edgecolors=pallette[mean_color_index], s=250, facecolors='none', linewidth=3, label='Mean', rebit_axes=rebit_axes ) plot_decorate_rebits(prior.basis, rebit_axes=rebit_axes ) if legend: plt.legend(loc='lower left', ncol=3, scatterpoints=1)
[ "def", "plot_rebit_prior", "(", "prior", ",", "rebit_axes", "=", "REBIT_AXES", ",", "n_samples", "=", "2000", ",", "true_state", "=", "None", ",", "true_size", "=", "250", ",", "force_mean", "=", "None", ",", "legend", "=", "True", ",", "mean_color_index", ...
Plots rebit states drawn from a given prior. :param qinfer.tomography.DensityOperatorDistribution prior: Distribution over rebit states to plot. :param list rebit_axes: List containing indices for the :math:`x` and :math:`z` axes. :param int n_samples: Number of samples to draw from the prior. :param np.ndarray true_state: State to be plotted as a "true" state for comparison.
[ "Plots", "rebit", "states", "drawn", "from", "a", "given", "prior", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/plotting_tools.py#L156-L202
22,807
QInfer/python-qinfer
src/qinfer/tomography/plotting_tools.py
plot_rebit_posterior
def plot_rebit_posterior(updater, prior=None, true_state=None, n_std=3, rebit_axes=REBIT_AXES, true_size=250, legend=True, level=0.95, region_est_method='cov' ): """ Plots posterior distributions over rebits, including covariance ellipsoids :param qinfer.smc.SMCUpdater updater: Posterior distribution over rebits. :param qinfer.tomography.DensityOperatorDistribution: Prior distribution over rebit states. :param np.ndarray true_state: Model parameters for "true" state to plot as comparison. :param float n_std: Number of standard deviations out from the mean at which to draw the covariance ellipse. Only used if region_est_method is ``'cov'``. :param float level: Credibility level to use for computing region estimators from convex hulls. :param list rebit_axes: List containing indices for the :math:`x` and :math:`z` axes. :param str region_est_method: Method to use to draw region estimation. Must be one of None, ``'cov'`` or ``'hull'``. """ pallette = plt.rcParams['axes.color_cycle'] plot_rebit_modelparams(updater.particle_locations, c=pallette[0], label='Posterior', s=12 * np.sqrt(updater.particle_weights * len(updater.particle_weights)), rebit_axes=rebit_axes, zorder=-10 ) plot_rebit_modelparams(true_state, c=pallette[1], label='True', marker='*', s=true_size, rebit_axes=rebit_axes ) if prior is not None: plot_rebit_modelparams( prior._basis.state_to_modelparams(prior._mean)[None, :], edgecolors=pallette[3], s=250, facecolors='none', linewidth=3, label='Prior Mean', rebit_axes=rebit_axes ) plot_rebit_modelparams( updater.est_mean()[None, :], edgecolors=pallette[2], s=250, facecolors='none', linewidth=3, label='Posterior Mean', rebit_axes=rebit_axes ) if region_est_method == 'cov': # Multiplying by sqrt{2} to rescale to Bloch ball. cov = 2 * updater.est_covariance_mtx() # Use fancy indexing to cut out all but the desired submatrix. cov = cov[rebit_axes, :][:, rebit_axes] plot_cov_ellipse( cov, updater.est_mean()[rebit_axes] * np.sqrt(2), nstd=n_std, edgecolor='k', fill=True, lw=2, facecolor=pallette[0], alpha=0.4, zorder=-9, label='Posterior Cov Ellipse ($Z = {}$)'.format(n_std) ) elif region_est_method == 'hull': # Find the convex hull from the updater, projected # on the rebit axes. faces, vertices = updater.region_est_hull(level, modelparam_slice=rebit_axes) polygon = Polygon(vertices * np.sqrt(2), facecolor=pallette[0], alpha=0.4, zorder=-9, label=r'Credible Region ($\alpha = {}$)'.format(level), edgecolor='k', lw=2, fill=True ) # TODO: consolidate add_patch code with that above. plt.gca().add_patch(polygon) plot_decorate_rebits(updater.model.base_model._basis, rebit_axes=rebit_axes ) if legend: plt.legend(loc='lower left', ncol=4, scatterpoints=1)
python
def plot_rebit_posterior(updater, prior=None, true_state=None, n_std=3, rebit_axes=REBIT_AXES, true_size=250, legend=True, level=0.95, region_est_method='cov' ): pallette = plt.rcParams['axes.color_cycle'] plot_rebit_modelparams(updater.particle_locations, c=pallette[0], label='Posterior', s=12 * np.sqrt(updater.particle_weights * len(updater.particle_weights)), rebit_axes=rebit_axes, zorder=-10 ) plot_rebit_modelparams(true_state, c=pallette[1], label='True', marker='*', s=true_size, rebit_axes=rebit_axes ) if prior is not None: plot_rebit_modelparams( prior._basis.state_to_modelparams(prior._mean)[None, :], edgecolors=pallette[3], s=250, facecolors='none', linewidth=3, label='Prior Mean', rebit_axes=rebit_axes ) plot_rebit_modelparams( updater.est_mean()[None, :], edgecolors=pallette[2], s=250, facecolors='none', linewidth=3, label='Posterior Mean', rebit_axes=rebit_axes ) if region_est_method == 'cov': # Multiplying by sqrt{2} to rescale to Bloch ball. cov = 2 * updater.est_covariance_mtx() # Use fancy indexing to cut out all but the desired submatrix. cov = cov[rebit_axes, :][:, rebit_axes] plot_cov_ellipse( cov, updater.est_mean()[rebit_axes] * np.sqrt(2), nstd=n_std, edgecolor='k', fill=True, lw=2, facecolor=pallette[0], alpha=0.4, zorder=-9, label='Posterior Cov Ellipse ($Z = {}$)'.format(n_std) ) elif region_est_method == 'hull': # Find the convex hull from the updater, projected # on the rebit axes. faces, vertices = updater.region_est_hull(level, modelparam_slice=rebit_axes) polygon = Polygon(vertices * np.sqrt(2), facecolor=pallette[0], alpha=0.4, zorder=-9, label=r'Credible Region ($\alpha = {}$)'.format(level), edgecolor='k', lw=2, fill=True ) # TODO: consolidate add_patch code with that above. plt.gca().add_patch(polygon) plot_decorate_rebits(updater.model.base_model._basis, rebit_axes=rebit_axes ) if legend: plt.legend(loc='lower left', ncol=4, scatterpoints=1)
[ "def", "plot_rebit_posterior", "(", "updater", ",", "prior", "=", "None", ",", "true_state", "=", "None", ",", "n_std", "=", "3", ",", "rebit_axes", "=", "REBIT_AXES", ",", "true_size", "=", "250", ",", "legend", "=", "True", ",", "level", "=", "0.95", ...
Plots posterior distributions over rebits, including covariance ellipsoids :param qinfer.smc.SMCUpdater updater: Posterior distribution over rebits. :param qinfer.tomography.DensityOperatorDistribution: Prior distribution over rebit states. :param np.ndarray true_state: Model parameters for "true" state to plot as comparison. :param float n_std: Number of standard deviations out from the mean at which to draw the covariance ellipse. Only used if region_est_method is ``'cov'``. :param float level: Credibility level to use for computing region estimators from convex hulls. :param list rebit_axes: List containing indices for the :math:`x` and :math:`z` axes. :param str region_est_method: Method to use to draw region estimation. Must be one of None, ``'cov'`` or ``'hull'``.
[ "Plots", "posterior", "distributions", "over", "rebits", "including", "covariance", "ellipsoids" ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/plotting_tools.py#L205-L291
22,808
QInfer/python-qinfer
src/qinfer/simple_est.py
data_to_params
def data_to_params(data, expparams_dtype, col_outcomes=(0, 'counts'), cols_expparams=None ): """ Given data as a NumPy array, separates out each column either as the outcomes, or as a field of an expparams array. Columns may be specified either as indices into a two-axis scalar array, or as field names for a one-axis record array. Since scalar arrays are homogenous in type, this may result in loss of precision due to casting between data types. """ BY_IDX, BY_NAME = range(2) is_exp_scalar = np.issctype(expparams_dtype) is_data_scalar = np.issctype(data.dtype) and not data.dtype.fields s_ = ( (lambda idx: np.s_[..., idx[BY_IDX]]) if is_data_scalar else (lambda idx: np.s_[idx[BY_NAME]]) ) outcomes = data[s_(col_outcomes)].astype(int) # mk new slicer t expparams = np.empty(outcomes.shape, dtype=expparams_dtype) if is_exp_scalar: expparams[:] = data[s_(cols_expparams)] else: for expparams_key, column in cols_expparams.items(): expparams[expparams_key] = data[s_(column)] return outcomes, expparams
python
def data_to_params(data, expparams_dtype, col_outcomes=(0, 'counts'), cols_expparams=None ): BY_IDX, BY_NAME = range(2) is_exp_scalar = np.issctype(expparams_dtype) is_data_scalar = np.issctype(data.dtype) and not data.dtype.fields s_ = ( (lambda idx: np.s_[..., idx[BY_IDX]]) if is_data_scalar else (lambda idx: np.s_[idx[BY_NAME]]) ) outcomes = data[s_(col_outcomes)].astype(int) # mk new slicer t expparams = np.empty(outcomes.shape, dtype=expparams_dtype) if is_exp_scalar: expparams[:] = data[s_(cols_expparams)] else: for expparams_key, column in cols_expparams.items(): expparams[expparams_key] = data[s_(column)] return outcomes, expparams
[ "def", "data_to_params", "(", "data", ",", "expparams_dtype", ",", "col_outcomes", "=", "(", "0", ",", "'counts'", ")", ",", "cols_expparams", "=", "None", ")", ":", "BY_IDX", ",", "BY_NAME", "=", "range", "(", "2", ")", "is_exp_scalar", "=", "np", ".", ...
Given data as a NumPy array, separates out each column either as the outcomes, or as a field of an expparams array. Columns may be specified either as indices into a two-axis scalar array, or as field names for a one-axis record array. Since scalar arrays are homogenous in type, this may result in loss of precision due to casting between data types.
[ "Given", "data", "as", "a", "NumPy", "array", "separates", "out", "each", "column", "either", "as", "the", "outcomes", "or", "as", "a", "field", "of", "an", "expparams", "array", ".", "Columns", "may", "be", "specified", "either", "as", "indices", "into", ...
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/simple_est.py#L70-L106
22,809
QInfer/python-qinfer
src/qinfer/tomography/models.py
TomographyModel.canonicalize
def canonicalize(self, modelparams): """ Truncates negative eigenvalues and from each state represented by a tensor of model parameter vectors, and renormalizes as appropriate. :param np.ndarray modelparams: Array of shape ``(n_states, dim**2)`` containing model parameter representations of each of ``n_states`` different states. :return: The same model parameter tensor with all states truncated to be positive operators. If :attr:`~TomographyModel.allow_subnormalized` is `False`, all states are also renormalized to trace one. """ modelparams = np.apply_along_axis(self.trunc_neg_eigs, 1, modelparams) # Renormalizes particles if allow_subnormalized=False. if not self._allow_subnormalied: modelparams = self.renormalize(modelparams) return modelparams
python
def canonicalize(self, modelparams): modelparams = np.apply_along_axis(self.trunc_neg_eigs, 1, modelparams) # Renormalizes particles if allow_subnormalized=False. if not self._allow_subnormalied: modelparams = self.renormalize(modelparams) return modelparams
[ "def", "canonicalize", "(", "self", ",", "modelparams", ")", ":", "modelparams", "=", "np", ".", "apply_along_axis", "(", "self", ".", "trunc_neg_eigs", ",", "1", ",", "modelparams", ")", "# Renormalizes particles if allow_subnormalized=False.", "if", "not", "self",...
Truncates negative eigenvalues and from each state represented by a tensor of model parameter vectors, and renormalizes as appropriate. :param np.ndarray modelparams: Array of shape ``(n_states, dim**2)`` containing model parameter representations of each of ``n_states`` different states. :return: The same model parameter tensor with all states truncated to be positive operators. If :attr:`~TomographyModel.allow_subnormalized` is `False`, all states are also renormalized to trace one.
[ "Truncates", "negative", "eigenvalues", "and", "from", "each", "state", "represented", "by", "a", "tensor", "of", "model", "parameter", "vectors", "and", "renormalizes", "as", "appropriate", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/models.py#L149-L170
22,810
QInfer/python-qinfer
src/qinfer/tomography/models.py
TomographyModel.trunc_neg_eigs
def trunc_neg_eigs(self, particle): """ Given a state represented as a model parameter vector, returns a model parameter vector representing the same state with any negative eigenvalues set to zero. :param np.ndarray particle: Vector of length ``(dim ** 2, )`` representing a state. :return: The same state with any negative eigenvalues set to zero. """ arr = np.tensordot(particle, self._basis.data.conj(), 1) w, v = np.linalg.eig(arr) if np.all(w >= 0): return particle else: w[w < 0] = 0 new_arr = np.dot(v * w, v.conj().T) new_particle = np.real(np.dot(self._basis.flat(), new_arr.flatten())) assert new_particle[0] > 0 return new_particle
python
def trunc_neg_eigs(self, particle): arr = np.tensordot(particle, self._basis.data.conj(), 1) w, v = np.linalg.eig(arr) if np.all(w >= 0): return particle else: w[w < 0] = 0 new_arr = np.dot(v * w, v.conj().T) new_particle = np.real(np.dot(self._basis.flat(), new_arr.flatten())) assert new_particle[0] > 0 return new_particle
[ "def", "trunc_neg_eigs", "(", "self", ",", "particle", ")", ":", "arr", "=", "np", ".", "tensordot", "(", "particle", ",", "self", ".", "_basis", ".", "data", ".", "conj", "(", ")", ",", "1", ")", "w", ",", "v", "=", "np", ".", "linalg", ".", "...
Given a state represented as a model parameter vector, returns a model parameter vector representing the same state with any negative eigenvalues set to zero. :param np.ndarray particle: Vector of length ``(dim ** 2, )`` representing a state. :return: The same state with any negative eigenvalues set to zero.
[ "Given", "a", "state", "represented", "as", "a", "model", "parameter", "vector", "returns", "a", "model", "parameter", "vector", "representing", "the", "same", "state", "with", "any", "negative", "eigenvalues", "set", "to", "zero", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/models.py#L172-L192
22,811
QInfer/python-qinfer
src/qinfer/tomography/models.py
TomographyModel.renormalize
def renormalize(self, modelparams): """ Renormalizes one or more states represented as model parameter vectors, such that each state has trace 1. :param np.ndarray modelparams: Array of shape ``(n_states, dim ** 2)`` representing one or more states as model parameter vectors. :return: The same state, normalized to trace one. """ # The 0th basis element (identity) should have # a value 1 / sqrt{dim}, since the trace of that basis # element is fixed to be sqrt{dim} by convention. norm = modelparams[:, 0] * np.sqrt(self._dim) assert not np.sum(norm == 0) return modelparams / norm[:, None]
python
def renormalize(self, modelparams): # The 0th basis element (identity) should have # a value 1 / sqrt{dim}, since the trace of that basis # element is fixed to be sqrt{dim} by convention. norm = modelparams[:, 0] * np.sqrt(self._dim) assert not np.sum(norm == 0) return modelparams / norm[:, None]
[ "def", "renormalize", "(", "self", ",", "modelparams", ")", ":", "# The 0th basis element (identity) should have", "# a value 1 / sqrt{dim}, since the trace of that basis", "# element is fixed to be sqrt{dim} by convention.", "norm", "=", "modelparams", "[", ":", ",", "0", "]", ...
Renormalizes one or more states represented as model parameter vectors, such that each state has trace 1. :param np.ndarray modelparams: Array of shape ``(n_states, dim ** 2)`` representing one or more states as model parameter vectors. :return: The same state, normalized to trace one.
[ "Renormalizes", "one", "or", "more", "states", "represented", "as", "model", "parameter", "vectors", "such", "that", "each", "state", "has", "trace", "1", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/models.py#L194-L209
22,812
QInfer/python-qinfer
src/qinfer/domains.py
ProductDomain.values
def values(self): """ Returns an `np.array` of type `dtype` containing some values from the domain. For domains where `is_finite` is ``True``, all elements of the domain will be yielded exactly once. :rtype: `np.ndarray` """ separate_values = [domain.values for domain in self._domains] return np.concatenate([ join_struct_arrays(list(map(np.array, value))) for value in product(*separate_values) ])
python
def values(self): separate_values = [domain.values for domain in self._domains] return np.concatenate([ join_struct_arrays(list(map(np.array, value))) for value in product(*separate_values) ])
[ "def", "values", "(", "self", ")", ":", "separate_values", "=", "[", "domain", ".", "values", "for", "domain", "in", "self", ".", "_domains", "]", "return", "np", ".", "concatenate", "(", "[", "join_struct_arrays", "(", "list", "(", "map", "(", "np", "...
Returns an `np.array` of type `dtype` containing some values from the domain. For domains where `is_finite` is ``True``, all elements of the domain will be yielded exactly once. :rtype: `np.ndarray`
[ "Returns", "an", "np", ".", "array", "of", "type", "dtype", "containing", "some", "values", "from", "the", "domain", ".", "For", "domains", "where", "is_finite", "is", "True", "all", "elements", "of", "the", "domain", "will", "be", "yielded", "exactly", "o...
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L238-L251
22,813
QInfer/python-qinfer
src/qinfer/domains.py
IntegerDomain.min
def min(self): """ Returns the minimum value of the domain. :rtype: `float` or `np.inf` """ return int(self._min) if not np.isinf(self._min) else self._min
python
def min(self): return int(self._min) if not np.isinf(self._min) else self._min
[ "def", "min", "(", "self", ")", ":", "return", "int", "(", "self", ".", "_min", ")", "if", "not", "np", ".", "isinf", "(", "self", ".", "_min", ")", "else", "self", ".", "_min" ]
Returns the minimum value of the domain. :rtype: `float` or `np.inf`
[ "Returns", "the", "minimum", "value", "of", "the", "domain", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L448-L454
22,814
QInfer/python-qinfer
src/qinfer/domains.py
IntegerDomain.max
def max(self): """ Returns the maximum value of the domain. :rtype: `float` or `np.inf` """ return int(self._max) if not np.isinf(self._max) else self._max
python
def max(self): return int(self._max) if not np.isinf(self._max) else self._max
[ "def", "max", "(", "self", ")", ":", "return", "int", "(", "self", ".", "_max", ")", "if", "not", "np", ".", "isinf", "(", "self", ".", "_max", ")", "else", "self", ".", "_max" ]
Returns the maximum value of the domain. :rtype: `float` or `np.inf`
[ "Returns", "the", "maximum", "value", "of", "the", "domain", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L456-L462
22,815
QInfer/python-qinfer
src/qinfer/domains.py
IntegerDomain.is_finite
def is_finite(self): """ Whether or not the domain contains a finite number of points. :type: `bool` """ return not np.isinf(self.min) and not np.isinf(self.max)
python
def is_finite(self): return not np.isinf(self.min) and not np.isinf(self.max)
[ "def", "is_finite", "(", "self", ")", ":", "return", "not", "np", ".", "isinf", "(", "self", ".", "min", ")", "and", "not", "np", ".", "isinf", "(", "self", ".", "max", ")" ]
Whether or not the domain contains a finite number of points. :type: `bool`
[ "Whether", "or", "not", "the", "domain", "contains", "a", "finite", "number", "of", "points", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L475-L481
22,816
QInfer/python-qinfer
src/qinfer/domains.py
MultinomialDomain.n_members
def n_members(self): """ Returns the number of members in the domain if it `is_finite`, otherwise, returns `None`. :type: ``int`` """ return int(binom(self.n_meas + self.n_elements -1, self.n_elements - 1))
python
def n_members(self): return int(binom(self.n_meas + self.n_elements -1, self.n_elements - 1))
[ "def", "n_members", "(", "self", ")", ":", "return", "int", "(", "binom", "(", "self", ".", "n_meas", "+", "self", ".", "n_elements", "-", "1", ",", "self", ".", "n_elements", "-", "1", ")", ")" ]
Returns the number of members in the domain if it `is_finite`, otherwise, returns `None`. :type: ``int``
[ "Returns", "the", "number", "of", "members", "in", "the", "domain", "if", "it", "is_finite", "otherwise", "returns", "None", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L619-L626
22,817
QInfer/python-qinfer
src/qinfer/domains.py
MultinomialDomain.to_regular_array
def to_regular_array(self, A): """ Converts from an array of type `self.dtype` to an array of type `int` with an additional index labeling the tuple indeces. :param np.ndarray A: An `np.array` of type `self.dtype`. :rtype: `np.ndarray` """ # this could be a static method, but we choose to be consistent with # from_regular_array return A.view((int, len(A.dtype.names))).reshape(A.shape + (-1,))
python
def to_regular_array(self, A): # this could be a static method, but we choose to be consistent with # from_regular_array return A.view((int, len(A.dtype.names))).reshape(A.shape + (-1,))
[ "def", "to_regular_array", "(", "self", ",", "A", ")", ":", "# this could be a static method, but we choose to be consistent with", "# from_regular_array", "return", "A", ".", "view", "(", "(", "int", ",", "len", "(", "A", ".", "dtype", ".", "names", ")", ")", "...
Converts from an array of type `self.dtype` to an array of type `int` with an additional index labeling the tuple indeces. :param np.ndarray A: An `np.array` of type `self.dtype`. :rtype: `np.ndarray`
[ "Converts", "from", "an", "array", "of", "type", "self", ".", "dtype", "to", "an", "array", "of", "type", "int", "with", "an", "additional", "index", "labeling", "the", "tuple", "indeces", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L661-L673
22,818
QInfer/python-qinfer
src/qinfer/domains.py
MultinomialDomain.from_regular_array
def from_regular_array(self, A): """ Converts from an array of type `int` where the last index is assumed to have length `self.n_elements` to an array of type `self.d_type` with one fewer index. :param np.ndarray A: An `np.array` of type `int`. :rtype: `np.ndarray` """ dims = A.shape[:-1] return A.reshape((np.prod(dims),-1)).view(dtype=self.dtype).squeeze(-1).reshape(dims)
python
def from_regular_array(self, A): dims = A.shape[:-1] return A.reshape((np.prod(dims),-1)).view(dtype=self.dtype).squeeze(-1).reshape(dims)
[ "def", "from_regular_array", "(", "self", ",", "A", ")", ":", "dims", "=", "A", ".", "shape", "[", ":", "-", "1", "]", "return", "A", ".", "reshape", "(", "(", "np", ".", "prod", "(", "dims", ")", ",", "-", "1", ")", ")", ".", "view", "(", ...
Converts from an array of type `int` where the last index is assumed to have length `self.n_elements` to an array of type `self.d_type` with one fewer index. :param np.ndarray A: An `np.array` of type `int`. :rtype: `np.ndarray`
[ "Converts", "from", "an", "array", "of", "type", "int", "where", "the", "last", "index", "is", "assumed", "to", "have", "length", "self", ".", "n_elements", "to", "an", "array", "of", "type", "self", ".", "d_type", "with", "one", "fewer", "index", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L675-L686
22,819
QInfer/python-qinfer
src/qinfer/ipy.py
IPythonProgressBar.start
def start(self, max): """ Displays the progress bar for a given maximum value. :param float max: Maximum value of the progress bar. """ try: self.widget.max = max display(self.widget) except: pass
python
def start(self, max): try: self.widget.max = max display(self.widget) except: pass
[ "def", "start", "(", "self", ",", "max", ")", ":", "try", ":", "self", ".", "widget", ".", "max", "=", "max", "display", "(", "self", ".", "widget", ")", "except", ":", "pass" ]
Displays the progress bar for a given maximum value. :param float max: Maximum value of the progress bar.
[ "Displays", "the", "progress", "bar", "for", "a", "given", "maximum", "value", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/ipy.py#L94-L104
22,820
QInfer/python-qinfer
src/qinfer/tomography/legacy.py
MultiQubitStatePauliModel.likelihood
def likelihood(self, outcomes, modelparams, expparams): """ Calculates the likelihood function at the states specified by modelparams and measurement specified by expparams. This is given by the Born rule and is the probability of outcomes given the state and measurement operator. """ # By calling the superclass implementation, we can consolidate # call counting there. super(MultiQubitStatePauliModel, self).likelihood(outcomes, modelparams, expparams) # Note that expparams['axis'] has shape (n_exp, 3). pr0 = 0.5*(1 + modelparams[:,expparams['pauli']]) # Use the following hack if you don't want to ensure positive weights pr0[pr0 < 0] = 0 pr0[pr0 > 1] = 1 # Note that expparams['vis'] has shape (n_exp, ). pr0 = expparams['vis'] * pr0 + (1 - expparams['vis']) * 0.5 # Now we concatenate over outcomes. return Model.pr0_to_likelihood_array(outcomes, pr0)
python
def likelihood(self, outcomes, modelparams, expparams): # By calling the superclass implementation, we can consolidate # call counting there. super(MultiQubitStatePauliModel, self).likelihood(outcomes, modelparams, expparams) # Note that expparams['axis'] has shape (n_exp, 3). pr0 = 0.5*(1 + modelparams[:,expparams['pauli']]) # Use the following hack if you don't want to ensure positive weights pr0[pr0 < 0] = 0 pr0[pr0 > 1] = 1 # Note that expparams['vis'] has shape (n_exp, ). pr0 = expparams['vis'] * pr0 + (1 - expparams['vis']) * 0.5 # Now we concatenate over outcomes. return Model.pr0_to_likelihood_array(outcomes, pr0)
[ "def", "likelihood", "(", "self", ",", "outcomes", ",", "modelparams", ",", "expparams", ")", ":", "# By calling the superclass implementation, we can consolidate", "# call counting there.", "super", "(", "MultiQubitStatePauliModel", ",", "self", ")", ".", "likelihood", "...
Calculates the likelihood function at the states specified by modelparams and measurement specified by expparams. This is given by the Born rule and is the probability of outcomes given the state and measurement operator.
[ "Calculates", "the", "likelihood", "function", "at", "the", "states", "specified", "by", "modelparams", "and", "measurement", "specified", "by", "expparams", ".", "This", "is", "given", "by", "the", "Born", "rule", "and", "is", "the", "probability", "of", "out...
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/legacy.py#L317-L341
22,821
QInfer/python-qinfer
src/qinfer/derived_models.py
BinomialModel.domain
def domain(self, expparams): """ Returns a list of ``Domain``s, one for each input expparam. :param numpy.ndarray expparams: Array of experimental parameters. This array must be of dtype agreeing with the ``expparams_dtype`` property, or, in the case where ``n_outcomes_constant`` is ``True``, ``None`` should be a valid input. :rtype: list of ``Domain`` """ return [IntegerDomain(min=0,max=n_o-1) for n_o in self.n_outcomes(expparams)]
python
def domain(self, expparams): return [IntegerDomain(min=0,max=n_o-1) for n_o in self.n_outcomes(expparams)]
[ "def", "domain", "(", "self", ",", "expparams", ")", ":", "return", "[", "IntegerDomain", "(", "min", "=", "0", ",", "max", "=", "n_o", "-", "1", ")", "for", "n_o", "in", "self", ".", "n_outcomes", "(", "expparams", ")", "]" ]
Returns a list of ``Domain``s, one for each input expparam. :param numpy.ndarray expparams: Array of experimental parameters. This array must be of dtype agreeing with the ``expparams_dtype`` property, or, in the case where ``n_outcomes_constant`` is ``True``, ``None`` should be a valid input. :rtype: list of ``Domain``
[ "Returns", "a", "list", "of", "Domain", "s", "one", "for", "each", "input", "expparam", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/derived_models.py#L287-L298
22,822
QInfer/python-qinfer
src/qinfer/derived_models.py
GaussianHyperparameterizedModel.underlying_likelihood
def underlying_likelihood(self, binary_outcomes, modelparams, expparams): """ Given outcomes hypothesized for the underlying model, returns the likelihood which which those outcomes occur. """ original_mps = modelparams[..., self._orig_mps_slice] return self.underlying_model.likelihood(binary_outcomes, original_mps, expparams)
python
def underlying_likelihood(self, binary_outcomes, modelparams, expparams): original_mps = modelparams[..., self._orig_mps_slice] return self.underlying_model.likelihood(binary_outcomes, original_mps, expparams)
[ "def", "underlying_likelihood", "(", "self", ",", "binary_outcomes", ",", "modelparams", ",", "expparams", ")", ":", "original_mps", "=", "modelparams", "[", "...", ",", "self", ".", "_orig_mps_slice", "]", "return", "self", ".", "underlying_model", ".", "likeli...
Given outcomes hypothesized for the underlying model, returns the likelihood which which those outcomes occur.
[ "Given", "outcomes", "hypothesized", "for", "the", "underlying", "model", "returns", "the", "likelihood", "which", "which", "those", "outcomes", "occur", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/derived_models.py#L443-L449
22,823
QInfer/python-qinfer
src/qinfer/abstract_model.py
Simulatable.are_expparam_dtypes_consistent
def are_expparam_dtypes_consistent(self, expparams): """ Returns ``True`` iff all of the given expparams correspond to outcome domains with the same dtype. For efficiency, concrete subclasses should override this method if the result is always ``True``. :param np.ndarray expparams: Array of expparamms of type ``expparams_dtype`` :rtype: ``bool`` """ if self.is_n_outcomes_constant: # This implies that all domains are equal, so this must be true return True # otherwise we have to actually check all the dtypes if expparams.size > 0: domains = self.domain(expparams) first_dtype = domains[0].dtype return all(domain.dtype == first_dtype for domain in domains[1:]) else: return True
python
def are_expparam_dtypes_consistent(self, expparams): if self.is_n_outcomes_constant: # This implies that all domains are equal, so this must be true return True # otherwise we have to actually check all the dtypes if expparams.size > 0: domains = self.domain(expparams) first_dtype = domains[0].dtype return all(domain.dtype == first_dtype for domain in domains[1:]) else: return True
[ "def", "are_expparam_dtypes_consistent", "(", "self", ",", "expparams", ")", ":", "if", "self", ".", "is_n_outcomes_constant", ":", "# This implies that all domains are equal, so this must be true", "return", "True", "# otherwise we have to actually check all the dtypes", "if", "...
Returns ``True`` iff all of the given expparams correspond to outcome domains with the same dtype. For efficiency, concrete subclasses should override this method if the result is always ``True``. :param np.ndarray expparams: Array of expparamms of type ``expparams_dtype`` :rtype: ``bool``
[ "Returns", "True", "iff", "all", "of", "the", "given", "expparams", "correspond", "to", "outcome", "domains", "with", "the", "same", "dtype", ".", "For", "efficiency", "concrete", "subclasses", "should", "override", "this", "method", "if", "the", "result", "is...
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L218-L239
22,824
QInfer/python-qinfer
src/qinfer/abstract_model.py
Simulatable.simulate_experiment
def simulate_experiment(self, modelparams, expparams, repeat=1): """ Produces data according to the given model parameters and experimental parameters, structured as a NumPy array. :param np.ndarray modelparams: A shape ``(n_models, n_modelparams)`` array of model parameter vectors describing the hypotheses under which data should be simulated. :param np.ndarray expparams: A shape ``(n_experiments, )`` array of experimental control settings, with ``dtype`` given by :attr:`~qinfer.Model.expparams_dtype`, describing the experiments whose outcomes should be simulated. :param int repeat: How many times the specified experiment should be repeated. :rtype: np.ndarray :return: A three-index tensor ``data[i, j, k]``, where ``i`` is the repetition, ``j`` indexes which vector of model parameters was used, and where ``k`` indexes which experimental parameters where used. If ``repeat == 1``, ``len(modelparams) == 1`` and ``len(expparams) == 1``, then a scalar datum is returned instead. """ self._sim_count += modelparams.shape[0] * expparams.shape[0] * repeat assert(self.are_expparam_dtypes_consistent(expparams))
python
def simulate_experiment(self, modelparams, expparams, repeat=1): self._sim_count += modelparams.shape[0] * expparams.shape[0] * repeat assert(self.are_expparam_dtypes_consistent(expparams))
[ "def", "simulate_experiment", "(", "self", ",", "modelparams", ",", "expparams", ",", "repeat", "=", "1", ")", ":", "self", ".", "_sim_count", "+=", "modelparams", ".", "shape", "[", "0", "]", "*", "expparams", ".", "shape", "[", "0", "]", "*", "repeat...
Produces data according to the given model parameters and experimental parameters, structured as a NumPy array. :param np.ndarray modelparams: A shape ``(n_models, n_modelparams)`` array of model parameter vectors describing the hypotheses under which data should be simulated. :param np.ndarray expparams: A shape ``(n_experiments, )`` array of experimental control settings, with ``dtype`` given by :attr:`~qinfer.Model.expparams_dtype`, describing the experiments whose outcomes should be simulated. :param int repeat: How many times the specified experiment should be repeated. :rtype: np.ndarray :return: A three-index tensor ``data[i, j, k]``, where ``i`` is the repetition, ``j`` indexes which vector of model parameters was used, and where ``k`` indexes which experimental parameters where used. If ``repeat == 1``, ``len(modelparams) == 1`` and ``len(expparams) == 1``, then a scalar datum is returned instead.
[ "Produces", "data", "according", "to", "the", "given", "model", "parameters", "and", "experimental", "parameters", "structured", "as", "a", "NumPy", "array", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L284-L307
22,825
QInfer/python-qinfer
src/qinfer/abstract_model.py
Model.likelihood
def likelihood(self, outcomes, modelparams, expparams): r""" Calculates the probability of each given outcome, conditioned on each given model parameter vector and each given experimental control setting. :param np.ndarray modelparams: A shape ``(n_models, n_modelparams)`` array of model parameter vectors describing the hypotheses for which the likelihood function is to be calculated. :param np.ndarray expparams: A shape ``(n_experiments, )`` array of experimental control settings, with ``dtype`` given by :attr:`~qinfer.Simulatable.expparams_dtype`, describing the experiments from which the given outcomes were drawn. :rtype: np.ndarray :return: A three-index tensor ``L[i, j, k]``, where ``i`` is the outcome being considered, ``j`` indexes which vector of model parameters was used, and where ``k`` indexes which experimental parameters where used. Each element ``L[i, j, k]`` then corresponds to the likelihood :math:`\Pr(d_i | \vec{x}_j; e_k)`. """ # Count the number of times the inner-most loop is called. self._call_count += ( safe_shape(outcomes) * safe_shape(modelparams) * safe_shape(expparams) )
python
def likelihood(self, outcomes, modelparams, expparams): r""" Calculates the probability of each given outcome, conditioned on each given model parameter vector and each given experimental control setting. :param np.ndarray modelparams: A shape ``(n_models, n_modelparams)`` array of model parameter vectors describing the hypotheses for which the likelihood function is to be calculated. :param np.ndarray expparams: A shape ``(n_experiments, )`` array of experimental control settings, with ``dtype`` given by :attr:`~qinfer.Simulatable.expparams_dtype`, describing the experiments from which the given outcomes were drawn. :rtype: np.ndarray :return: A three-index tensor ``L[i, j, k]``, where ``i`` is the outcome being considered, ``j`` indexes which vector of model parameters was used, and where ``k`` indexes which experimental parameters where used. Each element ``L[i, j, k]`` then corresponds to the likelihood :math:`\Pr(d_i | \vec{x}_j; e_k)`. """ # Count the number of times the inner-most loop is called. self._call_count += ( safe_shape(outcomes) * safe_shape(modelparams) * safe_shape(expparams) )
[ "def", "likelihood", "(", "self", ",", "outcomes", ",", "modelparams", ",", "expparams", ")", ":", "# Count the number of times the inner-most loop is called.", "self", ".", "_call_count", "+=", "(", "safe_shape", "(", "outcomes", ")", "*", "safe_shape", "(", "model...
r""" Calculates the probability of each given outcome, conditioned on each given model parameter vector and each given experimental control setting. :param np.ndarray modelparams: A shape ``(n_models, n_modelparams)`` array of model parameter vectors describing the hypotheses for which the likelihood function is to be calculated. :param np.ndarray expparams: A shape ``(n_experiments, )`` array of experimental control settings, with ``dtype`` given by :attr:`~qinfer.Simulatable.expparams_dtype`, describing the experiments from which the given outcomes were drawn. :rtype: np.ndarray :return: A three-index tensor ``L[i, j, k]``, where ``i`` is the outcome being considered, ``j`` indexes which vector of model parameters was used, and where ``k`` indexes which experimental parameters where used. Each element ``L[i, j, k]`` then corresponds to the likelihood :math:`\Pr(d_i | \vec{x}_j; e_k)`.
[ "r", "Calculates", "the", "probability", "of", "each", "given", "outcome", "conditioned", "on", "each", "given", "model", "parameter", "vector", "and", "each", "given", "experimental", "control", "setting", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L444-L468
22,826
QInfer/python-qinfer
src/qinfer/utils.py
get_qutip_module
def get_qutip_module(required_version='3.2'): """ Attempts to return the qutip module, but silently returns ``None`` if it can't be imported, or doesn't have version at least ``required_version``. :param str required_version: Valid input to ``distutils.version.LooseVersion``. :return: The qutip module or ``None``. :rtype: ``module`` or ``NoneType`` """ try: import qutip as qt from distutils.version import LooseVersion _qt_version = LooseVersion(qt.version.version) if _qt_version < LooseVersion(required_version): return None except ImportError: return None return qt
python
def get_qutip_module(required_version='3.2'): try: import qutip as qt from distutils.version import LooseVersion _qt_version = LooseVersion(qt.version.version) if _qt_version < LooseVersion(required_version): return None except ImportError: return None return qt
[ "def", "get_qutip_module", "(", "required_version", "=", "'3.2'", ")", ":", "try", ":", "import", "qutip", "as", "qt", "from", "distutils", ".", "version", "import", "LooseVersion", "_qt_version", "=", "LooseVersion", "(", "qt", ".", "version", ".", "version",...
Attempts to return the qutip module, but silently returns ``None`` if it can't be imported, or doesn't have version at least ``required_version``. :param str required_version: Valid input to ``distutils.version.LooseVersion``. :return: The qutip module or ``None``. :rtype: ``module`` or ``NoneType``
[ "Attempts", "to", "return", "the", "qutip", "module", "but", "silently", "returns", "None", "if", "it", "can", "t", "be", "imported", "or", "doesn", "t", "have", "version", "at", "least", "required_version", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L64-L85
22,827
QInfer/python-qinfer
src/qinfer/utils.py
particle_covariance_mtx
def particle_covariance_mtx(weights,locations): """ Returns an estimate of the covariance of a distribution represented by a given set of SMC particle. :param weights: An array containing the weights of each particle. :param location: An array containing the locations of each particle. :rtype: :class:`numpy.ndarray`, shape ``(n_modelparams, n_modelparams)``. :returns: An array containing the estimated covariance matrix. """ # TODO: add shapes to docstring. warnings.warn('particle_covariance_mtx is deprecated, please use distributions.ParticleDistribution', DeprecationWarning) # Find the mean model vector, shape (n_modelparams, ). mu = particle_meanfn(weights, locations) # Transpose the particle locations to have shape # (n_modelparams, n_particles). xs = locations.transpose([1, 0]) # Give a shorter name to the particle weights, shape (n_particles, ). ws = weights cov = ( # This sum is a reduction over the particle index, chosen to be # axis=2. Thus, the sum represents an expectation value over the # outer product $x . x^T$. # # All three factors have the particle index as the rightmost # index, axis=2. Using the Einstein summation convention (ESC), # we can reduce over the particle index easily while leaving # the model parameter index to vary between the two factors # of xs. # # This corresponds to evaluating A_{m,n} = w_{i} x_{m,i} x_{n,i} # using the ESC, where A_{m,n} is the temporary array created. np.einsum('i,mi,ni', ws, xs, xs) # We finish by subracting from the above expectation value # the outer product $mu . mu^T$. - np.dot(mu[..., np.newaxis], mu[np.newaxis, ...]) ) # The SMC approximation is not guaranteed to produce a # positive-semidefinite covariance matrix. If a negative eigenvalue # is produced, we should warn the caller of this. assert np.all(np.isfinite(cov)) if not np.all(la.eig(cov)[0] >= 0): warnings.warn('Numerical error in covariance estimation causing positive semidefinite violation.', ApproximationWarning) return cov
python
def particle_covariance_mtx(weights,locations): # TODO: add shapes to docstring. warnings.warn('particle_covariance_mtx is deprecated, please use distributions.ParticleDistribution', DeprecationWarning) # Find the mean model vector, shape (n_modelparams, ). mu = particle_meanfn(weights, locations) # Transpose the particle locations to have shape # (n_modelparams, n_particles). xs = locations.transpose([1, 0]) # Give a shorter name to the particle weights, shape (n_particles, ). ws = weights cov = ( # This sum is a reduction over the particle index, chosen to be # axis=2. Thus, the sum represents an expectation value over the # outer product $x . x^T$. # # All three factors have the particle index as the rightmost # index, axis=2. Using the Einstein summation convention (ESC), # we can reduce over the particle index easily while leaving # the model parameter index to vary between the two factors # of xs. # # This corresponds to evaluating A_{m,n} = w_{i} x_{m,i} x_{n,i} # using the ESC, where A_{m,n} is the temporary array created. np.einsum('i,mi,ni', ws, xs, xs) # We finish by subracting from the above expectation value # the outer product $mu . mu^T$. - np.dot(mu[..., np.newaxis], mu[np.newaxis, ...]) ) # The SMC approximation is not guaranteed to produce a # positive-semidefinite covariance matrix. If a negative eigenvalue # is produced, we should warn the caller of this. assert np.all(np.isfinite(cov)) if not np.all(la.eig(cov)[0] >= 0): warnings.warn('Numerical error in covariance estimation causing positive semidefinite violation.', ApproximationWarning) return cov
[ "def", "particle_covariance_mtx", "(", "weights", ",", "locations", ")", ":", "# TODO: add shapes to docstring.", "warnings", ".", "warn", "(", "'particle_covariance_mtx is deprecated, please use distributions.ParticleDistribution'", ",", "DeprecationWarning", ")", "# Find the mean...
Returns an estimate of the covariance of a distribution represented by a given set of SMC particle. :param weights: An array containing the weights of each particle. :param location: An array containing the locations of each particle. :rtype: :class:`numpy.ndarray`, shape ``(n_modelparams, n_modelparams)``. :returns: An array containing the estimated covariance matrix.
[ "Returns", "an", "estimate", "of", "the", "covariance", "of", "a", "distribution", "represented", "by", "a", "given", "set", "of", "SMC", "particle", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L235-L287
22,828
QInfer/python-qinfer
src/qinfer/utils.py
ellipsoid_volume
def ellipsoid_volume(A=None, invA=None): """ Returns the volume of an ellipsoid given either its matrix or the inverse of its matrix. """ if invA is None and A is None: raise ValueError("Must pass either inverse(A) or A.") if invA is None and A is not None: invA = la.inv(A) # Find the unit sphere volume. # http://en.wikipedia.org/wiki/Unit_sphere#General_area_and_volume_formulas n = invA.shape[0] Vn = (np.pi ** (n/2)) / gamma(1 + (n/2)) return Vn * la.det(sqrtm(invA))
python
def ellipsoid_volume(A=None, invA=None): if invA is None and A is None: raise ValueError("Must pass either inverse(A) or A.") if invA is None and A is not None: invA = la.inv(A) # Find the unit sphere volume. # http://en.wikipedia.org/wiki/Unit_sphere#General_area_and_volume_formulas n = invA.shape[0] Vn = (np.pi ** (n/2)) / gamma(1 + (n/2)) return Vn * la.det(sqrtm(invA))
[ "def", "ellipsoid_volume", "(", "A", "=", "None", ",", "invA", "=", "None", ")", ":", "if", "invA", "is", "None", "and", "A", "is", "None", ":", "raise", "ValueError", "(", "\"Must pass either inverse(A) or A.\"", ")", "if", "invA", "is", "None", "and", ...
Returns the volume of an ellipsoid given either its matrix or the inverse of its matrix.
[ "Returns", "the", "volume", "of", "an", "ellipsoid", "given", "either", "its", "matrix", "or", "the", "inverse", "of", "its", "matrix", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L290-L307
22,829
QInfer/python-qinfer
src/qinfer/utils.py
in_ellipsoid
def in_ellipsoid(x, A, c): """ Determines which of the points ``x`` are in the closed ellipsoid with shape matrix ``A`` centered at ``c``. For a single point ``x``, this is computed as .. math:: (c-x)^T\cdot A^{-1}\cdot (c-x) \leq 1 :param np.ndarray x: Shape ``(n_points, dim)`` or ``n_points``. :param np.ndarray A: Shape ``(dim, dim)``, positive definite :param np.ndarray c: Shape ``(dim)`` :return: `bool` or array of bools of length ``n_points`` """ if x.ndim == 1: y = c - x return np.einsum('j,jl,l', y, np.linalg.inv(A), y) <= 1 else: y = c[np.newaxis,:] - x return np.einsum('ij,jl,il->i', y, np.linalg.inv(A), y) <= 1
python
def in_ellipsoid(x, A, c): if x.ndim == 1: y = c - x return np.einsum('j,jl,l', y, np.linalg.inv(A), y) <= 1 else: y = c[np.newaxis,:] - x return np.einsum('ij,jl,il->i', y, np.linalg.inv(A), y) <= 1
[ "def", "in_ellipsoid", "(", "x", ",", "A", ",", "c", ")", ":", "if", "x", ".", "ndim", "==", "1", ":", "y", "=", "c", "-", "x", "return", "np", ".", "einsum", "(", "'j,jl,l'", ",", "y", ",", "np", ".", "linalg", ".", "inv", "(", "A", ")", ...
Determines which of the points ``x`` are in the closed ellipsoid with shape matrix ``A`` centered at ``c``. For a single point ``x``, this is computed as .. math:: (c-x)^T\cdot A^{-1}\cdot (c-x) \leq 1 :param np.ndarray x: Shape ``(n_points, dim)`` or ``n_points``. :param np.ndarray A: Shape ``(dim, dim)``, positive definite :param np.ndarray c: Shape ``(dim)`` :return: `bool` or array of bools of length ``n_points``
[ "Determines", "which", "of", "the", "points", "x", "are", "in", "the", "closed", "ellipsoid", "with", "shape", "matrix", "A", "centered", "at", "c", ".", "For", "a", "single", "point", "x", "this", "is", "computed", "as" ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L355-L374
22,830
QInfer/python-qinfer
src/qinfer/utils.py
assert_sigfigs_equal
def assert_sigfigs_equal(x, y, sigfigs=3): """ Tests if all elements in x and y agree up to a certain number of significant figures. :param np.ndarray x: Array of numbers. :param np.ndarray y: Array of numbers you want to be equal to ``x``. :param int sigfigs: How many significant figures you demand that they share. Default is 3. """ # determine which power of 10 best describes x xpow = np.floor(np.log10(x)) # now rescale 1 \leq x < 9 x = x * 10**(- xpow) # scale y by the same amount y = y * 10**(- xpow) # now test if abs(x-y) < 0.5 * 10**(-sigfigs) assert_almost_equal(x, y, sigfigs)
python
def assert_sigfigs_equal(x, y, sigfigs=3): # determine which power of 10 best describes x xpow = np.floor(np.log10(x)) # now rescale 1 \leq x < 9 x = x * 10**(- xpow) # scale y by the same amount y = y * 10**(- xpow) # now test if abs(x-y) < 0.5 * 10**(-sigfigs) assert_almost_equal(x, y, sigfigs)
[ "def", "assert_sigfigs_equal", "(", "x", ",", "y", ",", "sigfigs", "=", "3", ")", ":", "# determine which power of 10 best describes x", "xpow", "=", "np", ".", "floor", "(", "np", ".", "log10", "(", "x", ")", ")", "# now rescale 1 \\leq x < 9", "x", "=", "x...
Tests if all elements in x and y agree up to a certain number of significant figures. :param np.ndarray x: Array of numbers. :param np.ndarray y: Array of numbers you want to be equal to ``x``. :param int sigfigs: How many significant figures you demand that they share. Default is 3.
[ "Tests", "if", "all", "elements", "in", "x", "and", "y", "agree", "up", "to", "a", "certain", "number", "of", "significant", "figures", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L385-L406
22,831
QInfer/python-qinfer
src/qinfer/utils.py
format_uncertainty
def format_uncertainty(value, uncertianty, scinotn_break=4): """ Given a value and its uncertianty, format as a LaTeX string for pretty-printing. :param int scinotn_break: How many decimal points to print before breaking into scientific notation. """ if uncertianty == 0: # Return the exact number, without the ± annotation as a fixed point # number, since all digits matter. # FIXME: this assumes a precision of 6; need to select that dynamically. return "{0:f}".format(value) else: # Return a string of the form "0.00 \pm 0.01". mag_unc = int(np.log10(np.abs(uncertianty))) # Zero should be printed as a single digit; that is, as wide as str "1". mag_val = int(np.log10(np.abs(value))) if value != 0 else 0 n_digits = max(mag_val - mag_unc, 0) if abs(mag_val) < abs(mag_unc) and abs(mag_unc) > scinotn_break: # We're formatting something close to zero, so recale uncertianty # accordingly. scale = 10**mag_unc return r"({{0:0.{0}f}} \pm {{1:0.{0}f}}) \times 10^{{2}}".format( n_digits ).format( value / scale, uncertianty / scale, mag_unc ) if abs(mag_val) <= scinotn_break: return r"{{0:0.{n_digits}f}} \pm {{1:0.{n_digits}f}}".format(n_digits=n_digits).format(value, uncertianty) else: scale = 10**mag_val return r"({{0:0.{0}f}} \pm {{1:0.{0}f}}) \times 10^{{2}}".format( n_digits ).format( value / scale, uncertianty / scale, mag_val )
python
def format_uncertainty(value, uncertianty, scinotn_break=4): if uncertianty == 0: # Return the exact number, without the ± annotation as a fixed point # number, since all digits matter. # FIXME: this assumes a precision of 6; need to select that dynamically. return "{0:f}".format(value) else: # Return a string of the form "0.00 \pm 0.01". mag_unc = int(np.log10(np.abs(uncertianty))) # Zero should be printed as a single digit; that is, as wide as str "1". mag_val = int(np.log10(np.abs(value))) if value != 0 else 0 n_digits = max(mag_val - mag_unc, 0) if abs(mag_val) < abs(mag_unc) and abs(mag_unc) > scinotn_break: # We're formatting something close to zero, so recale uncertianty # accordingly. scale = 10**mag_unc return r"({{0:0.{0}f}} \pm {{1:0.{0}f}}) \times 10^{{2}}".format( n_digits ).format( value / scale, uncertianty / scale, mag_unc ) if abs(mag_val) <= scinotn_break: return r"{{0:0.{n_digits}f}} \pm {{1:0.{n_digits}f}}".format(n_digits=n_digits).format(value, uncertianty) else: scale = 10**mag_val return r"({{0:0.{0}f}} \pm {{1:0.{0}f}}) \times 10^{{2}}".format( n_digits ).format( value / scale, uncertianty / scale, mag_val )
[ "def", "format_uncertainty", "(", "value", ",", "uncertianty", ",", "scinotn_break", "=", "4", ")", ":", "if", "uncertianty", "==", "0", ":", "# Return the exact number, without the ± annotation as a fixed point", "# number, since all digits matter.", "# FIXME: this assumes a p...
Given a value and its uncertianty, format as a LaTeX string for pretty-printing. :param int scinotn_break: How many decimal points to print before breaking into scientific notation.
[ "Given", "a", "value", "and", "its", "uncertianty", "format", "as", "a", "LaTeX", "string", "for", "pretty", "-", "printing", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L408-L450
22,832
QInfer/python-qinfer
src/qinfer/utils.py
from_simplex
def from_simplex(x): r""" Inteprets the last index of x as unit simplices and returns a real array of the sampe shape in logit space. Inverse to :func:`to_simplex` ; see that function for more details. :param np.ndarray: Array of unit simplices along the last index. :rtype: ``np.ndarray`` """ n = x.shape[-1] # z are the stick breaking fractions in [0,1] # the last one is always 1, so don't worry about it z = np.empty(shape=x.shape) z[..., 0] = x[..., 0] z[..., 1:-1] = x[..., 1:-1] / (1 - x[..., :-2].cumsum(axis=-1)) # now z are the logit-transformed breaking fractions z[..., :-1] = logit(z[..., :-1]) - logit(1 / (n - np.arange(n-1, dtype=np.float))) # set this to 0 manually to avoid subtracting inf-inf z[..., -1] = 0 return z
python
def from_simplex(x): r""" Inteprets the last index of x as unit simplices and returns a real array of the sampe shape in logit space. Inverse to :func:`to_simplex` ; see that function for more details. :param np.ndarray: Array of unit simplices along the last index. :rtype: ``np.ndarray`` """ n = x.shape[-1] # z are the stick breaking fractions in [0,1] # the last one is always 1, so don't worry about it z = np.empty(shape=x.shape) z[..., 0] = x[..., 0] z[..., 1:-1] = x[..., 1:-1] / (1 - x[..., :-2].cumsum(axis=-1)) # now z are the logit-transformed breaking fractions z[..., :-1] = logit(z[..., :-1]) - logit(1 / (n - np.arange(n-1, dtype=np.float))) # set this to 0 manually to avoid subtracting inf-inf z[..., -1] = 0 return z
[ "def", "from_simplex", "(", "x", ")", ":", "n", "=", "x", ".", "shape", "[", "-", "1", "]", "# z are the stick breaking fractions in [0,1]", "# the last one is always 1, so don't worry about it", "z", "=", "np", ".", "empty", "(", "shape", "=", "x", ".", "shape"...
r""" Inteprets the last index of x as unit simplices and returns a real array of the sampe shape in logit space. Inverse to :func:`to_simplex` ; see that function for more details. :param np.ndarray: Array of unit simplices along the last index. :rtype: ``np.ndarray``
[ "r", "Inteprets", "the", "last", "index", "of", "x", "as", "unit", "simplices", "and", "returns", "a", "real", "array", "of", "the", "sampe", "shape", "in", "logit", "space", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L511-L533
22,833
QInfer/python-qinfer
src/qinfer/utils.py
join_struct_arrays
def join_struct_arrays(arrays): """ Takes a list of possibly structured arrays, concatenates their dtypes, and returns one big array with that dtype. Does the inverse of ``separate_struct_array``. :param list arrays: List of ``np.ndarray``s """ # taken from http://stackoverflow.com/questions/5355744/numpy-joining-structured-arrays sizes = np.array([a.itemsize for a in arrays]) offsets = np.r_[0, sizes.cumsum()] shape = arrays[0].shape joint = np.empty(shape + (offsets[-1],), dtype=np.uint8) for a, size, offset in zip(arrays, sizes, offsets): joint[...,offset:offset+size] = np.atleast_1d(a).view(np.uint8).reshape(shape + (size,)) dtype = sum((a.dtype.descr for a in arrays), []) return joint.ravel().view(dtype)
python
def join_struct_arrays(arrays): # taken from http://stackoverflow.com/questions/5355744/numpy-joining-structured-arrays sizes = np.array([a.itemsize for a in arrays]) offsets = np.r_[0, sizes.cumsum()] shape = arrays[0].shape joint = np.empty(shape + (offsets[-1],), dtype=np.uint8) for a, size, offset in zip(arrays, sizes, offsets): joint[...,offset:offset+size] = np.atleast_1d(a).view(np.uint8).reshape(shape + (size,)) dtype = sum((a.dtype.descr for a in arrays), []) return joint.ravel().view(dtype)
[ "def", "join_struct_arrays", "(", "arrays", ")", ":", "# taken from http://stackoverflow.com/questions/5355744/numpy-joining-structured-arrays", "sizes", "=", "np", ".", "array", "(", "[", "a", ".", "itemsize", "for", "a", "in", "arrays", "]", ")", "offsets", "=", "...
Takes a list of possibly structured arrays, concatenates their dtypes, and returns one big array with that dtype. Does the inverse of ``separate_struct_array``. :param list arrays: List of ``np.ndarray``s
[ "Takes", "a", "list", "of", "possibly", "structured", "arrays", "concatenates", "their", "dtypes", "and", "returns", "one", "big", "array", "with", "that", "dtype", ".", "Does", "the", "inverse", "of", "separate_struct_array", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L551-L567
22,834
QInfer/python-qinfer
src/qinfer/utils.py
separate_struct_array
def separate_struct_array(array, dtypes): """ Takes an array with a structured dtype, and separates it out into a list of arrays with dtypes coming from the input ``dtypes``. Does the inverse of ``join_struct_arrays``. :param np.ndarray array: Structured array. :param dtypes: List of ``np.dtype``, or just a ``np.dtype`` and the number of them is figured out automatically by counting bytes. """ try: offsets = np.cumsum([np.dtype(dtype).itemsize for dtype in dtypes]) except TypeError: dtype_size = np.dtype(dtypes).itemsize num_fields = int(array.nbytes / (array.size * dtype_size)) offsets = np.cumsum([dtype_size] * num_fields) dtypes = [dtypes] * num_fields offsets = np.concatenate([[0], offsets]).astype(int) uint_array = array.view(np.uint8).reshape(array.shape + (-1,)) return [ uint_array[..., offsets[idx]:offsets[idx+1]].flatten().view(dtype) for idx, dtype in enumerate(dtypes) ]
python
def separate_struct_array(array, dtypes): try: offsets = np.cumsum([np.dtype(dtype).itemsize for dtype in dtypes]) except TypeError: dtype_size = np.dtype(dtypes).itemsize num_fields = int(array.nbytes / (array.size * dtype_size)) offsets = np.cumsum([dtype_size] * num_fields) dtypes = [dtypes] * num_fields offsets = np.concatenate([[0], offsets]).astype(int) uint_array = array.view(np.uint8).reshape(array.shape + (-1,)) return [ uint_array[..., offsets[idx]:offsets[idx+1]].flatten().view(dtype) for idx, dtype in enumerate(dtypes) ]
[ "def", "separate_struct_array", "(", "array", ",", "dtypes", ")", ":", "try", ":", "offsets", "=", "np", ".", "cumsum", "(", "[", "np", ".", "dtype", "(", "dtype", ")", ".", "itemsize", "for", "dtype", "in", "dtypes", "]", ")", "except", "TypeError", ...
Takes an array with a structured dtype, and separates it out into a list of arrays with dtypes coming from the input ``dtypes``. Does the inverse of ``join_struct_arrays``. :param np.ndarray array: Structured array. :param dtypes: List of ``np.dtype``, or just a ``np.dtype`` and the number of them is figured out automatically by counting bytes.
[ "Takes", "an", "array", "with", "a", "structured", "dtype", "and", "separates", "it", "out", "into", "a", "list", "of", "arrays", "with", "dtypes", "coming", "from", "the", "input", "dtypes", ".", "Does", "the", "inverse", "of", "join_struct_arrays", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L569-L591
22,835
QInfer/python-qinfer
src/qinfer/utils.py
sqrtm_psd
def sqrtm_psd(A, est_error=True, check_finite=True): """ Returns the matrix square root of a positive semidefinite matrix, truncating negative eigenvalues. """ w, v = eigh(A, check_finite=check_finite) mask = w <= 0 w[mask] = 0 np.sqrt(w, out=w) A_sqrt = (v * w).dot(v.conj().T) if est_error: return A_sqrt, np.linalg.norm(np.dot(A_sqrt, A_sqrt) - A, 'fro') else: return A_sqrt
python
def sqrtm_psd(A, est_error=True, check_finite=True): w, v = eigh(A, check_finite=check_finite) mask = w <= 0 w[mask] = 0 np.sqrt(w, out=w) A_sqrt = (v * w).dot(v.conj().T) if est_error: return A_sqrt, np.linalg.norm(np.dot(A_sqrt, A_sqrt) - A, 'fro') else: return A_sqrt
[ "def", "sqrtm_psd", "(", "A", ",", "est_error", "=", "True", ",", "check_finite", "=", "True", ")", ":", "w", ",", "v", "=", "eigh", "(", "A", ",", "check_finite", "=", "check_finite", ")", "mask", "=", "w", "<=", "0", "w", "[", "mask", "]", "=",...
Returns the matrix square root of a positive semidefinite matrix, truncating negative eigenvalues.
[ "Returns", "the", "matrix", "square", "root", "of", "a", "positive", "semidefinite", "matrix", "truncating", "negative", "eigenvalues", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L593-L607
22,836
QInfer/python-qinfer
src/qinfer/tomography/bases.py
tensor_product_basis
def tensor_product_basis(*bases): """ Returns a TomographyBasis formed by the tensor product of two or more factor bases. Each basis element is the tensor product of basis elements from the underlying factors. """ dim = np.prod([basis.data.shape[1] for basis in bases]) tp_basis = np.zeros((dim**2, dim, dim), dtype=complex) for idx_factors, factors in enumerate(it.product(*[basis.data for basis in bases])): tp_basis[idx_factors, :, :] = reduce(np.kron, factors) return TomographyBasis(tp_basis, sum(( factor.dims for factor in bases ), []), list(map( r"\otimes".join, it.product(*[ basis.labels for basis in bases ]) )))
python
def tensor_product_basis(*bases): dim = np.prod([basis.data.shape[1] for basis in bases]) tp_basis = np.zeros((dim**2, dim, dim), dtype=complex) for idx_factors, factors in enumerate(it.product(*[basis.data for basis in bases])): tp_basis[idx_factors, :, :] = reduce(np.kron, factors) return TomographyBasis(tp_basis, sum(( factor.dims for factor in bases ), []), list(map( r"\otimes".join, it.product(*[ basis.labels for basis in bases ]) )))
[ "def", "tensor_product_basis", "(", "*", "bases", ")", ":", "dim", "=", "np", ".", "prod", "(", "[", "basis", ".", "data", ".", "shape", "[", "1", "]", "for", "basis", "in", "bases", "]", ")", "tp_basis", "=", "np", ".", "zeros", "(", "(", "dim",...
Returns a TomographyBasis formed by the tensor product of two or more factor bases. Each basis element is the tensor product of basis elements from the underlying factors.
[ "Returns", "a", "TomographyBasis", "formed", "by", "the", "tensor", "product", "of", "two", "or", "more", "factor", "bases", ".", "Each", "basis", "element", "is", "the", "tensor", "product", "of", "basis", "elements", "from", "the", "underlying", "factors", ...
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/bases.py#L113-L135
22,837
QInfer/python-qinfer
src/qinfer/tomography/bases.py
TomographyBasis.state_to_modelparams
def state_to_modelparams(self, state): """ Converts a QuTiP-represented state into a model parameter vector. :param qutip.Qobj state: State to be converted. :rtype: :class:`np.ndarray` :return: The representation of the given state in this basis, as a vector of real parameters. """ basis = self.flat() data = state.data.todense().view(np.ndarray).flatten() # NB: assumes Hermitian state and basis! return np.real(np.dot(basis.conj(), data))
python
def state_to_modelparams(self, state): basis = self.flat() data = state.data.todense().view(np.ndarray).flatten() # NB: assumes Hermitian state and basis! return np.real(np.dot(basis.conj(), data))
[ "def", "state_to_modelparams", "(", "self", ",", "state", ")", ":", "basis", "=", "self", ".", "flat", "(", ")", "data", "=", "state", ".", "data", ".", "todense", "(", ")", ".", "view", "(", "np", ".", "ndarray", ")", ".", "flatten", "(", ")", "...
Converts a QuTiP-represented state into a model parameter vector. :param qutip.Qobj state: State to be converted. :rtype: :class:`np.ndarray` :return: The representation of the given state in this basis, as a vector of real parameters.
[ "Converts", "a", "QuTiP", "-", "represented", "state", "into", "a", "model", "parameter", "vector", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/bases.py#L323-L336
22,838
QInfer/python-qinfer
src/qinfer/tomography/bases.py
TomographyBasis.modelparams_to_state
def modelparams_to_state(self, modelparams): """ Converts one or more vectors of model parameters into QuTiP-represented states. :param np.ndarray modelparams: Array of shape ``(basis.dim ** 2, )`` or ``(n_states, basis.dim ** 2)`` containing states represented as model parameter vectors in this basis. :rtype: :class:`~qutip.Qobj` or `list` of :class:`~qutip.Qobj` instances. :return: The given states represented as :class:`~qutip.Qobj` instances. """ if modelparams.ndim == 1: qobj = qt.Qobj( np.tensordot(modelparams, self.data, 1), dims=[self.dims, self.dims] ) if self.superrep is not None: qobj.superrep = self.superrep return qobj else: return list(map(self.modelparams_to_state, modelparams))
python
def modelparams_to_state(self, modelparams): if modelparams.ndim == 1: qobj = qt.Qobj( np.tensordot(modelparams, self.data, 1), dims=[self.dims, self.dims] ) if self.superrep is not None: qobj.superrep = self.superrep return qobj else: return list(map(self.modelparams_to_state, modelparams))
[ "def", "modelparams_to_state", "(", "self", ",", "modelparams", ")", ":", "if", "modelparams", ".", "ndim", "==", "1", ":", "qobj", "=", "qt", ".", "Qobj", "(", "np", ".", "tensordot", "(", "modelparams", ",", "self", ".", "data", ",", "1", ")", ",",...
Converts one or more vectors of model parameters into QuTiP-represented states. :param np.ndarray modelparams: Array of shape ``(basis.dim ** 2, )`` or ``(n_states, basis.dim ** 2)`` containing states represented as model parameter vectors in this basis. :rtype: :class:`~qutip.Qobj` or `list` of :class:`~qutip.Qobj` instances. :return: The given states represented as :class:`~qutip.Qobj` instances.
[ "Converts", "one", "or", "more", "vectors", "of", "model", "parameters", "into", "QuTiP", "-", "represented", "states", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/bases.py#L338-L362
22,839
QInfer/python-qinfer
src/qinfer/tomography/bases.py
TomographyBasis.covariance_mtx_to_superop
def covariance_mtx_to_superop(self, mtx): """ Converts a covariance matrix to the corresponding superoperator, represented as a QuTiP Qobj with ``type="super"``. """ M = self.flat() return qt.Qobj( np.dot(np.dot(M.conj().T, mtx), M), dims=[[self.dims] * 2] * 2 )
python
def covariance_mtx_to_superop(self, mtx): M = self.flat() return qt.Qobj( np.dot(np.dot(M.conj().T, mtx), M), dims=[[self.dims] * 2] * 2 )
[ "def", "covariance_mtx_to_superop", "(", "self", ",", "mtx", ")", ":", "M", "=", "self", ".", "flat", "(", ")", "return", "qt", ".", "Qobj", "(", "np", ".", "dot", "(", "np", ".", "dot", "(", "M", ".", "conj", "(", ")", ".", "T", ",", "mtx", ...
Converts a covariance matrix to the corresponding superoperator, represented as a QuTiP Qobj with ``type="super"``.
[ "Converts", "a", "covariance", "matrix", "to", "the", "corresponding", "superoperator", "represented", "as", "a", "QuTiP", "Qobj", "with", "type", "=", "super", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/bases.py#L364-L374
22,840
QInfer/python-qinfer
src/qinfer/distributions.py
MixtureDistribution._dist_kw_arg
def _dist_kw_arg(self, k): """ Returns a dictionary of keyword arguments for the k'th distribution. :param int k: Index of the distribution in question. :rtype: ``dict`` """ if self._dist_kw_args is not None: return { key:self._dist_kw_args[key][k,:] for key in self._dist_kw_args.keys() } else: return {}
python
def _dist_kw_arg(self, k): if self._dist_kw_args is not None: return { key:self._dist_kw_args[key][k,:] for key in self._dist_kw_args.keys() } else: return {}
[ "def", "_dist_kw_arg", "(", "self", ",", "k", ")", ":", "if", "self", ".", "_dist_kw_args", "is", "not", "None", ":", "return", "{", "key", ":", "self", ".", "_dist_kw_args", "[", "key", "]", "[", "k", ",", ":", "]", "for", "key", "in", "self", "...
Returns a dictionary of keyword arguments for the k'th distribution. :param int k: Index of the distribution in question. :rtype: ``dict``
[ "Returns", "a", "dictionary", "of", "keyword", "arguments", "for", "the", "k", "th", "distribution", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L207-L221
22,841
QInfer/python-qinfer
src/qinfer/distributions.py
ParticleDistribution.sample
def sample(self, n=1): """ Returns random samples from the current particle distribution according to particle weights. :param int n: The number of samples to draw. :return: The sampled model parameter vectors. :rtype: `~numpy.ndarray` of shape ``(n, updater.n_rvs)``. """ cumsum_weights = np.cumsum(self.particle_weights) return self.particle_locations[np.minimum(cumsum_weights.searchsorted( np.random.random((n,)), side='right' ), len(cumsum_weights) - 1)]
python
def sample(self, n=1): cumsum_weights = np.cumsum(self.particle_weights) return self.particle_locations[np.minimum(cumsum_weights.searchsorted( np.random.random((n,)), side='right' ), len(cumsum_weights) - 1)]
[ "def", "sample", "(", "self", ",", "n", "=", "1", ")", ":", "cumsum_weights", "=", "np", ".", "cumsum", "(", "self", ".", "particle_weights", ")", "return", "self", ".", "particle_locations", "[", "np", ".", "minimum", "(", "cumsum_weights", ".", "search...
Returns random samples from the current particle distribution according to particle weights. :param int n: The number of samples to draw. :return: The sampled model parameter vectors. :rtype: `~numpy.ndarray` of shape ``(n, updater.n_rvs)``.
[ "Returns", "random", "samples", "from", "the", "current", "particle", "distribution", "according", "to", "particle", "weights", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L320-L333
22,842
QInfer/python-qinfer
src/qinfer/distributions.py
ParticleDistribution.est_covariance_mtx
def est_covariance_mtx(self, corr=False): """ Returns the full-rank covariance matrix of the current particle distribution. :param bool corr: If `True`, the covariance matrix is normalized by the outer product of the square root diagonal of the covariance matrix, i.e. the correlation matrix is returned instead. :rtype: :class:`numpy.ndarray`, shape ``(n_modelparams, n_modelparams)``. :returns: An array containing the estimated covariance matrix. """ cov = self.particle_covariance_mtx(self.particle_weights, self.particle_locations) if corr: dstd = np.sqrt(np.diag(cov)) cov /= (np.outer(dstd, dstd)) return cov
python
def est_covariance_mtx(self, corr=False): cov = self.particle_covariance_mtx(self.particle_weights, self.particle_locations) if corr: dstd = np.sqrt(np.diag(cov)) cov /= (np.outer(dstd, dstd)) return cov
[ "def", "est_covariance_mtx", "(", "self", ",", "corr", "=", "False", ")", ":", "cov", "=", "self", ".", "particle_covariance_mtx", "(", "self", ".", "particle_weights", ",", "self", ".", "particle_locations", ")", "if", "corr", ":", "dstd", "=", "np", ".",...
Returns the full-rank covariance matrix of the current particle distribution. :param bool corr: If `True`, the covariance matrix is normalized by the outer product of the square root diagonal of the covariance matrix, i.e. the correlation matrix is returned instead. :rtype: :class:`numpy.ndarray`, shape ``(n_modelparams, n_modelparams)``. :returns: An array containing the estimated covariance matrix.
[ "Returns", "the", "full", "-", "rank", "covariance", "matrix", "of", "the", "current", "particle", "distribution", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L432-L453
22,843
QInfer/python-qinfer
src/qinfer/distributions.py
ParticleDistribution.est_credible_region
def est_credible_region(self, level=0.95, return_outside=False, modelparam_slice=None): """ Returns an array containing particles inside a credible region of a given level, such that the described region has probability mass no less than the desired level. Particles in the returned region are selected by including the highest- weight particles first until the desired credibility level is reached. :param float level: Crediblity level to report. :param bool return_outside: If `True`, the return value is a tuple of the those particles within the credible region, and the rest of the posterior particle cloud. :param slice modelparam_slice: Slice over which model parameters to consider. :rtype: :class:`numpy.ndarray`, shape ``(n_credible, n_mps)``, where ``n_credible`` is the number of particles in the credible region and ``n_mps`` corresponds to the size of ``modelparam_slice``. If ``return_outside`` is ``True``, this method instead returns tuple ``(inside, outside)`` where ``inside`` is as described above, and ``outside`` has shape ``(n_particles-n_credible, n_mps)``. :return: An array of particles inside the estimated credible region. Or, if ``return_outside`` is ``True``, both the particles inside and the particles outside, as a tuple. """ # which slice of modelparams to take s_ = np.s_[modelparam_slice] if modelparam_slice is not None else np.s_[:] mps = self.particle_locations[:, s_] # Start by sorting the particles by weight. # We do so by obtaining an array of indices `id_sort` such that # `particle_weights[id_sort]` is in descending order. id_sort = np.argsort(self.particle_weights)[::-1] # Find the cummulative sum of the sorted weights. cumsum_weights = np.cumsum(self.particle_weights[id_sort]) # Find all the indices where the sum is less than level. # We first find id_cred such that # `all(cumsum_weights[id_cred] <= level)`. id_cred = cumsum_weights <= level # By construction, by adding the next particle to id_cred, it must be # true that `cumsum_weights[id_cred] >= level`, as required. id_cred[np.sum(id_cred)] = True # We now return a slice onto the particle_locations by first permuting # the particles according to the sort order, then by selecting the # credible particles. if return_outside: return ( mps[id_sort][id_cred], mps[id_sort][np.logical_not(id_cred)] ) else: return mps[id_sort][id_cred]
python
def est_credible_region(self, level=0.95, return_outside=False, modelparam_slice=None): # which slice of modelparams to take s_ = np.s_[modelparam_slice] if modelparam_slice is not None else np.s_[:] mps = self.particle_locations[:, s_] # Start by sorting the particles by weight. # We do so by obtaining an array of indices `id_sort` such that # `particle_weights[id_sort]` is in descending order. id_sort = np.argsort(self.particle_weights)[::-1] # Find the cummulative sum of the sorted weights. cumsum_weights = np.cumsum(self.particle_weights[id_sort]) # Find all the indices where the sum is less than level. # We first find id_cred such that # `all(cumsum_weights[id_cred] <= level)`. id_cred = cumsum_weights <= level # By construction, by adding the next particle to id_cred, it must be # true that `cumsum_weights[id_cred] >= level`, as required. id_cred[np.sum(id_cred)] = True # We now return a slice onto the particle_locations by first permuting # the particles according to the sort order, then by selecting the # credible particles. if return_outside: return ( mps[id_sort][id_cred], mps[id_sort][np.logical_not(id_cred)] ) else: return mps[id_sort][id_cred]
[ "def", "est_credible_region", "(", "self", ",", "level", "=", "0.95", ",", "return_outside", "=", "False", ",", "modelparam_slice", "=", "None", ")", ":", "# which slice of modelparams to take", "s_", "=", "np", ".", "s_", "[", "modelparam_slice", "]", "if", "...
Returns an array containing particles inside a credible region of a given level, such that the described region has probability mass no less than the desired level. Particles in the returned region are selected by including the highest- weight particles first until the desired credibility level is reached. :param float level: Crediblity level to report. :param bool return_outside: If `True`, the return value is a tuple of the those particles within the credible region, and the rest of the posterior particle cloud. :param slice modelparam_slice: Slice over which model parameters to consider. :rtype: :class:`numpy.ndarray`, shape ``(n_credible, n_mps)``, where ``n_credible`` is the number of particles in the credible region and ``n_mps`` corresponds to the size of ``modelparam_slice``. If ``return_outside`` is ``True``, this method instead returns tuple ``(inside, outside)`` where ``inside`` is as described above, and ``outside`` has shape ``(n_particles-n_credible, n_mps)``. :return: An array of particles inside the estimated credible region. Or, if ``return_outside`` is ``True``, both the particles inside and the particles outside, as a tuple.
[ "Returns", "an", "array", "containing", "particles", "inside", "a", "credible", "region", "of", "a", "given", "level", "such", "that", "the", "described", "region", "has", "probability", "mass", "no", "less", "than", "the", "desired", "level", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L558-L614
22,844
QInfer/python-qinfer
src/qinfer/distributions.py
ParticleDistribution.region_est_hull
def region_est_hull(self, level=0.95, modelparam_slice=None): """ Estimates a credible region over models by taking the convex hull of a credible subset of particles. :param float level: The desired crediblity level (see :meth:`SMCUpdater.est_credible_region`). :param slice modelparam_slice: Slice over which model parameters to consider. :return: The tuple ``(faces, vertices)`` where ``faces`` describes all the vertices of all of the faces on the exterior of the convex hull, and ``vertices`` is a list of all vertices on the exterior of the convex hull. :rtype: ``faces`` is a ``numpy.ndarray`` with shape ``(n_face, n_mps, n_mps)`` and indeces ``(idx_face, idx_vertex, idx_mps)`` where ``n_mps`` corresponds to the size of ``modelparam_slice``. ``vertices`` is an ``numpy.ndarray`` of shape ``(n_vertices, n_mps)``. """ points = self.est_credible_region( level=level, modelparam_slice=modelparam_slice ) hull = ConvexHull(points) return points[hull.simplices], points[u.uniquify(hull.vertices.flatten())]
python
def region_est_hull(self, level=0.95, modelparam_slice=None): points = self.est_credible_region( level=level, modelparam_slice=modelparam_slice ) hull = ConvexHull(points) return points[hull.simplices], points[u.uniquify(hull.vertices.flatten())]
[ "def", "region_est_hull", "(", "self", ",", "level", "=", "0.95", ",", "modelparam_slice", "=", "None", ")", ":", "points", "=", "self", ".", "est_credible_region", "(", "level", "=", "level", ",", "modelparam_slice", "=", "modelparam_slice", ")", "hull", "=...
Estimates a credible region over models by taking the convex hull of a credible subset of particles. :param float level: The desired crediblity level (see :meth:`SMCUpdater.est_credible_region`). :param slice modelparam_slice: Slice over which model parameters to consider. :return: The tuple ``(faces, vertices)`` where ``faces`` describes all the vertices of all of the faces on the exterior of the convex hull, and ``vertices`` is a list of all vertices on the exterior of the convex hull. :rtype: ``faces`` is a ``numpy.ndarray`` with shape ``(n_face, n_mps, n_mps)`` and indeces ``(idx_face, idx_vertex, idx_mps)`` where ``n_mps`` corresponds to the size of ``modelparam_slice``. ``vertices`` is an ``numpy.ndarray`` of shape ``(n_vertices, n_mps)``.
[ "Estimates", "a", "credible", "region", "over", "models", "by", "taking", "the", "convex", "hull", "of", "a", "credible", "subset", "of", "particles", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L616-L641
22,845
QInfer/python-qinfer
src/qinfer/distributions.py
ParticleDistribution.in_credible_region
def in_credible_region(self, points, level=0.95, modelparam_slice=None, method='hpd-hull', tol=0.0001): """ Decides whether each of the points lie within a credible region of the current distribution. If ``tol`` is ``None``, the particles are tested directly against the convex hull object. If ``tol`` is a positive ``float``, particles are tested to be in the interior of the smallest enclosing ellipsoid of this convex hull, see :meth:`SMCUpdater.region_est_ellipsoid`. :param np.ndarray points: An ``np.ndarray`` of shape ``(n_mps)`` for a single point, or of shape ``(n_points, n_mps)`` for multiple points, where ``n_mps`` corresponds to the same dimensionality as ``param_slice``. :param float level: The desired crediblity level (see :meth:`SMCUpdater.est_credible_region`). :param str method: A string specifying which credible region estimator to use. One of ``'pce'``, ``'hpd-hull'`` or ``'hpd-mvee'`` (see below). :param float tol: The allowed error tolerance for those methods which require a tolerance (see :meth:`~qinfer.utils.mvee`). :param slice modelparam_slice: A slice describing which model parameters to consider in the credible region, effectively marginizing out the remaining parameters. By default, all model parameters are included. :return: A boolean array of shape ``(n_points, )`` specifying whether each of the points lies inside the confidence region. Methods ~~~~~~~ The following values are valid for the ``method`` argument. - ``'pce'``: Posterior Covariance Ellipsoid. Computes the covariance matrix of the particle distribution marginalized over the excluded slices and uses the :math:`\chi^2` distribution to determine how to rescale it such the the corresponding ellipsoid has the correct size. The ellipsoid is translated by the mean of the particle distribution. It is determined which of the ``points`` are on the interior. - ``'hpd-hull'``: High Posterior Density Convex Hull. See :meth:`SMCUpdater.region_est_hull`. Computes the HPD region resulting from the particle approximation, computes the convex hull of this, and it is determined which of the ``points`` are on the interior. - ``'hpd-mvee'``: High Posterior Density Minimum Volume Enclosing Ellipsoid. See :meth:`SMCUpdater.region_est_ellipsoid` and :meth:`~qinfer.utils.mvee`. Computes the HPD region resulting from the particle approximation, computes the convex hull of this, and determines the minimum enclosing ellipsoid. Deterimines which of the ``points`` are on the interior. """ if method == 'pce': s_ = np.s_[modelparam_slice] if modelparam_slice is not None else np.s_[:] A = self.est_covariance_mtx()[s_, s_] c = self.est_mean()[s_] # chi-squared distribution gives correct level curve conversion mult = st.chi2.ppf(level, c.size) results = u.in_ellipsoid(points, mult * A, c) elif method == 'hpd-mvee': tol = 0.0001 if tol is None else tol A, c = self.region_est_ellipsoid(level=level, tol=tol, modelparam_slice=modelparam_slice) results = u.in_ellipsoid(points, np.linalg.inv(A), c) elif method == 'hpd-hull': # it would be more natural to call region_est_hull, # but that function uses ConvexHull which has no # easy way of determining if a point is interior. # Here, Delaunay gives us access to all of the # necessary simplices. # this fills the convex hull with (n_mps+1)-dimensional # simplices; the convex hull is an almost-everywhere # disjoint union of these simplices hull = Delaunay(self.est_credible_region(level=level, modelparam_slice=modelparam_slice)) # now we just check whether each of the given points are in # any of the simplices. (http://stackoverflow.com/a/16898636/1082565) results = hull.find_simplex(points) >= 0 return results
python
def in_credible_region(self, points, level=0.95, modelparam_slice=None, method='hpd-hull', tol=0.0001): if method == 'pce': s_ = np.s_[modelparam_slice] if modelparam_slice is not None else np.s_[:] A = self.est_covariance_mtx()[s_, s_] c = self.est_mean()[s_] # chi-squared distribution gives correct level curve conversion mult = st.chi2.ppf(level, c.size) results = u.in_ellipsoid(points, mult * A, c) elif method == 'hpd-mvee': tol = 0.0001 if tol is None else tol A, c = self.region_est_ellipsoid(level=level, tol=tol, modelparam_slice=modelparam_slice) results = u.in_ellipsoid(points, np.linalg.inv(A), c) elif method == 'hpd-hull': # it would be more natural to call region_est_hull, # but that function uses ConvexHull which has no # easy way of determining if a point is interior. # Here, Delaunay gives us access to all of the # necessary simplices. # this fills the convex hull with (n_mps+1)-dimensional # simplices; the convex hull is an almost-everywhere # disjoint union of these simplices hull = Delaunay(self.est_credible_region(level=level, modelparam_slice=modelparam_slice)) # now we just check whether each of the given points are in # any of the simplices. (http://stackoverflow.com/a/16898636/1082565) results = hull.find_simplex(points) >= 0 return results
[ "def", "in_credible_region", "(", "self", ",", "points", ",", "level", "=", "0.95", ",", "modelparam_slice", "=", "None", ",", "method", "=", "'hpd-hull'", ",", "tol", "=", "0.0001", ")", ":", "if", "method", "==", "'pce'", ":", "s_", "=", "np", ".", ...
Decides whether each of the points lie within a credible region of the current distribution. If ``tol`` is ``None``, the particles are tested directly against the convex hull object. If ``tol`` is a positive ``float``, particles are tested to be in the interior of the smallest enclosing ellipsoid of this convex hull, see :meth:`SMCUpdater.region_est_ellipsoid`. :param np.ndarray points: An ``np.ndarray`` of shape ``(n_mps)`` for a single point, or of shape ``(n_points, n_mps)`` for multiple points, where ``n_mps`` corresponds to the same dimensionality as ``param_slice``. :param float level: The desired crediblity level (see :meth:`SMCUpdater.est_credible_region`). :param str method: A string specifying which credible region estimator to use. One of ``'pce'``, ``'hpd-hull'`` or ``'hpd-mvee'`` (see below). :param float tol: The allowed error tolerance for those methods which require a tolerance (see :meth:`~qinfer.utils.mvee`). :param slice modelparam_slice: A slice describing which model parameters to consider in the credible region, effectively marginizing out the remaining parameters. By default, all model parameters are included. :return: A boolean array of shape ``(n_points, )`` specifying whether each of the points lies inside the confidence region. Methods ~~~~~~~ The following values are valid for the ``method`` argument. - ``'pce'``: Posterior Covariance Ellipsoid. Computes the covariance matrix of the particle distribution marginalized over the excluded slices and uses the :math:`\chi^2` distribution to determine how to rescale it such the the corresponding ellipsoid has the correct size. The ellipsoid is translated by the mean of the particle distribution. It is determined which of the ``points`` are on the interior. - ``'hpd-hull'``: High Posterior Density Convex Hull. See :meth:`SMCUpdater.region_est_hull`. Computes the HPD region resulting from the particle approximation, computes the convex hull of this, and it is determined which of the ``points`` are on the interior. - ``'hpd-mvee'``: High Posterior Density Minimum Volume Enclosing Ellipsoid. See :meth:`SMCUpdater.region_est_ellipsoid` and :meth:`~qinfer.utils.mvee`. Computes the HPD region resulting from the particle approximation, computes the convex hull of this, and determines the minimum enclosing ellipsoid. Deterimines which of the ``points`` are on the interior.
[ "Decides", "whether", "each", "of", "the", "points", "lie", "within", "a", "credible", "region", "of", "the", "current", "distribution", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L668-L751
22,846
QInfer/python-qinfer
src/qinfer/distributions.py
PostselectedDistribution.sample
def sample(self, n=1): """ Returns one or more samples from this probability distribution. :param int n: Number of samples to return. :return numpy.ndarray: An array containing samples from the distribution of shape ``(n, d)``, where ``d`` is the number of random variables. """ samples = np.empty((n, self.n_rvs)) idxs_to_sample = np.arange(n) iters = 0 while idxs_to_sample.size and iters < self._maxiters: samples[idxs_to_sample] = self._dist.sample(len(idxs_to_sample)) idxs_to_sample = idxs_to_sample[np.nonzero(np.logical_not( self._model.are_models_valid(samples[idxs_to_sample, :]) ))[0]] iters += 1 if idxs_to_sample.size: raise RuntimeError("Did not successfully postselect within {} iterations.".format(self._maxiters)) return samples
python
def sample(self, n=1): samples = np.empty((n, self.n_rvs)) idxs_to_sample = np.arange(n) iters = 0 while idxs_to_sample.size and iters < self._maxiters: samples[idxs_to_sample] = self._dist.sample(len(idxs_to_sample)) idxs_to_sample = idxs_to_sample[np.nonzero(np.logical_not( self._model.are_models_valid(samples[idxs_to_sample, :]) ))[0]] iters += 1 if idxs_to_sample.size: raise RuntimeError("Did not successfully postselect within {} iterations.".format(self._maxiters)) return samples
[ "def", "sample", "(", "self", ",", "n", "=", "1", ")", ":", "samples", "=", "np", ".", "empty", "(", "(", "n", ",", "self", ".", "n_rvs", ")", ")", "idxs_to_sample", "=", "np", ".", "arange", "(", "n", ")", "iters", "=", "0", "while", "idxs_to_...
Returns one or more samples from this probability distribution. :param int n: Number of samples to return. :return numpy.ndarray: An array containing samples from the distribution of shape ``(n, d)``, where ``d`` is the number of random variables.
[ "Returns", "one", "or", "more", "samples", "from", "this", "probability", "distribution", "." ]
8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L1321-L1347
22,847
amelchio/pysonos
pysonos/services.py
Service.iter_actions
def iter_actions(self): """Yield the service's actions with their arguments. Yields: `Action`: the next action. Each action is an Action namedtuple, consisting of action_name (a string), in_args (a list of Argument namedtuples consisting of name and argtype), and out_args (ditto), eg:: Action( name='SetFormat', in_args=[ Argument(name='DesiredTimeFormat', vartype=<Vartype>), Argument(name='DesiredDateFormat', vartype=<Vartype>)], out_args=[] ) """ # pylint: disable=too-many-locals # pylint: disable=invalid-name ns = '{urn:schemas-upnp-org:service-1-0}' # get the scpd body as bytes, and feed directly to elementtree # which likes to receive bytes scpd_body = requests.get(self.base_url + self.scpd_url).content tree = XML.fromstring(scpd_body) # parse the state variables to get the relevant variable types vartypes = {} srvStateTables = tree.findall('{}serviceStateTable'.format(ns)) for srvStateTable in srvStateTables: statevars = srvStateTable.findall('{}stateVariable'.format(ns)) for state in statevars: name = state.findtext('{}name'.format(ns)) datatype = state.findtext('{}dataType'.format(ns)) default = state.findtext('{}defaultValue'.format(ns)) value_list_elt = state.find('{}allowedValueList'.format(ns)) if value_list_elt is None: value_list_elt = () value_list = [item.text for item in value_list_elt] or None value_range_elt = state.find('{}allowedValueRange'.format(ns)) if value_range_elt is None: value_range_elt = () value_range = [item.text for item in value_range_elt] or None vartypes[name] = Vartype(datatype, default, value_list, value_range) # find all the actions actionLists = tree.findall('{}actionList'.format(ns)) for actionList in actionLists: actions = actionList.findall('{}action'.format(ns)) for i in actions: action_name = i.findtext('{}name'.format(ns)) argLists = i.findall('{}argumentList'.format(ns)) for argList in argLists: args_iter = argList.findall('{}argument'.format(ns)) in_args = [] out_args = [] for arg in args_iter: arg_name = arg.findtext('{}name'.format(ns)) direction = arg.findtext('{}direction'.format(ns)) related_variable = arg.findtext( '{}relatedStateVariable'.format(ns)) vartype = vartypes[related_variable] if direction == "in": in_args.append(Argument(arg_name, vartype)) else: out_args.append(Argument(arg_name, vartype)) yield Action(action_name, in_args, out_args)
python
def iter_actions(self): # pylint: disable=too-many-locals # pylint: disable=invalid-name ns = '{urn:schemas-upnp-org:service-1-0}' # get the scpd body as bytes, and feed directly to elementtree # which likes to receive bytes scpd_body = requests.get(self.base_url + self.scpd_url).content tree = XML.fromstring(scpd_body) # parse the state variables to get the relevant variable types vartypes = {} srvStateTables = tree.findall('{}serviceStateTable'.format(ns)) for srvStateTable in srvStateTables: statevars = srvStateTable.findall('{}stateVariable'.format(ns)) for state in statevars: name = state.findtext('{}name'.format(ns)) datatype = state.findtext('{}dataType'.format(ns)) default = state.findtext('{}defaultValue'.format(ns)) value_list_elt = state.find('{}allowedValueList'.format(ns)) if value_list_elt is None: value_list_elt = () value_list = [item.text for item in value_list_elt] or None value_range_elt = state.find('{}allowedValueRange'.format(ns)) if value_range_elt is None: value_range_elt = () value_range = [item.text for item in value_range_elt] or None vartypes[name] = Vartype(datatype, default, value_list, value_range) # find all the actions actionLists = tree.findall('{}actionList'.format(ns)) for actionList in actionLists: actions = actionList.findall('{}action'.format(ns)) for i in actions: action_name = i.findtext('{}name'.format(ns)) argLists = i.findall('{}argumentList'.format(ns)) for argList in argLists: args_iter = argList.findall('{}argument'.format(ns)) in_args = [] out_args = [] for arg in args_iter: arg_name = arg.findtext('{}name'.format(ns)) direction = arg.findtext('{}direction'.format(ns)) related_variable = arg.findtext( '{}relatedStateVariable'.format(ns)) vartype = vartypes[related_variable] if direction == "in": in_args.append(Argument(arg_name, vartype)) else: out_args.append(Argument(arg_name, vartype)) yield Action(action_name, in_args, out_args)
[ "def", "iter_actions", "(", "self", ")", ":", "# pylint: disable=too-many-locals", "# pylint: disable=invalid-name", "ns", "=", "'{urn:schemas-upnp-org:service-1-0}'", "# get the scpd body as bytes, and feed directly to elementtree", "# which likes to receive bytes", "scpd_body", "=", ...
Yield the service's actions with their arguments. Yields: `Action`: the next action. Each action is an Action namedtuple, consisting of action_name (a string), in_args (a list of Argument namedtuples consisting of name and argtype), and out_args (ditto), eg:: Action( name='SetFormat', in_args=[ Argument(name='DesiredTimeFormat', vartype=<Vartype>), Argument(name='DesiredDateFormat', vartype=<Vartype>)], out_args=[] )
[ "Yield", "the", "service", "s", "actions", "with", "their", "arguments", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/services.py#L645-L711
22,848
amelchio/pysonos
pysonos/events.py
parse_event_xml
def parse_event_xml(xml_event): """Parse the body of a UPnP event. Args: xml_event (bytes): bytes containing the body of the event encoded with utf-8. Returns: dict: A dict with keys representing the evented variables. The relevant value will usually be a string representation of the variable's value, but may on occasion be: * a dict (eg when the volume changes, the value will itself be a dict containing the volume for each channel: :code:`{'Volume': {'LF': '100', 'RF': '100', 'Master': '36'}}`) * an instance of a `DidlObject` subclass (eg if it represents track metadata). * a `SoCoFault` (if a variable contains illegal metadata) Example: Run this code, and change your volume, tracks etc:: from __future__ import print_function try: from queue import Empty except: # Py2.7 from Queue import Empty import soco from pprint import pprint from soco.events import event_listener # pick a device at random device = soco.discover().pop() print (device.player_name) sub = device.renderingControl.subscribe() sub2 = device.avTransport.subscribe() while True: try: event = sub.events.get(timeout=0.5) pprint (event.variables) except Empty: pass try: event = sub2.events.get(timeout=0.5) pprint (event.variables) except Empty: pass except KeyboardInterrupt: sub.unsubscribe() sub2.unsubscribe() event_listener.stop() break """ result = {} tree = XML.fromstring(xml_event) # property values are just under the propertyset, which # uses this namespace properties = tree.findall( '{urn:schemas-upnp-org:event-1-0}property') for prop in properties: # pylint: disable=too-many-nested-blocks for variable in prop: # Special handling for a LastChange event specially. For details on # LastChange events, see # http://upnp.org/specs/av/UPnP-av-RenderingControl-v1-Service.pdf # and http://upnp.org/specs/av/UPnP-av-AVTransport-v1-Service.pdf if variable.tag == "LastChange": last_change_tree = XML.fromstring( variable.text.encode('utf-8')) # We assume there is only one InstanceID tag. This is true for # Sonos, as far as we know. # InstanceID can be in one of two namespaces, depending on # whether we are looking at an avTransport event, a # renderingControl event, or a Queue event # (there, it is named QueueID) instance = last_change_tree.find( "{urn:schemas-upnp-org:metadata-1-0/AVT/}InstanceID") if instance is None: instance = last_change_tree.find( "{urn:schemas-upnp-org:metadata-1-0/RCS/}InstanceID") if instance is None: instance = last_change_tree.find( "{urn:schemas-sonos-com:metadata-1-0/Queue/}QueueID") # Look at each variable within the LastChange event for last_change_var in instance: tag = last_change_var.tag # Remove any namespaces from the tags if tag.startswith('{'): tag = tag.split('}', 1)[1] # Un-camel case it tag = camel_to_underscore(tag) # Now extract the relevant value for the variable. # The UPnP specs suggest that the value of any variable # evented via a LastChange Event will be in the 'val' # attribute, but audio related variables may also have a # 'channel' attribute. In addition, it seems that Sonos # sometimes uses a text value instead: see # http://forums.sonos.com/showthread.php?t=34663 value = last_change_var.get('val') if value is None: value = last_change_var.text # If DIDL metadata is returned, convert it to a music # library data structure if value.startswith('<DIDL-Lite'): # Wrap any parsing exception in a SoCoFault, so the # user can handle it try: didl = from_didl_string(value) if not didl: continue value = didl[0] except SoCoException as original_exception: log.debug("Event contains illegal metadata" "for '%s'.\n" "Error message: '%s'\n" "The result will be a SoCoFault.", tag, str(original_exception)) event_parse_exception = EventParseException( tag, value, original_exception ) value = SoCoFault(event_parse_exception) channel = last_change_var.get('channel') if channel is not None: if result.get(tag) is None: result[tag] = {} result[tag][channel] = value else: result[tag] = value else: result[camel_to_underscore(variable.tag)] = variable.text return result
python
def parse_event_xml(xml_event): result = {} tree = XML.fromstring(xml_event) # property values are just under the propertyset, which # uses this namespace properties = tree.findall( '{urn:schemas-upnp-org:event-1-0}property') for prop in properties: # pylint: disable=too-many-nested-blocks for variable in prop: # Special handling for a LastChange event specially. For details on # LastChange events, see # http://upnp.org/specs/av/UPnP-av-RenderingControl-v1-Service.pdf # and http://upnp.org/specs/av/UPnP-av-AVTransport-v1-Service.pdf if variable.tag == "LastChange": last_change_tree = XML.fromstring( variable.text.encode('utf-8')) # We assume there is only one InstanceID tag. This is true for # Sonos, as far as we know. # InstanceID can be in one of two namespaces, depending on # whether we are looking at an avTransport event, a # renderingControl event, or a Queue event # (there, it is named QueueID) instance = last_change_tree.find( "{urn:schemas-upnp-org:metadata-1-0/AVT/}InstanceID") if instance is None: instance = last_change_tree.find( "{urn:schemas-upnp-org:metadata-1-0/RCS/}InstanceID") if instance is None: instance = last_change_tree.find( "{urn:schemas-sonos-com:metadata-1-0/Queue/}QueueID") # Look at each variable within the LastChange event for last_change_var in instance: tag = last_change_var.tag # Remove any namespaces from the tags if tag.startswith('{'): tag = tag.split('}', 1)[1] # Un-camel case it tag = camel_to_underscore(tag) # Now extract the relevant value for the variable. # The UPnP specs suggest that the value of any variable # evented via a LastChange Event will be in the 'val' # attribute, but audio related variables may also have a # 'channel' attribute. In addition, it seems that Sonos # sometimes uses a text value instead: see # http://forums.sonos.com/showthread.php?t=34663 value = last_change_var.get('val') if value is None: value = last_change_var.text # If DIDL metadata is returned, convert it to a music # library data structure if value.startswith('<DIDL-Lite'): # Wrap any parsing exception in a SoCoFault, so the # user can handle it try: didl = from_didl_string(value) if not didl: continue value = didl[0] except SoCoException as original_exception: log.debug("Event contains illegal metadata" "for '%s'.\n" "Error message: '%s'\n" "The result will be a SoCoFault.", tag, str(original_exception)) event_parse_exception = EventParseException( tag, value, original_exception ) value = SoCoFault(event_parse_exception) channel = last_change_var.get('channel') if channel is not None: if result.get(tag) is None: result[tag] = {} result[tag][channel] = value else: result[tag] = value else: result[camel_to_underscore(variable.tag)] = variable.text return result
[ "def", "parse_event_xml", "(", "xml_event", ")", ":", "result", "=", "{", "}", "tree", "=", "XML", ".", "fromstring", "(", "xml_event", ")", "# property values are just under the propertyset, which", "# uses this namespace", "properties", "=", "tree", ".", "findall", ...
Parse the body of a UPnP event. Args: xml_event (bytes): bytes containing the body of the event encoded with utf-8. Returns: dict: A dict with keys representing the evented variables. The relevant value will usually be a string representation of the variable's value, but may on occasion be: * a dict (eg when the volume changes, the value will itself be a dict containing the volume for each channel: :code:`{'Volume': {'LF': '100', 'RF': '100', 'Master': '36'}}`) * an instance of a `DidlObject` subclass (eg if it represents track metadata). * a `SoCoFault` (if a variable contains illegal metadata) Example: Run this code, and change your volume, tracks etc:: from __future__ import print_function try: from queue import Empty except: # Py2.7 from Queue import Empty import soco from pprint import pprint from soco.events import event_listener # pick a device at random device = soco.discover().pop() print (device.player_name) sub = device.renderingControl.subscribe() sub2 = device.avTransport.subscribe() while True: try: event = sub.events.get(timeout=0.5) pprint (event.variables) except Empty: pass try: event = sub2.events.get(timeout=0.5) pprint (event.variables) except Empty: pass except KeyboardInterrupt: sub.unsubscribe() sub2.unsubscribe() event_listener.stop() break
[ "Parse", "the", "body", "of", "a", "UPnP", "event", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/events.py#L37-L170
22,849
amelchio/pysonos
pysonos/events.py
Subscription.unsubscribe
def unsubscribe(self): """Unsubscribe from the service's events. Once unsubscribed, a Subscription instance should not be reused """ # Trying to unsubscribe if already unsubscribed, or not yet # subscribed, fails silently if self._has_been_unsubscribed or not self.is_subscribed: return # Cancel any auto renew self._auto_renew_thread_flag.set() # Send an unsubscribe request like this: # UNSUBSCRIBE publisher path HTTP/1.1 # HOST: publisher host:publisher port # SID: uuid:subscription UUID headers = { 'SID': self.sid } response = None try: response = requests.request( 'UNSUBSCRIBE', self.service.base_url + self.service.event_subscription_url, headers=headers, timeout=3) except requests.exceptions.RequestException: pass self.is_subscribed = False self._timestamp = None log.info( "Unsubscribed from %s, sid: %s", self.service.base_url + self.service.event_subscription_url, self.sid) # remove queue from event queues and sid to service mappings with _subscriptions_lock: try: del _subscriptions[self.sid] except KeyError: pass self._has_been_unsubscribed = True # Ignore "412 Client Error: Precondition Failed for url:" # from rebooted speakers. if response and response.status_code != 412: response.raise_for_status()
python
def unsubscribe(self): # Trying to unsubscribe if already unsubscribed, or not yet # subscribed, fails silently if self._has_been_unsubscribed or not self.is_subscribed: return # Cancel any auto renew self._auto_renew_thread_flag.set() # Send an unsubscribe request like this: # UNSUBSCRIBE publisher path HTTP/1.1 # HOST: publisher host:publisher port # SID: uuid:subscription UUID headers = { 'SID': self.sid } response = None try: response = requests.request( 'UNSUBSCRIBE', self.service.base_url + self.service.event_subscription_url, headers=headers, timeout=3) except requests.exceptions.RequestException: pass self.is_subscribed = False self._timestamp = None log.info( "Unsubscribed from %s, sid: %s", self.service.base_url + self.service.event_subscription_url, self.sid) # remove queue from event queues and sid to service mappings with _subscriptions_lock: try: del _subscriptions[self.sid] except KeyError: pass self._has_been_unsubscribed = True # Ignore "412 Client Error: Precondition Failed for url:" # from rebooted speakers. if response and response.status_code != 412: response.raise_for_status()
[ "def", "unsubscribe", "(", "self", ")", ":", "# Trying to unsubscribe if already unsubscribed, or not yet", "# subscribed, fails silently", "if", "self", ".", "_has_been_unsubscribed", "or", "not", "self", ".", "is_subscribed", ":", "return", "# Cancel any auto renew", "self"...
Unsubscribe from the service's events. Once unsubscribed, a Subscription instance should not be reused
[ "Unsubscribe", "from", "the", "service", "s", "events", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/events.py#L586-L633
22,850
amelchio/pysonos
pysonos/core.py
SoCo.play_mode
def play_mode(self, playmode): """Set the speaker's mode.""" playmode = playmode.upper() if playmode not in PLAY_MODES.keys(): raise KeyError("'%s' is not a valid play mode" % playmode) self.avTransport.SetPlayMode([ ('InstanceID', 0), ('NewPlayMode', playmode) ])
python
def play_mode(self, playmode): playmode = playmode.upper() if playmode not in PLAY_MODES.keys(): raise KeyError("'%s' is not a valid play mode" % playmode) self.avTransport.SetPlayMode([ ('InstanceID', 0), ('NewPlayMode', playmode) ])
[ "def", "play_mode", "(", "self", ",", "playmode", ")", ":", "playmode", "=", "playmode", ".", "upper", "(", ")", "if", "playmode", "not", "in", "PLAY_MODES", ".", "keys", "(", ")", ":", "raise", "KeyError", "(", "\"'%s' is not a valid play mode\"", "%", "p...
Set the speaker's mode.
[ "Set", "the", "speaker", "s", "mode", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L408-L417
22,851
amelchio/pysonos
pysonos/core.py
SoCo.repeat
def repeat(self, repeat): """Set the queue's repeat option""" shuffle = self.shuffle self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)]
python
def repeat(self, repeat): shuffle = self.shuffle self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)]
[ "def", "repeat", "(", "self", ",", "repeat", ")", ":", "shuffle", "=", "self", ".", "shuffle", "self", ".", "play_mode", "=", "PLAY_MODE_BY_MEANING", "[", "(", "shuffle", ",", "repeat", ")", "]" ]
Set the queue's repeat option
[ "Set", "the", "queue", "s", "repeat", "option" ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L444-L447
22,852
amelchio/pysonos
pysonos/core.py
SoCo.join
def join(self, master): """Join this speaker to another "master" speaker.""" self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', 'x-rincon:{0}'.format(master.uid)), ('CurrentURIMetaData', '') ]) self._zgs_cache.clear() self._parse_zone_group_state()
python
def join(self, master): self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', 'x-rincon:{0}'.format(master.uid)), ('CurrentURIMetaData', '') ]) self._zgs_cache.clear() self._parse_zone_group_state()
[ "def", "join", "(", "self", ",", "master", ")", ":", "self", ".", "avTransport", ".", "SetAVTransportURI", "(", "[", "(", "'InstanceID'", ",", "0", ")", ",", "(", "'CurrentURI'", ",", "'x-rincon:{0}'", ".", "format", "(", "master", ".", "uid", ")", ")"...
Join this speaker to another "master" speaker.
[ "Join", "this", "speaker", "to", "another", "master", "speaker", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L1079-L1087
22,853
amelchio/pysonos
pysonos/core.py
SoCo.unjoin
def unjoin(self): """Remove this speaker from a group. Seems to work ok even if you remove what was previously the group master from it's own group. If the speaker was not in a group also returns ok. """ self.avTransport.BecomeCoordinatorOfStandaloneGroup([ ('InstanceID', 0) ]) self._zgs_cache.clear() self._parse_zone_group_state()
python
def unjoin(self): self.avTransport.BecomeCoordinatorOfStandaloneGroup([ ('InstanceID', 0) ]) self._zgs_cache.clear() self._parse_zone_group_state()
[ "def", "unjoin", "(", "self", ")", ":", "self", ".", "avTransport", ".", "BecomeCoordinatorOfStandaloneGroup", "(", "[", "(", "'InstanceID'", ",", "0", ")", "]", ")", "self", ".", "_zgs_cache", ".", "clear", "(", ")", "self", ".", "_parse_zone_group_state", ...
Remove this speaker from a group. Seems to work ok even if you remove what was previously the group master from it's own group. If the speaker was not in a group also returns ok.
[ "Remove", "this", "speaker", "from", "a", "group", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L1089-L1101
22,854
amelchio/pysonos
pysonos/core.py
SoCo.set_sleep_timer
def set_sleep_timer(self, sleep_time_seconds): """Sets the sleep timer. Args: sleep_time_seconds (int or NoneType): How long to wait before turning off speaker in seconds, None to cancel a sleep timer. Maximum value of 86399 Raises: SoCoException: Upon errors interacting with Sonos controller ValueError: Argument/Syntax errors """ # Note: A value of None for sleep_time_seconds is valid, and needs to # be preserved distinctly separate from 0. 0 means go to sleep now, # which will immediately start the sound tappering, and could be a # useful feature, while None means cancel the current timer try: if sleep_time_seconds is None: sleep_time = '' else: sleep_time = format( datetime.timedelta(seconds=int(sleep_time_seconds)) ) self.avTransport.ConfigureSleepTimer([ ('InstanceID', 0), ('NewSleepTimerDuration', sleep_time), ]) except SoCoUPnPException as err: if 'Error 402 received' in str(err): raise ValueError('invalid sleep_time_seconds, must be integer \ value between 0 and 86399 inclusive or None') raise except ValueError: raise ValueError('invalid sleep_time_seconds, must be integer \ value between 0 and 86399 inclusive or None')
python
def set_sleep_timer(self, sleep_time_seconds): # Note: A value of None for sleep_time_seconds is valid, and needs to # be preserved distinctly separate from 0. 0 means go to sleep now, # which will immediately start the sound tappering, and could be a # useful feature, while None means cancel the current timer try: if sleep_time_seconds is None: sleep_time = '' else: sleep_time = format( datetime.timedelta(seconds=int(sleep_time_seconds)) ) self.avTransport.ConfigureSleepTimer([ ('InstanceID', 0), ('NewSleepTimerDuration', sleep_time), ]) except SoCoUPnPException as err: if 'Error 402 received' in str(err): raise ValueError('invalid sleep_time_seconds, must be integer \ value between 0 and 86399 inclusive or None') raise except ValueError: raise ValueError('invalid sleep_time_seconds, must be integer \ value between 0 and 86399 inclusive or None')
[ "def", "set_sleep_timer", "(", "self", ",", "sleep_time_seconds", ")", ":", "# Note: A value of None for sleep_time_seconds is valid, and needs to", "# be preserved distinctly separate from 0. 0 means go to sleep now,", "# which will immediately start the sound tappering, and could be a", "# u...
Sets the sleep timer. Args: sleep_time_seconds (int or NoneType): How long to wait before turning off speaker in seconds, None to cancel a sleep timer. Maximum value of 86399 Raises: SoCoException: Upon errors interacting with Sonos controller ValueError: Argument/Syntax errors
[ "Sets", "the", "sleep", "timer", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L1714-L1749
22,855
amelchio/pysonos
pysonos/snapshot.py
Snapshot._restore_coordinator
def _restore_coordinator(self): """Do the coordinator-only part of the restore.""" # Start by ensuring that the speaker is paused as we don't want # things all rolling back when we are changing them, as this could # include things like audio transport_info = self.device.get_current_transport_info() if transport_info is not None: if transport_info['current_transport_state'] == 'PLAYING': self.device.pause() # Check if the queue should be restored self._restore_queue() # Reinstate what was playing if self.is_playing_queue and self.playlist_position > 0: # was playing from playlist if self.playlist_position is not None: # The position in the playlist returned by # get_current_track_info starts at 1, but when # playing from playlist, the index starts at 0 # if position > 0: self.playlist_position -= 1 self.device.play_from_queue(self.playlist_position, False) if self.track_position is not None: if self.track_position != "": self.device.seek(self.track_position) # reinstate track, position, play mode, cross fade # Need to make sure there is a proper track selected first self.device.play_mode = self.play_mode self.device.cross_fade = self.cross_fade elif self.is_playing_cloud_queue: # was playing a cloud queue started by Alexa # No way yet to re-start this so prevent it throwing an error! pass else: # was playing a stream (radio station, file, or nothing) # reinstate uri and meta data if self.media_uri != "": self.device.play_uri( self.media_uri, self.media_metadata, start=False)
python
def _restore_coordinator(self): # Start by ensuring that the speaker is paused as we don't want # things all rolling back when we are changing them, as this could # include things like audio transport_info = self.device.get_current_transport_info() if transport_info is not None: if transport_info['current_transport_state'] == 'PLAYING': self.device.pause() # Check if the queue should be restored self._restore_queue() # Reinstate what was playing if self.is_playing_queue and self.playlist_position > 0: # was playing from playlist if self.playlist_position is not None: # The position in the playlist returned by # get_current_track_info starts at 1, but when # playing from playlist, the index starts at 0 # if position > 0: self.playlist_position -= 1 self.device.play_from_queue(self.playlist_position, False) if self.track_position is not None: if self.track_position != "": self.device.seek(self.track_position) # reinstate track, position, play mode, cross fade # Need to make sure there is a proper track selected first self.device.play_mode = self.play_mode self.device.cross_fade = self.cross_fade elif self.is_playing_cloud_queue: # was playing a cloud queue started by Alexa # No way yet to re-start this so prevent it throwing an error! pass else: # was playing a stream (radio station, file, or nothing) # reinstate uri and meta data if self.media_uri != "": self.device.play_uri( self.media_uri, self.media_metadata, start=False)
[ "def", "_restore_coordinator", "(", "self", ")", ":", "# Start by ensuring that the speaker is paused as we don't want", "# things all rolling back when we are changing them, as this could", "# include things like audio", "transport_info", "=", "self", ".", "device", ".", "get_current_...
Do the coordinator-only part of the restore.
[ "Do", "the", "coordinator", "-", "only", "part", "of", "the", "restore", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/snapshot.py#L186-L231
22,856
amelchio/pysonos
pysonos/snapshot.py
Snapshot._restore_volume
def _restore_volume(self, fade): """Reinstate volume. Args: fade (bool): Whether volume should be faded up on restore. """ self.device.mute = self.mute # Can only change volume on device with fixed volume set to False # otherwise get uPnP error, so check first. Before issuing a network # command to check, fixed volume always has volume set to 100. # So only checked fixed volume if volume is 100. if self.volume == 100: fixed_vol = self.device.renderingControl.GetOutputFixed( [('InstanceID', 0)])['CurrentFixed'] else: fixed_vol = False # now set volume if not fixed if not fixed_vol: self.device.bass = self.bass self.device.treble = self.treble self.device.loudness = self.loudness if fade: # if fade requested in restore # set volume to 0 then fade up to saved volume (non blocking) self.device.volume = 0 self.device.ramp_to_volume(self.volume) else: # set volume self.device.volume = self.volume
python
def _restore_volume(self, fade): self.device.mute = self.mute # Can only change volume on device with fixed volume set to False # otherwise get uPnP error, so check first. Before issuing a network # command to check, fixed volume always has volume set to 100. # So only checked fixed volume if volume is 100. if self.volume == 100: fixed_vol = self.device.renderingControl.GetOutputFixed( [('InstanceID', 0)])['CurrentFixed'] else: fixed_vol = False # now set volume if not fixed if not fixed_vol: self.device.bass = self.bass self.device.treble = self.treble self.device.loudness = self.loudness if fade: # if fade requested in restore # set volume to 0 then fade up to saved volume (non blocking) self.device.volume = 0 self.device.ramp_to_volume(self.volume) else: # set volume self.device.volume = self.volume
[ "def", "_restore_volume", "(", "self", ",", "fade", ")", ":", "self", ".", "device", ".", "mute", "=", "self", ".", "mute", "# Can only change volume on device with fixed volume set to False", "# otherwise get uPnP error, so check first. Before issuing a network", "# command to...
Reinstate volume. Args: fade (bool): Whether volume should be faded up on restore.
[ "Reinstate", "volume", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/snapshot.py#L233-L264
22,857
amelchio/pysonos
pysonos/discovery.py
discover_thread
def discover_thread(callback, timeout=5, include_invisible=False, interface_addr=None): """ Return a started thread with a discovery callback. """ thread = StoppableThread( target=_discover_thread, args=(callback, timeout, include_invisible, interface_addr)) thread.start() return thread
python
def discover_thread(callback, timeout=5, include_invisible=False, interface_addr=None): thread = StoppableThread( target=_discover_thread, args=(callback, timeout, include_invisible, interface_addr)) thread.start() return thread
[ "def", "discover_thread", "(", "callback", ",", "timeout", "=", "5", ",", "include_invisible", "=", "False", ",", "interface_addr", "=", "None", ")", ":", "thread", "=", "StoppableThread", "(", "target", "=", "_discover_thread", ",", "args", "=", "(", "callb...
Return a started thread with a discovery callback.
[ "Return", "a", "started", "thread", "with", "a", "discovery", "callback", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/discovery.py#L162-L171
22,858
amelchio/pysonos
pysonos/discovery.py
by_name
def by_name(name): """Return a device by name. Args: name (str): The name of the device to return. Returns: :class:`~.SoCo`: The first device encountered among all zone with the given player name. If none are found `None` is returned. """ devices = discover(all_households=True) for device in (devices or []): if device.player_name == name: return device return None
python
def by_name(name): devices = discover(all_households=True) for device in (devices or []): if device.player_name == name: return device return None
[ "def", "by_name", "(", "name", ")", ":", "devices", "=", "discover", "(", "all_households", "=", "True", ")", "for", "device", "in", "(", "devices", "or", "[", "]", ")", ":", "if", "device", ".", "player_name", "==", "name", ":", "return", "device", ...
Return a device by name. Args: name (str): The name of the device to return. Returns: :class:`~.SoCo`: The first device encountered among all zone with the given player name. If none are found `None` is returned.
[ "Return", "a", "device", "by", "name", "." ]
23527c445a00e198fbb94d44b92f7f99d139e325
https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/discovery.py#L262-L276
22,859
vsoch/pokemon
pokemon/master.py
get_trainer
def get_trainer(name): '''return the unique id for a trainer, determined by the md5 sum ''' name = name.lower() return int(hashlib.md5(name.encode('utf-8')).hexdigest(), 16) % 10**8
python
def get_trainer(name): '''return the unique id for a trainer, determined by the md5 sum ''' name = name.lower() return int(hashlib.md5(name.encode('utf-8')).hexdigest(), 16) % 10**8
[ "def", "get_trainer", "(", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "return", "int", "(", "hashlib", ".", "md5", "(", "name", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", ",", "16", ")", "%", "10", ...
return the unique id for a trainer, determined by the md5 sum
[ "return", "the", "unique", "id", "for", "a", "trainer", "determined", "by", "the", "md5", "sum" ]
c9cd8c5d64897617867d38d45183476ea64a0620
https://github.com/vsoch/pokemon/blob/c9cd8c5d64897617867d38d45183476ea64a0620/pokemon/master.py#L64-L68
22,860
vsoch/pokemon
pokemon/convert.py
scale_image
def scale_image(image, new_width): """Resizes an image preserving the aspect ratio. """ (original_width, original_height) = image.size aspect_ratio = original_height/float(original_width) new_height = int(aspect_ratio * new_width) # This scales it wider than tall, since characters are biased new_image = image.resize((new_width*2, new_height)) return new_image
python
def scale_image(image, new_width): (original_width, original_height) = image.size aspect_ratio = original_height/float(original_width) new_height = int(aspect_ratio * new_width) # This scales it wider than tall, since characters are biased new_image = image.resize((new_width*2, new_height)) return new_image
[ "def", "scale_image", "(", "image", ",", "new_width", ")", ":", "(", "original_width", ",", "original_height", ")", "=", "image", ".", "size", "aspect_ratio", "=", "original_height", "/", "float", "(", "original_width", ")", "new_height", "=", "int", "(", "a...
Resizes an image preserving the aspect ratio.
[ "Resizes", "an", "image", "preserving", "the", "aspect", "ratio", "." ]
c9cd8c5d64897617867d38d45183476ea64a0620
https://github.com/vsoch/pokemon/blob/c9cd8c5d64897617867d38d45183476ea64a0620/pokemon/convert.py#L34-L43
22,861
vsoch/pokemon
pokemon/convert.py
map_pixels_to_ascii_chars
def map_pixels_to_ascii_chars(image, range_width=25): """Maps each pixel to an ascii char based on the range in which it lies. 0-255 is divided into 11 ranges of 25 pixels each. """ pixels_in_image = list(image.getdata()) pixels_to_chars = [ASCII_CHARS[pixel_value/range_width] for pixel_value in pixels_in_image] return "".join(pixels_to_chars)
python
def map_pixels_to_ascii_chars(image, range_width=25): pixels_in_image = list(image.getdata()) pixels_to_chars = [ASCII_CHARS[pixel_value/range_width] for pixel_value in pixels_in_image] return "".join(pixels_to_chars)
[ "def", "map_pixels_to_ascii_chars", "(", "image", ",", "range_width", "=", "25", ")", ":", "pixels_in_image", "=", "list", "(", "image", ".", "getdata", "(", ")", ")", "pixels_to_chars", "=", "[", "ASCII_CHARS", "[", "pixel_value", "/", "range_width", "]", "...
Maps each pixel to an ascii char based on the range in which it lies. 0-255 is divided into 11 ranges of 25 pixels each.
[ "Maps", "each", "pixel", "to", "an", "ascii", "char", "based", "on", "the", "range", "in", "which", "it", "lies", "." ]
c9cd8c5d64897617867d38d45183476ea64a0620
https://github.com/vsoch/pokemon/blob/c9cd8c5d64897617867d38d45183476ea64a0620/pokemon/convert.py#L48-L59
22,862
NLeSC/scriptcwl
scriptcwl/library.py
load_steps
def load_steps(working_dir=None, steps_dir=None, step_file=None, step_list=None): """Return a dictionary containing Steps read from file. Args: steps_dir (str, optional): path to directory containing CWL files. step_file (str, optional): path or http(s) url to a single CWL file. step_list (list, optional): a list of directories, urls or local file paths to CWL files or directories containing CWL files. Return: dict containing (name, Step) entries. """ if steps_dir is not None: step_files = glob.glob(os.path.join(steps_dir, '*.cwl')) elif step_file is not None: step_files = [step_file] elif step_list is not None: step_files = [] for path in step_list: if os.path.isdir(path): step_files += glob.glob(os.path.join(path, '*.cwl')) else: step_files.append(path) else: step_files = [] if working_dir is not None: step_files = sort_loading_order(step_files) steps = {} for f in step_files: if working_dir is not None: # Copy file to working_dir if not working_dir == os.path.dirname(f) and not is_url(f): copied_file = os.path.join(working_dir, os.path.basename(f)) shutil.copy2(f, copied_file) f = copied_file # Create steps try: s = Step(f) steps[s.name] = s except (NotImplementedError, ValidationException, PackedWorkflowException) as e: logger.warning(e) return steps
python
def load_steps(working_dir=None, steps_dir=None, step_file=None, step_list=None): if steps_dir is not None: step_files = glob.glob(os.path.join(steps_dir, '*.cwl')) elif step_file is not None: step_files = [step_file] elif step_list is not None: step_files = [] for path in step_list: if os.path.isdir(path): step_files += glob.glob(os.path.join(path, '*.cwl')) else: step_files.append(path) else: step_files = [] if working_dir is not None: step_files = sort_loading_order(step_files) steps = {} for f in step_files: if working_dir is not None: # Copy file to working_dir if not working_dir == os.path.dirname(f) and not is_url(f): copied_file = os.path.join(working_dir, os.path.basename(f)) shutil.copy2(f, copied_file) f = copied_file # Create steps try: s = Step(f) steps[s.name] = s except (NotImplementedError, ValidationException, PackedWorkflowException) as e: logger.warning(e) return steps
[ "def", "load_steps", "(", "working_dir", "=", "None", ",", "steps_dir", "=", "None", ",", "step_file", "=", "None", ",", "step_list", "=", "None", ")", ":", "if", "steps_dir", "is", "not", "None", ":", "step_files", "=", "glob", ".", "glob", "(", "os",...
Return a dictionary containing Steps read from file. Args: steps_dir (str, optional): path to directory containing CWL files. step_file (str, optional): path or http(s) url to a single CWL file. step_list (list, optional): a list of directories, urls or local file paths to CWL files or directories containing CWL files. Return: dict containing (name, Step) entries.
[ "Return", "a", "dictionary", "containing", "Steps", "read", "from", "file", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/library.py#L83-L131
22,863
NLeSC/scriptcwl
scriptcwl/library.py
load_yaml
def load_yaml(filename): """Return object in yaml file.""" with open(filename) as myfile: content = myfile.read() if "win" in sys.platform: content = content.replace("\\", "/") return yaml.safe_load(content)
python
def load_yaml(filename): with open(filename) as myfile: content = myfile.read() if "win" in sys.platform: content = content.replace("\\", "/") return yaml.safe_load(content)
[ "def", "load_yaml", "(", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "myfile", ":", "content", "=", "myfile", ".", "read", "(", ")", "if", "\"win\"", "in", "sys", ".", "platform", ":", "content", "=", "content", ".", "replace", ...
Return object in yaml file.
[ "Return", "object", "in", "yaml", "file", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/library.py#L134-L140
22,864
NLeSC/scriptcwl
scriptcwl/library.py
sort_loading_order
def sort_loading_order(step_files): """Sort step files into correct loading order. The correct loading order is first tools, then workflows without subworkflows, and then workflows with subworkflows. This order is required to avoid error messages when a working directory is used. """ tools = [] workflows = [] workflows_with_subworkflows = [] for f in step_files: # assume that urls are tools if f.startswith('http://') or f.startswith('https://'): tools.append(f) else: obj = load_yaml(f) if obj.get('class', '') == 'Workflow': if 'requirements' in obj.keys(): subw = {'class': 'SubworkflowFeatureRequirement'} if subw in obj['requirements']: workflows_with_subworkflows.append(f) else: workflows.append(f) else: workflows.append(f) else: tools.append(f) return tools + workflows + workflows_with_subworkflows
python
def sort_loading_order(step_files): tools = [] workflows = [] workflows_with_subworkflows = [] for f in step_files: # assume that urls are tools if f.startswith('http://') or f.startswith('https://'): tools.append(f) else: obj = load_yaml(f) if obj.get('class', '') == 'Workflow': if 'requirements' in obj.keys(): subw = {'class': 'SubworkflowFeatureRequirement'} if subw in obj['requirements']: workflows_with_subworkflows.append(f) else: workflows.append(f) else: workflows.append(f) else: tools.append(f) return tools + workflows + workflows_with_subworkflows
[ "def", "sort_loading_order", "(", "step_files", ")", ":", "tools", "=", "[", "]", "workflows", "=", "[", "]", "workflows_with_subworkflows", "=", "[", "]", "for", "f", "in", "step_files", ":", "# assume that urls are tools", "if", "f", ".", "startswith", "(", ...
Sort step files into correct loading order. The correct loading order is first tools, then workflows without subworkflows, and then workflows with subworkflows. This order is required to avoid error messages when a working directory is used.
[ "Sort", "step", "files", "into", "correct", "loading", "order", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/library.py#L143-L171
22,865
NLeSC/scriptcwl
scriptcwl/scriptcwl.py
load_cwl
def load_cwl(fname): """Load and validate CWL file using cwltool """ logger.debug('Loading CWL file "{}"'.format(fname)) # Fetching, preprocessing and validating cwl # Older versions of cwltool if legacy_cwltool: try: (document_loader, workflowobj, uri) = fetch_document(fname) (document_loader, _, processobj, metadata, uri) = \ validate_document(document_loader, workflowobj, uri) except TypeError: from cwltool.context import LoadingContext, getdefault from cwltool import workflow from cwltool.resolver import tool_resolver from cwltool.load_tool import resolve_tool_uri loadingContext = LoadingContext() loadingContext.construct_tool_object = getdefault( loadingContext.construct_tool_object, workflow.default_make_tool) loadingContext.resolver = getdefault(loadingContext.resolver, tool_resolver) uri, tool_file_uri = resolve_tool_uri( fname, resolver=loadingContext.resolver, fetcher_constructor=loadingContext.fetcher_constructor) document_loader, workflowobj, uri = fetch_document( uri, resolver=loadingContext.resolver, fetcher_constructor=loadingContext.fetcher_constructor) document_loader, avsc_names, processobj, metadata, uri = \ validate_document( document_loader, workflowobj, uri, loadingContext.overrides_list, {}, enable_dev=loadingContext.enable_dev, strict=loadingContext.strict, preprocess_only=False, fetcher_constructor=loadingContext.fetcher_constructor, skip_schemas=False, do_validate=loadingContext.do_validate) # Recent versions of cwltool else: (loading_context, workflowobj, uri) = fetch_document(fname) loading_context, uri = resolve_and_validate_document(loading_context, workflowobj, uri) document_loader = loading_context.loader processobj = workflowobj metadata = loading_context.metadata return document_loader, processobj, metadata, uri
python
def load_cwl(fname): logger.debug('Loading CWL file "{}"'.format(fname)) # Fetching, preprocessing and validating cwl # Older versions of cwltool if legacy_cwltool: try: (document_loader, workflowobj, uri) = fetch_document(fname) (document_loader, _, processobj, metadata, uri) = \ validate_document(document_loader, workflowobj, uri) except TypeError: from cwltool.context import LoadingContext, getdefault from cwltool import workflow from cwltool.resolver import tool_resolver from cwltool.load_tool import resolve_tool_uri loadingContext = LoadingContext() loadingContext.construct_tool_object = getdefault( loadingContext.construct_tool_object, workflow.default_make_tool) loadingContext.resolver = getdefault(loadingContext.resolver, tool_resolver) uri, tool_file_uri = resolve_tool_uri( fname, resolver=loadingContext.resolver, fetcher_constructor=loadingContext.fetcher_constructor) document_loader, workflowobj, uri = fetch_document( uri, resolver=loadingContext.resolver, fetcher_constructor=loadingContext.fetcher_constructor) document_loader, avsc_names, processobj, metadata, uri = \ validate_document( document_loader, workflowobj, uri, loadingContext.overrides_list, {}, enable_dev=loadingContext.enable_dev, strict=loadingContext.strict, preprocess_only=False, fetcher_constructor=loadingContext.fetcher_constructor, skip_schemas=False, do_validate=loadingContext.do_validate) # Recent versions of cwltool else: (loading_context, workflowobj, uri) = fetch_document(fname) loading_context, uri = resolve_and_validate_document(loading_context, workflowobj, uri) document_loader = loading_context.loader processobj = workflowobj metadata = loading_context.metadata return document_loader, processobj, metadata, uri
[ "def", "load_cwl", "(", "fname", ")", ":", "logger", ".", "debug", "(", "'Loading CWL file \"{}\"'", ".", "format", "(", "fname", ")", ")", "# Fetching, preprocessing and validating cwl", "# Older versions of cwltool", "if", "legacy_cwltool", ":", "try", ":", "(", "...
Load and validate CWL file using cwltool
[ "Load", "and", "validate", "CWL", "file", "using", "cwltool" ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/scriptcwl.py#L42-L93
22,866
NLeSC/scriptcwl
scriptcwl/step.py
Step.set_input
def set_input(self, p_name, value): """Set a Step's input variable to a certain value. The value comes either from a workflow input or output of a previous step. Args: name (str): the name of the Step input value (str): the name of the output variable that provides the value for this input. Raises: ValueError: The name provided is not a valid input name for this Step. """ name = self.python_names.get(p_name) if p_name is None or name not in self.get_input_names(): raise ValueError('Invalid input "{}"'.format(p_name)) self.step_inputs[name] = value
python
def set_input(self, p_name, value): name = self.python_names.get(p_name) if p_name is None or name not in self.get_input_names(): raise ValueError('Invalid input "{}"'.format(p_name)) self.step_inputs[name] = value
[ "def", "set_input", "(", "self", ",", "p_name", ",", "value", ")", ":", "name", "=", "self", ".", "python_names", ".", "get", "(", "p_name", ")", "if", "p_name", "is", "None", "or", "name", "not", "in", "self", ".", "get_input_names", "(", ")", ":", ...
Set a Step's input variable to a certain value. The value comes either from a workflow input or output of a previous step. Args: name (str): the name of the Step input value (str): the name of the output variable that provides the value for this input. Raises: ValueError: The name provided is not a valid input name for this Step.
[ "Set", "a", "Step", "s", "input", "variable", "to", "a", "certain", "value", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/step.py#L90-L108
22,867
NLeSC/scriptcwl
scriptcwl/step.py
Step.output_reference
def output_reference(self, name): """Return a reference to the given output for use in an input of a next Step. For a Step named `echo` that has an output called `echoed`, the reference `echo/echoed` is returned. Args: name (str): the name of the Step output Raises: ValueError: The name provided is not a valid output name for this Step. """ if name not in self.output_names: raise ValueError('Invalid output "{}"'.format(name)) return Reference(step_name=self.name_in_workflow, output_name=name)
python
def output_reference(self, name): if name not in self.output_names: raise ValueError('Invalid output "{}"'.format(name)) return Reference(step_name=self.name_in_workflow, output_name=name)
[ "def", "output_reference", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "output_names", ":", "raise", "ValueError", "(", "'Invalid output \"{}\"'", ".", "format", "(", "name", ")", ")", "return", "Reference", "(", "step_name", ...
Return a reference to the given output for use in an input of a next Step. For a Step named `echo` that has an output called `echoed`, the reference `echo/echoed` is returned. Args: name (str): the name of the Step output Raises: ValueError: The name provided is not a valid output name for this Step.
[ "Return", "a", "reference", "to", "the", "given", "output", "for", "use", "in", "an", "input", "of", "a", "next", "Step", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/step.py#L113-L128
22,868
NLeSC/scriptcwl
scriptcwl/step.py
Step._input_optional
def _input_optional(inp): """Returns True if a step input parameter is optional. Args: inp (dict): a dictionary representation of an input. Raises: ValueError: The inp provided is not valid. """ if 'default' in inp.keys(): return True typ = inp.get('type') if isinstance(typ, six.string_types): return typ.endswith('?') elif isinstance(typ, dict): # TODO: handle case where iput type is dict return False elif isinstance(typ, list): # The cwltool validation expands optional arguments to # [u'null', <type>] return bool(u'null' in typ) else: raise ValueError('Invalid input "{}"'.format(inp.get['id']))
python
def _input_optional(inp): if 'default' in inp.keys(): return True typ = inp.get('type') if isinstance(typ, six.string_types): return typ.endswith('?') elif isinstance(typ, dict): # TODO: handle case where iput type is dict return False elif isinstance(typ, list): # The cwltool validation expands optional arguments to # [u'null', <type>] return bool(u'null' in typ) else: raise ValueError('Invalid input "{}"'.format(inp.get['id']))
[ "def", "_input_optional", "(", "inp", ")", ":", "if", "'default'", "in", "inp", ".", "keys", "(", ")", ":", "return", "True", "typ", "=", "inp", ".", "get", "(", "'type'", ")", "if", "isinstance", "(", "typ", ",", "six", ".", "string_types", ")", "...
Returns True if a step input parameter is optional. Args: inp (dict): a dictionary representation of an input. Raises: ValueError: The inp provided is not valid.
[ "Returns", "True", "if", "a", "step", "input", "parameter", "is", "optional", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/step.py#L131-L154
22,869
NLeSC/scriptcwl
scriptcwl/step.py
Step.to_obj
def to_obj(self, wd=False, pack=False, relpath=None): """Return the step as an dict that can be written to a yaml file. Returns: dict: yaml representation of the step. """ obj = CommentedMap() if pack: obj['run'] = self.orig elif relpath is not None: if self.from_url: obj['run'] = self.run else: obj['run'] = os.path.relpath(self.run, relpath) elif wd: if self.from_url: obj['run'] = self.run else: obj['run'] = os.path.basename(self.run) else: obj['run'] = self.run obj['in'] = self.step_inputs obj['out'] = self.output_names if self.is_scattered: obj['scatter'] = self.scattered_inputs # scatter_method is optional when scattering over a single variable if self.scatter_method is not None: obj['scatterMethod'] = self.scatter_method return obj
python
def to_obj(self, wd=False, pack=False, relpath=None): obj = CommentedMap() if pack: obj['run'] = self.orig elif relpath is not None: if self.from_url: obj['run'] = self.run else: obj['run'] = os.path.relpath(self.run, relpath) elif wd: if self.from_url: obj['run'] = self.run else: obj['run'] = os.path.basename(self.run) else: obj['run'] = self.run obj['in'] = self.step_inputs obj['out'] = self.output_names if self.is_scattered: obj['scatter'] = self.scattered_inputs # scatter_method is optional when scattering over a single variable if self.scatter_method is not None: obj['scatterMethod'] = self.scatter_method return obj
[ "def", "to_obj", "(", "self", ",", "wd", "=", "False", ",", "pack", "=", "False", ",", "relpath", "=", "None", ")", ":", "obj", "=", "CommentedMap", "(", ")", "if", "pack", ":", "obj", "[", "'run'", "]", "=", "self", ".", "orig", "elif", "relpath...
Return the step as an dict that can be written to a yaml file. Returns: dict: yaml representation of the step.
[ "Return", "the", "step", "as", "an", "dict", "that", "can", "be", "written", "to", "a", "yaml", "file", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/step.py#L205-L234
22,870
NLeSC/scriptcwl
scriptcwl/step.py
Step.list_inputs
def list_inputs(self): """Return a string listing all the Step's input names and their types. The types are returned in a copy/pastable format, so if the type is `string`, `'string'` (with single quotes) is returned. Returns: str containing all input names and types. """ doc = [] for inp, typ in self.input_types.items(): if isinstance(typ, six.string_types): typ = "'{}'".format(typ) doc.append('{}: {}'.format(inp, typ)) return '\n'.join(doc)
python
def list_inputs(self): doc = [] for inp, typ in self.input_types.items(): if isinstance(typ, six.string_types): typ = "'{}'".format(typ) doc.append('{}: {}'.format(inp, typ)) return '\n'.join(doc)
[ "def", "list_inputs", "(", "self", ")", ":", "doc", "=", "[", "]", "for", "inp", ",", "typ", "in", "self", ".", "input_types", ".", "items", "(", ")", ":", "if", "isinstance", "(", "typ", ",", "six", ".", "string_types", ")", ":", "typ", "=", "\"...
Return a string listing all the Step's input names and their types. The types are returned in a copy/pastable format, so if the type is `string`, `'string'` (with single quotes) is returned. Returns: str containing all input names and types.
[ "Return", "a", "string", "listing", "all", "the", "Step", "s", "input", "names", "and", "their", "types", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/step.py#L251-L265
22,871
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator.load
def load(self, steps_dir=None, step_file=None, step_list=None): """Load CWL steps into the WorkflowGenerator's steps library. Adds steps (command line tools and workflows) to the ``WorkflowGenerator``'s steps library. These steps can be used to create workflows. Args: steps_dir (str): path to directory containing CWL files. All CWL in the directory are loaded. step_file (str): path to a file containing a CWL step that will be added to the steps library. """ self._closed() self.steps_library.load(steps_dir=steps_dir, step_file=step_file, step_list=step_list)
python
def load(self, steps_dir=None, step_file=None, step_list=None): self._closed() self.steps_library.load(steps_dir=steps_dir, step_file=step_file, step_list=step_list)
[ "def", "load", "(", "self", ",", "steps_dir", "=", "None", ",", "step_file", "=", "None", ",", "step_list", "=", "None", ")", ":", "self", ".", "_closed", "(", ")", "self", ".", "steps_library", ".", "load", "(", "steps_dir", "=", "steps_dir", ",", "...
Load CWL steps into the WorkflowGenerator's steps library. Adds steps (command line tools and workflows) to the ``WorkflowGenerator``'s steps library. These steps can be used to create workflows. Args: steps_dir (str): path to directory containing CWL files. All CWL in the directory are loaded. step_file (str): path to a file containing a CWL step that will be added to the steps library.
[ "Load", "CWL", "steps", "into", "the", "WorkflowGenerator", "s", "steps", "library", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L160-L176
22,872
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator._has_requirements
def _has_requirements(self): """Returns True if the workflow needs a requirements section. Returns: bool: True if the workflow needs a requirements section, False otherwise. """ self._closed() return any([self.has_workflow_step, self.has_scatter_requirement, self.has_multiple_inputs])
python
def _has_requirements(self): self._closed() return any([self.has_workflow_step, self.has_scatter_requirement, self.has_multiple_inputs])
[ "def", "_has_requirements", "(", "self", ")", ":", "self", ".", "_closed", "(", ")", "return", "any", "(", "[", "self", ".", "has_workflow_step", ",", "self", ".", "has_scatter_requirement", ",", "self", ".", "has_multiple_inputs", "]", ")" ]
Returns True if the workflow needs a requirements section. Returns: bool: True if the workflow needs a requirements section, False otherwise.
[ "Returns", "True", "if", "the", "workflow", "needs", "a", "requirements", "section", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L185-L195
22,873
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator.inputs
def inputs(self, name): """List input names and types of a step in the steps library. Args: name (str): name of a step in the steps library. """ self._closed() step = self._get_step(name, make_copy=False) return step.list_inputs()
python
def inputs(self, name): self._closed() step = self._get_step(name, make_copy=False) return step.list_inputs()
[ "def", "inputs", "(", "self", ",", "name", ")", ":", "self", ".", "_closed", "(", ")", "step", "=", "self", ".", "_get_step", "(", "name", ",", "make_copy", "=", "False", ")", "return", "step", ".", "list_inputs", "(", ")" ]
List input names and types of a step in the steps library. Args: name (str): name of a step in the steps library.
[ "List", "input", "names", "and", "types", "of", "a", "step", "in", "the", "steps", "library", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L197-L206
22,874
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator._add_step
def _add_step(self, step): """Add a step to the workflow. Args: step (Step): a step from the steps library. """ self._closed() self.has_workflow_step = self.has_workflow_step or step.is_workflow self.wf_steps[step.name_in_workflow] = step
python
def _add_step(self, step): self._closed() self.has_workflow_step = self.has_workflow_step or step.is_workflow self.wf_steps[step.name_in_workflow] = step
[ "def", "_add_step", "(", "self", ",", "step", ")", ":", "self", ".", "_closed", "(", ")", "self", ".", "has_workflow_step", "=", "self", ".", "has_workflow_step", "or", "step", ".", "is_workflow", "self", ".", "wf_steps", "[", "step", ".", "name_in_workflo...
Add a step to the workflow. Args: step (Step): a step from the steps library.
[ "Add", "a", "step", "to", "the", "workflow", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L208-L217
22,875
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator.add_input
def add_input(self, **kwargs): """Add workflow input. Args: kwargs (dict): A dict with a `name: type` item and optionally a `default: value` item, where name is the name (id) of the workflow input (e.g., `dir_in`) and type is the type of the input (e.g., `'Directory'`). The type of input parameter can be learned from `step.inputs(step_name=input_name)`. Returns: inputname Raises: ValueError: No or multiple parameter(s) have been specified. """ self._closed() def _get_item(args): """Get a single item from args.""" if not args: raise ValueError("No parameter specified.") item = args.popitem() if args: raise ValueError("Too many parameters, not clear what to do " "with {}".format(kwargs)) return item symbols = None input_dict = CommentedMap() if 'default' in kwargs: input_dict['default'] = kwargs.pop('default') if 'label' in kwargs: input_dict['label'] = kwargs.pop('label') if 'symbols' in kwargs: symbols = kwargs.pop('symbols') name, input_type = _get_item(kwargs) if input_type == 'enum': typ = CommentedMap() typ['type'] = 'enum' # make sure symbols is set if symbols is None: raise ValueError("Please specify the enum's symbols.") # make sure symbols is not empty if symbols == []: raise ValueError("The enum's symbols cannot be empty.") # make sure the symbols are a list if type(symbols) != list: raise ValueError('Symbols should be a list.') # make sure symbols is a list of strings symbols = [str(s) for s in symbols] typ['symbols'] = symbols input_dict['type'] = typ else: # Set the 'type' if we can't use simple notation (because there is # a default value or a label) if bool(input_dict): input_dict['type'] = input_type msg = '"{}" is already used as a workflow input. Please use a ' +\ 'different name.' if name in self.wf_inputs: raise ValueError(msg.format(name)) # Add 'type' for complex input types, so the user doesn't have to do it if isinstance(input_type, dict): input_dict['type'] = input_type # Make sure we can use the notation without 'type' if the input allows # it. if bool(input_dict): self.wf_inputs[name] = input_dict else: self.wf_inputs[name] = input_type return Reference(input_name=name)
python
def add_input(self, **kwargs): self._closed() def _get_item(args): """Get a single item from args.""" if not args: raise ValueError("No parameter specified.") item = args.popitem() if args: raise ValueError("Too many parameters, not clear what to do " "with {}".format(kwargs)) return item symbols = None input_dict = CommentedMap() if 'default' in kwargs: input_dict['default'] = kwargs.pop('default') if 'label' in kwargs: input_dict['label'] = kwargs.pop('label') if 'symbols' in kwargs: symbols = kwargs.pop('symbols') name, input_type = _get_item(kwargs) if input_type == 'enum': typ = CommentedMap() typ['type'] = 'enum' # make sure symbols is set if symbols is None: raise ValueError("Please specify the enum's symbols.") # make sure symbols is not empty if symbols == []: raise ValueError("The enum's symbols cannot be empty.") # make sure the symbols are a list if type(symbols) != list: raise ValueError('Symbols should be a list.') # make sure symbols is a list of strings symbols = [str(s) for s in symbols] typ['symbols'] = symbols input_dict['type'] = typ else: # Set the 'type' if we can't use simple notation (because there is # a default value or a label) if bool(input_dict): input_dict['type'] = input_type msg = '"{}" is already used as a workflow input. Please use a ' +\ 'different name.' if name in self.wf_inputs: raise ValueError(msg.format(name)) # Add 'type' for complex input types, so the user doesn't have to do it if isinstance(input_type, dict): input_dict['type'] = input_type # Make sure we can use the notation without 'type' if the input allows # it. if bool(input_dict): self.wf_inputs[name] = input_dict else: self.wf_inputs[name] = input_type return Reference(input_name=name)
[ "def", "add_input", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_closed", "(", ")", "def", "_get_item", "(", "args", ")", ":", "\"\"\"Get a single item from args.\"\"\"", "if", "not", "args", ":", "raise", "ValueError", "(", "\"No parameter...
Add workflow input. Args: kwargs (dict): A dict with a `name: type` item and optionally a `default: value` item, where name is the name (id) of the workflow input (e.g., `dir_in`) and type is the type of the input (e.g., `'Directory'`). The type of input parameter can be learned from `step.inputs(step_name=input_name)`. Returns: inputname Raises: ValueError: No or multiple parameter(s) have been specified.
[ "Add", "workflow", "input", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L219-L299
22,876
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator.add_outputs
def add_outputs(self, **kwargs): """Add workflow outputs. The output type is added automatically, based on the steps in the steps library. Args: kwargs (dict): A dict containing ``name=source name`` pairs. ``name`` is the name of the workflow output (e.g., ``txt_files``) and source name is the name of the step that produced this output plus the output name (e.g., ``saf-to-txt/out_files``). """ self._closed() for name, source_name in kwargs.items(): obj = {} obj['outputSource'] = source_name obj['type'] = self.step_output_types[source_name] self.wf_outputs[name] = obj
python
def add_outputs(self, **kwargs): self._closed() for name, source_name in kwargs.items(): obj = {} obj['outputSource'] = source_name obj['type'] = self.step_output_types[source_name] self.wf_outputs[name] = obj
[ "def", "add_outputs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_closed", "(", ")", "for", "name", ",", "source_name", "in", "kwargs", ".", "items", "(", ")", ":", "obj", "=", "{", "}", "obj", "[", "'outputSource'", "]", "=", ...
Add workflow outputs. The output type is added automatically, based on the steps in the steps library. Args: kwargs (dict): A dict containing ``name=source name`` pairs. ``name`` is the name of the workflow output (e.g., ``txt_files``) and source name is the name of the step that produced this output plus the output name (e.g., ``saf-to-txt/out_files``).
[ "Add", "workflow", "outputs", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L301-L320
22,877
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator._get_step
def _get_step(self, name, make_copy=True): """Return step from steps library. Optionally, the step returned is a deep copy from the step in the steps library, so additional information (e.g., about whether the step was scattered) can be stored in the copy. Args: name (str): name of the step in the steps library. make_copy (bool): whether a deep copy of the step should be returned or not (default: True). Returns: Step from steps library. Raises: ValueError: The requested step cannot be found in the steps library. """ self._closed() s = self.steps_library.get_step(name) if s is None: msg = '"{}" not found in steps library. Please check your ' \ 'spelling or load additional steps' raise ValueError(msg.format(name)) if make_copy: s = copy.deepcopy(s) return s
python
def _get_step(self, name, make_copy=True): self._closed() s = self.steps_library.get_step(name) if s is None: msg = '"{}" not found in steps library. Please check your ' \ 'spelling or load additional steps' raise ValueError(msg.format(name)) if make_copy: s = copy.deepcopy(s) return s
[ "def", "_get_step", "(", "self", ",", "name", ",", "make_copy", "=", "True", ")", ":", "self", ".", "_closed", "(", ")", "s", "=", "self", ".", "steps_library", ".", "get_step", "(", "name", ")", "if", "s", "is", "None", ":", "msg", "=", "'\"{}\" n...
Return step from steps library. Optionally, the step returned is a deep copy from the step in the steps library, so additional information (e.g., about whether the step was scattered) can be stored in the copy. Args: name (str): name of the step in the steps library. make_copy (bool): whether a deep copy of the step should be returned or not (default: True). Returns: Step from steps library. Raises: ValueError: The requested step cannot be found in the steps library.
[ "Return", "step", "from", "steps", "library", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L342-L370
22,878
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator.to_obj
def to_obj(self, wd=False, pack=False, relpath=None): """Return the created workflow as a dict. The dict can be written to a yaml file. Returns: A yaml-compatible dict representing the workflow. """ self._closed() obj = CommentedMap() obj['cwlVersion'] = 'v1.0' obj['class'] = 'Workflow' try: obj['doc'] = self.documentation except (AttributeError, ValueError): pass try: obj['label'] = self.label except (AttributeError, ValueError): pass if self._has_requirements(): obj['requirements'] = [] if self.has_workflow_step: obj['requirements'].append( {'class': 'SubworkflowFeatureRequirement'}) if self.has_scatter_requirement: obj['requirements'].append({'class': 'ScatterFeatureRequirement'}) if self.has_multiple_inputs: obj['requirements'].append( {'class': 'MultipleInputFeatureRequirement'}) obj['inputs'] = self.wf_inputs obj['outputs'] = self.wf_outputs steps_obj = CommentedMap() for key in self.wf_steps: steps_obj[key] = self.wf_steps[key].to_obj(relpath=relpath, pack=pack, wd=wd) obj['steps'] = steps_obj return obj
python
def to_obj(self, wd=False, pack=False, relpath=None): self._closed() obj = CommentedMap() obj['cwlVersion'] = 'v1.0' obj['class'] = 'Workflow' try: obj['doc'] = self.documentation except (AttributeError, ValueError): pass try: obj['label'] = self.label except (AttributeError, ValueError): pass if self._has_requirements(): obj['requirements'] = [] if self.has_workflow_step: obj['requirements'].append( {'class': 'SubworkflowFeatureRequirement'}) if self.has_scatter_requirement: obj['requirements'].append({'class': 'ScatterFeatureRequirement'}) if self.has_multiple_inputs: obj['requirements'].append( {'class': 'MultipleInputFeatureRequirement'}) obj['inputs'] = self.wf_inputs obj['outputs'] = self.wf_outputs steps_obj = CommentedMap() for key in self.wf_steps: steps_obj[key] = self.wf_steps[key].to_obj(relpath=relpath, pack=pack, wd=wd) obj['steps'] = steps_obj return obj
[ "def", "to_obj", "(", "self", ",", "wd", "=", "False", ",", "pack", "=", "False", ",", "relpath", "=", "None", ")", ":", "self", ".", "_closed", "(", ")", "obj", "=", "CommentedMap", "(", ")", "obj", "[", "'cwlVersion'", "]", "=", "'v1.0'", "obj", ...
Return the created workflow as a dict. The dict can be written to a yaml file. Returns: A yaml-compatible dict representing the workflow.
[ "Return", "the", "created", "workflow", "as", "a", "dict", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L382-L423
22,879
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator.to_script
def to_script(self, wf_name='wf'): """Generated and print the scriptcwl script for the currunt workflow. Args: wf_name (str): string used for the WorkflowGenerator object in the generated script (default: ``wf``). """ self._closed() script = [] # Workflow documentation # if self.documentation: # if is_multiline(self.documentation): # print('doc = """') # print(self.documentation) # print('"""') # print('{}.set_documentation(doc)'.format(wf_name)) # else: # print('{}.set_documentation(\'{}\')'.format(wf_name, # self.documentation)) # Workflow inputs params = [] returns = [] for name, typ in self.wf_inputs.items(): params.append('{}=\'{}\''.format(name, typ)) returns.append(name) script.append('{} = {}.add_inputs({})'.format( ', '.join(returns), wf_name, ', '.join(params))) # Workflow steps returns = [] for name, step in self.wf_steps.items(): pyname = step.python_name returns = ['{}_{}'.format(pyname, o) for o in step['out']] params = ['{}={}'.format(name, python_name(param)) for name, param in step['in'].items()] script.append('{} = {}.{}({})'.format( ', '.join(returns), wf_name, pyname, ', '.join(params))) # Workflow outputs params = [] for name, details in self.wf_outputs.items(): params.append('{}={}'.format( name, python_name(details['outputSource']))) script.append('{}.add_outputs({})'.format(wf_name, ', '.join(params))) return '\n'.join(script)
python
def to_script(self, wf_name='wf'): self._closed() script = [] # Workflow documentation # if self.documentation: # if is_multiline(self.documentation): # print('doc = """') # print(self.documentation) # print('"""') # print('{}.set_documentation(doc)'.format(wf_name)) # else: # print('{}.set_documentation(\'{}\')'.format(wf_name, # self.documentation)) # Workflow inputs params = [] returns = [] for name, typ in self.wf_inputs.items(): params.append('{}=\'{}\''.format(name, typ)) returns.append(name) script.append('{} = {}.add_inputs({})'.format( ', '.join(returns), wf_name, ', '.join(params))) # Workflow steps returns = [] for name, step in self.wf_steps.items(): pyname = step.python_name returns = ['{}_{}'.format(pyname, o) for o in step['out']] params = ['{}={}'.format(name, python_name(param)) for name, param in step['in'].items()] script.append('{} = {}.{}({})'.format( ', '.join(returns), wf_name, pyname, ', '.join(params))) # Workflow outputs params = [] for name, details in self.wf_outputs.items(): params.append('{}={}'.format( name, python_name(details['outputSource']))) script.append('{}.add_outputs({})'.format(wf_name, ', '.join(params))) return '\n'.join(script)
[ "def", "to_script", "(", "self", ",", "wf_name", "=", "'wf'", ")", ":", "self", ".", "_closed", "(", ")", "script", "=", "[", "]", "# Workflow documentation", "# if self.documentation:", "# if is_multiline(self.documentation):", "# print('doc = \"\"\"')", "# ...
Generated and print the scriptcwl script for the currunt workflow. Args: wf_name (str): string used for the WorkflowGenerator object in the generated script (default: ``wf``).
[ "Generated", "and", "print", "the", "scriptcwl", "script", "for", "the", "currunt", "workflow", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L425-L473
22,880
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator._types_match
def _types_match(type1, type2): """Returns False only if it can show that no value of type1 can possibly match type2. Supports only a limited selection of types. """ if isinstance(type1, six.string_types) and \ isinstance(type2, six.string_types): type1 = type1.rstrip('?') type2 = type2.rstrip('?') if type1 != type2: return False return True
python
def _types_match(type1, type2): if isinstance(type1, six.string_types) and \ isinstance(type2, six.string_types): type1 = type1.rstrip('?') type2 = type2.rstrip('?') if type1 != type2: return False return True
[ "def", "_types_match", "(", "type1", ",", "type2", ")", ":", "if", "isinstance", "(", "type1", ",", "six", ".", "string_types", ")", "and", "isinstance", "(", "type2", ",", "six", ".", "string_types", ")", ":", "type1", "=", "type1", ".", "rstrip", "("...
Returns False only if it can show that no value of type1 can possibly match type2. Supports only a limited selection of types.
[ "Returns", "False", "only", "if", "it", "can", "show", "that", "no", "value", "of", "type1", "can", "possibly", "match", "type2", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L506-L519
22,881
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator.validate
def validate(self): """Validate workflow object. This method currently validates the workflow object with the use of cwltool. It writes the workflow to a tmp CWL file, reads it, validates it and removes the tmp file again. By default, the workflow is written to file using absolute paths to the steps. """ # define tmpfile (fd, tmpfile) = tempfile.mkstemp() os.close(fd) try: # save workflow object to tmpfile, # do not recursively call validate function self.save(tmpfile, mode='abs', validate=False) # load workflow from tmpfile document_loader, processobj, metadata, uri = load_cwl(tmpfile) finally: # cleanup tmpfile os.remove(tmpfile)
python
def validate(self): # define tmpfile (fd, tmpfile) = tempfile.mkstemp() os.close(fd) try: # save workflow object to tmpfile, # do not recursively call validate function self.save(tmpfile, mode='abs', validate=False) # load workflow from tmpfile document_loader, processobj, metadata, uri = load_cwl(tmpfile) finally: # cleanup tmpfile os.remove(tmpfile)
[ "def", "validate", "(", "self", ")", ":", "# define tmpfile", "(", "fd", ",", "tmpfile", ")", "=", "tempfile", ".", "mkstemp", "(", ")", "os", ".", "close", "(", "fd", ")", "try", ":", "# save workflow object to tmpfile,", "# do not recursively call validate fun...
Validate workflow object. This method currently validates the workflow object with the use of cwltool. It writes the workflow to a tmp CWL file, reads it, validates it and removes the tmp file again. By default, the workflow is written to file using absolute paths to the steps.
[ "Validate", "workflow", "object", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L652-L671
22,882
NLeSC/scriptcwl
scriptcwl/workflow.py
WorkflowGenerator.save
def save(self, fname, mode=None, validate=True, encoding='utf-8', wd=False, inline=False, relative=False, pack=False): """Save the workflow to file. Save the workflow to a CWL file that can be run with a CWL runner. Args: fname (str): file to save the workflow to. mode (str): one of (rel, abs, wd, inline, pack) encoding (str): file encoding to use (default: ``utf-8``). """ self._closed() if mode is None: mode = 'abs' if pack: mode = 'pack' elif wd: mode = 'wd' elif relative: mode = 'rel' msg = 'Using deprecated save method. Please save the workflow ' \ 'with: wf.save(\'{}\', mode=\'{}\'). Redirecting to new ' \ 'save method.'.format(fname, mode) warnings.warn(msg, DeprecationWarning) modes = ('rel', 'abs', 'wd', 'inline', 'pack') if mode not in modes: msg = 'Illegal mode "{}". Choose one of ({}).'\ .format(mode, ','.join(modes)) raise ValueError(msg) if validate: self.validate() dirname = os.path.dirname(os.path.abspath(fname)) if not os.path.exists(dirname): os.makedirs(dirname) if mode == 'inline': msg = ('Inline saving is deprecated. Please save the workflow ' 'using mode=\'pack\'. Setting mode to pack.') warnings.warn(msg, DeprecationWarning) mode = 'pack' if mode == 'rel': relpath = dirname save_yaml(fname=fname, wf=self, pack=False, relpath=relpath, wd=False) if mode == 'abs': save_yaml(fname=fname, wf=self, pack=False, relpath=None, wd=False) if mode == 'pack': self._pack(fname, encoding) if mode == 'wd': if self.get_working_dir() is None: raise ValueError('Working directory not set.') else: # save in working_dir bn = os.path.basename(fname) wd_file = os.path.join(self.working_dir, bn) save_yaml(fname=wd_file, wf=self, pack=False, relpath=None, wd=True) # and copy workflow file to other location (as though all steps # are in the same directory as the workflow) try: shutil.copy2(wd_file, fname) except shutil.Error: pass
python
def save(self, fname, mode=None, validate=True, encoding='utf-8', wd=False, inline=False, relative=False, pack=False): self._closed() if mode is None: mode = 'abs' if pack: mode = 'pack' elif wd: mode = 'wd' elif relative: mode = 'rel' msg = 'Using deprecated save method. Please save the workflow ' \ 'with: wf.save(\'{}\', mode=\'{}\'). Redirecting to new ' \ 'save method.'.format(fname, mode) warnings.warn(msg, DeprecationWarning) modes = ('rel', 'abs', 'wd', 'inline', 'pack') if mode not in modes: msg = 'Illegal mode "{}". Choose one of ({}).'\ .format(mode, ','.join(modes)) raise ValueError(msg) if validate: self.validate() dirname = os.path.dirname(os.path.abspath(fname)) if not os.path.exists(dirname): os.makedirs(dirname) if mode == 'inline': msg = ('Inline saving is deprecated. Please save the workflow ' 'using mode=\'pack\'. Setting mode to pack.') warnings.warn(msg, DeprecationWarning) mode = 'pack' if mode == 'rel': relpath = dirname save_yaml(fname=fname, wf=self, pack=False, relpath=relpath, wd=False) if mode == 'abs': save_yaml(fname=fname, wf=self, pack=False, relpath=None, wd=False) if mode == 'pack': self._pack(fname, encoding) if mode == 'wd': if self.get_working_dir() is None: raise ValueError('Working directory not set.') else: # save in working_dir bn = os.path.basename(fname) wd_file = os.path.join(self.working_dir, bn) save_yaml(fname=wd_file, wf=self, pack=False, relpath=None, wd=True) # and copy workflow file to other location (as though all steps # are in the same directory as the workflow) try: shutil.copy2(wd_file, fname) except shutil.Error: pass
[ "def", "save", "(", "self", ",", "fname", ",", "mode", "=", "None", ",", "validate", "=", "True", ",", "encoding", "=", "'utf-8'", ",", "wd", "=", "False", ",", "inline", "=", "False", ",", "relative", "=", "False", ",", "pack", "=", "False", ")", ...
Save the workflow to file. Save the workflow to a CWL file that can be run with a CWL runner. Args: fname (str): file to save the workflow to. mode (str): one of (rel, abs, wd, inline, pack) encoding (str): file encoding to use (default: ``utf-8``).
[ "Save", "the", "workflow", "to", "file", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/workflow.py#L692-L764
22,883
NLeSC/scriptcwl
scriptcwl/yamlutils.py
str_presenter
def str_presenter(dmpr, data): """Return correct str_presenter to write multiple lines to a yaml field. Source: http://stackoverflow.com/a/33300001 """ if is_multiline(data): return dmpr.represent_scalar('tag:yaml.org,2002:str', data, style='|') return dmpr.represent_scalar('tag:yaml.org,2002:str', data)
python
def str_presenter(dmpr, data): if is_multiline(data): return dmpr.represent_scalar('tag:yaml.org,2002:str', data, style='|') return dmpr.represent_scalar('tag:yaml.org,2002:str', data)
[ "def", "str_presenter", "(", "dmpr", ",", "data", ")", ":", "if", "is_multiline", "(", "data", ")", ":", "return", "dmpr", ".", "represent_scalar", "(", "'tag:yaml.org,2002:str'", ",", "data", ",", "style", "=", "'|'", ")", "return", "dmpr", ".", "represen...
Return correct str_presenter to write multiple lines to a yaml field. Source: http://stackoverflow.com/a/33300001
[ "Return", "correct", "str_presenter", "to", "write", "multiple", "lines", "to", "a", "yaml", "field", "." ]
33bb847a875379da3a5702c7a98dfa585306b960
https://github.com/NLeSC/scriptcwl/blob/33bb847a875379da3a5702c7a98dfa585306b960/scriptcwl/yamlutils.py#L22-L30
22,884
nschloe/colorio
experiments/new-cs.py
build_grad_matrices
def build_grad_matrices(V, points): """Build the sparse m-by-n matrices that map a coefficient set for a function in V to the values of dx and dy at a number m of points. """ # See <https://www.allanswered.com/post/lkbkm/#zxqgk> mesh = V.mesh() bbt = BoundingBoxTree() bbt.build(mesh) dofmap = V.dofmap() el = V.element() rows = [] cols = [] datax = [] datay = [] for i, xy in enumerate(points): cell_id = bbt.compute_first_entity_collision(Point(*xy)) cell = Cell(mesh, cell_id) coordinate_dofs = cell.get_vertex_coordinates() rows.append([i, i, i]) cols.append(dofmap.cell_dofs(cell_id)) v = el.evaluate_basis_derivatives_all(1, xy, coordinate_dofs, cell_id) v = v.reshape(3, 2) datax.append(v[:, 0]) datay.append(v[:, 1]) rows = numpy.concatenate(rows) cols = numpy.concatenate(cols) datax = numpy.concatenate(datax) datay = numpy.concatenate(datay) m = len(points) n = V.dim() dx_matrix = sparse.csr_matrix((datax, (rows, cols)), shape=(m, n)) dy_matrix = sparse.csr_matrix((datay, (rows, cols)), shape=(m, n)) return dx_matrix, dy_matrix
python
def build_grad_matrices(V, points): # See <https://www.allanswered.com/post/lkbkm/#zxqgk> mesh = V.mesh() bbt = BoundingBoxTree() bbt.build(mesh) dofmap = V.dofmap() el = V.element() rows = [] cols = [] datax = [] datay = [] for i, xy in enumerate(points): cell_id = bbt.compute_first_entity_collision(Point(*xy)) cell = Cell(mesh, cell_id) coordinate_dofs = cell.get_vertex_coordinates() rows.append([i, i, i]) cols.append(dofmap.cell_dofs(cell_id)) v = el.evaluate_basis_derivatives_all(1, xy, coordinate_dofs, cell_id) v = v.reshape(3, 2) datax.append(v[:, 0]) datay.append(v[:, 1]) rows = numpy.concatenate(rows) cols = numpy.concatenate(cols) datax = numpy.concatenate(datax) datay = numpy.concatenate(datay) m = len(points) n = V.dim() dx_matrix = sparse.csr_matrix((datax, (rows, cols)), shape=(m, n)) dy_matrix = sparse.csr_matrix((datay, (rows, cols)), shape=(m, n)) return dx_matrix, dy_matrix
[ "def", "build_grad_matrices", "(", "V", ",", "points", ")", ":", "# See <https://www.allanswered.com/post/lkbkm/#zxqgk>", "mesh", "=", "V", ".", "mesh", "(", ")", "bbt", "=", "BoundingBoxTree", "(", ")", "bbt", ".", "build", "(", "mesh", ")", "dofmap", "=", ...
Build the sparse m-by-n matrices that map a coefficient set for a function in V to the values of dx and dy at a number m of points.
[ "Build", "the", "sparse", "m", "-", "by", "-", "n", "matrices", "that", "map", "a", "coefficient", "set", "for", "a", "function", "in", "V", "to", "the", "values", "of", "dx", "and", "dy", "at", "a", "number", "m", "of", "points", "." ]
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/experiments/new-cs.py#L309-L346
22,885
nschloe/colorio
experiments/new-cs.py
PiecewiseEllipse.apply_M
def apply_M(self, ax, ay): """Linear operator that converts ax, ay to abcd. """ jac = numpy.array( [[self.dx.dot(ax), self.dy.dot(ax)], [self.dx.dot(ay), self.dy.dot(ay)]] ) # jacs and J are of shape (2, 2, k). M must be of the same shape and # contain the result of the k 2x2 dot products. Perhaps there's a # dot() for this. M = numpy.einsum("ijl,jkl->ikl", jac, self.J) # M = numpy.array([ # [ # jac[0][0]*self.J[0][0] + jac[0][1]*self.J[1][0], # jac[0][0]*self.J[0][1] + jac[0][1]*self.J[1][1], # ], # [ # jac[1][0]*self.J[0][0] + jac[1][1]*self.J[1][0], # jac[1][0]*self.J[0][1] + jac[1][1]*self.J[1][1], # ], # ]) # One could use # # M = numpy.moveaxis(M, -1, 0) # _, sigma, _ = numpy.linalg.svd(M) # # but computing the singular values explicitly via # <https://scicomp.stackexchange.com/a/14103/3980> is faster and more # explicit. a = (M[0, 0] + M[1, 1]) / 2 b = (M[0, 0] - M[1, 1]) / 2 c = (M[1, 0] + M[0, 1]) / 2 d = (M[1, 0] - M[0, 1]) / 2 return a, b, c, d
python
def apply_M(self, ax, ay): jac = numpy.array( [[self.dx.dot(ax), self.dy.dot(ax)], [self.dx.dot(ay), self.dy.dot(ay)]] ) # jacs and J are of shape (2, 2, k). M must be of the same shape and # contain the result of the k 2x2 dot products. Perhaps there's a # dot() for this. M = numpy.einsum("ijl,jkl->ikl", jac, self.J) # M = numpy.array([ # [ # jac[0][0]*self.J[0][0] + jac[0][1]*self.J[1][0], # jac[0][0]*self.J[0][1] + jac[0][1]*self.J[1][1], # ], # [ # jac[1][0]*self.J[0][0] + jac[1][1]*self.J[1][0], # jac[1][0]*self.J[0][1] + jac[1][1]*self.J[1][1], # ], # ]) # One could use # # M = numpy.moveaxis(M, -1, 0) # _, sigma, _ = numpy.linalg.svd(M) # # but computing the singular values explicitly via # <https://scicomp.stackexchange.com/a/14103/3980> is faster and more # explicit. a = (M[0, 0] + M[1, 1]) / 2 b = (M[0, 0] - M[1, 1]) / 2 c = (M[1, 0] + M[0, 1]) / 2 d = (M[1, 0] - M[0, 1]) / 2 return a, b, c, d
[ "def", "apply_M", "(", "self", ",", "ax", ",", "ay", ")", ":", "jac", "=", "numpy", ".", "array", "(", "[", "[", "self", ".", "dx", ".", "dot", "(", "ax", ")", ",", "self", ".", "dy", ".", "dot", "(", "ax", ")", "]", ",", "[", "self", "."...
Linear operator that converts ax, ay to abcd.
[ "Linear", "operator", "that", "converts", "ax", "ay", "to", "abcd", "." ]
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/experiments/new-cs.py#L423-L458
22,886
nschloe/colorio
experiments/new-cs.py
PiecewiseEllipse.cost_min2
def cost_min2(self, alpha): """Residual formulation, Hessian is a low-rank update of the identity. """ n = self.V.dim() ax = alpha[:n] ay = alpha[n:] # ml = pyamg.ruge_stuben_solver(self.L) # # ml = pyamg.smoothed_aggregation_solver(self.L) # print(ml) # print() # print(self.L) # print() # x = ml.solve(ax, tol=1e-10) # print('residual: {}'.format(numpy.linalg.norm(ax - self.L*x))) # print() # print(ax) # print() # print(x) # exit(1) # x = sparse.linalg.spsolve(self.L, ax) # print('residual: {}'.format(numpy.linalg.norm(ax - self.L*x))) # exit(1) q2, r2 = self.get_q2_r2(ax, ay) Lax = self.L * ax Lay = self.L * ay out = [ 0.5 * numpy.dot(Lax, Lax), 0.5 * numpy.dot(Lay, Lay), 0.5 * numpy.dot(q2 - 1, q2 - 1), 0.5 * numpy.dot(r2, r2), ] if self.num_f_eval % 10000 == 0: print("{:7d} {:e} {:e} {:e} {:e}".format(self.num_f_eval, *out)) self.num_f_eval += 1 return numpy.sum(out)
python
def cost_min2(self, alpha): n = self.V.dim() ax = alpha[:n] ay = alpha[n:] # ml = pyamg.ruge_stuben_solver(self.L) # # ml = pyamg.smoothed_aggregation_solver(self.L) # print(ml) # print() # print(self.L) # print() # x = ml.solve(ax, tol=1e-10) # print('residual: {}'.format(numpy.linalg.norm(ax - self.L*x))) # print() # print(ax) # print() # print(x) # exit(1) # x = sparse.linalg.spsolve(self.L, ax) # print('residual: {}'.format(numpy.linalg.norm(ax - self.L*x))) # exit(1) q2, r2 = self.get_q2_r2(ax, ay) Lax = self.L * ax Lay = self.L * ay out = [ 0.5 * numpy.dot(Lax, Lax), 0.5 * numpy.dot(Lay, Lay), 0.5 * numpy.dot(q2 - 1, q2 - 1), 0.5 * numpy.dot(r2, r2), ] if self.num_f_eval % 10000 == 0: print("{:7d} {:e} {:e} {:e} {:e}".format(self.num_f_eval, *out)) self.num_f_eval += 1 return numpy.sum(out)
[ "def", "cost_min2", "(", "self", ",", "alpha", ")", ":", "n", "=", "self", ".", "V", ".", "dim", "(", ")", "ax", "=", "alpha", "[", ":", "n", "]", "ay", "=", "alpha", "[", "n", ":", "]", "# ml = pyamg.ruge_stuben_solver(self.L)", "# # ml = pyamg.smooth...
Residual formulation, Hessian is a low-rank update of the identity.
[ "Residual", "formulation", "Hessian", "is", "a", "low", "-", "rank", "update", "of", "the", "identity", "." ]
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/experiments/new-cs.py#L757-L798
22,887
nschloe/colorio
colorio/tools.py
delta
def delta(a, b): """Computes the distances between two colors or color sets. The shape of `a` and `b` must be equal. """ diff = a - b return numpy.einsum("i...,i...->...", diff, diff)
python
def delta(a, b): diff = a - b return numpy.einsum("i...,i...->...", diff, diff)
[ "def", "delta", "(", "a", ",", "b", ")", ":", "diff", "=", "a", "-", "b", "return", "numpy", ".", "einsum", "(", "\"i...,i...->...\"", ",", "diff", ",", "diff", ")" ]
Computes the distances between two colors or color sets. The shape of `a` and `b` must be equal.
[ "Computes", "the", "distances", "between", "two", "colors", "or", "color", "sets", ".", "The", "shape", "of", "a", "and", "b", "must", "be", "equal", "." ]
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/colorio/tools.py#L24-L29
22,888
nschloe/colorio
colorio/tools.py
plot_flat_gamut
def plot_flat_gamut( xy_to_2d=lambda xy: xy, axes_labels=("x", "y"), plot_rgb_triangle=True, fill_horseshoe=True, plot_planckian_locus=True, ): """Show a flat color gamut, by default xy. There exists a chroma gamut for all color models which transform lines in XYZ to lines, and hence have a natural decomposition into lightness and chroma components. Also, the flat gamut is the same for every lightness value. Examples for color models with this property are CIELUV and IPT, examples for color models without are CIELAB and CIECAM02. """ observer = observers.cie_1931_2() # observer = observers.cie_1964_10() _plot_monochromatic(observer, xy_to_2d, fill_horseshoe=fill_horseshoe) # plt.grid() if plot_rgb_triangle: _plot_rgb_triangle(xy_to_2d) if plot_planckian_locus: _plot_planckian_locus(observer, xy_to_2d) plt.gca().set_aspect("equal") # plt.legend() plt.xlabel(axes_labels[0]) plt.ylabel(axes_labels[1]) return
python
def plot_flat_gamut( xy_to_2d=lambda xy: xy, axes_labels=("x", "y"), plot_rgb_triangle=True, fill_horseshoe=True, plot_planckian_locus=True, ): observer = observers.cie_1931_2() # observer = observers.cie_1964_10() _plot_monochromatic(observer, xy_to_2d, fill_horseshoe=fill_horseshoe) # plt.grid() if plot_rgb_triangle: _plot_rgb_triangle(xy_to_2d) if plot_planckian_locus: _plot_planckian_locus(observer, xy_to_2d) plt.gca().set_aspect("equal") # plt.legend() plt.xlabel(axes_labels[0]) plt.ylabel(axes_labels[1]) return
[ "def", "plot_flat_gamut", "(", "xy_to_2d", "=", "lambda", "xy", ":", "xy", ",", "axes_labels", "=", "(", "\"x\"", ",", "\"y\"", ")", ",", "plot_rgb_triangle", "=", "True", ",", "fill_horseshoe", "=", "True", ",", "plot_planckian_locus", "=", "True", ",", "...
Show a flat color gamut, by default xy. There exists a chroma gamut for all color models which transform lines in XYZ to lines, and hence have a natural decomposition into lightness and chroma components. Also, the flat gamut is the same for every lightness value. Examples for color models with this property are CIELUV and IPT, examples for color models without are CIELAB and CIECAM02.
[ "Show", "a", "flat", "color", "gamut", "by", "default", "xy", ".", "There", "exists", "a", "chroma", "gamut", "for", "all", "color", "models", "which", "transform", "lines", "in", "XYZ", "to", "lines", "and", "hence", "have", "a", "natural", "decomposition...
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/colorio/tools.py#L199-L228
22,889
nschloe/colorio
experiments/pade2d.py
_get_xy_tree
def _get_xy_tree(xy, degree): """Evaluates the entire tree of 2d mononomials. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (1, 0) (0, 1) (2, 0) (1, 1) (0, 2) ... ... ... """ x, y = xy tree = [numpy.array([numpy.ones(x.shape, dtype=int)])] for d in range(degree): tree.append(numpy.concatenate([tree[-1] * x, [tree[-1][-1] * y]])) return tree
python
def _get_xy_tree(xy, degree): x, y = xy tree = [numpy.array([numpy.ones(x.shape, dtype=int)])] for d in range(degree): tree.append(numpy.concatenate([tree[-1] * x, [tree[-1][-1] * y]])) return tree
[ "def", "_get_xy_tree", "(", "xy", ",", "degree", ")", ":", "x", ",", "y", "=", "xy", "tree", "=", "[", "numpy", ".", "array", "(", "[", "numpy", ".", "ones", "(", "x", ".", "shape", ",", "dtype", "=", "int", ")", "]", ")", "]", "for", "d", ...
Evaluates the entire tree of 2d mononomials. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (1, 0) (0, 1) (2, 0) (1, 1) (0, 2) ... ... ...
[ "Evaluates", "the", "entire", "tree", "of", "2d", "mononomials", "." ]
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/experiments/pade2d.py#L17-L32
22,890
nschloe/colorio
colorio/illuminants.py
spectrum_to_xyz100
def spectrum_to_xyz100(spectrum, observer): """Computes the tristimulus values XYZ from a given spectrum for a given observer via X_i = int_lambda spectrum_i(lambda) * observer_i(lambda) dlambda. In section 7, the technical report CIE Standard Illuminants for Colorimetry, 1999, gives a recommendation on how to perform the computation. """ lambda_o, data_o = observer lambda_s, data_s = spectrum # form the union of lambdas lmbda = numpy.sort(numpy.unique(numpy.concatenate([lambda_o, lambda_s]))) # The technical document prescribes that the integration be performed over # the wavelength range corresponding to the entire visible spectrum, 360 nm # to 830 nm. assert lmbda[0] < 361e-9 assert lmbda[-1] > 829e-9 # interpolate data idata_o = numpy.array([numpy.interp(lmbda, lambda_o, dt) for dt in data_o]) # The technical report specifies the interpolation techniques, too: # ``` # Use one of the four following methods to calculate needed but unmeasured # values of phi(l), R(l) or tau(l) within the range of measurements: # 1) the third-order polynomial interpolation (Lagrange) from the four # neighbouring data points around the point to be interpolated, or # 2) cubic spline interpolation formula, or # 3) a fifth order polynomial interpolation formula from the six # neighboring data points around the point to be interpolated, or # 4) a Sprague interpolation (see Seve, 2003). # ``` # Well, don't do that but simply use linear interpolation now. We only use # the midpoint rule for integration anyways. idata_s = numpy.interp(lmbda, lambda_s, data_s) # step sizes delta = numpy.zeros(len(lmbda)) diff = lmbda[1:] - lmbda[:-1] delta[1:] += diff delta[:-1] += diff delta /= 2 values = numpy.dot(idata_o, idata_s * delta) return values * 100
python
def spectrum_to_xyz100(spectrum, observer): lambda_o, data_o = observer lambda_s, data_s = spectrum # form the union of lambdas lmbda = numpy.sort(numpy.unique(numpy.concatenate([lambda_o, lambda_s]))) # The technical document prescribes that the integration be performed over # the wavelength range corresponding to the entire visible spectrum, 360 nm # to 830 nm. assert lmbda[0] < 361e-9 assert lmbda[-1] > 829e-9 # interpolate data idata_o = numpy.array([numpy.interp(lmbda, lambda_o, dt) for dt in data_o]) # The technical report specifies the interpolation techniques, too: # ``` # Use one of the four following methods to calculate needed but unmeasured # values of phi(l), R(l) or tau(l) within the range of measurements: # 1) the third-order polynomial interpolation (Lagrange) from the four # neighbouring data points around the point to be interpolated, or # 2) cubic spline interpolation formula, or # 3) a fifth order polynomial interpolation formula from the six # neighboring data points around the point to be interpolated, or # 4) a Sprague interpolation (see Seve, 2003). # ``` # Well, don't do that but simply use linear interpolation now. We only use # the midpoint rule for integration anyways. idata_s = numpy.interp(lmbda, lambda_s, data_s) # step sizes delta = numpy.zeros(len(lmbda)) diff = lmbda[1:] - lmbda[:-1] delta[1:] += diff delta[:-1] += diff delta /= 2 values = numpy.dot(idata_o, idata_s * delta) return values * 100
[ "def", "spectrum_to_xyz100", "(", "spectrum", ",", "observer", ")", ":", "lambda_o", ",", "data_o", "=", "observer", "lambda_s", ",", "data_s", "=", "spectrum", "# form the union of lambdas", "lmbda", "=", "numpy", ".", "sort", "(", "numpy", ".", "unique", "("...
Computes the tristimulus values XYZ from a given spectrum for a given observer via X_i = int_lambda spectrum_i(lambda) * observer_i(lambda) dlambda. In section 7, the technical report CIE Standard Illuminants for Colorimetry, 1999, gives a recommendation on how to perform the computation.
[ "Computes", "the", "tristimulus", "values", "XYZ", "from", "a", "given", "spectrum", "for", "a", "given", "observer", "via" ]
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/colorio/illuminants.py#L36-L84
22,891
nschloe/colorio
colorio/illuminants.py
d
def d(nominal_temperature): """CIE D-series illuminants. The technical report `Colorimetry, 3rd edition, 2004` gives the data for D50, D55, and D65 explicitly, but also explains how it's computed for S0, S1, S2. Values are given at 5nm resolution in the document, but really every other value is just interpolated. Hence, only provide 10 nm data here. """ # From CIE 15:2004. Colorimetry, 3rd edition, 2004 (page 69, note 5): # # The method required to calculate the values for the relative spectral # power distributions of illuminants D50, D55, D65, and D75, in Table T.1 # is as follows # 1. Multiply the nominal correlated colour temperature (5000 K, 5500 K, # 6500 K or 7500 K) by 1,4388/1,4380. # 2. Calculate XD and YD using the equations given in the text. # 3. Calculate M1 and M2 using the equations given in the text. # 4. Round M1 and M2 to three decimal places. # 5. Calculate S(lambda) every 10 nm by # S(lambda) = S0(lambda) + M1 S1(lambda) + M2 S2(lambda) # using values of S0(lambda), S1(lambda) and S2(lambda) from # Table T.2. # 6. Interpolate the 10 nm values of S(lambda) linearly to obtain values # at intermediate wavelengths. tcp = 1.4388e-2 / 1.4380e-2 * nominal_temperature if 4000 <= tcp <= 7000: xd = ((-4.6070e9 / tcp + 2.9678e6) / tcp + 0.09911e3) / tcp + 0.244063 else: assert 7000 < tcp <= 25000 xd = ((-2.0064e9 / tcp + 1.9018e6) / tcp + 0.24748e3) / tcp + 0.237040 yd = (-3.000 * xd + 2.870) * xd - 0.275 m1 = (-1.3515 - 1.7703 * xd + 5.9114 * yd) / (0.0241 + 0.2562 * xd - 0.7341 * yd) m2 = (+0.0300 - 31.4424 * xd + 30.0717 * yd) / (0.0241 + 0.2562 * xd - 0.7341 * yd) m1 = numpy.around(m1, decimals=3) m2 = numpy.around(m2, decimals=3) dir_path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(dir_path, "data/illuminants/d.yaml")) as f: data = yaml.safe_load(f) data = numpy.array(data).T lmbda = data[0] s = data[1:] return lmbda, s[0] + m1 * s[1] + m2 * s[2]
python
def d(nominal_temperature): # From CIE 15:2004. Colorimetry, 3rd edition, 2004 (page 69, note 5): # # The method required to calculate the values for the relative spectral # power distributions of illuminants D50, D55, D65, and D75, in Table T.1 # is as follows # 1. Multiply the nominal correlated colour temperature (5000 K, 5500 K, # 6500 K or 7500 K) by 1,4388/1,4380. # 2. Calculate XD and YD using the equations given in the text. # 3. Calculate M1 and M2 using the equations given in the text. # 4. Round M1 and M2 to three decimal places. # 5. Calculate S(lambda) every 10 nm by # S(lambda) = S0(lambda) + M1 S1(lambda) + M2 S2(lambda) # using values of S0(lambda), S1(lambda) and S2(lambda) from # Table T.2. # 6. Interpolate the 10 nm values of S(lambda) linearly to obtain values # at intermediate wavelengths. tcp = 1.4388e-2 / 1.4380e-2 * nominal_temperature if 4000 <= tcp <= 7000: xd = ((-4.6070e9 / tcp + 2.9678e6) / tcp + 0.09911e3) / tcp + 0.244063 else: assert 7000 < tcp <= 25000 xd = ((-2.0064e9 / tcp + 1.9018e6) / tcp + 0.24748e3) / tcp + 0.237040 yd = (-3.000 * xd + 2.870) * xd - 0.275 m1 = (-1.3515 - 1.7703 * xd + 5.9114 * yd) / (0.0241 + 0.2562 * xd - 0.7341 * yd) m2 = (+0.0300 - 31.4424 * xd + 30.0717 * yd) / (0.0241 + 0.2562 * xd - 0.7341 * yd) m1 = numpy.around(m1, decimals=3) m2 = numpy.around(m2, decimals=3) dir_path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(dir_path, "data/illuminants/d.yaml")) as f: data = yaml.safe_load(f) data = numpy.array(data).T lmbda = data[0] s = data[1:] return lmbda, s[0] + m1 * s[1] + m2 * s[2]
[ "def", "d", "(", "nominal_temperature", ")", ":", "# From CIE 15:2004. Colorimetry, 3rd edition, 2004 (page 69, note 5):", "#", "# The method required to calculate the values for the relative spectral", "# power distributions of illuminants D50, D55, D65, and D75, in Table T.1", "# is as follows...
CIE D-series illuminants. The technical report `Colorimetry, 3rd edition, 2004` gives the data for D50, D55, and D65 explicitly, but also explains how it's computed for S0, S1, S2. Values are given at 5nm resolution in the document, but really every other value is just interpolated. Hence, only provide 10 nm data here.
[ "CIE", "D", "-", "series", "illuminants", "." ]
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/colorio/illuminants.py#L137-L186
22,892
nschloe/colorio
colorio/illuminants.py
e
def e(): """This is a hypothetical reference radiator. All wavelengths in CIE illuminant E are weighted equally with a relative spectral power of 100.0. """ lmbda = 1.0e-9 * numpy.arange(300, 831) data = numpy.full(lmbda.shape, 100.0) return lmbda, data
python
def e(): lmbda = 1.0e-9 * numpy.arange(300, 831) data = numpy.full(lmbda.shape, 100.0) return lmbda, data
[ "def", "e", "(", ")", ":", "lmbda", "=", "1.0e-9", "*", "numpy", ".", "arange", "(", "300", ",", "831", ")", "data", "=", "numpy", ".", "full", "(", "lmbda", ".", "shape", ",", "100.0", ")", "return", "lmbda", ",", "data" ]
This is a hypothetical reference radiator. All wavelengths in CIE illuminant E are weighted equally with a relative spectral power of 100.0.
[ "This", "is", "a", "hypothetical", "reference", "radiator", ".", "All", "wavelengths", "in", "CIE", "illuminant", "E", "are", "weighted", "equally", "with", "a", "relative", "spectral", "power", "of", "100", ".", "0", "." ]
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/colorio/illuminants.py#L215-L221
22,893
nschloe/colorio
colorio/linalg.py
dot
def dot(a, b): """Take arrays `a` and `b` and form the dot product between the last axis of `a` and the first of `b`. """ b = numpy.asarray(b) return numpy.dot(a, b.reshape(b.shape[0], -1)).reshape(a.shape[:-1] + b.shape[1:])
python
def dot(a, b): b = numpy.asarray(b) return numpy.dot(a, b.reshape(b.shape[0], -1)).reshape(a.shape[:-1] + b.shape[1:])
[ "def", "dot", "(", "a", ",", "b", ")", ":", "b", "=", "numpy", ".", "asarray", "(", "b", ")", "return", "numpy", ".", "dot", "(", "a", ",", "b", ".", "reshape", "(", "b", ".", "shape", "[", "0", "]", ",", "-", "1", ")", ")", ".", "reshape...
Take arrays `a` and `b` and form the dot product between the last axis of `a` and the first of `b`.
[ "Take", "arrays", "a", "and", "b", "and", "form", "the", "dot", "product", "between", "the", "last", "axis", "of", "a", "and", "the", "first", "of", "b", "." ]
357d6001b3cf30f752e23726bf429dc1d1c60b3a
https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/colorio/linalg.py#L6-L11
22,894
dshean/demcoreg
demcoreg/dem_mask.py
get_nlcd_mask
def get_nlcd_mask(nlcd_ds, filter='not_forest', out_fn=None): """Generate raster mask for specified NLCD LULC filter """ print("Loading NLCD LULC") b = nlcd_ds.GetRasterBand(1) l = b.ReadAsArray() print("Filtering NLCD LULC with: %s" % filter) #Original nlcd products have nan as ndv #12 - ice #31 - rock #11 - open water, includes rivers #52 - shrub, <5 m tall, >20% #42 - evergreeen forest #Should use data dictionary here for general masking #Using 'rock+ice+water' preserves the most pixels, although could be problematic over areas with lakes if filter == 'rock': mask = (l==31) elif filter == 'rock+ice': mask = np.logical_or((l==31),(l==12)) elif filter == 'rock+ice+water': mask = np.logical_or(np.logical_or((l==31),(l==12)),(l==11)) elif filter == 'not_forest': mask = ~(np.logical_or(np.logical_or((l==41),(l==42)),(l==43))) elif filter == 'not_forest+not_water': mask = ~(np.logical_or(np.logical_or(np.logical_or((l==41),(l==42)),(l==43)),(l==11))) else: print("Invalid mask type") mask = None #Write out original data if out_fn is not None: print("Writing out %s" % out_fn) iolib.writeGTiff(l, out_fn, nlcd_ds) l = None return mask
python
def get_nlcd_mask(nlcd_ds, filter='not_forest', out_fn=None): print("Loading NLCD LULC") b = nlcd_ds.GetRasterBand(1) l = b.ReadAsArray() print("Filtering NLCD LULC with: %s" % filter) #Original nlcd products have nan as ndv #12 - ice #31 - rock #11 - open water, includes rivers #52 - shrub, <5 m tall, >20% #42 - evergreeen forest #Should use data dictionary here for general masking #Using 'rock+ice+water' preserves the most pixels, although could be problematic over areas with lakes if filter == 'rock': mask = (l==31) elif filter == 'rock+ice': mask = np.logical_or((l==31),(l==12)) elif filter == 'rock+ice+water': mask = np.logical_or(np.logical_or((l==31),(l==12)),(l==11)) elif filter == 'not_forest': mask = ~(np.logical_or(np.logical_or((l==41),(l==42)),(l==43))) elif filter == 'not_forest+not_water': mask = ~(np.logical_or(np.logical_or(np.logical_or((l==41),(l==42)),(l==43)),(l==11))) else: print("Invalid mask type") mask = None #Write out original data if out_fn is not None: print("Writing out %s" % out_fn) iolib.writeGTiff(l, out_fn, nlcd_ds) l = None return mask
[ "def", "get_nlcd_mask", "(", "nlcd_ds", ",", "filter", "=", "'not_forest'", ",", "out_fn", "=", "None", ")", ":", "print", "(", "\"Loading NLCD LULC\"", ")", "b", "=", "nlcd_ds", ".", "GetRasterBand", "(", "1", ")", "l", "=", "b", ".", "ReadAsArray", "("...
Generate raster mask for specified NLCD LULC filter
[ "Generate", "raster", "mask", "for", "specified", "NLCD", "LULC", "filter" ]
abd6be75d326b35f52826ee30dff01f9e86b4b52
https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L108-L141
22,895
dshean/demcoreg
demcoreg/dem_mask.py
get_bareground_mask
def get_bareground_mask(bareground_ds, bareground_thresh=60, out_fn=None): """Generate raster mask for exposed bare ground from global bareground data """ print("Loading bareground") b = bareground_ds.GetRasterBand(1) l = b.ReadAsArray() print("Masking pixels with <%0.1f%% bare ground" % bareground_thresh) if bareground_thresh < 0.0 or bareground_thresh > 100.0: sys.exit("Invalid bare ground percentage") mask = (l>bareground_thresh) #Write out original data if out_fn is not None: print("Writing out %s" % out_fn) iolib.writeGTiff(l, out_fn, bareground_ds) l = None return mask
python
def get_bareground_mask(bareground_ds, bareground_thresh=60, out_fn=None): print("Loading bareground") b = bareground_ds.GetRasterBand(1) l = b.ReadAsArray() print("Masking pixels with <%0.1f%% bare ground" % bareground_thresh) if bareground_thresh < 0.0 or bareground_thresh > 100.0: sys.exit("Invalid bare ground percentage") mask = (l>bareground_thresh) #Write out original data if out_fn is not None: print("Writing out %s" % out_fn) iolib.writeGTiff(l, out_fn, bareground_ds) l = None return mask
[ "def", "get_bareground_mask", "(", "bareground_ds", ",", "bareground_thresh", "=", "60", ",", "out_fn", "=", "None", ")", ":", "print", "(", "\"Loading bareground\"", ")", "b", "=", "bareground_ds", ".", "GetRasterBand", "(", "1", ")", "l", "=", "b", ".", ...
Generate raster mask for exposed bare ground from global bareground data
[ "Generate", "raster", "mask", "for", "exposed", "bare", "ground", "from", "global", "bareground", "data" ]
abd6be75d326b35f52826ee30dff01f9e86b4b52
https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L143-L158
22,896
dshean/demcoreg
demcoreg/dem_mask.py
get_snodas_ds
def get_snodas_ds(dem_dt, code=1036): """Function to fetch and process SNODAS snow depth products for input datetime http://nsidc.org/data/docs/noaa/g02158_snodas_snow_cover_model/index.html Product codes: 1036 is snow depth 1034 is SWE filename format: us_ssmv11036tS__T0001TTNATS2015042205HP001.Hdr """ import tarfile import gzip snodas_ds = None snodas_url_str = None outdir = os.path.join(datadir, 'snodas') if not os.path.exists(outdir): os.makedirs(outdir) #Note: unmasked products (beyond CONUS) are only available from 2010-present if dem_dt >= datetime(2003,9,30) and dem_dt < datetime(2010,1,1): snodas_url_str = 'ftp://sidads.colorado.edu/DATASETS/NOAA/G02158/masked/%Y/%m_%b/SNODAS_%Y%m%d.tar' tar_subfn_str_fmt = 'us_ssmv1%itS__T0001TTNATS%%Y%%m%%d05HP001.%s.gz' elif dem_dt >= datetime(2010,1,1): snodas_url_str = 'ftp://sidads.colorado.edu/DATASETS/NOAA/G02158/unmasked/%Y/%m_%b/SNODAS_unmasked_%Y%m%d.tar' tar_subfn_str_fmt = './zz_ssmv1%itS__T0001TTNATS%%Y%%m%%d05HP001.%s.gz' else: print("No SNODAS data available for input date") if snodas_url_str is not None: snodas_url = dem_dt.strftime(snodas_url_str) snodas_tar_fn = iolib.getfile(snodas_url, outdir=outdir) print("Unpacking") tar = tarfile.open(snodas_tar_fn) #gunzip to extract both dat and Hdr files, tar.gz for ext in ('dat', 'Hdr'): tar_subfn_str = tar_subfn_str_fmt % (code, ext) tar_subfn_gz = dem_dt.strftime(tar_subfn_str) tar_subfn = os.path.splitext(tar_subfn_gz)[0] print(tar_subfn) if outdir is not None: tar_subfn = os.path.join(outdir, tar_subfn) if not os.path.exists(tar_subfn): #Should be able to do this without writing intermediate gz to disk tar.extract(tar_subfn_gz) with gzip.open(tar_subfn_gz, 'rb') as f: outf = open(tar_subfn, 'wb') outf.write(f.read()) outf.close() os.remove(tar_subfn_gz) #Need to delete 'Created by module comment' line from Hdr, can contain too many characters bad_str = 'Created by module comment' snodas_fn = tar_subfn f = open(snodas_fn) output = [] for line in f: if not bad_str in line: output.append(line) f.close() f = open(snodas_fn, 'w') f.writelines(output) f.close() #Return GDAL dataset for extracted product snodas_ds = gdal.Open(snodas_fn) return snodas_ds
python
def get_snodas_ds(dem_dt, code=1036): import tarfile import gzip snodas_ds = None snodas_url_str = None outdir = os.path.join(datadir, 'snodas') if not os.path.exists(outdir): os.makedirs(outdir) #Note: unmasked products (beyond CONUS) are only available from 2010-present if dem_dt >= datetime(2003,9,30) and dem_dt < datetime(2010,1,1): snodas_url_str = 'ftp://sidads.colorado.edu/DATASETS/NOAA/G02158/masked/%Y/%m_%b/SNODAS_%Y%m%d.tar' tar_subfn_str_fmt = 'us_ssmv1%itS__T0001TTNATS%%Y%%m%%d05HP001.%s.gz' elif dem_dt >= datetime(2010,1,1): snodas_url_str = 'ftp://sidads.colorado.edu/DATASETS/NOAA/G02158/unmasked/%Y/%m_%b/SNODAS_unmasked_%Y%m%d.tar' tar_subfn_str_fmt = './zz_ssmv1%itS__T0001TTNATS%%Y%%m%%d05HP001.%s.gz' else: print("No SNODAS data available for input date") if snodas_url_str is not None: snodas_url = dem_dt.strftime(snodas_url_str) snodas_tar_fn = iolib.getfile(snodas_url, outdir=outdir) print("Unpacking") tar = tarfile.open(snodas_tar_fn) #gunzip to extract both dat and Hdr files, tar.gz for ext in ('dat', 'Hdr'): tar_subfn_str = tar_subfn_str_fmt % (code, ext) tar_subfn_gz = dem_dt.strftime(tar_subfn_str) tar_subfn = os.path.splitext(tar_subfn_gz)[0] print(tar_subfn) if outdir is not None: tar_subfn = os.path.join(outdir, tar_subfn) if not os.path.exists(tar_subfn): #Should be able to do this without writing intermediate gz to disk tar.extract(tar_subfn_gz) with gzip.open(tar_subfn_gz, 'rb') as f: outf = open(tar_subfn, 'wb') outf.write(f.read()) outf.close() os.remove(tar_subfn_gz) #Need to delete 'Created by module comment' line from Hdr, can contain too many characters bad_str = 'Created by module comment' snodas_fn = tar_subfn f = open(snodas_fn) output = [] for line in f: if not bad_str in line: output.append(line) f.close() f = open(snodas_fn, 'w') f.writelines(output) f.close() #Return GDAL dataset for extracted product snodas_ds = gdal.Open(snodas_fn) return snodas_ds
[ "def", "get_snodas_ds", "(", "dem_dt", ",", "code", "=", "1036", ")", ":", "import", "tarfile", "import", "gzip", "snodas_ds", "=", "None", "snodas_url_str", "=", "None", "outdir", "=", "os", ".", "path", ".", "join", "(", "datadir", ",", "'snodas'", ")"...
Function to fetch and process SNODAS snow depth products for input datetime http://nsidc.org/data/docs/noaa/g02158_snodas_snow_cover_model/index.html Product codes: 1036 is snow depth 1034 is SWE filename format: us_ssmv11036tS__T0001TTNATS2015042205HP001.Hdr
[ "Function", "to", "fetch", "and", "process", "SNODAS", "snow", "depth", "products", "for", "input", "datetime" ]
abd6be75d326b35f52826ee30dff01f9e86b4b52
https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L160-L228
22,897
dshean/demcoreg
demcoreg/dem_mask.py
get_modis_tile_list
def get_modis_tile_list(ds): """Helper function to identify MODIS tiles that intersect input geometry modis_gird.py contains dictionary of tile boundaries (tile name and WKT polygon ring from bbox) See: https://modis-land.gsfc.nasa.gov/MODLAND_grid.html """ from demcoreg import modis_grid modis_dict = {} for key in modis_grid.modis_dict: modis_dict[key] = ogr.CreateGeometryFromWkt(modis_grid.modis_dict[key]) geom = geolib.ds_geom(ds) geom_dup = geolib.geom_dup(geom) ct = osr.CoordinateTransformation(geom_dup.GetSpatialReference(), geolib.wgs_srs) geom_dup.Transform(ct) tile_list = [] for key, val in list(modis_dict.items()): if geom_dup.Intersects(val): tile_list.append(key) return tile_list
python
def get_modis_tile_list(ds): from demcoreg import modis_grid modis_dict = {} for key in modis_grid.modis_dict: modis_dict[key] = ogr.CreateGeometryFromWkt(modis_grid.modis_dict[key]) geom = geolib.ds_geom(ds) geom_dup = geolib.geom_dup(geom) ct = osr.CoordinateTransformation(geom_dup.GetSpatialReference(), geolib.wgs_srs) geom_dup.Transform(ct) tile_list = [] for key, val in list(modis_dict.items()): if geom_dup.Intersects(val): tile_list.append(key) return tile_list
[ "def", "get_modis_tile_list", "(", "ds", ")", ":", "from", "demcoreg", "import", "modis_grid", "modis_dict", "=", "{", "}", "for", "key", "in", "modis_grid", ".", "modis_dict", ":", "modis_dict", "[", "key", "]", "=", "ogr", ".", "CreateGeometryFromWkt", "("...
Helper function to identify MODIS tiles that intersect input geometry modis_gird.py contains dictionary of tile boundaries (tile name and WKT polygon ring from bbox) See: https://modis-land.gsfc.nasa.gov/MODLAND_grid.html
[ "Helper", "function", "to", "identify", "MODIS", "tiles", "that", "intersect", "input", "geometry" ]
abd6be75d326b35f52826ee30dff01f9e86b4b52
https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L230-L249
22,898
dshean/demcoreg
demcoreg/dem_mask.py
get_modscag_fn_list
def get_modscag_fn_list(dem_dt, tile_list=('h08v04', 'h09v04', 'h10v04', 'h08v05', 'h09v05'), pad_days=7): """Function to fetch and process MODSCAG fractional snow cover products for input datetime Products are tiled in MODIS sinusoidal projection example url: https://snow-data.jpl.nasa.gov/modscag-historic/2015/001/MOD09GA.A2015001.h07v03.005.2015006001833.snow_fraction.tif """ #Could also use global MODIS 500 m snowcover grids, 8 day #http://nsidc.org/data/docs/daac/modis_v5/mod10a2_modis_terra_snow_8-day_global_500m_grid.gd.html #These are HDF4, sinusoidal #Should be able to load up with warplib without issue import re import requests from bs4 import BeautifulSoup auth = iolib.get_auth() pad_days = timedelta(days=pad_days) dt_list = timelib.dt_range(dem_dt-pad_days, dem_dt+pad_days+timedelta(1), timedelta(1)) outdir = os.path.join(datadir, 'modscag') if not os.path.exists(outdir): os.makedirs(outdir) out_vrt_fn_list = [] for dt in dt_list: out_vrt_fn = os.path.join(outdir, dt.strftime('%Y%m%d_snow_fraction.vrt')) #If we already have a vrt and it contains all of the necessary tiles if os.path.exists(out_vrt_fn): vrt_ds = gdal.Open(out_vrt_fn) if np.all([np.any([tile in sub_fn for sub_fn in vrt_ds.GetFileList()]) for tile in tile_list]): out_vrt_fn_list.append(out_vrt_fn) continue #Otherwise, download missing tiles and rebuild #Try to use historic products modscag_fn_list = [] #Note: not all tiles are available for same date ranges in historic vs. real-time #Need to repeat search tile-by-tile for tile in tile_list: modscag_url_str = 'https://snow-data.jpl.nasa.gov/modscag-historic/%Y/%j/' modscag_url_base = dt.strftime(modscag_url_str) print("Trying: %s" % modscag_url_base) r = requests.get(modscag_url_base, auth=auth) modscag_url_fn = [] if r.ok: parsed_html = BeautifulSoup(r.content, "html.parser") modscag_url_fn = parsed_html.findAll(text=re.compile('%s.*snow_fraction.tif' % tile)) if not modscag_url_fn: #Couldn't find historic, try to use real-time products modscag_url_str = 'https://snow-data.jpl.nasa.gov/modscag/%Y/%j/' modscag_url_base = dt.strftime(modscag_url_str) print("Trying: %s" % modscag_url_base) r = requests.get(modscag_url_base, auth=auth) if r.ok: parsed_html = BeautifulSoup(r.content, "html.parser") modscag_url_fn = parsed_html.findAll(text=re.compile('%s.*snow_fraction.tif' % tile)) if not modscag_url_fn: print("Unable to fetch MODSCAG for %s" % dt) else: #OK, we got #Now extract actual tif filenames to fetch from html parsed_html = BeautifulSoup(r.content, "html.parser") #Fetch all tiles modscag_url_fn = parsed_html.findAll(text=re.compile('%s.*snow_fraction.tif' % tile)) if modscag_url_fn: modscag_url_fn = modscag_url_fn[0] modscag_url = os.path.join(modscag_url_base, modscag_url_fn) print(modscag_url) modscag_fn = os.path.join(outdir, os.path.split(modscag_url_fn)[-1]) if not os.path.exists(modscag_fn): iolib.getfile2(modscag_url, auth=auth, outdir=outdir) modscag_fn_list.append(modscag_fn) #Mosaic tiles - currently a hack if modscag_fn_list: cmd = ['gdalbuildvrt', '-vrtnodata', '255', out_vrt_fn] cmd.extend(modscag_fn_list) print(cmd) subprocess.call(cmd, shell=False) out_vrt_fn_list.append(out_vrt_fn) return out_vrt_fn_list
python
def get_modscag_fn_list(dem_dt, tile_list=('h08v04', 'h09v04', 'h10v04', 'h08v05', 'h09v05'), pad_days=7): #Could also use global MODIS 500 m snowcover grids, 8 day #http://nsidc.org/data/docs/daac/modis_v5/mod10a2_modis_terra_snow_8-day_global_500m_grid.gd.html #These are HDF4, sinusoidal #Should be able to load up with warplib without issue import re import requests from bs4 import BeautifulSoup auth = iolib.get_auth() pad_days = timedelta(days=pad_days) dt_list = timelib.dt_range(dem_dt-pad_days, dem_dt+pad_days+timedelta(1), timedelta(1)) outdir = os.path.join(datadir, 'modscag') if not os.path.exists(outdir): os.makedirs(outdir) out_vrt_fn_list = [] for dt in dt_list: out_vrt_fn = os.path.join(outdir, dt.strftime('%Y%m%d_snow_fraction.vrt')) #If we already have a vrt and it contains all of the necessary tiles if os.path.exists(out_vrt_fn): vrt_ds = gdal.Open(out_vrt_fn) if np.all([np.any([tile in sub_fn for sub_fn in vrt_ds.GetFileList()]) for tile in tile_list]): out_vrt_fn_list.append(out_vrt_fn) continue #Otherwise, download missing tiles and rebuild #Try to use historic products modscag_fn_list = [] #Note: not all tiles are available for same date ranges in historic vs. real-time #Need to repeat search tile-by-tile for tile in tile_list: modscag_url_str = 'https://snow-data.jpl.nasa.gov/modscag-historic/%Y/%j/' modscag_url_base = dt.strftime(modscag_url_str) print("Trying: %s" % modscag_url_base) r = requests.get(modscag_url_base, auth=auth) modscag_url_fn = [] if r.ok: parsed_html = BeautifulSoup(r.content, "html.parser") modscag_url_fn = parsed_html.findAll(text=re.compile('%s.*snow_fraction.tif' % tile)) if not modscag_url_fn: #Couldn't find historic, try to use real-time products modscag_url_str = 'https://snow-data.jpl.nasa.gov/modscag/%Y/%j/' modscag_url_base = dt.strftime(modscag_url_str) print("Trying: %s" % modscag_url_base) r = requests.get(modscag_url_base, auth=auth) if r.ok: parsed_html = BeautifulSoup(r.content, "html.parser") modscag_url_fn = parsed_html.findAll(text=re.compile('%s.*snow_fraction.tif' % tile)) if not modscag_url_fn: print("Unable to fetch MODSCAG for %s" % dt) else: #OK, we got #Now extract actual tif filenames to fetch from html parsed_html = BeautifulSoup(r.content, "html.parser") #Fetch all tiles modscag_url_fn = parsed_html.findAll(text=re.compile('%s.*snow_fraction.tif' % tile)) if modscag_url_fn: modscag_url_fn = modscag_url_fn[0] modscag_url = os.path.join(modscag_url_base, modscag_url_fn) print(modscag_url) modscag_fn = os.path.join(outdir, os.path.split(modscag_url_fn)[-1]) if not os.path.exists(modscag_fn): iolib.getfile2(modscag_url, auth=auth, outdir=outdir) modscag_fn_list.append(modscag_fn) #Mosaic tiles - currently a hack if modscag_fn_list: cmd = ['gdalbuildvrt', '-vrtnodata', '255', out_vrt_fn] cmd.extend(modscag_fn_list) print(cmd) subprocess.call(cmd, shell=False) out_vrt_fn_list.append(out_vrt_fn) return out_vrt_fn_list
[ "def", "get_modscag_fn_list", "(", "dem_dt", ",", "tile_list", "=", "(", "'h08v04'", ",", "'h09v04'", ",", "'h10v04'", ",", "'h08v05'", ",", "'h09v05'", ")", ",", "pad_days", "=", "7", ")", ":", "#Could also use global MODIS 500 m snowcover grids, 8 day", "#http://n...
Function to fetch and process MODSCAG fractional snow cover products for input datetime Products are tiled in MODIS sinusoidal projection example url: https://snow-data.jpl.nasa.gov/modscag-historic/2015/001/MOD09GA.A2015001.h07v03.005.2015006001833.snow_fraction.tif
[ "Function", "to", "fetch", "and", "process", "MODSCAG", "fractional", "snow", "cover", "products", "for", "input", "datetime" ]
abd6be75d326b35f52826ee30dff01f9e86b4b52
https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L251-L331
22,899
dshean/demcoreg
demcoreg/dem_mask.py
proc_modscag
def proc_modscag(fn_list, extent=None, t_srs=None): """Process the MODSCAG products for full date range, create composites and reproject """ #Use cubic spline here for improve upsampling ds_list = warplib.memwarp_multi_fn(fn_list, res='min', extent=extent, t_srs=t_srs, r='cubicspline') stack_fn = os.path.splitext(fn_list[0])[0] + '_' + os.path.splitext(os.path.split(fn_list[-1])[1])[0] + '_stack_%i' % len(fn_list) #Create stack here - no need for most of mastack machinery, just make 3D array #Mask values greater than 100% (clouds, bad pixels, etc) ma_stack = np.ma.array([np.ma.masked_greater(iolib.ds_getma(ds), 100) for ds in np.array(ds_list)], dtype=np.uint8) stack_count = np.ma.masked_equal(ma_stack.count(axis=0), 0).astype(np.uint8) stack_count.set_fill_value(0) stack_min = ma_stack.min(axis=0).astype(np.uint8) stack_min.set_fill_value(0) stack_max = ma_stack.max(axis=0).astype(np.uint8) stack_max.set_fill_value(0) stack_med = np.ma.median(ma_stack, axis=0).astype(np.uint8) stack_med.set_fill_value(0) out_fn = stack_fn + '_count.tif' iolib.writeGTiff(stack_count, out_fn, ds_list[0]) out_fn = stack_fn + '_max.tif' iolib.writeGTiff(stack_max, out_fn, ds_list[0]) out_fn = stack_fn + '_min.tif' iolib.writeGTiff(stack_min, out_fn, ds_list[0]) out_fn = stack_fn + '_med.tif' iolib.writeGTiff(stack_med, out_fn, ds_list[0]) ds = gdal.Open(out_fn) return ds
python
def proc_modscag(fn_list, extent=None, t_srs=None): #Use cubic spline here for improve upsampling ds_list = warplib.memwarp_multi_fn(fn_list, res='min', extent=extent, t_srs=t_srs, r='cubicspline') stack_fn = os.path.splitext(fn_list[0])[0] + '_' + os.path.splitext(os.path.split(fn_list[-1])[1])[0] + '_stack_%i' % len(fn_list) #Create stack here - no need for most of mastack machinery, just make 3D array #Mask values greater than 100% (clouds, bad pixels, etc) ma_stack = np.ma.array([np.ma.masked_greater(iolib.ds_getma(ds), 100) for ds in np.array(ds_list)], dtype=np.uint8) stack_count = np.ma.masked_equal(ma_stack.count(axis=0), 0).astype(np.uint8) stack_count.set_fill_value(0) stack_min = ma_stack.min(axis=0).astype(np.uint8) stack_min.set_fill_value(0) stack_max = ma_stack.max(axis=0).astype(np.uint8) stack_max.set_fill_value(0) stack_med = np.ma.median(ma_stack, axis=0).astype(np.uint8) stack_med.set_fill_value(0) out_fn = stack_fn + '_count.tif' iolib.writeGTiff(stack_count, out_fn, ds_list[0]) out_fn = stack_fn + '_max.tif' iolib.writeGTiff(stack_max, out_fn, ds_list[0]) out_fn = stack_fn + '_min.tif' iolib.writeGTiff(stack_min, out_fn, ds_list[0]) out_fn = stack_fn + '_med.tif' iolib.writeGTiff(stack_med, out_fn, ds_list[0]) ds = gdal.Open(out_fn) return ds
[ "def", "proc_modscag", "(", "fn_list", ",", "extent", "=", "None", ",", "t_srs", "=", "None", ")", ":", "#Use cubic spline here for improve upsampling ", "ds_list", "=", "warplib", ".", "memwarp_multi_fn", "(", "fn_list", ",", "res", "=", "'min'", ",", "extent",...
Process the MODSCAG products for full date range, create composites and reproject
[ "Process", "the", "MODSCAG", "products", "for", "full", "date", "range", "create", "composites", "and", "reproject" ]
abd6be75d326b35f52826ee30dff01f9e86b4b52
https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L333-L362