def addToLib(self):
        '''
        '''

        u.copy(self.outputDir, pathToReducedModel+self.packageName+slash)

        try:
            with open(pathToTemplate+'myInit.txt', "r") as myfile:
                myInit = myfile.read()

                myInit = myInit.replace('MyReducedModel',self.packageName[0].upper()+self.packageName[1:])
                myInit = myInit.replace('myReducedModel',self.packageName)

                with open(pathToReducedModel+self.packageName+slash+'__init__.py', "a") as logFile:
                    logFile.write(myInit)

                # print(myInit)

            for line in fileinput.input(pathToReducedModel+'__init__.py', inplace=True):
                if line.find('__all__') != -1:
                    if line.find('[]') != -1:
                        line = line[:-2]+"'"+self.packageName+"']"'\n'

                    else:
                        line = line[:-2]+",'"+self.packageName+"']"'\n'
                    print("%s" % line),

                else : print(line),

        except:
            print ("Unexpected error:", sys.exc_info()[0])
            raise
Пример #2
0
    def phase1(self, phasesToExecute=None):
        """
        **The step will launch in parallel multiple Sofa scene (nbrCPU by nbrCPU number of scene) until
        it has run all the scene in the sequence.** 

        +-----------------+-----------+----------------------------------------------------------+
        | argument        | type      | definition                                               |
        +=================+===========+==========================================================+
        | phasesToExecute | list(int) || Allow to choose which phase to execute for the reduction|
        |                 |           || *more details see* :py:func:`setListSofaScene`          |
        +-----------------+-----------+----------------------------------------------------------+
        
        To run the SOFA scene in parallele we use the ``sofa launcher`` utility

        What does it do to each scene:

            - Add animation to each :py:class:`.ObjToAnimate` we want for our model in the predifined sequence
            - Add a componant to save the shaking resulting states (WriteState)
            - Take all the resulting states files and combines them in one file put in the ``debug`` dir with a debug scene

        """
        start_time = time.time()

        if not phasesToExecute:
            phasesToExecute = list(
                range(self.reductionAnimations.nbPossibility))

        self.setListSofaScene(phasesToExecute)

        filenames = ["phase1_snapshots.py", "debug_scene.py"]
        filesandtemplates = []
        for filename in filenames:
            filesandtemplates.append(
                (open(pathToTemplate + filename).read(), filename))

        results = startSofa(self.listSofaScene,
                            filesandtemplates,
                            launcher=ParallelLauncher(self.nbrCPU))

        if self.verbose:
            for res in results:
                print("Results: ")
                print("    directory: " + res["directory"])
                print("        scene: " + res["scene"])
                print("     duration: " + str(res["duration"]) + " sec")

        self.packageBuilder.copyAndCleanState(
            results, self.reductionParam.periodSaveGIE,
            self.reductionParam.stateFileName,
            self.reductionParam.velocityFileName)
        u.copy(
            results[self.phaseToSaveIndex]["directory"] + slash +
            "debug_scene.py", self.packageBuilder.debugDir)

        print("PHASE 1 --- %s seconds ---" % (time.time() - start_time))
    def finalizePackage(self,result):
        '''
        '''

        shutil.move(result['directory']+slash+self.packageName+'.py', self.outputDir+slash+self.packageName+'.py')

        with open(result['directory']+slash+'meshFiles.txt', "r") as meshFiles:
            self.meshes = meshFiles.read().splitlines()

        u.checkExistance(self.meshDir)

        if self.meshes:
            for mesh in self.meshes:
                u.copy(mesh, self.meshDir)

        if self.addToLibBool :

            self.addToLib()
