Beispiel #1
0
def run_script(args):

    
    matplotlib.interactive(False)
        
    left = (args.left[0], args.left[1])
    right = (args.right[0], args.right[1])


    l1 = (150,110,110)
    l2 = (110,150,110)
    l3 = (110,110,150)
    layers= [l1,l2]

    # This is a hack to conserve colors
    colourmap = { rgb(l1[0],l1[1],l1[2]): args.Rock0,
                  rgb(l2[0],l2[1],l2[2]): args.Rock1 }
    
    if not isinstance(args.Rock2, str):
        colourmap[rgb( l3[0],l3[1],l3[2])] = args.Rock2
        layers.append( l3 )
    
    model = mb.body( traces = args.ntraces,
                     pad = args.pad,
                     margin=args.margin,
                     left = left,
                     right = right,
                     layers = layers
                   )

    return modelr_plot(model, colourmap, args)
Beispiel #2
0
def writeShape(shape, params):
	if isinstance(shape, list):
		for i in shape:
			writeShape(i, params)
	elif isinstance(shape, tuple):
		if len(shape) == 2:
			x, y = shape
			c = 0
		elif len(shape) == 3:
			x, y, c = shape
		else:
			raise Exception('Invalid point {}'.format(shape))
		x = (x * params['scale']) + (params['size'] / 2)
		y = (-y * params['scale']) + (params['size'] / 2)
		c = (c - params['colour_min']) / params['colour_range']
		if 0 < x < params['size'] and 0 < y < params['size']:
			r, g, b = colorsys.hsv_to_rgb(c, 1, 1)
			params['svg'].add(params['svg'].circle(center = (x, y), r = 1, stroke = svgwrite.rgb(r * 255, g * 255, b * 255)))
	elif isinstance(shape, data.Line):
		for (x1, y1), (x2, y2) in zip(shape.points[:-1], shape.points[1:]):
			x1 = (x1 * params['scale']) + (params['size'] / 2)
			y1 = (-y1 * params['scale']) + (params['size'] / 2)
			x2 = (x2 * params['scale']) + (params['size'] / 2)
			y2 = (-y2 * params['scale']) + (params['size'] / 2)
			if 0 < x1 < params['size'] and 0 < y1 < params['size'] and 0 < x2 < params['size'] and 0 < y2 < params['size']:
				params['svg'].add(params['svg'].line((x1, y1), (x2, y2), stroke = svgwrite.rgb(255, 0, 0)))
	else:
		print('Cannot plot type', type(shape))
Beispiel #3
0
 def svg_shape(self):
     """return the SVG shape that this object represents"""
     r, g, b = my_colormap[self.label]
     x, y, dx, dy = self.get_rect_data()
     return svgwrite.shapes.Rect(
         insert=(x, y), size=(dx, dy), stroke=svgwrite.rgb(r, g, b, "RGB"), fill=svgwrite.rgb(r, g, b, "RGB")
     )
Beispiel #4
0
    def graphic_output(self):

        cell_size = 100
        canvas_width = self.grid_width * cell_size
        canvas_height = self.grid_height * cell_size

        fname = "graph i=" + str(self.number_of_iterations_yet) + " width=" + str(canvas_width) + " height=" +str(canvas_height) + ".svg"

        dwg = svgwrite.Drawing(filename = fname, size = (canvas_width, canvas_height), debug = True)

        # Draw horizontal grid lines
        #for x in range(0, self.grid_width):
        #    dwg.add( dwg.line((x*cell_size, 0), (x*cell_size, canvas_height), stroke=svgwrite.rgb(0, 0, 0, "%")) )

        #for y in range(0, self.grid_height):
        #    dwg.add( dwg.line((0, y*cell_size), (canvas_width, y*cell_size), stroke=svgwrite.rgb(0, 0, 0, "%")) )

        for row in self.grid:
            for square in row:
                shapes = dwg.add(dwg.g(id='shapes', fill='red'))
                color_numerator = float(square.get_utility())  if type(square.get_utility()) is IntType else 0
                color_denominator = 2
                fill_color = svgwrite.rgb(255, 255, 255)
                if color_numerator > 0:
                    fill_color = svgwrite.rgb(255-250*(color_numerator/color_denominator), 220, 255-200*(color_denominator/color_denominator))
                elif color_numerator < 0:
                    fill_color = svgwrite.rgb(220, 255-250*(abs(color_numerator)/color_denominator), 255-250*(abs(color_numerator)/color_denominator) )

                shapes.add( dwg.rect(insert=(square.x*cell_size, square.y*cell_size), size=(cell_size, cell_size), fill=fill_color) )
                paragraph = dwg.add(dwg.g(font_size=16))
                paragraph.add(dwg.text(square.get_utility(), ( (square.x + 0.5) * cell_size, (square.y + 0.5) * cell_size)))

        dwg.save()
        print "grid.graphic_output() successful"
        return 0
Beispiel #5
0
def printmatrixmonthly(m,d): #matrix, drawing
	x_pos = 0
	y_pos = 0
	yearnum = 0		
	for y in m: #for every year in the matrix		
		curmo = 1
		weeknum = 0
		x_pos = 0
		#print(yearnum+startyear)
		for w in y: #for every week in the year
			#print(weeknum)			
			if(isnewmonth(yearnum+startyear,weeknum+1,curmo)):
				x_pos = 0				
				curmo += 1
				y_pos += shape_size + 2 #new month			
				#d.add(d.text(curmo, insert=(x_pos, y_pos), fill='red'))
				#x_pos += 5
			typecount = 0	
			for t in w: #for every square count in the week
				n = 0 #count number of squares				
				while n < t:
					#d.add(d.rect((x_pos, y_pos), (shape_size, shape_size), fill=svgwrite.rgb(worktypes[typecount][1], worktypes[typecount][2], worktypes[typecount][3]))) #print square
					d.add(d.circle((x_pos, y_pos), shape_size/2, fill=svgwrite.rgb(worktypes[typecount][1], worktypes[typecount][2], worktypes[typecount][3]))) #print circle
					x_pos += shape_size + 1
					n += 1
				typecount += 1	
			weeknum += 1
		d.add(d.rect((0, y_pos+1), (6, 4), fill=svgwrite.rgb(0,0,0))) #new year marker
		y_pos += 6 #new year
		yearnum += 1
	d.save()	
