Exemplo n.º 1
0
 def createNew(folder,name):
     paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
     paramFile.dataDict.pushBack("fileID", "Analysis::Omega3P_modeInfo")
     paramFile.dataDict.pushBack("lockdown", "False")
     paramFile.dataDict.pushBack("export", DataDict())
     #paramFile.dataDict["export"].pushBack("modes", DataDict())
     paramFile.write()
Exemplo n.º 2
0
    def createNew(folder):
        if os.path.exists(folder):
            raise TuneFreqException("Folder \"" + folder + "\" already exists")
        os.mkdir(folder)
        
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,"paramFile_scan.set"), "w")
        paramFile.dataDict.pushBack("fileID", "ParameterScan::TuneFreq")
        
        #Construct the instance name from folder
        instName = folder
        if instName[-1] == "/":
            instName = instName[0:-1]
        instName = instName = os.path.split(instName)[1]
        paramFile.dataDict.pushBack("instName", instName)
        
        paramFile.dataDict.pushBack("baseGeomInstance_name", "")
        paramFile.dataDict.pushBack("slaveGeoms", DataDict())

        paramFile.dataDict.pushBack("scanParameter_name", "")
        
        paramFile.dataDict.pushBack("predict_anaVariable","Omega3P_modeInfo.Mode.FrequencyReal_GHz")
        paramFile.dataDict.pushBack("predict_targetValue", "11.9942")
        paramFile.dataDict.pushBack("predict_tolerance", "0.001")
     
        paramFile.dataDict.pushBack("predict_a", "0")
        paramFile.dataDict.pushBack("predict_b", "0")
        paramFile.dataDict.pushBack("predict_x", "0")
        paramFile.dataDict.pushBack("predict_R2", "0")
        paramFile.dataDict.pushBack("predict_ndof", "-10") #predict_ndof only positive iff have valid prediction

        paramFile.dataDict.pushBack("lockdown", "False")

        paramFile.write()
Exemplo n.º 3
0
    def createNew(folder):
        if os.path.exists(folder):
            raise Scan2DException("Folder \"" + folder + "\" already exists")
        os.mkdir(folder)
        
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,"paramFile_scan.set"), "w")
        paramFile.dataDict.pushBack("fileID", "ParameterScan::Scan2D")
        
        #Construct the instance name from folder
        instName = folder
        if instName[-1] == "/":
            instName = instName[0:-1]
        instName = instName = os.path.split(instName)[1]
        paramFile.dataDict.pushBack("instName", instName)
        
        paramFile.dataDict.pushBack("baseGeomInstance_name", "")
        paramFile.dataDict.pushBack("slaveGeoms", DataDict())

        paramFile.dataDict.pushBack("scanParameter1_name", "")
        paramFile.dataDict.pushBack("scanParameter1_max", "0")
        paramFile.dataDict.pushBack("scanParameter1_min", "0")
        paramFile.dataDict.pushBack("scanParameter1_num", "0")
        
        paramFile.dataDict.pushBack("scanParameter2_name", "")
        paramFile.dataDict.pushBack("scanParameter2_max", "0")
        paramFile.dataDict.pushBack("scanParameter2_min", "0")
        paramFile.dataDict.pushBack("scanParameter2_num", "0")
                
        paramFile.dataDict.pushBack("lockdown", "False")

        paramFile.write()
Exemplo n.º 4
0
class DummyInput(AnalysisInterface):
    """
    Dummy analysis that doesn't actually do anything,
    used for testing the abstract machinery of input data
    """
    __paramFile = None
    
    def __init__(self, folder, name, runConfig):
        print "DummyInput::__init__()"
        self.type     = "DummyInput"
        self.folder   = folder
        self.instName = name
        self.runConfig = runConfig
        
        
        self.__paramFile = AcdOptiFileParser_simple(os.path.join(folder, name), 'rw')
        if self.__paramFile.dataDict["fileID"] != "Analysis::DummyInput":
            raise DummyInputException("Got fileID='" + self.__paramFile.dataDict["fileID"] + "'")
        self.lockdown = DataDict.boolconv(self.__paramFile.dataDict["lockdown"])

        self.exportResults = self.__paramFile.dataDict["export"]

        self.settings = self.__paramFile.dataDict["settings"]
    
    def runAnalysis(self):
        try:
            N = int(self.settings["N"])
        except ValueError:
            #Could raise an exception here, choose not to
            N = 0
        
        self.exportResults.setValSingle("result", "3.14")
        self.exportResults.setValSingle("Nparrot", str(N))
        self.exportResults.setValSingle("Npi", str(3.14*N))
        
        self.lockdown = True
        self.write()
        
    def clearLockdown(self):
        print "DummyInput::clearLockdown()"
        self.exportResults.setValSingle("result", "")
        self.lockdown = False
        self.write()
    
    def write(self):
        self.__paramFile.dataDict.setValSingle("lockdown", str(self.lockdown))
        self.__paramFile.write()
    
    @staticmethod
    def createNew(folder,name):
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::DummyInput")
        paramFile.dataDict.pushBack("lockdown", "False")
        paramFile.dataDict.pushBack("export", DataDict())
        paramFile.dataDict["export"].pushBack("result", "")
        paramFile.dataDict["export"].pushBack("Nparrot", "")
        paramFile.dataDict["export"].pushBack("Npi", "")
        paramFile.dataDict.pushBack("settings", DataDict())
        paramFile.dataDict["settings"].pushBack("N", "")
        paramFile.write()
Exemplo n.º 5
0
 def createNew(folder, parentScanName=None):
     
     if parentScanName == None:
         #If parentScan, they are created in the same folder
         os.mkdir(folder)
         
     paramFile = AcdOptiFileParser_simple(os.path.join(folder,"paramFile_scanCollection.set"), 'w')
     
     paramFile.dataDict.pushBack("fileID", "ParameterScan::ParameterScanCollection")
     
     instName = folder
     if instName[-1] == "/":
         instName = instName[0:-1]
     instName = os.path.split(instName)[1]
     paramFile.dataDict.pushBack("instName", instName)
     
     paramFile.dataDict.pushBack("scans", DataDict())
     os.mkdir(os.path.join(folder,"scans"))
     
     if parentScanName != None:
         paramFile.dataDict.pushBack("parentScan", parentScanName)
     else:
         paramFile.dataDict.pushBack("parentScan", "")
     
     paramFile.write()
Exemplo n.º 6
0
 def createNew(folder,name):
     paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
     paramFile.dataDict.pushBack("fileID", "Analysis::RFpost")
     paramFile.dataDict.pushBack("lockdown", "False")
     paramFile.dataDict.pushBack("export", DataDict())
     paramFile.dataDict.pushBack("settings", DataDict())
     paramFile.dataDict["settings"].pushBack("RFpost_LogFileName", "acdtool.log")
     paramFile.write()
