Memory GDS convert to DEF (gds2def)

#! /tools/cfr/bin/python
 
import os
import re
 
cfg_content_patt = """
 
TOP_CELL		  %s
GDS_MAP_FILE	/tools/fip40.3/lsi40nm_3.0/tsmc_cln40g/shared/apache/gds2def/lsi40_7+2.layermap
GDS_FILE		  %s
LEF_FILE	    %s
 
VDD_NETS {
  VDD09
}
GND_NETS {
  VSS
}
 
CORE_EXTRACTION_STARTING_LAYER  	M2
EXTRACTION_STARTING_LAYER       		M3
 
MEMORY_CELL	auto_detect
CHECK_TRACING	1
 
"""
 
def genrate_gds2def_cfg(mem_list, mem_model_dir):
  cfg_files = []
  for mem in mem_list:
    gds_file = os.path.join(mem_model_dir, "gds", mem + ".gds")
    lef_file = os.path.join(mem_model_dir, "lef", mem + ".lef")
    if not (os.path.exists(gds_file) and os.path.exists(lef_file)):
      print 'Error: GDS or LEF file not ready for memory "%s"' % mem
      continue
    cfg_content =  cfg_content_patt % (mem, gds_file, lef_file)
    cfg_file_name = "%s.cfg" % mem
    open(cfg_file_name, 'w').write(cfg_content)
    cfg_files.append(cfg_file_name)
    print "Info:  Generate cfg file %s" % cfg_file_name
  return cfg_files
 
def get_mem_list(mem_model_dir):
  gds_dir = os.path.join(mem_model_dir, "gds")
  lef_dir = os.path.join(mem_model_dir, "lef")
  gds_list = os.listdir(gds_dir)
  gds_files = []
  for f in gds_list:
    if f.endswith(".gds"):
      gds_files.append(f[:-4])
  return gds_files
 
 
def gen_run_csh(cfg_files):
  cmd = "#! /tools/cfr/bin/csh -f\n"
  for cfg_file in cfg_files:
    cmd += "gds2def -m %s\n" % cfg_file
  return cmd
 
if __name__ == "__main__":
  mem_model_dirs = [
    "/home/zx211100/Memory/current/macrocell_45.tsmc_cln45gl/model/",
    "/home/zx211100/Memory/current/macrocell_45.tsmc_cln45gs/model/"
    ]
  all_cfg_files = []
  for mem_model_dir in mem_model_dirs:
    mem_list = get_mem_list(mem_model_dir)
    cfg_files = genrate_gds2def_cfg(mem_list, mem_model_dir)
    all_cfg_files.extend(cfg_files)
  cmd = gen_run_csh(all_cfg_files)
  open("run_gds2def.csh", 'w').write(cmd)