def get_reflectivity(data,
                     colourmap,
                     theta=0,
                     reflectivity_method=reflection.zoeppritz
                     ):
    '''
    Create reflectivities from an image of an earth model and a
    mapping of colours to rock properties. Will find each interface
    and use the specified reflectivity method to calculate the Vp
    reflection coefficient.

    :param data: The image data of the earth model. A 3D array indexed
                 as [samples, traces, colour].
    :param colourmap: A lookup table (dict) that maps colour values to
                      rock property structures.

    :keyword theta: Angle of incidence to use reflectivity. Can be a
                  float or an array of angles [deg].
    :keyword reflectivity_method: The reflectivity algorithm to use.
                                  See bruges.reflection for methods.

    :returns: The vp reflectivity coefficients corresponding to the
             earth model. Data will be indexed as
             [sample, trace, theta]
    '''

    # Check if we only have one trace of data, and reform the array
    if(data.ndim == 2):
        reflect_data = np.zeros((data.size, 1, np.size(theta)))
        data = np.reshape(data, (data.shape[0], 1, 3))
    else:
        reflect_data = np.zeros((data.shape[0], data.shape[1],
                                np.size(theta)))

    # Make an array that only has the boundaries in it
    boundaries = get_boundaries(data)

    for i in boundaries:

        # These are the indices in data
        j = i.copy()
        j[0] += 1

        # Get the colourmap dictionary keys
        c1 = rgb(data[i[0], i[1], 0], data[i[0], i[1], 1],
                 data[i[0], i[1], 2])
        c2 = rgb(data[j[0], j[1], 0], data[j[0], j[1], 1],
                 data[j[0], j[1], 2])

        # Don't calculate if not in the cmap. If the model was
        # build properly this shouldn't happen.
        if((c1 not in colourmap) or (c2 not in colourmap)):
            continue

        # Get the reflectivity
        reflect_data[i[0], i[1], :] = rock_reflectivity(
            colourmap[c1], colourmap[c2], theta=theta,
            method=reflectivity_method)

    return reflect_data
def visualize_graph(graph, graph_parameters, output_file = None):
	if not graph_parameters.is_correct:
		raise Exception() #!!!!!
		
		
	graph_utilities = GraphUtilities(graph_parameters)
	drawing         = svgwrite.Drawing()
	
	for node in graph_utilities.nodes(graph):
		node_view_points = \
			[(node_vertex.real * 1, - node_vertex.imag * 1) for node_vertex \
				in graph_utilities.compute_node_vertices(node)]
				
		node_view = \
			svgwrite.shapes.Polygon(
				node_view_points,
				fill           = svgwrite.rgb(0, 0, 0),
				fill_opacity   = 1.0,
				stroke         = svgwrite.rgb(0, 0, 0),
				stroke_width   = 0.1,
				stroke_opacity = 1.0
			)
			
		drawing.add(node_view)
		
		
	if output_file is not None:
		drawing.write(output_file)
	else:
		return drawing
def run_script(args):
    matplotlib.interactive(False)

    """if args.transparent == 'False' or args.transparent == 'No':
        transparent = False
    else:
        transparent = True"""

    args.ntraces = 300
    args.pad = 150
    args.reflectivity_method = zoeppritz
    args.title = "Channel - angle gather (AVA)"
    args.theta = (0, 50, 0.5)
    args.wavelet = ricker
    args.wiggle_skips = 10
    args.aspect_ratio = 1
    args.thickness = 50
    args.margin = 1
    args.slice = "angle"

    transparent = False
    # This is a hack to conserve colors
    l1 = (150, 110, 110)
    l2 = (110, 150, 110)
    l3 = (110, 110, 150)
    layers = [l1, l2]
    colourmap = {rgb(150, 110, 110): args.Rock0, rgb(110, 150, 110): args.Rock1}

    if not isinstance(args.Rock2, str):
        colourmap[rgb(110, 110, 150)] = args.Rock2
        layers.append(l3)
    # Get the physical model (an array of rocks)
    model = mb.channel(pad=args.pad, thickness=args.thickness, traces=args.ntraces, layers=layers)

    return modelr_plot(model, colourmap, args)
Beispiel #9
0
 def svg_shape(self):
     """return the SVG shape that this object represents"""
     r, g, b = my_colormap[self.label]
     return svgwrite.shapes.Circle(
         center=(self.shape.x, self.shape.y),
         r=self.shape.radius,
         stroke=svgwrite.rgb(r, g, b, "RGB"),
         fill=svgwrite.rgb(r, g, b, "RGB"),
     )
Beispiel #10
0
def getline(startcoord):
    startcoord = startcoord
    endcoord = calculateEndCoord(startcoord)
    dwg.add(dwg.circle(startcoord, 2.5, stroke=svgwrite.rgb(10, 10, 16, '%'), fill='white'))
    for i in range(50):
        dwg.add(dwg.line(startcoord, endcoord, stroke=svgwrite.rgb(10, 10, 16, '%')))
        startcoord = endcoord
        endcoord = calculateEndCoord(startcoord)
    dwg.add(dwg.circle(startcoord, 2.5, stroke=svgwrite.rgb(10, 10, 16, '%'),fill='white'))
Beispiel #11
0
 def draw_grid(self):
     for i, n in enumerate(range(self.offset, self.width + 1, self.square_size)):
         self._draw_square(i, i, self.nodes[i - 1], fill='gray')
         self.dwg.add(self.dwg.line((self.offset, n),
                                    (self.width, n),
                                    stroke_width=self.line_width,
                                    stroke=svgwrite.rgb(10, 10, 16, '%')))
         self.dwg.add(self.dwg.line((n, self.offset),
                                    (n, self.height),
                                    stroke_width=self.line_width,
                                    stroke=svgwrite.rgb(10, 10, 16, '%')))
Beispiel #12
0
def plotfaces():
    for i in range(-N,N):
        for j in range(-N,N):
            if(i+j+1 <= N and i+j >= -N):
                stroke=svgwrite.rgb(10, 10, 16, '%')
                dwg.add(dwg.polygon(points=[coords(i+1,j),coords(i,j+1),coords(i,j)],fill='blue'))

    for i in range(-N,N):
        for j in range(-N,N):
            if(i+j+2 <= N and i+j+1 >= -N):
                stroke=svgwrite.rgb(10, 10, 16, '%')
                dwg.add(dwg.polygon(points=[coords(i+1,j),coords(i,j+1),coords(i+1,j+1)],fill='red'))
def zadani3_B_c():
    polomer = 100
    krok = 9
    dwg = svgwrite.Drawing("results/kulata_mriz.svg")
    offset = polomer
    for i in range(krok/2, polomer+1, krok):
        x = i
        y = (polomer**2 - x ** 2) ** 0.5
        dwg.add(dwg.line((x + offset, y + offset), (x + offset, -y + offset), stroke=svgwrite.rgb(10, 10, 16, '%')))
        dwg.add(dwg.line((-x + offset, y + offset), (-x + offset, -y + offset), stroke=svgwrite.rgb(10, 10, 16, '%')))
        dwg.add(dwg.line((-y + offset, x + offset), (y + offset, x + offset), stroke=svgwrite.rgb(10, 10, 16, '%')))
        dwg.add(dwg.line((-y + offset, -x + offset), (y + offset, -x + offset), stroke=svgwrite.rgb(10, 10, 16, '%')))
    dwg.save()
