How to use to_be_checked method in Playwright Python

Best Python code snippet using playwright-python

_low_level.py

Source:_low_level.py Github

copy

Full Screen

1# Copyright (C) 2015 Simon Biggs2# This program is free software: you can redistribute it and/or modify3# it under the terms of the GNU Affero General Public License as published4# by the Free Software Foundation, either version 3 of the License, or5# (at your option) any later version (the "AGPL-3.0+").6# This program is distributed in the hope that it will be useful,7# but WITHOUT ANY WARRANTY; without even the implied warranty of8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9# GNU Affero General Public License and the additional terms for more10# details.11# You should have received a copy of the GNU Affero General Public License12# along with this program. If not, see <http://www.gnu.org/licenses/>.13# ADDITIONAL TERMS are also included as allowed by Section 7 of the GNU14# Affrero General Public License. These aditional terms are Sections 1, 5,15# 6, 7, 8, and 9 from the Apache License, Version 2.0 (the "Apache-2.0")16# where all references to the definition "License" are instead defined to17# mean the AGPL-3.0+.18# You should have received a copy of the Apache-2.0 along with this19# program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.20"""Compare two dose grids with the gamma index.21This module is a python implementation of the gamma index.22It computes 1, 2, or 3 dimensional gamma with arbitrary gird sizes while23interpolating on the fly.24This module makes use of some of the ideas presented within25<http://dx.doi.org/10.1118/1.2721657>.26It needs to be noted that this code base has not yet undergone sufficient27independent validation.28"""29import numpy as np30from scipy.interpolate import RegularGridInterpolator31from multiprocessing import Process, Queue32def _run_input_checks(33 coords_reference, dose_reference,34 coords_evaluation, dose_evaluation):35 """Check user inputs."""36 if (37 not isinstance(coords_evaluation, tuple) or38 not isinstance(coords_reference, tuple)):39 if (40 isinstance(coords_evaluation, np.ndarray) and41 isinstance(coords_reference, np.ndarray)):42 if (43 len(np.shape(coords_evaluation)) == 1 and44 len(np.shape(coords_reference)) == 1):45 coords_evaluation = (coords_evaluation,)46 coords_reference = (coords_reference,)47 else:48 raise Exception(49 "Can only use numpy arrays as input for one dimensional "50 "gamma."51 )52 else:53 raise Exception(54 "Input coordinates must be inputted as a tuple, for "55 "one dimension input is (x,), for two dimensions, (x, y), "56 "for three dimensions input is (x, y, z).")57 reference_coords_shape = tuple([len(item) for item in coords_reference])58 if reference_coords_shape != np.shape(dose_reference):59 raise Exception(60 "Length of items in coords_reference does not match the shape of "61 "dose_reference")62 evaluation_coords_shape = tuple([len(item) for item in coords_evaluation])63 if evaluation_coords_shape != np.shape(dose_evaluation):64 raise Exception(65 "Length of items in coords_evaluation does not match the shape of "66 "dose_evaluation")67 if not (len(np.shape(dose_evaluation)) ==68 len(np.shape(dose_reference)) ==69 len(coords_evaluation) ==70 len(coords_reference)):71 raise Exception(72 "The dimensions of the input data do not match")73 return coords_reference, coords_evaluation74def _calculate_coordinates_kernel(75 distance, num_dimensions, distance_step_size):76 """Determine the coodinate shifts required.77 Coordinate shifts are determined to check the reference dose for a78 given distance, dimension, and step size79 """80 if num_dimensions == 1:81 if distance == 0:82 x_coords = np.array([0])83 else:84 x_coords = np.array([distance, -distance])85 return (x_coords,)86 elif num_dimensions == 2:87 amount_to_check = np.floor(88 2 * np.pi * distance / distance_step_size) + 289 theta = np.linspace(0, 2*np.pi, amount_to_check + 1)[:-1:]90 x_coords = distance * np.cos(theta)91 y_coords = distance * np.sin(theta)92 return (x_coords, y_coords)93 elif num_dimensions == 3:94 number_of_rows = np.floor(95 np.pi * distance / distance_step_size) + 296 elevation = np.linspace(0, np.pi, number_of_rows)97 row_radii = distance * np.sin(elevation)98 row_circumference = 2 * np.pi * row_radii99 amount_in_row = np.floor(100 row_circumference / distance_step_size) + 2101 x_coords = []102 y_coords = []103 z_coords = []104 for i, phi in enumerate(elevation):105 azimuth = np.linspace(0, 2*np.pi, amount_in_row[i] + 1)[:-1:]106 x_coords.append(distance * np.sin(phi) * np.cos(azimuth))107 y_coords.append(distance * np.sin(phi) * np.sin(azimuth))108 z_coords.append(distance * np.cos(phi) * np.ones_like(azimuth))109 return (110 np.hstack(x_coords), np.hstack(y_coords), np.hstack(z_coords))111 else:112 raise Exception("No valid dimension")113def _calculate_min_dose_difference(114 num_dimensions, mesh_coords_evaluation, to_be_checked,115 reference_interpolation, dose_evaluation,116 coordinates_at_distance_kernel):117 """Determine the minimum dose difference.118 Calculated for a given distance from each evaluation point.119 """120 coordinates_at_distance = []121 for i in range(num_dimensions):122 coordinates_at_distance.append(np.array(123 mesh_coords_evaluation[i][to_be_checked][None, :] +124 coordinates_at_distance_kernel[i][:, None])[:, :, None])125 all_points = np.concatenate(coordinates_at_distance, axis=2)126 dose_difference = np.array([127 reference_interpolation(points) -128 dose_evaluation[to_be_checked] for129 points in all_points130 ])131 min_dose_difference = np.min(np.abs(dose_difference), axis=0)132 return min_dose_difference133def _calculate_min_dose_difference_by_slice(134 max_concurrent_calc_points,135 num_dimensions, mesh_coords_evaluation, to_be_checked,136 reference_interpolation, dose_evaluation,137 coordinates_at_distance_kernel, **kwargs):138 """Determine minimum dose differences.139 Calculation is made with the evaluation set divided into slices. This140 enables less RAM usage.141 """142 all_checks = np.where(to_be_checked)143 min_dose_difference = (np.nan * np.ones_like(all_checks[0]))144 num_slices = np.floor(145 len(coordinates_at_distance_kernel[0]) *146 len(all_checks[0]) / max_concurrent_calc_points) + 1147 index = np.arange(len(all_checks[0]))148 np.random.shuffle(index)149 sliced = np.array_split(index, num_slices)150 for current_slice in sliced:151 current_to_be_checked = np.zeros_like(to_be_checked).astype(bool)152 current_to_be_checked[tuple([153 item[current_slice] for154 item in all_checks])] = True155 assert np.all(to_be_checked[current_to_be_checked])156 min_dose_difference[np.sort(current_slice)] = (157 _calculate_min_dose_difference(158 num_dimensions, mesh_coords_evaluation, current_to_be_checked,159 reference_interpolation, dose_evaluation,160 coordinates_at_distance_kernel))161 assert np.all(np.invert(np.isnan(min_dose_difference)))162 return min_dose_difference163def _calculation_loop(**kwargs):164 """Iteratively calculates gamma at increasing distances."""165 dose_valid = kwargs['dose_evaluation'] >= kwargs['lower_dose_cutoff']166 gamma_valid = np.ones_like(kwargs['dose_evaluation']).astype(bool)167 running_gamma = np.inf * np.ones_like(kwargs['dose_evaluation'])168 if kwargs.get('output_components', False):169 output_components = True170 running_dd = np.inf * np.ones_like(kwargs['dose_evaluation'])171 running_dta = np.inf * np.ones_like(kwargs['dose_evaluation'])172 else:173 output_components = False174 distance = 0175 while True:176 to_be_checked = (177 dose_valid & gamma_valid)178 coordinates_at_distance_kernel = _calculate_coordinates_kernel(179 distance, kwargs['num_dimensions'], kwargs['distance_step_size'])180 min_dose_difference = _calculate_min_dose_difference_by_slice(181 to_be_checked=to_be_checked,182 coordinates_at_distance_kernel=coordinates_at_distance_kernel,183 **kwargs)184 dd_term = min_dose_difference / kwargs['dose_threshold']185 dta_term = distance / kwargs['distance_threshold']186 gamma_at_distance = np.sqrt( dd_term**2 + dta_term**2)187 update_mask = (gamma_at_distance < running_gamma[to_be_checked])188 running_gamma[to_be_checked] = np.where(update_mask, gamma_at_distance, running_gamma[to_be_checked])189 # running_gamma[to_be_checked] = np.min(190 # np.vstack((191 # gamma_at_distance, running_gamma[to_be_checked]192 # )), axis=0)193 if output_components:194 running_dd[to_be_checked] = np.where(update_mask, dd_term, running_dd[to_be_checked])195 running_dta[to_be_checked] = np.where(update_mask, dta_term, running_dta[to_be_checked])196 gamma_valid = running_gamma > distance / kwargs['distance_threshold']197 distance += kwargs['distance_step_size']198 if (199 (np.sum(to_be_checked) == 0) |200 (distance > kwargs['maximum_test_distance'])):201 break202 if output_components:203 return (running_gamma, running_dd, running_dta)204 else:205 return running_gamma206def _new_thread(kwargs, output, thread_index, gamma_store):207 if kwargs.get('output_components', False):208 dd_store = np.nan*np.ones_like(gamma_store)209 dta_store = np.nan*np.ones_like(gamma_store)210 gamma_store[thread_index], dd_store[thread_index], dta_store[thread_index] = _calculation_loop(**kwargs)211 if output is not None:212 output.put((gamma_store, dd_store, dta_store))213 else:214 return (gamma_store, dd_store, dta_store)215 else:216 gamma_store[thread_index] = _calculation_loop(**kwargs)217 if output is not None:218 output.put(gamma_store)219 else:220 return gamma_store221def calc_gamma(coords_reference, dose_reference,222 coords_evaluation, dose_evaluation,223 distance_threshold, dose_threshold,224 lower_dose_cutoff=0, distance_step_size=None,225 maximum_test_distance=np.inf,226 max_concurrent_calc_points=np.inf,227 num_threads=1, output_components=False):228 """Compare two dose grids with the gamma index.229 Args:230 coords_reference (tuple): The reference coordinates.231 dose_reference (np.array): The reference dose grid.232 coords_evaluation (tuple): The evaluation coordinates.233 dose_evaluation (np.array): The evaluation dose grid.234 distance_threshold (float): The gamma distance threshold. Units must235 match of the coordinates given.236 dose_threshold (float): An absolute dose threshold.237 If you wish to use 3% of maximum reference dose input238 np.max(dose_reference) * 0.03 here.239 lower_dose_cutoff (:obj:`float`, optional): The lower dose cutoff below240 which gamma will not be calculated.241 distance_step_size (:obj:`float`, optional): The step size to use in242 within the reference grid interpolation. Defaults to a tenth of the243 distance threshold as recommended within244 <http://dx.doi.org/10.1118/1.2721657>.245 maximum_test_distance (:obj:`float`, optional): The distance beyond246 which searching will stop. Defaults to np.inf. To speed up247 calculation it is recommended that this parameter is set to248 something reasonable such as 2*distance_threshold249 Returns:250 gamma (np.array): The array of gamma values the same shape as that251 given by the evaluation coordinates and dose.252 """253 # num_threads = 1 # force single-threading to avoid memory leaks254 coords_reference, coords_evaluation = _run_input_checks(255 coords_reference, dose_reference,256 coords_evaluation, dose_evaluation)257 if distance_step_size is None:258 distance_step_size = distance_threshold / 10259 reference_interpolation = RegularGridInterpolator(260 coords_reference, np.array(dose_reference),261 bounds_error=False, fill_value=np.inf262 )263 dose_evaluation = np.array(dose_evaluation)264 dose_evaluation_flat = np.ravel(dose_evaluation)265 mesh_coords_evaluation = np.meshgrid(*coords_evaluation, indexing='ij')266 coords_evaluation_flat = [267 np.ravel(item)268 for item in mesh_coords_evaluation]269 kwargs = {270 "coords_reference": coords_reference,271 "num_dimensions": len(coords_evaluation),272 "reference_interpolation": reference_interpolation,273 "lower_dose_cutoff": lower_dose_cutoff,274 "distance_threshold": distance_threshold,275 "dose_threshold": dose_threshold,276 "distance_step_size": distance_step_size,277 "max_concurrent_calc_points": max_concurrent_calc_points / num_threads,278 "maximum_test_distance": maximum_test_distance,279 "output_components": output_components}280 gamma_flat = np.nan * np.ones_like(dose_evaluation_flat)281 if output_components:282 dd_flat = np.nan * np.ones_like(dose_evaluation_flat)283 dta_flat = np.nan * np.ones_like(dose_evaluation_flat)284 evaluation_index = np.arange(len(dose_evaluation_flat))285 if num_threads > 1:286 np.random.shuffle(evaluation_index)287 thread_indicies = np.array_split(evaluation_index, num_threads)288 output = Queue()289 processes = []290 for thread_index in thread_indicies:291 thread_index.sort()292 thread_dose_evaluation = dose_evaluation_flat[thread_index]293 thread_coords_evaluation = [294 coords[thread_index]295 for coords in coords_evaluation_flat]296 kwargs['dose_evaluation'] = thread_dose_evaluation297 kwargs['mesh_coords_evaluation'] = thread_coords_evaluation298 p = Process(299 target=_new_thread,300 args=(301 kwargs, output, thread_index,302 np.nan * np.ones_like(dose_evaluation_flat)))303 p.start()304 processes.append(p)305 for i in range(num_threads):306 if output_components:307 res_gamma, res_dd, res_dta = output.get()308 thread_reference = np.invert(np.isnan(res_gamma))309 gamma_flat[thread_reference] = res_gamma[thread_reference]310 dd_flat[thread_reference] = res_dd[thread_reference]311 dta_flat[thread_reference] = res_dta[thread_reference]312 else:313 result = output.get()314 thread_reference = np.invert(np.isnan(result))315 gamma_flat[thread_reference] = result[thread_reference]316 for p in processes:317 p.join()318 else:319 kwargs['dose_evaluation'] = dose_evaluation_flat[evaluation_index]320 kwargs['mesh_coords_evaluation'] = [coords[evaluation_index] for coords in coords_evaluation_flat]321 result = _new_thread(kwargs, None, evaluation_index, np.nan*np.ones_like(dose_evaluation_flat))322 if output_components:323 res_gamma, res_dd, res_dta = result324 reference = np.invert(np.isnan(res_gamma))325 gamma_flat[reference] = res_gamma[reference]326 dd_flat[reference] = res_dd[reference]327 dta_flat[reference] = res_dta[reference]328 else:329 reference = np.invert(np.isnan(result))330 gamma_flat[reference] = result[reference]331 assert np.all(np.invert(np.isnan(gamma_flat)))332 # gamma_flat[np.isinf(gamma_flat)] = np.nan333 gamma = np.reshape(gamma_flat, np.shape(dose_evaluation))334 if output_components:335 dd = np.reshape(dd_flat, np.shape(dose_evaluation))336 dta = np.reshape(dta_flat, np.shape(dose_evaluation))337 return (gamma, dd, dta)338 else:...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

