Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def sample_multinomial(N, p, size=None): r # ensure s is array s = np.array([1]) if size is None else np.array([size]).flatten() def take_samples(ps): # we have to flatten to make apply_along_axis work. return np.random.multinomial(N, ps, np....
[ "\n Draws fixed number of samples N from different\n multinomial distributions (with the same number dice sides).\n\n :param int N: How many samples to draw from each distribution.\n :param np.ndarray p: Probabilities specifying each distribution.\n Sum along axis 0 should be 1.\n :param size:...
Please provide a description of the function:def outer_product(vec): r return ( np.dot(vec[:, np.newaxis], vec[np.newaxis, :]) if len(vec.shape) == 1 else np.dot(vec, vec.T) )
[ "\n Returns the outer product of a vector :math:`v`\n with itself, :math:`v v^\\T`.\n " ]
Please provide a description of the function:def particle_meanfn(weights, locations, fn=None): r warnings.warn('particle_meanfn is deprecated, please use distributions.ParticleDistribution', DeprecationWarning) fn_vals = fn(locations) if fn is not None else locations return np.sum(weig...
[ "\n Returns the mean of a function :math:`f` over model\n parameters.\n\n :param numpy.ndarray weights: Weights of each particle.\n :param numpy.ndarray locations: Locations of each\n particle.\n :param callable fn: Function of model parameters to\n take the mean of. If `None`, the iden...
Please provide a description of the function: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 Returns an estimate of the covariance of a distribution\n represented by a given set of SMC particle.\n\n :param weights: An array containing the weights of each\n particle.\n :param location: An array containing the locations of\n each particle.\n :rtype: :class:`numpy.ndarray`, sh...
Please provide a description of the function: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/...
[ "\n Returns the volume of an ellipsoid given either its\n matrix or the inverse of its matrix.\n " ]
Please provide a description of the function:def mvee(points, tol=0.001): # This function is a port of the matlab function by # Nima Moshtagh found here: # https://www.mathworks.com/matlabcentral/fileexchange/9542-minimum-volume-enclosing-ellipsoid # with accompanying writup here: # https://ww...
[ "\n Returns the minimum-volume enclosing ellipse (MVEE)\n of a set of points, using the Khachiyan algorithm.\n " ]
Please provide a description of the function: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
[ "\n Determines which of the points ``x`` are in the\n closed ellipsoid with shape matrix ``A`` centered at ``c``.\n For a single point ``x``, this is computed as\n\n .. math::\n (c-x)^T\\cdot A^{-1}\\cdot (c-x) \\leq 1\n\n :param np.ndarray x: Shape ``(n_points, dim)`` or ``n_points``....
Please provide a description of the function: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) ...
[ "\n Tests if all elements in x and y\n agree up to a certain number of\n significant figures.\n\n :param np.ndarray x: Array of numbers.\n :param np.ndarray y: Array of numbers you want to\n be equal to ``x``.\n :param int sigfigs: How many significant\n figures you demand that they ...
Please provide a description of the function: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 t...
[ "\n Given a value and its uncertianty, format as a LaTeX string\n for pretty-printing.\n\n :param int scinotn_break: How many decimal points to print\n before breaking into scientific notation.\n " ]
Please provide a description of the function:def compactspace(scale, n): r logit = logistic(scale=scale).ppf compact_xs = np.linspace(0, 1, n + 2)[1:-1] return logit(compact_xs)
[ "\n Returns points :math:`x` spaced in the open interval\n :math:`(-\\infty, \\infty)` by linearly spacing in the compactified\n coordinate :math:`s(x) = e^{-\\alpha x} / (1 + e^{-\\alpha x})^2`,\n where :math:`\\alpha` is a scale factor.\n " ]
Please provide a description of the function:def to_simplex(y): r n = y.shape[-1] # z are the stick breaking fractions in [0,1] z = expit(y - np.log(n - np.arange(1, n+1))) x = np.empty(y.shape) x[..., 0] = z[..., 0] x[..., 1:] = z[..., 1:] * (1 - z[..., :-1]).cumprod(axis=-1) return x
[ "\n Interprets the last index of ``y`` as stick breaking fractions \n in logit space and returns a non-negative array of \n the same shape where the last dimension always sums to unity.\n \n A unit simplex is a list of non-negative numbers :math:`(x_1,...,x_K)`\n that sum to one, :math:`\\sum_{k=1...
Please provide a description of the function:def from_simplex(x): r 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=-...
[ "\n Inteprets the last index of x as unit simplices and returns a\n real array of the sampe shape in logit space.\n\n Inverse to :func:`to_simplex` ; see that function for more details.\n\n :param np.ndarray: Array of unit simplices along the last index.\n \n :rtype: ``np.ndarray``\n " ]
Please provide a description of the function: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 +...
[ "\n Takes a list of possibly structured arrays, concatenates their\n dtypes, and returns one big array with that dtype. Does the\n inverse of ``separate_struct_array``.\n\n :param list arrays: List of ``np.ndarray``s\n " ]
Please provide a description of the function: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)) ...
[ "\n Takes an array with a structured dtype, and separates it out into\n a list of arrays with dtypes coming from the input ``dtypes``.\n Does the inverse of ``join_struct_arrays``.\n\n :param np.ndarray array: Structured array.\n :param dtypes: List of ``np.dtype``, or just a ``np.dtype`` and the num...
Please provide a description of the function: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...
[ "\n Returns the matrix square root of a positive semidefinite matrix,\n truncating negative eigenvalues.\n " ]
Please provide a description of the function:def decorate_init(init_decorator): def class_decorator(cls): cls.__init__ = init_decorator(cls.__init__) return cls return class_decorator
[ "\n Given a class definition and a decorator that acts on methods,\n applies that decorator to the class' __init__ method.\n Useful for decorating __init__ while still allowing __init__ to be\n inherited.\n " ]
Please provide a description of the function:def binom_est_error(p, N, hedge = float(0)): r # asymptotic np.sqrt(p * (1 - p) / N) return np.sqrt(p*(1-p)/(N+2*hedge+1))
[ "\n " ]
Please provide a description of the function:def gell_mann_basis(dim): # Start by making an empty array of the right shape to # hold the matrices that we construct. basis = np.zeros((dim**2, dim, dim), dtype=complex) # The first matrix should be the identity. basis[0, :, :] = np.eye(dim) / np....
[ " \n Returns a :class:`~qinfer.tomography.TomographyBasis` on dim dimensions\n using the generalized Gell-Mann matrices.\n\n This implementation is based on a MATLAB-language implementation\n provided by Carlos Riofrío, Seth Merkel and Andrew Silberfarb.\n Used with permission.\n\n :param int d...
Please provide a description of the function: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_factor...
[ "\n Returns a TomographyBasis formed by the tensor\n product of two or more factor bases. Each basis element\n is the tensor product of basis elements from the underlying\n factors.\n " ]
Please provide a description of the function:def pauli_basis(nq=1): basis = tensor_product_basis(*[ TomographyBasis( gell_mann_basis(2).data[[0, 2, 3, 1]], [2], [u'𝟙', r'\sigma_x', r'\sigma_y', r'\sigma_z'] ) ] * nq) basis._name = 'pauli_basis' ...
[ "\n Returns a TomographyBasis for the Pauli basis on ``nq``\n qubits.\n\n :param int nq: Number of qubits on which the returned\n basis is defined.\n " ]
Please provide a description of the function: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))
[ "\n Converts a QuTiP-represented state into a model parameter vector.\n\n :param qutip.Qobj state: State to be converted.\n :rtype: :class:`np.ndarray`\n :return: The representation of the given state in this basis,\n as a vector of real parameters.\n " ]
Please provide a description of the function: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: ...
[ "\n Converts one or more vectors of model parameters into\n QuTiP-represented states.\n\n :param np.ndarray modelparams: Array of shape\n ``(basis.dim ** 2, )`` or\n ``(n_states, basis.dim ** 2)`` containing\n states represented as model parameter vectors in thi...
Please provide a description of the function: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 )
[ "\n Converts a covariance matrix to the corresponding\n superoperator, represented as a QuTiP Qobj\n with ``type=\"super\"``.\n " ]
Please provide a description of the function:def rescaled_distance_mtx(p, q): r # TODO: check that models are actually the same! p_locs = p.particle_locations if isinstance(p, qinfer.ParticleDistribution) else p q_locs = q.particle_locations if isinstance(q, qinfer.ParticleDistribution) else q Q = ...
[ "\n Given two particle updaters for the same model, returns a matrix\n :math:`\\matr{d}` with elements\n\n .. math::\n \\matr{d}_{i,j} = \\left\\Vert \\sqrt{\\matr{Q}} \\cdot\n (\\vec{x}_{p, i} - \\vec{x}_{q, j}) \\right\\Vert_2,\n\n where :math:`\\matr{Q}` is the scale matrix of the m...
Please provide a description of the function:def weighted_pairwise_distances(X, w, metric='euclidean', w_pow=0.5): r if sklearn is None: raise ImportError("This function requires scikit-learn.") base_metric = sklearn.metrics.pairwise.pairwise_distances(X, metric=metric) N = w.shape[0] w_ma...
[ "\n Given a feature matrix ``X`` with weights ``w``, calculates the modified\n distance metric :math:`\\tilde{d}(p, q) = d(p, q) / (w(p) w(q) N^2)^p`, where\n :math:`N` is the length of ``X``. This metric is such that \"heavy\" feature\n vectors are considered to be closer to each other than \"light\" f...
Please provide a description of the function: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 {}
[ "\n Returns a dictionary of keyword arguments\n for the k'th distribution.\n\n :param int k: Index of the distribution in question.\n :rtype: ``dict``\n " ]
Please provide a description of the function: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)]
[ "\n Returns random samples from the current particle distribution according\n to particle weights.\n\n :param int n: The number of samples to draw.\n :return: The sampled model parameter vectors.\n :rtype: `~numpy.ndarray` of shape ``(n, updater.n_rvs)``.\n " ]
Please provide a description of the function:def est_meanfn(self, fn): return np.einsum('i...,i...', self.particle_weights, fn(self.particle_locations) )
[ "\n Returns an the expectation value of a given function\n :math:`f` over the current particle distribution.\n\n Here, :math:`f` is represented by a function ``fn`` that is vectorized\n over particles, such that ``f(modelparams)`` has shape\n ``(n_particles, k)``, where ``n_partic...
Please provide a description of the function: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(d...
[ "\n Returns the full-rank covariance matrix of the current particle\n distribution.\n\n :param bool corr: If `True`, the covariance matrix is normalized\n by the outer product of the square root diagonal of the covariance matrix,\n i.e. the correlation matrix is returned i...
Please provide a description of the function:def est_entropy(self): r nz_weights = self.particle_weights[self.particle_weights > 0] return -np.sum(np.log(nz_weights) * nz_weights)
[ "\n Estimates the entropy of the current particle distribution\n as :math:`-\\sum_i w_i \\log w_i` where :math:`\\{w_i\\}`\n is the set of particles with nonzero weight.\n " ]
Please provide a description of the function:def _kl_divergence(self, other_locs, other_weights, kernel=None, delta=1e-2): if kernel is None: kernel = st.norm(loc=0, scale=1).pdf dist = rescaled_distance_mtx(self, other_locs) / delta K = kernel(dist) return -self.e...
[ "\n Finds the KL divergence between this and another particle\n distribution by using a kernel density estimator to smooth over the\n other distribution's particles.\n " ]
Please provide a description of the function:def est_kl_divergence(self, other, kernel=None, delta=1e-2): return self._kl_divergence( other.particle_locations, other.particle_weights, kernel, delta )
[ "\n Finds the KL divergence between this and another particle\n distribution by using a kernel density estimator to smooth over the\n other distribution's particles.\n\n :param SMCUpdater other:\n " ]
Please provide a description of the function:def est_cluster_metric(self, cluster_opts=None): wcv, bcv, tv = self.est_cluster_covs(cluster_opts) return np.diag(bcv) / np.diag(tv)
[ "\n Returns an estimate of how much of the variance in the current posterior\n can be explained by a separation between *clusters*.\n " ]
Please provide a description of the function: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_] ...
[ "\n Returns an array containing particles inside a credible region of a\n given level, such that the described region has probability mass\n no less than the desired level.\n\n Particles in the returned region are selected by including the highest-\n weight particles first until t...
Please provide a description of the function: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...
[ "\n Estimates a credible region over models by taking the convex hull of\n a credible subset of particles.\n\n :param float level: The desired crediblity level (see\n :meth:`SMCUpdater.est_credible_region`).\n :param slice modelparam_slice: Slice over which model parameters\n ...
Please provide a description of the function:def region_est_ellipsoid(self, level=0.95, tol=0.0001, modelparam_slice=None): r _, vertices = self.region_est_hull(level=level, modelparam_slice=modelparam_slice) A, centroid = u.mvee(vertices, tol) return A, centroid
[ "\n Estimates a credible region over models by finding the minimum volume\n enclosing ellipse (MVEE) of a credible subset of particles.\n\n :param float level: The desired crediblity level (see\n :meth:`SMCUpdater.est_credible_region`).\n :param float tol: The allowed error to...
Please provide a description of the function: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_, ...
[ "\n Decides whether each of the points lie within a credible region\n of the current distribution.\n\n If ``tol`` is ``None``, the particles are tested directly against\n the convex hull object. If ``tol`` is a positive ``float``,\n particles are tested to be in the interior of th...
Please provide a description of the function: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)) ...
[ "\n Returns one or more samples from this probability distribution.\n\n :param int n: Number of samples to return.\n :return numpy.ndarray: An array containing samples from the\n distribution of shape ``(n, d)``, where ``d`` is the number of\n random variables.\n " ...
Please provide a description of the function: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 ...
[ "Yield the service's actions with their arguments.\n\n Yields:\n `Action`: the next action.\n\n Each action is an Action namedtuple, consisting of action_name\n (a string), in_args (a list of Argument namedtuples consisting of name\n and argtype), and out_args (ditto), eg::\n\...
Please provide a description of the function: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...
[ "Parse the body of a UPnP event.\n\n Args:\n xml_event (bytes): bytes containing the body of the event encoded\n with utf-8.\n\n Returns:\n dict: A dict with keys representing the evented variables. The\n relevant value will usually be a string representation of the\n ...
Please provide a description of the function: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_r...
[ "Unsubscribe from the service's events.\n\n Once unsubscribed, a Subscription instance should not be reused\n " ]
Please provide a description of the function: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), ...
[ "Set the speaker's mode." ]
Please provide a description of the function:def repeat(self, repeat): shuffle = self.shuffle self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)]
[ "Set the queue's repeat option" ]
Please provide a description of the function:def cross_fade(self): response = self.avTransport.GetCrossfadeMode([ ('InstanceID', 0), ]) cross_fade_state = response['CrossfadeMode'] return bool(int(cross_fade_state))
[ "bool: The speaker's cross fade state.\n\n True if enabled, False otherwise\n " ]
Please provide a description of the function:def mute(self): response = self.renderingControl.GetMute([ ('InstanceID', 0), ('Channel', 'Master') ]) mute_state = response['CurrentMute'] return bool(int(mute_state))
[ "bool: The speaker's mute state.\n\n True if muted, False otherwise.\n " ]
Please provide a description of the function:def loudness(self): response = self.renderingControl.GetLoudness([ ('InstanceID', 0), ('Channel', 'Master'), ]) loudness = response["CurrentLoudness"] return bool(int(loudness))
[ "bool: The Sonos speaker's loudness compensation.\n\n True if on, False otherwise.\n\n Loudness is a complicated topic. You can find a nice summary about this\n feature here: http://forums.sonos.com/showthread.php?p=4698#post4698\n " ]
Please provide a description of the function:def join(self, master): self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', 'x-rincon:{0}'.format(master.uid)), ('CurrentURIMetaData', '') ]) self._zgs_cache.clear() self._parse_z...
[ "Join this speaker to another \"master\" speaker." ]
Please provide a description of the function:def unjoin(self): self.avTransport.BecomeCoordinatorOfStandaloneGroup([ ('InstanceID', 0) ]) self._zgs_cache.clear() self._parse_zone_group_state()
[ "Remove this speaker from a group.\n\n Seems to work ok even if you remove what was previously the group\n master from it's own group. If the speaker was not in a group also\n returns ok.\n " ]
Please provide a description of the function: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 c...
[ "Sets the sleep timer.\n\n Args:\n sleep_time_seconds (int or NoneType): How long to wait before\n turning off speaker in seconds, None to cancel a sleep timer.\n Maximum value of 86399\n\n Raises:\n SoCoException: Upon errors interacting with Sonos ...
Please provide a description of the function:def restore(self, fade=False): try: if self.is_coordinator: self._restore_coordinator() finally: self._restore_volume(fade) # Now everything is set, see if we need to be playing, stopped # or ...
[ "Restore the state of a device to that which was previously saved.\n\n For coordinator devices restore everything. For slave devices\n only restore volume etc., not transport info (transport info\n comes from the slave's coordinator).\n\n Args:\n fade (bool): Whether volume sh...
Please provide a description of the function: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_tr...
[ "Do the coordinator-only part of the restore." ]
Please provide a description of the function: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 alw...
[ "Reinstate volume.\n\n Args:\n fade (bool): Whether volume should be faded up on restore.\n " ]
Please provide a description of the function:def _discover_thread(callback, timeout, include_invisible, interface_addr): def create_socket(interface_addr=None): _sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM...
[ " Discover Sonos zones on the local network. ", " A helper function for creating a socket for discover purposes.\n\n Create and return a socket with appropriate options set for multicast.\n ", "\\\n M-SEARCH * HTTP/1.1\n HOST: 239.255.255.250:1900\n MAN: \"ssdp:discover\"\n ...
Please provide a description of the function:def discover_thread(callback, timeout=5, include_invisible=False, interface_addr=None): thread = StoppableThread( target=_discover_thread, args=(callback, timeout, include_invisible, interfa...
[ " Return a started thread with a discovery callback. " ]
Please provide a description of the function:def discover(timeout=5, include_invisible=False, interface_addr=None, all_households=False): found_zones = set() first_response = None def callback(zone): nonlocal first_response if first_response is ...
[ " Discover Sonos zones on the local network.\n\n Return a set of `SoCo` instances for each zone found.\n Include invisible zones (bridges and slave zones in stereo pairs if\n ``include_invisible`` is `True`. Will block for up to ``timeout`` seconds,\n after which return `None` if no zones found.\n\n ...
Please provide a description of the function:def by_name(name): devices = discover(all_households=True) for device in (devices or []): if device.player_name == name: return device return None
[ "Return a device by name.\n\n Args:\n name (str): The name of the device to return.\n\n Returns:\n :class:`~.SoCo`: The first device encountered among all zone with the\n given player name. If none are found `None` is returned.\n " ]
Please provide a description of the function:def get_ascii(pid=None, name=None, pokemons=None, return_pokemons=False, message=None): '''get_ascii will return ascii art for a pokemon based on a name or pid. :param pid: the pokemon ID to return :param name: the pokemon name to return :param return_pokemon...
[]
Please provide a description of the function:def get_avatar(name, pokemons=None, print_screen=True, include_name=True): '''get_avatar will return a unique pokemon for a specific avatar based on the hash :param name: the name to look up :param print_screen: if True, will print ascii to the screen (default Tr...
[]
Please provide a description of the function:def get_pokemon(pid=None,name=None,pokemons=None): '''get_pokemon will return a pokemon with a specific ID, or if none is given, will select randomly. First the pid will be used, then the name, then any filters. :param pid: the pokemon ID to return :param pok...
[]
Please provide a description of the function: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
[]
Please provide a description of the function:def catch_em_all(data_file=None, return_names=False): '''catch_em_all returns the entire database of pokemon, a base function for starting :param data_file: location of pokemons.json data file (not required) ''' if data_file == None: data_file = "%s/d...
[]
Please provide a description of the function:def lookup_pokemon(field,value,pokemons=None): '''lookup_pokemon will search a particular field (name) for a value. If no pokemons data structure is provided, all will be used. :param field: the field to look up. :param pokemons: the pokemons data structure ...
[]
Please provide a description of the function: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...
[ "Resizes an image preserving the aspect ratio.\n " ]
Please provide a description of the function: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)
[ "Maps each pixel to an ascii char based on the range\n in which it lies.\n\n 0-255 is divided into 11 ranges of 25 pixels each.\n " ]
Please provide a description of the function: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...
[ "Return a dictionary containing Steps read from file.\n\n Args:\n steps_dir (str, optional): path to directory containing CWL files.\n step_file (str, optional): path or http(s) url to a single CWL file.\n step_list (list, optional): a list of directories, urls or local file\n pat...
Please provide a description of the function: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)
[ "Return object in yaml file." ]
Please provide a description of the function: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) ...
[ "Sort step files into correct loading order.\n\n The correct loading order is first tools, then workflows without\n subworkflows, and then workflows with subworkflows. This order is\n required to avoid error messages when a working directory is used.\n " ]
Please provide a description of the function: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) ...
[ "Load and validate CWL file using cwltool\n " ]
Please provide a description of the function: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
[ "Set a Step's input variable to a certain value.\n\n The value comes either from a workflow input or output of a previous\n step.\n\n Args:\n name (str): the name of the Step input\n value (str): the name of the output variable that provides the\n value ...
Please provide a description of the function: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)
[ "Return a reference to the given output for use in an input\n of a next Step.\n\n For a Step named `echo` that has an output called `echoed`, the\n reference `echo/echoed` is returned.\n\n Args:\n name (str): the name of the Step output\n Raises:\n ValueE...
Please provide a description of the function: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 cas...
[ "Returns True if a step input parameter is optional.\n\n Args:\n inp (dict): a dictionary representation of an input.\n\n Raises:\n ValueError: The inp provided is not valid.\n " ]
Please provide a description of the function: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: ...
[ "Return the step as an dict that can be written to a yaml file.\n\n Returns:\n dict: yaml representation of the step.\n " ]
Please provide a description of the function: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)
[ "Return a string listing all the Step's input names and their types.\n\n The types are returned in a copy/pastable format, so if the type is\n `string`, `'string'` (with single quotes) is returned.\n\n Returns:\n str containing all input names and types.\n " ]
Please provide a description of the function: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)
[ "Load CWL steps into the WorkflowGenerator's steps library.\n\n Adds steps (command line tools and workflows) to the\n ``WorkflowGenerator``'s steps library. These steps can be used to\n create workflows.\n\n Args:\n steps_dir (str): path to directory containing CWL files. All...
Please provide a description of the function: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.\n\n Returns:\n bool: True if the workflow needs a requirements section, False\n otherwise.\n " ]
Please provide a description of the function: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.\n\n Args:\n name (str): name of a step in the steps library.\n " ]
Please provide a description of the function: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
[ "Add a step to the workflow.\n\n Args:\n step (Step): a step from the steps library.\n " ]
Please provide a description of the function:def add_input(self, **kwargs): self._closed() def _get_item(args): if not args: raise ValueError("No parameter specified.") item = args.popitem() if args: raise ValueEr...
[ "Add workflow input.\n\n Args:\n kwargs (dict): A dict with a `name: type` item\n and optionally a `default: value` item, where name is the\n name (id) of the workflow input (e.g., `dir_in`) and type is\n the type of the input (e.g., `'Directory'`).\n ...
Please provide a description of the function: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[nam...
[ "Add workflow outputs.\n\n The output type is added automatically, based on the steps in the steps\n library.\n\n Args:\n kwargs (dict): A dict containing ``name=source name`` pairs.\n ``name`` is the name of the workflow output (e.g.,\n ``txt_files``) a...
Please provide a description of the function: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' ...
[ "Return step from steps library.\n\n Optionally, the step returned is a deep copy from the step in the steps\n library, so additional information (e.g., about whether the step was\n scattered) can be stored in the copy.\n\n Args:\n name (str): name of the step in the steps lib...
Please provide a description of the function: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, V...
[ "Return the created workflow as a dict.\n\n The dict can be written to a yaml file.\n\n Returns:\n A yaml-compatible dict representing the workflow.\n " ]
Please provide a description of the function:def to_script(self, wf_name='wf'): self._closed() script = [] # Workflow documentation # if self.documentation: # if is_multiline(self.documentation): # print('doc = ') # print('{}.set_docume...
[ "Generated and print the scriptcwl script for the currunt workflow.\n\n Args:\n wf_name (str): string used for the WorkflowGenerator object in the\n generated script (default: ``wf``).\n ", "')\n # print(self.documentation)\n # print('" ]
Please provide a description of the function: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: retur...
[ "Returns False only if it can show that no value of type1\n can possibly match type2.\n\n Supports only a limited selection of types.\n " ]
Please provide a description of the function: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 workflow object.\n\n This method currently validates the workflow object with the use of\n cwltool. It writes the workflow to a tmp CWL file, reads it, validates\n it and removes the tmp file again. By default, the workflow is written\n to file using absolute paths to the steps...
Please provide a description of the function:def _pack(self, fname, encoding): (fd, tmpfile) = tempfile.mkstemp() os.close(fd) try: self.save(tmpfile, mode='abs', validate=False) document_loader, processobj, metadata, uri = load_cwl(tmpfile) finally: ...
[ "Save workflow with ``--pack`` option\n\n This means that al tools and subworkflows are included in the workflow\n file that is created. A packed workflow cannot be loaded and used in\n scriptcwl.\n " ]
Please provide a description of the function: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' ...
[ "Save the workflow to file.\n\n Save the workflow to a CWL file that can be run with a CWL runner.\n\n Args:\n fname (str): file to save the workflow to.\n mode (str): one of (rel, abs, wd, inline, pack)\n encoding (str): file encoding to use (default: ``utf-8``).\n ...
Please provide a description of the function:def add_inputs(self, **kwargs): msg = ('The add_inputs() function is deprecation in favour of the ' 'add_input() function, redirecting...') warnings.warn(msg, DeprecationWarning) return self.add_input(**kwargs)
[ "Deprecated function, use add_input(self, **kwargs) instead.\n Add workflow input.\n\n Args:\n kwargs (dict): A dict with a `name: type` item\n and optionally a `default: value` item, where name is the\n name (id) of the workflow input (e.g., `dir_in`) and type...
Please provide a description of the function: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)
[ "Return correct str_presenter to write multiple lines to a yaml field.\n\n\n Source: http://stackoverflow.com/a/33300001\n " ]
Please provide a description of the function: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 = [] ...
[ "Build the sparse m-by-n matrices that map a coefficient set for a function in V\n to the values of dx and dy at a number m of points.\n " ]
Please provide a description of the function: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 2...
[ "Linear operator that converts ax, ay to abcd.\n " ]
Please provide a description of the function: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....
[ "Residual formulation, Hessian is a low-rank update of the identity.\n " ]
Please provide a description of the function: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\n `a` and `b` must be equal.\n " ]
Please provide a description of the function: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(ob...
[ "Show a flat color gamut, by default xy. There exists a chroma gamut for\n all color models which transform lines in XYZ to lines, and hence have a\n natural decomposition into lightness and chroma components. Also, the flat\n gamut is the same for every lightness value. Examples for color models with\n ...
Please provide a description of the function:def plot_macadam( ellipse_scaling=10, plot_filter_positions=False, plot_standard_deviations=False, plot_rgb_triangle=True, plot_mesh=True, n=1, xy_to_2d=lambda xy: xy, axes_labels=("x", "y"), ): dir_path = os.path.dirname(os.path.real...
[ "See <https://en.wikipedia.org/wiki/MacAdam_ellipse>,\n <https://doi.org/10.1364%2FJOSA.32.000247>.\n " ]
Please provide a description of the function: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
[ "Evaluates the entire tree of 2d mononomials.\n\n The return value is a list of arrays, where `out[k]` hosts the `2*k+1`\n values of the `k`th level of the tree\n\n (0, 0)\n (1, 0) (0, 1)\n (2, 0) (1, 1) (0, 2)\n ... ... ...\n " ]
Please provide a description of the function:def _get_dx_tree(xy, degree): x, y = xy # build smaller tree one = numpy.array([numpy.ones(x.shape, dtype=int)]) tree = [one] for d in range(1, degree): tree.append( numpy.concatenate( [ # Inte...
[ "\n 0\n 1*(0, 0) 0\n 2*(1, 0) 1*(0, 1) 0\n 3*(2, 0) 2*(1, 1) 1*(0, 2) 0\n ... ... ... ...\n " ]
Please provide a description of the function:def jac(self, xy=None): if xy is not None: self.set_xy(xy) ux = numpy.dot(self.ax, self.xy_list[: len(self.ax)]) vx = numpy.dot(self.bx, self.xy_list[: len(self.bx)]) uy = numpy.dot(self.ay, self.xy_list[: len(self.ay)]) ...
[ "Get the Jacobian at (x, y).\n " ]
Please provide a description of the function: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 i...
[ "Computes the tristimulus values XYZ from a given spectrum for a given\n observer via\n\n X_i = int_lambda spectrum_i(lambda) * observer_i(lambda) dlambda.\n\n In section 7, the technical report CIE Standard Illuminants for\n Colorimetry, 1999, gives a recommendation on how to perform the\n computati...
Please provide a description of the function:def white_point(illuminant, observer=observers.cie_1931_2()): values = spectrum_to_xyz100(illuminant, observer) # normalize for relative luminance, Y=100 values /= values[1] values *= 100 return values
[ "From <https://en.wikipedia.org/wiki/White_point>:\n The white point of an illuminant is the chromaticity of a white object\n under the illuminant.\n " ]
Please provide a description of the function:def a(interval=1.0e-9): # https://en.wikipedia.org/wiki/Standard_illuminant#Illuminant_A lmbda = numpy.arange(300e-9, 831e-9, interval) c2 = 1.435e-2 color_temp = 2848 numpy.exp(c2 / (color_temp * 560e-9)) vals = ( 100 * (560e-9 /...
[ "CIE Standard Illuminants for Colorimetry, 1999:\n CIE standard illuminant A is intended to represent typical, domestic,\n tungsten-filament lighting. Its relative spectral power distribution is\n that of a Planckian radiator at a temperature of approximately 2856 K. CIE\n standard illuminant A should b...