Beispiel #14
0
def channel_svg(pad, thickness, traces, layers):
    """
    Makes a rounded channel.
    Give it pad, thickness, traces, and an iterable of layers.
    Returns an SVG file.

    :param pad: The number (n) of points on top of the channel.
    :param: thickness: The radius of the channel (npoints).
    :param traces: The number of traces in the channel model.
    :param layers: An 3X3 array or tuple of RGB values corresponding
                   to each rock layer. ((R,G,B),(R,G,B),(R,G,B)).
                   Indexed as (top, channel, bottom ).

    :returns: a tempfile object pointed to the model svg file.
    """    
    
    outfile = tempfile.NamedTemporaryFile(suffix='.svg', delete=True )
    
    top_colour = rgb( layers[0][0],layers[0][1], layers[0][2] )
    body_colour = rgb( layers[1][0],layers[1][1], layers[1][2] )
    bottom_colour = rgb( layers[2][0],layers[2][1], layers[2][2] )

    
    width = traces
    height = 2.5*pad + thickness
    
    dwg = svgwrite.Drawing(outfile.name, size=(width,height),
                           profile='tiny')
    
    # Draw the bottom layer
    bottom_layer = \
      svgwrite.shapes.Rect(insert=(0,0),
                            size=(width,height)).fill(bottom_colour)
    dwg.add(bottom_layer)
    
    # Draw the body
    body = \
      svgwrite.shapes.Ellipse(center=(width/2,pad/2),
                        r=(0.3*width,pad+thickness)).fill(body_colour)
    dwg.add(body)

    # Draw the top layer
    top_layer = \
      svgwrite.shapes.Rect(insert=(0,0),
                           size=(width,pad)).fill(top_colour)
    dwg.add(top_layer)
    
    # Do this for a file
    dwg.save()
    
    return outfile
def recur_triangle():
    verts = ngram_vertexes(3, 400)
    triang = Polygon(verts)
    dwg = svgwrite.Drawing('triang.svg')
    
    offset = 0
    
    dwg.add(dwg.circle((verts[0][0] + offset, verts[0][1] + offset), r=1, stroke=svgwrite.rgb(255, 0, 0, '%')))
    dwg.add(dwg.circle((verts[1][0] + offset, verts[1][1] + offset), r=1, stroke=svgwrite.rgb(255, 0, 0, '%')))
    dwg.add(dwg.circle((verts[2][0] + offset, verts[2][1] + offset), r=1, stroke=svgwrite.rgb(255, 0, 0, '%')))
        
    
    recurse_transformations(triang, dwg, 7, 100)
    dwg.save()
Beispiel #16
0
def use(name):
    # Shows how to use the 'use' element.
    #
    w, h = '100%', '100%'
    dwg = svgwrite.Drawing(filename=name, size=(w, h), debug=True)
    dwg.add(dwg.rect(insert=(0,0), size=(w, h), fill='lightgray', stroke='black'))

    # add a group of graphic elements to the defs section of the main drawing
    g = dwg.defs.add(dwg.g(id='g001'))

    unit=40
    g.add(dwg.rect((0,0), (unit, unit)))
    for y in range(10):
        for x in range(5):
            x1 = 2*unit+2*unit*x
            y1 = 2*unit+2*unit*y
            cx = x1 + unit/2
            cy = y1 + unit/2
            cval = (y*5 + x)*2

            # reference the group by the 'use' element, you can overwrite
            # graphical properties, ...
            u = dwg.use(g, insert=(x1, y1), fill=rgb(cval, cval, cval))
            # ... and you can also transform the the whole reference object.
            u.rotate(y*5+x, center=(cx, cy))
            dwg.add(u)
    dwg.save()
Beispiel #17
0
def mandala(filename='poirot.svg'):
    '''
    Draw a mandala, inspired by Danna's.
    '''
    d = svgwrite.Drawing(filename)
    d.add(d.line((0, 0), (10, 0), stroke=svgwrite.rgb(10, 10, 16, '%')))
    d.save()
Beispiel #18
0
def renderSegments(svg, segments, offset, scale):
	for segment in segments:
			svg.add(svg.line(	mult(add(segment[0], offset), scale), 
								mult(add(segment[1], offset), scale), 
								stroke=svgwrite.rgb(0, 0, 0, '%'), 
								stroke_width=2,
								stroke_linecap="square"))
Beispiel #19
0
def print_path(path):
    print(path)
    wall=50
    for l in range(1, len(path)+1):
        dwg = svgwrite.Drawing('color_maze_solution' + str(l)+ '.svg', profile='full')
        dwg.add(dwg.line((0, 0), (0, size_X * wall), stroke=svgwrite.rgb(0, 0, 0, '%')))
        dwg.add(dwg.line((0, 0), (size_X * wall, 0), stroke=svgwrite.rgb(0, 0, 0, '%')))
        dwg.add(dwg.line((size_X * wall, size_X * wall), (size_X * wall, 0), stroke=svgwrite.rgb(0, 0, 0, '%')))
        dwg.add(dwg.line((size_X * wall, size_X * wall), (0, size_X * wall), stroke=svgwrite.rgb(0, 0, 0, '%')))
        for x in range(l):
            i=path[x][0]
            j=path[x][1]
            dwg.add(dwg.rect((j * 50, i * 50), (50, 50), fill=dict[maze[i][j]]))

        dwg.add(dwg.text("start",(10,(size_X-1)*50+25)))
        dwg.save()
Beispiel #20
0
def displaySVGPaths(pathList,*colors): #creates and saves an svf file displaying the input paths
    show_closed_discont=True
    import svgwrite
    from svgpathtools import Path, Line, CubicBezier
#    from time import strftime
#    from re import sub
#    dwg = svgwrite.Drawing('temporary_displaySVGPaths%s.svg'%time_date, size= ("%spx"%(int(xmax-xmin+1)), "%spx"%(int(ymax-ymin+1))))
#    dwg = svgwrite.Drawing('temporary_displaySVGPaths%s.svg'%time_date)
    dwg = svgwrite.Drawing('temporary_displaySVGPaths.svg')
    dwg.add(dwg.rect(insert=(0, 0), size=('100%', '100%'), rx=None, ry=None, fill='white')) #add white background
    dc = 100/len(pathList)
    for i,p in enumerate(pathList):
        if isinstance(p,Path):
            startpt = p[0].start
            ps = path2str(p)
        elif isinstance(p,Line) or isinstance(p,CubicBezier):
            startpt = p.start
            ps = path2str(p)
        else:
            startpt = parse_path(p)[0].start
            ps = p
        if colors !=tuple():
            dwg.add(dwg.path(ps, stroke=colors[0][i], fill='none'))
        else:
            dwg.add(dwg.path(ps, stroke=svgwrite.rgb(0+dc, 0+dc, 16, '%'), fill='none'))
        if show_closed_discont and isApproxClosedPath(p):
            startpt = (startpt.real,startpt.imag)
            dwg.add(dwg.circle(startpt,1, stroke='gray', fill='gray'))
    dwg.save()
