How to use _add_process method in autotest

Best Python code snippet using autotest_python

trajectory.py

Source:trajectory.py Github

copy

Full Screen

...138 def __init__(self, xy, kind: str):139140 self._processing = []141 super().__init__(xy, kind)142 self._add_process('initialize', 'initialize', self._kind)143144 @property145 def processing(self):146 return self._processing147148 def _add_process(self,process_type:str, process_name:str,process_parameter=None):149 """ This function is to document the changes to the data in variable "_processing"150151 @:param process_type: string152 intern keyword153 @:param process_name: string154 description of change155 @:param process_parameter: any156 value of change157 """158159 if process_type in ['filter', 'conversion', 'interpolation', 'removal', 'extension', 'data', 'calculation']:160 # reset velocities161 self._velocity = None162 elif process_type not in ['initialize', 'offset']:163 raise Exception("Process unknown! Bad Programmer")164 self._processing.append((process_name, process_parameter))165 return166167168class TrajectoryModify(TrajectoryProcess):169 """ Methods to change the content of Trajectory """170171 def __init__(self, xy, kind: str):172173 super().__init__(xy, kind)174175 self._interpolated = [False] * self._xy.shape[0]176 self._removed_duplicates = [False] * self._xy.shape[0]177178 @property179 def isnan(self):180 return np.isnan(self._xy[:, 0]+self._xy[:, 1])181182 def apply_filter(self, filter_type: str, **kwargs):183 """ Use some Filter on data.184185 :param filter_type: name of Filter (e.g. "savgol")186 :param kwargs: Parameter for selected Filter187 """188 if filter_type == 'savgol':189 self._xy = filtering.savgol_filter_trajectory(self._xy, **kwargs)190 self._add_process('filter', filter_type, kwargs)191 else:192 raise Exception('"{}" is not yet implemented'.format(filter_type))193194 @property195 def interpolated(self):196 return self._interpolated197198 def interpolate(self):199 nan_before = self.isnan200 self._xy[self.isnan, 0] = np.interp(np.nonzero(self.isnan)[0],201 np.nonzero(~self.isnan)[0],202 self._xy[~self.isnan, 0])203 self._xy[self.isnan, 1] = np.interp(np.nonzero(self.isnan)[0],204 np.nonzero(~self.isnan)[0],205 self._xy[~self.isnan, 1])206 self._interpolated = self.isnan != nan_before207 self._add_process('interpolation', 'interpolate', sum(self._interpolated))208 return self._interpolated209210 def remove_duplicates(self, threshold: int = 0):211 """ remove unchanged values212213 :param threshold: amount of ignored values (0 = every duplicate, 1 = three ore more, 2 = ..."""214 xy, remove_stats = filtering.remove_duplicates(self._xy, threshold)215 self._removed_duplicates = self.xy != xy216 self._xy = xy217 self._add_process('removal', 'removed duplicates', remove_stats)218 return remove_stats219220 def invert_y(self):221 """ y = - y """222 self._xy[:, 1] = - self._xy[:, 1]223 self._add_process('data', 'invert','y')224 return225226 def offset(self,offset_x, offset_y):227 """ xy = xy + Offset """228 self._xy[:, 0] = self._xy[:, 0] + offset_x229 self._xy[:, 1] = self._xy[:, 1] + offset_y230 self._add_process('offset', 'offset', (offset_x, offset_y))231 return232233 def center(self):234 """ centering data"""235 center_of_gravity = self.statistics['cog']236 self._xy[:, 0] = self._xy[:, 0] - center_of_gravity[0]237 self._xy[:, 1] = self._xy[:, 1] - center_of_gravity[1]238 self._add_process('offset', 'centering', -center_of_gravity)239 return240241 def scale(self,scaling_factor,scaling_y:float = None):242243 if scaling_y is None:244 self._xy = self._xy * scaling_factor245 self._add_process('calculation', 'scaling', scaling_factor)246 else:247 self._xy[:, 0] = self._xy[:, 0] * scaling_factor248 self._xy[:, 1] = self._xy[:, 1] * scaling_y249 self._add_process('calculation', 'scaling', (scaling_factor, scaling_y))250 return251252253class TrajectoryFOV(TrajectoryModify):254 """ Optional field of view:255256 @:param fov_x: width or radius (y=None) of field of view257 @:param fov_y: float height of field of view258 @:param fov_type: type of field of view - string [default_x='circle',tbd='ellipse',default_xy='rectangle']259 """260 def __init__(self, xy, kind: str,261 fov_x: float = None, fov_y: float = None, fov_type: str = None):262263 if isinstance(fov_x,np.ndarray):264 fov_x = fov_x.item()265 if isinstance(fov_y, np.ndarray):266 fov_y = fov_y.item()267268 self._fov_x = fov_x269 self._fov_y = fov_y270271 super().__init__(xy, kind)272273 if fov_type is None:274 if fov_y is None:275 self._fov_type = 'circle'276 else:277 self._fov_type = 'rectangle'278 else:279 self._fov_type = fov_type280281 def __check_fov(self):282 if self._fov_x is None:283 raise Exception('fov_x is not defined')284 if self._fov_type == 'rectangle' and self._fov_y is None:285 raise Exception('fov_y is not defined')286287 def _set_kind(self, kind):288 if kind in ['pixel_image', 'pixel_shifted']:289 # data kind has to be centered, so the negative offset will be applied.290 if self._fov_x is None or self._fov_y is None:291 raise Exception('For "pixel_image" or "pixel_shifted" fov information is mandatory!')292 self.offset(- self._fov_x/2, - self._fov_y/2)293 if kind == 'pixel_image':294 # y is inverted and and has to be fixed295 self.invert_y()296 # noinspection PyUnresolvedReferences297 self._TrajectoryConvert__set_kind('pixel')298 else:299 # noinspection PyUnresolvedReferences300 self._TrajectoryConvert__set_kind(kind)301302 @property303 def isfov(self):304 self.__check_fov()305 if self._fov_type == 'circle':306 return np.sum(np.square(self._xy),axis=1) <= self._fov_x307 elif self._fov_type == 'rectangle':308 return abs(self._xy[:, 0]) <= self._fov_x and abs(self._xy[:, 0]) <= self._fov_y309 else:310 raise Exception('"{}" is not yet implemented.'.format(self._fov_type))311312 def has_same_infos(self, other):313 assert isinstance(other, TrajectoryFOV)314 if self._fov_x != other._fov_x or self._fov_y != other._fov_y:315 return False316 else:317 return True318319320class TrajectoryConvertError(Exception):321322 @staticmethod323 def bad_input(name, value):324 print('E: Input: {}'.format(value))325 return TrajectoryConvertError('"{name}" got unknown input "{type}" or bad shape.'.format(326 name=name, type=type(value)))327328 @staticmethod329 def assert_1d(name, value, length:int = None):330 if isinstance(value, (list, tuple)):331 if length is None or len(value) == length:332 value = np.asarray(value)333 else:334 raise TrajectoryConvertError(335 '"{name}" expected {length} 1D input, but got {number} elements".'.format(336 name=name, length=length, number=len(value)))337 if isinstance(value, np.ndarray):338 if len(value.shape) != 1:339 raise TrajectoryConvertError(340 '"{name}" expected 1D input, but got {number} dimensions.'.format(341 name=name, length=length, number=len(value.shape)))342 elif length is not None and value.shape[0] != length:343 raise TrajectoryConvertError(344 '"{name}" expected {length} 1D input, but got {number} dimensions.'.format(345 name=name, length=length, number=value.shape[0]))346 return value347348 @staticmethod349 def assert_2d(name, value):350 if isinstance(value, (list, tuple)):351 if len(value) == 2:352 value = np.asarray([value])353 else:354 value = np.asarray(value)355 elif isinstance(value,np.ndarray):356 if len(value.shape) == 1:357 value = np.asarray([value])358 elif value is None:359 return np.ndarray([0,2])360 else:361 raise TrajectoryConvertError('"{name}" expected 2D input, but got bad type: "{type}".'.format(362 name=name, type=type(value)))363 if not value.shape[1] == 2:364 raise TrajectoryConvertError('"{name}" expected 2D input, but got bad shape: "{shape}".'.format(365 name=name, shape=value.shape))366 return value367368369class TrajectoryConvert(TrajectoryFOV):370 """ Conversion between pixel and angle """371372 def __init__(self, xy, kind: str,373 pix_per_mm=None, screen_dist_mm=None,374 fov_x=None,fov_y=None,fov_type=None):375 """376 Optional experiment data (needed for conversion):377 @:param pix_per_mm: [float, float]...378 relative resolution of screen379 @:param screen_dist_mm: float380 distance of eyes to the screen381 """382383 # experiment_data384 self._pix_per_mm = None385 self.set_pix_per_mm(pix_per_mm)386387 self._screen_dist_mm = None388 self.set_screen_dist_mm(screen_dist_mm)389390 super().__init__(xy, kind,391 fov_x=fov_x,fov_y=fov_y,fov_type=fov_type)392393 def set_pix_per_mm(self, value):394 value = TrajectoryConvertError.assert_1d('pixel2rad', value)395 self._pix_per_mm = value396397 def get_pix_per_mm(self):398 return self._pix_per_mm399400 pix_per_mm = property(get_pix_per_mm, set_pix_per_mm)401402 def set_screen_dist_mm(self, value):403 if value is None or isinstance(value, (float, int)):404 self._screen_dist_mm = value405 else:406 raise TrajectoryConvertError.bad_input('screen_dist_mm', value)407408 def get_screen_dist_mm(self):409 return self._screen_dist_mm410411 screen_dist_mm = property(get_screen_dist_mm, set_screen_dist_mm)412413 def has_same_infos(self, other):414 assert isinstance(other, TrajectoryConvert)415 if not super().has_same_infos(other) \416 or self._pix_per_mm[0] != other._pix_per_mm[0] \417 or self._pix_per_mm[1] != other._pix_per_mm[1] \418 or self._screen_dist_mm != other._screen_dist_mm:419 return False420 else:421 return True422423 @property424 def screen_params(self):425 """ for compatibility """426 return {'pix_per_mm':self._pix_per_mm,427 'screen_dist_mm':self.screen_dist_mm,428 'screen_res':self.get_fov('pixel')}429430 @staticmethod431 def screen_params_converter(screen_params: dict):432 screen_params = screen_params.copy()433 screen_params['fov_x'] = screen_params['screen_res'][0]434 screen_params['fov_y'] = screen_params['screen_res'][1]435 del screen_params['screen_res']436 return screen_params437438 def __set_kind(self, kind):439 if self._kind is None:440 if kind in ['pixel', 'angle_deg', 'angle_rad']:441 self._kind = kind442 elif kind == 'angle':443 print('W: by "angle" you mean degrees. Use "angle_deg" to suppress this warning.')444 print_file_and_line()445 self._kind = 'angle_deg'446 else:447 raise Exception('"{}" is an unknown Type'.format(kind))448 else:449 self.convert_to(kind)450451 @property452 def is_experiment_data(self):453 if self._pix_per_mm is None or self._screen_dist_mm is None:454 return False455 else:456 return True457458 def convert_to(self, kind):459 self.get_trajectory(kind, inplace=True, return_copy=False)460 return461462 def pixel2rad(self, pixel):463 assert self.is_experiment_data464 pixel = TrajectoryConvertError.assert_2d('pixel2rad', pixel)465 return np.arctan2(pixel, self._screen_dist_mm * self._pix_per_mm)466467 def rad2pixel(self, rad):468 assert self.is_experiment_data469 rad = TrajectoryConvertError.assert_2d('pixel2rad', rad)470 return self._pix_per_mm * np.tan(rad) * self._screen_dist_mm471472 def get_trajectory(self, kind, inplace: bool = False, data_slice: slice = None, return_copy: bool = True):473 """ Return xy array of type "kind"474475 :param kind: 'pixel', 'angle_rad', ... kind of data type476 'pixel_image', 'pixel_shifted' have a special role, they will always be calculated.477 Both have a shift to the first quadrant. 'pixel_image' will invert the y component478 :param inplace: if True the saved data kind will be changed (faster for the next call)479 :param data_slice: return only a part of the trajectory480 :param return_copy: will return a copy of the original data by default481 :return: ndarray482 """483 if data_slice is not None and inplace:484 raise Exception('Can not convert while slicing.')485 if kind == self.kind:486 if data_slice is None:487 xy = self._xy488 else:489 xy = self._xy[data_slice, :]490 if return_copy:491 return copy.deepcopy(xy)492 else:493 return xy494495 # it is not relevant for rad to deg496 # if not self.is_experiment_data:497 # raise Exception('Experiment Information are necessary for conversion!')498499 def nope(self_kind, new_kind):500 return Exception('Type "{now}" can not be turned to "{to}" yet!'.format(501 now=self_kind, to=new_kind))502503 if kind == 'pixel':504 if self.kind in ['angle_rad', 'angle_deg']:505 xy = self.rad2pixel(self.get_trajectory('angle_rad', return_copy=False, data_slice=data_slice))506 else:507 raise nope(self._kind, kind)508 elif kind in ['pixel_image', 'pixel_shifted']:509 """ move the trajectory out of the center in quadrant 1510 if pixel_image is selected: invert y component bevore.511 """512 if inplace:513 raise Exception('"{}" can\'t be the saved value.'.format(kind))514 xy = self.get_trajectory('pixel', data_slice=data_slice)515 fov = self.get_fov('pixel')516 # can not use += for following lines, because xy could be integer. An Error would occur.517 xy[:, 0] = xy[:, 0] + fov[0] / 2518 if kind == 'pixel_image':519 xy[:, 1] = -xy[:, 1] + fov[1] / 2520 else:521 xy[:, 1] = xy[:, 1] + fov[1] / 2522 elif kind == 'angle_deg':523 if self.kind in ['pixel', 'angle_rad']:524 xy = np.degrees(self.get_trajectory('angle_rad', return_copy=False, data_slice=data_slice))525 else:526 raise nope(self._kind, kind)527 elif kind == 'angle_rad':528529 if data_slice is None:530 xy = copy.deepcopy(self._xy)531 else:532 xy = self._xy[data_slice, :]533534 if self.kind == 'pixel':535 xy = self.pixel2rad(xy)536 elif self.kind == 'angle_deg':537 xy = np.radians(xy)538 else:539 raise nope(self._kind, kind)540 elif kind == 'angle':541 print('W: by "angle" you mean degrees. Use "angle_deg" to suppress this warning.')542 print_file_and_line()543 kind = 'angle_deg'544 xy = self.get_trajectory(kind, return_copy=False, data_slice=data_slice)545 else:546 raise Exception('"{}" is an unknown type.'.format(kind))547 if inplace:548 self._xy = xy549 self.__convert_fov_to(kind)550 self._add_process('conversion', self._kind, kind)551 self._kind = kind552553 if return_copy and data_slice is None:554 return copy.deepcopy(xy)555 else:556 return xy557558 def __convert_fov_to(self, kind):559 self.get_fov(kind, inplace=True)560561 def get_fov(self, kind, inplace=False):562 if kind == self.kind:563 return np.asarray([self._fov_x, self._fov_y])564565 def convert(fun):566 xy = fun(np.asarray([self._fov_x, self._fov_y]) / 2) * 2567 fov_x = xy[0, 0]568 fov_y = xy[0, 1]569 if inplace:570 self._fov_x = fov_x571 self._fov_y = fov_y572 return np.asarray([fov_x, fov_y])573574 if kind == 'pixel':575 if self.kind == 'angle_rad':576 return convert(self.rad2pixel)577 elif self.kind == 'angle_deg':578 return convert(lambda x: self.rad2pixel(np.deg2rad(x)))579 else:580 raise Exception581 elif kind == 'angle_deg':582 if self.kind == 'pixel':583 return convert(lambda x: np.rad2deg(self.pixel2rad(x)))584 elif self.kind == 'angle_rad':585 return convert(np.rad2deg)586 else:587 raise Exception588 elif kind == 'angle_rad':589 if self.kind == 'pixel':590 return convert(self.pixel2rad)591 elif self.kind == 'angle_deg':592 return convert(np.deg2rad)593 else:594 raise Exception595 else:596 raise Exception597598599class TrajectoryCalculate(TrajectoryConvert):600 """ Simple Calculation Methods for Trajectory """601602 def __int__(self, xy, kind: str):603 super().__init__(xy, kind)604605 def __mul__(self, other: (int, float, list, np.ndarray)):606 result = self.deepcopy()607 result *= other608 return result609610 def __imul__(self, other: (int, float, list, np.ndarray)):611 if isinstance(other, (int, float)):612 self._xy *= other613 elif isinstance(other, list):614 if len(other) == 2:615 self._xy[:, 0] *= other[0]616 self._xy[:, 1] *= other[1]617 else:618 raise Exception('List has to have length 2. Got length {}.'.format(len(other)))619 elif isinstance(other, np.ndarray):620 if len(other.shape) == 1 and other.shape[0] == 2:621 self._xy[:, 0] *= other[0]622 self._xy[:, 1] *= other[1]623 else:624 raise Exception('ndarray has to have length 2. Got shape {}.'.format(other.shape))625626 else:627 raise Exception('"{}" is an unknown Type for multiplication.'.format(type(other)))628 self._add_process('calculation', 'multiplication', other)629 return self630631 def __truediv__(self, other: (int, float)):632 result = self.deepcopy()633 result /= other634 return result635636 def __itruediv__(self, other: (int, float)):637 assert isinstance(other, (int, float))638 self._xy /= other639 self._add_process('calculation', 'division', other)640 return self641642 def __add__(self, other: (int, float, TrajectoryConvert)):643 result = self.deepcopy()644 result += other645 return result646647 def __iadd__(self, other: (int, float, TrajectoryConvert)):648 if isinstance(other, (int, float)):649 self._xy += other650 self._add_process('calculation', 'addition', other)651 elif isinstance(other, TrajectoryConvert):652 self._xy += other.get_trajectory(self.kind)653 self._add_process('calculation', 'addition', 'Trajectory')654 return self655656 def extend(self, other: TrajectoryConvert, ignore_infos=False):657 assert isinstance(other, TrajectoryConvert)658 if not ignore_infos and not self.has_same_infos(other):659 raise Exception("Trajectory Infos are not the same!")660 self._xy = np.concatenate([self.xy, other.get_trajectory(self.kind)])661 self._interpolated += other.interpolated662 self._removed_duplicates += other._removed_duplicates663 self._add_process('extension', 'extend', 'Trajectory')664 return self665666667class TrajectoryVelocity(TrajectoryCalculate):668 """ Provides velocity values to Trajectory"""669670 def __init__(self, xy, kind: str, sample_rate: float = 1,671 pix_per_mm=None, screen_dist_mm=None,672 fov_x=None, fov_y=None, fov_type=None):673 """674 @:param sample_rate: int675 samples per second676 necessary to calculate a correct velocity in kind per second677 """ ...

