rospy.Subscriber(topic_name, FeedbackMsg, feedback_callback, queue_size = 1) rospy.loginfo("Waiting for feedback message on topic %s.", topic_name) rate = rospy.Rate(10.0) feedbackMsg = [] timestr = time.strftime("%Y%m%d_%H%M%S") filename_string = "teb_svg_" + timestr + '.svg' rospy.loginfo("SVG will be written to '%s'.", filename_string) random.seed(0) svg=svgwrite.Drawing(filename=filename_string, debug=True) # Create viewbox -> this box defines the size of the visible drawing svg.viewbox(GRID_X_MIN*SCALE-1*SCALE,GRID_Y_MIN*SCALE-1*SCALE,GRID_X_MAX*SCALE-GRID_X_MIN*SCALE+2*SCALE,GRID_Y_MAX*SCALE-GRID_Y_MIN*SCALE+2*SCALE) # Draw grid: hLines = svg.add(svg.g(id='hLines', stroke='black')) hLines.add(svg.line(start=(GRID_X_MIN*SCALE, 0), end=(GRID_X_MAX*SCALE, 0))) for y in range(GRID_Y_MAX): hLines.add(svg.line(start=(GRID_X_MIN*SCALE, SCALE+y*SCALE), end=(GRID_X_MAX*SCALE, SCALE+y*SCALE))) for y in range(-GRID_Y_MIN): hLines.add(svg.line(start=(GRID_X_MIN*SCALE, -SCALE-y*SCALE), end=(GRID_X_MAX*SCALE, -SCALE-y*SCALE))) vLines = svg.add(svg.g(id='vline', stroke='black')) vLines.add(svg.line(start=(0, GRID_Y_MIN*SCALE), end=(0, GRID_Y_MAX*SCALE))) for x in range(GRID_X_MAX): vLines.add(svg.line(start=(SCALE+x*SCALE, GRID_Y_MIN*SCALE), end=(SCALE+x*SCALE, GRID_Y_MAX*SCALE)))
origin_y = plate_dia + 50 circle_spacing = 28 # --- plate_r = plate_dia / 2.0 hole_r = hole_dia / 2.0 conn_r = conn_dia / 2.0 def border(dwg, radius, origin_x, origin_y): STEPS = 360 points = [] for i in range(STEPS - 40): theta = i * (pi * 2.0) / STEPS r1 = radius + (10 * sin(7 * radians(i))) y1 = r1 * sin(theta) + origin_y x1 = r1 * cos(theta) + origin_x points.append((x1, y1)) return points dwg = svgwrite.Drawing('foot.svg', profile='tiny') points = border(dwg, plate_r, origin_x, origin_y) inner = border(dwg, plate_r - 36, origin_x, origin_y) inner.reverse() points.extend(inner) dwg.add(dwg.polygon(points, fill='none', stroke=svgwrite.rgb(0, 0, 0, '%'))) dwg.save()
def parseTrace(time): data = [] readData(data) formatData(data, time) time = {} parseTrace(time) keys = list(time.keys()) keys.sort() duration = max(time[keys[-1]]) - max(time[keys[0]]) height = str(duration + 100) + 'mm' dwg = svgwrite.Drawing(filename='time.svg', size=('100cm', height), debug=True) shapes = dwg.add(dwg.g(id='shapes', fill='red')) text = dwg.add(dwg.g(font_size=14)) throughput = len(keys) * 1000000 / duration text.add(dwg.text('duration: ' + str(duration) + ' us', (10 * mm, 5 * mm))) text.add(dwg.text('# submit: ' + str(len(keys)), (10 * mm, 10 * mm))) text.add(dwg.text('submit throughput: ' + str(throughput), (10 * mm, 15 * mm))) offset = time[keys[0]][0] for k in keys: #print(time[k]) drawItem(time[k], k, offset) dwg.save()
def draw_line(dwg, start, end, stroke=svgwrite.rgb(10, 10, 16, '%')): start = inches(start) end = inches(end) stroke = stroke print("Start at %s, End at %s" % (start, end)) dwg.add(dwg.line(start, end, stroke=stroke)) # the range here should be the size you want * 1000 i.e. 0.124 = 124 since range doesn't take floats for slot_width in range(120, 130, 1): slot_width = slot_width / 1000 filename = "%1.4f - slot test.svg" % slot_width dwg = svgwrite.Drawing(filename, profile='tiny', height=canvas_height, width=canvas_width) slot_offset = (1 - slot_width) / 2 x = 1 y = 1 draw_line(dwg, (x, y), (x, y + 1)) # left side draw_line(dwg, (x, y + 1), (x + 1, y + 1)) # bottom side draw_line(dwg, (x + 1, y + 1), (x + 1, y)) # right side draw_line(dwg, (x, y), (x + slot_offset, y)) # left top draw_line(dwg, (x + 1, y), (x + 1 - slot_offset, y)) # right top draw_line(dwg, (x + slot_offset, y), (x + slot_offset, y + 0.5)) # down draw_line(dwg, (x + slot_offset, y + 0.5), (x + slot_offset + slot_width, y + 0.5)) # over draw_line(dwg, (x + slot_offset + slot_width, y + 0.5),
if sys.argv[i]=="-f": print("permet de désigner un input de type fichier "+sys.argv[i+1]+" car le -f est présent") if len(sys.argv)==i: sys.exit() i+=2 if len(sys.argv)==i: sys.exit() if sys.argv[i]=="-o" : if len(sys.argv)==i: sys.exit() print(" le -o est bien présent "+sys.argv[i+1]) print("Ce qui reste c'est de creer un fichier svg valide respectant les normes du MLD") svg_document = svgwrite.Drawing(filename =sys.argv[i+1], size = (1500,1500)) XmlExtraction(sys.argv[i-1]) # lineXML() else: print("pas de fichier svg") elif sys.argv[2]=="json": print("traitement avec un fichier json") i+=1 if sys.argv[i]=="-t": i+=1 classe=ValidatorAndExtractorJson(sys.argv[sys.argv.index("-f")+1])
def sample(self, sess, num=1200): def get_pi_idx(x, pdf): N = pdf.size accumulate = 0 for i in range(0, N): accumulate += pdf[i] if (accumulate >= x): return i print 'error with sampling ensemble' return -1 def sample_gaussian_2d(mu, sig): #x = np.random.multivariate_normal(mu, np.diag(sig) ** 2, 1) #return x[0] return mu pose = np.array([0], dtype=np.float32) prev_x = np.zeros((1, 1, self.dim), dtype=np.float32) prev_state = sess.run(self.cell.zero_state(1, tf.float32)) f = open("output.txt", "w") f.write(" ".join(["%f" % x for x in pose]) + "\n") height = 500 dims = (1000, height) dwg = svgwrite.Drawing("result.svg", size=dims) dwg.add(dwg.rect(insert=(0, 0), size=dims, fill='white')) p = "M 0,%f " % (height / 2) print sess.run(self.w) #exit(0) # priming for i in range(100): feed = {self.input_data: prev_x, self.initial_state: prev_state} prev_x[0][0][0] = 25 * (math.sin(i * 2 * np.pi / 100) - math.sin( (i - 1) * 2 * np.pi / 100)) #[o_pi, o_mu, o_sig, prev_state] = sess.run([self.pi, self.mu, self.sig, self.final_state],feed) prev_state = sess.run(self.final_state, feed) for i in xrange(num): feed = {self.input_data: prev_x, self.initial_state: prev_state} [o_pi, o_mu, o_sig, next_state ] = sess.run([self.pi, self.mu, self.sig, self.final_state], feed) #idx = get_pi_idx(random.random(), o_pi[0]) idx = np.argmax(o_pi[0]) nxt = sample_gaussian_2d(o_mu[0][idx::self.num_mixture], o_sig[0][idx::self.num_mixture]) pose += nxt / self.args.data_scale p += "L %f,%f " % (i + 1, height / 2 + pose) #print pose print idx f.write(" ".join(["%f" % x for x in pose]) + "\n") prev_x[0][0] = nxt prev_state = next_state stroke_width = 1 the_color = "black" dwg.add(dwg.path(p).stroke(the_color, stroke_width).fill("none")) dwg.save() f.close()
miterlimit=4) arcstr = "M%d,%d A12,12 0 0,1 %d,%d" % ((60 + llx), (90 + lly), (45 + llx), (100 + lly)) arc = dwg.path(d=arcstr) arc.fill(color='none') arc.stroke(color='black', width=0.1, opacity=1, linejoin='round', miterlimit=4) dwg.add(arc) return (border) dwg = svgwrite.Drawing('circles.svg', profile='full', size=('200mm', '150mm'), viewBox=('0 0 200 150')) dwg.set_desc(title='circle example', desc='my first example') #view_attributes= { # 'sodipodi:namedview' ink = Inkscape(dwg) #layer=ink.layer(label="top LAYER1", locked=True) #dwg.add(layer) xoff = 10 yoff = 10 step = 8 offset = step / 2 d = 6 r = d / 2 cx = 25 cy = 25
help="Line stroke width for symbols") parser.add_argument('-fontsize', dest="FONT_SIZE", default=14, type=int, help="Font size") a = parser.parse_args() # open the map image im = Image.open(a.MAP_IMAGE) width, height = im.size print("Target size: %s x %s" % (width, height)) routes = parseRouteData(a.ROUTE_DATA, a.UROUTE_DATA) dwg = svg.Drawing(a.OUTPUT_FILE, size=(width, height), profile='full') # add guides guides = dwg.add(dwg.g(id="guides")) guides.add( dwg.image(href=os.path.basename(a.MAP_IMAGE), insert=(0, 0), size=(width, height))) # add center points for i, route in enumerate(routes): for j, group in enumerate(route["groups"]): for k, station in enumerate(group): x, y = tuple(station["point"]) w, h = tuple(station["size"]) x += w * 0.5
def predict_batch(region_weight, edge_map_weight, junctions_weight): metrics = Metrics() for _id in _ids: # load detections fname = '{}/{}.jpg_5.pkl'.format(res_dir, _id) with open(fname, 'rb') as f: c = p.load(f, encoding='latin1') # apply non maxima supression cs, cs_c, th, th_c = nms(c['junctions'], c['junc_confs'], c['thetas'], c['theta_confs'], nms_thresh=8.0) # load annotations p_path = '{}/{}.npy'.format(annot_dir, _id) v_set = np.load(open(p_path, 'rb'), encoding='bytes') graph_annot = dict(v_set[()]) cs_annot, es_annot = load_annots(graph_annot) # load edge map edge_map_path = '{}/{}.jpg'.format(edge_dir, _id) im_path = '{}/{}.jpg'.format(rgb_dir, _id) edge_map = np.array(Image.open(edge_map_path).convert('L')) / 255.0 # load region masks region_path = '{}/{}.npy'.format(region_dir, _id) region_mks = np.load(region_path) region_mks = filter_regions(region_mks) # compute edge scores from classifier lw_from_cls = get_edge_scores(cs, region_mks, rgb_dir, _id) # Reconstruct junctions, juncs_on, lines_on, regs_sm_on = reconstructBuildingBaseline( cs, edge_map, use_junctions_with_var=True, use_regions=True, thetas=th, regions=region_mks, angle_thresh=5, with_corner_edge_confidence=True, corner_confs=cs_c, corner_edge_thresh=0.125, theta_confs=th_c, theta_threshold=0.25, region_hit_threshold=0.1, lw_from_cls=lw_from_cls, use_edge_classifier=True, closed_region_lowerbound=True, closed_region_upperbound=True, with_corner_variables=True, corner_min_degree_constraint=True, junctions_soft=True, region_intersection_constraint=True, inter_region_constraint=True, post_process=True, region_weight=region_weight, edge_map_weight=edge_map_weight, junctions_weight=junctions_weight, ) dwg = svgwrite.Drawing('../result/svg/{}.svg'.format(_id), (128, 128)) dwg.add(svgwrite.image.Image(edge_map_path, size=(128, 128))) im_path = os.path.join(rgb_dir, _id + '.jpg') draw_building(dwg, junctions, juncs_on, lines_on) dwg.save() metrics.forward(graph_annot, junctions, juncs_on, lines_on, _id) return metrics.edge_f_score()
charge = Charge(50, 50, 2) nodes = [] for key in keys: value = volumes[key] x, y = np.random.normal(size=2, loc=50, scale=10) node = Node(x, y, value / factor, m=value, friction=0.1) charge.add(node) nodes.append(node) universe = Universe(.1) universe.add_nodes(nodes) universe.add_forces([charge]) positions = universe.history(200) # svgwrite dwg = svgwrite.Drawing('test.svg', width=1000, height=1000) i = 0 for node, key in zip(nodes, keys): radius = volumes[key] x, y = positions[-1, i] x *= 1000 / 100 y *= 1000 / 100 radius *= 1000 / 100 radius *= 0.9 circle = dwg.circle((x, y), radius / factor, stroke=colors[key], stroke_width=3, fill_opacity=0) dwg.add(circle) i += 1
peak = sota_api.SotaPeak(text) peaks.append(peak) else: peak = sota_api_impl.retrieve_peak(peak_code) if peak is not None: with open(filename, "w") as file: file.write(json.dumps(peak.data)) peaks.append(peak) static_maps = StaticMapDownloader(args.static_maps_key) geocoding_api = GeocodingApi(args.static_maps_key) dwg = svgwrite.Drawing("reference_card.svg", size=full_size) bg = dwg.add(dwg.rect(size=full_size)) bg.fill("none") bg.stroke("none") card = dwg.svg(insert=(0, 0), size=card_size) populate_card(dwg, card, peaks[0], args.loc_id, static_maps, geocoding_api) dwg.add(card) if len(peaks) > 1: card = dwg.svg(insert=(card_size[0], 0), size=card_size) populate_card(dwg, card, peaks[1], args.loc_id, static_maps, geocoding_api) dwg.add(card) if len(peaks) > 2:
def create_maze(height, width): dwg = svgwrite.Drawing('Maze.svg', profile='tiny', size=(int(width) * mm, int(height) * mm)) length = 0 file = open("Maze.txt", "w+") for x in range(width): for y in range(height): if x == 0 and y == 0: file.write(str(x + 1) + ',' + str(y + 1) + ' Visited\n') else: file.write(str(x + 1) + ',' + str(y + 1) + '\n') con = open("Maze Connections.txt", "w+") for x in range(width): for y in range(height): con.write( str(x + 1) + ' ' + str(y + 1) + '\n\n\n\n\n') file.close() itcount = 0 x_coord = 1 y_coord = 1 done = 'no' count = 0 while count < 1000: count = count + 1 dirc = "not_done" file = open("Maze.txt", 'r') con = open("Maze Connections.txt", 'r') file_lines = file.readlines() con_lines = con.readlines() file.close() con.close() ymax = y_coord == height ymin = y_coord == 1 xmax = x_coord == width xmin = x_coord == 1 current_x = x_coord current_y = y_coord it = 0 con_count = 0 #print(con_lines[ (x + 1) * 10 + (y + 1)]) while dirc != "done" and it < 20: xmax = x_coord == width ymax = y_coord == height xmin = x_coord == 1 ymin = y_coord == 1 it3 = 1 it = it + 1 print('it') print(it) if ymax: upvisit = True if xmax: rightvisit = True if x_coord == 1: leftvisit = True if y_coord == 1: downvisit = True line_in_file = (x_coord - 1) * height + (y_coord - 1) if not ymax: print(x_coord) print(y_coord) print(len(file_lines)) print(line_in_file + 1) upvisit = ("Visited" in file_lines[line_in_file + 1]) if y_coord != 1: downvisit = ("Visited" in file_lines[line_in_file - 1]) if x_coord != 1: leftvisit = ("Visited" in file_lines[line_in_file - width]) if not xmax: print(x_coord) print(width) print(y_coord) print(line_in_file + width) rightvisit = ("Visited" in file_lines[line_in_file + width]) direction = random.randint(1, 4) '''if upvisit and rightvisit and downvisit and leftvisit: print(upvisit) print(rightvisit) print(downvisit) print(leftvisit) sys.exit()''' print("Visiteds:") print(direction) print(leftvisit) print(rightvisit) print(downvisit) print(upvisit) if direction == 1 and not ymax and not upvisit: dirc = "done" #print('upvisit') print(file_lines[line_in_file]) print(file_lines[line_in_file + 1]) print(upvisit) y_coord = y_coord + 1 if direction == 2 and not xmax and not rightvisit: dirc = "done" #print('rightvisit') print(file_lines[line_in_file]) print(file_lines[line_in_file + width]) print(rightvisit) x_coord = x_coord + 1 if direction == 3 and not ymin and not downvisit: dirc = "done" #print('downvisit') print(file_lines[line_in_file]) print(file_lines[line_in_file - 1]) print(downvisit) y_coord = y_coord - 1 if direction == 4 and not xmin and not leftvisit: dirc = "done" #print('leftvisit') print(file_lines[line_in_file]) print(file_lines[line_in_file - width]) print(leftvisit) x_coord = x_coord - 1 if dirc == "done": length = length + 1 elif leftvisit and rightvisit and upvisit and downvisit: dirdone = False print("All Visited") print(it3) #count = 100000 #it = 1000 if it3 < 2000: it4 = 0 it3 = it3 + 1 up = False down = False right = False left = False print("Backtrack testing") print(x_coord) print(y_coord) print(con_lines[5 * (height * (x_coord - 1) + (y_coord - 1))]) print(con_lines[5 * (height * (x_coord - 1) + (y_coord - 1))][:5]) print(con_lines[5 * (height * (x_coord - 1) + (y_coord - 1))][-6:]) if (con_lines[5 * (height * (x_coord - 1) + (y_coord - 1))]) != '\n': x1 = int(con_lines[5 * (height * (x_coord - 1) + (y_coord - 1))][:5]) y1 = int(con_lines[5 * (height * (x_coord - 1) + (y_coord - 1))][-6:]) for n in range(4): if (con_lines[5 * (height * (x_coord - 1) + (y_coord - 1)) + n]) != '\n': print(con_lines[(height * (x_coord - 1) + (y_coord - 1)) + n][-6:]) x2 = int(con_lines[5 * (height * (x_coord - 1) + (y_coord - 1)) + n][:5]) y2 = int(con_lines[5 * (height * (x_coord - 1) + (y_coord - 1)) + n][-6:]) if y1 > y2: up = True if y1 < y2: down = True if x1 > x2: left = True if x1 < x2: right = True it4 = 0 while it4 < 5: direction = random.randint(1, 4) if direction == 1 and up: y_coord = current_y current_y = current_y - 1 itcount = itcount + 1 #dwg.add(dwg.circle(center=((x_coord)*mm,(y_coord-10)*mm), r=0.15*mm, stroke='red',fill='red', stroke_width=0.05*mm)) it4 = 5 elif direction == 2 and right: x_coord = current_x current_x = current_x + 1 itcount = itcount + 1 #dwg.add(dwg.circle(center=((x_coord)*mm,(y_coord)*mm), r=0.15*mm, stroke='red',fill='black', stroke_width=0.05*mm)) it4 = 5 elif direction == 3 and down: y_coord = current_y current_y = current_y + 1 itcount = itcount + 1 #dwg.add(dwg.circle(center=((x_coord)*mm,(y_coord)*mm), r=0.15*mm, stroke='red',fill='yellow', stroke_width=0.05*mm)) it4 = 5 elif direction == 4 and left: x_coord = current_x current_x = current_x - 1 itcount = itcount + 1 #dwg.add(dwg.circle(center=((x_coord)*mm,(y_coord)*mm), r=0.15*mm, stroke='red',fill='green', stroke_width=0.05*mm)) it4 = 5 if it4 == 5: print(it) '''print("COO") print(x_coord) print(y_coord)''' '''if direction == 4: x_coord = x_coord - 1 if direction == 3: y_coord = y_coord - 1 if direction == 2: x_coord = x_coord + 1 if direction == 1: y_coord = y_coord + 1''' if not leftvisit or not rightvisit or not upvisit or not downvisit: count = count + 1 line_number = height * (x_coord - 1) + (y_coord - 1) file = open("Maze.txt", 'w') for line in file_lines: if file_lines.index(line) != line_number: file.write(line) elif file_lines.index(line) == line_number: file.write( str(x_coord) + ',' + str(y_coord) + ' Visited\n') con = open("Maze Connections.txt", "w") edit = False conline_pos_a = 5 * (height * (current_x - 1) + (current_y - 1)) conline_pos_b = 5 * (height * (x_coord - 1) + (y_coord - 1)) #print(x_coord) #print(y_coord) #print(conline_pos_b) con_count = 0 cycle_count_a = 1 cycle_count_b = 1 '''print("Diagnostic") print(x_coord) print(current_x) print(y_coord) print(current_y)''' for conline in con_lines: if con_count == conline_pos_a + cycle_count_a: if conline == '\n': con.write( str(x_coord) + " " + str(y_coord) + "\n") cycle_count_a = 1 elif conline != '\n': con.write(conline) cycle_count_a = cycle_count_a + 1 elif con_count == conline_pos_b + cycle_count_b: if conline == '\n': con.write( str(current_x) + " " + str(current_y) + "\n") cycle_count_b = 1 elif conline != '\n': con.write(conline) cycle_count_b = cycle_count_b + 1 #con.write("test (" + str(current_x) +"," + str(current_y) + ")\n") else: con.write(conline) con_count = con_count + 1 con = open("Maze Connections.txt", 'r') con_lines = con.readlines() con_count = 0 con_count = con_count + 1 con_count = 0 path_width = 0.2 for cell in con_lines: if con_count % 5 == 0: up = False down = False right = False left = False conn_test = False for conn in range(4): if con_lines[con_count + conn + 1] != '\n': conn_test = True #print(("First Cell Contents:")) #print(con_lines[con_count + conn + 1]) x1 = int(con_lines[con_count + conn + 1][:5]) y1 = int(con_lines[con_count + conn + 1][-6:]) x2 = int(cell[:5]) y2 = int(cell[-6:]) if y1 > y2: dwg.add( dwg.line(((x1 + path_width) * mm, (y1 - path_width) * mm), ((x2 + path_width) * mm, (y2 + path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) dwg.add( dwg.line(((x1 - path_width) * mm, (y1 - path_width) * mm), ((x2 - path_width) * mm, (y2 + path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) down = True if y1 < y2: dwg.add( dwg.line(((x1 + path_width) * mm, (y1 + path_width) * mm), ((x2 + path_width) * mm, (y2 - path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) dwg.add( dwg.line(((x1 - path_width) * mm, (y1 + path_width) * mm), ((x2 - path_width) * mm, (y2 - path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) up = True if x1 > x2: dwg.add( dwg.line(((x1 - path_width) * mm, (y1 + path_width) * mm), ((x2 + path_width) * mm, (y2 + path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) dwg.add( dwg.line(((x1 - path_width) * mm, (y1 - path_width) * mm), ((x2 + path_width) * mm, (y2 - path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) right = True if x1 < x2: dwg.add( dwg.line(((x1 + path_width) * mm, (y1 + path_width) * mm), ((x2 - path_width) * mm, (y2 + path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) dwg.add( dwg.line(((x1 + path_width) * mm, (y1 - path_width) * mm), ((x2 - path_width) * mm, (y2 - path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) left = True if conn_test == True: if not down: dwg.add( dwg.line( ((x2 + path_width) * mm, (y2 + path_width) * mm), ((x2 - path_width) * mm, (y2 + path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) if not up: dwg.add( dwg.line( ((x2 + path_width) * mm, (y2 - path_width) * mm), ((x2 - path_width) * mm, (y2 - path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) if not right: dwg.add( dwg.line( ((x2 + path_width) * mm, (y2 + path_width) * mm), ((x2 + path_width) * mm, (y2 - path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) if not left: dwg.add( dwg.line( ((x2 - path_width) * mm, (y2 + path_width) * mm), ((x2 - path_width) * mm, (y2 - path_width) * mm), stroke_width=0.01 * mm, stroke=svgwrite.rgb(10, 10, 16, '%'))) con_count = con_count + 1 dwg.save() print("itcount") print(itcount)
linecolor = "black" #线颜色 genecolor = "black" #基因名颜色 bootcolor = "black" #bootstrap值颜色 nameback = 10 #基因名与线距离 strokewidth = 2 #线宽 textdown = 6 #基因名名称下移量 scalestrokewidth = 2 #比例尺线宽 scaleunit = 0.1 #比例尺大小 scalecolor = "black" #比例尺颜色 scaletextcolor = "black" #比例尺字体颜色 unit = MaxCladePx / MaxCladeLength svgheight = GeneInterval * len(AllGeneName) + 100 svgweihht = MaxCladePx + 480 treepaint = svgwrite.Drawing("test.tree.svg", (svgweihht, svgheight)) #treepaint.add(treepaint.text("test tree", insert=(20, 20), font_size = 16,fill = 'red')) #找出每一个基因的y轴绘图位置 AllGenePy = {} y = painty0 for gene in AllGeneName: AllGenePy[gene] = y y += GeneInterval cladeid = 1 two = 1 flag = True while flag: minclaseinfo = GetMinClade(nwkdata) #找出没有嵌套括号的括号内容 for mininfo in minclaseinfo:
def create_svg(name): class bezier(object): def __init__(self, val_x, val_y): # The main point self.x = val_x self.y = val_y # control point before main point self.cbx = None self.cby = None # control point after main point self.cax = None self.cay = None def displayf(self): # display formatted with brackets and commas if self.cbx: self.s_cb = '({:f}, {:f})'.format(self.cbx, self.cby) else: self.s_cb = '(None, None)' if self.cax: self.s_ca = '({:f}, {:f})'.format(self.cax, self.cay) else: self.s_ca = ' (None, None)' return '({:s}, ({:f}, {:f}), {:s})'.format(self.s_cb, self.x, self.y, self.s_ca) def display(self): # display without formatted with brackets and commas if self.cbx: self.s_cb = '{:f} {:f}'.format(self.cbx, self.cby) else: self.s_cb = 'None None' if self.cax: self.s_ca = '{:f} {:f}'.format(self.cax, self.cay) else: self.s_ca = ' None None' return '{:s} {:f} {:f} {:s}'.format(self.s_cb, self.x, self.y, self.s_ca) svg_size = 900 font_size = 20 title = name + ': Example of Bezier curves' dwg = svgwrite.Drawing(name, (svg_size, svg_size), debug=True) # background will be white. dwg.add( dwg.rect(insert=(0, 0), size=('100%', '100%'), rx=None, ry=None, fill='white')) # give the name of the example and a title. dwg.add( dwg.text(title, insert=(0, (font_size + 5)), font_family="serif", font_size=font_size, fill='black')) # http://www.w3.org/TR/SVG11/paths.html # M=move to L=line to z=close path. # Uppercase means absolute coordinates, lowercase means relative coordinates # H=draw horizonal line V=draw vertical line # # C (absolute) c (relative) curveto (x1 y1 x2 y2 x y)+ # Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve. C (uppercase) indicates that absolute coordinates will follow; c (lowercase) indicates that relative coordinates will follow. Multiple sets of coordinates may be specified to draw a polybezier. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier. # S (absolute) s (relative) shorthand/smooth curveto (x2 y2 x y)+ # Draws a cubic Bezier curve from the current point to (x,y). The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an C, c, S or s, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). S (uppercase) indicates that absolute coordinates will follow; s (lowercase) indicates that relative coordinates will follow. Multiple sets of coordinates may be specified to draw a polybezier. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier. # Q (absolute) q (relative) quadratic Bezier curveto (x1 y1 x y)+ # Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point. Q (uppercase) indicates that absolute coordinates will follow; q (lowercase) indicates that relative coordinates will follow. Multiple sets of coordinates may be specified to draw a polybezier. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier. # T (absolute) t (relative) Shorthand/smooth quadratic Bezier curveto (x y)+ # Draws a quadratic Bezier curve from the current point to (x,y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a Q, q, T or t, assume the control point is coincident with the current point.) T (uppercase) indicates that absolute coordinates will follow; t (lowercase) indicates that relative coordinates will follow. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier. # # Draw rectangle but with wiggly Bezier line. start = [50.0, 100.0] size = [200.0, 200.0] pts_per_side = 7 ctl_pt_weight = 2.50 # what weight is given to control point? (distance to next point) x ctl_pt_weight vert_pt_weight = .80 # what weight is given to vertical distance? (distance to next point) x vert_pt_weight plus_minus = cycle( [1, -1]) # create iterator which alternates between +1 and -1 forever. # s1 = 'M {0[0]} {0[1]}'.format(start) p3 = dwg.path(d=s1, stroke_width=1, stroke='red', fill='none') # top left to top right l1 = nfrange(start[0], (start[0] + size[0]), 7) for item in l1: circle_3 = dwg.circle(center=(item, start[1]), r=3) circle_3.fill('green', opacity=0.5).stroke('black', width=1) dwg.add(circle_3) pm = next(plus_minus) l1l = [] for i, item in enumerate(l1): # Do not add the starting point because the starting point is given by the M command ## TODO: change the loop to have the starting point M done within the loop. if i != 0: # create control point for the previous point ctl_pt_dist = ctl_pt_weight * (item - l1[i - 1]) vert_dist_chg = vert_pt_weight * ( item - l1[i - 1]) * pm # vertical distance off off straight line. l1l.append(l1[i - 1] + ctl_pt_dist) # x l1l.append(start[1] + vert_dist_chg) # y circle_1 = dwg.circle(center=(l1[i - 1] + ctl_pt_dist, start[1] + vert_dist_chg), r=1) circle_1.fill('blue', opacity=0.5).stroke('black', width=1) dwg.add(circle_1) pm = next(plus_minus) vert_dist_chg = vert_pt_weight * ( item - l1[i - 1]) * pm # vertical distance off off straight line. # create control point for the current point l1l.append(item - ctl_pt_dist) # x l1l.append(start[1] + vert_dist_chg) # y circle_1 = dwg.circle(center=(item - ctl_pt_dist, start[1] + vert_dist_chg), r=1) circle_1.fill('purple', opacity=0.5).stroke('black', width=1) dwg.add(circle_1) # create the current point l1l.append(item) l1l.append(start[1] + vert_dist_chg) circle_3 = dwg.circle(center=(item, start[1] + vert_dist_chg), r=3) circle_3.fill('blue', opacity=0.5).stroke('black', width=1) dwg.add(circle_3) p3.push('C', l1l) dwg.add(p3) dwg.save()
#!/usr/bin/env python3 # coding: utf-8 import svgwrite dwg = svgwrite.Drawing("text.example.svg", (1000, 1800), debug=True) paragraph = dwg.add(dwg.g(font_size=14)) paragraph.add(dwg.text("This is a Test!", (10, 20))) #横向位置 paragraph.add( dwg.text("Test!", insert=(450, 20), text_anchor='middle', font_family="sans-serif", font_size='25px', fill='black')) paragraph.add( dwg.text("Test!", insert=(450, 20), text_anchor='start', font_family="sans-serif", font_size='25px', fill='red')) paragraph.add( dwg.text("Test!", insert=(450, 20), text_anchor='end', font_family="sans-serif", font_size='25px', fill='green'))
def _draw(self, strokes, lines, filename, line_num, stroke_colors=None, stroke_widths=None): stroke_colors = stroke_colors or ['black'] * 4 stroke_widths = stroke_widths or [2] * 4 i = 1 #i+=1 img_large = cv2.imread("templates/large1.jpg") l_img = cv2.imread("large1.jpg", 0) for offsets, line, color, width in zip(strokes, lines, stroke_colors, stroke_widths): svgfil = 'p' + str(i) + '.svg' if i == 1: line_height = 30 view_width = 200 dwg1 = svgwrite.Drawing(filename=svgfil) dwg = dwg1 if i == 2: line_height = 30 view_width = 300 dwg2 = svgwrite.Drawing(filename=svgfil) dwg = dwg2 if i == 3: line_height = 60 view_width = 450 dwg3 = svgwrite.Drawing(filename=svgfil) dwg = dwg3 if i == 4: line_height = 60 view_width = 450 dwg4 = svgwrite.Drawing(filename=svgfil) dwg = dwg4 #line_height = 50 #view_width = 300 view_height = line_height * 2 dwg.viewbox(width=view_width, height=view_height) dwg.add( dwg.rect(insert=(0, 0), size=(view_width, view_height), fill='white')) initial_coord = np.array([0, -(3 * line_height / 4)]) if not line: initial_coord[1] -= line_height continue offsets[:, :2] *= 1.1 strokes = drawing.offsets_to_coords(offsets) strokes = drawing.denoise(strokes) strokes[:, :2] = drawing.align(strokes[:, :2]) strokes[:, 1] *= -1 strokes[:, :2] -= strokes[:, :2].min() + initial_coord strokes[:, 0] += (view_width - strokes[:, 0].max()) / 2 prev_eos = 1.0 p = "M{},{} ".format(0, 0) for x, y, eos in zip(*strokes.T): p += '{}{},{} '.format('M' if prev_eos == 1.0 else 'L', x, y) prev_eos = eos if i == 1: path1 = svgwrite.path.Path(p) path1 = path1.stroke(color=color, width=width, linecap='round').fill("none") dwg.add(path1) if i == 2: path2 = svgwrite.path.Path(p) path2 = path2.stroke(color=color, width=width, linecap='round').fill("none") dwg.add(path2) if i == 3: path3 = svgwrite.path.Path(p) path3 = path3.stroke(color=color, width=width, linecap='round').fill("none") dwg.add(path3) if i == 4: path4 = svgwrite.path.Path(p) path4 = path4.stroke(color=color, width=width, linecap='round').fill("none") dwg.add(path4) #initial_coord[1] -= line_height dwg.save() with Image(filename=svgfil, format='svg') as img: img.format = 'png' img.save(filename="s.png") s_img = cv2.imread("s.png", 0) #control placement of text on the form if i == 1: x_offset = 135 y_offset = 50 if i == 2: x_offset = 155 y_offset = 110 if i == 3: x_offset = 150 y_offset = 300 if i == 4: x_offset = 150 y_offset = 390 l_img[y_offset:y_offset + s_img.shape[0], x_offset:x_offset + s_img.shape[1]] = s_img outfile = "output/" + filename i = i + 1 cv2.imwrite(outfile, l_img) s_img = np.ones(s_img.shape) * int(255) cv2.imwrite("s.png", s_img)
def generate_balcony_svg(rows_json, seat): min_left = 0 max_right = 0 max_y = 0 for row_number, row in enumerate(rows_json): x_offset = PERRSPECTIVE_X * row_number y_offset = -(LENGTH_TOP + HEIGTH) * row_number x_left_additional = 0 x_right_additional = 0 if row_number in BALCONY_OFFSET_LEFT: x_left_additional = BALCONY_OFFSET_LEFT[row_number] * SEAT_PADDING if row_number in BALCONY_OFFSET_RIGHT: x_right_additional = BALCONY_OFFSET_RIGHT[row_number] * \ SEAT_PADDING min_left = min(min_left, x_offset - x_left_additional) max_right = max(max_right, x_offset + x_right_additional) max_y = max(max_y, -y_offset + HEIGTH + LENGTH_TOP) for seatNumber in range(row["left"]): min_left = min( min_left, x_offset - x_left_additional - STAIRS_WITH_LEFT - SEAT_PADDING * seatNumber - CIRCLE_RADIUS) for seatNumber in range(row["right"]): max_right = max( max_right, x_offset + x_right_additional + STAIRS_WITH_RIGHT + SEAT_PADDING * seatNumber + CIRCLE_RADIUS) dwg = svgwrite.Drawing('/tmp/output.svg', (max_right - min_left, max_y), profile='tiny', fill="#FFFFFF") for row_number, row in enumerate(rows_json): x_offset = -min_left + PERRSPECTIVE_X * row_number y_offset = max_y - (LENGTH_TOP + HEIGTH) * (row_number + 1) x_left_additional = 0 x_right_additional = 0 if row_number in BALCONY_OFFSET_LEFT: x_left_additional = BALCONY_OFFSET_LEFT[row_number] * SEAT_PADDING if row_number in BALCONY_OFFSET_RIGHT: x_right_additional = BALCONY_OFFSET_RIGHT[row_number] * \ SEAT_PADDING if row_number < BALCONY_FIRST_ROWS: draw_stairs(dwg, x_offset + x_right_additional, y_offset) for seatNumber in range(BALCONY_FIRST_ROWS_MIDDLE_SEATS): draw_seat( dwg, x_offset - x_left_additional + STAIRS_WITH_RIGHT + (SEAT_PADDING * 0.9) * seatNumber, y_offset, seat["side"] == "middle" and seat["row"] == row_number and seat["number"] == seatNumber) if row_number < 19: draw_stairs(dwg, x_offset - x_left_additional, y_offset) for seatNumber in range(row["left"]): draw_seat( dwg, x_offset - x_left_additional - STAIRS_WITH_LEFT - SEAT_PADDING * seatNumber, y_offset, seat["side"] == "left" and seat["row"] == row_number and seat["number"] == seatNumber) for seatNumber in range(row["right"]): draw_seat( dwg, x_offset + x_right_additional + STAIRS_WITH_RIGHT + SEAT_PADDING * seatNumber, y_offset, seat["side"] == "right" and seat["row"] == row_number and seat["number"] == seatNumber) dwg.save()
poly.append((cx+round(scal*xx), cy+round(scal*yy))) #dwg.add(dwg.line(, (cx+round(scal*xx1), cy+round(scal*yy1)), stroke=svgwrite.rgb(10, 10, 16, '%'))) xx1=xx yy1=yy dwg.add(dwg.polygon(poly,stroke='black', fill='none')) #, stroke=svgwrite.rgb(10, 10, 16, '%') if (not text == ""): dwg.add(dwg.text(text, insert=(cx+round(scal*xx)+5, cy+round(scal*yy)), fill='black')) cx = 600 cy = 420 scal = 18 dwg = svgwrite.Drawing('test2.svg', profile='tiny') kmperly = 9460730472580 mpc = 3260000 * kmperly drawLineR(dwg, 0, 152098232) drawLineR(dwg, 0.1, kmperly*10) drawLineR(dwg, 0.3, kmperly*1000) drawLineR(dwg, 0.5, kmperly*100000) drawLineR(dwg, 0.7, mpc) drawLineR(dwg, 0.9, 100*mpc) drawObject(dwg, 6371, 0, 6371, 0.01, "Earth") drawObject(dwg, 6471, 0, 6371, 0.01) drawObject(dwg, 100, 0, 6371, 0.01)
def prettier_tracks_svg(self, top_n=3, size=1024, pad=0.05): import numpy as np import svgwrite as svg imgs = [ svg.Drawing(shape_rendering="crispEdges") for _ in range(top_n) ] for i in range(top_n): mins, _ = torch.min(self.bounds[i * self.num_players, :, :].view( -1, 2), dim=0) maxs, _ = torch.max(self.bounds[i * self.num_players, :, :].view( -1, 2), dim=0) # mins, _ = torch.tensor([-20., -20.]), 0 # maxs, _ = torch.tensor([ 20., 20.]), 0 longer = torch.max(maxs - mins).item() shift = 0.5 * (1. - (maxs - mins) / longer) minx, miny = mins.tolist() shiftx, shifty = shift.tolist() def _move_x(x): return float(pad * size + (1. - 2. * pad) * size * ((x - minx) / longer + shiftx)) def _move_y(y): return float(size - (pad * size + (1. - 2. * pad) * size * ((y - miny) / longer + shifty))) def _move_xy(xy): return (_move_x(xy[0]), _move_y(xy[1])), (_move_x(xy[2]), _move_y(xy[3])) def _norm(v): return v / np.sqrt(np.sum(v**2.)) def _adjust(points): l1, l2, p2, p1 = np.array(points) r = p2 - l2 u = l2 - l1 l1 += _norm(-r - u) * 0.01 * size l2 += _norm(-r + u) * 0.01 * size p2 += _norm(r + u) * 0.01 * size p1 += _norm(r - u) * 0.01 * size return [x.tolist() for x in (l1, l2, p2, p1)] for j, (l, p) in enumerate( zip(self.left_bounds[i, ...], self.right_bounds[i, ...])): l_1, l_2 = _move_xy(l) p_1, p_2 = _move_xy(p) imgs[i].add(imgs[i].polygon( points=_adjust([l_1, l_2, p_2, p_1]), fill=svg.rgb(70, 70, 70) if (j // 5) % 2 == 0 else svg.rgb(50, 50, 50))) # draw every segment of first track # for x1, y1, x2, y2 in self.bounds[i * self.num_players, :, :]: # imgs[i].add(imgs[i].line((_move_x(x1), _move_y(y1)), (_move_x(x2), _move_y(y2)), # style='stroke:rgb(5, 5, 5, 255), stroke-width:1')) f1, f2 = _move_xy(self.reward_bound[i * self.num_players, 0, :]) fl, fr = np.array(f1), np.array(f2) r = _norm(fr - fl) * 0.01 * size fl -= r fr += r perp = (np.array([fl[1] - fr[1], -(fl[0] - fr[0])]) * 0.22).astype( np.int32) x_steps, y_steps = 2, 7 xx_step, yy_step = perp / x_steps, (fr - fl) / y_steps for xx in range(x_steps): for yy in range(y_steps): p = fl + xx * xx_step + yy * yy_step points = np.stack((p, p + xx_step, p + yy_step + xx_step, p + yy_step)).tolist() imgs[i].add(imgs[i].polygon( points=points, fill=svg.rgb(20, 20, 20) if (xx % 2 == 0) == (yy % 2 == 0) else svg.rgb(210, 210, 210))) # cv2.line(imgs[i], (_move_x(fx1), _move_y(fy1)), (_move_x(fx2), _move_y(fy2)), (0, 0, 145, 255), # thickness=1, lineType=cv2.LINE_AA) return imgs
import svgwrite from svgwrite import mm my_opart = svgwrite.Drawing("kurs_27_opart.svg") count = 16 anfangsbreite = 10 hoehe = 10 xstart = 5 ystart = 5 zoom = 0.75 xdelta = anfangsbreite xkoord = xstart # spalten in der zeile x for x in range(count // 2): # zeilen in der spalte y rechtecke in einer spalte zeichnen for y in range(count // 2): # print(xdelta) # even (gerade), in zweiter zeile anfangen xevenkoord = xkoord # print(xevenkoord) ykoord = ystart + hoehe + hoehe * 2 * y my_even_col = my_opart.rect( insert=(xevenkoord * mm, ykoord * mm), size=(xdelta * mm, hoehe * mm), fill='black',
def write( vector_data: VectorData, output, single_path: bool, page_format: str, landscape: bool, center: bool, ): """ Save geometries to a SVG file. By default, the SVG generated has bounds tightly fit around the geometries. Optionally, a page format can be provided (`--page-format`). In this case, the geometries are not scaled or translated by default, even if they lie outside of the page bounds. The `--center` option translates the geometries to the center of the page. If output path is `-`, SVG content is output on stdout. """ if vector_data.is_empty(): logging.warning("no geometry to save, no file created") return vector_data # compute bounds bounds = vector_data.bounds() if page_format != "tight": size = tuple(c * 96.0 / 25.4 for c in PAGE_FORMATS[page_format]) if landscape: size = tuple(reversed(size)) else: size = (bounds[2] - bounds[0], bounds[3] - bounds[1]) if center: corrected_vector_data = copy.deepcopy(vector_data) corrected_vector_data.translate( (size[0] - (bounds[2] - bounds[0])) / 2.0 - bounds[0], (size[1] - (bounds[3] - bounds[1])) / 2.0 - bounds[1], ) elif page_format == "tight": corrected_vector_data = copy.deepcopy(vector_data) corrected_vector_data.translate(-bounds[0], -bounds[1]) else: corrected_vector_data = vector_data # output SVG dwg = svgwrite.Drawing(size=size, profile="tiny", debug=False) dwg.attribs[ "xmlns:inkscape"] = "http://www.inkscape.org/namespaces/inkscape" for layer_id in sorted(corrected_vector_data.layers.keys()): layer = corrected_vector_data.layers[layer_id] group = dwg.g(style="display:inline", id=f"layer{layer_id}") group.attribs["inkscape:groupmode"] = "layer" group.attribs["inkscape:label"] = str(layer_id) if single_path: group.add( dwg.path( " ".join(("M" + " L".join(f"{x},{y}" for x, y in as_vector(line))) for line in layer), fill="none", stroke="black", )) else: for line in layer: group.add( dwg.path( "M" + " L".join(f"{x},{y}" for x, y in as_vector(line)), fill="none", stroke="black", )) dwg.add(group) dwg.write(output, pretty=True) return vector_data
import svgwrite drawObj = svgwrite.Drawing('username.svg', profile='tiny', width=444, height=300) drawObj.add(drawObj.text('Test', insert=(15, 64), fill='red', font_size=70, font_family='sans-serif', font_weight='bold')) drawObj.add(drawObj.line((10, 10), (10, 70), stroke=svgwrite.rgb(0, 0, 0, '%'))) drawObj.add(drawObj.line((10, 70), (370, 70), stroke=svgwrite.rgb(0, 0, 0, '%'))) drawObj.save()
# output.writerow([''] + list(resMap.keys())) # # for first_vertex in resMap: # matrix_row = [] # for second_vertex in resMap: # if second_vertex in resMap[first_vertex]: # matrix_row.append(1) # else: # matrix_row.append(0) # output.writerow([first_vertex] + list(matrix_row)) scale = 2000.0 scaleLat = (maxlat - minlat) / scale scaleLong = (maxlong - minlong) / scale resGraph = svgwrite.Drawing("city_graph_with_paths.svg", size=(str(scale) + 'px', str(scale) + 'px')) for first_point in resMap: # resGraph.add(resGraph.circle((scale - (maxlong - coordMap[first_point][1]) / scaleLong, # (maxlat - coordMap[first_point][0]) / scaleLat), 2)) for second_point in resMap[first_point]: # resGraph.add(resGraph.circle((scale - (maxlong - coordMap[second_point][1]) / scaleLong, # (maxlat - coordMap[second_point][0]) / scaleLat), 2)) resGraph.add( resGraph.line( (scale - (maxlong - coordMap[first_point][1]) / scaleLong, (maxlat - coordMap[first_point][0]) / scaleLat), (scale - (maxlong - coordMap[second_point][1]) / scaleLong, (maxlat - coordMap[second_point][0]) / scaleLat), stroke="black"))
def gasket(): venturiRadius = 20 screwRadius = 5 shoulder = 10 screwOffset = 40 dwg = svgwrite.Drawing('gasket.svg') venturiHole = dwg.circle([0, 0], venturiRadius, fill='none', stroke='blue', stroke_width=.1) leftScrew = dwg.circle([-screwOffset, 0], screwRadius, fill='none', stroke='blue', stroke_width=.1) righttScrew = dwg.circle([screwOffset, 0], screwRadius, fill='none', stroke='blue', stroke_width=.1) leftShoulder = dwg.circle([-screwOffset, 0], screwRadius + shoulder, fill='none', stroke='blue', stroke_width=.1) rightShoulder = dwg.circle([screwOffset, 0], screwRadius + shoulder, fill='none', stroke='blue', stroke_width=.1) outerShoulder = dwg.circle([0, 0], venturiRadius + shoulder, fill='none', stroke='blue', stroke_width=.1) # center hole dwg.add(venturiHole) # screw holes dwg.add(leftScrew) dwg.add(righttScrew) # left/right edges #dwg.add(leftShoulder) #dwg.add(rightShoulder) # top/bottom edge #dwg.add(outerShoulder) # join up the edges lsleft = svgTangents(leftShoulder, outerShoulder) # decorate the tangents as you wish lsleft[0]['fill'] = 'none' lsleft[0]['stroke'] = 'orange' lsleft[0]['stroke-width'] = 0.1 lsleft[1]['fill'] = 'none' lsleft[1]['stroke'] = 'purple' lsleft[1]['stroke-width'] = 0.1 dwg.add(lsleft[0]) dwg.add(lsleft[1]) # build arc from left shoulder p = svgArcBuild(leftShoulder, lsleft, beginFlag=False, largeFlag=False) p['fill'] = 'none' p['stroke'] = 'orange' p['stroke-width'] = 0.1 dwg.add(p) lsright = svgTangents(rightShoulder, outerShoulder) # decorate the tangents as you wish lsright[0]['fill'] = 'none' lsright[0]['stroke'] = 'orange' lsright[0]['stroke-width'] = 0.1 lsright[1]['fill'] = 'none' lsright[1]['stroke'] = 'purple' lsright[1]['stroke-width'] = 0.1 dwg.add(lsright[0]) dwg.add(lsright[1]) # build arc from right shoulder p = svgArcBuild(rightShoulder, lsright, beginFlag=False, largeFlag=False) p['fill'] = 'none' p['stroke'] = 'orange' p['stroke-width'] = 0.1 dwg.add(p) # build arc from outershoulder and top tangents p = svgArcBuild(outerShoulder, [lsright[0], lsleft[1]], largeFlag=False, leftFlag=False) p['fill'] = 'none' p['stroke'] = 'green' p['stroke-width'] = 0.2 dwg.add(p) # build arc from outershoulder and bottom tangents p = svgArcBuild(outerShoulder, [lsright[1], lsleft[0]], largeFlag=False) p['fill'] = 'none' p['stroke'] = 'green' p['stroke-width'] = 0.2 dwg.add(p) dwg.save()
def visualizeOfftargets(infile, outfile, title, PAM): output_folder = os.path.dirname(outfile) if not os.path.exists(output_folder): os.makedirs(output_folder) # Get offtargets array from file offtargets, target_seq, total_seq = parseSitesFile(infile) # Initiate canvas dwg = svgwrite.Drawing(outfile + '.svg', profile='full', size=(u'110%', 100 + (total_seq + 3) * (box_size + 1))) if title is not None: # Define top and left margins x_offset = 20 y_offset = 50 dwg.add( dwg.text(title, insert=(x_offset, 30), style="font-size:20px; font-family:Courier")) else: # Define top and left margins x_offset = 20 y_offset = 20 # Draw ticks # if target_seq.find('N') >= 0: # p = target_seq.index('N') # if p > len(target_seq) / 2: # PAM on the right end # tick_locations = [1, len(target_seq)] + range(p, len(target_seq)) # limits and PAM # tick_locations += [x + p - 20 + 1 for x in range(p)[::10][1:]] # intermediate values # tick_locations = list(set(tick_locations)) # tick_locations.sort() # tick_legend = [p, 10, 1] + ['P', 'A', 'M'] # else: # tick_locations = range(2, 6) + [14, len(target_seq)] # complementing PAM and limits # tick_legend = ['P', 'A', 'M', '1', '10'] + [str(len(target_seq) - 4)] # for x, y in zip(tick_locations, tick_legend): # dwg.add(dwg.text(y, insert=(x_offset + (x - 1) * box_size + 2, y_offset - 2), style="font-size:10px; font-family:Courier")) # else: # tick_locations = [1, len(target_seq)] # limits # tick_locations += range(len(target_seq) + 1)[::10][1:] # tick_locations.sort() # for x in tick_locations: # dwg.add(dwg.text(str(x), insert=(x_offset + (x - 1) * box_size + 2, y_offset - 2), style="font-size:10px; font-family:Courier")) ## Assume PAM is on the right end Yichao rewrite visualization code, generic PAM ## PAM can be on the left or right, Yichao 0713 tick_locations = [] tick_legend = [] # PAM_index = target_seq.index(PAM) PAM_index = find_PAM(target_seq, PAM) count = 0 for i in range(PAM_index, 0, -1): count = count + 1 if count % 10 == 0: tick_legend.append(count) # print (count,i) tick_locations.append(i) tick_legend += ['P', 'A', 'M'] + ['-'] * (len(PAM) - 3) tick_locations += range(PAM_index + 1, len(target_seq) + 1) if PAM_index == 0: tick_legend = [] tick_locations = [] tick_legend += ['P', 'A', 'M'] + ['-'] * (len(PAM) - 3) tick_locations += range(1, len(PAM) + 1) count = 0 for i in range(len(PAM) + 1, len(target_seq) + 1): count = count + 1 if count % 10 == 0 or count == 1: tick_legend.append(count) # print (count,i) tick_locations.append(i) # print (zip(tick_locations, tick_legend)) for x, y in zip(tick_locations, tick_legend): dwg.add( dwg.text(y, insert=(x_offset + (x - 1) * box_size + 2, y_offset - 2), style="font-size:10px; font-family:Courier")) # Draw reference sequence row for i, c in enumerate(target_seq): y = y_offset x = x_offset + i * box_size dwg.add(dwg.rect((x, y), (box_size, box_size), fill=colors[c])) dwg.add( dwg.text(c, insert=(x + 3, y + box_size - 3), fill='black', style="font-size:15px; font-family:Courier")) #dwg.add(dwg.text('Reads', insert=(x_offset + box_size * len(target_seq) + 16, y_offset + box_size - 3), style="font-size:15px; font-family:Courier")) names = title.split(",") offset_steps = 0 for n in names: dwg.add( dwg.text(n, insert=(x_offset + box_size * len(target_seq) + 16 + offset_steps, y_offset + box_size - 3), style="font-size:15px; font-family:Courier")) offset_steps = offset_steps + 96 # Draw aligned sequence rows y_offset += 1 # leave some extra space after the reference row line_number = 0 # keep track of plotted sequences for j, seq in enumerate(offtargets): realigned_target_seq = offtargets[j]['realigned_target_seq'] no_bulge_offtarget_sequence = offtargets[j]['seq'] bulge_offtarget_sequence = offtargets[j]['bulged_seq'] if no_bulge_offtarget_sequence != '': k = 0 line_number += 1 y = y_offset + line_number * box_size for i, (c, r) in enumerate( zip(no_bulge_offtarget_sequence, target_seq)): x = x_offset + k * box_size if r == '-': if 0 < k < len(target_seq): x = x_offset + (k - 0.25) * box_size dwg.add( dwg.rect((x, box_size * 1.4 + y), (box_size * 0.6, box_size * 0.6), fill=colors[c])) dwg.add( dwg.text( c, insert=(x + 1, 2 * box_size + y - 2), fill='black', style="font-size:10px; font-family:Courier")) elif c == r: dwg.add( dwg.text(u"\u2022", insert=(x + 4.5, 2 * box_size + y - 4), fill='black', style="font-size:10px; font-family:Courier")) k += 1 elif r == 'N': dwg.add( dwg.text(c, insert=(x + 3, 2 * box_size + y - 3), fill='black', style="font-size:15px; font-family:Courier")) k += 1 else: dwg.add( dwg.rect((x, box_size + y), (box_size, box_size), fill=colors[c])) dwg.add( dwg.text(c, insert=(x + 3, 2 * box_size + y - 3), fill='black', style="font-size:15px; font-family:Courier")) k += 1 if bulge_offtarget_sequence != '': k = 0 line_number += 1 y = y_offset + line_number * box_size for i, (c, r) in enumerate( zip(bulge_offtarget_sequence, realigned_target_seq)): x = x_offset + k * box_size if r == '-': if 0 < k < len(realigned_target_seq): x = x_offset + (k - 0.25) * box_size dwg.add( dwg.rect((x, box_size * 1.4 + y), (box_size * 0.6, box_size * 0.6), fill=colors[c])) dwg.add( dwg.text( c, insert=(x + 1, 2 * box_size + y - 2), fill='black', style="font-size:10px; font-family:Courier")) elif c == r: dwg.add( dwg.text(u"\u2022", insert=(x + 4.5, 2 * box_size + y - 4), fill='black', style="font-size:10px; font-family:Courier")) k += 1 elif r == 'N': dwg.add( dwg.text(c, insert=(x + 3, 2 * box_size + y - 3), fill='black', style="font-size:15px; font-family:Courier")) k += 1 else: dwg.add( dwg.rect((x, box_size + y), (box_size, box_size), fill=colors[c])) dwg.add( dwg.text(c, insert=(x + 3, 2 * box_size + y - 3), fill='black', style="font-size:15px; font-family:Courier")) k += 1 # added by jiajian, 20200913 offset_steps = 0 for c in seq['counts']: reads_text = dwg.text( c, insert=(box_size * (len(target_seq) + 1) + 20 + offset_steps, y_offset + box_size * (j + 3) - 2), fill='black', style="font-size:15px; font-family:Courier") offset_steps = offset_steps + 96 dwg.add(reads_text) #if no_bulge_offtarget_sequence == '' or bulge_offtarget_sequence == '': # reads_text = dwg.text(str(seq['reads']), insert=(box_size * (len(target_seq) + 1) + 20, y_offset + box_size * (line_number + 2) - 2), # fill='black', style="font-size:15px; font-family:Courier") # dwg.add(reads_text) #else: # reads_text = dwg.text(str(seq['reads']), insert=(box_size * (len(target_seq) + 1) + 20, y_offset + box_size * (line_number + 1) + 5), # fill='black', style="font-size:15px; font-family:Courier") # dwg.add(reads_text) # reads_text02 = dwg.text(u"\u007D", insert=(box_size * (len(target_seq) + 1) + 7, y_offset + box_size * (line_number + 1) + 5), # fill='black', style="font-size:23px; font-family:Courier") # dwg.add(reads_text02) # added by jiajian, 2020.09.13 copy_y = y_offset + box_size * (total_seq + 1) + 5 copy_right_text = dwg.text( "Author: [email protected] (*)", insert=(box_size * (len(target_seq) + 1) + 20 + offset_steps, copy_y + (offset_steps / 96) * 15 + 15), fill='black', style="font-size:15px; font-family:Courier") dwg.add(copy_right_text) blank_line = dwg.text( "Dr. Jiajian ZHOU @SMU.China ", insert=(box_size * (len(target_seq) + 1) + 20 + offset_steps, copy_y + (offset_steps / 96) * 15 + 15 * 3), fill='black', style="font-size:15px; font-family:Courier") dwg.add(blank_line) dwg.save()
reverse=True ) #Sort sequence lengths in descending order to find the longest sequence length LONGEST_SEQ = SEQUENCE_LENGTHS[ 0] #Use the longest sequence to generate the width of the svg canvas NUM_SEQS = len( SEQUENCE_IDS ) #Use the number of sequences to generate the length of the svg canvas LONGEST_ID_LEN = len( max(SEQUENCE_IDS, key=len) ) #Create an integer variable which contains the length of the longest string - this is to be used to appropriately format the width of the canvas. LINE_SCAFFOLD_START = (LONGEST_ID_LEN * 10) + 5 #CREATE SVG CANVAS svgdoc = svgwrite.Drawing( filename="test_drawing.svg", size=(((LONGEST_ID_LEN * 10) + LONGEST_SEQ + (LONGEST_SEQ * (1 / 20))), NUM_SEQS * 30) ) #At size 10 arial bold, the W glyph is 9.43px -- therefor the x for scaffold size is loaded as a function of (longest length sequence name * 10) + (length of longest sequence) + (Addition 5% of the length of the longest seq to account for trim). Y scaffold size is loaded as the number of sequences * 30 (15 above and below scaffold line) for appropriate spacing. Final 5 accounts for the spacing between text and the line object. #Create TEXT AND LINE-SCAFFOLD PER SEQUENCE for SEQi in range( len(SEQLEN_DICT) ): #Iterate numerically through a series of numbers equal to the number of unique sequence svgdoc.add( svgdoc.text( #Create the text for the sequence scaffold str(SEQUENCE_IDS[SEQi]), #Load text insert=((LONGEST_ID_LEN * 10), ((SEQi * 30) + 15)), #Place cursor stroke='none', #No stroke on text fill=svgwrite.rgb(0, 0, 0), #Write letters in black with no stroke alignment_baseline= "middle", #Positioning baseline is set to the middle of the written text
def __init__(self): self.dwg = svgwrite.Drawing(size=(100, 100)) self.palette = Palette()
def project_badge(request, group_slug, project_slug): group = Group.objects.get(slug=group_slug) project = group.projects.get(slug=project_slug) status = ProjectStatus.objects.filter( build__project=project, finished=True).order_by("-build__datetime").first() title_text = project.slug if request.GET and 'title' in request.GET.keys(): title_text = request.GET['title'] badge_text = "no results found" if status: badge_text = "pass: %s, fail: %s, xfail: %s, skip: %s" % \ (status.tests_pass, status.tests_fail, status.tests_xfail, status.tests_skip) badge_colour = "#999" pass_rate = -1 if status and status.tests_total: pass_rate = 100 * float(status.tests_pass) / float(status.tests_total) badge_colour = "#f0ad4e" if status.tests_fail == 0: badge_colour = "#5cb85c" if status.tests_pass == 0: badge_colour = "#d9534f" if request.GET: if 'passrate' in request.GET.keys() and pass_rate != -1: badge_text = "%.2f%%" % (pass_rate) elif 'metrics' in request.GET.keys( ) and status is not None and status.has_metrics: badge_text = str(status.metrics_summary) badge_colour = "#5cb85c" font_size = 110 character_width = font_size / 2 padding_width = character_width title_width = len(title_text) * character_width + 2 * padding_width title_x = title_width / 2 + padding_width badge_width = len(badge_text) * character_width + 2 * padding_width badge_x = badge_width / 2 + 3 * padding_width + title_width total_width = (title_width + badge_width + 4 * padding_width) / 10 dwg = svgwrite.Drawing("test_badge.svg", (total_width, 20)) a = dwg.add(dwg.clipPath()) a.add(dwg.rect(rx=3, size=(total_width, 20), fill="#fff")) b = dwg.add(dwg.linearGradient(end=(0, 1), id="b")) b.add_stop_color(0, "#bbb", 0.1) b.add_stop_color(1, None, 0.1) g1 = dwg.add(dwg.g(clip_path=a.get_funciri())) g1.add( dwg.path(fill="#555", d=[ 'M0', '0h', '%sv' % ((2 * padding_width + title_width) / 10), '20H', '0z' ])) g1.add( dwg.path(fill=badge_colour, d=[ 'M%s' % ((2 * padding_width + title_width) / 10), '0h', '%sv' % ((2 * padding_width + badge_width) / 10), '20H', '%sz' % ((2 * padding_width + title_width) / 10) ])) g1.add( dwg.path(fill=b.get_funciri(), d=['M0', '0h', '%sv' % total_width, '20H', '0z'])) g2 = dwg.add( dwg.g(fill="#fff", text_anchor="middle", font_family="monospace", font_size=font_size)) g2.add( dwg.text(title_text, x=[title_x], y=[150], fill="#010101", fill_opacity=".3", transform="scale(.1)", textLength=title_width)) g2.add( dwg.text(title_text, x=[title_x], y=[140], transform="scale(.1)", textLength=title_width)) g2.add( dwg.text(badge_text, x=[badge_x], y=[150], fill="#010101", fill_opacity=".3", transform="scale(.1)", textLength=badge_width)) g2.add( dwg.text(badge_text, x=[badge_x], y=[140], transform="scale(.1)", textLength=badge_width)) badge = dwg.tostring() return HttpResponse(badge, content_type="image/svg+xml")
def create_svg(name): """ Create many circles in a curling tentril fashion. """ global file_log global dwg svg_size_width = 900 svg_size_height = 900 dwg = svgwrite.Drawing(name, (svg_size_width, svg_size_height), debug=True) # Background will be black so the background does not overwhelm the colors. dwg.add( dwg.rect(insert=(0, 0), size=('100%', '100%'), rx=None, ry=None, fill='black')) #angle_max = 2*math.pi # maximum angle allowed. 360 degrees. #angle_min = -1 * angle_max # minimum angle allowed -360 degrees. #file_log = open("tendriles_branch.log", "w") # Create effect instance and apply it. # option values. n = 100 # number of circles default 100 #n = 20 # number of circles default 100 num_arms = 5 # number of tendriles default 5 #num_arms = 10 # number of tendriles default 5 #num_arms = 1 # number of tendriles default 5 d_width = svg_size_width d_height = svg_size_height ########################### #x_org = d_height / 10 #y_org = d_width / 10 #delta_x = d_width / 6 #delta_y = d_width / 10 ########################### stroke_width = 1 #n = 200 #number of circles #n = 75 #number of circles #num_arms = 9 #step = 0.05 #step = 0.02 step = 4.0 / n #curl = 1.0 #c_width= d_width/12.0 #c_width= d_width/50.0 green_light1 = ( 102, 229, 132 ) # starting colour. Colour will linearly change to ending colour. green_dark1 = (25, 76, 37) salmon1 = (240, 184, 178) pink1 = (251, 170, 176) pink2 = (255, 170, 204) pink2light = (255, 215, 231) pink2dsat = (247, 225, 234) blue1 = (193, 197, 251) grey7_5 = (236, 236, 236) grey80 = (51, 51, 51) # starting colour. Colour will linearly change to ending colour. #start_colour = pink2light #end_colour = blue1 start_colour = green_dark1 end_colour = green_light1 #distance = 9.0 #distance = c_width/3.0 # The next circle is 1/3 the original circle's width from the centre. #n - number of circles in each tendrile. #num_arms - number of arms that is tendriles. # x, y - centre of current circle, 0,0 is top left of screen # c_width - initial circle width. # r - radius of current circle. gradually decreases. # distance - length to next circle. # angle - angle to next circle. value -pi to +pi. # step - range of randomness of angle. constant. # curl - how much curl will happen. constant. .1*curl incremented to v, angle. # v - change in angle. random value -step to +step plus curl # can_branch - true or false. Can this tendrile branch? can_branch = True #can_branch = False ########################### # The change in the starting colour is small so all of the tenticles seem like a group but # still have a very slight variation to give individuality. If the starting colour is too # different the arms look like they are not connected at the centre. #start_lin_colour = gen_colour(start_colour, blue1, num_arms) # debug start_lin_colour = gen_colour(start_colour, end_colour, num_arms * 8) # Create all tendriles for j in range(num_arms): # set start of arm x y x = d_height / 2 y = d_width / 2 angle = random.uniform( (-1.0 * math.pi), math.pi) # random angle in radians. 2*pi radians = 360 degrees v = 0.0 # variety to the size of the starting circle c_width = random.uniform((d_width * .015), (d_width * .025)) r = random.uniform((c_width * .9), (c_width * 1.1)) new_start_colour = next(start_lin_colour) #curl = random.choice((-1, 1)) # random.choice picks random item from list #curl = random.choice((-1.1, 1.1)) # random.choice picks random item from list #curl = random.choice((-1.05, 1.05)) # random.choice picks random item from list #curl = 1.1 curl = 1.0 # create a tendrile tend = tendrile(x, y, r, angle, step, v, curl, n, new_start_colour, end_colour, can_branch) #tend = tendrile(x, y, r, angle, step, v, curl, n, blue1, end_colour, can_branch) # create the tendrile as svg elements tend.create() # draw the tendrile as svg elements tend.draw() #file_log.close() dwg.save()
def renderToFile(self, filepath, margin, width=None, height=None, maxWidth=None, maxHeight=None, padding=None, timing=None): ''' Padding in css order: top, right, bottom, left. ''' if timing is not None: timing.mark('TFSSvg.renderToFile.0') margin = round(margin) # height = round(height) # maxWidth = round(maxWidth) if padding is None: padding = ( 0, 0, 0, 0, ) topPadding, rightPadding, bottomPadding, leftPadding = [ int(round(value)) for value in padding ] # print 'margin, height, maxWidth', margin, height, maxWidth minmax = None for item in self.items: if minmax is None: minmax = item.minmax() else: minmax = minmaxMerge(minmax, item.minmax()) # #minmax = item.minmax() # if minmax == None: itemsWidth = 500 itemsHeight = 500 else: itemsWidth = (minmax.maxX - minmax.minX) itemsHeight = (minmax.maxY - minmax.minY) hSpacing = (2 * margin + leftPadding + rightPadding) vSpacing = (2 * margin + topPadding + bottomPadding) if maxWidth is None: maxWidth = width if maxHeight is None: maxHeight = height if maxWidth is None or maxHeight is None: raise Exception( 'Unknown combination of arguments: width: %s, height: %s, maxWidth: %s, maxHeight: %s' % ([ str(value) for value in ( width, height, maxWidth, maxHeight, ) ])) scalingX = (maxWidth - hSpacing) / itemsWidth scalingY = (maxHeight - vSpacing) / itemsHeight scaling = min(scalingX, scalingY) if width is None: width = math.ceil(itemsWidth * scaling) + hSpacing if height is None: height = math.ceil(itemsHeight * scaling) + vSpacing # if width is not None and height is not None: # pass ## contentWidth = width - (2 * margin + leftPadding + rightPadding) ## contentHeight = height - (2 * margin + topPadding + bottomPadding) # elif height is not None and maxWidth is not None: # scalingX = (maxWidth - hSpacing) / itemsWidth # scalingY = (height - vSpacing) / itemsHeight # scaling = min(scalingX, scalingY) # contentWidth = math.ceil(itemsWidth * scaling) # width = contentWidth + hSpacing # elif maxWidth is not None and maxHeight is not None: # scalingX = (maxWidth - hSpacing) / itemsWidth # scalingY = (maxHeight - vSpacing) / itemsHeight # scalingX = (maxWidth - vSpacing) / (minmax.maxX - minmax.minX) # scalingY = (height - hSpacing) / (minmax.maxY - minmax.minY) # scaling = min(scalingX, scalingY) # contentWidth = math.ceil((minmax.maxX - minmax.minX) * scaling) # contentHeight = math.ceil((minmax.maxY - minmax.minY) * scaling) # width = contentWidth + 2 * margin # else: # raise Exception('Unknown combination of arguments: width: %s, height: %s, maxWidth: %s, maxHeight: %s' % ( [str(value) for value in ( width, height, maxWidth, maxHeight, ) ] ) ) contentWidth = width - hSpacing contentHeight = height - vSpacing width = int(round(width)) height = int(round(height)) contentWidth = int(round(contentWidth)) contentHeight = int(round(contentHeight)) scalingX = contentWidth / itemsWidth scalingY = contentHeight / itemsHeight scaling = min(scalingX, scalingY) # print 'scaling, contentWidth, contentHeight', scaling, contentWidth, contentHeight svg_document = svgwrite.Drawing(filename=filepath, size=( formatSvgPixels(width), formatSvgPixels(height), )) if self.backgroundColor is not None: fillSvgRect(svg_document, 0, 0, width, height, self.backgroundColor) def pointFunc(point): x, y = point.x, point.y x -= minmax.minX y -= minmax.minY x *= scaling y *= scaling x += math.floor((width - contentWidth) / 2) y += math.floor((height - contentHeight) / 2) return TFSPoint(x, y) # return TFSPoint(margin + scaling * (point.x - minmax.minX), # math.floor((height - contentHeight) / 2) + scaling * (point.y - minmax.minY)) if timing is not None: timing.mark('TFSSvg.renderToFile.6') for item in self.items: item.resetRenderState() item.applyFunction(pointFunc) # item.translate(TFSPoint(-minmax.minX, # -minmax.minY)) # item.scale(scaling) # item.translate(TFSPoint(margin, # math.floor((height - contentHeight) / 2))) item.render(svg_document) if timing is not None: timing.mark('TFSSvg.renderToFile.7') if self.borderColor is not None: drawSvgRect(svg_document, 0, 0, width, height, self.borderColor) if timing is not None: timing.mark('TFSSvg.renderToFile.8') # svg_document.save() # if timing is not None: # timing.mark('TFSSvg.renderToFile.9') # # svg_document.tostring() if filepath is not None: svg_document.save() result = None else: result = svg_document.tostring() if timing is not None: timing.mark('TFSSvg.renderToFile.9') return result