Beispiel #21
0
def printmatrix(m,d):
	x_pos = 0
	y_pos = 0
	yearnum = 0		
	for y in m: #for every year in the matrix		
		curmo = 1
		weeknum = 0
		for w in y: #for every week in the year
			x_pos = 0
			if(isnewmonth(yearnum+startyear,weeknum+1,curmo)):
				curmo += 1
				y_pos += shape_size + 2 #new month
			else:
				y_pos += shape_size + 1 #new week
			typecount = 0	
			for t in w: #for every square count in the week
				n = 0 #count number of squares				
				while n < t:
					#d.add(d.rect((x_pos, y_pos), (shape_size, shape_size), fill=svgwrite.rgb(worktypes[typecount][1], worktypes[typecount][2], worktypes[typecount][3]))) #print square
					d.add(d.circle((x_pos, y_pos), shape_size/2, fill=svgwrite.rgb(worktypes[typecount][1], worktypes[typecount][2], worktypes[typecount][3]))) #print circle
					x_pos += shape_size + 1
					n += 1
				typecount += 1	
			weeknum += 1
		y_pos += 6 #new year
		yearnum += 1
	d.save()
Beispiel #22
0
def ex1(name):
    stvorec = square(200)
    pocet_opakovani = 120
    translist = []

    translist.append(shear(0.1))
    translist.append(rotate(radians(7)))
   
    name = "pokus4"
    img = svgwrite.Drawing('transformations_' + name + '.svg', profile='tiny')
    stroke = svgwrite.rgb(10,10,16,'%')    
    size = 1000
    
    for i in range(pocet_opakovani): 
        lines = []
        for bod in stvorec:
            lines.append(np.dot(trans(translist),[bod[0],bod[1],1]))
              
        #vykresleni jednu transformaciu  
        for idx,bod in enumerate(lines):
            bod2 = lines[(idx+1)%len(lines)]

            fr = ( int(bod[0]+size/2), int(bod[1])+size/2 )
 	    to = ( int(bod2[0]+size/2), int(bod2[1])+size/2 )
    
            img.add(img.line(fr, to, stroke=stroke))

        stvorec = lines
    img.save()
Beispiel #23
0
def convert(input,output,width,height,scale):
        d = xml.etree.ElementTree.parse(input)
        r = d.getroot()
       
        scale = int(scale)
        width = int(width)
        height = int(height)
        
        canvas = svg.Drawing(output, size=(str(width*scale), str(height*scale)))
        canvas.add(canvas.rect(insert=(0, 0), size=('100%', '100%'), rx=None, ry=None, fill='rgb(0,0,0)'))
        for poly in r.find('Polygons'):
                red = int(poly.find('Brush').find('Red').text)
                blue = int(poly.find('Brush').find('Blue').text)
                green = int(poly.find('Brush').find('Green').text)
                alpha = float(poly.find('Brush').find('Alpha').text)
                alpha = alpha/255
                color = svg.rgb(red,green,blue)
                pts = []
                for point in poly.find('Points'):
                        x = int(point.find('X').text)*scale
                        y = int(point.find('Y').text)*scale
                        pts.append((x,y))
                       
                canvas.add(svg.shapes.Polygon(points=pts, fill=color, opacity=alpha))
        canvas.save()
Beispiel #24
0
def draw():
	drawing = Drawing(drawing_file_name, drawing_size)
	
	
	first_circle_view = \
		Circle(
			center       = first_circle_center,
			r            = first_circle_radius,
			fill_opacity = 0,
			stroke       = rgb(0, 0, 0),
			stroke_width = 1
		)
		
	first_circle_center_view = \
		Circle(
			center       = first_circle_center,
			r            = 3,
			fill         = rgb(0, 0, 0),
			stroke_width = 0
		)
		
	drawing.add(first_circle_view)
	drawing.add(first_circle_center_view)
	
	
	second_circle_view = \
		Circle(
			center       = second_circle_center,
			r            = second_circle_radius,
			fill_opacity = 0,
			stroke       = rgb(0, 0, 0),
			stroke_width = 1
		)
		
	second_circle_center_view = \
		Circle(
			center       = second_circle_center,
			r            = 3,
			fill         = rgb(0, 0, 0),
			stroke_width = 0
		)
		
	drawing.add(second_circle_view)
	drawing.add(second_circle_center_view)
	
	
	drawing.save()
Beispiel #25
0
def generate_image(lines):
    dwg = svgwrite.Drawing('out.svg', profile='tiny')
    for line in lines:
        (r, g, b) = (10, 10, 16) if len(line) < 3 else line[2]
        width = 1 if len(line) < 4 else line[3]
        dwg.add(dwg.line(line[0], line[1], stroke=svgwrite.rgb(r, g, b, '%'), stroke_width = width))
    #dwg.add(dwg.text('Test', insert=(0, 0.2), fill='red'))
    dwg.save()
Beispiel #26
0
def test_svgwrite_line():
    dwg = svgwrite.Drawing(svg_filename, profile='tiny')
    stroke = svgwrite.rgb(10, 10, 16, '%')
    line = svgwrite.shapes.Line((0, 0), (10, 0), stroke=stroke)
    text = dwg.text('Test', insert=(0, 0.2), fill='red')
    dwg.add(line)
    dwg.add(text)
    dwg.save()
Beispiel #27
0
 def __init__(self, dates, rgb_color, name):
     self.start_date = dates[0]
     self.end_date = dates[1]
     self.dates = dates
     self._rgb_color = rgb_color
     self.background_color = svgwrite.rgb(*rgb_color)
     self.name = name
     self.slot = None
Beispiel #28
0
def initDraw(name,dimX,dimY):
	"""
	A function which oppen a new draw, called "name", and write a white rectangle
	of drawingDimension*drawingDimension
	"""
	dwg = svgwrite.Drawing(name,size=(dimX,dimY), profile='full')
	dwg.add(dwg.rect((0,0),(dimX,dimY),fill=svgwrite.rgb(255,255,255)))
	return dwg
Beispiel #29
0
def drawExon(dwg,lineNumber,start,end,rvb,idExon):
	"""
	A function which draw a new exon on a opened dwg draw
	it draw that exon from 'start', to 'end' (x position)
	at the line 'lineNumber' (y position) with the color
	'rvb'
	"""
	dwg.add(dwg.rect((start,lineNumber),(end - start, exon_height),fill=svgwrite.rgb(rvb[0],rvb[1],rvb[2]),id="exon",onmouseover="evt.target.setAttribute('opacity', '0.5');",onmouseout="evt.target.setAttribute('opacity','1)');"))
