text
stringlengths
81
112k
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 ...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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, ...
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...
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...
Plots a covariance matrix `cov` as a 3D ellipsoid centered around the `mean`. Parameters ---------- mean : 3-vector mean in x, y, z. Can be any type convertable to a row vector. cov : ndarray 3x3 covariance matrix std : double, default=1 standard deviation of ellipsoi...
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,...
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...
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...
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...
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 covarianc...
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 standa...
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 -...
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, ...
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 ...
r""" Performs the predict step of the CKF. On return, self.x and self.P contain the predicted state (x) and covariance (P). Important: this MUST be called before update() is called for the first time. Parameters ---------- dt : double, optional If specified...
Update the CKF with the given measurements. On return, self.x and self.P contain the new mean and covariance of the filter. Parameters ---------- z : numpy.array of shape (dim_z) measurement vector R : numpy.array((dim_z, dim_z)), optional Measurement n...
Add a new measurement (z) to the kalman filter. If z is None, nothing is changed. Parameters ---------- z : np.array measurement for this update. R : np.array, scalar, or None Optionally provide R to override the measurement noise for this o...
Predict next position. Parameters ---------- u : ndarray Optional control vector. If non-zero, it is multiplied by B to create the control input into the system. def predict(self, u=0): """ Predict next position. Parameters ---------- ...
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'. Rs : list-like, optional optional list of values to use for the me...
State Transition matrix def F(self, value): """State Transition matrix""" self._F = value self._F_inv = self.inv(self._F)
computes 4th order Runge-Kutta for dy/dx. Parameters ---------- y : scalar Initial/current value for y x : scalar Initial/current value for x dx : scalar difference in x (e.g. the time step) f : ufunc(y,x) Callable function (y, x) that you supply to compute dy/d...
Generates a pretty printed NumPy array with an assignment. Optionally transposes column vectors so they are drawn on one line. Strictly speaking arr can be any time convertible by `str(arr)`, but the output may not be what you want if the type of the variable is not a scalar or an ndarray. Examples...
ensure z is a (dim_z, 1) shaped vector def reshape_z(z, dim_z, ndim): """ ensure z is a (dim_z, 1) shaped vector""" z = np.atleast_2d(z) if z.shape[1] == dim_z: z = z.T if z.shape != (dim_z, 1): raise ValueError('z must be convertible to shape ({}, 1)'.format(dim_z)) if ndim == 1...
Computes the inverse of a diagonal NxN np.array S. In general this will be much faster than calling np.linalg.inv(). However, does NOT check if the off diagonal elements are non-zero. So long as S is truly diagonal, the output is identical to np.linalg.inv(). Parameters ---------- S : np.array...
Computes the sum of the outer products of the rows in A and B P = \Sum {A[i] B[i].T} for i in 0..N Notionally: P = 0 for y in A: P += np.outer(y, y) This is a standard computation for sigma points used in the UKF, ensemble Kalman filter, etc., where A would be the...
save the current state of the Kalman filter def save(self): """ save the current state of the Kalman filter""" kf = self._kf # force all attributes to be computed. this is only necessary # if the class uses properties that compute data only when # accessed for prop in ...
Convert all saved attributes from a list to np.array. This may or may not work - every saved attribute must have the same shape for every instance. i.e., if `K` changes shape due to `z` changing shape then the call will raise an exception. This can also happen if the default initializa...
Flattens any np.array of column vectors into 1D arrays. Basically, this makes data readable for humans if you are just inspecting via the REPL. For example, if you have saved a KalmanFilter object with 89 epochs, self.x will be shape (89, 9, 1) (for example). After flatten is run, self.x...
Add a new measurement (z) to the Kalman filter. If z is None, nothing is changed. Parameters ---------- z : np.array measurement for this update. def update(self, z): """ Add a new measurement (z) to the Kalman filter. If z is None, nothing is chang...
Predict next state (prior) using the IMM 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. def predict(self, u=None): """ P...
Computes the IMM's mixed state estimate from each filter using the the mode probability self.mu to weight the estimates. def _compute_state_estimate(self): """ Computes the IMM's mixed state estimate from each filter using the the mode probability self.mu to weight the estimates. ...
Compute the mixing probability for each filter. def _compute_mixing_probabilities(self): """ Compute the mixing probability for each filter. """ self.cbar = dot(self.mu, self.M) for i in range(self.N): for j in range(self.N): self.omega[i, j] = (self...
r""" Performs the predict step of the UKF. On return, self.x and self.P contain the predicted state (x) and covariance (P). ' Important: this MUST be called before update() is called for the first time. Parameters ---------- dt : double, optional If...
Update the UKF with the given measurements. On return, self.x and self.P contain the new mean and covariance of the filter. Parameters ---------- z : numpy.array of shape (dim_z) measurement vector R : numpy.array((dim_z, dim_z)), optional Measurement n...
Compute cross variance of the state `x` and measurement `z`. def cross_variance(self, x, z, sigmas_f, sigmas_h): """ Compute cross variance of the state `x` and measurement `z`. """ Pxz = zeros((sigmas_f.shape[1], sigmas_h.shape[1])) N = sigmas_f.shape[0] for i in range...
computes the values of sigmas_f. Normally a user would not call this, but it is useful if you need to call update more than once between calls to predict (to update for multiple simultaneous measurements), so the sigmas correctly reflect the updated state x, P. def compute_process_sigma...
Performs the UKF filter over the list of measurement in `zs`. Parameters ---------- zs : list-like list of measurements at each time step `self._dt` Missing measurements must be represented by 'None'. Rs : None, np.array or list-like, default=None o...
Runs the Rauch-Tung-Striebal Kalman smoother on a set of means and covariances computed by the UKF. The usual input would come from the output of `batch_filter()`. Parameters ---------- Xs : numpy.array array of the means (state variable x) of the output of a Kalman ...
Returns slant range to the object. Call once for each new measurement at dt time from last call. def get_range(self, process_err_pct=0.05): """ Returns slant range to the object. Call once for each new measurement at dt time from last call. """ vel = self.vel + 5 * rand...
Predict next position using the Kalman filter state propagation equations for each filter in the bank. Parameters ---------- u : np.array Optional control vector. If non-zero, it is multiplied by B to create the control input into the system. def predict(self, ...
Add a new measurement (z) to the Kalman filter. If z is None, nothing is changed. Parameters ---------- z : np.array measurement for this update. R : np.array, scalar, or None Optionally provide R to override the measurement noise for this o...
Performs the residual resampling algorithm used by particle filters. Based on observation that we don't need to use random numbers to select most of the weights. Take int(N*w^i) samples of each particle i, and then resample any remaining using a standard resampling algorithm [1] Parameters ------...
Performs the stratified resampling algorithm used by particle filters. This algorithms aims to make selections relatively uniformly across the particles. It divides the cumulative sum of the weights into N equal divisions, and then selects one particle randomly from each division. This guarantees that ...
Performs the systemic resampling algorithm used by particle filters. This algorithm separates the sample space into N divisions. A single random offset is used to to choose where to sample from for all divisions. This guarantees that every sample is exactly 1/N apart. Parameters ---------- wei...
This is the naive form of roulette sampling where we compute the cumulative sum of the weights and then use binary search to select the resampled point based on a uniformly distributed random number. Run time is O(n log n). You do not want to use this algorithm in practice; for some reason it is popular...
Add a new measurement `z` to the H-Infinity filter. If `z` is None, nothing is changed. Parameters ---------- z : ndarray measurement for this update. def update(self, z): """ Add a new measurement `z` to the H-Infinity filter. If `z` is None, nothin...
Predict next position. Parameters ---------- u : ndarray Optional control vector. If non-zero, it is multiplied by `B` to create the control input into the system. def predict(self, u=0): """ Predict next position. Parameters ---------- ...
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'. update_first : bool, default=False, optional, controls whether the ...
Predicts the next state of the filter and returns it. Does not alter the state of the filter. Parameters ---------- u : ndarray optional control input Returns ------- x : ndarray State vector of the prediction. def get_prediction(self, u...
measurement noise matrix def V(self, value): """ measurement noise matrix""" if np.isscalar(value): self._V = np.array([[value]], dtype=float) else: self._V = value self._V_inv = linalg.inv(self._V)
Add a new measurement (z) to the kalman filter. If z is None, nothing is changed. Parameters ---------- z : np.array measurement for this update. R2 : np.array, scalar, or None Sqrt of meaaurement noize. Optionally provide to override the me...
Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- u : np.array, optional Optional control vector. If non-zero, it is multiplied by B to create the control input into the system. def predict(self, u=0): ...
Process uncertainty def Q(self, value): """ Process uncertainty""" self._Q = value self._Q1_2 = cholesky(self._Q, lower=True)
covariance matrix def P(self, value): """ covariance matrix""" self._P = value self._P1_2 = cholesky(self._P, lower=True)
measurement uncertainty def R(self, value): """ measurement uncertainty""" self._R = value self._R1_2 = cholesky(self._R, lower=True)
This hook is called to determine if the websocket should return an HTTP response and close. Our behavior here is to start the ASGI application, and then wait for either `accept` or `close` in order to determine if we should close the connection. async def process_request(self, path, he...
This is the main handler function for the 'websockets' implementation to call into. We just wait for close then return, and instead allow 'send' and 'receive' events to drive the flow. async def ws_handler(self, protocol, path): """ This is the main handler function for the 'websockets'...
Wrapper around the ASGI callable, handling exceptions and unexpected termination states. async def run_asgi(self): """ Wrapper around the ASGI callable, handling exceptions and unexpected termination states. """ try: result = await self.app(self.scope, self.a...
Called by the server to commence a graceful shutdown. def shutdown(self): """ Called by the server to commence a graceful shutdown. """ if self.cycle is None or self.cycle.response_complete: self.transport.close() else: self.cycle.keep_alive = False
Called by the server to commence a graceful shutdown. def shutdown(self): """ Called by the server to commence a graceful shutdown. """ if self.cycle is None or self.cycle.response_complete: event = h11.ConnectionClosed() self.conn.send(event) self.tr...
Called on a keep-alive connection if no new data is received after a short delay. def timeout_keep_alive_handler(self): """ Called on a keep-alive connection if no new data is received after a short delay. """ if not self.transport.is_closing(): event = h11.ConnectionClosed(...
Builds a scope and request message into a WSGI environ object. def build_environ(scope, message, body): """ Builds a scope and request message into a WSGI environ object. """ environ = { "REQUEST_METHOD": scope["method"], "SCRIPT_NAME": "", "PATH_INFO": scope["path"], "Q...
Return an ASGI message, with any body-type content omitted and replaced with a placeholder. def message_with_placeholders(message): """ Return an ASGI message, with any body-type content omitted and replaced with a placeholder. """ new_message = message.copy() for attr in PLACEHOLDER_FORMAT...
setup root logger with ColoredFormatter. def setup_logger(log_level, log_file=None): """setup root logger with ColoredFormatter.""" level = getattr(logging, log_level.upper(), None) if not level: color_print("Invalid log level: %s" % log_level, "RED") sys.exit(1) # hide traceback when ...
log with color by different level def log_with_color(level): """ log with color by different level """ def wrapper(text): color = log_colors_config[level.upper()] getattr(logger, level.lower())(coloring(text, color)) return wrapper
handle skip feature for test - skip: skip current test unconditionally - skipIf: skip current test if condition is true - skipUnless: skip current test unless condition is true Args: test_dict (dict): test info Raises: SkipTest: skip test de...
call hook actions. Args: actions (list): each action in actions list maybe in two format. format1 (dict): assignment, the value returned by hook function will be assigned to variable. {"var": "${func()}"} format2 (str): only call hook functions. ...
extract output variables def extract_output(self, output_variables_list): """ extract output variables """ variables_mapping = self.session_context.session_variables_mapping output = {} for variable in output_variables_list: if variable not in variables_mapping: ...
run tests in test_suite Args: test_suite: unittest.TestSuite() Returns: list: tests_results def _run_suite(self, test_suite): """ run tests in test_suite Args: test_suite: unittest.TestSuite() Returns: list: tests_results ...
aggregate results Args: tests_results (list): list of (testcase, result) def _aggregate(self, tests_results): """ aggregate results Args: tests_results (list): list of (testcase, result) """ summary = { "success": True, "stat": ...
run testcase/testsuite file or folder. Args: path (str): testcase/testsuite file/foler path. dot_env_path (str): specified .env file path. mapping (dict): if mapping is specified, it will override variables in config block. Returns: instance: HttpRunner(...
main interface. Args: path_or_tests: str: testcase/testsuite file/foler path dict: valid testcase/testsuite data def run(self, path_or_tests, dot_env_path=None, mapping=None): """ main interface. Args: path_or_tests: str:...
set variables mapping to os.environ def set_os_environ(variables_mapping): """ set variables mapping to os.environ """ for variable in variables_mapping: os.environ[variable] = variables_mapping[variable] logger.log_debug("Set OS environment variable: {}".format(variable))
set variables mapping to os.environ def unset_os_environ(variables_mapping): """ set variables mapping to os.environ """ for variable in variables_mapping: os.environ.pop(variable) logger.log_debug("Unset OS environment variable: {}".format(variable))
prepend url with base_url unless it's already an absolute URL def build_url(base_url, path): """ prepend url with base_url unless it's already an absolute URL """ if absolute_http_url_regexp.match(path): return path elif base_url: return "{}/{}".format(base_url.rstrip("/"), path.lstrip("/")...
Do an xpath-like query with json_content. Args: json_content (dict/list/string): content to be queried. query (str): query string. delimiter (str): delimiter symbol. Returns: str: queried result. Examples: >>> json_content = { "ids": [1, 2, 3, 4], ...
update origin dict with override dict recursively e.g. origin_dict = {'a': 1, 'b': {'c': 2, 'd': 4}} override_dict = {'b': {'c': 3}} return: {'a': 1, 'b': {'c': 3, 'd': 4}} def deep_update_dict(origin_dict, override_dict): """ update origin dict with override dict recursively e.g. origin_dict ...
convert dict to params string Args: src_dict (dict): source mapping data structure Returns: str: string params data Examples: >>> src_dict = { "a": 1, "b": 2 } >>> convert_dict_to_params(src_dict) >>> "a=1&b=2" def convert_dict_to_p...
convert keys in dict to lower case Args: origin_dict (dict): mapping data structure Returns: dict: mapping with all keys lowered. Examples: >>> origin_dict = { "Name": "", "Request": "", "URL": "", "METHOD": "", "Headers"...
deepcopy dict data, ignore file object (_io.BufferedReader) Args: data (dict): dict data structure { 'a': 1, 'b': [2, 4], 'c': lambda x: x+1, 'd': open('LICENSE'), 'f': { 'f1': {'a1': 2}, ...
ensure variables are in mapping format. Args: variables (list/dict): original variables Returns: dict: ensured variables in dict format Examples: >>> variables = [ {"a": 1}, {"b": 2} ] >>> print(ensure_mapping_format(variables)) ...
extend raw_variables with override_variables. override_variables will merge and override raw_variables. Args: raw_variables (list): override_variables (list): Returns: dict: extended variables mapping Examples: >>> raw_variables = [{"var1": "val1"}, {"var2": "val2"...
print info in mapping. Args: info_mapping (dict): input(variables) or output mapping. Examples: >>> info_mapping = { "var_a": "hello", "var_b": "world" } >>> info_mapping = { "status_code": 500 } >>> print_...
create scaffold with specified project name. def create_scaffold(project_name): """ create scaffold with specified project name. """ if os.path.isdir(project_name): logger.log_warning(u"Folder {} exists, please specify a new folder name.".format(project_name)) return logger.color_print...
generate cartesian product for lists Args: args (list of list): lists to be generated with cartesian product Returns: list: cartesian product in list Examples: >>> arg1 = [{"a": 1}, {"a": 2}] >>> arg2 = [{"x": 111, "y": 112}, {"x": 121, "y": 122}] >>> args = [arg1...
prettify JSON testcase format def prettify_json_file(file_list): """ prettify JSON testcase format """ for json_file in set(file_list): if not json_file.endswith(".json"): logger.log_warning("Only JSON file format can be prettified, skip: {}".format(json_file)) continue ...
omit too long str/bytes def omit_long_data(body, omit_len=512): """ omit too long str/bytes """ if not isinstance(body, basestring): return body body_len = len(body) if body_len <= omit_len: return body omitted_body = body[0:omit_len] appendix_str = " ... OMITTED {} CHARA...
dump json data to file def dump_json_file(json_data, pwd_dir_path, dump_file_name): """ dump json data to file """ class PythonObjectEncoder(json.JSONEncoder): def default(self, obj): try: return super().default(self, obj) except TypeError: re...
prepare dump file info. def _prepare_dump_info(project_mapping, tag_name): """ prepare dump file info. """ test_path = project_mapping.get("test_path") or "tests_mapping" pwd_dir_path = project_mapping.get("PWD") or os.getcwd() file_name, file_suffix = os.path.splitext(os.path.basename(test_path.rs...
dump tests data to json file. the dumped file is located in PWD/logs folder. Args: json_data (list/dict): json data to dump project_mapping (dict): project info tag_name (str): tag name, loaded/parsed/summary def dump_logs(json_data, project_mapping, tag_name): """ dump tests d...
check testcase format if valid def _check_format(file_path, content): """ check testcase format if valid """ # TODO: replace with JSON schema validation if not content: # testcase file content is empty err_msg = u"Testcase file content is empty: {}".format(file_path) logger.log_...