Exemplo n.º 7
0
class FileList(AnalysisInterface):
    """
    Simple analysis that lists the files in the finished folder
    """

    __paramFile = None

    def __init__(self, folder, name, runConfig):
        print "FileList::__init__()"
        self.type = "FileList"
        self.folder = folder
        self.instName = name
        self.runConfig = runConfig

        self.__paramFile = AcdOptiFileParser_simple(os.path.join(folder, name), "rw")
        if self.__paramFile.dataDict["fileID"] != "Analysis::FileList":
            raise FileListException("Got fileID='" + self.__paramFile.dataDict["fileID"] + "'")
        self.lockdown = DataDict.boolconv(self.__paramFile.dataDict["lockdown"])

        self.exportResults = self.__paramFile.dataDict["export"]

    def runAnalysis(self):
        finishedFolder = self.runConfig.finishedFolder
        if finishedFolder == None:
            raise FileListException_runAna("No data to analyse")
        self.__recursiveDirList(self.exportResults["files"], finishedFolder)
        self.lockdown = True
        self.write()

    def __recursiveDirList(self, storeDict, path):
        dirlist = os.listdir(path)
        for entry in dirlist:
            path2 = os.path.join(path, entry)
            if os.path.isdir(path2):
                folderDict = storeDict.pushBack(entry, DataDict())
                self.__recursiveDirList(folderDict, path2)
            else:
                storeDict.pushBack(entry, "")

    def clearLockdown(self):
        print "FileList::clearLockdown()"
        self.exportResults["files"].clear()
        self.lockdown = False
        self.write()

    def write(self):
        self.__paramFile.dataDict.setValSingle("lockdown", str(self.lockdown))
        self.__paramFile.write()

    @staticmethod
    def createNew(folder, name):
        paramFile = AcdOptiFileParser_simple(os.path.join(folder, name), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::FileList")
        paramFile.dataDict.pushBack("lockdown", "False")
        paramFile.dataDict.pushBack("export", DataDict())
        paramFile.dataDict["export"].pushBack("files", DataDict())
        paramFile.write()
Exemplo n.º 8
0
 def createNew(folder,name):
     paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
     paramFile.dataDict.pushBack("fileID", "Analysis::DummyInput")
     paramFile.dataDict.pushBack("lockdown", "False")
     paramFile.dataDict.pushBack("export", DataDict())
     paramFile.dataDict["export"].pushBack("result", "")
     paramFile.dataDict["export"].pushBack("Nparrot", "")
     paramFile.dataDict["export"].pushBack("Npi", "")
     paramFile.dataDict.pushBack("settings", DataDict())
     paramFile.dataDict["settings"].pushBack("N", "")
     paramFile.write()
Exemplo n.º 9
0
    def createNew(folder,name):
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::ScMax")
        paramFile.dataDict.pushBack("lockdown", "False")

        paramFile.dataDict.pushBack("export", DataDict())

        paramFile.dataDict.pushBack("settings", DataDict())
        paramFile.dataDict["settings"].pushBack("RFpostName", "RFpost_local")
        paramFile.dataDict["settings"].pushBack("fieldOnSurface_basename", "fieldOnSurface_metal")
        
        paramFile.write()
Exemplo n.º 10
0
    def createNew(folder,name):
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::GroupVelocity")
        paramFile.dataDict.pushBack("lockdown", "False")

        paramFile.dataDict.pushBack("export", DataDict())

        paramFile.dataDict.pushBack("settings", DataDict())
        paramFile.dataDict["settings"].pushBack("ModeInfoName", "Omega3P_modeInfo")
        paramFile.dataDict["settings"].pushBack("RFpostName", "RFpost_local")
        paramFile.dataDict["settings"].pushBack("SurfaceID", "")
        
        paramFile.write()
Exemplo n.º 11
0
 def createNew(folder,name):
     #Create a new folder to hold the stuff
     os.mkdir(os.path.join(folder,name))
     
     #Parameter file
     paramFile = AcdOptiFileParser_simple(os.path.join(folder,name,"paramFile.set"), "w")
     paramFile.dataDict.pushBack("fileID", "Analysis::ModeFileRecalc")
     paramFile.dataDict.pushBack("lockdown", "False")
     
     paramFile.dataDict.pushBack("export", DataDict())
     
     paramFile.dataDict.pushBack("settings", DataDict())
     paramFile.dataDict["settings"].pushBack("ResultDir","omega3p_results")
     
     paramFile.write()
Exemplo n.º 12
0
 def createNew(folder,name):
     #Create a new folder to hold the stuff
     os.mkdir(os.path.join(folder,name))
     
     #Create a SolverSetup
     AcdOptiSolverManager.createNew("acdtool_rfpost", os.path.join(folder,name))
     
     #Parameter file
     paramFile = AcdOptiFileParser_simple(os.path.join(folder,name,"paramFile.set"), "w")
     paramFile.dataDict.pushBack("fileID", "Analysis::RFpost_local")
     paramFile.dataDict.pushBack("lockdown", "False")
     
     paramFile.dataDict.pushBack("export", DataDict())
     
     paramFile.dataDict.pushBack("settings", DataDict())
     paramFile.dataDict["settings"].pushBack("L","")
     
     paramFile.write()
Exemplo n.º 13
0
    def createNew(folder):
        if os.path.exists(folder):
            raise Scan2D_TuneException("Folder \"" + folder + "\" already exists")
        os.mkdir(folder)
        
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,"paramFile_scan.set"), "w")
        paramFile.dataDict.pushBack("fileID", "ParameterScan::Scan2D_Tune")
        
        #Construct the instance name from folder
        instName = folder
        if instName[-1] == "/":
            instName = instName[0:-1]
        instName = instName = os.path.split(instName)[1]
        paramFile.dataDict.pushBack("instName", instName)
        
        paramFile.dataDict.pushBack("baseGeomInstance_name", "")
        paramFile.dataDict.pushBack("slaveGeoms", DataDict())

        paramFile.dataDict.pushBack("scanParameter1_name", "")
        paramFile.dataDict.pushBack("scanParameter1_max", "0")
        paramFile.dataDict.pushBack("scanParameter1_min", "0")
        paramFile.dataDict.pushBack("scanParameter1_num", "0")
        
        paramFile.dataDict.pushBack("scanParameter2_name", "")
        paramFile.dataDict.pushBack("scanParameter2_max", "0")
        paramFile.dataDict.pushBack("scanParameter2_min", "0")
        paramFile.dataDict.pushBack("scanParameter2_num", "0")
        
        paramFile.dataDict.pushBack("tune_parameter","")
        paramFile.dataDict.pushBack("tune_anaVariable","Omega3P_modeInfo.Mode.FrequencyReal_GHz")
        paramFile.dataDict.pushBack("tune_targetValue","11.9942")
        paramFile.dataDict.pushBack("tune_initialPoints", DataDict())
        
        paramFile.dataDict.pushBack("tune_ipModelDict", DataDict())
        paramFile.dataDict.pushBack("tune_useModelPoints", "False")
        
        paramFile.dataDict.pushBack("lockdown", "False")

        paramFile.write()
    
        #Setup the ScanCollection in the same folder
        ParameterScanCollection.createNew(folder, instName)
Exemplo n.º 14
0
    def createNew(folder):
        if os.path.exists(folder):
            raise DummySubscanException('Folder "' + folder + '" already exists')
        os.mkdir(folder)

        paramFile = AcdOptiFileParser_simple(os.path.join(folder, "paramFile_scan.set"), "w")
        paramFile.dataDict.pushBack("fileID", "ParameterScan::DummySubscan")

        # Construct the instance name from folder
        instName = folder
        if instName[-1] == "/":
            instName = instName[0:-1]
        instName = instName = os.path.split(instName)[1]
        paramFile.dataDict.pushBack("instName", instName)

        paramFile.dataDict.pushBack("baseGeomInstance_name", "")
        paramFile.dataDict.pushBack("slaveGeoms", DataDict())

        paramFile.dataDict.pushBack("lockdown", "False")

        paramFile.write()

        # Setup the ScanCollection in the same folder
        ParameterScanCollection.createNew(folder, instName)