Beispiel #30
0
    def image_svg(self, svg, scale, stonescale=1.0):
        """Draw the map to an svg image."""

        import svgwrite

        dwg = svg
        log.debug('Creating map image svg')

        dwg.add(dwg.line((0, 0), (10, 0), stroke=svgwrite.rgb(10, 10, 16, '%')))
        dwg.add(dwg.text('Test', insert=(0, 0.2), fill='red'))

        for s in self.stones:
            center, size, angle = s.center, s.size, s.angle
            center = float((self.size[0] - center[0]) / scale), float(center[1] / scale)
            size = float(size[0] / scale) * stonescale, float(size[1] / scale) * stonescale
            dummy = np.array([np.array([s.color], dtype=np.uint8)])
            color = (cv2.cvtColor(dummy, cv2.COLOR_LAB2BGR)[0, 0]).tolist()
            svgcolor = svgwrite.rgb(color[2], color[1], color[0], 'RGB')
            # structure = s.structure
            # cv2.ellipse(img, center, size, 360 - angle, 0, 360, color, -1)
            svg_ellip = dwg.ellipse(center=center, r=size, fill=svgcolor)
            svg_ellip.rotate(360 - angle, center=center)
            dwg.add(svg_ellip)

            cl = 2.0

            svg_line1 = dwg.line(start=(center[0] + cl, center[1]), end=(center[0] - cl, center[1]), stroke='red')
            svg_line1.rotate(360 - angle, center=center)
            dwg.add(svg_line1)
            svg_line2 = dwg.line(start=(center[0], center[1] + cl), end=(center[0], center[1] - cl), stroke='red')
            svg_line2.rotate(360 - angle, center=center)
            dwg.add(svg_line2)

            # if s.flag:
            #    cv2.circle(img, center, 3, (0, 69, 255))

        for h in self.holes:
            center = float((self.size[0] - h.center[0]) / scale), float(h.center[1] / scale)
            size = float(h.size / scale)

            print size
            print center
            svg_circle = dwg.circle(center=center, r=size, stroke='black', stroke_width=0.8, fill='none')

            dwg.add(svg_circle)
Beispiel #31
0
def run_script(args):
    matplotlib.interactive(False)
    """if args.transparent == 'False' or args.transparent == 'No':
        transparent = False
    else:
        transparent = True"""

    args.ntraces = 300
    args.pad = 150
    args.reflectivity_method = zoeppritz
    args.title = 'Wedge model - wavelet cross section'
    args.wavelet = ricker
    args.wiggle_skips = 10
    args.aspect_ratio = 1
    args.left = (0, 0)
    args.right = (0, 50)
    args.margin = 1
    args.slice = 'frequency'
    args.f = (8, 256, 1)

    transparent = False
    # This is a hack to conserve colors
    l1 = (150, 110, 110)
    l2 = (110, 150, 110)
    l3 = (110, 110, 150)
    layers = [l1, l2]
    colourmap = {
        rgb(150, 110, 110): args.Rock0,
        rgb(110, 150, 110): args.Rock1
    }

    if not isinstance(args.Rock2, str):
        colourmap[rgb(110, 110, 150)] = args.Rock2
        layers.append(l3)
    # Get the physical model (an array of rocks)
    model = mb.body(traces=args.ntraces,
                    pad=args.pad,
                    margin=args.margin,
                    left=args.left,
                    right=args.right,
                    layers=layers)

    return modelr_plot(model, colourmap, args)
Beispiel #32
0
    def plot_grid():
        # horizontal lines
        for col in range(1, len(columns)):
            for row in range(0, len(rows)):
                x1, y1 = coord(col - 1, row)
                x2, y2 = coord(col, row)
                dwg.add(
                    dwg.line((x1 + 5, y1), (x2 - 5, y2),
                             stroke=svgwrite.rgb(10, 10, 16,
                                                 '%'))).dasharray([5, 5])

        for col in range(0, len(columns)):
            for row in range(1, len(rows)):
                x1, y1 = coord(col, row - 1)
                x2, y2 = coord(col, row)
                dwg.add(
                    dwg.line((x1, y1 + 5), (x2, y2 - 5),
                             stroke=svgwrite.rgb(10, 10, 16,
                                                 '%'))).dasharray([5, 5])
def write_svg(fn, vertices, edges):
  import svgwrite
  dwg = svgwrite.Drawing(fn+'.svg', profile='tiny')

  for a, b in edges:
    p1 = get_coord(vertices, a, scale=1000.0)
    p2 = get_coord(vertices, b, scale=1000.0)
    dwg.add(dwg.line(p1, p2, stroke=svgwrite.rgb(10, 10, 16, '%')))

  dwg.save()
Beispiel #34
0
def showCell(dwg, grid, cell, cell_size, center):
    radius = (cell.row + .5) * cell_size
    theta = 2 * math.pi / len(grid[cell.row])
    angle = (cell.column + .5) * theta
    coords = polarToRect(center, radius, angle)
    dwg.add(
        dwg.circle(center=(coords.x, coords.y),
                   r=(cell_size * .25),
                   stroke=svgwrite.rgb(10, 10, 16, '%'),
                   fill='red'))
Beispiel #35
0
def render(lines, points):
    img = svgwrite.Drawing('intersections.svg', profile='tiny')
    stroke = svgwrite.rgb(10, 10, 16, '%')
    for f, t in lines:
        img.add(img.line(f, t, stroke=stroke))

    for p in points:
        img.add(img.circle(p, r=3))

    img.save()
Beispiel #36
0
def thingy(d):

    paper_centre = Point(102.5, 148)
    paper_size = Point(192, 270)
    
    lines = []
    lines_r = []
    lines_g = []
    lines_b = []
    
    size = 3
    nr = 50
    nc = 30
    for r in range(0, nr+1):
        for c in range(0, nc+1):
            pt = paper_centre + Point(0, 5) * (r - nr/2) + Point(5, 0) * (c - nc/2)
            a = random.random() * math.pi * 2
            line = d.make_square(pt, size)
            line.append(line[0])
            centre = pt + Point(1,1) * size/2
            line = [d.rotate_about(pt, centre, a) for pt in line]
            lines.append(line)
            
            line = d.make_circle(centre, size/4)
            lines_circle = lines_b
            x = random.random()
            if x < 0.333:
                lines_circle = lines_r
            elif x < 0.666:
                lines_circle = lines_g
                
            lines_circle.append(line)
            
            line = d.make_square(pt + Point(1,1)*size/4, size/2)
            line.append(line[0])
            centre = pt + Point(1,1) * size/2
            line = [d.rotate_about(pt, centre, a) for pt in line]
            # lines.append(line)

    d.add_polylines(lines, container=d.add_layer("1"))
    d.add_polylines(lines_r, container=d.add_layer("2"), stroke=svgwrite.rgb(100, 0, 0, '%'))
    d.add_polylines(lines_g, container=d.add_layer("3"), stroke=svgwrite.rgb(0, 50, 0, '%'))
    d.add_polylines(lines_b, container=d.add_layer("4"), stroke=svgwrite.rgb(0, 0, 100, '%'))
