def __main__(stdscr, projection=False): angleX, angleY, angleZ = 0, 0, 0 c = Canvas() while 1: # Will hold transformed vertices. t = [] for v in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D p = p.project(50, 50, 50, 50) #Put the point in the list of transformed vertices t.append(p) for f in faces: for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y): c.set(x, y) for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y): c.set(x, y) for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y): c.set(x, y) for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y): c.set(x, y) f = c.frame(-40, -40, 80, 80) stdscr.addstr(0, 0, '{0}\n'.format(f)) stdscr.refresh() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0 / 20) c.clear()
def __main__(stdscr, projection=False): angleX, angleY, angleZ = 0, 0, 0 c = Canvas() while 1: # Will hold transformed vertices. t = [] for v in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D p = p.project(50, 50, 50, 50) #Put the point in the list of transformed vertices t.append(p) for f in faces: for x,y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y): c.set(x,y) for x,y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y): c.set(x,y) for x,y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y): c.set(x,y) for x,y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y): c.set(x,y) f = c.frame(-40, -40, 80, 80) stdscr.addstr(0, 0, '{0}\n'.format(f)) stdscr.refresh() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0/20) c.clear()
def draw_simple_map(stdscr): c = Canvas() v1 = Point(-20, 20) v2 = Point(20, 20) v3 = Point(-20, -20) v4 = Point(20, -20) lines = [ (v1, v2), (v1, v3), (v3, v4), (v4, v2), ] for start, end in lines: for x, y in line(start.x, start.y, end.x, end.y): c.set(x, y) df = c.frame(-40, -40, 80, 80) stdscr.addstr(1, 0, f"{df}") stdscr.refresh() sleep(10) c.clear()
def main(args, opts): curses.use_default_colors() curses.curs_set(0) win = curses.initscr() source = Image.open(opts.filename) c = Canvas() try: while True: (wh, ww) = win.getmaxyx() try: source.seek(source.tell() + 1) except: if opts.onetime: break source.seek(0) img = (source .resize(((ww - 1) * 2, wh * 4)) .convert("1") ) w = img.width (x, y) = (0, 0) for v in img.getdata(): if opts.reverse: if not v: c.set(x, y) else: if v: c.set(x, y) x += 1 if w <= x: x = 0 y += 1 for r in range(wh): line = c.rows(min_y=(r*4), max_y=((r+1)*4))[0] win.addnstr(r, 0, pad(line, ww), ww) win.refresh() c.clear() time.sleep(opts.interval) except KeyboardInterrupt: pass
def main(stdscr): global frame_no, speed, fps, position, delta, score c = Canvas() bar_width = 16 bars = [Bar(bar_width)] stdscr.refresh() while True: frame_no += 1 for bar in bars: if check_collision(position, bar): return while not keys.empty(): if keys.get() == 113: return speed = 32.0 c.set(0,0) c.set(width, height) if frame_no % 50 == 0: bars.append(Bar(bar_width)) for x,y in bird: c.set(x,y+position) for bar_index, bar in enumerate(bars): if bar.x < 1: bars.pop(bar_index) score += 1 else: bars[bar_index].x -= 1 for x,y in bar.draw(): c.set(x,y) f = c.frame()+'\n' stdscr.addstr(0, 0, f) stdscr.addstr(height/4+1, 0, 'score: {0}'.format(score)) stdscr.refresh() c.clear() speed -= 2 position -= speed/10 if position < 0: position = 0 speed = 0.0 elif position > height-13: position = height-13 speed = 0.0 sleep(1.0/fps)
def main(stdscr): global frame_no, speed, position, score c = Canvas() bar_width = 16 bars = [Bar(bar_width)] stdscr.refresh() while True: frame_no += 1 for bar in bars: if check_collision(position, bar): return while not keys.empty(): if keys.get() == 113: return speed = 32.0 c.set(0,0) c.set(width, height) if frame_no % 50 == 0: bars.append(Bar(bar_width)) for x,y in bird: c.set(x,y+position) for bar_index, bar in enumerate(bars): if bar.x < 1: bars.pop(bar_index) score += 1 else: bars[bar_index].x -= 1 for x,y in bar.draw(): c.set(x,y) f = c.frame()+'\n' stdscr.addstr(0, 0, f) stdscr.addstr(height/4+1, 0, 'score: {0}'.format(score)) stdscr.refresh() c.clear() speed -= 2 position -= speed/10 if position < 0: position = 0 speed = 0.0 elif position > height-13: position = height-13 speed = 0.0 sleep(1.0/fps)
def __main__(stdscr, projection=False): angleX, angleY, angleZ = 0, 0, 0 canvas = Canvas() while 1: # Will hold transformed vertices. transformed_vertices = [] for vertex in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. point = vertex.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D point = point.project(50, 50, 50, 50) #Put the point in the list of transformed vertices transformed_vertices.append(point) for face in faces: for x, y in line(transformed_vertices[face[0]].x, transformed_vertices[face[0]].y, transformed_vertices[face[1]].x, transformed_vertices[face[1]].y): canvas.set(x, y) for x, y in line(transformed_vertices[face[1]].x, transformed_vertices[face[1]].y, transformed_vertices[face[2]].x, transformed_vertices[face[2]].y): canvas.set(x, y) for x, y in line(transformed_vertices[face[2]].x, transformed_vertices[face[2]].y, transformed_vertices[face[3]].x, transformed_vertices[face[3]].y): canvas.set(x, y) for x, y in line(transformed_vertices[face[3]].x, transformed_vertices[face[3]].y, transformed_vertices[face[0]].x, transformed_vertices[face[0]].y): canvas.set(x, y) frame = canvas.frame(-40, -40, 80, 80) stdscr.addstr(0, 0, '{0}\n'.format(frame)) stdscr.refresh() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0 / 20) canvas.clear()
def __main__(stdscr): i = 0 c = Canvas() height = 40 while True: for x,y in line(0, height, 180, int(math.sin(math.radians(i)) * height + height)): c.set(x,y) for x in range(0, 360, 2): coords = (x/2, height + int(round(math.sin(math.radians(x+i)) * height))) c.set(*coords) f = c.frame() stdscr.addstr(0, 0, '{0}\n'.format(f)) stdscr.refresh() i += 2 sleep(1.0/24) c.clear()
def draw_coords(stdscr, design): c = Canvas() for i in range(10): for point in design: c.set(point.x, point.y) df = c.frame(-40, -40, 80, 80) stdscr.addstr(1, 0, df) stdscr.refresh() new_move_delta = Point(choice([-1, 0, 1]), choice([-1, 0, 1])) design = move(design, new_move_delta) sleep(.5) c.clear() sleep(6) c.clear()
def __main__(projection=False): angleX, angleY, angleZ = 0, 0, 0 c = Canvas() while 1: # Will hold transformed vertices. t = [] for v in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D p = p.project(50, 50, 50, 50) #Put the point in the list of transformed vertices t.append(p) for f in faces: for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y): c.set(x, y) for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y): c.set(x, y) for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y): c.set(x, y) for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y): c.set(x, y) f = c.frame(-20, -20, 20, 20) s = 'broadcast "\\n\\n\\n' for l in format(f).splitlines(): s += l.replace(' ', ' ').rstrip('\n') + '\\n' s = s[:-2] s += '"' print(s) sys.stdout.flush() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0 / 10) c.clear()
def __main__(projection=False): angleX, angleY, angleZ = 0, 0, 0 c = Canvas() while 1: # Will hold transformed vertices. t = [] for v in vertices: # Rotate the point around X axis, then around Y axis, and finally around Z axis. p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ) if projection: # Transform the point from 3D to 2D p = p.project(50, 50, 50, 50) # Put the point in the list of transformed vertices t.append(p) for f in faces: for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y): c.set(x, y) for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y): c.set(x, y) for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y): c.set(x, y) for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y): c.set(x, y) f = c.frame(-20, -20, 20, 20) s = 'broadcast "\\n\\n\\n' for l in format(f).splitlines(): s += l.replace(" ", " ").rstrip("\n") + "\\n" s = s[:-2] s += '"' print(s) sys.stdout.flush() angleX += 2 angleY += 3 angleZ += 5 sleep(1.0 / 10) c.clear()
def printa_parabola(lado): s = Canvas() s.clear() for x in range(0, 180): s.set(x / 4, lado + sin(radians(x)) * lado) return s.frame()
class Sparkline(Widget): def __init__(self, scr, data, maxlen=1024, enc="utf-8", name="Sparkline"): super(Sparkline, self).__init__(scr, enc=enc, name=name) def mkcanvases(): d = { "data": collections.deque([], maxlen=maxlen), "canvas": Canvas(), "attr": curses.color_pair(random.choice([1, 2, 3, 4, 5])), "dirty": True, } return d self.axes = Canvas() self.canvases = collections.defaultdict(mkcanvases) self.maxlen = maxlen for x in data: # data=[("foo", [...]), ("bar", [...])] if len(x) == 3: name, d, attr = x else: name, d = x attr = None self.add_data(name, d, attr=attr) self.edge_buffer = 20 # 20px from edges self.data_buffer = 3 # + 3px added buffer for the data canvas self.rounding = 5 # round axes up to nearest 5. self.fill = True # fill inbetween points with lines def add_data(self, name, data, maxlen=None, attr=None): if maxlen is None: maxlen = self.maxlen if attr is not None: self.canvases[name]["attr"] = attr self.canvases[name]["data"] = collections.deque(data, maxlen=maxlen) def add_point(self, name, p): self.canvases[name]["data"].append(p) self.canvases[name]["dirty"] = True def map(self, x, in_min, in_max, out_min, out_max): # Shamelessly lifted from the Arduino project. if in_max == 0: return 0 return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min) def _render_canvas(self, name, mx, my): if not self.canvases[name]["dirty"]: # Nothing to do unless the canvas data is dirty. return # NOTE: We can only show at most (x*2) data points because of how the # braille trick works. # We're also accounting for the screen borders, the buffers for # the axis edges, as well as buffering the data some more. _m = -((mx - 2 - (self.edge_buffer + self.data_buffer)) * 2) data = list(self.canvases[name]["data"])[_m:] max_point = float(max(data)) # Round our vertical axes up to the nearest five. This just looks nicer. max_axes = int(math.ceil(max_point / self.rounding)) * self.rounding # max_points represents the "100%" mark for our y-axis. i.e. top. max_points = (my * 4) - self.edge_buffer * 2 - self.data_buffer * 2 canvas = self.canvases[name]["canvas"] canvas.clear() canvas.set(0, 0) # TODO: why do I need this hack? lx, ly = -1, -1 for i, point in enumerate(data): x = i - self.edge_buffer + self.data_buffer # 0 -> 0%, max_point -> 100% mapped = self.map(float(point), 0.0, max_point, 0.0, float(max_points)) # account for edges and stuff, my*8/2 etc. y = (my * 4) - self.edge_buffer - self.data_buffer - mapped canvas.set(x, y) if not self.fill: continue if lx == -1 and ly == -1: lx, ly = x, y continue # Draw a line between the new points and the last point. # It just makes it look better. for nx, ny in line(lx, ly, x, y): canvas.set(nx, ny) lx, ly = x, y def draw(self, mx, my): # Just warning you, this code is absolute trash. if not any(map(lambda c: c["dirty"], self.canvases.values())): # Nothing dirty here, just skip. self.dirty = False return # TODO debugging trash #sf = "max_axes=%d max_point=%d max_points=%d fill=%s" #self.scr.addstr(1, 1, sf % (max_axes, max_point, max_points, self.fill)) # Draw axes self.axes.clear() self.axes.set(0, 0) # TODO: why do I need this hack? for y in range(self.edge_buffer, (my) * 4 - self.edge_buffer): # left axes self.axes.set(self.edge_buffer, y) for x in range(self.edge_buffer, (mx) * 2 - self.edge_buffer): # bottom axes # (my*4) is (my*8)/2 for the edge. self.axes.set(x, (my) * 4 - self.edge_buffer) # Render all the canvases for name in self.canvases.keys(): self._render_canvas(name, mx, my) # Draw all the canvases for name in self.canvases.keys(): self.draw_canvas(self.canvases[name]["canvas"], left=(self.data_buffer + self.edge_buffer) / 2, attr=self.canvases[name]["attr"]) # Draw the axes last. self.draw_canvas(self.axes, attr=curses.color_pair(0))
def view_protein(in_file, file_format=None, curr_model=1, chains=[], box_size=100.0): if box_size < 10.0 or box_size > 400.0: print("Box size must be between 10 and 400") return zoom_speed = 1.1 trans_speed = 1.0 rot_speed = 0.1 spin_speed = 0.01 action_count = 500 auto_spin = False cycle_models = False # Infer file format from extension if file_format is None: file_format = os.path.basename(in_file).rsplit(".", 1)[-1] # Handle stdin if in_file == "-": contents = sys.stdin.read() struct_file = StringIO(contents) try: # Redirect stdin from pipe back to terminal sys.stdin = open("/dev/tty", "r") except: print( "Piping structures not supported on this system (no /dev/tty)") return else: struct_file = in_file if file_format.lower() == "pdb": from Bio.PDB import PDBParser p = PDBParser() struc = p.get_structure("", struct_file) elif file_format.lower() in ("mmcif", "cif"): from Bio.PDB.MMCIFParser import MMCIFParser p = MMCIFParser() struc = p.get_structure("", struct_file) elif file_format.lower() == "mmtf": from Bio.PDB.mmtf import MMTFParser struc = MMTFParser.get_structure(struct_file) else: print("Unrecognised file format") return # Get backbone coordinates coords = [] connections = [] atom_counter, res_counter = 0, 0 chain_ids = [] for mi, model in enumerate(struc): model_coords = [] for chain in model: chain_id = chain.get_id() if len(chains) > 0 and chain_id not in chains: continue if mi == 0: chain_ids.append(chain_id) for res in chain: if mi == 0: res_counter += 1 res_n = res.get_id()[1] for atom in res: if mi == 0: atom_counter += 1 if atom.get_name() in ( "N", "CA", "C", # Protein "P", "O5'", "C5'", "C4'", "C3'", "O3'", # Nucleic acid ): if mi == 0 and len(model_coords) > 0: # Determine if the atom is connected to the previous atom connections.append(chain_id == last_chain_id and (res_n == (last_res_n + 1) or res_n == last_res_n)) model_coords.append(atom.get_coord()) last_chain_id, last_res_n = chain_id, res_n model_coords = np.array(model_coords) if mi == 0: if model_coords.shape[0] == 0: print("Nothing to show") return coords_mean = model_coords.mean(0) model_coords -= coords_mean # Center on origin of first model coords.append(model_coords) coords = np.array(coords) if curr_model > len(struc): print("Can't find that model") return info_str = "{} with {} models, {} chains ({}), {} residues, {} atoms".format( os.path.basename(in_file), len(struc), len(chain_ids), "".join(chain_ids), res_counter, atom_counter) # Make square bounding box of a set size and determine zoom x_min, x_max = float(coords[curr_model - 1, :, 0].min()), float(coords[curr_model - 1, :, 0].max()) y_min, y_max = float(coords[curr_model - 1, :, 1].min()), float(coords[curr_model - 1, :, 1].max()) x_diff, y_diff = x_max - x_min, y_max - y_min box_bound = float(np.max([x_diff, y_diff])) + 2.0 zoom = box_size / box_bound x_min = zoom * (x_min - (box_bound - x_diff) / 2.0) x_max = zoom * (x_max + (box_bound - x_diff) / 2.0) y_min = zoom * (y_min - (box_bound - y_diff) / 2.0) y_max = zoom * (y_max + (box_bound - y_diff) / 2.0) # See https://stackoverflow.com/questions/13207678/whats-the-simplest-way-of-detecting-keyboard-input-in-python-from-the-terminal/13207724 fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) canvas = Canvas() trans_x, trans_y = 0.0, 0.0 rot_x, rot_y = 0.0, 0.0 try: while True: os.system("clear") points = [] for x_start, y_start, x_end, y_end in ( (x_min, y_min, x_max, y_min), (x_max, y_min, x_max, y_max), (x_max, y_max, x_min, y_max), (x_min, y_max, x_min, y_min), ): for x, y in line(x_start, y_start, x_end, y_end): points.append([x, y]) rot_mat_x = np.array([ [1.0, 0.0, 0.0], [0.0, np.cos(rot_x), -np.sin(rot_x)], [0.0, np.sin(rot_x), np.cos(rot_x)], ], dtype=np.float32) rot_mat_y = np.array([ [np.cos(rot_y), 0.0, np.sin(rot_y)], [0.0, 1.0, 0.0], [-np.sin(rot_y), 0.0, np.cos(rot_y)], ], dtype=np.float32) trans_coords = coords[curr_model - 1] + np.array( [trans_x, trans_y, 0.0], dtype=np.float32) zoom_rot_coords = zoom * np.matmul( rot_mat_y, np.matmul(rot_mat_x, trans_coords.T)).T for i in range(coords.shape[1] - 1): if connections[i]: x_start, x_end = float(zoom_rot_coords[i, 0]), float( zoom_rot_coords[i + 1, 0]) y_start, y_end = float(zoom_rot_coords[i, 1]), float( zoom_rot_coords[i + 1, 1]) if x_min < x_start < x_max and x_min < x_end < x_max and y_min < y_start < y_max and y_min < y_end < y_max: for x, y in line(x_start, y_start, x_end, y_end): points.append([x, y]) print(info_str) print( "W/A/S/D rotates, T/F/G/H moves, I/O zooms, U spins, P cycles models, Q quits" ) canvas.clear() for x, y in points: canvas.set(x, y) print(canvas.frame()) counter = 0 while True: if auto_spin or cycle_models: counter += 1 if counter == action_count: if auto_spin: rot_y += spin_speed if cycle_models: curr_model += 1 if curr_model > len(struc): curr_model = 1 break try: k = sys.stdin.read(1) if k: if k.upper() == "O": zoom /= zoom_speed elif k.upper() == "I": zoom *= zoom_speed elif k.upper() == "F": trans_x -= trans_speed elif k.upper() == "H": trans_x += trans_speed elif k.upper() == "G": trans_y -= trans_speed elif k.upper() == "T": trans_y += trans_speed elif k.upper() == "S": rot_x -= rot_speed elif k.upper() == "W": rot_x += rot_speed elif k.upper() == "A": rot_y -= rot_speed elif k.upper() == "D": rot_y += rot_speed elif k.upper() == "U": auto_spin = not auto_spin elif k.upper() == "P" and len(struc) > 1: cycle_models = not cycle_models elif k.upper() == "Q": return break except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
def test_clear(self): c = Canvas() c.set(1, 1) c.clear() self.assertEqual(c.chars, dict())
########NEW FILE######## __FILENAME__ = basic from __future__ import print_function from drawille import Canvas import math s = Canvas() for x in range(1800): s.set(x/10, math.sin(math.radians(x)) * 10) print(s.frame()) s.clear() for x in range(0, 1800, 10): s.set(x/10, 10 + math.sin(math.radians(x)) * 10) s.set(x/10, 10 + math.cos(math.radians(x)) * 10) print(s.frame()) s.clear() for x in range(0, 3600, 20): s.set(x/20, 4 + math.sin(math.radians(x)) * 4) print(s.frame()) s.clear()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from drawille import Canvas import math s = Canvas() for x in range(1800): s.set(x / 10, math.sin(math.radians(x)) * 10) print(s.frame()) s.clear() for x in range(0, 1800, 10): s.set(x / 10, 10 + math.sin(math.radians(x)) * 10) s.set(x / 10, 10 + math.cos(math.radians(x)) * 10) print(s.frame()) s.clear() for x in range(0, 3600, 20): s.set(x / 20, 4 + math.sin(math.radians(x)) * 4) print(s.frame()) s.clear()
from drawille import Canvas, line, Turtle, polygon from colorama import * from math import sin, radians init() c = Canvas() c.clear() pnts = [] t = Turtle() tpos = [] class plot: def lnres(inres): res = inres def printc(color): for x,y in pnts: c.set(x,y) if color == 'green': print(Fore.GREEN+c.frame()) if color == 'red': print(Fore.RED+c.frame()) if color == 'yellow': print(Fore.YELLOW+c.frame()) if color == 'blue': print(Fore.BLUE+c.frame()) if color == 'cyan': print(Fore.CYAN+c.frame())
class GameOfLife: def __init__(self, rows, cols): self.rows = rows self.cols = cols self.can = Canvas() self.state = [[bool(random.getrandbits(1)) for y in range(rows)] for x in range(cols)] def tick(self): next_gen = [[False for y in range(self.rows)] for x in range(self.cols)] for y in range(self.rows): for x in range(self.cols): nburs = self._ncount(x, y) if self.state[x][y]: # Alive if nburs > 1 and nburs < 4: self.can.set(x,y) next_gen[x][y] = True else: next_gen[x][y] = False else: # Dead if nburs == 3: self.can.set(x,y) next_gen[x][y] = True else: next_gen[x][y] = False self.state = next_gen def draw(self): f = self.can.frame(0,0,self.cols,self.rows) stdscr.addstr(0, 0, '{0}\n'.format(f)) self.can.clear() def put(self, matrix, x, y): for mx in range(len(matrix)): for my in range(len(matrix[0])): self.state[min(x+my,self.cols-1)][min(y+mx,self.rows-1)] = matrix[mx][my] def _ncount(self, x, y): nburs = 0 # Left if x > 0: if self.state[x-1][y]: nburs += 1 # Top if y > 0: if self.state[x-1][y-1]: nburs += 1 # Bottom if y < self.rows-1: if self.state[x-1][y+1]: nburs += 1 # Right if x < self.cols-1: if self.state[x+1][y]: nburs += 1 # Top if y > 0: if self.state[x+1][y-1]: nburs += 1 # Bottom if y < self.rows-1: if self.state[x+1][y+1]: nburs += 1 # Top if y > 0: if self.state[x][y-1]: nburs += 1 # Bottom if y < self.rows-1: if self.state[x][y+1]: nburs += 1 return nburs
def view(in_file, file_format=None, curr_model=1, chains=[], box_size=100.0): if box_size < 10.0 or box_size > 400.0: print("Box size must be between 10 and 400") return auto_spin = False cycle_models = False coords, info = read_inputs(in_file, file_format, curr_model, chains) if coords is None: return # Build help strings info_str = ( f"{os.path.basename(in_file)} with {info['num_struc']} models, " f"{len(info['chain_ids'])} chains ({''.join(info['chain_ids'])}) " f"{info['res_counter']} residues, {info['atom_counter']} atoms.") help_str = "W/A/S/D rotates, T/F/G/H moves, I/O zooms, U spins, P cycles models, Q quits" # Make square bounding box of a set size and determine zoom x_min, x_max = float(coords[curr_model - 1, :, 0].min()), float(coords[curr_model - 1, :, 0].max()) y_min, y_max = float(coords[curr_model - 1, :, 1].min()), float(coords[curr_model - 1, :, 1].max()) x_diff, y_diff = x_max - x_min, y_max - y_min box_bound = float(np.max([x_diff, y_diff])) + 2.0 zoom = box_size / box_bound x_min = zoom * (x_min - (box_bound - x_diff) / 2.0) x_max = zoom * (x_max + (box_bound - x_diff) / 2.0) y_min = zoom * (y_min - (box_bound - y_diff) / 2.0) y_max = zoom * (y_max + (box_bound - y_diff) / 2.0) # Set up curses screen # https://docs.python.org/3/howto/curses.html stdscr = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(False) stdscr.keypad(True) # Respond to keypresses w/o Enter stdscr.nodelay(True) # Don't block while waiting for keypress # Divide curses screen into windows window_info = stdscr.subwin( 2, curses.COLS - 1, # height, width 0, 0) # begin_y, begin_x window_structure = stdscr.subwin( curses.LINES - 1 - 2, curses.COLS - 1, # height, width 2, 0) # begin_y, begin_x # Print help strings (only need to do this once) window_info.addnstr(0, 0, info_str, window_info.getmaxyx()[1] - 1) window_info.addnstr(1, 0, help_str, window_info.getmaxyx()[1] - 1) window_info.refresh() canvas = Canvas() trans_x, trans_y = 0.0, 0.0 rot_x, rot_y = 0.0, 0.0 try: points = [] do_update = True while True: curses.napms(50) # Delay a short while # Re-draw structure if needed if do_update: points = [] for x_start, y_start, x_end, y_end in ( (x_min, y_min, x_max, y_min), (x_max, y_min, x_max, y_max), (x_max, y_max, x_min, y_max), (x_min, y_max, x_min, y_min), ): for x, y in line(x_start, y_start, x_end, y_end): points.append([x, y]) rot_mat_x = np.array([ [1.0, 0.0, 0.0], [0.0, np.cos(rot_x), -np.sin(rot_x)], [0.0, np.sin(rot_x), np.cos(rot_x)], ], dtype=np.float32) rot_mat_y = np.array([ [np.cos(rot_y), 0.0, np.sin(rot_y)], [0.0, 1.0, 0.0], [-np.sin(rot_y), 0.0, np.cos(rot_y)], ], dtype=np.float32) trans_coords = coords[curr_model - 1] + np.array( [trans_x, trans_y, 0.0], dtype=np.float32) zoom_rot_coords = zoom * np.matmul( rot_mat_y, np.matmul(rot_mat_x, trans_coords.T)).T for i in range(coords.shape[1] - 1): if not info['connections'][i]: continue x_start, x_end = float(zoom_rot_coords[i, 0]), float( zoom_rot_coords[i + 1, 0]) y_start, y_end = float(zoom_rot_coords[i, 1]), float( zoom_rot_coords[i + 1, 1]) # Check if the bond fits in the box if x_min < x_start < x_max and x_min < x_end < x_max and y_min < y_start < y_max and y_min < y_end < y_max: for x, y in line(x_start, y_start, x_end, y_end): points.append([x, y]) # Update displayed structure canvas.clear() for x, y in points: canvas.set(x, y) window_structure.addstr(0, 0, canvas.frame()) window_structure.refresh() do_update = False # Prepare rotation/model selection for next time if auto_spin: rot_y += spin_speed do_update = True if cycle_models: curr_model += 1 if curr_model > len(coords): curr_model = 1 do_update = True # Handle keypresses try: c = stdscr.getch() if c != curses.ERR: do_update = True if c in (ord("o"), ord("O")): zoom /= zoom_speed elif c in (ord("i"), ord("I")): zoom *= zoom_speed elif c in (ord("f"), ord("F")): trans_x -= trans_speed elif c in (ord("h"), ord("H")): trans_x += trans_speed elif c in (ord("g"), ord("G")): trans_y -= trans_speed elif c in (ord("t"), ord("T")): trans_y += trans_speed elif c in (ord("s"), ord("S")): rot_x -= rot_speed elif c in (ord("w"), ord("W")): rot_x += rot_speed elif c in (ord("a"), ord("A")): rot_y -= rot_speed elif c in (ord("d"), ord("D")): rot_y += rot_speed elif c in (ord("u"), ord("U")): auto_spin = not auto_spin elif c in (ord("p"), ord("P")) and len(coords) > 1: cycle_models = not cycle_models elif c in (ord("q"), ord("Q")): return except IOError: pass except KeyboardInterrupt: # If user presses Ctrl+C, pretend as if they pressed q. return finally: # Teardown curses interface curses.nocbreak() curses.echo() curses.curs_set(True) stdscr.keypad(False) curses.endwin() # Make sure last view stays on screen print(info_str) print(help_str) print(canvas.frame())
from __future__ import print_function from drawille import Canvas import math s = Canvas() for x in range(1800): s.set((x/10, math.sin(math.radians(x)) * 10)) print(s.frame()) s.clear() for x in range(0, 1800, 10): s.set((x/10, 10 + math.sin(math.radians(x)) * 10)) s.set((x/10, 10 + math.cos(math.radians(x)) * 10)) print(s.frame()) s.clear() for x in range(0, 3600, 20): s.set((x/20, 4 + math.sin(math.radians(x)) * 4)) print(s.frame()) s.clear() for x in range(0, 360, 4): s.set((x/4, 30 + math.sin(math.radians(x)) * 30))
from drawille import Canvas from timeit import timeit canvas = Canvas() frames = 1000 * 10 sizes = ((0, 0), (10, 10), (20, 20), (20, 40), (40, 20), (40, 40), (100, 100)) for x, y in sizes: canvas.set(0, 0) for i in range(y): canvas.set(x, i) r = timeit(canvas.frame, number=frames) print('{0}x{1}\t{2}'.format(x, y, r)) canvas.clear()
#!/usr/bin/env python # -*- coding: utf-8 -*- from drawille import Canvas from timeit import timeit c = Canvas() frames = 1000 * 10 sizes = ((0, 0), (10, 10), (20, 20), (20, 40), (40, 20), (40, 40), (100, 100)) for x, y in sizes: c.set(0, 0) for i in range(y): c.set(x, i) r = timeit(c.frame, number=frames) print('{0}x{1}\t{2}'.format(x, y, r)) c.clear()