Ejemplo n.º 1
0
    def __init__(self,
                 basename,
                 solver,
                 template=None,
                 cloneParameters=[],
                 arrayJob=False,
                 hardRestart=False,
                 autoParallel=True,
                 doAutoReconstruct=None,
                 foamVersion=None,
                 compileOption=None,
                 useFoamMPI=False,
                 steady=False,
                 multiRegion=False,
                 parameters={},
                 progress=False,
                 solverProgress=False,
                 solverNoLog=False,
                 solverLogCompress=False,
                 isDecomposed=False):
        """@param template: Name of the template-case. It is assumed that
        it resides in the same directory as the actual case
        @param cloneParameters: a list with additional parameters for the
        CloneCase-object that copies the template
        @param solverProgress: Only writes the current time of the solver"""

        ClusterJob.__init__(self,
                            basename,
                            arrayJob=arrayJob,
                            hardRestart=hardRestart,
                            autoParallel=autoParallel,
                            doAutoReconstruct=doAutoReconstruct,
                            foamVersion=foamVersion,
                            compileOption=compileOption,
                            useFoamMPI=useFoamMPI,
                            multiRegion=multiRegion,
                            parameters=parameters,
                            isDecomposed=isDecomposed)
        self.solver = solver
        self.steady = steady
        if template != None and not self.restarted:
            template = path.join(path.dirname(self.casedir()), template)
            if path.abspath(basename) == path.abspath(template):
                error("The basename", basename, "and the template", template,
                      "are the same directory")
            if isDecomposed:
                cloneParameters += ["--parallel"]
            clone = CloneCase(
                args=cloneParameters +
                [template, self.casedir(), "--follow-symlinks"])
        self.solverProgress = solverProgress
        self.solverNoLog = solverNoLog
        self.solverLogCompress = solverLogCompress
 def postRunTestCheckConverged(self):
     '''
     self.isNotEqual(
         value=self.runInfo()["time"],
         target=self.controlDict()["endTime"],
         message="Reached endTime -> not converged")
     '''
     self.shell("cp -r 0 0_orig") #initial fields
     #self.shell("pyFoamCopyLastToFirst.py . .")
     #self.shell("pyFoamClearCase.py .")
     CloneCase(args=(self.case_path, self.case_path+"heat_exchange")) #Only works with Python3
     self.shell("cp -r 0_orig heat_exchange/") #initial fields
     self.shell("cp -r heat_exchange/constant/polyMesh heat_exchange/constant/polyMesh_backup")
Ejemplo n.º 3
0
#!/usr/bin/python

from PyFoam.Applications.CloneCase import CloneCase

CloneCase()
Ejemplo n.º 4
0
def FOAM_model(xtr, y, ztr, Patient, Template):
    errorCode = True  ## True when simulation has succesfully run
    ## Specify simulation folder
    Simulation = Patient + "/simulation"

    ## Clear case
    ClearCase(args=["--clear-history", Simulation])
    print("Complete cleaning the case done")

    if not os.path.exists(Simulation):  ## if simulation directory doesnt exist
        ## Clone template onto simulation folder
        CloneCase(args=[Template, Simulation])
        print("Copied generic case to patient specific folder")

    ## copy betavSolid and actual skin temperature data onto the gland 0 folder
    shutil.copyfile(Template + "/0/gland/betavSolid",
                    Simulation + "/0/gland/betavSolid")
    shutil.copyfile(Patient + "/actualSkinData",
                    Simulation + "/0/gland/actualSkinData")

    ## define different cell zones using topoSetDict
    bmName = os.path.join(Simulation, 'system', "topoSetDict")
    template = TemplateFile(bmName + ".template", expressionDelimiter="$")
    template.writeToFile(bmName, {
        'x': xtr,
        'y': y,
        'z': ztr,
        'r': radius,
        'gr': gr
    })

    print("Setting template file for topoSet done")

    ## Run topoSet
    topoSetRun = BasicRunner(argv=["topoSet", "-case", Simulation],
                             silent=True,
                             server=False,
                             logname='log.topoSet')
    topoSetRun.start()
    if not topoSetRun.runOK():
        error("There was a problem with topoSet")
    print("topoSet done")
    print(xtr, y, ztr)

    ## Split mesh regions based on toposet
    splitMeshRegionsRun = BasicRunner(
        argv=["splitMeshRegions -cellZones -overwrite", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.splitMeshRegions')
    splitMeshRegionsRun.start()
    if not splitMeshRegionsRun.runOK():
        error("There was a problem with split mesh regions")
    print("split mesh regions done")

    ## Run change dictionary for gland region
    changeDictionaryGlandRun = BasicRunner(
        argv=[" changeDictionary -region gland", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.changeDictionaryGland')
    changeDictionaryGlandRun.start()
    if not changeDictionaryGlandRun.runOK():
        error("There was a problem with change dictionary for gland")
    print("change dictionary gland done")

    ## Run change dictionary for tumor region
    changeDictionaryTumorRun = BasicRunner(
        argv=[" changeDictionary -region tumor", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.changeDictionaryTumor')
    changeDictionaryTumorRun.start()
    if not changeDictionaryTumorRun.runOK():
        error("There was a problem with change dictionary for tumor")
    print("change dictionary tumor done")

    ## Run setFields for gland region
    setFieldsGlandRun = BasicRunner(
        argv=["setFields -region gland", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.setFieldsGland')
    setFieldsGlandRun.start()
    if not setFieldsGlandRun.runOK():
        error("There was a problem with setFields for gland")
    print("set fields for gland done")

    ## define gland anisotropic thermal conductivity
    bmName = os.path.join(Simulation, 'constant', 'gland',
                          "thermophysicalProperties")
    template = TemplateFile(bmName + ".template", expressionDelimiter="$")
    template.writeToFile(bmName, {'x': xtr, 'y': y, 'z': ztr})

    print("Setting anisotropic thermal conductivity for gland done")

    ## define tumor anisotropic thermal conductivity
    bmName = os.path.join(Simulation, 'constant', 'tumor',
                          "thermophysicalProperties")
    template = TemplateFile(bmName + ".template", expressionDelimiter="$")
    template.writeToFile(bmName, {'x': xtr, 'y': y, 'z': ztr})

    print("Setting anisotropic thermal conductivity for tumor done")

    ## removing fvoptions if benign tumor
    if state == 'benign':
        if not os.path.exists(Simulation + "/constant/tumor/fvOptions"):
            print("Removing heat sources for benign tumors done")
        else:
            os.remove(Simulation + "/constant/tumor/fvOptions")
            print("Removing heat sources for benign tumors done")

    ## multi region simple foam with two heat sources specified for tumor region
    print("Running")
    theRun = BasicRunner(
        argv=["chtMultiRegionSimpleFoam", "-case", Simulation],
        silent=True,
        server=False,
        logname='log.solver')
    #"-postProcess", "-func", "surfaces"
    theRun.start()
    errorCode = theRun.endSeen

    if not theRun.runOK():
        error("There was a problem while running the solver")
    print("Solver run done")

    ## converting latest simulation step to VTK- gland
    print("Converting gland region to VTK")
    VTKGlandRun = BasicRunner(argv=[
        "foamToVTK -fields '(T)' -latestTime -ascii -region gland", "-case",
        Simulation
    ],
                              silent=True,
                              server=False,
                              logname='log.VTKGland')
    VTKGlandRun.start()
    if not VTKGlandRun.runOK():
        error(
            "There was a problem while converting the gland region to VTK for post-processing"
        )
    print("Conversion of Gland region to VTK done")

    ## converting latest simulation step to VTK- tumor
    print("Converting tumor region to VTK")
    VTKTumorRun = BasicRunner(argv=[
        "foamToVTK -fields '(T)' -latestTime -ascii -region tumor", "-case",
        Simulation
    ],
                              silent=True,
                              server=False,
                              logname='log.VTKTumor')
    VTKTumorRun.start()
    if not VTKTumorRun.runOK():
        error(
            "There was a problem while converting the tumor region to VTK for post-processing"
        )
    print("Conversion of Tumor region to VTK done")

    ## Moving VTK for post processing by rounding off to two decimal places
    if ((y * 100) % 1) == 0:
        y_str = str(round(y * 100) / 100) + '0'
    else:
        y_str = str(y)
    shutil.move(Simulation + "/VTK", Patient + "/VTK" + "/VTK" + y_str)
    return errorCode
Ejemplo n.º 5
0
    def run(self):
        """Run the actual test"""

        startTime = time.time()

        self.processOptions()

        self.__doInit(**self.parameterValues())

        self.wrapCallbacks()

        self.__runParallel = False

        if self.doClone:
            self.status("Cloning case")

            clone = CloneCase([self.originalCase, self.caseDir] +
                              ["--add=" + a for a in self.__addToClone])
        else:
            self.status("Skipping cloning")

        if self.doPreparation:
            if self.referenceData:
                if path.exists(path.join(self.referenceData, "copyToCase")):
                    self.status("Copying reference data")
                    self.cloneData(path.join(self.referenceData, "copyToCase"),
                                   self.caseDir)
                else:
                    self.status("No reference data - No 'copyToCase' in",
                                self.referenceData)

                if path.exists(
                        path.join(self.referenceData,
                                  "additionalFunctionObjects")):
                    self.status("Adding function objects")
                    self.addFunctionObjects(
                        path.join(self.referenceData,
                                  "additionalFunctionObjects"))
                else:
                    self.status(
                        "No additional function objects - No 'additionalFunctionObjects' in",
                        self.referenceData)

            self.status("Preparing mesh")
            self.meshPrepare()

            self.status("Preparing case")
            self.casePrepare()
        else:
            self.status("Skipping case preparation")

        if self.doSerialPreTests:
            self.status("Running serial pre-run tests")
            self.runTests("serialPreRunTest", warnSerial=True)
        else:
            self.status("Skipping the serial pre-tests")

        if self["parallel"]:
            if self.doDecompose:
                self.status("Decomposing the case")
                if self["autoDecompose"]:
                    self.autoDecompose()
                else:
                    self.decompose()
            else:
                self.status("Skipping the decomposition")

        self.__runParallel = self["parallel"]

        if self["parallel"]:
            if self.doParallelPreparation:
                self.status("Parallel preparation of the case")
                self.parallelPrepare()
            else:
                self.status("Skipping parallel preparation")

        if self.doPreTests:
            self.status("Running pre-run tests")
            self.runTests("preRunTest")
        else:
            self.status("Skipping the pre-tests")

        if self.doSimulation:
            self.status("Run solver")
            self.__runInfo = dict(self.execute(self.solver).getData())
            self.writeRunInfo()
            print_()
            if not self.runInfo()["OK"]:
                self.fail("Solver", self.solver, "ended with an error")
            else:
                try:
                    self.status("Solver ran until time",
                                self.runInfo()["time"])
                except KeyError:
                    self.fail("No information how long the solver ran")
        else:
            self.status("Skipping running of the simulation")

        if self.doPrintRunInfo:
            print_()
            print_("runInfo used in further tests")
            import pprint

            printer = pprint.PrettyPrinter()
            printer.pprint(self.__runInfo)

        if self.doPostprocessing:
            self.status("Running postprocessing tools")
            self.postprocess()
        else:
            self.status("Skipping the postprocessing tools")

        if self.doPostTests:
            self.status("Running post-run tests")
            self.runTests("postRunTest")
        else:
            self.status("Skipping the post-run tests")

        self.__runParallel = False

        if self["parallel"]:
            if self.doReconstruction and self["doReconstruct"]:
                self.status("Reconstructing the case")
                if self["autoDecompose"]:
                    self.autoReconstruct()
                else:
                    self.reconstruct()
            else:
                self.status("Skipping the reconstruction")

        if self.doSerialPostTests:
            self.status("Running serial post-run tests")
            self.runTests("serialPostRunTest", warnSerial=True)
        else:
            self.status("Skipping the serial post-tests")

        if self.minimumRunTime:
            try:
                if float(self.runInfo()["time"]) < self.minimumRunTime:
                    self.fail("Solver only ran to",
                              self.runInfo()["time"],
                              "but should at least run to",
                              self.minimumRunTime)
            except KeyError:
                self.fail("No information about run-time. Should have run to",
                          self.minimumRunTime)
            except TypeError:
                self.warn("Silently ignoring missing runInfo()")

        runTime = time.time() - startTime
        self.status("Total running time", runTime, "seconds")
        if runTime > self.timeout:
            self.warn("Running time", runTime, "bigger than assigned timeout",
                      self.timeout, ". Consider other sizeclass than",
                      self["sizeClass"], "from sizeclasses",
                      self.sizeClassString())
        elif runTime < self.toSmallTimeout:
            self.warn("Running time", runTime,
                      "much smaller than assigned timeout", self.timeout,
                      ". Consider other sizeclass than",
                      self["sizeClass"], "from sizeclasses",
                      self.sizeClassString(), "for instance",
                      self.proposedSizeClass)
        return self.endTest()
Ejemplo n.º 6
0
    print('ARRE YOU SUUUUUUUUUUURE ?')

if generate:
    for Ccmc in ccmcList:
        for Cbd in CbdList:
            for Cbc in CbcList:
                print('Step {}, Ccmc = {}, Cbd = {}, Cbc = {}'.format(
                    i, Ccmc, Cbd, Cbc))
                if i == 2:
                    break
                caseName = str(i) + '_Ccmc' + str(Ccmc) + '_Cbd' + \
                    str(Cbd) + '_Cbc' + str(Cbc)
                caseName = caseName.replace(".", "")
                caseList.append(caseName)
                if force:
                    CloneCase(args=[refCase, caseName, '--force'])
                else:
                    try:
                        CloneCase(args=[refCase, caseName])
                    except BaseException:
                        print(
                            '\n' + caseName +
                            'already exist. Be careful or I\'ll destroy your data'
                            + '\n')
                        i += 1
                        break
                print('toto')

                #loading sim files
                dire = SolutionDirectory(caseName)
                dire.clearResults()