How to use draw_symbol method in hypothesis

Best Python code snippet using hypothesis

ap.py

Source:ap.py Github

copy

Full Screen

1"""2Package that allows you to plot simple graphs in ASCII, a la matplotlib.3This package is a inspired from Imri Goldberg's ASCII-Plotter 1.04(https://pypi.python.org/pypi/ASCII-Plotter/1.0)5At a time I was enoyed by security not giving me direct access to my computer,6and thus to quickly make figures from python, I looked at how I could make7quick and dirty ASCII figures. But if I were to develop something, I wanted8something that can be used with just python and possible standard-ish packages9(numpy, scipy).10So I came up with this package after many iterations based of ASCII-plotter.11I added the feature to show multiple curves on one plot with different markers.12And I also made the usage, close to matplotlib, such that there is a plot,13hist, hist2d and imshow functions.14TODO:15 imshow does not plot axis yet.16 make a correct documentation17"""18import math as _math19import numpy as np20__version__ = 0.921__author__ = 'M. Fouesneau'22__all__ = ['markers', 'ACanvas', 'AData', 'AFigure',23 'hist', 'hist2d', 'imshow', 'percentile_imshow',24 'plot', 'stem', 'stemify', 'step', 'steppify',25 '__version__', '__author__']26markers = { '-' : u'None' , # solid line style27 ',': u'\u2219', # point marker28 '.': u'\u2218', # pixel marker29 '.f': u'\u2218', # pixel marker30 'o': u'\u25CB', # circle marker31 'of': u'\u25CF', # circle marker32 'v': u'\u25BD', # triangle_down marker33 'vf': u'\u25BC', # filler triangle_down marker34 '^': u'\u25B3', # triangle_up marker35 '^f': u'\u25B2', # filled triangle_up marker36 '<': u'\u25C1', # triangle_left marker37 '<f': u'\u25C0', # filled triangle_left marker38 '>': u'\u25B7', # triangle_right marker39 '>f': u'\u25B6', # filled triangle_right marker40 's': u'\u25FD', # square marker41 'sf': u'\u25FC', # square marker42 '*': u'\u2606', # star marker43 '*f': u'\u2605', # star marker44 '+': u'\u271A', # plus marker45 'x': u'\u274C', # x marker46 'd': u'\u25C7', # diamond marker47 'df': u'\u25C6' # filled diamond marker48 }49def _sign(x):50 """ Return the sign of x51 INPUTS52 ------53 x: number54 value to get the sign of55 OUTPUTS56 -------57 s: signed int58 -1, 0 or 1 if negative, null or positive59 """60 if (x > 0):61 return 162 elif (x == 0):63 return 064 else:65 return -166def _transpose(mat):67 """ Transpose matrice made of lists68 INPUTS69 ------70 mat: iterable 2d list like71 OUTPUTS72 -------73 r: list of list, 2d list like74 transposed matrice75 """76 r = [ [x[i] for x in mat] for i in range(len(mat[0])) ]77 return r78def _y_reverse(mat):79 """ Reverse the y axis of a 2d list-like80 INPUTS81 ------82 mat: list of lists83 the matrix to reverse on axis 084 OUTPUTS85 -------86 r: list of lists87 the reversed version88 """89 r = [ list(reversed(mat_i)) for mat_i in mat ]90 return r91class AData(object):92 """ Data container for ascii AFigure """93 def __init__(self, x, y, marker='_.', plot_slope=True):94 """ Constructor95 INPUTS96 ------97 x: iterable98 x values99 y: iterable100 y values101 KEYWORDS102 --------103 marker: str104 marker for the data.105 if None or empty, the curve will be plotted106 if the first character of the marker is '_' then unicode markers will be called:107 marker repr description108 ======== =========== =============================109 '-' u'None' solid line style110 ',' u'\u2219' point marker111 '.' u'\u2218' pixel marker112 '.f' u'\u2218' pixel marker113 'o' u'\u25CB' circle marker114 'of' u'\u25CF' circle marker115 'v' u'\u25BD' triangle_down marker116 'vf' u'\u25BC' filler triangle_down marker117 '^' u'\u25B3' triangle_up marker118 '^f' u'\u25B2' filled triangle_up marker119 '<' u'\u25C1' triangle_left marker120 '<f' u'\u25C0' filled triangle_left marker121 '>' u'\u25B7' triangle_right marker122 '>f' u'\u25B6' filled triangle_right marker123 's' u'\u25FD' square marker124 'sf' u'\u25FC' square marker125 '*' u'\u2606' star marker126 '*f' u'\u2605' star marker127 '+' u'\u271A' plus marker128 'x' u'\u274C' x marker129 'd' u'\u25C7' diamond marker130 'df' u'\u25C6' filled diamond marker131 plot_slope: bool132 if set, the curve will be plotted133 """134 self.x = x135 self.y = y136 self.plot_slope = plot_slope137 self.set_marker(marker)138 def set_marker(self, marker):139 """ set the marker of the data140 INPUTS141 ------142 marker: str143 marker for the data.144 see constructor for marker descriptions145 """146 if marker in [None, 'None', u'None', '']:147 self.plot_slope = True148 self.marker = ''149 elif marker[0] == '_':150 self.marker = markers[marker[1:]]151 else:152 self.marker = marker153 def extent(self):154 """ return the extention of the data155 OUPUTS156 ------157 e: list158 [ min(x), max(x), min(y), max(y) ]159 """160 return [min(self.x), max(self.x), min(self.y), max(self.y)]161 def __repr__(self):162 s = 'AData: %s\n' % object.__repr__(self)163 return s164class ACanvas(object):165 """ Canvas of a AFigure instance. A Canvas handles all transformations166 between data space and figure space accounting for scaling and pixels167 In general there is no need to access the canvas directly168 """169 def __init__(self, shape=None, margins=None, xlim=None, ylim=None):170 """ Constructor171 KEYWORDS172 --------173 shape: tuple of 2 ints174 shape of the canvas in number of characters: (width, height)175 margins: tuple of 2 floats176 fractional margins177 xlim: tuple of 2 floats178 limits of the xaxis179 ylim: tuple of 2 floats180 limits of the yaxis181 """182 self.shape = shape or (50, 20)183 self.margins = margins or (0.05, 0.1)184 self._xlim = xlim or [0, 1]185 self._ylim = ylim or [0, 1]186 self.auto_adjust = True187 self.margin_factor = 1188 @property189 def x_size(self):190 """ return the width """191 return self.shape[0]192 @property193 def y_size(self):194 """ return the height """195 return self.shape[1]196 @property197 def x_margin(self):198 """ return the margin in x """199 return self.margins[0]200 @property201 def y_margin(self):202 """ return the margin in y """203 return self.margins[1]204 def xlim(self, vmin=None, vmax=None):205 """206 Get or set the *x* limits of the current axes.207 KEYWORDS208 --------209 vmin: float210 lower limit211 vmax: float212 upper limit213 xmin, xmax = xlim() # return the current xlim214 xlim( (xmin, xmax) ) # set the xlim to xmin, xmax215 xlim( xmin, xmax ) # set the xlim to xmin, xmax216 """217 if vmin is None and vmax is None:218 return self._xlim219 elif hasattr(vmin, '__iter__'):220 self._xlim = vmin[:2]221 else:222 self._xlim = [vmin, vmax]223 if self._xlim[0] == self._xlim[1]:224 self._xlim[1] += 1225 self._xlim[0] -= self.x_mod226 self._xlim[1] += self.x_mod227 def ylim(self, vmin=None, vmax=None):228 """229 Get or set the *y* limits of the current axes.230 KEYWORDS231 --------232 vmin: float233 lower limit234 vmax: float235 upper limit236 ymin, ymax = ylim() # return the current xlim237 ylim( (ymin, ymax) ) # set the xlim to xmin, xmax238 ylim( ymin, ymax ) # set the xlim to xmin, xmax239 """240 if vmin is None and vmax is None:241 return self._ylim242 elif hasattr(vmin, '__iter__'):243 self._ylim = vmin[:2]244 else:245 self._ylim = [vmin, vmax]246 if self._ylim[0] == self._ylim[1]:247 self._ylim[1] += 1248 self._ylim[0] -= self.y_mod249 self._ylim[1] += self.y_mod250 @property251 def min_x(self):252 """ return the lower x limit """253 return self._xlim[0]254 @property255 def max_x(self):256 """ return the upper x limit """257 return self._xlim[1]258 @property259 def min_y(self):260 """ return the lower y limit """261 return self._ylim[0]262 @property263 def max_y(self):264 """ return the upper y limit """265 return self._ylim[1]266 @property267 def x_step(self):268 return float(self.max_x - self.min_x) / float(self.x_size)269 @property270 def y_step(self):271 return float(self.max_y - self.min_y) / float(self.y_size)272 @property273 def ratio(self):274 return self.y_step / self.x_step275 @property276 def x_mod(self):277 return (self.max_x - self.min_x) * self.x_margin278 @property279 def y_mod(self):280 return (self.max_y - self.min_y) * self.y_margin281 def extent(self, margin_factor=None):282 margin_factor = margin_factor or self.margin_factor283 min_x = (self.min_x + self.x_mod * margin_factor)284 max_x = (self.max_x - self.x_mod * margin_factor)285 min_y = (self.min_y + self.y_mod * margin_factor)286 max_y = (self.max_y - self.y_mod * margin_factor)287 return (min_x, max_x, min_y, max_y)288 def extent_str(self, margin=None):289 def transform(val, fmt):290 if abs(val) < 1:291 _str = "%+.2g" % val292 elif fmt is not None:293 _str = fmt % val294 else:295 _str = None296 return _str297 e = self.extent(margin)298 xfmt = self.x_str()299 yfmt = self.y_str()300 return transform(e[0], xfmt), transform(e[1], xfmt), transform(e[2], yfmt), transform(e[3], yfmt)301 def x_str(self):302 if self.x_size < 16:303 x_str = None304 elif self.x_size < 23:305 x_str = "%+.2g"306 else:307 x_str = "%+g"308 return x_str309 def y_str(self):310 if self.x_size < 8:311 y_str = None312 elif self.x_size < 11:313 y_str = "%+.2g"314 else:315 y_str = "%+g"316 return y_str317 def coords_inside_buffer(self, x, y):318 return (0 <= x < self.x_size) and (0 < y < self.y_size)319 def coords_inside_data(self, x, y):320 """ return if (x,y) covered by the data box321 x, y: float322 coordinates to test323 """324 return (self.min_x <= x < self.max_x) and (self.min_y <= y < self.max_y)325 def _clip_line(self, line_pt_1, line_pt_2):326 """ clip a line to the canvas """327 e = self.extent()328 x_min = min(line_pt_1[0], line_pt_2[0])329 x_max = max(line_pt_1[0], line_pt_2[0])330 y_min = min(line_pt_1[1], line_pt_2[1])331 y_max = max(line_pt_1[1], line_pt_2[1])332 if line_pt_1[0] == line_pt_2[0]:333 return ( ( line_pt_1[0], max(y_min, e[1]) ),334 ( line_pt_1[0], min(y_max, e[3]) ))335 if line_pt_1[1] == line_pt_2[1]:336 return ( ( max(x_min, e[0]), line_pt_1[1] ),337 ( min(x_max, e[2]), line_pt_1[1] ))338 if ( (e[0] <= line_pt_1[0] < e[2]) and339 (e[1] <= line_pt_1[1] < e[3]) and340 (e[0] <= line_pt_2[0] < e[2]) and341 (e[1] <= line_pt_2[1] < e[3]) ):342 return line_pt_1, line_pt_2343 ts = [0.0,344 1.0,345 float(e[0] - line_pt_1[0]) / (line_pt_2[0] - line_pt_1[0]),346 float(e[2] - line_pt_1[0]) / (line_pt_2[0] - line_pt_1[0]),347 float(e[1] - line_pt_1[1]) / (line_pt_2[1] - line_pt_1[1]),348 float(e[3] - line_pt_1[1]) / (line_pt_2[1] - line_pt_1[1])349 ]350 ts.sort()351 if (ts[2] < 0) or (ts[2] >= 1) or (ts[3] < 0) or (ts[2] >= 1):352 return None353 result = [(pt_1 + t * (pt_2 - pt_1)) for t in (ts[2], ts[3]) for (pt_1, pt_2) in zip(line_pt_1, line_pt_2)]354 return ( result[:2], result[2:] )355class AFigure(object):356 def __init__(self, shape=(80, 20), margins=(0.05, 0.1), draw_axes=True, newline='\n',357 plot_labels=True, xlim=None, ylim=None, **kwargs):358 self.canvas = ACanvas(shape, margins=margins, xlim=xlim, ylim=ylim)359 self.draw_axes = draw_axes360 self.new_line = newline361 self.plot_labels = plot_labels362 self.output_buffer = None363 self.tickSymbols = u'\u253C' # "+"364 self.x_axis_symbol = u'\u2500' # u"\u23bc" # "-"365 self.y_axis_symbol = u'\u2502' # "|"366 self.data = []367 def xlim(self, vmin=None, vmax=None):368 return self.canvas.xlim(vmin, vmax)369 def ylim(self, vmin=None, vmax=None):370 return self.canvas.ylim(vmin, vmax)371 def get_coord(self, val, min, step, limits=None):372 result = int((val - min) / step)373 if limits is not None:374 if result <= limits[0]:375 result = limits[0]376 elif result >= limits[1]:377 result = limits[1] - 1378 return result379 def _draw_axes(self):380 zero_x = self.get_coord(0, self.canvas.min_x, self.canvas.x_step, limits=[1, self.canvas.x_size])381 if zero_x >= self.canvas.x_size:382 zero_x = self.canvas.x_size - 1383 for y in range(self.canvas.y_size):384 self.output_buffer[zero_x][y] = self.y_axis_symbol385 zero_y = self.get_coord(0, self.canvas.min_y, self.canvas.y_step, limits=[1, self.canvas.y_size])386 if zero_y >= self.canvas.y_size:387 zero_y = self.canvas.y_size - 1388 for x in range(self.canvas.x_size):389 self.output_buffer[x][zero_y] = self.x_axis_symbol # u'\u23bc'390 self.output_buffer[zero_x][zero_y] = self.tickSymbols # "+"391 def _get_symbol_by_slope(self, slope, default_symbol):392 """ Return a line oriented directed approximatively along the slope value """393 if slope > _math.tan(3 * _math.pi / 8):394 draw_symbol = "|"395 elif _math.tan(_math.pi / 8) < slope < _math.tan(3 * _math.pi / 8):396 draw_symbol = u'\u27cb' # "/"397 elif abs(slope) < _math.tan(_math.pi / 8):398 draw_symbol = "-"399 elif slope < _math.tan(-_math.pi / 8) and slope > _math.tan(-3 * _math.pi / 8):400 draw_symbol = u'\u27CD' # "\\"401 elif slope < _math.tan(-3 * _math.pi / 8):402 draw_symbol = "|"403 else:404 draw_symbol = default_symbol405 return draw_symbol406 def _plot_labels(self):407 if self.canvas.y_size < 2:408 return409 act_min_x, act_max_x, act_min_y, act_max_y = self.canvas.extent()410 min_x_coord = self.get_coord(act_min_x, self.canvas.min_x, self.canvas.x_step, limits=[0, self.canvas.x_size])411 max_x_coord = self.get_coord(act_max_x, self.canvas.min_x, self.canvas.x_step, limits=[0, self.canvas.x_size])412 min_y_coord = self.get_coord(act_min_y, self.canvas.min_y, self.canvas.y_step, limits=[1, self.canvas.y_size])413 max_y_coord = self.get_coord(act_max_y, self.canvas.min_y, self.canvas.y_step, limits=[1, self.canvas.y_size])414 x_zero_coord = self.get_coord(0, self.canvas.min_x, self.canvas.x_step, limits=[0, self.canvas.x_size])415 y_zero_coord = self.get_coord(0, self.canvas.min_y, self.canvas.y_step, limits=[1, self.canvas.y_size])416 self.output_buffer[x_zero_coord][min_y_coord] = self.tickSymbols417 self.output_buffer[x_zero_coord][max_y_coord] = self.tickSymbols418 self.output_buffer[min_x_coord][y_zero_coord] = self.tickSymbols419 self.output_buffer[max_x_coord][y_zero_coord] = self.tickSymbols420 min_x_str, max_x_str, min_y_str, max_y_str = self.canvas.extent_str()421 if (self.canvas.x_str() is not None):422 for i, c in enumerate(min_x_str):423 self.output_buffer[min_x_coord + i + 1][y_zero_coord - 1] = c424 for i, c in enumerate(max_x_str):425 self.output_buffer[max_x_coord + i - len(max_x_str)][y_zero_coord - 1] = c426 if (self.canvas.y_str() is not None):427 for i, c in enumerate(max_y_str):428 self.output_buffer[x_zero_coord + i + 1][max_y_coord] = c429 for i, c in enumerate(min_y_str):430 self.output_buffer[x_zero_coord + i + 1][min_y_coord] = c431 def _plot_line(self, start, end, data):432 """ plot a line from start = (x0, y0) to end = (x1, y1) """433 clipped_line = self.canvas._clip_line(start, end)434 if clipped_line is None:435 return False436 start, end = clipped_line437 x0 = self.get_coord(start[0], self.canvas.min_x, self.canvas.x_step)438 y0 = self.get_coord(start[1], self.canvas.min_y, self.canvas.y_step)439 x1 = self.get_coord(end[0], self.canvas.min_x, self.canvas.x_step)440 y1 = self.get_coord(end[1], self.canvas.min_y, self.canvas.y_step)441 if (x0, y0) == (x1, y1):442 return True443 #x_zero_coord = self.get_coord(0, self.canvas.min_x, self.canvas.x_step)444 y_zero_coord = self.get_coord(0, self.canvas.min_y, self.canvas.y_step, limits=[1, self.canvas.y_size])445 if start[0] - end[0] == 0:446 draw_symbol = u"|"447 elif start[1] - end[1] == 0:448 draw_symbol = '-'449 else:450 slope = (1.0 / self.canvas.ratio) * (end[1] - start[1]) / (end[0] - start[0])451 draw_symbol = self._get_symbol_by_slope(slope, data.marker)452 dx = x1 - x0453 dy = y1 - y0454 if abs(dx) > abs(dy):455 s = _sign(dx)456 slope = float(dy) / dx457 for i in range(0, abs(int(dx))):458 cur_draw_symbol = draw_symbol459 x = i * s460 cur_y = int(y0 + slope * x)461 if (self.draw_axes) and (cur_y == y_zero_coord) and (draw_symbol == self.x_axis_symbol):462 cur_draw_symbol = "-"463 self.output_buffer[x0 + x][cur_y] = cur_draw_symbol464 else:465 s = _sign(dy)466 slope = float(dx) / dy467 for i in range(0, abs(int(dy))):468 y = i * s469 cur_draw_symbol = draw_symbol470 cur_y = y0 + y471 if (self.draw_axes) and (cur_y == y_zero_coord) and (draw_symbol == self.x_axis_symbol):472 cur_draw_symbol = "-"473 self.output_buffer[int(x0 + slope * y)][cur_y] = cur_draw_symbol474 return False475 def _plot_data_with_slope(self, data):476 xy = list(zip(data.x, data.y))477 #sort according to the x coord478 xy.sort(key=lambda c: c[0])479 prev_p = xy[0]480 e_xy = enumerate(xy)481 e_xy.next()482 for i, (xi, yi) in e_xy:483 line = self._plot_line(prev_p, (xi, yi), data)484 prev_p = (xi, yi)485 # if no line, then symbol486 if not line & self.canvas.coords_inside_data(xi, yi):487 draw_symbol = data.marker488 px, py = xy[i - 1]489 nx, ny = xy[i]490 if abs(nx - px) > 0.000001:491 slope = (1.0 / self.canvas.ratio) * (ny - py) / (nx - px)492 draw_symbol = self._get_symbol_by_slope(slope, draw_symbol)493 x_coord = self.get_coord(xi, self.canvas.min_x, self.canvas.x_step)494 y_coord = self.get_coord(yi, self.canvas.min_y, self.canvas.y_step)495 if self.canvas.coords_inside_buffer(x_coord, y_coord):496 y0_coord = self.get_coord(0, self.canvas.min_y, self.canvas.y_step)497 if self.draw_axes:498 if (y_coord == y0_coord) and (draw_symbol == u"\u23bc"):499 draw_symbol = "="500 self.output_buffer[x_coord][y_coord] = draw_symbol501 def _plot_data(self, data):502 if data.plot_slope:503 self._plot_data_with_slope(data)504 else:505 for x, y in zip(data.x, data.y):506 if self.canvas.coords_inside_data(x, y):507 x_coord = self.get_coord(x, self.canvas.min_x, self.canvas.x_step)508 y_coord = self.get_coord(y, self.canvas.min_y, self.canvas.y_step)509 if self.canvas.coords_inside_buffer(x_coord, y_coord):510 self.output_buffer[x_coord][y_coord] = data.marker511 def auto_limits(self):512 if self.canvas.auto_adjust is True:513 min_x = 0.514 max_x = 0.515 min_y = 0.516 max_y = 0.517 for dk in self.data:518 ek = dk.extent()519 min_x = min(min_x, min(ek[:2]))520 min_y = min(min_y, min(ek[2:]))521 max_x = max(max_x, max(ek[:2]))522 max_y = max(max_y, max(ek[2:]))523 self.canvas.xlim(min_x, max_x)524 self.canvas.ylim(min_y, max_y)525 def append_data(self, data):526 self.data.append(data)527 self.auto_limits()528 def plot(self, x_seq, y_seq=None, marker=None, plot_slope=False, xlim=None, ylim=None):529 if y_seq is None:530 y_seq = x_seq[:]531 x_seq = range(len(y_seq))532 data = AData(x_seq, y_seq, marker=marker, plot_slope=plot_slope)533 self.append_data(data)534 if xlim is not None:535 self.canvas.xlim(xlim)536 if ylim is not None:537 self.canvas.ylim(xlim)538 return self.draw()539 def draw(self):540 self.output_buffer = [[" "] * self.canvas.y_size for i in range(self.canvas.x_size)]541 if self.draw_axes:542 self._draw_axes()543 for dk in self.data:544 self._plot_data(dk)545 if self.plot_labels:546 self._plot_labels()547 trans_result = _transpose(_y_reverse(self.output_buffer))548 result = self.new_line.join(["".join(row) for row in trans_result])549 return result550def plot(x, y=None, marker=None, shape=(50, 20), draw_axes=True,551 newline='\n', plot_slope=False, x_margin=0.05,552 y_margin=0.1, plot_labels=True, xlim=None, ylim=None):553 flags = {'shape': shape,554 'draw_axes': draw_axes,555 'newline': newline,556 'marker': marker,557 'plot_slope': plot_slope,558 'margins': (x_margin, y_margin),559 'plot_labels': plot_labels }560 p = AFigure(**flags)561 print(p.plot(x, y, marker=marker, plot_slope=plot_slope))562def steppify(x, y):563 """ Steppify a curve (x,y). Useful for manually filling histograms """564 dx = 0.5 * (x[1:] + x[:-1])565 xx = np.zeros( 2 * len(dx), dtype=float)566 yy = np.zeros( 2 * len(y), dtype=float)567 xx[0::2], xx[1::2] = dx, dx568 yy[0::2], yy[1::2] = y, y569 xx = np.concatenate(([x[0] - (dx[0] - x[0])], xx, [x[-1] + (x[-1] - dx[-1])]))570 return xx, yy571def stemify(x, y):572 """ Steppify a curve (x,y). Useful for manually filling histograms """573 xx = np.zeros( 3 * len(x), dtype=float)574 yy = np.zeros( 3 * len(y), dtype=float)575 xx[0::3], xx[1::3], xx[2::3] = x, x, x576 yy[1::3] = y577 return xx, yy578def hist(x, bins=10, normed=False, weights=None, density=None, histtype='stem',579 shape=(50, 20), draw_axes=True, newline='\n',580 marker='_.', plot_slope=False, x_margin=0.05,581 y_margin=0.1, plot_labels=True, xlim=None, ylim=None ):582 from numpy import histogram583 if histtype not in ['None', 'stem', 'step']:584 raise ValueError('histtype must be in [None, stem, step]')585 n, b = histogram(x, bins=bins, range=xlim, normed=normed, weights=weights, density=density)586 _x = 0.5 * ( b[:-1] + b[1:] )587 if histtype == 'step':588 step(_x, n.astype(float))589 elif histtype == 'stem':590 stem(_x, n.astype(float))591 else:592 _y = n.astype(float)593 plot(_x, _y, shape=shape, draw_axes=draw_axes, newline=newline, marker=marker,594 plot_slope=plot_slope, x_margin=x_margin, y_margin=y_margin,595 plot_labels=plot_labels, xlim=xlim, ylim=ylim)596def step(x, y, shape=(50, 20), draw_axes=True,597 newline='\n', marker='_.', plot_slope=True, x_margin=0.05,598 y_margin=0.1, plot_labels=True, xlim=None, ylim=None ):599 _x, _y = steppify(x, y)600 plot(_x, _y, shape=shape, draw_axes=draw_axes, newline=newline, marker=marker,601 plot_slope=plot_slope, x_margin=x_margin, y_margin=y_margin,602 plot_labels=plot_labels, xlim=xlim, ylim=ylim)603def stem(x, y, shape=(50, 20), draw_axes=True,604 newline='\n', marker='_.', plot_slope=True, x_margin=0.05,605 y_margin=0.1, plot_labels=True, xlim=None, ylim=None ):606 _x, _y = stemify(x, y)607 plot(_x, _y, shape=shape, draw_axes=draw_axes, newline=newline, marker=marker,608 plot_slope=plot_slope, x_margin=x_margin, y_margin=y_margin,609 plot_labels=plot_labels, xlim=xlim, ylim=ylim)610def hist2d(x, y, bins=[50, 20], range=None, normed=False, weights=None, ncolors=16,611 width=50, percentiles=None):612 im, ex, ey = np.histogram2d(x, y, bins, range=None, normed=normed, weights=weights)613 if percentiles is None:614 imshow(im, extent=[min(ex), max(ex), min(ey), max(ey)],615 ncolors=ncolors, width=width)616 else:617 percentile_imshow(im, levels=percentiles, extent=None,618 width=width, ncolors=width)619def percentile_imshow(im, levels=[68, 95, 99], extent=None, width=50, ncolors=16):620 _im = im.astype(float)621 _im -= im.min()622 _im /= _im.max()623 n = len(levels)624 for e, lk in enumerate(sorted(levels)):625 _im[ _im <= 0.01 * float(lk) ] = n - e626 imshow(1. - _im, extent=None, width=width, ncolors=ncolors)627def imshow(im, extent=None, width=50, ncolors=16):628 from scipy import ndimage629 width0 = im.shape[0]630 _im = ndimage.zoom(im.astype(float), float(width) / float(width0) )631 _im -= im.min()632 _im /= _im.max()633 width, height = _im.shape[:2]634 if len(im.shape) > 2:635 _clr = True636 else:637 _clr = False638 if ncolors == 16:639 color = "MNHQ$OC?7>!:-;. "[::-1]640 else:641 color = '''$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. '''[::-1]642 ncolors = len(color)643 string = ""644 if not _clr:645 for h in range(height): # first go through the height, otherwise will roate646 for w in range(width):647 string += color[int(_im[w, h] * (ncolors - 1) )]648 string += "\n"649 else:650 for h in range(height): # first go through the height, otherwise will roate651 for w in range(width):652 string += color[int(sum(_im[w, h]) * (ncolors - 1) )]653 string += "\n"...

Full Screen

Full Screen

opencv_filter.py

Source:opencv_filter.py Github

copy

Full Screen

...222 output = np.dstack([frame, np.ones((h, w), dtype="uint8") * 255])223 # Threshold the HSV image224 # Red225 light_red_mask = cv2.inRange(hsv, lower_light_red, upper_light_red)226 draw_symbol(light_red_mask, detector, 'vermelho.png', output, h, w)227 228 red_mask = cv2.inRange(hsv, lower_red, upper_red)229 draw_symbol(red_mask, detector, 'vermelho.png', output, h, w)230 231 dark_red_mask = cv2.inRange(hsv, lower_dark_red, upper_dark_red)232 draw_symbol(dark_red_mask, detector, 'vermelho.png', output, h, w)233 # Yellow234 light_yellow_mask = cv2.inRange(hsv, lower_light_yellow, upper_light_yellow)235 draw_symbol(light_yellow_mask, detector, 'amarelo.png', output, h, w)236 237 yellow_mask = cv2.inRange(hsv, lower_yellow, upper_yellow)238 draw_symbol(yellow_mask, detector, 'amarelo.png', output, h, w)239 240 dark_yellow_mask = cv2.inRange(hsv, lower_dark_yellow, upper_dark_yellow)241 draw_symbol(dark_yellow_mask, detector, 'amarelo.png', output, h, w)242 # Orange243 light_orange_mask = cv2.inRange(hsv, lower_light_orange, upper_light_orange)244 draw_symbol(light_orange_mask, detector, 'laranja.png', output, h, w)245 246 orange_mask = cv2.inRange(hsv, lower_orange, upper_orange)247 draw_symbol(orange_mask, detector, 'laranja.png', output, h, w)248 249 dark_orange_mask = cv2.inRange(hsv, lower_dark_orange, upper_dark_orange)250 draw_symbol(dark_orange_mask, detector, 'laranja.png', output, h, w)251 # Brown252 light_brown_mask = cv2.inRange(hsv, lower_light_brown, upper_light_brown)253 draw_symbol(light_brown_mask, detector, 'castanho.png', output, h, w)254 255 brown_mask = cv2.inRange(hsv, lower_brown, upper_brown)256 draw_symbol(brown_mask, detector, 'castanho.png', output, h, w)257 258 dark_brown_mask = cv2.inRange(hsv, lower_dark_brown, upper_dark_brown)259 draw_symbol(dark_brown_mask, detector, 'castanho.png', output, h, w)260 # Green261 light_green_mask = cv2.inRange(hsv, lower_light_green, upper_light_green)262 draw_symbol(light_green_mask, detector, 'verde.png', output, h, w)263 264 green_mask = cv2.inRange(hsv, lower_green, upper_green)265 draw_symbol(green_mask, detector, 'verde.png', output, h, w)266 267 dark_green_mask = cv2.inRange(hsv, lower_dark_green, upper_dark_green)268 draw_symbol(dark_green_mask, detector, 'verde.png', output, h, w)269 # Blue270 light_blue_mask = cv2.inRange(hsv, lower_light_blue, upper_light_blue)271 draw_symbol(light_blue_mask, detector, 'azul.png', output, h, w)272 blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)273 draw_symbol(blue_mask, detector, 'azul.png', output, h, w)274 dark_blue_mask = cv2.inRange(hsv, lower_dark_blue, upper_dark_blue)275 draw_symbol(dark_blue_mask, detector, 'azul.png', output, h, w)276 # Violet277 light_violet_mask = cv2.inRange(hsv, lower_light_violet, upper_light_violet)278 draw_symbol(light_violet_mask, detector, 'violeta.png', output, h, w)279 280 violet_mask = cv2.inRange(hsv, lower_violet, upper_violet)281 draw_symbol(violet_mask, detector, 'violeta.png', output, h, w)282 dark_violet_mask = cv2.inRange(hsv, lower_dark_violet, upper_dark_violet)283 draw_symbol(dark_violet_mask, detector, 'violeta.png', output, h, w)284 # Black285 black_mask = cv2.inRange(hsv, lower_black, upper_black)286 white_mask = cv2.inRange(hsv, lower_white, upper_white)287 288 ratio_blue = getPercentage(frame, hsv, lower_dark_blue, upper_blue)289 ratio_blue = ratio_blue + getPercentage(frame, hsv, lower_light_blue, upper_light_blue)290 ratio_blue = ratio_blue + getPercentage(frame, hsv, lower_dark_blue, upper_dark_blue)291 log.update({'blue' : ratio_blue})292 ratio_green = getPercentage(frame, hsv, lower_dark_green, upper_green)293 ratio_green = ratio_green + getPercentage(frame, hsv, lower_light_green, upper_light_green)294 ratio_green = ratio_green + getPercentage(frame, hsv, lower_dark_green, upper_dark_green)295 log.update({'green' : ratio_green})296 ratio_yellow = getPercentage(frame, hsv, lower_dark_yellow, upper_yellow)297 ratio_yellow = ratio_yellow + getPercentage(frame, hsv, lower_light_yellow, upper_light_yellow)298 ratio_yellow = ratio_yellow + getPercentage(frame, hsv, lower_dark_yellow, upper_dark_yellow)299 log.update({'yellow' : ratio_yellow})300 ratio_orange = getPercentage(frame, hsv, lower_dark_orange, upper_orange)301 ratio_orange = ratio_orange + getPercentage(frame, hsv, lower_light_orange, upper_light_orange)302 ratio_orange = ratio_orange + getPercentage(frame, hsv, lower_dark_orange, upper_dark_orange)303 log.update({'orange' : ratio_orange})304 ratio_red = getPercentage(frame, hsv, lower_dark_red, upper_red)305 ratio_red = ratio_red + getPercentage(frame, hsv, lower_light_red, upper_light_red)306 ratio_red = ratio_red + getPercentage(frame, hsv, lower_dark_red, upper_dark_red)307 log.update({'red' : ratio_red})308 ratio_violet = getPercentage(frame, hsv, lower_dark_violet, upper_violet)309 ratio_violet = ratio_violet + getPercentage(frame, hsv, lower_light_violet, upper_light_violet)310 ratio_violet = ratio_violet + getPercentage(frame, hsv, lower_dark_violet, upper_dark_violet)311 log.update({'violet' : ratio_violet})312 ratio_brown = getPercentage(frame, hsv, lower_dark_brown, upper_brown)313 ratio_brown = ratio_brown + getPercentage(frame, hsv, lower_light_brown, upper_light_brown)314 ratio_brown = ratio_brown + getPercentage(frame, hsv, lower_dark_brown, upper_dark_brown)315 log.update({'brown' : ratio_brown})316 ratio_white = getPercentage(frame, hsv, lower_white, upper_white)317 log.update({'white' : ratio_white})318 ratio_black = getPercentage(frame, hsv, lower_black, upper_black)319 log.update({'black' : ratio_black})320 321 with open("ratio.csv", "a") as write_file:322 write_file.write("\n")323 write_file.close()324 print(log)325 return output, log326def draw_symbol(color_mask, detector, file_name, output, h, w):327 #print(file_name)328 # Detect blobs.329 mask = cv2.bitwise_not(color_mask)330 keypoints = detector.detect(mask)331 332 # Load symbol333 watermark = cv2.imread("symbols/"+file_name, -1)334 watermark = cv2.resize(watermark, (20,20))335 (wH, wW) = watermark.shape[:2]336 #print(type(keypoints))337 #print(keypoints)338 for point in keypoints:339 #print(str(h)+" "+str(w))340 overlay = np.zeros((h, w, 4), dtype="uint8")...

Full Screen

Full Screen

minimalgame.py

Source:minimalgame.py Github

copy

Full Screen

...22 23 def game_loop(self):24 # this gets executed every frame25 if self.key_up():26 self.draw_symbol(1,1, NamedSymbol.H, NamedColor.blue)27 self.draw_symbol(1,2, NamedSymbol.E, NamedColor.yellow)28 self.draw_symbol(1,3, NamedSymbol.L, NamedColor.black)29 self.draw_symbol(1,4, NamedSymbol.L, NamedColor.green)30 self.draw_symbol(1,5, NamedSymbol.O, NamedColor.red)31 else:32 self.draw_symbol(1,1, NamedSymbol.none, NamedColor.blue)33 self.draw_symbol(1,2, NamedSymbol.none, NamedColor.yellow)34 self.draw_symbol(1,3, NamedSymbol.none, NamedColor.black)35 self.draw_symbol(1,4, NamedSymbol.none, NamedColor.green)36 self.draw_symbol(1,5, NamedSymbol.none, NamedColor.red)37def main():38 game = MinimalGame(3, BRIDGES_USERNAME, BRIDGES_API_KEY,)39 # start the game40 game.start()41if __name__ == "__main__":...

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