1# Copyright (C) 2015 Simon Biggs2# This program is free software: you can redistribute it and/or modify3# it under the terms of the GNU Affero General Public License as published4# by the Free Software Foundation, either version 3 of the License, or5# (at your option) any later version (the "AGPL-3.0+").6# This program is distributed in the hope that it will be useful,7# but WITHOUT ANY WARRANTY; without even the implied warranty of8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9# GNU Affero General Public License and the additional terms for more10# details.11# You should have received a copy of the GNU Affero General Public License12# along with this program. If not, see <http://www.gnu.org/licenses/>.13# ADDITIONAL TERMS are also included as allowed by Section 7 of the GNU14# Affrero General Public License. These aditional terms are Sections 1, 5,15# 6, 7, 8, and 9 from the Apache License, Version 2.0 (the "Apache-2.0")16# where all references to the definition "License" are instead defined to17# mean the AGPL-3.0+.18# You should have received a copy of the Apache-2.0 along with this19# program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.20"""[DEPRECATED] Use `pymedphys.gamma` instead. See21https://pymedphys.com/en/latest/user/gamma.html22Compare two dose grids with the gamma index.23This module is a python implementation of the gamma index.24It computes 1, 2, or 3 dimensional gamma with arbitrary gird sizes while25interpolating on the fly.26This module makes use of some of the ideas presented within27<http://dx.doi.org/10.1118/1.2721657>.28It needs to be noted that this code base has not yet undergone sufficient29independent validation.30"""31import numpy as np32from scipy.interpolate import RegularGridInterpolator33from multiprocessing import Process, Queue34import warnings35WARNING_STRING = (36 'The `npgamma` module is deprecated. It contains known bugs. '37 'The bugfixes for these are within the `pymedphys.gamma` module. '38 'See https://pymedphys.com/en/latest/user/gamma.html for how to use '39 'the module that has superseded `npgamma`.'40)41warnings.warn(WARNING_STRING, UserWarning)42def _run_input_checks(43 coords_reference, dose_reference,44 coords_evaluation, dose_evaluation):45 """Check user inputs."""46 if (47 not isinstance(coords_evaluation, tuple) or48 not isinstance(coords_reference, tuple)):49 if (50 isinstance(coords_evaluation, np.ndarray) and51 isinstance(coords_reference, np.ndarray)):52 if (53 len(np.shape(coords_evaluation)) == 1 and54 len(np.shape(coords_reference)) == 1):55 coords_evaluation = (coords_evaluation,)56 coords_reference = (coords_reference,)57 else:58 raise Exception(59 "Can only use numpy arrays as input for one dimensional "60 "gamma."61 )62 else:63 raise Exception(64 "Input coordinates must be inputted as a tuple, for "65 "one dimension input is (x,), for two dimensions, (x, y), "66 "for three dimensions input is (x, y, z).")67 reference_coords_shape = tuple([len(item) for item in coords_reference])68 if reference_coords_shape != np.shape(dose_reference):69 raise Exception(70 "Length of items in coords_reference does not match the shape of "71 "dose_reference")72 evaluation_coords_shape = tuple([len(item) for item in coords_evaluation])73 if evaluation_coords_shape != np.shape(dose_evaluation):74 raise Exception(75 "Length of items in coords_evaluation does not match the shape of "76 "dose_evaluation")77 if not (len(np.shape(dose_evaluation)) ==78 len(np.shape(dose_reference)) ==79 len(coords_evaluation) ==80 len(coords_reference)):81 raise Exception(82 "The dimensions of the input data do not match")83 return coords_reference, coords_evaluation84def _calculate_coordinates_kernel(85 distance, num_dimensions, distance_step_size):86 """Determine the coodinate shifts required.87 Coordinate shifts are determined to check the reference dose for a88 given distance, dimension, and step size89 """90 if num_dimensions == 1:91 if distance == 0:92 x_coords = np.array([0])93 else:94 x_coords = np.array([distance, -distance])95 return (x_coords,)96 elif num_dimensions == 2:97 amount_to_check = np.floor(98 2 * np.pi * distance / distance_step_size) + 299 theta = np.linspace(0, 2*np.pi, amount_to_check + 1)[:-1:]100 x_coords = distance * np.cos(theta)101 y_coords = distance * np.sin(theta)102 return (x_coords, y_coords)103 elif num_dimensions == 3:104 number_of_rows = np.floor(105 np.pi * distance / distance_step_size) + 2106 elevation = np.linspace(0, np.pi, number_of_rows)107 row_radii = distance * np.sin(elevation)108 row_circumference = 2 * np.pi * row_radii109 amount_in_row = np.floor(110 row_circumference / distance_step_size) + 2111 x_coords = []112 y_coords = []113 z_coords = []114 for i, phi in enumerate(elevation):115 azimuth = np.linspace(0, 2*np.pi, amount_in_row[i] + 1)[:-1:]116 x_coords.append(distance * np.sin(phi) * np.cos(azimuth))117 y_coords.append(distance * np.sin(phi) * np.sin(azimuth))118 z_coords.append(distance * np.cos(phi) * np.ones_like(azimuth))119 return (120 np.hstack(x_coords), np.hstack(y_coords), np.hstack(z_coords))121 else:122 raise Exception("No valid dimension")123def _calculate_min_dose_difference(124 num_dimensions, mesh_coords_evaluation, to_be_checked,125 reference_interpolation, dose_evaluation,126 coordinates_at_distance_kernel):127 """Determine the minimum dose difference.128 Calculated for a given distance from each evaluation point.129 """130 coordinates_at_distance = []131 for i in range(num_dimensions):132 coordinates_at_distance.append(np.array(133 mesh_coords_evaluation[i][to_be_checked][None, :] +134 coordinates_at_distance_kernel[i][:, None])[:, :, None])135 all_points = np.concatenate(coordinates_at_distance, axis=2)136 dose_difference = np.array([137 reference_interpolation(points) -138 dose_evaluation[to_be_checked] for139 points in all_points140 ])141 min_dose_difference = np.min(np.abs(dose_difference), axis=0)142 return min_dose_difference143def _calculate_min_dose_difference_by_slice(144 max_concurrent_calc_points,145 num_dimensions, mesh_coords_evaluation, to_be_checked,146 reference_interpolation, dose_evaluation,147 coordinates_at_distance_kernel, **kwargs):148 """Determine minimum dose differences.149 Calculation is made with the evaluation set divided into slices. This150 enables less RAM usage.151 """152 all_checks = np.where(to_be_checked)153 min_dose_difference = (np.nan * np.ones_like(all_checks[0]))154 num_slices = np.floor(155 len(coordinates_at_distance_kernel[0]) *156 len(all_checks[0]) / max_concurrent_calc_points) + 1157 index = np.arange(len(all_checks[0]))158 np.random.shuffle(index)159 sliced = np.array_split(index, num_slices)160 for current_slice in sliced:161 current_to_be_checked = np.zeros_like(to_be_checked).astype(bool)162 current_to_be_checked[[163 item[current_slice] for164 item in all_checks]] = True165 assert np.all(to_be_checked[current_to_be_checked])166 min_dose_difference[np.sort(current_slice)] = (167 _calculate_min_dose_difference(168 num_dimensions, mesh_coords_evaluation, current_to_be_checked,169 reference_interpolation, dose_evaluation,170 coordinates_at_distance_kernel))171 assert np.all(np.invert(np.isnan(min_dose_difference)))172 return min_dose_difference173def _calculation_loop(**kwargs):174 """Iteratively calculates gamma at increasing distances."""175 dose_valid = kwargs['dose_evaluation'] >= kwargs['lower_dose_cutoff']176 gamma_valid = np.ones_like(kwargs['dose_evaluation']).astype(bool)177 running_gamma = np.inf * np.ones_like(kwargs['dose_evaluation'])178 distance = 0179 while True:180 to_be_checked = (181 dose_valid & gamma_valid)182 coordinates_at_distance_kernel = _calculate_coordinates_kernel(183 distance, kwargs['num_dimensions'], kwargs['distance_step_size'])184 min_dose_difference = _calculate_min_dose_difference_by_slice(185 to_be_checked=to_be_checked,186 coordinates_at_distance_kernel=coordinates_at_distance_kernel,187 **kwargs)188 gamma_at_distance = np.sqrt(189 min_dose_difference ** 2 / kwargs['dose_threshold'] ** 2 +190 distance ** 2 / kwargs['distance_threshold'] ** 2)191 running_gamma[to_be_checked] = np.min(192 np.vstack((193 gamma_at_distance, running_gamma[to_be_checked]194 )), axis=0)195 gamma_valid = running_gamma > distance / kwargs['distance_threshold']196 distance += kwargs['distance_step_size']197 if (198 (np.sum(to_be_checked) == 0) |199 (distance > kwargs['maximum_test_distance'])):200 break201 return running_gamma202def _new_thread(kwargs, output, thread_index, gamma_store):203 gamma_store[thread_index] = _calculation_loop(**kwargs)204 output.put(gamma_store)205def calc_gamma(coords_reference, dose_reference,206 coords_evaluation, dose_evaluation,207 distance_threshold, dose_threshold,208 lower_dose_cutoff=0, distance_step_size=None,209 maximum_test_distance=np.inf,210 max_concurrent_calc_points=np.inf,211 num_threads=1):212 """[DEPRECATED] Use `pymedphys.gamma` instead. See213 https://pymedphys.com/en/latest/user/gamma.html214 Compare two dose grids with the gamma index.215 Args:216 coords_reference (tuple): The reference coordinates.217 dose_reference (np.array): The reference dose grid.218 coords_evaluation (tuple): The evaluation coordinates.219 dose_evaluation (np.array): The evaluation dose grid.220 distance_threshold (float): The gamma distance threshold. Units must221 match of the coordinates given.222 dose_threshold (float): An absolute dose threshold.223 If you wish to use 3% of maximum reference dose input224 np.max(dose_reference) * 0.03 here.225 lower_dose_cutoff (:obj:`float`, optional): The lower dose cutoff below226 which gamma will not be calculated.227 distance_step_size (:obj:`float`, optional): The step size to use in228 within the reference grid interpolation. Defaults to a tenth of the229 distance threshold as recommended within230 <http://dx.doi.org/10.1118/1.2721657>.231 maximum_test_distance (:obj:`float`, optional): The distance beyond232 which searching will stop. Defaults to np.inf. To speed up233 calculation it is recommended that this parameter is set to234 something reasonable such as 2*distance_threshold235 Returns:236 gamma (np.array): The array of gamma values the same shape as that237 given by the evaluation coordinates and dose.238 """239 warnings.warn(WARNING_STRING, UserWarning)240 coords_reference, coords_evaluation = _run_input_checks(241 coords_reference, dose_reference,242 coords_evaluation, dose_evaluation)243 if distance_step_size is None:244 distance_step_size = distance_threshold / 10245 reference_interpolation = RegularGridInterpolator(246 coords_reference, np.array(dose_reference),247 bounds_error=False, fill_value=np.inf248 )249 dose_evaluation = np.array(dose_evaluation)250 dose_evaluation_flat = np.ravel(dose_evaluation)251 mesh_coords_evaluation = np.meshgrid(*coords_evaluation, indexing='ij')252 coords_evaluation_flat = [253 np.ravel(item)254 for item in mesh_coords_evaluation]255 evaluation_index = np.arange(len(dose_evaluation_flat))256 np.random.shuffle(evaluation_index)257 thread_indicies = np.array_split(evaluation_index, num_threads)258 output = Queue()259 kwargs = {260 "coords_reference": coords_reference,261 "num_dimensions": len(coords_evaluation),262 "reference_interpolation": reference_interpolation,263 "lower_dose_cutoff": lower_dose_cutoff,264 "distance_threshold": distance_threshold,265 "dose_threshold": dose_threshold,266 "distance_step_size": distance_step_size,267 "max_concurrent_calc_points": max_concurrent_calc_points / num_threads,268 "maximum_test_distance": maximum_test_distance}269 for thread_index in thread_indicies:270 thread_index.sort()271 thread_dose_evaluation = dose_evaluation_flat[thread_index]272 thread_coords_evaluation = [273 coords[thread_index]274 for coords in coords_evaluation_flat]275 kwargs['dose_evaluation'] = thread_dose_evaluation276 kwargs['mesh_coords_evaluation'] = thread_coords_evaluation277 Process(278 target=_new_thread,279 args=(280 kwargs, output, thread_index,281 np.nan * np.ones_like(dose_evaluation_flat))).start()282 gamma_flat = np.nan * np.ones_like(dose_evaluation_flat)283 for i in range(num_threads):284 result = output.get()285 thread_reference = np.invert(np.isnan(result))286 gamma_flat[thread_reference] = result[thread_reference]287 assert np.all(np.invert(np.isnan(gamma_flat)))288 gamma_flat[np.isinf(gamma_flat)] = np.nan289 gamma = np.reshape(gamma_flat, np.shape(dose_evaluation))...

