How to use _calculateBbox method in fMBT

Best Python code snippet using fMBT_python

fmbtandroid.py

Source:fmbtandroid.py Github

copy

Full Screen

...794 self._rawProps = ""795 if not "scrolling:mScrollX" in self._p:796 self._p["scrolling:mScrollX"] = 0797 self._p["scrolling:mScrollY"] = 0798 fmbtgti.GUIItem.__init__(self, className, self._calculateBbox(displayToScreen), dumpFilename)799 def addChild(self, child): self._children.append(child)800 def _calculateBbox(self, displayToScreen):801 left = int(self._p["layout:mLeft"])802 top = int(self._p["layout:mTop"])803 parent = self._parent804 while parent:805 pp = parent._p806 left += int(pp["layout:mLeft"]) - int(pp["scrolling:mScrollX"])807 top += int(pp["layout:mTop"]) - int(pp["scrolling:mScrollY"])808 parent = parent._parent809 height = int(self._p["layout:getHeight()"])810 width = int(self._p["layout:getWidth()"])811 screenLeft, screenTop = displayToScreen(left, top)812 screenRight, screenBottom = displayToScreen(left + width, top + height)813 return (screenLeft, screenTop, screenRight, screenBottom)814 def children(self): return self._children...

Full Screen

Full Screen

citymap.py

Source:citymap.py Github

copy

Full Screen

