def parse_file(ifile, ofile): rexp = re.compile(r'^(?P<tag>[^:]+)(:\s*(?P<rest>.*))?$') lineno = 1 for line in ifile: stripped = line.strip() m = rexp.match(stripped) if not m: print('Parse error at line {0}'.format(lineno), file=sys.stderr) sys.exit(1) tag_name = m.group('tag') rest = m.group('rest') tag = tags.DICT[tag_name] tag_type = tags.type_of_tag(tag) if tag_type == types.NODATA: data = None elif tag_type == types.ASCII: data = rest[1:-1].encode() # FIXME elif tag_type == types.BITARRAY: data = int(rest) elif tag_type == types.REAL8: data = [float(s) for s in rest.split(',')] elif tag_type == types.INT2 or tag_type == types.INT4: data = [int(s) for s in rest.split(',')] else: raise Exception('Unsupported type') rec = Record(tag, data) rec.save(ofile) lineno += 1
def store_data(tag_name, idata): tag = tags.DICT[tag_name] tag_type = tags.type_of_tag(tag) rest = idata if tag_type == types.NODATA: data = None elif tag_type == types.ASCII: data = rest[1:-1].encode() # FIXME elif tag_type == types.BITARRAY: data = int(rest) elif tag_type == types.REAL8: data = [float(s) for s in rest.split(',')] elif tag_type == types.INT2 or tag_type == types.INT4: data = [int(s) for s in rest.split(',')] else: raise Exception('Unsupported type') rec = Record(tag, data) rec.save(ofile)
def main(name): with open(name, 'rb') as a_file: for item in Record.iterate(a_file): if item.tag_type == types.NODATA: gds_file.write(item.tag_name) gds_file.write("\n") else: gds_file.write('%s: %s' % (item.tag_name, layout(item))) gds_file.write("\n") gds_file.close()
def main(self): """ open filename (if exists) read units get list of polygons """ # test = [] no_of_Structures = 0 string_position = [] strings = [] with open(self.fname, 'rb') as a_file: for rec in Record.iterate(a_file): # test.append([rec.tag_name, rec.data, rec.tag_type]) if rec.tag_type == types.NODATA: pass else: # print('%s: %s' % (rec.tag_name, show_data(rec))) # print('%s:' % (rec.tag_name)) if rec.tag_name == 'UNITS': """ get units """ unitstring = self.show_data(rec) self.units = np.array(re.split( ',', unitstring)).astype(float) elif rec.tag_name == 'XY': no_of_Structures += 1 """ get pointlist """ # get data datastring = self.show_data(rec) # split string at , and convert to float data = np.array(re.split(',', datastring)).astype(float) # reshape into [[x1,y1],[x2,y2],...] if len(data) > 2: data = np.reshape(data, (len(data) / 2, 2))[:-1] else: data = np.reshape(data, (len(data) / 2, 2)) self.pointlists.append(data) elif rec.tag_name == 'STRING': string_position.append(no_of_Structures - 1) strings.append(rec.data) self.string_infos = dict(zip(string_position, strings))
def convert_GDS_GDSjson(name, oname): level = 0 ofile = open(oname, 'wt') top = {} cursors = [top, {}, {}, {}, {}, {}, {}] with open(name, 'rb') as a_file: for rec in Record.iterate(a_file): tag_name = rec.tag_name tag_type = rec.tag_type jsonName = "" if isElement(tag_name): jsonName = "elements" else: jsonName = tag_name.lower() if ((tag_type != types.NODATA and tag_name[0:3] == "BGN") or isElement(tag_name)): if isinstance(cursors[level], dict): level = level + 1 cursors[level] = [] cursors[level - 1][jsonName] = cursors[level] level = level + 1 cursors[level] = {} cursors[level - 1].append(cursors[level]) if isElement(tag_name): cursors[level]["type"] = tag_name.lower() if tag_name[0:3] == "BGN": cursors[level]["time"] = show_data(rec) if tag_type != types.NODATA and tag_name[0:3] != "BGN": cursors[level][jsonName] = show_data(rec) elif tag_name[0:3] == "END": if isinstance(cursors[level - 1], dict): level = level - 1 level = level - 1 json.dump(top, ofile, indent=4)
def main(argv): global pcbApp, pcbDoc, pcbGui, pcbUtil global erase, gdsin, progress, lockserver, replace, shuffle, transaction, work Version() ## Parse command line try: opts, args = getopt.getopt(argv, "deghi:lprstvw:", [ \ "debug", "erase", "gui", "help", "gds=", "lockserver", \ "progress", "replaced", "shuffle", "transaction", \ "version", "work="]) except getopt.GetoptError as err: tprint(err) usage(os.path.basename(sys.argv[0])) sys.exit(2) ## Only show version? if len([i for i, j in opts if i in ['-v', '--version']]): sys.exit(0) ## Initialize variables rc = 0 erase = False debug = False gui = False gdsin = None progress = False lockserver = False transaction = False work = os.getcwd() ## Parse command line options Transcript("", None, False) Transcript("Command line options", None, False) Transcript("", None, False) for opt, arg in opts: if opt in ("-h", "--help"): usage(os.path.basename(sys.argv[0])) sys.exit(0) if opt in ("-d", "--debug"): debug = True if opt in ("-e", "--erase"): erase = True if opt in ("-g", "--gui"): gui = True if opt in ("-i", "--gds"): gdsin = arg Transcript("{} set to: {}".format(opt, arg), "note", False) if opt in ("-l", "--lockserver"): lockserver = True if opt in ("-p", "--progress"): progress = True if opt in ("-r", "--replace"): replace = True Transcript("{} option enabled".format(opt), "note", False) if opt in ("-s", "--shuffle"): shuffle = True Transcript("{} option enabled".format(opt), "note", False) if opt in ("-t", "--transaction"): transaction = True Transcript("{} option enabled".format(opt), "note", False) if opt in ("-w", "--work"): work = arg Transcript("{} set to: {}".format(opt, arg), "note", False) Transcript("", None, False) ## If Gui not specified but GDS not provided, default to GUI if gdsin is None and not gui: gui = True # Try and launch Xpedition, it should already be open try: pcbApp = win32com.client.gencache.EnsureDispatch( "MGCPCB.ExpeditionPCBApplication") pcbGui = pcbApp.Gui pcbUtil = pcbApp.Utility pcbApp.Visible = 1 except pythoncom.com_error(hr, msg, exc, argv): Transcript("Unabled to launch Xpedition", "error", False) sys.exit("Terminating script.") pcbApp.Gui.StatusBarText("Running Python GDS Import Script ...") # Get a PCB document and make sure it is licensed # If there isn't a design open, prompt the user for one while True: if pcbApp.ActiveDocument == None: pcbApp.Gui.ProcessCommand("File->Open") else: break pcbDoc = GetLicensedDoc(pcbApp) if pcbDoc == None: Transcript("No PCB database open, GDS import aborted.", "error") else: Transcript( "GDS Import Python script connected to PCB database \"{}\".". format(pcbDoc.Name), "note") ## Present GUI? if gui or gdsin is None: root = TK.Tk() root.title("Import GDS") #root.geometry("600x600+300+300") app = BuildGUI(root, gdsin, replace, progress, lockserver, shuffle, transaction, work) ## Setup key binds for Run and Cancel root.bind('<Return>', app.ReturnKey) root.bind('<Escape>', app.EscapeKey) root.protocol("WM_DELETE_WINDOW", app.Cancel) root.mainloop() ## Make sure input file exists! if not os.path.isfile(gdsin): Transcript("--gds file ({}) does not exist".format(gdsin), "error") sys.exit(2) ## Raw dump of the GDS file when in debug mode ... if debug: with open(gdsin, 'rb') as a_file: for rec in Record.iterate(a_file): if rec.tag_type == types.NODATA: Transcript(rec.tag_name, "debug", False) else: Transcript('{}: {}'.format(rec.tag_name, showData(rec)), "debug", False) ## Capture the start time st = time.time() ## Load the source GDS file with open(gdsin, 'rb') as stream: lib = Library.load(stream) ## "Pre-scan" the GDS to gather up the layers that will be imported. gdslayers = [] for struc in lib: for elem in struc: if isinstance(elem, Boundary): gdslayer = "{}.{}".format(elem.layer, elem.data_type) if isinstance(elem, Path): gdslayer = "{}.{}".format(elem.layer, elem.path_type) elif isinstance(elem, Text): gdslayer = "{}.{}".format(elem.layer, elem.text_type) elif isinstance(elem, Node): gdslayer = "{}.{}".format(elem.layer, elem.node_type) elif isinstance(elem, Box): gdslayer = "{}.{}".format(elem.layer, elem.box_type) if gdslayer not in gdslayers: gdslayers.append(gdslayer) for gdslayer in gdslayers: Transcript("GDS layer {} will be imported.".format(gdslayer), "note") ## Lock the Server? if lockserver: ls = pcbApp.LockServer if ls: Transcript("Locking Server ...", "note") ## Start Transaction? if transaction: trs = pcbDoc.TransactionStart(0) if trs: Transcript("Starting Transaction ...", "note") ## Erase all GDS layers? if erase: for l in range(0, 255): for d in range(0, 255): uln = "GDS_{}.{}".format(l, d) ul = pcbDoc.FindUserLayer(uln) if ul != None: Transcript("User Layer {} will be erased.".format(uln), "warning") ## Select All on the user layer ug = pcbDoc.GetUserLayerGfxs(constants.epcbSelectAll, uln, False) ## Delete everything selected if ug != None: ug.Delete() else: Transcript("User Layer {} is empty.".format(uln), "note") ## Select All text on the user layer ut = pcbDoc.GetUserLayerTexts(constants.epcbSelectAll, ul.Name, False) ## Delete everything selected if ut != None: ut.Delete() else: Transcript( "User Layer {} has no text.".format(ul.Name), "note") ## Delete the user layer - it will be recreated on import try: ul.Delete() except: Transcript( "User Layer {} was not removed. Is it empty?". format(ul.Name), "warning") ## Replace existing layers? if replace: for gdslayer in gdslayers: uln = "GDS_{}".format(gdslayer) ul = pcbDoc.FindUserLayer(uln) if ul != None: Transcript("User Layer {} will be replaced.".format(uln), "warning") ## Select All on the user layer ug = pcbDoc.GetUserLayerGfxs(constants.epcbSelectAll, uln, False) ## Delete everything selected if ug != None: ug.Delete() else: Transcript("User Layer {} is empty.".format(uln), "note") ## Select All text on the user layer ut = pcbDoc.GetUserLayerTexts(constants.epcbSelectAll, ul.Name, False) ## Delete everything selected if ut != None: ut.Delete() else: Transcript("User Layer {} has no text.".format(ul.Name), "note") ## Delete the user layer - it will be recreated on import try: ul.Delete() except: Transcript( "User Layer {} was not removed. Is it empty?".format( ul.Name), "warning") ## Setup User Layers for GDS import colorpatterns = [ \ pcbApp.Utility.NewColorPattern(255, 0, 0, 100, 14, False, False), # Red \ pcbApp.Utility.NewColorPattern(0, 255, 0, 100, 14, False, False), # Blue \ pcbApp.Utility.NewColorPattern(0, 0, 255, 100, 14, False, False), # Green \ pcbApp.Utility.NewColorPattern(255, 0, 255, 100, 14, False, False), # Purple \ pcbApp.Utility.NewColorPattern(255, 255, 0, 100, 14, False, False), # Yellow \ pcbApp.Utility.NewColorPattern(0, 255, 255, 100, 14, False, False), # Aqua \ ] ## Shuffle the color patterns just to mix up the colors ... if shuffle: random.shuffle(colorpatterns) ## Loop through the layers in the GDS file and set up a user layer for each for gdslayer in gdslayers: uln = "GDS_{}".format(gdslayer) cp = colorpatterns[(gdslayers.index(gdslayer) % len(colorpatterns))] setupUserLayer(uln, cp) ## Traverse the design, looking for layers to import for struc in lib: for elem in struc: if progress: Transcript("GDS Element on Layer {}".format(elem.layer), "note") if isinstance(elem, Boundary): Transcript( "GDS Element of Datatype {}".format(elem.data_type), "note") if isinstance(elem, Path): Transcript( "GDS Element of Pathtype {}".format(elem.path_type), "note") elif isinstance(elem, Text): Transcript( "GDS Element of Texttype {}".format(elem.text_type), "note") elif isinstance(elem, Node): Transcript( "GDS Element of Nodetype {}".format(elem.node_type), "note") elif isinstance(elem, Box): Transcript( "GDS Element of Boxtype {}".format(elem.box_type), "note") if isinstance(elem, Boundary): if progress: Transcript("GDS Boundary element found ...", "note") drawBoundry(elem) elif isinstance(elem, Path): if progress: Transcript("GDS Path element found ...", "note") drawPath(elem) elif isinstance(elem, Text): if progress: Transcript("GDS Text element found ...", "note") drawText(elem) elif isinstance(elem, Node): if progress: Transcript("GDS Node element found ...", "note") Transcript("GDS Node element has not been implemented.", "warning") elif isinstance(elem, Box): if progress: Transcript("GDS Box element found ...", "note") Transcript("GDS Box element has not been implemented.", "warning") rc += 1 # if rc == 25: # break ## End Transaction? if transaction: tre = pcbDoc.TransactionEnd(True) if tre: Transcript("Ending Transaction ...", "note") ## Unlock the Server? if lockserver: pcbApp.UnlockServer Transcript("Unlocking Server ...", "note") ## Capture the end time et = time.time() ## Compute run time rt = datetime.timedelta(seconds=int(et - st)) Transcript("Processed {} records in GDS source file.".format(rc), "note") Transcript( "Start Time: {}".format( time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(st))), "note") Transcript( " End Time: {}".format( time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(et))), "note") Transcript(" Run Time: {}".format(rt.__str__()), "note")
def convert_GDS_GDSprettyjson(name, oname): level = 0 ofile = open(oname, 'wt') def indent(l): while l > 0: print(" ", end='', file=ofile) l = l - 1 def indentPrint(first, *s): if not first: print(',', file=ofile) else: print('', file=ofile) indent(level) for i in s: print(i, end='', file=ofile) first = True levelTag = [""] * 256 with open(name, 'rb') as a_file: indentPrint(first, '{') for rec in Record.iterate(a_file): if rec.tag_type == types.NODATA: if isElement(rec.tag_name): if levelTag[level] == "": indentPrint(first, quote("elements"), ": [") level = level + 1 levelTag[level] = rec.tag_name first = True indentPrint(first, "{") level = level + 1 indentPrint(True, quote("type"), ": ", quote(rec.tag_name.lower())) elif rec.tag_name == "ENDEL" or rec.tag_name == "ENDSTR" or rec.tag_name == "ENDLIB": if levelTag[level] != "": s = levelTag[level] levelTag[level] = "" level = level - 1 indentPrint(True, ']') level = level - 1 if rec.tag_name != s: indentPrint(True, '}') else: level = level - 1 indentPrint(True, '}') else: print('>', rec.tag_name) else: if rec.tag_name == "BGNLIB" or rec.tag_name == "BGNSTR": if levelTag[level] == "": indentPrint(first, quote(rec.tag_name.lower()), ": [") level = level + 1 levelTag[level] = rec.tag_name first = True indentPrint(first, "{") level = level + 1 indentPrint(True, quote('time'), ": ", show_data(rec)) else: indentPrint(first, quote(rec.tag_name.lower()), ": ", show_data(rec)) first = False if levelTag[level] != "": levelTag[level] = "" level = level - 1 indentPrint(True, ']') indentPrint(True, '}')