Beispiel #37
0
    def save(self):
        dwg = svgwrite.Drawing(self.output_filename, profile="full")
        shapes = self.get_current_shapes()
        for shape in shapes:
            shape_type = shape["type"]
            if shape_type == "line":
                # color 0 - 1.0 -> percentage
                color = tuple(map(lambda x: min(x * 100, 100), shape["color"]))
                pline = dwg.polyline(
                    points=shape["points"],
                    stroke=svgwrite.rgb(color[0], color[1], color[2], "%"),
                    stroke_width=shape["width"],
                    fill_opacity=0,
                )
                dwg.add(pline)
            elif shape_type == "text":
                text = shape["text"]
                color = tuple(map(lambda x: min(x * 100, 100), shape["color"]))
                dwg.add(
                    dwg.text(
                        text,
                        font_size=self.font_size,
                        font_family=FONT_NAME,
                        insert=shape["position"],
                        stroke=svgwrite.rgb(*color, "%"),
                    )
                )
            elif shape_type == "rect":
                width = shape["width"]
                height = shape["height"]
                color = tuple(map(lambda x: min(x * 100, 100), shape["color"]))
                position = shape["position"]
                dwg.add(
                    dwg.rect(
                        insert=position,
                        size=(width, height),
                        fill=svgwrite.rgb(*color, "%"),
                    )
                )

            # elif shape_type == "image":
        dwg.save()
Beispiel #38
0
def render_features_from_text(input_text: str):
    global parser
    try:
        expression: MathExpression = parser.parse(input_text)
        state = MathyEnvState(problem=input_text)
        observation: MathyObservation = state.to_observation(
            hash_type=[13, 37])

        length = len(observation.nodes)
        types = observation.nodes
        values = observation.values
        nodes = expression.to_list()
        chars = [n.name for n in nodes]
        assert len(types) == len(values) == len(chars)

        view_x = 0
        view_y = 0
        view_w = BOX_SIZE * length
        view_h = BOX_SIZE * 3 + BORDER_WIDTH * 2

        tree = svgwrite.Drawing(size=(view_w, view_h))
        tree.viewbox(minx=view_x, miny=view_y, width=view_w, height=view_h)

        curr_x = BORDER_WIDTH
        for n, t, v, c in zip(nodes, types, values, chars):

            color = svgwrite.rgb(180, 200, 255)
            if isinstance(n, BinaryExpression):
                color = svgwrite.rgb(230, 230, 230)
            elif isinstance(n, VariableExpression):
                color = svgwrite.rgb(150, 250, 150)
            if n == n.get_root():
                color = svgwrite.rgb(250, 220, 200)

            box_with_char(tree, c, x=curr_x, y=BORDER_WIDTH, fill=color)
            box_with_char(tree, v, x=curr_x, y=BOX_SIZE + BORDER_WIDTH)
            box_with_char(tree, t, x=curr_x, y=BOX_SIZE * 2 + BORDER_WIDTH)
            curr_x += BOX_SIZE - (BORDER_WIDTH)

        return svgwrite.utils.pretty_xml(tree.tostring(), indent=2)
    except BaseException as error:
        return f"Failed to parse: '{input_text}' with error: {error}"
Beispiel #39
0
def run_script(args):
    matplotlib.interactive(False)
 
    Rprop0 = args.Rock0 
    Rprop1 = args.Rock1
    Rprop2 = args.Rock2
    Rprop3 = args.Rock3
    
    colourmap = {}

    if isinstance(Rprop0, str):
        Rprop0 = None
    else:
        colourmap[rgb(255,255,255)] = Rprop0 
        
    if isinstance(Rprop1, str):
        Rprop1 = None
    else:
        colourmap[rgb( 255,0,0 )] = Rprop1 
        
    if isinstance(Rprop2, str):
        Rprop2 = None
    else:
        colourmap[rgb( 0,0,255 )] = Rprop2 
        
    if isinstance(Rprop3, str):
        Rprop3 = None
    else:
        colourmap[3] = Rprop3 
    
    if not isinstance(args.rocks, int):
        colours = 0
    else:
        colours = args.rocks

    
    colours = ((255,255,255),(255,0,0), (0,0,255) )
    model = mb.web2array(args.url,
                         colours = colours
                         )
    
    return modelr_plot( model, colourmap, args )
Beispiel #40
0
 def DrawDefaultStatusBox(self):
     self.dwg.add(
         self.dwg.use(self.device_not,
                      x=self.ConBoxMargin + (self.CntBoxWidth * 0.5) +
                      self.grid_s * 0.5,
                      y=self.top_m + 20))
     self.dwg.add(
         self.dwg.text("NOT Gate",
                       x=[self.ConBoxMargin + (self.CntBoxWidth * 0.5)],
                       y=[self.top_m + 60],
                       text_anchor="middle",
                       alignment_baseline="central",
                       font_size="%dpt" % int(self.grid_s * 0.20),
                       font_family="consolas"))
     self.dwg.add(
         self.dwg.text("NOR Gate",
                       x=[self.ConBoxMargin + (self.CntBoxWidth * 0.5)],
                       y=[self.top_m + 170],
                       text_anchor="middle",
                       alignment_baseline="central",
                       font_size="%dpt" % int(self.grid_s * 0.20),
                       font_family="consolas"))
     self.dwg.add(
         self.dwg.use(self.device_nor,
                      x=self.ConBoxMargin + (self.CntBoxWidth * 0.5) +
                      self.grid_s * 0.5,
                      y=self.top_m + 120))
     self.dwg.add(
         self.dwg.rect((self.ConBoxMargin, self.top_m * 2),
                       (self.CntBoxWidth, 80),
                       rx=10,
                       ry=10,
                       fill=svgwrite.rgb(100, 100, 100, '%'),
                       stroke=svgwrite.rgb(0, 0, 0, '%')))
     self.dwg.add(
         self.dwg.text("Current Inst",
                       x=[self.ConBoxMargin + (self.CntBoxWidth * 0.5)],
                       y=[self.top_m * 2.7],
                       text_anchor="middle",
                       alignment_baseline="central",
                       font_size="%dpt" % int(self.grid_s * 0.30),
                       font_family="consolas"))
Beispiel #41
0
 def render_connectivity_graph(self, ):
     for i, room in enumerate(self.floorplan.rooms):
         for e in room.edges:
             for door in e.doors:
                 self.group.add(
                     self.drawing.line(
                         self.scale_point(room.center),
                         self.scale_point(e.center), **{
                             "stroke": svgwrite.rgb(0, 255, 0),
                             "stroke-width": 4
                         }))
Beispiel #42
0
def border(dwg, radius, origin_x, origin_y):
    STEPS = 360
    points = []
    for i in range(STEPS):
        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))

    dwg.add(dwg.polygon(points, fill='none', stroke=svgwrite.rgb(0, 0, 0, '%')))