1import logging2from time import sleep3from math import cos, sin, asin, radians, sqrt4from OSMPythonTools.nominatim import Nominatim5from OSMPythonTools.overpass import overpassQueryBuilder, Overpass6class CityMap:7 def __init__(self, city: str) -> None:8 """Create city map9 Args:10 city (str): City name11 radius (float, optional): City radius, in meters. Defaults to 3000.12 """13 self._city = city14 self._elements_dict = {}15 self._normalized_dict = {}16 self._features_list = []17 # request timing18 self._timeout = 30019 self._try_again = 3020 # initialize instances21 self._nominatim = Nominatim()22 self._overpass = Overpass()23 def __getattr__(self, feature: str) -> list[tuple[float, float]]:24 """Returns a list of features. Too check the available features, try using the features attribute25 Returns:26 list[tuple[float, float]]: list of relative positions27 """28 if feature in self._normalized_dict:29 return self._normalized_dict[feature]30 return []31 @property32 def features(self) -> list[str]:33 """Returns all loaded and normalized features34 Returns:35 list[str]36 """37 return [f for f in self._normalized_dict]38 @property39 def circular_features(self) -> dict[list[tuple[float, float]]]:40 """Returns all features that can must drawn as circles41 Returns:42 dict[list[tuple[float, float]]]43 """44 return {45 k: v46 for k, v in self._normalized_dict.items()47 if any(48 "node" in x["topology"] and x["name"] == k for x in self._features_list49 )50 }51 @property52 def polygonal_features(self) -> dict[list[tuple[float, float]]]:53 """Returns all features that can must drawn as polygons54 Returns:55 dict[list[tuple[float, float]]]56 """57 return {58 k: v59 for k, v in self._normalized_dict.items()60 if any(61 any(y in x["topology"] for y in {"way", "area"}) and x["name"] == k62 for x in self._features_list63 )64 }65 def loadCity(self) -> None:66 """Loads city area id and bounding box (both in xy and coordinates forms)"""67 city_query = self._nominatim.query(68 self._city,69 timeout=self._timeout,70 )71 # city area id72 self._area_id = city_query.areaId()73 # bounding box74 raw_bbox = city_query.toJSON()[0]["boundingbox"]75 self._bbox = (76 float(raw_bbox[0]),77 float(raw_bbox[2]),78 float(raw_bbox[1]),79 float(raw_bbox[3]),80 )81 def _coordsToXY(self, lat: float, lon: float) -> tuple[float, float]:82 """Calculates points x and y coordinates according to its latitude and longitude83 Args:84 lat (float)85 lon (float)86 Returns:87 tuple[float, float]: x, y coordinates88 """89 x = (lat - self._bbox[0]) / (self._bbox[2] - self._bbox[0])90 y = (lon - self._bbox[1]) / (self._bbox[3] - self._bbox[1])91 return x, y92 def _isPositionValid(self, *_) -> bool:93 """Is the provided position valid?94 Let's just say that the position is valid. The actual check is delegated to the subclasses.95 Returns:96 bool:97 """98 return True99 def _queryOSM(self, **kwargs) -> None:100 """Query OSM and load data into self._elements_dict101 Keyword args:102 name (str): Element type.103 tag (str): Element tag.104 topology (str): Element topology.105 """106 if not self._bbox:107 raise ValueError("Bounding Box not loaded.")108 self._elements_dict[kwargs["name"]] = []109 for t in kwargs["tag"]:110 query = overpassQueryBuilder(111 bbox=self._bbox,112 selector=t,113 elementType=kwargs["topology"],114 includeGeometry=True,115 )116 while True:117 try:118 results = self._overpass.query(119 query,120 timeout=self._timeout,121 )122 break123 except Exception as _:124 # OFC they couldn't raise proper exceptions.125 # this exceptions is a "generic" exception.126 logging.error(f"Trying again in {self._try_again} seconds...")127 sleep(self._try_again)128 if not results.elements():129 continue130 if "node" in kwargs["topology"]:131 self._elements_dict[kwargs["name"]].extend(results.nodes())132 elif any(t in ["way", "area"] for t in kwargs["topology"]):133 self._elements_dict[kwargs["name"]].extend(results.ways())134 def _rotateCoordinates(self, coords: list[tuple[float, float]], angle: float = -90):135 """Rotates each coordinates around its center136 Args:137 coords (list[tuple[float, float]]): List of normalized coordinates138 angle (float, optional): Rotation angle. Defaults to -90.139 Returns:140 [type]: [description]141 """142 c = cos(radians(angle))143 s = sin(radians(angle))144 translated = [tuple(s - 0.5 for s in t) for t in coords]145 rotated = [(x * c - y * s, x * s + y * c) for x, y in translated]146 return [tuple(s + 0.5 for s in t) for t in rotated]147 def _normalizeElements(self, **kwargs) -> None:148 """Creates an entry in self._normalized_dict for a set of positions in self._elements_dict.149 The resulting coordinates are a list of (x, y) tuples in range [0, 1]x[0, 1], relative to150 the bounding box of the coordinates themselves.151 Keyword args:152 name (str): Element type.153 tag (str): Element tag.154 topology (str): Element topology.155 """156 if "node" in kwargs["topology"]:157 coords = [158 self._coordsToXY(e.lat(), e.lon())159 for e in self._elements_dict[kwargs["name"]]160 if self._isPositionValid(e.lat(), e.lon())161 ]162 if not coords:163 return164 # rotate coordinates165 rotated = self._rotateCoordinates(coords)166 # add to dictionary167 self._normalized_dict[kwargs["name"]] = rotated168 elif any(t in ["way", "area"] for t in kwargs["topology"]):169 self._normalized_dict[kwargs["name"]] = []170 for element in self._elements_dict[kwargs["name"]]:171 for shape in element.geometry()["coordinates"]:172 # sometimes shape are just an element173 if len(shape) == 1:174 shape = shape[0]175 # filter coords and convert to xy176 # sometimes coords are not lists? I don't understand why177 coords = [178 self._coordsToXY(*s[::-1])179 for s in shape180 if isinstance(s, list) and self._isPositionValid(*s[::-1])181 ]182 # sometimes the coords list might be empty183 if len(coords) < 3:184 continue185 # rotate coordinates186 rotated = self._rotateCoordinates(coords)187 # add to dictionary188 self._normalized_dict[kwargs["name"]].append(rotated)189 def loadFeatures(self) -> None:190 """Loads and normalize all features."""191 for feature in self._features_list:192 self._queryOSM(**feature)193 self._normalizeElements(**feature)194class MinimalMap(CityMap):195 def __init__(self, city: str):196 super().__init__(city)197 self._features_list = [198 {199 "name": "benches",200 "tag": ["amenity=bench"],201 "topology": ["node"],202 "color": "#cb99c9",203 },204 {205 "name": "traffic signals",206 "tag": ["traffic_signals"],207 "topology": ["node"],208 "color": "#ff6961",209 },210 {211 "name": "water fountains",212 "tag": ["amenity=drinking_water"],213 "topology": ["node"],214 "color": "#89cff0",215 },216 {217 "name": "trees",218 "tag": ["natural=tree"],219 "topology": ["node"],220 "color": "#77dd77",221 },222 {223 "name": "bars",224 "tag": ["amenity=bar"],225 "topology": ["node"],226 "color": "#ca9bf7",227 },228 {229 "name": "restaurants",230 "tag": ["amenity=restaurant"],231 "topology": ["node"],232 "color": "#ffb7ce",233 },234 {235 "name": "ATMs",236 "tag": ["amenity=atm"],237 "topology": ["node"],238 "color": "#ffee93",239 },240 ]241 def _isPositionValid(self, *_) -> bool:242 """243 All positions are valid in the minimal map. There's no need to check if they are in bbox.244 This is redundant and probably unnecessary, but I wouldn't know how to change this."""245 return True246 def getColor(self, feature: str) -> str:247 """Returns color relative to feature.248 Args:249 feature (str): Feature in class250 Returns:251 str: Feature color¨252 """253 for f in self._features_list:254 if f["name"] == feature:255 return f.get("color")256 return None257class RoundCityMap(CityMap):258 def __init__(self, city: str, radius: float = 3000):259 """Creates a round city260 Args:261 city (str): Name of the city262 radius (float, optional): City radius. Defaults to 3000.263 """264 super().__init__(city)265 self._radius = radius266 self._features_list = [267 {268 "name": "trees",269 "tag": ["natural=tree"],270 "topology": ["node"],271 },272 {273 "name": "water",274 "tag": [275 "natural=water",276 "water",277 "waterway",278 "leisure=marinas",279 "place=sea",280 "place=ocean",281 ],282 "topology": ["way"],283 },284 {285 "name": "parks",286 "tag": [287 "leisure=park",288 "leisure=garden",289 "leisure=dog_park",290 "leisure=pitch",291 "landuse=green",292 "landuse=grass",293 "landuse=cemetery",294 ],295 "topology": ["area"],296 },297 {298 "name": "buildings",299 "tag": ["building"],300 "topology": ["way"],301 },302 ]303 def loadCity(self) -> None:304 """Loads city area id and bounding box (both in xy and coordinates forms)"""305 city_query = self._nominatim.query(306 self._city,307 timeout=self._timeout,308 )309 # city area id310 self._area_id = city_query.areaId()311 # city center cords312 self._city_center = tuple(313 float(city_query.toJSON()[0][x]) for x in ["lat", "lon"]314 )315 self._city_center_rad = tuple(radians(x) for x in self._city_center)316 self._calculateBBOX()317 def _calculateBBOX(self) -> None:318 """Calculates city area bounding box according to its center"""319 r_lat = radians(self._city_center[0])320 km_lat, km_lon = 110.574235, 110.572833 * cos(r_lat)321 d_lat = self._radius / 1000 / km_lat322 d_lon = self._radius / 1000 / km_lon323 self._bbox = (324 self._city_center[0] - d_lat,325 self._city_center[1] - d_lon,326 self._city_center[0] + d_lat,327 self._city_center[1] + d_lon,328 )329 def _distFromCityCenter(self, lat: float, lon: float) -> float:330 """Returns distance between a point and the city center coordinates331 Args:332 lat (float)333 lon (float)334 Returns:335 float: distance in meters336 """337 R = 6371338 r_lat, r_lon = radians(lat), radians(lon)339 d_lat, d_lon = (340 r_lat - self._city_center_rad[0],341 r_lon - self._city_center_rad[1],342 )343 a = (344 sin(d_lat / 2) ** 2345 + cos(r_lat) * cos(self._city_center_rad[0]) * sin(d_lon / 2) ** 2346 )347 c = 2 * asin(sqrt(a))348 return R * c * 1000 # meters349 def _isPositionValid(self, lat: float, lon: float) -> bool:350 """Checks whether the given point is indide the circle radius351 Args:352 lat (float): longitude of the point353 lon (float): latitude of the point354 Returns:355 bool356 """...

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 fMBT 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