Full Screen

Full Screen

infint.py

Source:infint.py Github

copy

Full Screen

1# imports2import sys3# Takes number string and creates list with each node of a predetermined length.4def infinite_num_build(digits, node_length):5 number_list = []6 i = 07 node = ''8 for index in digits:9 if i % node_length == 0:10 if node != '':11 number_list.append(node)12 node = ''13 node += index14 i += 115 number_list.append(node)16 return number_list17# Checks for correct inputs based on assignment18def limit_check(to_be_checked, function):19 node = 420 input_length_limit = 4021 output_length_limit = 10022 length_limit = 023 if function == 'node':24 if int(to_be_checked) > node:25 return 'invalid expression'26 else:27 if function == 'input':28 length_limit = input_length_limit29 elif function == 'output':30 length_limit = output_length_limit31 # Length check32 i = 033 while i < len(to_be_checked):34 digit_length = 035 while i < len(to_be_checked) and to_be_checked[i].isdigit():36 digit_length += 137 i += 138 if digit_length > length_limit:39 return 'invalid expression'40 i += 141 return to_be_checked42# Finds digit at specific index43def infinite_int_digit_index(number, index):44 count = 045 for sublist in number:46 for digit in sublist:47 if count == index:48 return digit49 count += 150# Counts number of digits in infinite int format number51def infinite_int_digit_count(number):52 count = 053 for sublist in number:54 count += len(sublist)55 return count56# Iteratively adds two numbers built from lists.57def add(num1, num2, node_length):58 # Error Checking59 if num1 == 'invalid expression' or num2 == 'invalid expression':60 return 'invalid expression'61 answer = ''62 overflow = 063 num1_length = infinite_int_digit_count(num1)64 num2_length = infinite_int_digit_count(num2)65 add_number_length = max(num1_length, num2_length)66 for i in range(add_number_length):67 if i >= num1_length:68 digit1 = 069 else:70 digit1 = infinite_int_digit_index(num1, num1_length-1-i)71 if i >= num2_length:72 digit2 = 073 else:74 digit2 = infinite_int_digit_index(num2, num2_length-1-i)75 added = int(digit1) + int(digit2) + overflow76 overflow = 077 if added > 9:78 overflow = 179 added -= 1080 answer = str(added) + answer81 if overflow > 0:82 answer = str(overflow) + answer83 answer_infinite_format = infinite_num_build(answer, node_length)84 return answer_infinite_format85# Function to multiply two numbers86def multiply(num1, num2, node_length):87 num1_length = infinite_int_digit_count(num1)88 num2_length = infinite_int_digit_count(num2)89 # Error Checking90 if num1 == 'invalid expression' or num2 == 'invalid expression':91 return 'invalid expression'92 if num1 == ['0'] or num2 == ['0']:93 return ['0']94 answer = infinite_num_build('0', node_length)95 for i in range(num1_length):96 for j in range(num2_length):97 digit1 = infinite_int_digit_index(num1, num1_length-i-1)98 # print('Digit 1: ' + str(digit1))99 digit2 = infinite_int_digit_index(num2, num2_length-j-1)100 # print('To be multiplied: {} * {}'.format(digit1, digit2))101 multiplied = str(int(digit1) * int(digit2)) + (i * '0') + (j * '0')102 # print(multiplied)103 multiplied_infinite_num = infinite_num_build(multiplied, node_length)104 answer = add(answer, multiplied_infinite_num, node_length)105 # print(answer)106 return answer107# Converts nested number list to string for printing108def list_print_to_string(list_to_print):109 answer_string = ''110 for sublist in list_to_print:111 for digit in sublist:112 answer_string += digit113 answer_string = limit_check(answer_string, 'output')114 return answer_string115# To solve nested operations, loosely based on evaluation expression examples on GeekForGeeks116def nested_operations(string_line, node_length):117 try:118 operation_stack = []119 digit_stack = []120 i = 0121 while i < len(string_line):122 operator = ''123 if string_line[i].isalpha():124 while i < len(string_line) and string_line[i].isalpha():125 operator += string_line[i]126 i += 1127 if string_line[i] == '(':128 operation_stack.append(operator)129 i += 1130 elif string_line[i].isdigit():131 digit = ''132 while i < len(string_line) and string_line[i].isdigit():133 digit += string_line[i]134 i += 1135 digit_stack.append(infinite_num_build(digit, node_length))136 elif string_line[i] == ')':137 operation = operation_stack.pop()138 if operation == 'multiply':139 digit_stack.append(multiply(digit_stack.pop(), digit_stack.pop(), node_length))140 elif operation == 'add':141 digit_stack.append(add(digit_stack.pop(), digit_stack.pop(), node_length))142 else:143 return 'invalid expression'144 i += 1145 else:146 i += 1147 if len(digit_stack) != 1:148 return 'invalid expression'149 return limit_check(list_print_to_string(digit_stack.pop()), 'output')150 except:151 return 'invalid expression'152# Main function153# Check argument length154if len(sys.argv) < 2:155 print('Error: Insufficient filename arguments found')156 sys.exit()157arg1 = sys.argv[1]158fileName = ''159nodeLength = ''160# Separate file name from input argument161for ind in range(6, arg1.find(';')):162 fileName += arg1[ind]163# Separate node length from input argument164try:165 for ind in range(arg1.find(';') + 15, len(arg1)):166 nodeLength += arg1[ind]167 nodeLengthInt = int(nodeLength)168 if limit_check(nodeLengthInt, 'node') == 'invalid expression':169 print('Invalid node length')170 sys.exit()171except Exception:172 nodeLengthInt = 3173with open(fileName) as fp:174 for line in fp:175 line = line.rstrip('\n')176 if line != '':...