Пример #4
0
    def phase3(self, phasesToExecute=None, nbrOfModes=None):
        """
        **This step will launch in parallel multiple Sofa scene (nbrCPU by nbrCPU number of scene) until
        it has run all the scene in the sequence.**

        +-----------------+-----------+----------------------------------------------------------+
        | argument        | type      | definition                                               |
        +=================+===========+==========================================================+
        | phasesToExecute | list(int) || Allow to choose which phase to execute for the reduction|
        |                 |           || *more details see* :py:func:`setListSofaScene`          |
        +-----------------+-----------+----------------------------------------------------------+
        | nbrOfModes      | int       || Number of modes you want to keep                        |
        |                 |           || ``by default will keep them all``                       |
        +-----------------+-----------+----------------------------------------------------------+

        To run the SOFA scene in parallele we use the ``sofa launcher`` utility

        What does it do to each scene:

            - Take the previous one and add the model order reduction component:
               - HyperReducedFEMForceField
               - MappedMatrixForceFieldAndMas
               - ModelOrderReductionMapping
            - Produce an Hyper Reduced description of the model
            - Produce files listing the different element to keep
            - Take all the resulting states files and combines them in one file put in the ``debug`` dir with a debug scene


        """
        start_time = time.time()

        if not phasesToExecute:
            phasesToExecute = list(
                range(self.reductionAnimations.nbPossibility))
        if not nbrOfModes:
            nbrOfModes = self.reductionParam.nbrOfModes

        if not os.path.isfile(self.packageBuilder.dataDir +
                              self.reductionParam.modesFileName):
            raise IOError("There is no mode file at "+self.packageBuilder.dataDir+self.reductionParam.modesFileName\
                +"\nPlease give one at this location or indicate the correct location or re-generate one with phase 1 & 2")

        nbrOfModesPossible = self.packageBuilder.checkNodeNbr(
            self.reductionParam.modesFileName)

        if not nbrOfModes:
            nbrOfModes = self.reductionParam.nbrOfModes
        if nbrOfModes == -1:
            nbrOfModes = self.reductionParam.nbrOfModes = nbrOfModesPossible

        if (nbrOfModes <= 0) or (nbrOfModes > nbrOfModesPossible):
            raise ValueError("nbrOfModes incorrect\n"\
                +"  nbrOfModes given :"+str(nbrOfModes)+" | nbrOfModes max possible : "+str(nbrOfModesPossible))

        self.setListSofaScene(phasesToExecute)

        for i in range(len(phasesToExecute)):
            self.listSofaScene[i]['NBROFMODES'] = nbrOfModes

        filenames = [
            "phase2_prepareECSW.py", "phase1_snapshots.py", "debug_scene.py"
        ]
        filesandtemplates = []
        for filename in filenames:
            filesandtemplates.append(
                (open(pathToTemplate + filename).read(), filename))
        results = startSofa(self.listSofaScene,
                            filesandtemplates,
                            launcher=ParallelLauncher(self.nbrCPU))

        if self.verbose:
            for res in results:
                print("Results: ")
                print("    directory: " + res["directory"])
                print("        scene: " + res["scene"])
                print("     duration: " + str(res["duration"]) + " sec")

        files = glob.glob(results[self.phaseToSaveIndex]["directory"] + slash +
                          "*_elmts.txt")
        if files:
            for i, file in enumerate(files):
                file = os.path.normpath(file)
                files[i] = file.split(slash)[-1]
            # print("FILES ----------->",files)
            self.reductionParam.savedElementsFilesNames = files

        for fileName in self.reductionParam.savedElementsFilesNames:
            u.copyFileIntoAnother(
                results[self.phaseToSaveIndex]["directory"] + slash + fileName,
                self.packageBuilder.debugDir + fileName)
        self.reductionParam.massName = glob.glob(
            results[self.phaseToSaveIndex]["directory"] + slash +
            "*_reduced.txt")[0]
        # print("massName -----------------------> ",self.reductionParam.massName)
        u.copy(self.reductionParam.massName, self.reductionParam.dataDir)

        files = glob.glob(results[self.phaseToSaveIndex]["directory"] + slash +
                          "*_Gie.txt")
        if files:
            for i, file in enumerate(files):
                file = os.path.normpath(file)
                files[i] = file.split(slash)[-1]
            # print("FILES ----------->",files)
            self.reductionParam.gieFilesNames = files
        else:
            raise IOError("Missing GIE Files")

        self.packageBuilder.copyAndCleanState(
            results,
            self.reductionParam.periodSaveGIE,
            'step2_' + self.reductionParam.stateFileName,
            gie=self.reductionParam.gieFilesNames)

        print("PHASE 3 --- %s seconds ---" % (time.time() - start_time))