Exemplo n.º 15
0
class Omega3P_modeInfo(AnalysisInterface):
    """
    Analysis that presents the information
    being output directly from Omega3P per mode 
    """
    __paramFile = None
    
    def __init__(self, folder, name, runConfig):
        print "Omega3P_modeInfo::__init__()"
        self.type      = "Omega3P_modeInfo"
        self.folder    = folder
        self.instName  = name
        self.runConfig = runConfig
        
        self.__paramFile = AcdOptiFileParser_simple(os.path.join(folder, name), 'rw')
        if self.__paramFile.dataDict["fileID"] != "Analysis::Omega3P_modeInfo":
            raise Omega3P_modeInfo_exception("Got fileID='" + self.__paramFile.dataDict["fileID"] + "'")
        self.lockdown = DataDict.boolconv(self.__paramFile.dataDict["lockdown"])

        self.exportResults = self.__paramFile.dataDict["export"]
    
        if "modes" in self.exportResults:
            #Convert to new format
            print "Converting to new format..."
            modes = self.exportResults["modes"].copy()
            self.exportResults.clear()
            for (k,v) in modes:
                self.exportResults.pushBack(k,v)
            self.write()
    
    def runAnalysis(self):
        finishedFolder = self.runConfig.finishedFolder
        if finishedFolder == None:
            raise Omega3P_modeInfo_exception_runAna("No data to analyze")
        
        if os.path.isdir(os.path.join(finishedFolder, "omega3p_results")):
            outputFilePath = os.path.join(finishedFolder, "omega3p_results", "omega3p.out")
        elif os.path.isfile(os.path.join(finishedFolder,"output")):
            outputFilePath = os.path.join(finishedFolder, "output")
        else:
            #self.exportResults.setValSingle("modes", "!!FILE_NOT_FOUND!!")
            raise Omega3P_modeInfo_exception_runAna("File '" + os.path.join(finishedFolder, "omega3p_results") + "' not found")
            
        outputFile = open(outputFilePath, "r")
        #Find the lines with KVC syntax
#        data = ""
#        lastLineWasComment = True
#        for line in outputFile.readlines():
#            ls = line.strip()
#            if ls.startswith("/*") and ls.endswith("*/"):
#                if lastLineWasComment:
#                    continue #comments at beginning
#                else:
#                    break #comments at end
#            #Not a comment line
#            data += line
#            lastLineWasComment = False
#        
        
        #Find the lines relating to mode (else the timestamps will crash the parser due to extra ":")
        thereYet=False
        data = ""
        for line in outputFile.readlines():
            ls = line.strip()
            if ls.startswith("Mode :"):
                thereYet = True
            elif not thereYet:
                continue
            elif ls.startswith("Mesh :") or ls.startswith("AMRLevel"):
                break
            data += line
        print data
        
        #Parse the data
        dataParser = AcdOptiFileParser_KVC(data,"s")
        
        for (modeName, mode) in dataParser.dataDict:
            #print mode
            if "," in mode["TotalEnergy"]:
                te = mode["TotalEnergy"]
                teSplit = te.split(",")
                mode.delItem("TotalEnergy")
                mode.pushBack("TotalEnergyReal", teSplit[0].strip())
                mode.pushBack("TotalEnergyImag", teSplit[1].strip())
            if "," in mode["Frequency"]:
                freq = mode["Frequency"]
                freqSplit = freq.split(",")
                mode.delItem("Frequency")
                mode.pushBack("FrequencyReal", freqSplit[0].strip())
                mode.pushBack("FrequencyReal_GHz", str(float(freqSplit[0].strip())/1e9))
                mode.pushBack("FrequencyImag", freqSplit[1].strip())
                mode.pushBack("FrequencyImag_GHz", str(float(freqSplit[1].strip())/1e9))
            else:
                mode.pushBack("Frequency_GHz", str(float(mode["Frequency"])/1e9))
            self.exportResults.pushBack(modeName,mode.copy())
        
        self.lockdown = True
        self.write()
    def clearLockdown(self):
        self.exportResults.clear()
        self.lockdown = False
        self.write()
    
    def write(self):
        self.__paramFile.dataDict.setValSingle("lockdown", str(self.lockdown))
        self.__paramFile.write()
    
    @staticmethod
    def createNew(folder,name):
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::Omega3P_modeInfo")
        paramFile.dataDict.pushBack("lockdown", "False")
        paramFile.dataDict.pushBack("export", DataDict())
        #paramFile.dataDict["export"].pushBack("modes", DataDict())
        paramFile.write()
Exemplo n.º 16
0
class RFpost(AnalysisInterface, RFpostParser):
    """
    Parses rfpost output files
    """
    __paramFile = None
    fname = None
    
    def __init__(self, folder, name, runConfig):
        print "RFpost::__init__()"
        self.type     = "RFpost"
        self.folder   = folder
        self.instName = name
        self.runConfig = runConfig
        
        
        self.__paramFile = AcdOptiFileParser_simple(os.path.join(folder, name), 'rw')
        if self.__paramFile.dataDict["fileID"] != "Analysis::RFpost":
            raise RFpostException("Got fileID='" + self.__paramFile.dataDict["fileID"] + "'")
        self.lockdown = DataDict.boolconv(self.__paramFile.dataDict["lockdown"])

        self.exportResults = self.__paramFile.dataDict["export"]

        self.settings = self.__paramFile.dataDict["settings"]
    
    def runAnalysis(self):
        if self.settings["RFpost_LogFileName"] == "":
            raise RFpostException_runAna("Input file not set")
        self.fname = fname = os.path.join(self.runConfig.finishedFolder, self.settings["RFpost_LogFileName"])
        if not os.path.isfile(fname):
            raise RFpostException_runAna("Could not find input file '" + fname + "'")
        
        ifile = open(fname, 'r')
        fileData = ifile.read()
        ifile.close()
        
        addDic = self.parseData(fileData)
        for (k,v) in addDic:
            self.exportResults.pushBack(k,v)

        self.lockdown = True
        self.write()
    
    def clearLockdown(self):
        print "RFpost::clearLockdown()"
        self.exportResults.clear()
        self.lockdown = False
        self.fname = None
        self.write()
    
    def write(self):
        self.__paramFile.dataDict.setValSingle("lockdown", str(self.lockdown))
        self.__paramFile.write()
    
    @staticmethod
    def createNew(folder,name):
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::RFpost")
        paramFile.dataDict.pushBack("lockdown", "False")
        paramFile.dataDict.pushBack("export", DataDict())
        paramFile.dataDict.pushBack("settings", DataDict())
        paramFile.dataDict["settings"].pushBack("RFpost_LogFileName", "acdtool.log")
        paramFile.write()