Beispiel #43
0
def main():
    n = int(input("Input iteration value: "))
    koch_curve(size, n)

    dwg = svgwrite.Drawing('koch.svg', profile='tiny')
    for i in range(len(points) - 1):
        a, b = points[i], points[i + 1]
        a[1] += 100
        b[1] += 100
        dwg.add(dwg.line(a, b, stroke=svgwrite.rgb(0, 0, 0, '%')))
    dwg.save()
Beispiel #44
0
 def __init__(self, dim=None):
     if dim is None:
         self.dim = self.defaults['dim']
     else:
         self.dim = dim  # list, dimensions, in pixels, [width, height]
     self.data = {
     }  # dictionary to store all data values. will be referenced by data name
     self.drawables = OrderedDict(
     )  # keep track of the drawable items (charts, axes) in the figure. each drawable has a name
     self.background_color = rgb(255, 255, 255)
     self.anti_aliasing = True
Beispiel #45
0
def slice_file(f=None, resolution=0.1):
    print("Status: Loading File.")

    model = STLModel(f)
    scale = 10
    stats = model.stats()

    sub_vertex = Vector3(stats['extents']['x']['lower'],
                         stats['extents']['y']['lower'],
                         stats['extents']['z']['lower'])
    add_vertex = Vector3(0.5, 0.5, 0.5)

    model.xmin = model.xmax = None
    model.ymin = model.ymax = None
    model.zmin = model.zmax = None

    print("Status: Scaling Triangles.")

    for triangle in model.triangles:
        triangle.vertices[0] -= sub_vertex
        triangle.vertices[1] -= sub_vertex
        triangle.vertices[2] -= sub_vertex

        # The lines above have no effect on the normal.

        triangle.vertices[0] = (triangle.vertices[0] * scale) + add_vertex
        triangle.vertices[1] = (triangle.vertices[1] * scale) + add_vertex
        triangle.vertices[2] = (triangle.vertices[2] * scale) + add_vertex

        # Recalculate the triangle normal

        u = model.triangles[0].vertices[1] - model.triangles[0].vertices[0]
        v = model.triangles[0].vertices[2] - model.triangles[0].vertices[0]

        triangle.n = Normal((u.y * v.z) - (u.z * v.y),
                            (u.z * v.x) - (u.x * v.z),
                            (u.x * v.y) - (u.y * v.x))
        model.update_extents(triangle)

    print("Status: Calculating Slices")

    interval = scale * resolution
    stats = model.stats()
    print(stats)

    for targetz in range(0, int(stats['extents']['z']['upper']),
                         int(interval)):
        dwg = Drawing('outputs/svg/' + str(targetz) + '.svg', profile='tiny')
        pairs = model.slice_at_z(targetz)
        for pair in pairs:
            dwg.add(dwg.line(pair[0], pair[1], stroke=rgb(0, 0, 0, "%")))
        dwg.save()

    print("Status: Finished Outputting Slices")
Beispiel #46
0
def get_paletton(filename):
    # extract a list of svgwrite colors from a paletton txt file
    lines = [
        line.split("=") for line in open(filename, "r").readlines()
        if len(line.split("=")) > 3
    ]
    rgbs = [
        line[2].replace("rgb(", "").replace(")", "").split(",")
        for line in lines
    ]
    return [rgb(*[float(x) for x in _rgb]) for _rgb in rgbs]
def curve_to_svg(curve, svg, scale):
    domain = curve.Domain
    for i in range(100):
        t0 = domain.T0 + (domain.T1 - domain.T0) * (i / 100.0)
        t1 = domain.T0 + (domain.T1 - domain.T0) * ((i + 1) / 100.0)
        pt0 = curve.PointAt(t0)
        pt1 = curve.PointAt(t1)
        svg.add(
            svg.line((pt0.X * scale, pt0.Y * scale),
                     (pt1.X * scale, pt1.Y * scale),
                     stroke=svgwrite.rgb(10, 10, 16, '%')))
Beispiel #48
0
def draw_grids(dwg, grid, position, show_lines=True):
    if len(grid.subgrids) == 0:
        grid.shape.draw(dwg, position)
        return

    x1, y1, x2, y2 = position
    up = ((x1 + x2) / 2, y1)
    right = (x2, (y1 + y2) / 2)
    down = ((x1 + x2) / 2, y2)
    left = (x1, (y1 + y2) / 2)
    center = ((x1 + x2) / 2, (y1 + y2) / 2)

    if show_lines:
        dwg.add(dwg.line(up, down, stroke=svgwrite.rgb(10, 10, 16, '%')))
        dwg.add(dwg.line(left, right, stroke=svgwrite.rgb(10, 10, 16, '%')))

    draw_grids(dwg, grid.subgrids[0], (x1, y1) + center, show_lines)
    draw_grids(dwg, grid.subgrids[1], up + right, show_lines)
    draw_grids(dwg, grid.subgrids[2], center + (x2, y2), show_lines)
    draw_grids(dwg, grid.subgrids[3], left + down, show_lines)
Beispiel #49
0
def spirograph6(drawing):

    paper_centre = Point(102.5, 148)
    r = [70, 3, 2, 1]
    s = [1, -1, 1, -1]
    scale = 1
    for i in range(0, 20):
        add_spirograph(drawing,
                       paper_centre,
                       r,
                       s,
                       scale=scale,
                       stroke=svgwrite.rgb(0, 0, 0, '%'),
                       container=drawing.add_layer("1"))
        scale *= 0.9
    drawing.add_dot(paper_centre,
                    75,
                    r_start=73,
                    stroke=svgwrite.rgb(50, 0, 0, '%'),
                    container=drawing.add_layer("2"))
Beispiel #50
0
def get_poly_kwargs_from_style_obj(style_obj):
    return_obj = {}

    for k, v in style_obj.items():
        #FIXME: This is a really hacky way to extract and convert rgb objects
        if type(v) == list:
            return_obj[k] = svgwrite.rgb(v[0], v[1], v[2])
        else:
            return_obj[k] = v

    return return_obj
Beispiel #51
0
    def test_get_reflectivity(self):

        cmap = {rgb(150, 100, 100): self.Rp0, rgb(100, 150, 100): self.Rp1}
        theta = 15.0
        data = np.zeros((100, 100, 3))

        data[:50, :, :] += [150, 100, 100]
        data[50:, :, :] += [100, 150, 100]

        reflectivity = \
          get_reflectivity( data, cmap, theta,
                            reflectivity_method=avo.zoeppritz )

        truth = avo.zoeppritz(self.vp0, self.vs0, self.rho0, self.vp1,
                              self.vs1, self.rho1, theta)

        test = np.zeros((100, 100, 1))
        test[49, :, 0] = truth

        self.assertTrue(np.array_equal(test, reflectivity))
Beispiel #52
0
def makelabels(x, y, size, text):
    x = x * scale
    y = y * scale
    dwg.add(
        dwg.text(text,
                 insert=(x, y),
                 stroke='none',
                 fill=svgwrite.rgb(15, 15, 15),
                 font_size=size,
                 font_weight="bold",
                 style="font-family:Arial"))
