_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q237900
SMCUpdater.reset
train
def reset(self, n_particles=None, only_params=None, reset_weights=True): """ Causes all particle locations and weights to be drawn fresh from the initial prior. :param int n_particles: Forces the size of the new particle set. If `None`, the size of the particle set is not ch...
python
{ "resource": "" }
q237901
SMCUpdater.batch_update
train
def batch_update(self, outcomes, expparams, resample_interval=5): r""" Updates based on a batch of outcomes and experiments, rather than just one. :param numpy.ndarray outcomes: An array of outcomes of the experiments that were performed. :param numpy.ndarray exppara...
python
{ "resource": "" }
q237902
SMCUpdater.resample
train
def resample(self): """ Forces the updater to perform a resampling step immediately. """ if self.just_resampled: warnings.warn( "Resampling without additional data; this may not perform as " "desired.", ResamplerWarning ...
python
{ "resource": "" }
q237903
SMCUpdater.expected_information_gain
train
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 cur...
python
{ "resource": "" }
q237904
SMCUpdater.posterior_marginal
train
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 margin...
python
{ "resource": "" }
q237905
SMCUpdater.plot_posterior_marginal
train
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 marginali...
python
{ "resource": "" }
q237906
SMCUpdater.plot_covariance
train
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 matri...
python
{ "resource": "" }
q237907
SMCUpdater.posterior_mesh
train
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 ...
python
{ "resource": "" }
q237908
SMCUpdater.plot_posterior_contour
train
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 p...
python
{ "resource": "" }
q237909
plot_rebit_prior
train
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: Distributio...
python
{ "resource": "" }
q237910
plot_rebit_posterior
train
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.SMCUpdat...
python
{ "resource": "" }
q237911
data_to_params
train
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 scal...
python
{ "resource": "" }
q237912
TomographyModel.canonicalize
train
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 para...
python
{ "resource": "" }
q237913
TomographyModel.trunc_neg_eigs
train
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, )`` repres...
python
{ "resource": "" }
q237914
TomographyModel.renormalize
train
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 para...
python
{ "resource": "" }
q237915
ProductDomain.values
train
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.valu...
python
{ "resource": "" }
q237916
IntegerDomain.min
train
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
{ "resource": "" }
q237917
IntegerDomain.max
train
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
{ "resource": "" }
q237918
IntegerDomain.is_finite
train
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
{ "resource": "" }
q237919
MultinomialDomain.n_members
train
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
{ "resource": "" }
q237920
MultinomialDomain.to_regular_array
train
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 b...
python
{ "resource": "" }
q237921
MultinomialDomain.from_regular_array
train
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` ...
python
{ "resource": "" }
q237922
IPythonProgressBar.start
train
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
{ "resource": "" }
q237923
MultiQubitStatePauliModel.likelihood
train
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 operato...
python
{ "resource": "" }
q237924
BinomialModel.domain
train
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_...
python
{ "resource": "" }
q237925
GaussianHyperparameterizedModel.underlying_likelihood
train
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_mo...
python
{ "resource": "" }
q237926
Simulatable.are_expparam_dtypes_consistent
train
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.ndarr...
python
{ "resource": "" }
q237927
Simulatable.simulate_experiment
train
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 ...
python
{ "resource": "" }
q237928
Model.likelihood
train
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)`` a...
python
{ "resource": "" }
q237929
get_qutip_module
train
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``. :retur...
python
{ "resource": "" }
q237930
particle_covariance_mtx
train
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 partic...
python
{ "resource": "" }
q237931
ellipsoid_volume
train
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) ...
python
{ "resource": "" }
q237932
in_ellipsoid
train
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)`...
python
{ "resource": "" }
q237933
assert_sigfigs_equal
train
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 ...
python
{ "resource": "" }
q237934
format_uncertainty
train
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: # Retur...
python
{ "resource": "" }
q237935
from_simplex
train
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``...
python
{ "resource": "" }
q237936
join_struct_arrays
train
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/question...
python
{ "resource": "" }
q237937
separate_struct_array
train
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...
python
{ "resource": "" }
q237938
sqrtm_psd
train
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) ...
python
{ "resource": "" }
q237939
tensor_product_basis
train
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.zero...
python
{ "resource": "" }
q237940
TomographyBasis.state_to_modelparams
train
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 ...
python
{ "resource": "" }
q237941
TomographyBasis.modelparams_to_state
train
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 r...
python
{ "resource": "" }
q237942
TomographyBasis.covariance_mtx_to_superop
train
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=[...
python
{ "resource": "" }
q237943
MixtureDistribution._dist_kw_arg
train
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...
python
{ "resource": "" }
q237944
ParticleDistribution.sample
train
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)``. ...
python
{ "resource": "" }
q237945
ParticleDistribution.est_covariance_mtx
train
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, ...
python
{ "resource": "" }
q237946
ParticleDistribution.est_credible_region
train
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 retur...
python
{ "resource": "" }
q237947
ParticleDistribution.region_est_hull
train
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`). :para...
python
{ "resource": "" }
q237948
ParticleDistribution.in_credible_region
train
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 h...
python
{ "resource": "" }
q237949
PostselectedDistribution.sample
train
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...
python
{ "resource": "" }
q237950
Service.iter_actions
train
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 ou...
python
{ "resource": "" }
q237951
parse_event_xml
train
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 rep...
python
{ "resource": "" }
q237952
Subscription.unsubscribe
train
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_sub...
python
{ "resource": "" }
q237953
SoCo.play_mode
train
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',...
python
{ "resource": "" }
q237954
SoCo.repeat
train
def repeat(self, repeat): """Set the queue's repeat option""" shuffle = self.shuffle self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)]
python
{ "resource": "" }
q237955
SoCo.join
train
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._...
python
{ "resource": "" }
q237956
SoCo.unjoin
train
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([ ...
python
{ "resource": "" }
q237957
SoCo.set_sleep_timer
train
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: SoCoE...
python
{ "resource": "" }
q237958
Snapshot._restore_coordinator
train
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_curre...
python
{ "resource": "" }
q237959
Snapshot._restore_volume
train
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 fir...
python
{ "resource": "" }
q237960
discover_thread
train
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_invis...
python
{ "resource": "" }
q237961
by_name
train
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_househol...
python
{ "resource": "" }
q237962
get_trainer
train
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
{ "resource": "" }
q237963
scale_image
train
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 ...
python
{ "resource": "" }
q237964
map_pixels_to_ascii_chars
train
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 ...
python
{ "resource": "" }
q237965
load_steps
train
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. ...
python
{ "resource": "" }
q237966
load_yaml
train
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
{ "resource": "" }
q237967
sort_loading_order
train
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 = []...
python
{ "resource": "" }
q237968
load_cwl
train
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(fnam...
python
{ "resource": "" }
q237969
Step.set_input
train
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 p...
python
{ "resource": "" }
q237970
Step.output_reference
train
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 ...
python
{ "resource": "" }
q237971
Step._input_optional
train
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 ...
python
{ "resource": "" }
q237972
Step.to_obj
train
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 No...
python
{ "resource": "" }
q237973
Step.list_inputs
train
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. ...
python
{ "resource": "" }
q237974
WorkflowGenerator.load
train
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: ...
python
{ "resource": "" }
q237975
WorkflowGenerator._has_requirements
train
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_requ...
python
{ "resource": "" }
q237976
WorkflowGenerator.inputs
train
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
{ "resource": "" }
q237977
WorkflowGenerator._add_step
train
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
{ "resource": "" }
q237978
WorkflowGenerator.add_input
train
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 i...
python
{ "resource": "" }
q237979
WorkflowGenerator.add_outputs
train
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., ...
python
{ "resource": "" }
q237980
WorkflowGenerator._get_step
train
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: nam...
python
{ "resource": "" }
q237981
WorkflowGenerator.to_obj
train
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['cwlVersio...
python
{ "resource": "" }
q237982
WorkflowGenerator.to_script
train
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 = [] ...
python
{ "resource": "" }
q237983
WorkflowGenerator._types_match
train
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): typ...
python
{ "resource": "" }
q237984
WorkflowGenerator.validate
train
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 absolu...
python
{ "resource": "" }
q237985
WorkflowGenerator.save
train
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. ...
python
{ "resource": "" }
q237986
str_presenter
train
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,2...
python
{ "resource": "" }
q237987
build_grad_matrices
train
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) do...
python
{ "resource": "" }
q237988
PiecewiseEllipse.apply_M
train
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 re...
python
{ "resource": "" }
q237989
PiecewiseEllipse.cost_min2
train
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) ...
python
{ "resource": "" }
q237990
delta
train
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
{ "resource": "" }
q237991
plot_flat_gamut
train
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...
python
{ "resource": "" }
q237992
_get_xy_tree
train
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, ...
python
{ "resource": "" }
q237993
spectrum_to_xyz100
train
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 recommendat...
python
{ "resource": "" }
q237994
d
train
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 jus...
python
{ "resource": "" }
q237995
e
train
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
{ "resource": "" }
q237996
dot
train
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
{ "resource": "" }
q237997
get_nlcd_mask
train
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 ...
python
{ "resource": "" }
q237998
get_bareground_mask
train
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" % baregro...
python
{ "resource": "" }
q237999
get_snodas_ds
train
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__T0001TTNATS2015042205HP...
python
{ "resource": "" }