Exemplo n.º 17
0
class ParameterScanInterface(object):
    
    type           = None 
    folder         = None #Folder where it stores it data
    scanCollection = None #Pointer to ParameterScanCollection
    instName       = None #Name of this particular ParameterScan instance
    
    _paramFile    = None
    
    baseGeomInstance = None #Geometry instance on which to base the scan
    slaveGeoms       = None #List of geometry instances "belonging" to this scan
    slaveScanCollection = None #ParameterScanCollection with slave scans
    
    lockdown = False  #Set to true once we have slaveGeoms. When true baseGeom isn't changeable
    
    def __init__(self,folder,collection, typ):
        from ParameterScanCollection import ParameterScanCollection
        assert typ in ParameterScanCollection.parameterScanTypes or "ParameterScan::"+ typ in ParameterScanCollection.parameterScanTypes
        self.type      = typ
        self.folder    = folder
        self.scanCollection = collection
        
        #Construct the instance name from folder
        instName = folder
        if instName[-1] == "/":
            instName = instName[0:-1]
        self.instName = instName = os.path.split(instName)[1]
        
        #Load paramFile.set
        self._paramFile = AcdOptiFileParser_simple(os.path.join(folder, "paramFile_scan.set"), 'rw')
        if self._paramFile.dataDict["fileID"] != self.type:
            raise ParameterScanInterfaceException_init("Got fileID='" + self._paramFile.dataDict["fileID"] + "'")
        
        if self._paramFile.dataDict.getValSingle("instName") != self.instName:
            raise ParameterScanInterfaceException_init("instName doesn't match folder name")
    
        self.lockdown = DataDict.boolconv(self._paramFile.dataDict["lockdown"])
        
        baseGeomInstance_name = self._paramFile.dataDict["baseGeomInstance_name"]
        if baseGeomInstance_name == "":
            self.baseGeomInstance = None
            assert len(self._paramFile.dataDict["slaveGeoms"]) == 0
            assert self.lockdown == False
        else:
            self.baseGeomInstance = self.getProject().geomCollection.geomInstances[baseGeomInstance_name]
        
        self.slaveGeoms = {}
        for (geomName, nothingOfInterest) in self._paramFile.dataDict["slaveGeoms"]:
            #Mutal referencing
            self.slaveGeoms[geomName] = self.getProject().geomCollection.geomInstances[geomName]
            self.slaveGeoms[geomName].scanInstances.append(self)
        if len(self.slaveGeoms) > 0:
            assert self.lockdown == True
             
    def write(self):
        "Update slaveGeoms and write to paramfile"
        if len(self.slaveGeoms) > 0:
            assert self.lockdown == True
            
        for geomName in self.slaveGeoms.keys():
            if not geomName in self._paramFile.dataDict["slaveGeoms"]:
                self._paramFile.dataDict["slaveGeoms"].pushBack(geomName, "")
        
        if self.lockdown == True:
            assert self.baseGeomInstance != None
            assert self._paramFile.dataDict["baseGeomInstance_name"] == self.baseGeomInstance.instName

        if self.baseGeomInstance != None:
            assert self.baseGeomInstance in self.getProject().geomCollection.geomInstances.values()
            self._paramFile.dataDict["baseGeomInstance_name"] = self.baseGeomInstance.instName
        else:
            self._paramFile.dataDict["baseGeomInstance_name"] = ""
        
        self._paramFile.dataDict["lockdown"] = str(self.lockdown) 

        self._paramFile.write() 
    
    def setBaseGeom(self,baseGeomName):
        assert self.lockdown == False, "Can't change baseGeomInstance once we have lockdown"
        assert len(self.slaveGeoms) == 0
        
        self.baseGeomInstance = self.getProject().geomCollection.geomInstances[baseGeomName]
        self.write()
    
    @staticmethod
    def createNew(folder):
        """
        Create a new ParameterScan of the implementing type
        """
        raise NotImplementedError("Please implement a createNew method in your class!")

    @classmethod
    def createNew_clone(cls, folder, collection, cloneFrom):
        """
        Clone an already existing ParameterScan
        of the implementing type.
        """
        print "ParameterScan::createNew_clone()"
        raise NotImplementedError
#        cls.createNew(folder)
#        newScan = cls(folder, collection)
#        if cloneFrom.settings != None:
#            newScan.settings.clear()
#            for (k,v) in cloneFrom.settings:
#                if isinstance(v,DataDict):
#                    newScan.settings.pushBack(k,v.copy())
#                else:
#                    newScan.settings.pushBack(k,v)
#            newScan.write()
#            
#        return newScan
 
    # # # # # # # Utility methods # # # # # # # # # # # # # # # # # # # # # # #
    def getProject(self):
        #Find the project's GeometryCollection:
        from acdOpti.AcdOptiProject import AcdOptiProject
        scanCollectionParent = self.scanCollection.parent
        while True:
            if isinstance(scanCollectionParent,AcdOptiProject):
                return scanCollectionParent
            else:
                scanCollectionParent = scanCollectionParent.parent
    
    @staticmethod
    def getAnalysisResults(geom,anaVarString):
        """
        For a geom, retrive all analysis results using the address anaVarString,
        maximum one result per analysisInstance.
        AnaVarString syntax:
         key.key[idx].key....
         If [idx] not present, assume [idx]=0
         First key is analysis instance name
        """
        anaVarSplit = anaVarString.split(".")
        retVals = []
        
        for mesh in geom.meshInsts.itervalues():
            for rc in mesh.runConfigs.itervalues():
                for ana in rc.analysis.itervalues():
                    if ana.instName == anaVarSplit[0]:
                        #Recursive function to find the analysis result
                        #Uses the usual key.key[idx].key.... syntax
                        #If not [idx] present, assume idx=0
                        #If not found, return None
                        def dictRecDig(avsRemaining, dictBranch):
                            avsParsed = re.match(r'(\w)+[(\d+)]',avsRemaining[0])
                            if avsParsed != None:
                                nextName = avsParsed.group(1)
                                nextNumber = int(avsParsed.group(2))
                            else:
                                nextName = avsRemaining[0]
                                nextNumber = 0

                            try:
                                nextBranch = dictBranch.getVals(nextName)[nextNumber]
                            except IndexError:
                                print "WARNING in dictRecDig(): Key '" + avsRemaining[0] + "' not found"
                                return None
                            
                            if isinstance(nextBranch,DataDict):
                                if len(avsRemaining) == 1:
                                    print "WARNING in dictRecDig(): More depth than keys"
                                    return None
                                return dictRecDig(avsRemaining[1:],nextBranch)
                            else:
                                if len(avsRemaining) > 1:
                                    print "WARNING in dictRecDig(): More keys than depth"
                                    return None
                                return nextBranch
                        r = dictRecDig(anaVarSplit[1:],ana.exportResults)
                        if r != None:
                            retVals.append(r)
        return retVals
    
    @staticmethod
    def fit1D(x,y, deg):
        """
        For two lists of values (x,y), return a a fitted model ŷ = a0 + a1*x + a2*x^2 + ... + adeg*x^deg.
        Also return number of degrees of freedom and R^2 = sum (ŷ(x_i)-y_i)^2.
        Return:
        ((a0,a1,...,adeg), ndof, R^2) 
        """
        
        if len(x) != len(y):
            raise FittingException("length of x (%i) should be equal to length of y (%i)" % ( len(x), len(y) ) )
        ndof = len(y) - (deg+1) 
        if ndof < 0:
            raise FittingException_NDOF("ndof =", ndof, "< 0, can't fit.")
        A = [np.ones(len(x))]
        for i in xrange(deg):
            A.append(np.asarray(x)**(i+1))
        A = np.vstack(A).T
        
        model = np.linalg.lstsq(A,y)[0]
        
        R2 = 0.0
        for i in xrange(len(x)):
            R2 += (y[i]-ParameterScanInterface.eval1D(x[i],model))**2

        return (model, ndof, R2)

    @staticmethod
    def eval1D(x,model):
        """
        Evaluate a polynomial y=model[0]+model[1]*x+model[2]*x**2 + ... model[n]*x**n.
        Works with x both float as and ndarray.
        """
        y = None
        if type(x) == float:
            y = 0.0
        elif type(x) == np.ndarray:
            y = np.zeros_like(x)
        for i in xrange(len(model)):
            y += model[i]*x**i
        return y
