Best Python code snippet using fMBT_python
widgets.py
Source:widgets.py
1import functools2import importlib3import os4import math5from typing import Callable, Tuple, Any6from PIL import Image, ImageDraw7from . import icons8from .dimensions import Dimension9from .functional import compose10from .point import Coordinate11anchors = {12 "left": "la",13 "right": "ra",14 "centre": "ma",15}16class CachingText:17 def __init__(self, at: Coordinate, value: Callable, font, align="left", direction="ltr", fill=None):18 self.at = at19 self.value = value20 self.font = font21 self.anchor = anchors.get(align, align)22 self.direction = direction23 self.fill = fill if fill else (255, 255, 255)24 self.cache = {}25 def draw(self, image, draw):26 text = self.value()27 if text is None:28 raise ValueError("Refusing to draw text with value of 'None'")29 cached = self.cache.get(text, None)30 if cached is None:31 x0, y0, x1, y1 = self.font.getbbox(32 text=text,33 stroke_width=2,34 anchor=self.anchor,35 direction=self.direction36 )37 if x0 < 0:38 x1 = x1 + abs(x0)39 if y0 < 0:40 y1 = y1 + abs(x0)41 backing_image = Image.new(mode="RGBA", size=(x1, y1))42 backing_draw = ImageDraw.Draw(backing_image)43 backing_draw.text(44 (abs(x0), 0),45 text,46 anchor=self.anchor,47 direction=self.direction,48 font=self.font,49 fill=self.fill,50 stroke_width=2,51 stroke_fill=(0, 0, 0)52 )53 cached = {54 "at": Coordinate(x0 if x0 < 0 else 0, y0 if y0 < 0 else 0),55 "image": backing_image56 }57 self.cache[text] = cached58 image.alpha_composite(cached["image"], (self.at + cached["at"]).tuple())59class Text:60 def __init__(self,61 at: Coordinate,62 value: Callable[[], str],63 font: Any, align: str = "left",64 direction: str = "ltr",65 fill: Tuple = None) -> None:66 self.at = at67 self.value = value68 self.font = font69 self.anchor = anchors.get(align, align)70 self.direction = direction71 self.fill = fill if fill else (255, 255, 255)72 def draw(self, image, draw):73 draw.text(74 self.at.tuple(),75 self.value(),76 anchor=self.anchor,77 direction=self.direction,78 font=self.font,79 fill=self.fill,80 stroke_width=2,81 stroke_fill=(0, 0, 0)82 )83class EmptyDrawable:84 def draw(self, image, draw):85 pass86class Composite:87 def __init__(self, *widgets):88 self.widgets = widgets89 def draw(self, image, draw):90 for w in self.widgets:91 w.draw(image, draw)92class Drawable:93 def __init__(self, at, drawable):94 self.at = at95 self.drawable = drawable96 def draw(self, image, draw):97 image.alpha_composite(self.drawable, self.at.tuple())98def icon(file, at, transform=lambda x: x):99 if os.path.exists(file):100 image = Image.open(file)101 else:102 with importlib.resources.path(icons, file) as f:103 image = Image.open(f)104 return Drawable(at, transform(image))105def simple_icon(at, file, size=64, invert=False):106 return icon(file, at, transform=compose(107 functools.partial(transform_resize, (size, size)),108 transform_rgba,109 transform_negative if invert else transform_identity110 ))111def transform_identity(img):112 return img113def transform_resize(target, img):114 return img.resize(target)115def transform_rgba(img):116 return img.convert("RGBA") if img.mode == "P" else img117def transform_negative(img):118 if img.mode != "RGBA":119 raise ValueError(f"I only work on RGBA, not {img.mode}")120 for i in range(0, img.size[0]):121 for j in range(0, img.size[1]):122 pixel = img.getpixel((i, j))123 img.putpixel((i, j), (255 - pixel[0], 255 - pixel[1], 255 - pixel[2], pixel[3]))124 return img125class ImageTranslate:126 def __init__(self, at, image):127 self.at = at128 self.image = image129 def _txy(self, xy):130 return xy[0] + self.at.x, xy[1] + self.at.y131 def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):132 self.image.alpha_composite(im, dest=self._txy(dest), source=source)133 def paste(self, img, box):134 self.image.paste(img, box=self._txy(box))135class DrawTranslate:136 def __init__(self, at, draw):137 self.at = at138 self.draw = draw139 def _txy(self, xy):140 return xy[0] + self.at.x, xy[1] + self.at.y141 def text(self, xy, text, **kwargs):142 self.draw.text(xy=self._txy(xy), text=text, **kwargs)143 def rounded_rectangle(self, xy, *args, **kwargs):144 self.draw.rounded_rectangle([self._txy(pair) for pair in xy], *args, **kwargs)145 def point(self, xy, **kwargs):146 self.draw.point(xy=self._txy(xy), **kwargs)147 def rectangle(self, xy, *args, **kwargs):148 self.draw.rectangle([self._txy(pair) for pair in xy], *args, **kwargs)149 def line(self, xy, *args, **kwargs):150 self.draw.line([self._txy(pair) for pair in xy], *args, **kwargs)151 def ellipse(self, xy, *args, **kwargs):152 self.draw.ellipse([self._txy(pair) for pair in xy], *args, **kwargs)153 def arc(self, xy, *args, **kwargs):154 self.draw.arc([self._txy(pair) for pair in xy], *args, **kwargs)155 def pieslice(self, xy, *args, **kwargs):156 self.draw.pieslice([self._txy(pair) for pair in xy], *args, **kwargs)157 def polygon(self, xy, *args, **kwargs):158 self.draw.polygon([self._txy(pair) for pair in xy], *args, **kwargs)159class Translate:160 """Extremely rudimentary translation support!161 Translate the 'at' of child widget by this widget's location. Use in combination with a Composite162 Need to test each child type that intend to put in here, as certainly won't work for many use cases.163 """164 def __init__(self, at: Coordinate, widget):165 self.at = at166 self.widget = widget167 def draw(self, image, draw):168 ivp = ImageTranslate(self.at, image)169 dvp = DrawTranslate(self.at, draw)170 self.widget.draw(ivp, dvp)171class Frame:172 """173 A clipping bordered frame that also makes a child controllably transparent174 """175 def __init__(self,176 dimensions: Dimension,177 opacity: float = 1.0,178 corner_radius: int = 0,179 outline: Tuple = None,180 fill: Tuple = None,181 child: Any = EmptyDrawable(),182 fade_out: int = 0) -> None:183 self.child = child184 self.corner_radius = corner_radius185 self.fill = fill186 self.outline = outline187 self.opacity = opacity188 self.dimensions = dimensions189 self.mask = None190 self.fade_out = fade_out191 def _maybe_init(self):192 if self.mask is None:193 self.mask = Image.new('L', (self.dimensions.x, self.dimensions.y), 0)194 ImageDraw.Draw(self.mask).rounded_rectangle(195 (0, 0) + (self.dimensions.x - 1, self.dimensions.y - 1),196 radius=self.corner_radius,197 fill=int(self.opacity * 255)198 )199 if self.fade_out > 0:200 self._init_fadeout()201 def _init_fadeout(self):202 for y in range(self.dimensions.y):203 for x in range(self.dimensions.x):204 distance_to_center = math.sqrt((x - self.dimensions.x/2) ** 2 + (y - self.dimensions.y/2) ** 2)205 radius = min(self.dimensions.x, self.dimensions.y) / 2206 distance_from_side = 1 - (distance_to_center / radius)207 distance_from_side = min(x, min(y, min(self.dimensions.x - x, self.dimensions.y - y))) / radius208 if self.corner_radius == 0:209 # no radius defined, we will use distance_from_side210 distance_from_corner_radius = distance_from_side211 else:212 # we can use a more complex formula for getting the distance from corner_radius, but for simplicity we will use this one213 # it will lead to more straight lines instead of rounded corners214 outer_radius = math.sqrt(self.corner_radius ** 2 + self.corner_radius ** 2) - self.corner_radius215 rounder_radius = math.sqrt((self.dimensions.x/2) ** 2 + (self.dimensions.y/2) ** 2) - outer_radius216 distance_from_corner_radius = (rounder_radius - distance_to_center) / rounder_radius217 fade_out_percents = max(0.01, min(1, self.fade_out / radius))218 self.mask.putpixel((x, y), int(min(1, min(distance_from_side, distance_from_corner_radius) / fade_out_percents) * 255 * self.opacity))219 def draw(self, image, draw):220 self._maybe_init()221 rect = Image.new('RGBA', (self.dimensions.x, self.dimensions.y), self.fill)222 rect_draw = ImageDraw.Draw(rect)223 self.child.draw(rect, rect_draw)224 if self.outline is not None:225 rect_draw.rounded_rectangle(226 ((0, 0), (self.dimensions.x - 1, self.dimensions.y - 1)),227 radius=self.corner_radius,228 outline=self.outline229 )230 rect.putalpha(self.mask)231 image.alpha_composite(rect, (0, 0))232class Scene:233 def __init__(self, dimensions: Dimension, widgets, ):234 self._widgets = widgets235 self._dimensions = dimensions236 def draw(self):237 image = Image.new("RGBA", (self._dimensions.x, self._dimensions.y), (0, 0, 0, 0))238 draw = ImageDraw.Draw(image)239 for w in self._widgets:240 w.draw(image, draw)...
variogram.py
Source:variogram.py
1import numpy as np2class Variogram:3 def __init__(self, rx, ry=1.0, rz=1.0, azi=0.0, dip=0.0, std=1.0):4 self._rx, self._ry, self._rz = rx, ry, rz5 self._azi = azi6 self._dip = dip7 self._var = std * std # Not currently used?8 # Factors9 cos_rot = np.cos(azi)10 sin_rot = np.sin(azi)11 cos_dip = np.cos(dip)12 sin_dip = np.sin(dip)13 f1 = 1 / rx ** 214 f2 = 1 / ry ** 215 f3 = 1 / rz ** 216 self._txx = cos_rot * cos_rot * cos_dip * cos_dip * f1 + sin_rot * sin_rot * f2 + cos_rot * cos_rot * sin_dip * sin_dip * f317 self._tyy = sin_rot * sin_rot * cos_dip * cos_dip * f1 + cos_rot * cos_rot * f2 + sin_rot * sin_rot * sin_dip * sin_dip * f318 self._tzz = sin_dip * sin_dip * f1 + cos_dip * cos_dip * f319 self._txy = 2 * (20 cos_dip * cos_dip * cos_rot * sin_rot * f1 - sin_rot * cos_rot * f2 + sin_dip * sin_dip * cos_rot * sin_rot * f3)21 self._txz = 2 * (cos_rot * cos_dip * sin_dip * f1 - cos_rot * cos_dip * sin_dip * f3)22 self._tyz = 2 * (sin_rot * cos_dip * sin_dip * f1 - sin_rot * cos_dip * sin_dip * f3)23 def _distance(self, dx, dy=0.0, dz=0.0):24 return np.sqrt(self._txx * dx ** 2 + self._tyy * dy ** 2 + self._tzz * dz ** 2 +25 self._txy * dx * dy + self._txz * dx * dz + self._tyz * dy * dz)26 def _corr(self, dx, dy=0.0, dz=0.0):27 d = self._distance(dx, dy, dz)28 return self._corr_1d(d)29 def _corr_1d(self, d):30 raise NotImplementedError()31 def create_corr_array(self, nx, dx, ny=1, dy=1.0, nz=1, dz=1.0, centered=True):32 xx, yy, zz = np.meshgrid(np.arange(-nx, nx + 1), np.arange(-ny, ny + 1), np.arange(-nz, nz + 1), indexing='ij')33 c = self._corr(xx * dx, yy * dy, zz * dz)34 if not centered:35 c = np.roll(c, shift=tuple(-(s // 2) for s in c.shape), axis=(0, 1, 2))36 return c37class ExponentialVariogram(Variogram):38 def _corr_1d(self, d):39 return np.exp(-3 * d)40class GaussianVariogram(Variogram):41 def _corr_1d(self, d):42 return np.exp(-3 * d ** 2)43class GeneralExponentialVariogram(Variogram):44 def __init__(self, rx, ry=1.0, rz=1.0, azi=0.0, dip=0.0, std=1.0, power=1.5):45 super().__init__(rx, ry, rz, azi, dip, std)46 self._power = power47 def _corr_1d(self, d):48 return np.exp(-3 * d ** self._power)49class SphericalVariogram(Variogram):50 def _corr_1d(self, d):51 return np.where(d < 1.0, 1.0 - d * (1.5 - 0.5 * (d ** 2)), 0.0)52class Matern32Variogram(Variogram):53 def _corr_1d(self, d):54 sd = 4.744 * d55 return np.exp(-sd) * (1.0 + sd)56class Matern52Variogram(Variogram):57 def _corr_1d(self, d):58 sd = 5.918 * d59 return np.exp(-sd) * (1.0 + sd + sd ** 2 / 3.0)60class Matern72Variogram(Variogram):61 def _corr_1d(self, d):62 sd = 6.877 * d...
geometry.py
Source:geometry.py
1from typing import Tuple2import numpy as np3class CoordinateTransformation:4 def __init__(self, rx, ry=1.0, rz=1.0, azi=0.0, dip=0.0):5 self._rx, self._ry, self._rz = rx, ry, rz6 self._azi = azi7 self._dip = dip8 # Factors9 cos_rot = np.cos(azi)10 sin_rot = np.sin(azi)11 cos_dip = np.cos(dip)12 sin_dip = np.sin(dip)13 # Rotation matrix14 self._rot_mat = np.array([15 [cos_dip * cos_rot, -sin_rot, sin_dip * cos_rot],16 [cos_dip * sin_rot, cos_rot, sin_dip * sin_rot],17 [-sin_dip, 0.0, cos_dip]18 ])19 # Scaling matrix20 self._scale_mat = np.diag([1 / rx, 1 / ry, 1 / rz])21 # Coefficients used to calculate distance directly22 f1 = 1 / rx ** 223 f2 = 1 / ry ** 224 f3 = 1 / rz ** 225 self._txx = cos_rot * cos_rot * cos_dip * cos_dip * f1 + sin_rot * sin_rot * f2 + cos_rot * cos_rot * sin_dip * sin_dip * f326 self._tyy = sin_rot * sin_rot * cos_dip * cos_dip * f1 + cos_rot * cos_rot * f2 + sin_rot * sin_rot * sin_dip * sin_dip * f327 self._tzz = sin_dip * sin_dip * f1 + cos_dip * cos_dip * f328 self._txy = 2 * (29 cos_dip * cos_dip * cos_rot * sin_rot * f1 - sin_rot * cos_rot * f2 + sin_dip * sin_dip * cos_rot * sin_rot * f3)30 self._txz = 2 * (cos_rot * cos_dip * sin_dip * f1 - cos_rot * cos_dip * sin_dip * f3)31 self._tyz = 2 * (sin_rot * cos_dip * sin_dip * f1 - sin_rot * cos_dip * sin_dip * f3)32 def distance(self, dx, dy=0.0, dz=0.0):33 return np.sqrt(self._txx * dx ** 2 + self._tyy * dy ** 2 + self._tzz * dz ** 2 +34 self._txy * dx * dy + self._txz * dx * dz + self._tyz * dy * dz)35 def forward_transform(self, s: np.ndarray) -> np.ndarray:36 if 0 < s.ndim < 3:37 s_3d = np.vstack((s, np.zeros(shape=(3 - s.ndim, s.shape[0]))))38 r = np.matmul(self._rot_mat, s)39 return np.matmul(self._scale_mat, r)40 def distance_field(self,41 x_lags: Tuple[int, int],42 y_lags: Tuple[int, int],43 n_x: int,44 n_y: int) -> Tuple[np.ndarray, np.ndarray]:45 h_x = np.linspace(x_lags[0], x_lags[1], n_x)46 h_y = np.linspace(y_lags[0], y_lags[1], n_y)47 hx_mesh, hy_mesh = np.meshgrid(h_x, h_y)48 hh = self.distance(hx_mesh.flatten(), hy_mesh.flatten())49 return hh50 def axis_aligned_bounding_box(self, factor: float) -> np.ndarray:51 m = (1.0/factor) * np.matmul(self._scale_mat, self._rot_mat)52 omega_inv = np.linalg.inv(np.matmul(m.transpose(), m))...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!