Full Screen

Full Screen

uMonitor.py

Source:uMonitor.py Github

copy

Full Screen

...98 service["program"],99 service["program"]100 )101 return (program,)+tuple(service["args"])102 def _add_process(self, service):103 ''' Creates a process, for a given service104 specification. The executable is being mapped 105 from the "interpreters" json section. 106 Child process environment is also changed to 107 what user provided through the json config.108 '''109 service_tuple = self._service_to_tup(service)110 self.processes[service_tuple] = service111 ser_env = self._service_vars(service)112 proc = Popen(113 service_tuple, 114 cwd = service.get("cwd", os.getcwd()),115 env=ser_env ,116 stdin=PIPE, 117 stdout=PIPE,118 stderr=PIPE119 )120 service["proc"] = proc 121 print("Started: {}".format(service_tuple))122 def _launch_services(self):123 '''Creates child process for all the 124 given services. Services should be described125 in the __init__ config.126 '''127 services = self.config["services"]128 for service in services:129 self._add_process(service)130 def run(self):131 '''The only method, user supposed to run.132 Will create the child processes and monitor their133 execution.134 '''135 self._launch_services()136 while True:137 time.sleep(1)138 for ser_tup, service in self.processes.items():139 proc = service.get("proc")140 if (not proc) or (proc.poll() != None): 141 if service.get("persist", False):142 self._add_process(service)143 else:144 self.processes[ser_tup]["proc"] = None145 print("Terminated: ", ser_tup)146 self.processes = dict(filter(147 lambda kv: kv[1]["proc"], 148 self.processes.items()149 ))...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful