def draw_keyboard(keyboard_or_index: Union[int, Keyboard]) -> draw.Group: keyboard: Keyboard = keyboards[keyboard_or_index] if isinstance( keyboard_or_index, int) else keyboard_or_index outlines = draw.Group( transform=f"translate({-keyboard.left},{-keyboard.top})") chars = draw.Group(transform="scale(1,-1)") for key in keyboard.values(): outlines.append( draw.Rectangle(key.x, key.y, key.width, key.height, fill='transparent', stroke_width=5, stroke='blue')) if key.code > 0: chars.append( draw.Text(key.char, fontSize=25, x=key.x + key.width / 2, y=-key.y - key.height / 2, center=True)) outlines.append(chars) return outlines
def draw_whole_frame(f1, f2, background='white', extra_elements=()): d = draw.Drawing(10, 4, origin=(-5, -1.5)) d.setRenderSize(624 * 2) if background: d.append(draw.Rectangle(-100, -100, 200, 200, fill=background)) d.append(draw.Group([f1.elements[-1]], transform='translate(-2.5)')) d.append(draw.Group([f2.elements[-1]], transform='translate(2.5)')) d.extend(extra_elements) return d
def render_animation(name, func1, func2, circuit_qcircuit='', equation_latex='', save=False, fps=20, preview=True, **kwargs): with draw.animation.AnimationContext(animate_bloch.draw_frame, jupyter=preview, delay=0 ) as anim: state = animate_bloch.AnimState(anim, fps=fps) func1(state) frames1 = anim.frames with draw.animation.AnimationContext(animate_bloch.draw_frame, jupyter=preview, delay=0 ) as anim: state = animate_bloch.AnimState(anim, fps=fps) func2(state) frames2 = anim.frames g = draw.Group() # Equals sign g.append(draw.Rectangle(-0.4, 0.075, 0.8, 0.075, fill='#000')) g.append(draw.Rectangle(-0.4, -0.15, 0.8, 0.075, fill='#000')) if circuit_qcircuit: circuit_elem = latextools.render_qcircuit(circuit_qcircuit).as_svg() g.draw(circuit_elem, x=0, y=2, center=True, scale=0.04) if equation_latex: equation_elem = latextools.render_snippet( equation_latex, latextools.pkg.qcircuit).as_svg() g.draw(equation_elem, x=0, y=-0.8, center=True, scale=0.03) extra_elements = (g,) save_side_by_side(name, frames1, frames2, extra_elements=extra_elements, save=save, fps=fps, preview=preview, **kwargs)
def draw_line(self, dims, vals, grid_size=10, color='#ffffff'): anim = draw.Drawing(330, 120, origin=(0, 0)) for x in range(dims[0]): group = draw.Group() group.draw( draw.Rectangle( 100 * x + grid_size, # origin x coords grid_size, # origin y coords 100, # grid width 100, # grid height stroke_width=grid_size, # outline size stroke='black', # outline color fill=color)) # fill color string_output = str(vals[x]) font_size = 50 / len(string_output) + 25 group.draw( draw.Text( string_output, font_size, 100 * x + grid_size + font_size / 3 + 2 * len(string_output), # origin x coords grid_size + 2250 / (font_size + 20), # origin y coords center=0)) anim.append(group) return anim
def __init__(self, n_qubits, init_state=None, w_time = 120, h_state = 40, font = 12, gate_font = 16, ws_label = 6, arrow_space = 1): if arrow_space > ws_label/2: arrow_space = ws_label/2 self.w_time = w_time self.h_state = h_state self.font = font self.gate_font = gate_font self.w_label = self.font * ws_label self.arrow_off = self.w_label/2 * arrow_space self.d = draw.Group() self.arrows = {} self.possible_states = [ ''.join(map(str, qs[::-1])) for qs in itertools.product(range(2), repeat=n_qubits) ] self.num_states = len(self.possible_states) if init_state is None: init_state = {'0'*n_qubits: 1} self.state_sequence = [init_state] self.draw_states()
def __init__(self): """반지름이 1인 원을 생성하고, group하나를 만든다.""" self.image_size = 500 self.d = draw.Drawing(2, 2, origin='center') # viewbox(-1, -1, 2, 2) self.d.setRenderSize(self.image_size) self.d.append(draw.Circle(0, 0, 1, fill='orange')) group = draw.Group() self.d.append(group)
def group_with_word(frame, word, i): group = draw.Group() group.append(frame) group.append( draw.Text(str(i) + ': ' + word, fontSize=40, x=10, y=-40, transform='scale(1, -1)')) return group
def draw_frame(*args, background='white', **kwargs): d = draw.Drawing(5, 3, origin='center') d.setRenderSize(624) if background: d.append(draw.Rectangle(-100, -100, 200, 200, fill=background)) g = draw.Group() draw_bloch_sphere(g, background=None, *args, **kwargs) d.append(g) return d
def to_svg(elements): keyboard_index = 0 keyboard = keyboards[keyboard_index] width, height = keyboard.left + keyboard.width, keyboard.top + keyboard.height root = draw.Group(transform=f'scale(1,-1)') root.append(draw_keyboard(keyboard_index)) root.extend(elements) svg = draw.Drawing(width, height, origin=(0, -height)) svg.append(root) return svg
def draw(self, x=0, y=0, xscale=1.0): h = self.h #assert isinstance(x, int) and isinstance(y, int) g = draw.Group(transform="translate({} {})".format(x, y)) if self.join: start = min([t.a for t in self.tracks]) * xscale end = max([t.b for t in self.tracks]) * xscale g.append(draw.Lines(start, h / 2, end, h / 2, stroke='lightgrey')) for track in self.tracks: g.append(track.draw(xscale=xscale)) return g
def draw(self, x=0, y=0, xscale=1.0): h = self.h a = self.a * xscale b = self.b * xscale x = x * xscale #assert isinstance(x, float) and isinstance(y, float) d = draw.Group(transform="translate({} {})".format(x, y)) d.append( draw.Rectangle(a, 0, b - a, h, fill=self.color, stroke=self.color)) if 'f' in self.direction: d.append( draw.Lines(b, 0, b + 5, (h / 2), b, h, fill=self.color, stroke=self.color)) if 'r' in self.direction: d.append( draw.Lines(a, 0, a - 5, (h / 2), a, h, fill=self.color, stroke=self.color)) for r_a, r_b, color in self.regions: r_a = r_a * xscale r_b = r_b * xscale d.append( draw.Rectangle(r_a, 0, r_b - r_a, h, fill=color, stroke=color)) for tick in self.ticks: tick = tick * xscale d.append(draw.Lines(tick, 0, tick, h, stroke='red')) if self.label: label = self.label font_size = 10 offset = h + font_size if isinstance(self.label, Label): d.append(label.draw(x=(b + a) / 2)) elif isinstance(self.label, str): d.append(Label(0, self.label).draw(x=(b + a) / 2)) return d
def draw(self, x=None, y=0, xscale=1.0): # font_family = self.label.font_family if self.offset is not None: offset = self.offset if x is None: x = self.w * xscale d = draw.Group(transform="translate({} {})".format(x, y)) d.append( draw.Text(self.text, self.font_size, self.w, (self.font_size / 2 + offset), font_family='monospace', center=True)) return d
def draw(self, x=0, y=0, xscale=1.0): h = self.h a = self.x * xscale b = (self.x + self.w) * xscale x = x * xscale r = h / 2 font_size = h * 0.55 arrow_size = 7 if self.direction >= 0: line_start = a arrow_end = b arrow_start = max(arrow_end - arrow_size, line_start) else: line_start = b arrow_end = a arrow_start = min(arrow_end + arrow_size, line_start) centre = (a + b) / 2 arrow_y = h / 2 + self.elevation * r group = draw.Group(transform="translate({} {})".format(x, y)) group.append( draw.Line(line_start, arrow_y, arrow_start, arrow_y, stroke='black')) group.append( draw.Circle(centre, h / 2, r, fill='ivory', stroke='black')) group.append( draw.Lines(arrow_end, arrow_y, arrow_start, arrow_y + arrow_size / 2, arrow_start, arrow_y - arrow_size / 2, arrow_end, arrow_y, fill='black')) group.append( draw.Text(self.label, font_size, centre, h / 2, text_anchor='middle', dy="0.35em")) return group
def draw(self, x=0, y=0, xscale=1.0): d = draw.Group(transform="translate({} {})".format(x, y)) d.append(self.t1.draw(xscale=xscale)) d.append(self.t2.draw(y=self.t1.h + self.gap, xscale=xscale)) for bottom, top in self.connections: bottom = bottom * xscale top = top * xscale d.append(draw.Lines(bottom, 0, top, -self.gap, stroke=self.color)) d.append( draw.Lines(bottom, self.t1.h, bottom, 0, stroke=self.color)) d.append( draw.Lines(top, -self.gap, top, -(self.gap + self.t2.h), stroke=self.color)) return d
def draw(self, x=0, y=0, xscale=1.0): #assert isinstance(x, int) and isinstance(y, int) h = self.h a = self.a * xscale b = self.b * xscale x = x * xscale d = draw.Group(transform="translate({} {})".format(x, y)) yscale = self.h / max(self.ys) for i, v in enumerate(self.ys): d.append( draw.Rectangle( a + (i * xscale), 0, xscale, v * yscale, fill=self.color, fill_opacity=self.opacity)) #, stroke=self.color)) return d
def draw(self, x=0, y=0, xscale=1.0): a = self.a * xscale x = x * xscale d = draw.Group(transform="translate({} {})".format(x, y)) yscale = self.h / max(y for y, count in self.coverage_groups) pos = 0 for y, count in self.coverage_groups: if y != 0: d.append( draw.Rectangle(a + (pos * xscale), self.h // 2 - 1, count * xscale, y * yscale, fill=self.get_color(y), fill_opacity=self.opacity, shape_rendering='crispEdges')) pos += count return d
#!/usr/bin/env python3 import drawSvg as draw import latextools from bloch_sphere.animate_bloch import do_or_save_animation, AnimState from bloch_sphere.animate_bloch_compare import render_animation # Add some extra labels zero_ket = draw.Group() zero_ket.draw(latextools.render_snippet('$\ket{0}$', latextools.pkg.qcircuit), x=0, y=0, center=True, scale=0.015) one_ket = draw.Group() one_ket.draw(latextools.render_snippet('$\ket{1}$', latextools.pkg.qcircuit), x=0, y=0, center=True, scale=0.015) zero_ket_inner = draw.Use(zero_ket, 0, 0, transform='scale(0.75)') one_ket_inner = draw.Use(one_ket, 0, 0, transform='scale(0.75)') w = 624 * 2 # Output width fps = 20 draw_args = dict( w=w / 2, outer_labels=[ [(0, 0, 1), (-0.15, 0.13), zero_ket], [(0, 0, -1), (0.15, -0.13), one_ket], ],
fill_color = "none" stroke_color = "black" d = draw.Drawing(2**(1 / 4) * pixels_per_m, 1 / (2**(1 / 4)) * pixels_per_m, origin="center", displayInline=False) y = -64 for i in [1, 2, 3, 5, 7, 11]: x = 0 length = string_length / i midpoint = length / 2 deflection = (string_length / i)**0.5 / 2 string = draw.Group() for j in range(i): p = draw.Path(stroke_width=stroke_width, stroke=stroke_color, fill=fill_color) for k in list(range(4)): p.M(x, y) p.q(midpoint, k * deflection, length, 0) p.M(x + length, y) p.q(-midpoint, -k * deflection, -length, 0) string.append(p) x += length d.append(string) y -= deflection * 4
def draw_catdog(name, param): """ Draws a cat/dog and saves it as an svg Parameters ---------- name : string Filename to save catdog as param : dictionary (keys: variables list) Variable values for the structure of the face """ full_dwg = draw.Drawing(800, 600) dwg = draw.Group() full_dwg.append(dwg) width = 173*(param["face_aspect_ratio"])**0.5 height = 173/(param["face_aspect_ratio"])**0.5 cx = 800/2 cy = 600/2 #Ears ear_angle = param["ear_angle"] ear_tip_angle = param["ear_tip_angle"] ear_length = param["ear_length"] ear_orientation = param["ear_orientation"] ear_point = param["ear_point"] eye_height = param["eye_height"] eye_width = eye_height*param["eye_aspect_ratio"] eye_distance = param["eye_distance"] nose_size = param["nose_size"] fur_color = "hsl(%i, %i%%, %i%%)" % (45,param["fur_saturation"],param["fur_lightness"]) dist_to_tip = r_ellipse(ear_angle,width,height)+ear_length right_tip = dir_point((cx,cy),dist_to_tip,ear_angle) bottom_right = dir_point(right_tip,ear_length*2.2,180+ear_angle+ear_tip_angle*ear_orientation) bottom_right_ctrl = dir_point(bottom_right,ear_length*2.2-ear_point,ear_angle+ear_tip_angle*ear_orientation) top_right = dir_point(right_tip,ear_length*2.2,180+ear_angle-ear_tip_angle*(1-ear_orientation)) top_right_ctrl = dir_point(top_right,ear_length*2.2-ear_point,ear_angle-ear_tip_angle*(1-ear_orientation)) top_left, top_left_ctrl, left_tip, bottom_left_ctrl, bottom_left = mirror([top_right, top_right_ctrl, right_tip, bottom_right_ctrl, bottom_right],cx) left_ear = draw.Path(stroke_width = 1, stroke='black', fill = fur_color) left_ear.M(*bottom_left) left_ear.L(*bottom_left_ctrl) left_ear.A(ear_point*.8, ear_point*.8, 0, False, True, *top_left_ctrl) left_ear.L(*top_left) right_ear = draw.Path(stroke_width = 1, stroke='black', fill = fur_color) right_ear.M(*bottom_right) right_ear.L(*bottom_right_ctrl) right_ear.A(ear_point*.8, ear_point*.8, 0, False, False, *top_right_ctrl) right_ear.L(*top_right) dwg.draw(left_ear) dwg.draw(right_ear) #Face face = ellipse(cx, cy, width, height, stroke_width = 1, stroke='black', fill = fur_color) dwg.draw(face) #Eyes left_eye = ellipse(cx-eye_distance, cy+height/4, eye_width, eye_height, stroke_width = 1, stroke='black', fill = "black") right_eye = ellipse(cx+eye_distance, cy+height/4, eye_width, eye_height, stroke_width = 1, stroke='black', fill = "black") dwg.draw(left_eye) dwg.draw(right_eye) #Nose dwg.draw(draw.Lines(cx-nose_size, cy+nose_size/3, cx+nose_size, cy+nose_size/3, cx,cy-nose_size, close=True, stroke_width = 1, stroke='black', fill = "black")) #Snout dwg.draw(draw.Line(cx,cy-nose_size,cx,cy-nose_size*2.5, stroke_width = 2, stroke='black', fill = "black")) #Mouth mouth = draw.Path(fill = "none", stroke_width = 2, stroke = 'black') mouth.M(cx-nose_size*2,cy-nose_size*2.5-4) mouth.A(nose_size*2, nose_size*2, 30, False, False, cx, cy-nose_size*2.5) mouth.A(nose_size*2, nose_size*2, 150, False, False, cx+nose_size*2, cy-nose_size*2.5-4) dwg.draw(mouth) #Whiskers whisker_length = param["whisker_length"] whiskers = [((cx-34,cy-nose_size-10),195), ((cx-40,cy-nose_size-4),185), ((cx-34,cy-nose_size+2),175), ((cx+34,cy-nose_size-10),345), ((cx+40,cy-nose_size-4),355), ((cx+34,cy-nose_size+2),5) ] for whisker in whiskers: dwg.draw(draw.Line(*whisker[0],*dir_point(whisker[0],whisker_length,whisker[1]), stroke_width = 1, stroke='black', fill = "black")) full_dwg.saveSvg(name)
def toSVG(read_path, path, path2): pth = read_path.split("/") for i in pth[-1]: if i == '.': dotindx = pth[-1].index(".", 0) pth[-1] = pth[-1][0:dotindx] ############ #################### # parsing the def file def_parser = DefParser(read_path) def_parser.parse() macro = "" for key, val in def_parser.components.comp_dict.items(): x = str(val).split() macro = macro + " " + x[3] + " " + str(x[5]).strip("[,") + " " + str( x[6]).strip("]") + " " + str(x[7]) nets = [] for key, val in def_parser.nets.net_dict.items( ): # extracting nets information and putting in list nets += str(val).split() # print(nets) def_scale = def_parser.scale # scalling the def # print("DEF scale: ",def_scale) MACRO = macro.split() # DEF INFO CARRIER # print(MACRO) # getting the die area of the circuit z = def_parser.diearea pos = re.split('[, ()]', str(z)) # diearea coordinates in string x1 = pos[1] # diearea coordinates in string x2 = pos[3] # diearea coordinates in string x3 = pos[7] # diearea coordinates in string x4 = pos[9] dx0 = int(x1) # diearea coordinates in int dy0 = int(x2) # diearea coordinates in int dx1 = int(x3) # diearea coordinates in int dy1 = int(x4) # diearea coordinates in int width = int(x3) - int( x1) # getting the width of the are lower left - upper right height = int(x4) - int( x2) # getting the hihgt of the are lower left - upper right clip = draw.ClipPath() d = draw.Drawing(width, height, origin=(0, -height), id="svgContainer") # drawing of diearea d.append( draw.Rectangle( dx0, -(height + dy0), width, height, fill='#D8FEEA', fill_opacity=0.4, )) # parsing the lef file lef_parser = LefParser(path) # getting the lef file path lef_parser.parse() x = "" for i in lef: # putting lef infrmation in list x = x + i + " " lef_info = x.split() # print(lef_info) k = 0 # g = "" counter = 0 for i in range(0, len(MACRO)): # for loop for drawing of components if k < len(MACRO): # if we still have macro we keep drawing g = draw.Group() for j in range( 0, len(lef_info), 2 ): # loop on th size of the block in the LEF file on details of a macro if MACRO[k] == lef_info[j]: # Matching macros from LEF / DEF counter = counter + 1 # print(MACRO[k]) opacity = 0.6 # opacity of all rectangles, opacity only changes if OBS xplacement = float( MACRO[k + 1] ) # extracting and storing placement and orientation of macro from DEF yplacement = float(MACRO[k + 2]) orientation = MACRO[k + 3] endindx = lef_info.index("END", j) # Extracting macros's details for m in range(j, endindx): if (lef_info[m] == "Size"): swidth = float( lef_info[m + 1]) * 100 # width size of macro sheight = float(lef_info[ m + 2]) * 100 # height width size of macrp d.append( draw.Rectangle(xplacement - dx0, -(height - (yplacement - dy0)), swidth, sheight, fill='#a877f2', stroke='#412f5c', stroke_width=10, fill_opacity=0.2, class_="cell", name=MACRO[k], id=MACRO[k] + "_c" + str(counter))) elif (lef_info[m] == "Layer:" or lef_info[m] == "Layer" or lef_info[m] == "LAYER"): # Layer met = lef_info[m + 1] if (lef_info[m + 1] == "metal1"): # COLOR CODE For each metal color = "#7D5AB1" elif (lef_info[m + 1] == "metal2"): # COLOR CODE For each meta2 color = "#8C8E8E" elif (lef_info[m + 1] == "metal3"): # COLOR CODE For each meta3 color = "#FF839D" elif (lef_info[m + 1] == "metal4"): # COLOR CODE For each meta4 color = "#83C9FF" elif (lef_info[m + 1] == "via1"): # COLOR CODE For each via1 color = "#83FFC3" elif (lef_info[m + 1] == "via2"): # COLOR CODE For each via2 color = "#FFD683" elif (lef_info[m + 1] == "via3"): # COLOR CODE For each via3 color = "#83FFE1" elif ((lef_info[m] == "PIN:")): # metal info met = lef_info[m + 1] # pin info pin = lef_info[m + 1] # PIN NAME elif ((lef_info[m] == "OBS" )): # setting different opacity for rectangles met = lef_info[m + 1] opacity = 0.6 elif ( (lef_info[m] == "RECT" )): # extracting dimensions of rectangles in LEF # x left x0 = float(lef_info[m + 1]) * 100 # y left y0 = float(lef_info[m + 2]) * 100 # x right x01 = float(lef_info[m + 3]) * 100 # y right y01 = float(lef_info[m + 4]) * 100 # width of the rects rwidth = x01 - x0 # width of rectangle # height of the rects rheight = y01 - y0 # height of rectangle if (orientation == "N"): g.append( draw.Rectangle(xplacement - dx0 + x0, -(height - (yplacement - dy0 + y0)), rwidth, rheight, fill=color, fill_opacity=opacity, class_=met)) g.append( draw.Text(pin, 20, xplacement - dx0 + x0, -(height - (yplacement - dy0 + y0)), centre='origin', class_=met)) elif (orientation == "FN"): FNx = x0 + ((swidth / 2 - x0) * 2) - rwidth g.append( draw.Rectangle(xplacement - dx0 + FNx, -(height - (yplacement - dy0 + y0)), rwidth, rheight, fill=color, fill_opacity=opacity, class_=met)) g.append( draw.Text(pin, 20, xplacement - dx0 + FNx, -(height - (yplacement - dy0 + y0)), centre='origin', class_=met)) elif (orientation == "FS"): FSy = y0 + ((sheight / 2 - y0) * 2) - rheight g.append( draw.Rectangle(xplacement - dx0 + x0, -(height - (yplacement - dy0 + FSy)), rwidth, rheight, fill=color, fill_opacity=opacity, class_=met)) g.append( draw.Text(pin, 20, xplacement - dx0 + x0, -(height - (yplacement - dy0 + FSy)), centre='origin', class_=met)) elif (orientation == "S"): Sx = x0 + ((swidth / 2 - x0) * 2) - rwidth Sy = y0 + ((sheight / 2 - y0) * 2) - rheight g.append( draw.Rectangle(xplacement - dx0 + Sx, -(height - (yplacement - dy0 + Sy)), rwidth, rheight, fill=color, fill_opacity=opacity, Class=met)) g.append( draw.Text(pin, 35, xplacement - dx0 + Sx, -(height - (yplacement - dy0 + Sy)), centre='origin', class_=met)) d.append(g) k = k + 4 nx = "" ny = "" for i in range(0, len(nets)): # for loop to draw vias if (nets[i] == "M2_M1" or nets[i] == "M3_M2" or nets[i] == "M4_M3"): ny = nets[i - 1] nx = nets[i - 2] nx = int(nx.strip("[],")) ny = int(ny.strip("[],")) opacity = 0.5 NETstartindx = lef_info.index(nets[i]) if (nets[i] == "M2_M1" or nets[i] == "M3_M2"): NETendindx = lef_info.index("VIA", NETstartindx) elif (nets[i] == "M4_M3"): NETendindx = lef_info.index("Macro", NETstartindx) for n in range(NETstartindx, NETendindx): if (lef_info[n] == "LAYER"): # Layer if (lef_info[n + 1] == "metal1"): color = "#7D5AB1" # COLOR CODE For each metal elif (lef_info[n + 1] == "metal2"): # COLOR CODE For each meta2 color = "#8C8E8E" elif (lef_info[n + 1] == "metal3"): # COLOR CODE For each meta3 color = "#FF839D" elif (lef_info[n + 1] == "metal4"): # COLOR CODE For each meta4 color = "#83C9FF" elif (lef_info[n + 1] == "via1"): # COLOR CODE For each via1 color = "#83FFC3" elif (lef_info[n + 1] == "via2"): # COLOR CODE For each via2 color = "#FFD683" elif (lef_info[n + 1] == "via3"): # COLOR CODE For each via3 color = "#83FFE1" elif ((lef_info[n] == "RECT" )): # extracting dimensions of rectangles in # x left x0 = float(lef_info[n + 1]) * 100 # y left y0 = float(lef_info[n + 2]) * 100 # xright x01 = float(lef_info[n + 3]) * 100 # y right y01 = float(lef_info[n + 4]) * 100 rwidth = x01 - x0 # width of rectangle rheight = y01 - y0 # height of rectangle d.append( draw.Rectangle(nx - dx0 + x0, -(height - (ny - dy0 + y0)), rwidth, rheight, fill=color, fill_opacity=opacity, class_=lef_info[n + 1])) i = 0 RouteEnd = 0 RouteStart = 0 print(nets) for i in range(0, len(nets)): # checking that am at metal components if (nets[i] == "NET_DEF:"): net_ident = nets[i + 1] #g = draw.Group(fill="Black", Class="net", id=net_ident) net_ident = net_ident.replace('<', '') net_ident = net_ident.replace('>', '') g = draw.Group() if (nets[i] == "metal1" or nets[i] == "metal2" or nets[i] == "metal3" or nets[i] == "metal4" or nets[i] == "via1" or nets[i] == "via2" or nets[i] == "via3"): RouteStart = i if (nets[i] == "metal1"): met = nets[i] color = "#7D5AB1" # COLOR CODE For each metal strokewidth = 0.6 * 100 # width of metal elif (nets[i] == "metal2"): # COLOR CODE For each meta2 met = nets[i] color = "#8C8E8E" # width of meta2 strokewidth = 0.6 * 100 elif (nets[i] == "metal3"): met = nets[i] # COLOR CODE For each meta3 color = "#FF839D" # width of meta3 strokewidth = 0.6 * 100 elif (nets[i] == "metal4"): met = nets[i] # COLOR CODE For each meta4 color = "#83C9FF" # width of meta4 strokewidth = 1.2 * 100 elif (nets[i] == "via1"): # COLOR CODE For each via1 met = nets[i] color = "#83FFC3" strokewidth = 0.6 * 100 elif (nets[i] == "via2"): # COLOR CODE For each via2 met = nets[i] color = "#FFD683" strokewidth = 0.6 * 100 elif (nets[i] == "via3"): met = nets[i] # COLOR CODE For each via3 color = "#83FFE1" strokewidth = 0.6 * 100 # print(RouteStart) for j in range(i + 1, len(nets)): if (nets[j] == "M2_M1" or nets[j] == "M3_M2" or nets[j] == "M4_M3" or nets[j] == "metal1" or nets[j] == "metal2" or nets[j] == "metal3" or nets[j] == "metal4" or nets[j] == ";"): RouteEnd = j # print(RouteEnd) break no_of_pairs = int((RouteEnd - RouteStart - 1) / 2) # number of pairs of coordinates (x,y) temp = RouteStart if ( no_of_pairs > 1 ): # if number of pairs=1 , then only via and it's already drawn in previous loop for k in range( 0, no_of_pairs - 1 ): # extracting placement of wires and drawing routing route_wirex0 = int(nets[temp + 1].strip("[],")) route_wirey0 = int(nets[temp + 2].strip("[],")) route_wirex1 = int(nets[temp + 3].strip("[],")) route_wirey1 = int(nets[temp + 4].strip("[],")) rw = route_wirex1 - route_wirex0 rh = route_wirey1 - route_wirey0 p = draw.Path(stroke_width=strokewidth, stroke=color, stroke_opacity=0.7, fill_opacity=0) # d.append(draw.Lines(route_wirex0,route_wirey1,stroke_width=strokewidth, stroke=color, stroke_opacity=0.7, fill_opacity=0)) p.M(route_wirex0 - dx0, -(height - (route_wirey0 - dy0))) # Start path at point p.l(rw, rh) # Draw line to g.append(p) d.append( draw.Rectangle(route_wirex0 - dx0, -(height - (route_wirey0 - dy0)), rh, strokewidth, fill=color, stroke_opacity=0.7, fill_opacity=0, class_=met)) #d.append(draw.Rectangle(route_wirex0 - dx0,-(height - (route_wirey0 - dy0)),abs(rw)+50 ,abs(rh)+50,stroke_width=strokewidth, stroke="#FFF300", stroke_opacity=0, fill_opacity=0.5, class_="net",id=net_ident+"_net")) #d.append(draw.Lines(route_wirex0,route_wirey1,stroke_width=strokewidth, stroke=color, stroke_opacity=0.7, fill_opacity=0)) temp = temp + 2 d.append(g) pin_info = [] # Contains the needed details to draw the pins splt = "" for keys, val in def_parser.pins.pin_dict.items(): # print(keys) splt = str(val) # print(val) splt = splt.split() pin_info.append(splt[3]) pin_info.append(splt[9].strip("[],")) pin_info.append(splt[10].strip("[],")) pin_info.append(splt[11].strip("[],")) pin_info.append(splt[12].strip("[],")) pin_info.append(splt[13].strip("[],")) pin_info.append(splt[15].strip("[],")) pin_info.append(splt[16].strip("[],")) pin_info.append(splt[17].strip("[],")) # print(pin_info) for b in range(0, len(pin_info)): if (pin_info[b] == "metal1" or pin_info[b] == "metal2" or pin_info[b] == "metal3" or pin_info[b] == "metal4"): pinx0 = int(pin_info[b + 1]) piny0 = int(pin_info[b + 2]) pinx1 = int(pin_info[b + 3]) piny1 = int(pin_info[b + 4]) pin_pos1 = int(pin_info[b + 5]) pin_pos2 = int(pin_info[b + 6]) pin_name = pin_info[b - 1] PINS = pin_name.replace('<', '') PINS = PINS.replace('>', '') d.append( draw.Rectangle(pin_pos1 - dx0, -(height - (pin_pos2 - dy0)), pinx1 - pinx0 + 200, piny1 - piny0 + 200, fill='#B1725A', fill_opacity=0.6, Class="PIN", id=PINS)) d.append( draw.Text(pin_name, 40, pin_pos1 - dx0, -(height - (pin_pos2 - dy0 - 20)), centre='origin', Class="PINNames")) #drc_parser=[] #read_path = input("Enter DRC file path: ") #ENTER DRC FILE PATH HERE! drc = DRC_parser(path2) drc.parse() # x = drc_parser.DRC_parser() SVG = str(pth[-1]) + ".html" d.saveSvg("templates/" + SVG) # draw svg image and give it a file name with open('htmlHead.txt', 'r') as file: Head = file.read() with open('htmlTail.txt', 'r') as file: Tail = file.read() with open("templates/" + SVG, 'r+') as f: content = f.read() contentX = content.replace(str(height), "950", 1) contentX = contentX.replace(str(width), "950", 1) f.seek(0, 0) f.write(Head + contentX + Tail) return SVG
def draw_bloch_sphere(d, inner_proj=euclid3d.identity(3), label='', axis=None, rot_proj=None, rot_deg=180, outer_labels=(), inner_labels=(), extra_opacity=1, inner_opacity=1, background='white'): spin = euclid3d.rotation(3, 0, 2, 2 * np.pi / 16 / 2 * 1.001) tilt = euclid3d.rotation(3, 1, 2, np.pi / 8) trans = tilt @ spin @ euclid3d.axis_swap((1, 2, 0)) proj = euclid3d.perspective3d(np.pi / 8, view_size=4) @ trans zx = euclid3d.axis_swap((2, 0, 1)) xy = euclid3d.identity(3) yz = euclid3d.axis_swap((1, 2, 0)) proj_zx = proj @ zx proj_xy = proj @ xy proj_yz = proj @ yz if background: d.append(draw.Rectangle(-100, -100, 200, 200, fill=background)) def draw_band(proj, trans, r_outer=1, r_inner=0.9, color='black', z_mul=1, opacity=1, divs=4, d=d, **kwargs): color = (color * divs)[:divs] if isinstance(color, list) else [color] * divs points = np.array([[-1, -1, 1, 1], [-1, 1, 1, -1]]).T sqr12 = 0.5**0.5 overlap = np.pi / 500 * (divs != 4) start_end_points = [ np.array([[ np.cos(pr - 2 * np.pi / divs - overlap), np.sin(pr - 2 * np.pi / divs - overlap) ], [np.cos(pr + overlap), np.sin(pr + overlap)], [np.cos(pr - np.pi / divs), np.sin(pr - np.pi / divs)]]) for pr in np.linspace(0, 2 * np.pi, num=divs, endpoint=False) ] for i in range(divs): p = draw.Path(fill=color[i], stroke='none', stroke_width=0.002, **kwargs, opacity=opacity) z = trans.project_point( (r_inner + r_outer) / 2 * start_end_points[i][2])[2] e = shapes.EllipseArc.fromBoundingQuad( *proj.project_list(points * r_outer)[:, :2].flatten(), *proj.project_list(start_end_points[i] * r_outer)[:, :2].flatten(), ) if e: e.drawToPath(p) if r_inner > 0: e = shapes.EllipseArc.fromBoundingQuad( *proj.project_list(points * r_inner)[:, :2].flatten(), *proj.project_list(start_end_points[i] * r_inner)[:, :2].flatten(), ) if e: e.reversed().drawToPath(p, includeL=True) p.Z() d.append(p, z=z * z_mul) if False: d.draw(shapes.EllipseArc.fromBoundingQuad( *proj.project_list( (r_outer + r_inner) / 2 * points)[:, :2].flatten(), *proj.project_list((r_outer + r_inner) / 2 * start_end_points[i])[:, :2].flatten(), ), fill='none', stroke_width=0.02, stroke=color[i], **kwargs, z=z * z_mul) xycolors = ['#56e', '#239', '#56e', '#56e'] yzcolors = ['#e1e144', '#909022', '#e1e144', '#e1e144'] zxcolors = ['#9e2', '#6a1', '#9e2', '#9e2'] draw_band(proj_xy, trans @ xy, 1, 0.925, z_mul=10, color=xycolors) draw_band(proj_yz, trans @ yz, 1, 0.925, z_mul=10, color=yzcolors) draw_band(proj_zx, trans @ zx, 1, 0.925, z_mul=10, color=zxcolors) # Inner g = draw.Group(opacity=inner_opacity) z_center = trans.project_point((0, 0, 0))[2] d.append(g, z=z_center) inner_xy = proj @ inner_proj @ xy # Darker colors: #34b, #a8a833, #7b2 draw_band(proj @ inner_proj @ xy, trans @ inner_proj @ xy, 0.8, 0.7, color=xycolors, d=g) draw_band(proj @ inner_proj @ yz, trans @ inner_proj @ yz, 0.8, 0.7, color=yzcolors, divs=4, d=g) draw_band(proj @ inner_proj @ zx, trans @ inner_proj @ zx, 0.8, 0.7, color=zxcolors, divs=8 // 2, d=g) elevation_lines = False if elevation_lines: for elevation in (*np.linspace(0, np.pi / 2, 4, True)[1:-1], *np.linspace(-np.pi / 2, 0, 3, False)[1:]): y = 0.75 * np.sin(elevation) r = 0.75 * np.cos(elevation) draw_band(proj @ inner_proj @ xy @ euclid3d.translation((0, 0, y)), trans @ inner_proj @ xy @ euclid3d.translation( (0, 0, y)), r_outer=r - 0.01, r_inner=r + 0.01, color='#bbb', opacity=1, d=g) arrow = draw.Marker(-0.1, -0.5, 0.9, 0.5, scale=4, orient='auto') arrow.append( draw.Lines(-0.1, -0.5, -0.1, 0.5, 0.9, 0, fill='black', close=True)) g.append(draw.Line(*inner_xy.p2(-0.65, 0, 0), *inner_xy.p2(0.6, 0, 0), stroke='black', stroke_width=0.015, marker_end=arrow), z=z_center) g.append(draw.Line(*inner_xy.p2(0, -0.65, 0), *inner_xy.p2(0, 0.6, 0), stroke='black', stroke_width=0.015, marker_end=arrow), z=z_center) g.append(draw.Line(*inner_xy.p2(0, 0, -0.65), *inner_xy.p2(0, 0, 0.6), stroke='black', stroke_width=0.015, marker_end=arrow), z=z_center) for pt, (x_off, y_off), elem in inner_labels: x, y = (proj @ inner_proj).p2(*pt) g.append(draw.Use(elem, x + x_off, y + y_off), z=10000) # Outer arrows and text arrow = draw.Marker(-0.1, -0.5, 0.9, 0.5, scale=4, orient='auto') arrow.append( draw.Lines(-0.1, -0.5, -0.1, 0.5, 0.9, 0, fill='black', close=True)) d.append(draw.Line(*proj_xy.p2(1, 0, 0), *proj_xy.p2(1.2, 0, 0), stroke='black', stroke_width=0.02, marker_end=arrow), z=100) d.append(draw.Line(*proj_xy.p2(0, 1, 0), *proj_xy.p2(0, 1.2, 0), stroke='black', stroke_width=0.02, marker_end=arrow), z=100) d.append(draw.Line(*proj_xy.p2(0, 0, 1), *proj_xy.p2(0, 0, 1.2), stroke='black', stroke_width=0.02, marker_end=arrow), z=100) d.append( draw.Line(*proj_xy.p2(-1, 0, 0), *proj_xy.p2(-1.2, 0, 0), stroke='black', stroke_width=0.02)) d.append( draw.Line(*proj_xy.p2(0, -1, 0), *proj_xy.p2(0, -1.2, 0), stroke='black', stroke_width=0.02)) d.append( draw.Line(*proj_xy.p2(0, 0, -1), *proj_xy.p2(0, 0, -1.2), stroke='black', stroke_width=0.02)) d.append(draw.Text(['X'], 0.2, *proj_xy.p2(1.7, 0, 0), center=True, fill='black'), z=100) d.append(draw.Text(['Y'], 0.2, *proj_xy.p2(0, 1.35, 0), center=True, fill='black'), z=100) d.append(draw.Text(['Z'], 0.2, *proj_xy.p2(0, 0, 1.4), center=True, fill='black'), z=100) for pt, (x_off, y_off), elem in outer_labels: x, y = proj.p2(*pt) d.append(draw.Use(elem, x + x_off, y + y_off), z=10000) # Extra annotations #label='', axis=None, rot_proj=None if label: d.append( draw.Text([label], 0.4, -0.6, 1.2, center=True, fill='#c00', text_anchor='end', opacity=extra_opacity)) if axis: g = draw.Group(opacity=extra_opacity) axis = np.array(axis, dtype=float) axis_len = 1.18 axis /= np.linalg.norm(axis) arrow = draw.Marker(-0.1, -0.5, 0.9, 0.5, scale=3, orient='auto') arrow.append( draw.Lines(-0.1, -0.5, -0.1, 0.5, 0.9, 0, fill='#e00', close=True)) z = 100 #10 * proj_xy.project_point(axis*1)[2] g.append( draw.Line(*proj_xy.p2(0, 0, 0), *proj_xy.p2(*axis * axis_len), stroke='#e00', stroke_width=0.04, marker_end=arrow)) d.append(g, z=z) if rot_proj is not None: rot_proj = inner_proj @ rot_proj r_inner, r_outer = 0.1, 0.16 points = np.array([[-1, -1, 1, 1], [-1, 1, 1, -1]]).T start_end_points = np.array([[1, 0], [-1, 0], [0, 1]]) p = draw.Path(fill='orange', fill_rule='nonzero', opacity=extra_opacity) z = 9 * (trans @ rot_proj).project_point(start_end_points[2])[2] e = shapes.EllipseArc.fromBoundingQuad( *(proj @ rot_proj).project_list(points * r_outer)[:, :2].flatten(), *(proj @ rot_proj).project_list(start_end_points * r_outer)[:, :2].flatten(), ) if e: e.reversed().drawToPath(p) e = shapes.EllipseArc.fromBoundingQuad( *(proj @ rot_proj).project_list(points * r_inner)[:, :2].flatten(), *(proj @ rot_proj).project_list(start_end_points * r_inner)[:, :2].flatten(), ) if e: e.drawToPath(p, includeL=True) sa = 2.5 * (r_outer - r_inner) xa = -(r_inner + r_outer) / 2 p.L(*(proj @ rot_proj).p2(xa, 0.3 * sa)) p.L(*(proj @ rot_proj).p2(xa + 0.5 * sa, 0.3 * sa)) p.L(*(proj @ rot_proj).p2(xa, -0.7 * sa)) p.L(*(proj @ rot_proj).p2(xa - 0.5 * sa, 0.3 * sa)) p.L(*(proj @ rot_proj).p2(xa, 0.3 * sa)) p.Z() d.append(p, z=z) return d
def setup(levers, exp=True): start_time = time.time() global path path = "markovchain/%.0f/" % (start_time) drawbutton = widgets.Button(description="Draw") submit = widgets.Button(description="Submit") full_dwg = draw.Drawing(800, 600) dwg = draw.Group() full_dwg.append(dwg) animal = DrawingWidget(full_dwg) def ellipse(cx, cy, rx, ry, stroke_width, stroke, fill): ell_path = draw.Path(stroke_width=stroke_width, stroke=stroke, fill=fill) ell_path.M(cx - rx, cy) ell_path.A(rx, ry, 0, False, False, cx + rx, cy) ell_path.A(rx, ry, 0, False, False, cx - rx, cy) return ell_path def dir_point(start, distance, angle): return (start[0] + distance * math.cos(math.radians(angle)), start[1] + distance * math.sin(math.radians(angle))) def mirror(points, cx): return [(2 * cx - point[0], point[1]) for point in points] def r_ellipse(angle, rx, ry): return ((math.cos(math.radians(angle)) / rx)**2 + (math.sin(math.radians(angle)) / ry)**2)**(-.5) def draw_img(change): dwg.children.clear() width = 173 * (levers["face_aspect_ratio"].value)**0.5 height = 173 / (levers["face_aspect_ratio"].value)**0.5 cx = 800 / 2 cy = 600 / 2 #Ears ear_angle = levers["ear_angle"].value ear_tip_angle = levers["ear_tip_angle"].value ear_length = levers["ear_length"].value ear_orientation = levers["ear_orientation"].value ear_point = levers["ear_point"].value eye_height = levers["eye_height"].value eye_width = eye_height * levers["eye_aspect_ratio"].value eye_distance = levers["eye_distance"].value nose_size = levers["nose_size"].value fur_color = "hsl(%i, %i%%, %i%%)" % ( 45, levers["fur_saturation"].value, levers["fur_lightness"].value) dist_to_tip = r_ellipse(ear_angle, width, height) + ear_length right_tip = dir_point((cx, cy), dist_to_tip, ear_angle) bottom_right = dir_point( right_tip, ear_length * 2.2, 180 + ear_angle + ear_tip_angle * ear_orientation) bottom_right_ctrl = dir_point( bottom_right, ear_length * 2.2 - ear_point, ear_angle + ear_tip_angle * ear_orientation) top_right = dir_point( right_tip, ear_length * 2.2, 180 + ear_angle - ear_tip_angle * (1 - ear_orientation)) top_right_ctrl = dir_point( top_right, ear_length * 2.2 - ear_point, ear_angle - ear_tip_angle * (1 - ear_orientation)) top_left, top_left_ctrl, left_tip, bottom_left_ctrl, bottom_left = mirror( [ top_right, top_right_ctrl, right_tip, bottom_right_ctrl, bottom_right ], cx) left_ear = draw.Path(stroke_width=1, stroke='black', fill=fur_color) left_ear.M(*bottom_left) left_ear.L(*bottom_left_ctrl) left_ear.A(ear_point * .8, ear_point * .8, 0, False, True, *top_left_ctrl) left_ear.L(*top_left) right_ear = draw.Path(stroke_width=1, stroke='black', fill=fur_color) right_ear.M(*bottom_right) right_ear.L(*bottom_right_ctrl) right_ear.A(ear_point * .8, ear_point * .8, 0, False, False, *top_right_ctrl) right_ear.L(*top_right) dwg.draw(left_ear) dwg.draw(right_ear) #Face face = ellipse(cx, cy, width, height, stroke_width=1, stroke='black', fill=fur_color) dwg.draw(face) #Eyes left_eye = ellipse(cx - eye_distance, cy + height / 4, eye_width, eye_height, stroke_width=1, stroke='black', fill="black") right_eye = ellipse(cx + eye_distance, cy + height / 4, eye_width, eye_height, stroke_width=1, stroke='black', fill="black") dwg.draw(left_eye) dwg.draw(right_eye) #Nose dwg.draw( draw.Lines(cx - nose_size, cy + nose_size / 3, cx + nose_size, cy + nose_size / 3, cx, cy - nose_size, close=True, stroke_width=1, stroke='black', fill="black")) #Snout dwg.draw( draw.Line(cx, cy - nose_size, cx, cy - nose_size * 2.5, stroke_width=2, stroke='black', fill="black")) #Mouth mouth = draw.Path(fill="none", stroke_width=2, stroke='black') mouth.M(cx - nose_size * 2, cy - nose_size * 2.5 - 4) mouth.A(nose_size * 2, nose_size * 2, 30, False, False, cx, cy - nose_size * 2.5) mouth.A(nose_size * 2, nose_size * 2, 150, False, False, cx + nose_size * 2, cy - nose_size * 2.5 - 4) dwg.draw(mouth) #Whiskers whisker_length = levers["whisker_length"].value whiskers = [((cx - 34, cy - nose_size - 10), 195), ((cx - 40, cy - nose_size - 4), 185), ((cx - 34, cy - nose_size + 2), 175), ((cx + 34, cy - nose_size - 10), 345), ((cx + 40, cy - nose_size - 4), 355), ((cx + 34, cy - nose_size + 2), 5)] for whisker in whiskers: dwg.draw( draw.Line(*whisker[0], *dir_point(whisker[0], whisker_length, whisker[1]), stroke_width=1, stroke='black', fill="black")) animal.refresh() draw_img(None) levers_text = [] for lever in levers: levers[lever].style = {'description_width': '200px'} levers[lever].layout.width = '800px' levers[lever].continuous_update = True levers[lever].readout = True levers[lever].readout_format = '.2f' levers[lever].observe(draw_img, names="value") levers_text.append(levers[lever]) item_layout = widgets.Layout(margin='50px', justify_content='space-around', justify_items='center', align_content='space-evenly', align_items='center') def on_draw(b): draw_img(None) drawbutton.on_click(on_draw) def on_submit(b): point_time = time.time() if exp: filename = path + "%.0f.svg" % point_time if not os.path.isdir(path): os.makedirs(path) full_dwg.saveSvg(filename) submit.on_click(on_submit) if exp: subj_name = widgets.Text(description='Subject ID') subj_enter = widgets.Button(description="Submit Subject ID") subj = widgets.HBox([subj_name, subj_enter]) def subj_dir(b): global path path = "markovchain/%.0f (ID %s)/" % (start_time, subj_name.value) os.makedirs(path) subj_name.layout.visibility = 'hidden' subj_enter.layout.visibility = 'hidden' subj_enter.on_click(subj_dir) return widgets.HBox([ widgets.VBox(levers_text), widgets.VBox([subj, animal, submit], layout=item_layout) ], layout=item_layout) return widgets.HBox([ widgets.VBox(levers_text), widgets.VBox( [animal, widgets.HBox([drawbutton, submit], layout=item_layout)], layout=item_layout) ], layout=item_layout)
def draw(self, x=0, y=0, xscale=1.0): group = draw.Group(transform="translate({} {})".format(x, y)) for i, (child_y, arrow) in enumerate(zip(self.y_coordinates, self.arrows)): group.append(arrow.draw(y=child_y, xscale=xscale)) return group
print("---") for placeholder in pres.slide_master.placeholders: print(placeholder) print(placeholder.left, placeholder.top, placeholder.width, placeholder.height) import drawSvg as draw print("---") print(pres.slide_width, pres.slide_height) # drawSvg was designed for the coordinates x and y to increase rightward and upward. (#11) FACTOR = 720 d = draw.Drawing(pres.slide_width/FACTOR, pres.slide_height/FACTOR) g = draw.Group(transform="scale(1,-1) translate(0,{})".format(pres.slide_height/FACTOR)) for shape in pres.slide_master.shapes: print(shape.shape_type, shape.left, shape.top, shape.width, shape.height) if shape.shape_type == MSO_SHAPE_TYPE.AUTO_SHAPE: if shape.auto_shape_type == MSO_SHAPE.OVAL: r = shape.width/FACTOR c = shape.fill.fore_color.rgb line_color = shape.line.fill.fore_color.rgb line_width = shape.line.width/FACTOR g.append(draw.Circle(shape.left/FACTOR+r/2, shape.top/FACTOR+r/2, r/2, fill='#{}'.format(c), stroke='#{}'.format(line_color), stroke_width=line_width)) elif shape.shape_type == MSO_SHAPE_TYPE.GROUP: print(shape, shape.name, "SHAPE len = {}".format(len(shape.shapes))) for shape in shape.shapes: print(shape.shape_type, shape.left, shape.top, shape.width, shape.height) g.append(draw.Rectangle(shape.left/FACTOR, shape.top/FACTOR, shape.width/FACTOR, shape.height/FACTOR, fill='#1248ff'))