Exemplo n.º 18
0
class ScMax(AnalysisInterface):
    """
    Calculate the peak Sc value using a fieldOnSurface file
    """
    __paramFile = None
    
    def __init__(self, folder, name, runConfig):
        print "ScMax::__init__()"
        self.type     = "ScMax"
        self.folder   = folder
        self.instName = name
        self.runConfig = runConfig
        
        self.__paramFile = AcdOptiFileParser_simple(os.path.join(folder, name), 'rw')
        if self.__paramFile.dataDict["fileID"] != "Analysis::ScMax":
            raise ScMaxException("Got fileID='" + self.__paramFile.dataDict["fileID"] + "'")
        self.lockdown = DataDict.boolconv(self.__paramFile.dataDict["lockdown"])

        self.exportResults = self.__paramFile.dataDict["export"]

        self.settings = self.__paramFile.dataDict["settings"]
    
    @staticmethod
    def crossProd(a,b):
        r = np.array((a[1]*b[2]-a[2]*b[1], -a[0]*b[2]+a[2]*b[0], a[0]*b[1]-a[1]*b[0]))
        return r
    @staticmethod
    def complexConjVec(a):
        r = np.empty_like(a);
        for i in xrange(len(a)):
            r[i] = complex(a[i].real, -a[i].imag)
        return r
    @staticmethod
    def makeComplxVec(ampl, phas):
        r = np.array(map(lambda (a,p): complex(a*math.cos(p),a*math.sin(p)),zip(ampl,phas)))
        return r
    mu0 = (4e-7*np.pi)
    
    def runAnalysis(self):
        print "ScMax::RunAnalysis()"
        assert not self.lockdown
        
        try:
            RFpost = self.runConfig.analysis[self.settings["RFpostName"]]
        except KeyError:
            raise ScMaxException_runAna("Key for RFpostName not found")
        if not RFpost.lockdown:
            RFpost.runAnalysis() 
        
        #Load the files
        print "Loading files..."
        basefname = os.path.join(RFpost.folder, RFpost.instName, self.settings["fieldOnSurface_basename"])
        try:
            file_eField = open(basefname + ".e", 'r');
            file_bField = open(basefname + ".b", 'r');
        except IOError:
            raise ScMaxException_runAna("Could not open file(s)")
        (Epos,Eampl,Ephas) = self.__readfile(file_eField)
        (Bpos,Bampl,Bphas) = self.__readfile(file_bField)
        file_eField.close()
        file_bField.close()
        
        #Calculate Sc in every point, find the maximum
        print "Calculating..."
        maxPos = None
        maxSc = -1.0
        
        for i in xrange(len(Epos)):
            #Complex S-vectorfield, frequency domain definition
            S = 0.5 * self.crossProd( self.makeComplxVec(Eampl[i],Ephas[i]), self.complexConjVec(self.makeComplxVec(Bampl[i]/self.mu0,Bphas[i])) )
            Sc = np.sqrt(np.sum((np.abs(np.real(S))+np.abs(np.imag(S))/6.0)**2))
            if Sc > maxSc:
                maxSc = Sc
                maxPos = Epos[i]
                #assert Epos[i] == Bpos[i]

        #Try to find Ez_ave for the right surface
        Ez_ave = None
        if "RoverQ" in RFpost.exportResults:
            RoQ = RFpost.exportResults["RoverQ"]
            try:
                Ez_ave = float(RoQ["mode"]["Ez_ave"])
            except AcdOptiException_dataDict_getValsSingle:
                print "Couldn't find normalization"
        
        
        self.exportResults.pushBack("maxSc", str(maxSc))
        if Ez_ave != None:
            self.exportResults.pushBack("maxSc_norm", str(maxSc/Ez_ave**2))
        self.exportResults.pushBack("maxPos", str(maxPos))
        
        self.lockdown = True
        self.write()
    
    def __readfile(self, fileObject):
        print "ScMax::__readfile(), fileObject = " + str(fileObject)
        
        #Create storage
        pos  = []
        #real = []
        #imag = []
        ampl = []
        phas = []
        
        #Read files
        for line in fileObject.readlines():
            if line[0] == "!":
                continue #Skip comment line at the beginning
            ls = line.split()
    
            #Get position
            pos.append(map(float,ls[0:3]))
    
            #E-field
            #real.append(map(float,ls[3:6]))
            real = map(float,ls[3:6])
            #imag.append(map(float,ls[6:9]))
            imag = map(float,ls[6:9])
            
            ampl.append(map(lambda r,i: np.sqrt(r**2 + i**2), real, imag))
            phas.append(np.arctan2(imag,real))
        
        #Convert to numpy arrays
        pos  = np.asarray(pos)
        #real = np.asarray(real)
        #imag = np.asarray(imag)
        ampl = np.asarray(ampl)
        phas = np.asarray(phas)
    
        #return (pos,real,imag,ampl,phas)
        return (pos,ampl,phas)
        
    def clearLockdown(self):
        print "ScMax::clearLockdown()"
        self.exportResults.clear()
        self.lockdown = False
        self.write()
    
    def write(self):
        self.__paramFile.dataDict.setValSingle("lockdown", str(self.lockdown))
        self.__paramFile.write()
    
    @staticmethod
    def createNew(folder,name):
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::ScMax")
        paramFile.dataDict.pushBack("lockdown", "False")

        paramFile.dataDict.pushBack("export", DataDict())

        paramFile.dataDict.pushBack("settings", DataDict())
        paramFile.dataDict["settings"].pushBack("RFpostName", "RFpost_local")
        paramFile.dataDict["settings"].pushBack("fieldOnSurface_basename", "fieldOnSurface_metal")
        
        paramFile.write()