Beispiel #53
0
def makesquares(x1, y1, x2, y2):
    # draw a nofill box
    x1 = x1 * scale
    y1 = y1 * scale
    x2 = x2 * scale
    y2 = y2 * scale
    dwg.add(
        dwg.rect((x1, y1), (x2, y2),
                 stroke=svgwrite.rgb(10, 10, 20),
                 stroke_width=stroke,
                 fill='none'))
Beispiel #54
0
def main():
    drawing = svgwrite.Drawing(filename='tower.svg',
                               size=(page_width, page_height))

    drawing.add(
        drawing.circle((100 * mm, 100 * mm),
                       r=30 * mm,
                       stroke=svgwrite.rgb(255, 255, 255, '%'),
                       stroke_width=1 * mm))
    drawing.add(
        drawing.circle((100 * mm, 70 * mm),
                       r=15 * mm,
                       stroke=svgwrite.rgb(255, 255, 255, '%'),
                       stroke_width=1 * mm))
    drawing.add(
        drawing.circle((100 * mm, 45 * mm),
                       r=7.5 * mm,
                       stroke=svgwrite.rgb(255, 255, 255, '%'),
                       stroke_width=1 * mm))
    drawing.save()
Beispiel #55
0
def markup_extra_staffs(staff_prop: StaffProperties, staff_start_position,
                        horizontal_note_position, note_vertical_offset):
    objects = []
    if note_vertical_offset < 0:
        count = abs(int(
            (note_vertical_offset) // staff_prop.staff_line_offset))

        for idx in range(1, count + 1):
            y = staff_start_position - idx * staff_prop.staff_line_offset
            line = Polyline(points=[(horizontal_note_position - 40,
                                     y), (horizontal_note_position + 50,
                                          y)]).stroke(
                                              color=svgwrite.rgb(0, 0, 0),
                                              width=2,
                                              linejoin='bevel',
                                          )

            # 7 lines in LINE_SET_SETUP, last - bottom.
            # Get for next top last with skipping 1 doubled starting and 1 existing.
            if LINE_SET_SETUP[-((idx) % 3) - 1]:
                line.dasharray([5, 7])
            objects += [line]

    if note_vertical_offset > staff_prop.staff_height:
        count = int((note_vertical_offset - staff_prop.staff_height) //
                    staff_prop.staff_line_offset)
        for idx in range(1, count + 1):
            y = staff_start_position + staff_prop.staff_height + idx * staff_prop.staff_line_offset
            line = Polyline(points=[(horizontal_note_position - 40,
                                     y), (horizontal_note_position + 50,
                                          y)]).stroke(
                                              color=svgwrite.rgb(0, 0, 0),
                                              width=2,
                                              linejoin='bevel',
                                          )

            # 7 lines in LINE_SET_SETUP, first - top. Get for next bottom from start, skipping 1 existing.
            if LINE_SET_SETUP[idx % 3]:
                line.dasharray([5, 7])
            objects += [line]
    return objects
Beispiel #56
0
 def add_boxes(self, step_dict, width, name_fill):
     x, y = step_dict['position']['left'], step_dict['position']['top']
     self.boxes.append(
         svgwrite.shapes.Rect((x - MARGIN, y), (width, 30),
                              fill=name_fill,
                              stroke='#000000'))
     box_height = (len(step_dict['data_inputs']) +
                   len(step_dict['data_outputs'])) * LINE_SPACING + MARGIN
     # Draw separator line.
     if len(step_dict['data_inputs']) > 0:
         box_height += LINE_SPACING
         sep_y = y + len(step_dict['data_inputs']) * LINE_SPACING + 40
         self.text.append(
             svgwrite.shapes.Line((x - MARGIN, sep_y),
                                  (x + width - MARGIN, sep_y),
                                  stroke=svgwrite.rgb(0, 0, 0)))
     # Define an input/output box.
     self.boxes.append(
         svgwrite.shapes.Rect((x - MARGIN, y + 30), (width, box_height),
                              fill="#ffffff",
                              stroke=svgwrite.rgb(0, 0, 0)))
Beispiel #57
0
    def Backward(self, length):
        x1 = self.posX
        y1 = self.posY

        x2 = x1 - math.cos(math.radians(self.angle)) * length
        y2 = y1 - math.sin(math.radians(self.angle)) * length

        self.posX = x2
        self.posY = y2

        self.file.add(self.file.line((x1, y1), (x2, y2), stroke=svgwrite.rgb(self.color[0], self.color[1], self.color[2], '%'),
                                                        stroke_width = self.penStat))
Beispiel #58
0
def svgcreate(pairs, z, ymax, fillx, filly):
    # Create a new SVG file with the file name as the z-coordinate (inches) of the slice (round to 0.001 in)
    dwg = svgwrite.Drawing('outputs/' + str(round(z/25.4, 3)) + '.svg')

    # Create lines for the geometry segment point pairs sliced on the given z-plane
    for pair in pairs:
        # Offset the y position by ymax-y in order to account for the difference in SVG coordinate system (+Y is down)
        dwg.add(dwg.line((pair[0], ymax-pair[1]), (pair[2], ymax-pair[3]), stroke=svgwrite.rgb(0, 0, 0, "%")))
    # Create lines for infill parallel to the Y axis
    for fill_line in fillx:
        # Loop over points for each fill line in X (always even number)
        for pts in range(int(len(fill_line[1])/2)):
            dwg.add(dwg.line((fill_line[0], ymax - fill_line[1][2*pts]), (fill_line[0], ymax - fill_line[1][2*pts+1]),
                             stroke=svgwrite.rgb(0, 0, 0, "%")))
    # Create lines for infill parallel to the X axis
    for fill_line in filly:
        # Loop over points for each fill line in Y (always even number)
        for pts in range(int(len(fill_line[1])/2)):
            dwg.add(dwg.line((fill_line[1][2*pts], ymax - fill_line[0]), (fill_line[1][2*pts+1], ymax - fill_line[0]),
                             stroke=svgwrite.rgb(0, 0, 0, "%")))
    dwg.save()  # Save the SVG file to the output folder
Beispiel #59
0
    def svg(self):
        p = self.calcLines()
        curve = svgwrite.container.Group()

        for i in range(len(p) - 1):
            curve.add(
                svgwrite.shapes.Line(start=p[i],
                                     end=p[i + 1],
                                     stroke=svgwrite.rgb(10, 10, 16, '%')))
            #pg.draw.line(screen, self.color, p[i], p[i+1], self.width)

        return curve
def test_add_line_to_layer(dwg):
    inkscape = Inkscape(dwg)
    layer = inkscape.layer(label="Layer one", locked=True)
    dwg.add(layer)

    line = dwg.line((100, 100), (300, 100),
                    stroke=svgwrite.rgb(10, 10, 16, '%'),
                    stroke_width=10)
    layer.add(line)

    text = dwg.text('Test', insert=(100, 100), font_size=100, fill='red')
    layer.add(text)