def load_regions_from_svg(self, url, attr): import svgfig svg = svgfig.load(url) self.svg = svg g = svg[2] coords = {} for path in g[:]: path_str = path['d'] id = path['data-'+attr] poly = restore_poly_from_path_str(path_str) coords[id] = poly.center() return coords
def add_shapefile_layer(self, svg_src, shp_src, data_column=None, outfile=None, polycolor=None): """ adds the content of a shapefile as a new map layer """ import svgfig, shapefile if data_column == None: data_column = () options = self.options svg = svgfig.load(svg_src) svg_views = svg[1][0] svg_view = svg_views[0] svg_proj = svg_view[0] svg_bbox = svg_view[1] svg_llbbox = svg_view[2] pd = float(svg_view['padding']) globe = proj.Proj.fromXML(svg_proj) bbox = Bounds2D(left=float(svg_bbox['x']), top=float(svg_bbox['y']), width=float(svg_bbox['w']), height=float(svg_bbox['h'])) vh = float(svg_view['h']) vw = float(svg_view['w']) options.out_width = vw options.out_height = vh options.force_ratio = True options.out_padding = pd options.llbbox = map(float, (svg_llbbox['lon0'],svg_llbbox['lat0'],svg_llbbox['lon1'],svg_llbbox['lat1'])) view = self.get_view(bbox) viewbox = Bounds2D(width=view.width, height=view.height) if options.verbose: print view print viewbox print globe # eventually crop at layer layer_poly = None if options.crop_at_layer != None: from Polygon import Polygon as Poly from Polygon.IO import writeSVG from gisutils import restore_poly_from_path_str if options.verbose: print 'crop at layer "%s"' % options.crop_at_layer for g in svg[2:]: if g['id'] == options.crop_at_layer: if options.verbose: print 'found layer!' # restore polygons from that layer layer_poly = Poly() for path in g[:]: path_str = path['d'] poly = restore_poly_from_path_str(path_str) layer_poly = layer_poly | poly break # read shapefile sf = shapefile.Reader(shp_src) filt = self.get_polygon_filter(sf) fields = [] for f in sf.fields[1:]: fields.append(f[0]) shprecs = sf.shapeRecords() polygons = [] for sx in range(len(shprecs)): shp = shprecs[sx].shape rec = shprecs[sx].record if not filt(rec): continue data = { } for d in data_column: for f in range(len(fields)): if d == fields[f]: data[fields[f].lower().replace('_','-')] = Utils.remove_unicode(rec[f]) polys = self.get_shape_polygons(shp, "", globe, view, data=data) for poly in polys: if poly.bbox.intersects(viewbox): polygons.append(poly) # polygons = self.merge_biggest_polygons(polygons, 4000) self.simplify_polygons(polygons) if options.cut_lakes: polygons = self.cut_lakes(polygons, globe, view, viewbox) if options.llbbox != (-180,-90,180,90): polygons = self.clip_polygons_to_sea(polygons, globe, view) else: polygons = self.clip_polygons(polygons, viewbox) if layer_poly != None: from gisutils import polygon_to_poly, poly_to_polygons out = [] for polygon in polygons: poly = polygon_to_poly(polygon) poly_ = poly & layer_poly if poly_ != None: out += poly_to_polygons(poly_, id=polygon.id, data=polygon.data, closed=polygon.closed) polygons = out self.add_map_layer(svg, polygons, options.layer_id, polycolor=polycolor) self.save_or_display(svg, "", outfile)
#weekendMargin = 0 #wordGroup = dwg.g(transform="rotate(%f, %f, %f) translate(%f,0)" \ #%( math.degrees(angle+dayAngle+textAngleShift)+90, mid[0], mid[1], +R_dates+weekendMargin ) \ #) #wordGroup.add( dwg.text( '%s'%(yearDays[index]), \ #insert=mid, fill=fillColor \ ##,style="font-weight: %s;"%(fontWeight) #)) #textGroup.add(wordGroup) if __name__ == '__main__': baseDir = os.path.dirname(os.path.realpath(__file__))+"\\" canvasSize = (500,707) canvasMiddle = canvasSize[0]/2.0, canvasSize[1]/2.0 #baseDir = "C:\\Users\\ewew\\Dropbox\\_PROJECTS\\2014.08.24 Kruglendar_2015\\python\\" dayShapes = svgfig.load(baseDir+"dayShapes-proper.svg") # парсить argv: outputFile, timeModelType, language = sys.argv[1:] # Размер документа svgfig._canvas_defaults['width'] = canvasSize[0] svgfig._canvas_defaults['height'] = canvasSize[1] svgfig._canvas_defaults['viewBox'] = "0 0 %d %d"% \ (canvasSize[0], canvasSize[1]) c = Calendar(dayShapes, canvasSize, timeModelType, language) svg = svgfig.SVG("g", c.render(), transform="translate(%f %f)" \ %(canvasSize[0]/2.0,canvasSize[1]/2.0)) # записать svg svg.save(baseDir + outputFile) #print(repr(svg))
def __init__(self, basefile, strokewidth_multiplier=3, max_strokewidth=5, min_strokewidth=0.2): import svgfig svg = svgfig.load(basefile) # build path and text dicts used to reference fluxes in the svg rawPathList = [] rawTextDict = {} for index, item in svg: # Title info try: attr = item.attr try: id = attr['id'] if 'title' in id: titleLoc = (index, 0, 0) except KeyError: pass except AttributeError: pass # The rest try: # ungrouped paths if item.t == "path" and len(index) == 1: rawPathList.append((item.attr['id'], [index])) # grouped paths # if item type is group and the ID isn't a generic "gNNNN" if item.t == "g" and not item.attr['id'][1:].isnumeric(): # if every subitem in the group is a path pathtest = [] for s in item.sub: pathtest.append(s.t == "path") if all(pathtest): rawPathList.append( (item.attr['id'], [(index[0], u) for u in range(len(item.sub))])) # get text entry names and numbers if item.t == "text": # set up a dict lookup by name, store top-level index as the dict contents # index,0,0 : the name # index,1,0 : the rate number name = svg[index, 0, 0].strip() rate = (index[0], 1, 0) stds = (index[0], 2, 0) if name in rawTextDict: rawTextDict[name].append((rate, stds)) else: rawTextDict[name] = [(rate, stds)] # svgfig silently handles IndexError exception if svg[index,1,0] does not exist except: pass # clean misc paths and cofactors out of the path list cleanPathList = [] badTerms = [ "path", "atpc", "adpc", "coac", "co2c", "nadc", "nadhc", "nadpc", "nadphc" ] for entry in rawPathList: flagBad = False for bad in badTerms: if bad in entry[0]: flagBad = True break if not flagBad: cleanPathList.append(entry) pathdict = dict(cleanPathList) # clean metabolite labels and pure numeric labels out of the text list cleanTextDict = {} badTerms = ["[c]", "[e]"] for entry in rawTextDict: flagBad = False for bad in badTerms: if bad in entry: flagBad = True break #if not flagBad and entry[0].isnumeric() == False: if not flagBad and entry.isnumeric() == False: cleanTextDict[entry] = rawTextDict[entry] textdict = cleanTextDict #textdict = dict(cleanTextDict) # assign attributes self.basefile = basefile self.basesvg = svg self.svg = svg self.pathdict = pathdict self.textdict = textdict self.strokewidth_multiplier = strokewidth_multiplier self.max_strokewidth = max_strokewidth self.min_strokewidth = min_strokewidth self.titleLoc = titleLoc