Exemplo n.º 19
0
class ModeFileRecalc(AnalysisInterface):
    """
    Analysis that runs acdtool postprocess eigentomode locally,
    recreating the buggy modefiles you get from paralell O3P. 
    """
    __paramFile = None
        
    def __init__(self, folder, name, runConfig):
        print "ModeFileRecalc::__init__()"
        self.type     = "ModeFileRecalc"
        self.folder   = folder
        self.instName = name
        self.runConfig = runConfig
        
        #Load paramFile
        self.__paramFile = AcdOptiFileParser_simple(os.path.join(folder, name, "paramFile.set"), 'rw')
        if self.__paramFile.dataDict["fileID"] != "Analysis::ModeFileRecalc":
            raise ModeFileRecalcException("Got fileID='" + self.__paramFile.dataDict["fileID"] + "'")
        self.lockdown = DataDict.boolconv(self.__paramFile.dataDict["lockdown"])

        self.exportResults = self.__paramFile.dataDict["export"]
    
        #Load the settings
        self.settings = self.__paramFile.dataDict["settings"]
    
    def runAnalysis(self):
        print "ModeFileRecalc::runAnalysis()"        
        assert not self.lockdown
        
        #Generate the setup file
        self.lockdown = True

        origResultDir = self.settings["ResultDir"] #Subdirectory whith the data
        dataPath = os.path.join(self.folder, self.instName, "data") #Path to symlink to data folder
        dataPath2 = os.path.join(dataPath, origResultDir) #Path to O3P etc. results thorough symlink
        
        #Create a symlink to avoid long folder names (ACDtool doesn't like that)
        if os.path.islink(dataPath):
            os.unlink(dataPath)
        os.symlink(self.runConfig.finishedFolder, dataPath) #UNIX only!
        
        #Modify the postprocess.in file to the right path
        shutil.copy(os.path.join(dataPath2, "VECTOR", "postprocess.in"),\
                    os.path.join(self.folder, self.instName, "postprocess.in.bak"))
        
        postFile = AcdOptiFileParser_KVC(os.path.join(dataPath2, "VECTOR", "postprocess.in"),"rw")
        postFile.dataDict["ModelInfo"].setValSingle("File", os.path.join(dataPath, "mesh.ncdf"))
        postFile.dataDict["CheckPoint"].setValSingle("Directory", os.path.join(os.path.join(dataPath2, "VECTOR")))
        postFile.write()
        
        #Check that we don't destroy any data...
        if os.path.isfile(os.path.join(dataPath, "acdtool.log")) or os.path.isfile(os.path.join(dataPath, "acdtool.warn")):
            #Restore stuff
            shutil.copy(os.path.join(self.folder, self.instName, "postprocess.in.bak"),\
                        os.path.join(dataPath2, "VECTOR", "postprocess.in"))
            os.unlink(dataPath)
            raise ModeFileRecalcException_runAna("acdtool log files already exists")
        
        #Move the old modefile out of the way...
        oldFilesFolder = os.path.join(self.folder,self.instName, "oldModes")
        if os.path.isdir(oldFilesFolder):
            offls = os.listdir(oldFilesFolder)
            if len(offls) > 0:
                shutil.copy(os.path.join(self.folder, self.instName, "postprocess.in.bak"),\
                            os.path.join(dataPath2, "VECTOR", "postprocess.in"))   
                raise ModeFileRecalcException_runAna
        else:
            os.mkdir(oldFilesFolder)
        files = os.listdir(dataPath2)
        movedFiles = []
        for f in files:
            if f.startswith("mode.") and f.endswith(".mod"):
                shutil.move( os.path.join(dataPath2,f), os.path.join(oldFilesFolder,f) )
                movedFiles.append(f)
        
        #Run AcdTool!
        try:
            AcdOptiAcdtoolWrapper.eigentomode(origResultDir, dataPath)
        except:
            shutil.move( os.path.join(dataPath,"acdtool.log"), os.path.join(self.folder,self.instName,"acdtool.log"))
            raise
        
        #Move newly created files to results dir
        files = os.listdir(dataPath2)
        for f in files:
            if f.startswith("mode.") and f.endswith(".mod"):
                shutil.move( os.path.join(dataPath2,f), os.path.join(self.folder,self.instName,f)) 
        shutil.move( os.path.join(dataPath,"acdtool.log"), os.path.join(self.folder,self.instName,"acdtool.log"))
        shutil.move( os.path.join(dataPath,"acdtool.warn"), os.path.join(self.folder,self.instName,"acdtool.warn"))
        
        #Restore stuff
        shutil.copy(os.path.join(self.folder, self.instName, "postprocess.in.bak"),\
                    os.path.join(dataPath2, "VECTOR", "postprocess.in"))
        
        for f in movedFiles:
            shutil.move(os.path.join(oldFilesFolder,f), os.path.join(dataPath2,f))
        os.rmdir(oldFilesFolder)
        
        os.unlink(dataPath)
        
        #Save results
        self.exportResults.pushBack("Job", "complete")
        
        self.write()
        
    def clearLockdown(self):
        print "ModeFileRecalc::clearLockdown()"
        if not self.lockdown:
            return
        self.exportResults.clear()
        self.lockdown = False
        self.write()
    
    def write(self):
        self.__paramFile.dataDict.setValSingle("lockdown", str(self.lockdown))
        self.__paramFile.write()
    
    @staticmethod
    def createNew(folder,name):
        #Create a new folder to hold the stuff
        os.mkdir(os.path.join(folder,name))
        
        #Parameter file
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,name,"paramFile.set"), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::ModeFileRecalc")
        paramFile.dataDict.pushBack("lockdown", "False")
        
        paramFile.dataDict.pushBack("export", DataDict())
        
        paramFile.dataDict.pushBack("settings", DataDict())
        paramFile.dataDict["settings"].pushBack("ResultDir","omega3p_results")
        
        paramFile.write()
