INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return command-line parser.
def create_parser(): """Return command-line parser.""" parser = argparse.ArgumentParser(description=docstring_summary(__doc__), prog='autopep8') parser.add_argument('--version', action='version', version='%(prog)s {} ({})'.format( ...
Parse command-line options.
def parse_args(arguments, apply_config=False): """Parse command-line options.""" parser = create_parser() args = parser.parse_args(arguments) if not args.files and not args.list_fixes: parser.error('incorrect number of arguments') args.files = [decode_filename(name) for name in args.files]...
Return Unicode filename.
def decode_filename(filename): """Return Unicode filename.""" if isinstance(filename, unicode): return filename return filename.decode(sys.getfilesystemencoding())
Yield pep8 error codes that autopep8 fixes. Each item we yield is a tuple of the code followed by its description.
def supported_fixes(): """Yield pep8 error codes that autopep8 fixes. Each item we yield is a tuple of the code followed by its description. """ yield ('E101', docstring_summary(reindent.__doc__)) instance = FixPEP8(filename=None, options=None, contents='') for attribute in dir(instance):...
Return rank of candidate. This is for sorting candidates.
def line_shortening_rank(candidate, indent_word, max_line_length, experimental=False): """Return rank of candidate. This is for sorting candidates. """ if not candidate.strip(): return 0 rank = 0 lines = candidate.rstrip().split('\n') offset = 0 if ( ...
Return standard deviation.
def standard_deviation(numbers): """Return standard deviation.""" numbers = list(numbers) if not numbers: return 0 mean = sum(numbers) / len(numbers) return (sum((n - mean) ** 2 for n in numbers) / len(numbers)) ** .5
Return number of unmatched open/close brackets.
def count_unbalanced_brackets(line): """Return number of unmatched open/close brackets.""" count = 0 for opening, closing in ['()', '[]', '{}']: count += abs(line.count(opening) - line.count(closing)) return count
Split line at offsets. Return list of strings.
def split_at_offsets(line, offsets): """Split line at offsets. Return list of strings. """ result = [] previous_offset = 0 current_offset = 0 for current_offset in sorted(offsets): if current_offset < len(line) and previous_offset != current_offset: result.append(line[...
Return True if file is okay for modifying/recursing.
def match_file(filename, exclude): """Return True if file is okay for modifying/recursing.""" base_name = os.path.basename(filename) if base_name.startswith('.'): return False for pattern in exclude: if fnmatch.fnmatch(base_name, pattern): return False if fnmatch.fn...
Fix list of files. Optionally fix files recursively.
def fix_multiple_files(filenames, options, output=None): """Fix list of files. Optionally fix files recursively. """ results = [] filenames = find_files(filenames, options.recursive, options.exclude) if options.jobs > 1: import multiprocessing pool = multiprocessing.Pool(option...
Return output with specified encoding.
def wrap_output(output, encoding): """Return output with specified encoding.""" return codecs.getwriter(encoding)(output.buffer if hasattr(output, 'buffer') else output)
Return a version of the source code with PEP 8 violations fixed.
def fix(self): """Return a version of the source code with PEP 8 violations fixed.""" pep8_options = { 'ignore': self.options.ignore, 'select': self.options.select, 'max_line_length': self.options.max_line_length, 'hang_closing': self.options.hang_closing,...
Fix a badly indented line. This is done by adding or removing from its initial indent only.
def _fix_reindent(self, result): """Fix a badly indented line. This is done by adding or removing from its initial indent only. """ num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] self.source[l...
Fix under-indented comments.
def fix_e112(self, result): """Fix under-indented comments.""" line_index = result['line'] - 1 target = self.source[line_index] if not target.lstrip().startswith('#'): # Don't screw with invalid syntax. return [] self.source[line_index] = self.indent_wor...
Fix unexpected indentation.
def fix_e113(self, result): """Fix unexpected indentation.""" line_index = result['line'] - 1 target = self.source[line_index] indent = _get_indentation(target) stripped = target.lstrip() self.source[line_index] = indent[1:] + stripped
Fix indentation undistinguish from the next logical line.
def fix_e125(self, result): """Fix indentation undistinguish from the next logical line.""" num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] spaces_to_add = num_indent_spaces - len(_get_indentation(target)) ...
Fix indentation undistinguish from the next logical line.
def fix_e131(self, result): """Fix indentation undistinguish from the next logical line.""" num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] spaces_to_add = num_indent_spaces - len(_get_indentation(target)) ...
Remove extraneous whitespace around operator.
def fix_e224(self, result): """Remove extraneous whitespace around operator.""" target = self.source[result['line'] - 1] offset = result['column'] - 1 fixed = target[:offset] + target[offset:].replace('\t', ' ') self.source[result['line'] - 1] = fixed
Fix missing whitespace around operator.
def fix_e225(self, result): """Fix missing whitespace around operator.""" target = self.source[result['line'] - 1] offset = result['column'] - 1 fixed = target[:offset] + ' ' + target[offset:] # Only proceed if non-whitespace characters match. # And make sure we don't br...
Add missing whitespace.
def fix_e231(self, result): """Add missing whitespace.""" line_index = result['line'] - 1 target = self.source[line_index] offset = result['column'] fixed = target[:offset].rstrip() + ' ' + target[offset:].lstrip() self.source[line_index] = fixed
Remove whitespace around parameter '=' sign.
def fix_e251(self, result): """Remove whitespace around parameter '=' sign.""" line_index = result['line'] - 1 target = self.source[line_index] # This is necessary since pycodestyle sometimes reports columns that # goes past the end of the physical line. This happens in cases li...
Fix spacing after comment hash.
def fix_e262(self, result): """Fix spacing after comment hash.""" target = self.source[result['line'] - 1] offset = result['column'] code = target[:offset].rstrip(' \t#') comment = target[offset:].lstrip(' \t#') fixed = code + (' # ' + comment if comment.strip() else '...
Fix extraneous whitespace around keywords.
def fix_e271(self, result): """Fix extraneous whitespace around keywords.""" line_index = result['line'] - 1 target = self.source[line_index] offset = result['column'] - 1 fixed = fix_whitespace(target, offset=offset, ...
Add missing blank line.
def fix_e301(self, result): """Add missing blank line.""" cr = '\n' self.source[result['line'] - 1] = cr + self.source[result['line'] - 1]
Add missing 2 blank lines.
def fix_e302(self, result): """Add missing 2 blank lines.""" add_linenum = 2 - int(result['info'].split()[-1]) cr = '\n' * add_linenum self.source[result['line'] - 1] = cr + self.source[result['line'] - 1]
Remove extra blank lines.
def fix_e303(self, result): """Remove extra blank lines.""" delete_linenum = int(result['info'].split('(')[1].split(')')[0]) - 2 delete_linenum = max(1, delete_linenum) # We need to count because pycodestyle reports an offset line number if # there are comments. cnt = 0 ...
Remove blank line following function decorator.
def fix_e304(self, result): """Remove blank line following function decorator.""" line = result['line'] - 2 if not self.source[line].strip(): self.source[line] = ''
Add missing 2 blank lines after end of function or class.
def fix_e305(self, result): """Add missing 2 blank lines after end of function or class.""" add_delete_linenum = 2 - int(result['info'].split()[-1]) cnt = 0 offset = result['line'] - 2 modified_lines = [] if add_delete_linenum < 0: # delete cr add_...
Put imports on separate lines.
def fix_e401(self, result): """Put imports on separate lines.""" line_index = result['line'] - 1 target = self.source[line_index] offset = result['column'] - 1 if not target.lstrip().startswith('import'): return [] indentation = re.split(pattern=r'\bimport\b...
Remove extraneous escape of newline.
def fix_e502(self, result): """Remove extraneous escape of newline.""" (line_index, _, target) = get_index_offset_contents(result, self.source) self.source[line_index] = target.rstrip('\n\r \t\\') + '\n'
Put colon-separated compound statement on separate lines.
def fix_e701(self, result): """Put colon-separated compound statement on separate lines.""" line_index = result['line'] - 1 target = self.source[line_index] c = result['column'] fixed_source = (target[:c] + '\n' + _get_indentation(target) + self.indent_wo...
Put semicolon-separated compound statement on separate lines.
def fix_e702(self, result, logical): """Put semicolon-separated compound statement on separate lines.""" if not logical: return [] # pragma: no cover logical_lines = logical[2] # Avoid applying this when indented. # https://docs.python.org/reference/compound_stmts.h...
Fix multiple statements on one line def
def fix_e704(self, result): """Fix multiple statements on one line def""" (line_index, _, target) = get_index_offset_contents(result, self.source) match = STARTSWITH_DEF_REGEX.match(target) if match: self.source[line...
Fix comparison with None.
def fix_e711(self, result): """Fix comparison with None.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) right_offset = offset + 2 if right_offset >= len(target): return [] ...
Fix (trivial case of) comparison with boolean.
def fix_e712(self, result): """Fix (trivial case of) comparison with boolean.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # Handle very easy "not" special cases. if re.match(r'^\s*if [\...
Fix (trivial case of) non-membership check.
def fix_e713(self, result): """Fix (trivial case of) non-membership check.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # to convert once 'not in' -> 'in' before_target = target[:offset]...
Fix object identity should be 'is not' case.
def fix_e714(self, result): """Fix object identity should be 'is not' case.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # to convert once 'is not' -> 'is' before_target = target[:offset...
Fix do not assign a lambda expression check.
def fix_e731(self, result): """Fix do not assign a lambda expression check.""" (line_index, _, target) = get_index_offset_contents(result, self.source) match = LAMBDA_REGEX.search(target) if match: end = match.end() ...
Remove trailing whitespace.
def fix_w291(self, result): """Remove trailing whitespace.""" fixed_line = self.source[result['line'] - 1].rstrip() self.source[result['line'] - 1] = fixed_line + '\n'
Remove trailing blank lines.
def fix_w391(self, _): """Remove trailing blank lines.""" blank_count = 0 for line in reversed(self.source): line = line.rstrip() if line: break else: blank_count += 1 original_length = len(self.source) self.sou...
The size of the current line minus the indentation.
def current_size(self): """The size of the current line minus the indentation.""" size = 0 for item in reversed(self._lines): size += item.size if isinstance(item, self._LineBreak): break return size
Add an item to the line. Reflow the line to get the best formatting after the item is inserted. The bracket depth indicates if the item is being inserted inside of a container or not.
def _add_item(self, item, indent_amt): """Add an item to the line. Reflow the line to get the best formatting after the item is inserted. The bracket depth indicates if the item is being inserted inside of a container or not. """ if self._prev_item and self._prev_item.i...
Prevent splitting between a default initializer. When there is a default initializer, it's best to keep it all on the same line. It's nicer and more readable, even if it goes over the maximum allowable line length. This goes back along the current line to determine if we have a default ...
def _prevent_default_initializer_splitting(self, item, indent_amt): """Prevent splitting between a default initializer. When there is a default initializer, it's best to keep it all on the same line. It's nicer and more readable, even if it goes over the maximum allowable line length. T...
Enforce a space in certain situations. There are cases where we will want a space where normally we wouldn't put one. This just enforces the addition of a space.
def _enforce_space(self, item): """Enforce a space in certain situations. There are cases where we will want a space where normally we wouldn't put one. This just enforces the addition of a space. """ if isinstance(self._lines[-1], (self._Space, self._Line...
Delete all whitespace from the end of the line.
def _delete_whitespace(self): """Delete all whitespace from the end of the line.""" while isinstance(self._lines[-1], (self._Space, self._LineBreak, self._Indent)): del self._lines[-1]
The extent of the full element. E.g., the length of a function call or keyword.
def _get_extent(self, index): """The extent of the full element. E.g., the length of a function call or keyword. """ extent = 0 prev_item = get_item(self._items, index - 1) seen_dot = prev_item and unicode(prev_item) == '.' while index < len(self._items): ...
Fix indentation and return modified line numbers. Line numbers are indexed at 1.
def run(self, indent_size=DEFAULT_INDENT_SIZE): """Fix indentation and return modified line numbers. Line numbers are indexed at 1. """ if indent_size < 1: return self.input_text try: stats = _reindent_stats(tokenize.generate_tokens(self.getline)) ...
Line-getter for tokenize.
def getline(self): """Line-getter for tokenize.""" if self.index >= len(self.lines): line = '' else: line = self.lines[self.index] self.index += 1 return line
A stand-in for tokenize.generate_tokens().
def generate_tokens(self, text): """A stand-in for tokenize.generate_tokens().""" if text != self.last_text: string_io = io.StringIO(text) self.last_tokens = list( tokenize.generate_tokens(string_io.readline) ) self.last_text = text ...
reset filter back to state at time of construction
def reset(self): """ reset filter back to state at time of construction""" self.n = 0 # nth step in the recursion self.x = np.zeros(self._order + 1) self.K = np.zeros(self._order + 1) self.y = 0
Update filter with new measurement `z` Returns ------- x : np.array estimate for this time step (same as self.x)
def update(self, z): """ Update filter with new measurement `z` Returns ------- x : np.array estimate for this time step (same as self.x) """ self.n += 1 # rename for readability n = self.n dt = self.dt x = self.x K =...
Computes and returns the error and standard deviation of the filter at this time step. Returns ------- error : np.array size 1xorder+1 std : np.array size 1xorder+1
def errors(self): """ Computes and returns the error and standard deviation of the filter at this time step. Returns ------- error : np.array size 1xorder+1 std : np.array size 1xorder+1 """ n = self.n dt = self.dt order = self._...
Add a new measurement (z) to the Kalman filter. If z is None, nothing is changed. This can handle either the multidimensional or unidimensional case. If all parameters are floats instead of arrays the filter will still work, and return floats for x, P as the result. update(1, 2, 1, 1, 1) # univar...
def update(x, P, z, R, H=None, return_all=False): """ Add a new measurement (z) to the Kalman filter. If z is None, nothing is changed. This can handle either the multidimensional or unidimensional case. If all parameters are floats instead of arrays the filter will still work, and return float...
Add a new measurement (z) to the Kalman filter. If z is None, nothing is changed. Parameters ---------- x : numpy.array(dim_x, 1), or float State estimate vector z : (dim_z, 1): array_like measurement for this update. z can be a scalar if dim_z is 1, otherwise it must be...
def update_steadystate(x, z, K, H=None): """ Add a new measurement (z) to the Kalman filter. If z is None, nothing is changed. Parameters ---------- x : numpy.array(dim_x, 1), or float State estimate vector z : (dim_z, 1): array_like measurement for this update. z can be...
Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- x : numpy.array State estimate vector P : numpy.array Covariance matrix F : numpy.array() State Transition matrix Q : numpy.array, Optional Process noise...
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.): """ Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- x : numpy.array State estimate vector P : numpy.array Covariance matrix F : numpy.array() State Transitio...
Predict next state (prior) using the Kalman filter state propagation equations. This steady state form only computes x, assuming that the covariance is constant. Parameters ---------- x : numpy.array State estimate vector P : numpy.array Covariance matrix F : numpy.array(...
def predict_steadystate(x, F=1, u=0, B=1): """ Predict next state (prior) using the Kalman filter state propagation equations. This steady state form only computes x, assuming that the covariance is constant. Parameters ---------- x : numpy.array State estimate vector P : nump...
Batch processes a sequences of measurements. Parameters ---------- zs : list-like list of measurements at each time step. Missing measurements must be represented by None. Fs : list-like list of values to use for the state transition matrix matrix. Qs : list-like ...
def batch_filter(x, P, zs, Fs, Qs, Hs, Rs, Bs=None, us=None, update_first=False, saver=None): """ Batch processes a sequences of measurements. Parameters ---------- zs : list-like list of measurements at each time step. Missing measurements must be represented by N...
Runs the Rauch-Tung-Striebal Kalman smoother on a set of means and covariances computed by a Kalman filter. The usual input would come from the output of `KalmanFilter.batch_filter()`. Parameters ---------- Xs : numpy.array array of the means (state variable x) of the output of a Kalman ...
def rts_smoother(Xs, Ps, Fs, Qs): """ Runs the Rauch-Tung-Striebal Kalman smoother on a set of means and covariances computed by a Kalman filter. The usual input would come from the output of `KalmanFilter.batch_filter()`. Parameters ---------- Xs : numpy.array array of the means (s...
Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- u : np.array Optional control vector. If not `None`, it is multiplied by B to create the control input into the system. B : np.array(dim_x, dim_z), or ...
def predict(self, u=None, B=None, F=None, Q=None): """ Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- u : np.array Optional control vector. If not `None`, it is multiplied by B to create the ...
Predict state (prior) using the Kalman filter state propagation equations. Only x is updated, P is left unchanged. See update_steadstate() for a longer explanation of when to use this method. Parameters ---------- u : np.array Optional control vector. If non...
def predict_steadystate(self, u=0, B=None): """ Predict state (prior) using the Kalman filter state propagation equations. Only x is updated, P is left unchanged. See update_steadstate() for a longer explanation of when to use this method. Parameters ---------- ...
Add a new measurement (z) to the Kalman filter without recomputing the Kalman gain K, the state covariance P, or the system uncertainty S. You can use this for LTI systems since the Kalman gain and covariance converge to a fixed value. Precompute these and assign them explicitly, ...
def update_steadystate(self, z): """ Add a new measurement (z) to the Kalman filter without recomputing the Kalman gain K, the state covariance P, or the system uncertainty S. You can use this for LTI systems since the Kalman gain and covariance converge to a fixed value...
Add a new measurement (z) to the Kalman filter assuming that process noise and measurement noise are correlated as defined in the `self.M` matrix. If z is None, nothing is changed. Parameters ---------- z : (dim_z, 1): array_like measurement for this update....
def update_correlated(self, z, R=None, H=None): """ Add a new measurement (z) to the Kalman filter assuming that process noise and measurement noise are correlated as defined in the `self.M` matrix. If z is None, nothing is changed. Parameters ---------- z : (di...
Batch processes a sequences of measurements. Parameters ---------- zs : list-like list of measurements at each time step `self.dt`. Missing measurements must be represented by `None`. Fs : None, list-like, default=None optional value or list of valu...
def batch_filter(self, zs, Fs=None, Qs=None, Hs=None, Rs=None, Bs=None, us=None, update_first=False, saver=None): """ Batch processes a sequences of measurements. Parameters ---------- zs : list-like list of measurements at each tim...
Runs the Rauch-Tung-Striebal Kalman smoother on a set of means and covariances computed by a Kalman filter. The usual input would come from the output of `KalmanFilter.batch_filter()`. Parameters ---------- Xs : numpy.array array of the means (state variable x) of th...
def rts_smoother(self, Xs, Ps, Fs=None, Qs=None, inv=np.linalg.inv): """ Runs the Rauch-Tung-Striebal Kalman smoother on a set of means and covariances computed by a Kalman filter. The usual input would come from the output of `KalmanFilter.batch_filter()`. Parameters --...
Predicts the next state of the filter and returns it without altering the state of the filter. Parameters ---------- u : np.array optional control input Returns ------- (x, P) : tuple State vector and covariance array of the prediction.
def get_prediction(self, u=0): """ Predicts the next state of the filter and returns it without altering the state of the filter. Parameters ---------- u : np.array optional control input Returns ------- (x, P) : tuple S...
Computes the new estimate based on measurement `z` and returns it without altering the state of the filter. Parameters ---------- z : (dim_z, 1): array_like measurement for this update. z can be a scalar if dim_z is 1, otherwise it must be convertible to a colum...
def get_update(self, z=None): """ Computes the new estimate based on measurement `z` and returns it without altering the state of the filter. Parameters ---------- z : (dim_z, 1): array_like measurement for this update. z can be a scalar if dim_z is 1, ...
log-likelihood of the last measurement.
def log_likelihood(self): """ log-likelihood of the last measurement. """ if self._log_likelihood is None: self._log_likelihood = logpdf(x=self.y, cov=self.S) return self._log_likelihood
Computed from the log-likelihood. The log-likelihood can be very small, meaning a large negative value such as -28000. Taking the exp() of that results in 0.0, which can break typical algorithms which multiply by this value, so by default we always return a number >= sys.float_info.min.
def likelihood(self): """ Computed from the log-likelihood. The log-likelihood can be very small, meaning a large negative value such as -28000. Taking the exp() of that results in 0.0, which can break typical algorithms which multiply by this value, so by default we always retu...
Mahalanobis distance of measurement. E.g. 3 means measurement was 3 standard deviations away from the predicted value. Returns ------- mahalanobis : float
def mahalanobis(self): """" Mahalanobis distance of measurement. E.g. 3 means measurement was 3 standard deviations away from the predicted value. Returns ------- mahalanobis : float """ if self._mahalanobis is None: self._mahalanobis = sqrt(f...
log likelihood of the measurement `z`. This should only be called after a call to update(). Calling after predict() will yield an incorrect result.
def log_likelihood_of(self, z): """ log likelihood of the measurement `z`. This should only be called after a call to update(). Calling after predict() will yield an incorrect result.""" if z is None: return log(sys.float_info.min) return logpdf(z, dot(self.H...
Computes the sigma points for an unscented Kalman filter given the mean (x) and covariance(P) of the filter. Returns tuple of the sigma points and weights. Works with both scalar and array inputs: sigma_points (5, 9, 2) # mean 5, covariance 9 sigma_points ([5, 2], 9*eye(2), 2) #...
def sigma_points(self, x, P): """ Computes the sigma points for an unscented Kalman filter given the mean (x) and covariance(P) of the filter. Returns tuple of the sigma points and weights. Works with both scalar and array inputs: sigma_points (5, 9, 2) # mean 5, covariance 9 ...
Computes the weights for the scaled unscented Kalman filter.
def _compute_weights(self): """ Computes the weights for the scaled unscented Kalman filter. """ n = self.n lambda_ = self.alpha**2 * (n +self.kappa) - n c = .5 / (n + lambda_) self.Wc = np.full(2*n + 1, c) self.Wm = np.full(2*n + 1, c) self.Wc[0] = lam...
Computes the weights for the unscented Kalman filter. In this formulation the weights for the mean and covariance are the same.
def _compute_weights(self): """ Computes the weights for the unscented Kalman filter. In this formulation the weights for the mean and covariance are the same. """ n = self.n k = self.kappa self.Wm = np.full(2*n+1, .5 / (n + k)) self.Wm[0] = k / (n+k) se...
Computes the implex sigma points for an unscented Kalman filter given the mean (x) and covariance(P) of the filter. Returns tuple of the sigma points and weights. Works with both scalar and array inputs: sigma_points (5, 9, 2) # mean 5, covariance 9 sigma_points ([5, 2], 9*eye(2...
def sigma_points(self, x, P): """ Computes the implex sigma points for an unscented Kalman filter given the mean (x) and covariance(P) of the filter. Returns tuple of the sigma points and weights. Works with both scalar and array inputs: sigma_points (5, 9, 2) # mean 5, ...
Computes the weights for the scaled unscented Kalman filter.
def _compute_weights(self): """ Computes the weights for the scaled unscented Kalman filter. """ n = self.n c = 1. / (n + 1) self.Wm = np.full(n + 1, c) self.Wc = self.Wm
r""" Computes unscented transform of a set of sigma points and weights. returns the mean and covariance in a tuple. This works in conjunction with the UnscentedKalmanFilter class. Parameters ---------- sigmas: ndarray, of size (n, 2n+1) 2D array of sigma points. Wm : ndarray [# ...
def unscented_transform(sigmas, Wm, Wc, noise_cov=None, mean_fn=None, residual_fn=None): r""" Computes unscented transform of a set of sigma points and weights. returns the mean and covariance in a tuple. This works in conjunction with the UnscentedKalmanFilter class. Para...
Computes the Mahalanobis distance between the state vector x from the Gaussian `mean` with covariance `cov`. This can be thought as the number of standard deviations x is from the mean, i.e. a return value of 3 means x is 3 std from mean. Parameters ---------- x : (N,) array_like, or float ...
def mahalanobis(x, mean, cov): """ Computes the Mahalanobis distance between the state vector x from the Gaussian `mean` with covariance `cov`. This can be thought as the number of standard deviations x is from the mean, i.e. a return value of 3 means x is 3 std from mean. Parameters ------...
Returns log-likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance error R
def log_likelihood(z, x, P, H, R): """ Returns log-likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance error R """ S = np.dot(H, np.dot(P, H.T)) + R return logpdf(z, np.dot(H, x), S)
Returns likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance error R
def likelihood(z, x, P, H, R): """ Returns likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance error R """ return np.exp(log_likelihood(z, x, P, H, R))
Computes the log of the probability density function of the normal N(mean, cov) for the data x. The normal may be univariate or multivariate. Wrapper for older versions of scipy.multivariate_normal.logpdf which don't support support the allow_singular keyword prior to verion 0.15.0. If it is not suppo...
def logpdf(x, mean=None, cov=1, allow_singular=True): """ Computes the log of the probability density function of the normal N(mean, cov) for the data x. The normal may be univariate or multivariate. Wrapper for older versions of scipy.multivariate_normal.logpdf which don't support support the allo...
returns normal distribution (pdf) for x given a Gaussian with the specified mean and variance. All must be scalars. gaussian (1,2,3) is equivalent to scipy.stats.norm(2,math.sqrt(3)).pdf(1) It is quite a bit faster albeit much less flexible than the latter. Parameters ---------- x : scalar or...
def gaussian(x, mean, var, normed=True): """ returns normal distribution (pdf) for x given a Gaussian with the specified mean and variance. All must be scalars. gaussian (1,2,3) is equivalent to scipy.stats.norm(2,math.sqrt(3)).pdf(1) It is quite a bit faster albeit much less flexible than the latt...
Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF, so it is safe to treat the output as a PDF for any filter using ...
def mul(mean1, var1, mean2, var2): """ Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF, so it is safe to ...
Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var, scale_factor). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF. `scale_factor` provides this proportionality const...
def mul_pdf(mean1, var1, mean2, var2): """ Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var, scale_factor). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF....
This is designed to replace scipy.stats.multivariate_normal which is not available before version 0.14. You may either pass in a multivariate set of data: .. code-block:: Python multivariate_gaussian (array([1,1]), array([3,4]), eye(2)*1.4) multivariate_gaussian (array([1,1,1]), array([3,4,5...
def multivariate_gaussian(x, mu, cov): """ This is designed to replace scipy.stats.multivariate_normal which is not available before version 0.14. You may either pass in a multivariate set of data: .. code-block:: Python multivariate_gaussian (array([1,1]), array([3,4]), eye(2)*1.4) ...
Multiplies the two multivariate Gaussians together and returns the results as the tuple (mean, covariance). Examples -------- .. code-block:: Python m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]], [3.2, 0], [[8.0, 1.1], [1.1,8.0]]) Pa...
def multivariate_multiply(m1, c1, m2, c2): """ Multiplies the two multivariate Gaussians together and returns the results as the tuple (mean, covariance). Examples -------- .. code-block:: Python m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]], ...
Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-axis shows the cumulative probability. Parameters ---------- xs : list-like of scalars x values corresponding to the values in `y`s. Can be `None`, in which case range(len(ys)) will be use...
def plot_discrete_cdf(xs, ys, ax=None, xlabel=None, ylabel=None, label=None): """ Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-axis shows the cumulative probability. Parameters ---------- xs : list-like of scalars ...
Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-axis shows the cumulative probability. Parameters ---------- mean : scalar, default 0. mean for the normal distribution. variance : scalar, default 0. variance for the normal distribu...
def plot_gaussian_cdf(mean=0., variance=1., ax=None, xlim=None, ylim=(0., 1.), xlabel=None, ylabel=None, label=None): """ Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-...
Plots a normal distribution PDF with the given mean and variance. x-axis contains the mean, the y-axis shows the probability density. Parameters ---------- mean : scalar, default 0. mean for the normal distribution. variance : scalar, default 1., optional variance for the normal d...
def plot_gaussian_pdf(mean=0., variance=1., std=None, ax=None, mean_line=False, xlim=None, ylim=None, xlabel=None, ylabel=None, label=None): """ Plots a norma...
DEPRECATED. Use plot_gaussian_pdf() instead. This is poorly named, as there are multiple ways to plot a Gaussian.
def plot_gaussian(mean=0., variance=1., ax=None, mean_line=False, xlim=None, ylim=None, xlabel=None, ylabel=None, label=None): """ DEPRECATED. Use plot_gaussian_pdf() instead. This is po...
Returns a tuple defining the ellipse representing the 2 dimensional covariance matrix P. Parameters ---------- P : nd.array shape (2,2) covariance matrix deviations : int (optional, default = 1) # of standard deviations. Default is 1. Returns (angle_radians, width_radius, heigh...
def covariance_ellipse(P, deviations=1): """ Returns a tuple defining the ellipse representing the 2 dimensional covariance matrix P. Parameters ---------- P : nd.array shape (2,2) covariance matrix deviations : int (optional, default = 1) # of standard deviations. Default i...
Computes eigenvalues and eigenvectors of a covariance matrix and returns them sorted by eigenvalue. Parameters ---------- cov : ndarray covariance matrix asc : bool, default=True determines whether we are sorted smallest to largest (asc=True), or largest to smallest (asc=Fa...
def _eigsorted(cov, asc=True): """ Computes eigenvalues and eigenvectors of a covariance matrix and returns them sorted by eigenvalue. Parameters ---------- cov : ndarray covariance matrix asc : bool, default=True determines whether we are sorted smallest to largest (asc=Tr...
Deprecated function to plot a covariance ellipse. Use plot_covariance instead. See Also -------- plot_covariance
def plot_covariance_ellipse( mean, cov=None, variance=1.0, std=None, ellipse=None, title=None, axis_equal=True, show_semiaxis=False, facecolor=None, edgecolor=None, fc='none', ec='#004080', alpha=1.0, xlim=None, ylim=None, ls='solid'): """ Deprecated function to p...
Convienence function for plotting. Given one of var, standard deviation, or interval, return the std. Any of the three can be an iterable list. Examples -------- >>>_std_tuple_of(var=[1, 3, 9]) (1, 2, 3)
def _std_tuple_of(var=None, std=None, interval=None): """ Convienence function for plotting. Given one of var, standard deviation, or interval, return the std. Any of the three can be an iterable list. Examples -------- >>>_std_tuple_of(var=[1, 3, 9]) (1, 2, 3) """ if std is n...
Plots the covariance ellipse for the 2D normal defined by (mean, cov) `variance` is the normal sigma^2 that we want to plot. If list-like, ellipses for all ellipses will be ploted. E.g. [1,2] will plot the sigma^2 = 1 and sigma^2 = 2 ellipses. Alternatively, use std for the standard deviation, in which...
def plot_covariance( mean, cov=None, variance=1.0, std=None, interval=None, ellipse=None, title=None, axis_equal=True, show_semiaxis=False, show_center=True, facecolor=None, edgecolor=None, fc='none', ec='#004080', alpha=1.0, xlim=None, ylim=None, ls='solid'): ...
Computes the probability that a Gaussian distribution lies within a range of values. Parameters ---------- x_range : (float, float) tuple of range to compute probability for mu : float mean of the Gaussian var : float, optional variance of the Gaussian. Ignored if `st...
def norm_cdf(x_range, mu, var=1, std=None): """ Computes the probability that a Gaussian distribution lies within a range of values. Parameters ---------- x_range : (float, float) tuple of range to compute probability for mu : float mean of the Gaussian var : float, o...
If x is a scalar, returns a covariance matrix generated from it as the identity matrix multiplied by x. The dimension will be nxn. If x is already a 2D numpy array then it is returned unchanged. Raises ValueError if not positive definite
def _to_cov(x, n): """ If x is a scalar, returns a covariance matrix generated from it as the identity matrix multiplied by x. The dimension will be nxn. If x is already a 2D numpy array then it is returned unchanged. Raises ValueError if not positive definite """ if np.isscalar(x): ...
return random number distributed by student's t distribution with `df` degrees of freedom with the specified mean and standard deviation.
def rand_student_t(df, mu=0, std=1): """ return random number distributed by student's t distribution with `df` degrees of freedom with the specified mean and standard deviation. """ x = random.gauss(0, std) y = 2.0*random.gammavariate(0.5 * df, 2.0) return x / (math.sqrt(y / df)) + mu
Computes the normalized estimated error squared test on a sequence of estimates. The estimates are optimal if the mean error is zero and the covariance matches the Kalman filter's covariance. If this holds, then the mean of the NESS should be equal to or less than the dimension of x. Examples -...
def NESS(xs, est_xs, ps): """ Computes the normalized estimated error squared test on a sequence of estimates. The estimates are optimal if the mean error is zero and the covariance matches the Kalman filter's covariance. If this holds, then the mean of the NESS should be equal to or less than the d...
r""" Creates cubature points for the the specified state and covariance according to [1]. Parameters ---------- x: ndarray (column vector) examples: np.array([[1.], [2.]]) P : scalar, or np.array Covariance of the filter. References ---------- .. [1] Arasaratnam, I, ...
def spherical_radial_sigmas(x, P): r""" Creates cubature points for the the specified state and covariance according to [1]. Parameters ---------- x: ndarray (column vector) examples: np.array([[1.], [2.]]) P : scalar, or np.array Covariance of the filter. References ...
Compute mean and covariance of array of cubature points. Parameters ---------- Xs : ndarray Cubature points Q : ndarray Noise covariance Returns ------- mean : ndarray mean of the cubature points variance: ndarray covariance matrix of the cubature ...
def ckf_transform(Xs, Q): """ Compute mean and covariance of array of cubature points. Parameters ---------- Xs : ndarray Cubature points Q : ndarray Noise covariance Returns ------- mean : ndarray mean of the cubature points variance: ndarray ...