Full Screen

Full Screen

problem_3.py

Source:problem_3.py Github

copy

Full Screen

1import argparse2import fileinput3import functools4import logging5from typing import List6# Redefine the print function with flush=True. Needed for interactive problems.7print = functools.partial(print, flush=True)8# Configure logging9logging.basicConfig(10 format='[%(lineno)03d]: %(message)s', level=logging.WARNING)11LOG = logging.getLogger(__name__)12def get_int() -> int:13 """Read an int from file or stdin."""14 string = FILE.readline().strip()15 return int(string)16def get_float() -> float:17 """Read a float from file or stdin."""18 string = FILE.readline().strip()19 return float(string)20def get_ints() -> List[int]:21 """Read multiple ints from file or stdin."""22 string = FILE.readline().strip()23 return [int(s) for s in string.split()]24def get_string() -> str:25 """Read a string from file or stdin."""26 string = FILE.readline().strip()27 return string28def interest_level(floor: dict):29 """Calculate the interest level of the current floor."""30 level = sum(value for value in floor.values())31 return level32def initial_neighbours(floor: dict, rows: int, cols: int) -> dict:33 """Find all the inital neighbours."""34 all_neighbours = dict()35 for row in range(rows):36 for col in range(cols):37 cell_neigbours = dict()38 if col > 0:39 cell_neigbours["W"] = (row, col - 1)40 if col + 1 < cols:41 cell_neigbours["E"] = (row, col + 1)42 if row > 0:43 cell_neigbours["N"] = (row - 1, col)44 if row + 1 < rows:45 cell_neigbours["S"] = (row + 1, col)46 all_neighbours[(row, col)] = cell_neigbours47 return all_neighbours48def eliminate_and_update(to_eliminated: List, floor: dict, neighbours: dict) -> set:49 """Eliminate dancers and create list of dancers to check in next round."""50 LOG.info("Eliminating %d dancers", len(to_eliminated))51 to_be_checked = set()52 for pos in to_eliminated:53 LOG.debug("Eliminating pos: {}".format(pos))54 # Remove the person from the floor55 del floor[pos]56 # Update the neighbours of our neigbours57 to_west = neighbours[pos].get("W", None)58 to_east = neighbours[pos].get("E", None)59 to_north = neighbours[pos].get("N", None)60 to_south = neighbours[pos].get("S", None)61 if to_west:62 if to_east:63 neighbours[to_west]["E"] = to_east64 else:65 del neighbours[to_west]["E"]66 if to_east:67 if to_west:68 neighbours[to_east]["W"] = to_west69 else:70 del neighbours[to_east]["W"]71 if to_north:72 if to_south:73 neighbours[to_north]["S"] = to_south74 else:75 del neighbours[to_north]["S"]76 if to_south:77 if to_north:78 neighbours[to_south]["N"] = to_north79 else:80 del neighbours[to_south]["N"]81 # Add our neighbours to the check_list82 for neig in neighbours[pos].values():83 to_be_checked.add(neig)84 # Remove person from neighbours list85 del neighbours[pos]86 # No need to check persons that have been eliminated87 to_be_checked -= set(to_eliminated)88 return to_be_checked89def main():90 """This is where you write your solution."""91 cases = get_int()92 for case in range(1, cases + 1):93 # Read input data94 rows, cols = get_ints()95 # Store skill levels in a dictionary96 floor = dict()97 to_be_checked = []98 for row in range(rows):99 for col, value in enumerate(get_ints()):100 floor[(row, col)] = value101 to_be_checked.append((row, col))102 # Find initial neighbours, store in a dictionary103 neighbours = initial_neighbours(floor, rows, cols)104 # Interest level before any eliminations105 competition_interest = interest_level(floor)106 # Loop until competition is over107 n_rounds = 0108 while True:109 n_rounds += 1110 to_be_eliminated = []111 # Loop over the positions we need to check112 LOG.info("Need to check %s positions", len(to_be_checked))113 for pos in to_be_checked:114 if len(neighbours[pos]) == 0:115 continue # This dancer doesn't have any neighbours116 neig_values = [floor[neig] for neig in neighbours[pos].values()]117 if floor[pos] < (sum(neig_values) / len(neig_values)):118 to_be_eliminated.append(pos)119 # Finished or not?120 if len(to_be_eliminated) == 0:121 break122 # Eliminate dancers and create new list to be checked123 to_be_checked = eliminate_and_update(to_be_eliminated, floor, neighbours)124 # Increase competition interest125 competition_interest += interest_level(floor)126 LOG.info("End of round %d: %d dancers left", n_rounds, len(floor))127 LOG.info("End of competition after %d rounds: %d dancers left",128 n_rounds, len(floor))129 print('Case #{}: {}'.format(case, competition_interest))130if __name__ == '__main__':131 # Parse command line arguments132 parser = argparse.ArgumentParser(description='Code Jam solution')133 parser.add_argument('-v', '--verbose', action='count', default=0,134 help="Increase verbosity. "135 "Can be repeated up to two times.")136 parser.add_argument('infile', default="-", nargs="?",137 help="Read from file instead of stdin")138 arguments = parser.parse_args()139 # Possibly change logging level of the top-level logger140 if arguments.verbose == 1:141 logging.getLogger().setLevel(logging.INFO)142 if arguments.verbose >= 2:143 logging.getLogger().setLevel(logging.DEBUG)144 # Print debugging information145 LOG.debug("Finished parsing arguments: %s", arguments)146 # Define a global FILE variable (sys.stdin or infile) and run main()147 FILE = fileinput.input(files=arguments.infile)...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python 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