Exemplo n.º 20
0
class ParameterScanCollection(object):
    """
    Collection class organizing the contents of a ParameterScan folder
    """

    folder   = None
    instName = None #Name of this instance. Set to "ParameterScanCollection" iff parent is AcdOptiProject
    parent   = None #AcdOptiProject OR another ParameterScanCollection (including implementations)
    parentScan = None #If the scan collection is owned by a ParameterScan, this points to it
    
    __paramfile = None
    
    scans = None #Map of objects implementing ParameterScanInterface 
    
    parameterScanTypes = ["ParameterScan::Dummy", "ParameterScan::DummySubscan", "ParameterScan::TuneFreq",\
                          "ParameterScan::Scan2D", "ParameterScan::Scan2D_Tune"]
    
    def __init__(self, folder, parent, parentScan=None):
        self.folder = folder
        self.parent = parent
        
        #Construct the instance name from folder
        instName = folder
        if instName[-1] == "/":
            instName = instName[0:-1]
        self.instName = instName = os.path.split(instName)[1]
        
        from acdOpti.AcdOptiProject import AcdOptiProject
        if not isinstance(parent,ParameterScanCollection) and not isinstance(parent, AcdOptiProject):
            raise ParameterScanCollectionException("Error when initializing ParameterScanCollection, "+\
                                                   "type(parent) must be AcdOptiProject or ParameterScanCollection, type was '" + str(type(parent)))
        elif self.instName == "ParameterScanCollection" and not isinstance(parent, AcdOptiProject):
            raise ParameterScanCollectionException("Error when initializing ParameterScanCollection, instName='"+self.instName+"', but type(parent)="+str(type(parent)))
        
        #Load paramFile
        self.__paramfile = AcdOptiFileParser_simple(os.path.join(folder, "paramFile_scanCollection.set"), 'rw')
        if self.__paramfile.dataDict["fileID"] != "ParameterScan::ParameterScanCollection":
            raise ParameterScanCollectionException("Error loading ParameterScanCollection: Got wrong fileID='" + self.paramFile.dataDict["fileID"] + "'")            
        if self.__paramfile.dataDict["instName"] != self.instName:
            raise ParameterScanCollectionException("Error loading ParameterScanCollection: instName mismatch")
        
        #Look for scans
        self.scans = {}
        for (scanName, scanType) in self.__paramfile.dataDict["scans"]:
            childPath = os.path.join(self.folder,"scans",scanName)
            if not os.path.exists(childPath):
                raise ParameterScanCollectionException("Error loading ParameterScanCollection, path='" + childPath + "' does not exist")
            if scanType == "ParameterScan::Dummy":
                from Dummy import Dummy
                self.scans[scanName] = Dummy(childPath, self)
            elif scanType == "ParameterScan::DummySubscan":
                from DummySubscan import DummySubscan
                self.scans[scanName] = DummySubscan(childPath, self)
            elif scanType == "ParameterScan::TuneFreq":
                from TuneFreq import TuneFreq
                self.scans[scanName] = TuneFreq(childPath,self)
            elif scanType == "ParameterScan::Scan2D":
                from Scan2D import Scan2D
                self.scans[scanName] = Scan2D(childPath,self)
            elif scanType == "ParameterScan::Scan2D_Tune":
                from Scan2D_Tune import Scan2D_Tune
                self.scans[scanName] = Scan2D_Tune(childPath,self)
            else:
                if scanType in self.parameterScanTypes or "ParameterScan::"+scanType in self.parameterScanTypes:
                    raise NotImplementedError("Forgot to implement support for ParameterScan '" + scanType + "'!")
                raise ParameterScanCollectionException("Unknown scanType='"+scanType+"'")
        
        #Setup parentScan
        if parentScan != None:
            from acdOpti.parameterScan.ParameterScanInterface import ParameterScanInterface
            assert isinstance(parentScan, ParameterScanInterface)
            
            if self.__paramfile.dataDict["parentScan"] != parentScan.instName:
                raise ParameterScanCollectionException("ParentScan mismatch, got '"+self.__paramfile.dataDict["parentScan"]+"' from paramfile" )
            
            self.parentScan = parentScan
    
    def addNew(self, name, scanType):
        """
        Try to add a new scan with the given name and tnype
        ParameterScanCollectionException is raised if there is a problem (name already taken or invalid type).
        Returns a reference to the newly created scan.
        """
        
        if name in self.scans.keys():
            raise ParameterScanCollectionException("Name '" + name + "' already taken")
        
        scanFolder = os.path.join(self.folder, "scans", name)
        
        if scanType == "ParameterScan::Dummy" or scanType == "Dummy":
            from Dummy import Dummy
            Dummy.createNew(scanFolder)
            self.scans[name] = newScan = Dummy(scanFolder, self)
        elif scanType == "ParameterScan::DummySubscan" or scanType == "DummySubscan":
            from DummySubscan import DummySubscan
            DummySubscan.createNew(scanFolder)
            self.scans[name] = newScan = DummySubscan(scanFolder, self)
        elif scanType == "ParameterScan::TuneFreq" or scanType == "TuneFreq":
            from TuneFreq import TuneFreq
            TuneFreq.createNew(scanFolder)
            self.scans[name] = newScan = TuneFreq(scanFolder,self)
        elif scanType == "ParameterScan::Scan2D" or scanType == "Scan2D":
            from Scan2D import Scan2D
            Scan2D.createNew(scanFolder)
            self.scans[name] = newScan = Scan2D(scanFolder,self)
        elif scanType == "ParameterScan::Scan2D_Tune" or scanType == "Scan2D_Tune":
            from Scan2D_Tune import Scan2D_Tune
            Scan2D_Tune.createNew(scanFolder)
            self.scans[name] = newScan = Scan2D_Tune(scanFolder,self)
        else:
            if scanType in self.parameterScanTypes or "ParameterScan::"+scanType in self.parameterScanTypes:
                raise NotImplementedError("Forgot to implement support for ParameterScan '" + scanType + "'!")
            raise ParameterScanCollectionException("Unknown ParameterScan type '" + scanType + "'")
        
        self.__paramfile.dataDict["scans"].pushBack(name,newScan.type)
        self.__paramfile.write()
        
        return self.scans[name]
    
    
    @staticmethod
    def createNew(folder, parentScanName=None):
        
        if parentScanName == None:
            #If parentScan, they are created in the same folder
            os.mkdir(folder)
            
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,"paramFile_scanCollection.set"), 'w')
        
        paramFile.dataDict.pushBack("fileID", "ParameterScan::ParameterScanCollection")
        
        instName = folder
        if instName[-1] == "/":
            instName = instName[0:-1]
        instName = os.path.split(instName)[1]
        paramFile.dataDict.pushBack("instName", instName)
        
        paramFile.dataDict.pushBack("scans", DataDict())
        os.mkdir(os.path.join(folder,"scans"))
        
        if parentScanName != None:
            paramFile.dataDict.pushBack("parentScan", parentScanName)
        else:
            paramFile.dataDict.pushBack("parentScan", "")
        
        paramFile.write()
Exemplo n.º 21
0
class GroupVelocity(AnalysisInterface):
    """
    Calculate the group velocity of the cell by powerFlow,
    cell length (both from RFpost_local), and stored energy (Omega3P_modeInfo)
    """
    __paramFile = None
    
    def __init__(self, folder, name, runConfig):
        print "GroupVelocity::__init__()"
        self.type     = "GroupVelocity"
        self.folder   = folder
        self.instName = name
        self.runConfig = runConfig
        
        self.__paramFile = AcdOptiFileParser_simple(os.path.join(folder, name), 'rw')
        if self.__paramFile.dataDict["fileID"] != "Analysis::GroupVelocity":
            raise GroupVelocityException("Got fileID='" + self.__paramFile.dataDict["fileID"] + "'")
        self.lockdown = DataDict.boolconv(self.__paramFile.dataDict["lockdown"])

        self.exportResults = self.__paramFile.dataDict["export"]

        self.settings = self.__paramFile.dataDict["settings"]
    
    def runAnalysis(self):
        print "GroupVelocity::RunAnalysis()"
        assert not self.lockdown
        
        try:
            surfID = int(self.settings["SurfaceID"])
        except ValueError:
            raise GroupVelocityException_runAna("SurfaceID setting not understood")
        
        try:
            RFpost = self.runConfig.analysis[self.settings["RFpostName"]]
        except KeyError:
            raise GroupVelocityException_runAna("Key for RFpostName not found")
        if not RFpost.lockdown:
            RFpost.runAnalysis() 
        
        try:
            ModeInfo = self.runConfig.analysis[self.settings["ModeInfoName"]] 
        except KeyError:
            raise GroupVelocityException_runAna("Key for ModeInfoName not found")
        if not ModeInfo.lockdown:
            ModeInfo.runAnalysis()
        
        #So far, only analyse 1st mode
        
        power = None
        try:
            powerThroughSurface = RFpost.exportResults["powerThroughSurface"]
        except AcdOptiException_dataDict_getValsSingle:
            raise GroupVelocityException_runAna("Couldn't find powerThroughSurface data")
        if len(powerThroughSurface) == 0:
            raise GroupVelocityException_runAna("powerThroughSurface data empty")
        
        for (key, val) in powerThroughSurface:
            assert key == "surf"
            if val["surfaceID"] == str(surfID):
                power = float(val["Power_real"])
        if power == None:
            raise GroupVelocityException_runAna("Surface " + str(surfID) + " not found")
        
        #length = None
        length = float(RFpost.settings["L"])/1000.0 #mm->meters
        
        energy = None
        modes = ModeInfo.exportResults.getVals("Mode")
        if len(modes) == 0:
            raise GroupVelocityException_runAna("No mode found")
        if "TotalEnergyReal" in modes[0]:
            energy = float(modes[0]["TotalEnergyReal"])
        elif "TotalEnergy" in modes[0]:
            energy = float(modes[0]["TotalEnergyReal"])
        else:
            raise GroupVelocityException_runAna("Total energy not found")
        assert energy != None
        
        #print "L =", length
        #print "P =", power
        #print "U =", energy
        
        vg = length*power/energy
        self.exportResults.pushBack("VG", str(vg))
        self.exportResults.pushBack("VG_cp", str(100.0*vg/3e8))
        
        self.lockdown = True
        self.write()
        
    def clearLockdown(self):
        print "GroupVelocity::clearLockdown()"
        self.exportResults.clear()
        self.lockdown = False
        self.write()
    
    def write(self):
        self.__paramFile.dataDict.setValSingle("lockdown", str(self.lockdown))
        self.__paramFile.write()
    
    @staticmethod
    def createNew(folder,name):
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,name), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::GroupVelocity")
        paramFile.dataDict.pushBack("lockdown", "False")

        paramFile.dataDict.pushBack("export", DataDict())

        paramFile.dataDict.pushBack("settings", DataDict())
        paramFile.dataDict["settings"].pushBack("ModeInfoName", "Omega3P_modeInfo")
        paramFile.dataDict["settings"].pushBack("RFpostName", "RFpost_local")
        paramFile.dataDict["settings"].pushBack("SurfaceID", "")
        
        paramFile.write()
Exemplo n.º 22
0
class RFpost_local(AnalysisInterface, RFpostParser):
    """
    Analysis that runs acdtool postprocess rf locally.
    The output can then be parsed by the RFpost analysis.
    
    This analysis is detected specially by the AnalysisExportedResults
    GUI infoframecomponent, making it simple to edit its SolverSetup.
    """
    __paramFile = None
        
    def __init__(self, folder, name, runConfig):
        print "RFpost_local::__init__()"
        self.type     = "RFpost_local"
        self.folder   = folder
        self.instName = name
        self.runConfig = runConfig
        
        #Load paramFile
        self.__paramFile = AcdOptiFileParser_simple(os.path.join(folder, name, "paramFile.set"), 'rw')
        if self.__paramFile.dataDict["fileID"] != "Analysis::RFpost_local":
            raise RFpostException("Got fileID='" + self.__paramFile.dataDict["fileID"] + "'")
        self.lockdown = DataDict.boolconv(self.__paramFile.dataDict["lockdown"])

        self.exportResults = self.__paramFile.dataDict["export"]
    
        #Load RFpost solverManager
        self.localSolver = AcdOptiSolverManager("rfPost.in", os.path.join(folder,name))
        if self.lockdown:
            self.localSolver.lockdown = True
    
        #Load the settings
        if len(self.__paramFile.dataDict.getVals("settings")) == 0:
            self.__paramFile.dataDict.pushBack("settings", DataDict())
            self.__paramFile.dataDict["settings"].pushBack("L","")
            self.__paramFile.write()
        self.settings = self.__paramFile.dataDict["settings"]
    
    def runAnalysis(self):
        print "RFpost_local::runAnalysis()"        
        assert not self.lockdown
        
        #Generate the setup file
        self.lockdown = True

        origResultDir = self.localSolver.metaSetup['RFField']['children']['ResultDir']['value'] #Subdirectory whith the data
        dataPath = os.path.join(self.folder, self.instName, "data") #Path to symlink to data folder
        dataPath2 = os.path.join(dataPath, origResultDir) #Path to O3P etc. results thorough symlink
        self.localSolver.metaSetup['RFField']['children']['ResultDir'].setValSingle("value", os.path.join("data", origResultDir))
        
        self.localSolver.generateSetup()
        self.localSolver.lockdown = True

        #Create a symlink to avoid long folder names (ACDtool doesn't like that)
        if os.path.islink(dataPath):
            os.unlink(dataPath)
        os.symlink(self.runConfig.finishedFolder, dataPath) #UNIX only!

        #Modify the postprocess.in file to the right path
        shutil.copy(os.path.join(dataPath2, "VECTOR", "postprocess.in"),\
                    os.path.join(self.folder, self.instName, "postprocess.in.bak"))
        
        postFile = AcdOptiFileParser_KVC(os.path.join(dataPath2, "VECTOR", "postprocess.in"),"rw")
        #print postFile.dataDict
        postFile.dataDict["ModelInfo"].setValSingle("File", os.path.join(dataPath, "mesh.ncdf"))
        postFile.dataDict["CheckPoint"].setValSingle("Directory", os.path.join(os.path.join(dataPath2, "VECTOR")))
        postFile.write()
        
        #Run AcdTool!
        try:
            AcdOptiAcdtoolWrapper.rfPost("rfPost.in", os.path.join(self.folder, self.instName))
        except:
            self.localSolver.metaSetup['RFField']['children']['ResultDir'].setValSingle("value", origResultDir)
            self.localSolver.write()
        
            shutil.copy(os.path.join(self.folder, self.instName, "postprocess.in.bak"),\
                        os.path.join(dataPath2, "VECTOR", "postprocess.in"))
            os.unlink(dataPath)
            
            raise

        #Restore stuff
        self.localSolver.metaSetup['RFField']['children']['ResultDir'].setValSingle("value", origResultDir)
        self.localSolver.write()
        
        shutil.copy(os.path.join(self.folder, self.instName, "postprocess.in.bak"),\
                    os.path.join(dataPath2, "VECTOR", "postprocess.in"))
        
        os.unlink(dataPath)
        
        #Parse output
        ifile = open(os.path.join(self.folder, self.instName, "rfpost.out"), 'r')
        fileData = ifile.read()
        ifile.close()
        
        #Save results
        try:
            L = float(self.settings["L"])
        except ValueError:
            print 'Couldnt parse self.settings["L"]'
            L = -1.0;
        addDic = self.parseData(fileData, L)
        for (k,v) in addDic:
            self.exportResults.pushBack(k,v)
        
        self.write()
        
    def clearLockdown(self):
        print "RFpost_local::clearLockdown()"
        if not self.lockdown:
            return
        self.exportResults.clear()
        os.remove(self.localSolver.fileName)
        self.lockdown = False
        self.localSolver.lockdown = False
        self.write()
    
    def write(self):
        self.__paramFile.dataDict.setValSingle("lockdown", str(self.lockdown))
        self.__paramFile.write()
    
    @staticmethod
    def createNew(folder,name):
        #Create a new folder to hold the stuff
        os.mkdir(os.path.join(folder,name))
        
        #Create a SolverSetup
        AcdOptiSolverManager.createNew("acdtool_rfpost", os.path.join(folder,name))
        
        #Parameter file
        paramFile = AcdOptiFileParser_simple(os.path.join(folder,name,"paramFile.set"), "w")
        paramFile.dataDict.pushBack("fileID", "Analysis::RFpost_local")
        paramFile.dataDict.pushBack("lockdown", "False")
        
        paramFile.dataDict.pushBack("export", DataDict())
        
        paramFile.dataDict.pushBack("settings", DataDict())
        paramFile.dataDict["settings"].pushBack("L","")
        
        paramFile.write()

    @classmethod
    def createNew_clone(cls, folder,cloneFrom,newRunConfig):
        print "RFpost_local::createNew_clone()"
        #Call baseclass createNew_clone(), but don't keep the object:
        #AnalysisInterface.createNew_clone(folder, cloneFrom, newRunConfig)
        super(RFpost_local,cls).createNew_clone(folder,cloneFrom,newRunConfig)
        #Replace the SolverSetup
        os.unlink(os.path.join(folder,cloneFrom.instName,"rfPost.in.meta"))
        AcdOptiSolverManager.createNew_clone(os.path.join(folder, cloneFrom.instName),cloneFrom.localSolver)
        
        return RFpost_local(folder,cloneFrom.instName,newRunConfig)