Ejemplo n.º 1
0
class ParsedBlockMeshDictTest(unittest.TestCase):
    def setUp(self):
        self.dest = mktemp()
        SolutionDirectory(plateHoleTutorial(),
                          archive=None,
                          paraviewLink=False).cloneCase(self.dest)

    def tearDown(self):
        rmtree(self.dest)

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testBoundaryRead(self):
        blk = ParsedBlockMeshDict(SolutionDirectory(self.dest).blockMesh())
        self.assertEqual(blk.convertToMeters(), 1.)
        self.assertEqual(len(blk.vertices()), 22)
        self.assertEqual(len(blk.blocks()), 5)
        self.assertEqual(len(blk.patches()), 6)
        self.assertEqual(len(blk.arcs()), 8)
        self.assertEqual(blk.typicalLength(), 1.25)
        self.assertEqual(str(blk.getBounds()),
                         "([0.0, 0.0, 0.0], [2.0, 2.0, 0.5])")

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testRoundtripBlockMesh(self):
        blk = ParsedBlockMeshDict(SolutionDirectory(self.dest).blockMesh())
        txt = str(blk)
        try:
            i = int(txt.split("blocks")[1].split("(")[0])
            self.assertTrue(False)
        except ValueError:
            pass
Ejemplo n.º 2
0
class BoundaryDictTest(unittest.TestCase):
    def setUp(self):
        self.dest = mktemp()
        wholePath = path.join(foamTutorials(), "incompressible", "simpleFoam",
                              "airFoil2D")
        SolutionDirectory(wholePath, archive=None,
                          paraviewLink=False).cloneCase(self.dest)

    def tearDown(self):
        rmtree(self.dest)

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testBoundaryRead(self):
        bnd = BoundaryDict(self.dest)
        self.assertEqual(bnd["walls"]["type"], "wall")
        self.assertEqual(bnd["walls"]["nFaces"], 78)
        self.assertEqual(len(bnd.patches()), 4)
        self.assertEqual(len(bnd.patches(patchType="patch")), 2)

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testBoundaryWrite(self):
        bnd = BoundaryDict(self.dest)
        test1 = {"type": "wall", "nFaces": 0, "startFace": 666}
        bnd["testIt"] = test1
        self.assertEqual(len(bnd.patches()), 5)
        bnd["walls"] = test1
        self.assertEqual(len(bnd.patches()), 5)
        test2 = {"type": "wall", "Faces": 0, "startFace": 666}
        try:
            bnd["nix"] = test2
            self.fail()
        except PyFoamException:
            pass
Ejemplo n.º 3
0
class ParameterFileTest(unittest.TestCase):
    def setUp(self):
        self.dest = mktemp()
        SolutionDirectory(damBreakTutorial(), archive=None,
                          paraviewLink=False).cloneCase(self.dest)

    def tearDown(self):
        rmtree(self.dest)

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testParameterFileRead(self):
        par = ParameterFile(path.join(self.dest, "system", "controlDict"))
        self.assertEqual(par.readParameter("notHere"), "")
        self.assertEqual(par.readParameter("startTime"), "0")

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testParameterFileWrite(self):
        par = ParameterFile(path.join(self.dest, "system", "controlDict"),
                            backup=True)
        self.assertEqual(par.readParameter("startTime"), "0")
        par.replaceParameter("startTime", "42")
        self.assertEqual(par.readParameter("startTime"), "42")
        par.restore()
        self.assertEqual(par.readParameter("startTime"), "0")

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testParameterReadWithTab(self):
        par = ParameterFile(path.join(self.dest, "system", "controlDict"))
        par.replaceParameter("startTime", " 42")
        self.assertEqual(par.readParameter("startTime"), "42")
        par.replaceParameter("startTime", "\t 42")
        self.assertEqual(par.readParameter("startTime"), "42")
Ejemplo n.º 4
0
class ReadIncludeAndMacroExpansionTest(unittest.TestCase):
    def setUp(self):
        self.testDir=mkdtemp()
        self.dest=path.join(self.testDir,"0.org")
        if foamFork() in ["openfoam","openfoamplus"] and foamVersionNumber()>=(4,):
            null="0.orig"
        else:
            null="0.org"

        copytree(path.join(foamTutorials(),"incompressible","simpleFoam","motorBike",null),
                 self.dest)

    def tearDown(self):
        rmtree(self.testDir)

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadNoMacroExpansion(self):
        kFile=ParsedParameterFile(path.join(self.dest,"k"))
        self.assertEqual(str(kFile["internalField"]),"uniform $turbulentKE")
        self.assertEqual(kFile["boundaryField"]["lowerWall"]["value"],"$internalField")
        self.assertEqual(kFile["boundaryField"]["motorBikeGroup"]["value"],"$internalField")

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadMacroExpansion(self):
        kFile=ParsedParameterFile(path.join(self.dest,"k"),
                                  doMacroExpansion=True)
        self.assertEqual(str(kFile["internalField"]),"uniform 0.24")
        self.assertEqual(str(kFile["boundaryField"]["lowerWall"]["value"]),"uniform 0.24")
        self.assertEqual(str(kFile["boundaryField"]["motorBikeGroup"]["value"]),"uniform 0.24")
Ejemplo n.º 5
0
class TimeDirectoryTest(unittest.TestCase):
    def setUp(self):
        self.theDir = mkdtemp()
        self.theFile = path.join(self.theDir, "damBreak")
        copytree(damBreakTutorial(), self.theFile)
        if foamVersionNumber() >= (2, ):
            if foamFork() in ["openfoam", "openfoamplus"
                              ] and foamVersionNumber() >= (4, ):
                extension = ".orig"
            else:
                extension = ".org"
            copyfile(path.join(self.theFile, "0",
                               gammaName() + extension),
                     path.join(self.theFile, "0", gammaName()))

    def tearDown(self):
        rmtree(self.theDir)

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testTimeDirectoryBasicContainerStuff(self):
        test = SolutionDirectory(self.theFile)["0"]
        self.assertEqual(len(test), 4)
        self.assertTrue(gammaName() in test)
        self.assertTrue("nix" not in test)
        tf = test["U"]
        self.assertEqual(type(tf), SolutionFile)
        self.assertTrue(FileBasis in tf.__class__.__mro__)
        self.assertRaises(KeyError, test.__getitem__, "nix")
        self.assertRaises(TypeError, test.__getitem__, 42)
        lst = []
        for v in test:
            lst.append(v.baseName())
        self.assertTrue(gammaName() in lst)
        self.assertEqual(len(lst), len(test))

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testTimeDirectoryAdding(self):
        test = SolutionDirectory(self.theFile)["0"]
        self.assertEqual(len(test), 4)
        test["U2"] = test["U"]
        self.assertEqual(len(test), 5)
        test["nix"] = 23
        self.assertEqual(len(test), 6)
        del test["nix"]
        self.assertEqual(len(test), 5)
        del test["U2"]
        self.assertEqual(len(test), 4)

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testTimeDirectoryCreating(self):
        self.assertEqual(len(SolutionDirectory(self.theFile)), 1)
        test = TimeDirectory(self.theFile, "42", create=True)
        self.assertEqual(len(test), 0)
        self.assertEqual(len(SolutionDirectory(self.theFile)), 2)
Ejemplo n.º 6
0
class ParsedParameterFileTest5(unittest.TestCase):
    def setUp(self):
        self.theFile=mktemp()
        if foamVersionNumber()<(2,):
            # there is no appropriate volSymmTensorField-file in 2.x
            copyfile(path.join(turbCavityTutorial(),"0","R"),self.theFile)

    def tearDown(self):
        if foamVersionNumber()<(2,):
            # there is no appropriate volSymmTensorField-file in 2.x
            remove(self.theFile)

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadTutorial(self):
        if foamVersionNumber()>=(2,):
            # there is no appropriate volSymmTensorField-file in 2.x
            return

        test=ParsedParameterFile(self.theFile)
        self.assertEqual(test["internalField"].__class__,Field)
        self.assertEqual(test["internalField"].isUniform(),True)
        if foamVersionNumber()<(1,5):
            self.assertEqual(test["internalField"].value().__class__,Tensor)
        else:
            self.assertEqual(test["internalField"].value().__class__,SymmTensor)
Ejemplo n.º 7
0
class TimeDirectoryTestZipped(unittest.TestCase):
    def setUp(self):
        self.theDir = mkdtemp()
        self.theFile = path.join(self.theDir, "damBreak")
        copytree(damBreakTutorial(), self.theFile)
        if foamVersionNumber() >= (2, ):
            if foamFork() in ["openfoam", "openfoamplus"
                              ] and foamVersionNumber() >= (4, ):
                extension = ".orig"
            else:
                extension = ".org"
            copyfile(path.join(self.theFile, "0",
                               gammaName() + extension),
                     path.join(self.theFile, "0", gammaName()))
        system("gzip " + path.join(self.theFile, "0", gammaName()))

    def tearDown(self):
        rmtree(self.theDir)

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testTimeReplacingZippedFile(self):
        test = SolutionDirectory(self.theFile)["0"]
        self.assertEqual(len(test), 4)
        if foamFork() in ["openfoam", "openfoamplus"
                          ] and foamVersionNumber() >= (4, ):
            extension = ".orig"
        else:
            extension = ".org"
        test[gammaName()] = test[gammaName() + extension]
        self.assertEqual(len(test), 4)
Ejemplo n.º 8
0
def damBreakTutorial():
    prefix = foamTutorials()
    if oldTutorialStructure():
        prefix = path.join(prefix, "interFoam")
    else:
        prefix = path.join(prefix, "multiphase", "interFoam", "laminar")
    return path.join(prefix, "damBreak")
Ejemplo n.º 9
0
class MeshInformationTest(unittest.TestCase):
    def setUp(self):
        self.dest = mktemp()
        SolutionDirectory(damBreakTutorial(), archive=None,
                          paraviewLink=False).cloneCase(self.dest)

        if oldApp():
            pathSpec = [path.dirname(self.dest), path.basename(self.dest)]
        else:
            pathSpec = ["-case", self.dest]

        run = UtilityRunner(argv=["blockMesh"] + pathSpec,
                            silent=False,
                            server=False)
        run.start()

    def tearDown(self):
        rmtree(self.dest)

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testBoundaryRead(self):
        mesh = MeshInformation(self.dest)
        self.assertEqual(mesh.nrOfFaces(), 9176)
        self.assertEqual(mesh.nrOfPoints(), 4746)
        self.assertEqual(mesh.nrOfCells(), 2268)
        try:
            self.assertEqual(mesh.nrOfCells(), 2268)
        except:
            if not oldApp():
                self.fail()
Ejemplo n.º 10
0
def damBreakTutorial():
    prefix=foamTutorials()
    if oldTutorialStructure():
        prefix=path.join(prefix,"interFoam")
    else:
        prefix=path.join(prefix,"multiphase","interFoam","laminar")            
    return path.join(prefix,"damBreak")
Ejemplo n.º 11
0
class TimeDirectoryTestCopy(unittest.TestCase):
    def setUp(self):
        self.theDir = mkdtemp()
        self.theFile = path.join(self.theDir, "damBreak")
        copytree(damBreakTutorial(), self.theFile)
        if foamVersionNumber() >= (2, ):
            if foamFork() in ["openfoam", "openfoamplus"
                              ] and foamVersionNumber() >= (4, ):
                extension = ".orig"
            else:
                extension = ".org"
            copyfile(path.join(self.theFile, "0",
                               gammaName() + extension),
                     path.join(self.theFile, "0", gammaName()))

    def tearDown(self):
        rmtree(self.theDir)

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testTimeCopy(self):
        sol = SolutionDirectory(self.theFile)
        self.assertEqual(len(sol), 1)
        sol["42"] = sol["0"]
        sol["13"] = sol["0"]
        self.assertEqual(len(sol), 3)
        test1 = sol["0"]
        test2 = sol["13"]
        test3 = sol["42"]
        self.assertEqual(len(test3), 4)
        del test3[gammaName()]
        self.assertEqual(len(test3), 3)
        res = test1.copy(test3)
        self.assertEqual(len(test1), 4)
        self.assertEqual(len(res), 3)
        res = test1.copy(test3, purge=True)
        self.assertEqual(len(test1), 3)
        self.assertEqual(len(res), 3)
        res = test1.copy(test2, overwrite=False)
        self.assertEqual(len(test1), 4)
        self.assertEqual(len(res), 1)
        test1.clear()
        self.assertEqual(len(test1), 0)
        res = test1.copy(test2, overwrite=False)
        self.assertEqual(len(test1), 4)
        self.assertEqual(len(res), 4)
        res = test1.copy(test2, overwrite=False)
        self.assertEqual(len(test1), 4)
        self.assertEqual(len(res), 0)
        self.assertEqual(len(test3), 3)
        res = test3.copy(test1, mustExist=True)
        self.assertEqual(len(test3), 3)
        self.assertEqual(len(res), 3)
        test1.clear()
        res = test1.copy(test2, include=[gammaName() + "*"])
        self.assertEqual(len(test1), 2)
        self.assertEqual(len(res), 2)
        res = test1.copy(test2, exclude=["U"], overwrite=False)
        self.assertEqual(len(test1), 3)
        self.assertEqual(len(res), 1)
Ejemplo n.º 12
0
def potentialCylinderTutorial():
    prefix=foamTutorials()
    if oldTutorialStructure():
        prefix=path.join(prefix,"potentialFoam")
    else:
        prefix=path.join(prefix,"basic","potentialFoam")
    return path.join(prefix,"cylinder")
Ejemplo n.º 13
0
def turbCavityTutorial():
    prefix=foamTutorials()
    if oldTutorialStructure():
        prefix=path.join(prefix,"turbFoam")
    else:
        prefix=path.join(prefix,"incompressible","pisoFoam","ras")
    return path.join(prefix,"cavity")
Ejemplo n.º 14
0
class SolutionFileTestZipped(unittest.TestCase):
    def setUp(self):
        self.theFile = mktemp()
        if foamVersionNumber() < (2, 0):
            extension = ""
        elif foamFork() in ["openfoam", "openfoamplus"
                            ] and foamVersionNumber() >= (4, ):
            extension = ".orig"
        else:
            extension = ".org"
        copyfile(path.join(damBreakTutorial(), "0",
                           gammaName() + extension), self.theFile)
        system("gzip -f " + self.theFile)

    def tearDown(self):
        remove(self.theFile + ".gz")

    @pytest.mark.skipif(foamTutorials() == '',
                        reason="$FOAM_TUTORIALS is not defined")
    def testSolutionFileZippedReadWrite(self):
        test = SolutionFile(path.dirname(self.theFile),
                            path.basename(self.theFile))
        self.assertEqual(test.readInternalUniform(), "0")
        self.assertEqual(test.readBoundary("atmosphere"), "0")
        self.assertEqual(test.readDimension(), "0 0 0 0 0 0 0")
        test.replaceBoundary("atmosphere", 2.3)
        self.assertEqual(test.readBoundary("atmosphere"), "2.3")
        test.replaceInternal(3.14)
        self.assertEqual(test.readInternalUniform(), "3.14")
Ejemplo n.º 15
0
def potentialCylinderTutorial():
    prefix=foamTutorials()
    if oldTutorialStructure():
        prefix=path.join(prefix,"potentialFoam")            
    else:
        prefix=path.join(prefix,"basic","potentialFoam")            
    return path.join(prefix,"cylinder")
Ejemplo n.º 16
0
def XoodlesPitzTutorial():
    prefix=foamTutorials()
    if oldTutorialStructure():
        prefix=path.join(prefix,"Xoodles")
    else:
        prefix=path.join(prefix,"combustion","XiFoam","les")
    return path.join(prefix,"pitzDaily3D")
Ejemplo n.º 17
0
def XoodlesPitzTutorial():
    prefix=foamTutorials()
    if oldTutorialStructure():
        prefix=path.join(prefix,"Xoodles")
    else:
        prefix=path.join(prefix,"combustion","XiFoam","les")
    return path.join(prefix,"pitzDaily3D")
Ejemplo n.º 18
0
def turbCavityTutorial():
    prefix=foamTutorials()
    if oldTutorialStructure():
        prefix=path.join(prefix,"turbFoam")            
    else:
        prefix=path.join(prefix,"incompressible","pisoFoam","ras")            
    return path.join(prefix,"cavity")
Ejemplo n.º 19
0
def buoyHotRoomTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"heatTransfer")
    if foamVersionNumber()>=(3,):
        return path.join(prefix,"buoyantSimpleFoam","hotRadiationRoom")
    else:
        return path.join(prefix,"buoyantSimpleFoam","hotRoom")
Ejemplo n.º 20
0
def simpleBikeTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"incompressible")
    else:
        error("The simpleFoam-motorBike-case does not exist before 1.6")

    return path.join(prefix,"simpleFoam","motorBike")
def bubbleColumnTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"multiphase")
    if foamVersionNumber()>=(3,):
        return path.join(prefix,"twoPhaseEulerFoam","laminar","bubbleColumn")
    else:
        return path.join(prefix,"twoPhaseEulerFoam","bubbleColumn")
Ejemplo n.º 22
0
def bubbleColumnTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"multiphase")
    if foamVersionNumber()>=(3,):
        return path.join(prefix,"twoPhaseEulerFoam","laminar","bubbleColumn")
    else:
        return path.join(prefix,"twoPhaseEulerFoam","bubbleColumn")
Ejemplo n.º 23
0
def XiFoamMoriyoshiTutorial():
    prefix=foamTutorials()
    if foamFork()=="openfoamplus" and foamVersionNumber()>=(1612,):
        ras="RAS"
    else:
        ras="ras"

    return path.join(prefix,"combustion","XiFoam",ras,"moriyoshiHomogeneous")
Ejemplo n.º 24
0
def simpleBikeTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"incompressible")
    else:
        error("The simpleFoam-motorBike-case does not exist before 1.6")
        
    return path.join(prefix,"simpleFoam","motorBike")
Ejemplo n.º 25
0
def damBreakTutorial():
    prefix=foamTutorials()
    if oldTutorialStructure():
        prefix=path.join(prefix,"interFoam")
    else:
        prefix=path.join(prefix,"multiphase","interFoam","laminar")
        if foamFork() in ["openfoam","openfoamplus"] and foamVersionNumber()>=(4,):
            prefix=path.join(prefix,"damBreak")
    return path.join(prefix,"damBreak")
def damBreakTutorial():
    prefix=foamTutorials()
    if oldTutorialStructure():
        prefix=path.join(prefix,"interFoam")
    else:
        prefix=path.join(prefix,"multiphase","interFoam","laminar")
        if foamFork() in ["openfoam","openfoamplus"] and foamVersionNumber()>=(4,):
            prefix=path.join(prefix,"damBreak")
    return path.join(prefix,"damBreak")
Ejemplo n.º 27
0
class IncludeFilesRoundTrip(unittest.TestCase):
    def setUp(self):
        self.theDir=mkdtemp()
        if oldTutorialStructure():
            null="0"
        elif foamFork() in ["openfoam","openfoamplus"] and foamVersionNumber()>=(4,):
            null="0.orig"
        else:
            null="0.org"

        usedDir=path.join(self.theDir,"data")
        copytree(path.join(simpleBikeTutorial(),null),usedDir)
        self.theFile=path.join(usedDir,"U")

    def tearDown(self):
        rmtree(self.theDir)

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadTutorial(self):
        test=ParsedParameterFile(self.theFile,listLengthUnparsed=100)
        data1=deepcopy(test.content)
        open(self.theFile,"w").write(str(FoamFileGenerator(data1,header=test.header)))
        del test
        test2=ParsedParameterFile(self.theFile,listLengthUnparsed=100)
        self.assertEqual(data1,test2.content)

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadTutorialWithMacros(self):
        test=ParsedParameterFile(self.theFile,
                                 listLengthUnparsed=100,
                                 doMacroExpansion=True)
        data1=deepcopy(test.content)
        open(self.theFile,"w").write(str(FoamFileGenerator(data1,header=test.header)))
        del test
        test2=ParsedParameterFile(self.theFile,listLengthUnparsed=100,doMacroExpansion=True)
        self.compareData(data1,test2.content)

    def compareData(self,d1,d2):
        for k in d1:
            if type(k) not in [int]:
                if type(d1[k])!=DictProxy:
                    self.assertEqual(str(d1[k]),str(d2[k]))
                else:
                    self.compareData(d1[k],d2[k])
Ejemplo n.º 28
0
    def setUp(self):
        self.testDir=mkdtemp()
        self.dest=path.join(self.testDir,"0.org")
        if foamFork() in ["openfoam","openfoamplus"] and foamVersionNumber()>=(4,):
            null="0.orig"
        else:
            null="0.org"

        copytree(path.join(foamTutorials(),"incompressible","simpleFoam","motorBike",null),
                 self.dest)
    def test_with_broyden(self):
        """
        broyden test
        """
        if not foamVersionNumber() in [(2,3),(2,2)]:
            raise unittest.SkipTest("need ver.2.3 or 2.2 for this unittest.")
        
        cavityTut = os.path.join(foamTutorials(),
                                "incompressible/icoFoam/cavity")

        if not os.path.exists(cavityTut):
            raise unittest.SkipTest("need $FOAM_TUTORIALS/incompressible/cavity \
                               for unittest.")

        try:
            shutil.copytree(cavityTut, os.path.join(self.tmpDir,"cavity"))
            cavityCase = SolutionDirectory(os.path.join(self.tmpDir,"cavity"))
        except:
            raise unittest.SkipTest("can not copy cavity case to temp_dir.")   
                 
        #create Allrun 
        with open(os.path.join(cavityCase.name,"Allrun"),'w') as fp:
            fp.write('#!/bin/sh\nblockMesh>log.blockMesh\nicoFoam>log.icoFoam\n')
        os.chmod(os.path.join(cavityCase.name,"Allrun"),0777)
         
        #append controlDict
        fObj="""
functions
{
    probes
    {
        type            probes;
        functionObjectLibs ("libsampling.so");
        enabled         true;
        outputControl   timeStep;
        outputInterval  1;
        fields
        (
            p
        );
        probeLocations
        (
            ( 0.1 0.0925 0.005 )
        );
    }
}
"""
        with open(cavityCase.controlDict(),'a') as fp:
            fp.write(fObj)
        
        #test start
        sim = set_as_top(BroydenCavityInstance())
        sim.cavity.case_dir = cavityCase.name
        sim.run()
        self.assertEqual(round(sim.cavity.nu,4),0.01)
Ejemplo n.º 30
0
class ParsedParameterFileIncludeFuncQuotedTest(unittest.TestCase):
    def setUp(self):
        self.fileName=path.join(backwardFacingStep2DTutorial(),"system","controlDict")

    def tearDown(self):
        pass

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testBasicIncludeFunc(self):
        test=ParsedParameterFile(self.fileName,doMacroExpansion=True)
        self.assertEqual(test["functions"]["sampleCp"]["fields"],["cp"])
        self.assertEqual(test["functions"]["wallShearStress"]["writeControl"],"writeTime")
Ejemplo n.º 31
0
class ParsedParameterFileIncludeFuncTest(unittest.TestCase):
    def setUp(self):
        self.fileName=path.join(planarContractionTutorial(),"system","controlDict")

    def tearDown(self):
        pass

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testBasicIncludeFunc(self):
        test=ParsedParameterFile(self.fileName,doMacroExpansion=True)
        self.assertEqual(test["functions"]["graphs"]["fields"],["U"])
        self.assertEqual(test["functions"]["graphs"]["writeControl"],"writeTime")
Ejemplo n.º 32
0
class ParsedBoundaryDictTest(unittest.TestCase):
    def setUp(self):
        self.theFile=mktemp()
        copyfile(path.join(foamTutorials(),"incompressible","simpleFoam","airFoil2D","constant","polyMesh","boundary"),self.theFile)

    def tearDown(self):
        remove(self.theFile)

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadTutorial(self):
        test=ParsedBoundaryDict(self.theFile)
        self.assertEqual(len(test.content),4)
        self.assertTrue("inlet" in test)
Ejemplo n.º 33
0
class FoamFileGeneratorRoundtrip4(unittest.TestCase):
    def setUp(self):
        self.theFile=mktemp()
        copyfile(path.join(buoyHotRoomTutorial(),"0","U"),self.theFile)

    def tearDown(self):
        remove(self.theFile)

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadTutorial(self):
        test=ParsedParameterFile(self.theFile)
        data1=deepcopy(test.content)
        open(self.theFile,"w").write(str(FoamFileGenerator(data1,header=test.header)))
        del test
        test2=ParsedParameterFile(self.theFile)
        self.assertEqual(data1,test2.content)
Ejemplo n.º 34
0
class ParsedParameterFileTest2(unittest.TestCase):
    def setUp(self):
        self.theFile=mktemp()
        if foamVersionNumber()<=(2,0):
            extension=""
        elif foamFork() in ["openfoam","openfoamplus"] and foamVersionNumber()>=(4,):
            extension=".orig"
        else:
            extension=".org"
        copyfile(path.join(damBreakTutorial(),"0",gammaName()+extension),self.theFile)

    def tearDown(self):
        remove(self.theFile)

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadTutorial(self):
        test=ParsedParameterFile(self.theFile)
        self.assertEqual(len(test["boundaryField"]),5)
Ejemplo n.º 35
0
class ParsedParameterFileTest6(unittest.TestCase):
    def setUp(self):
        if foamVersionNumber()>=(1,6):
            import pytest
            pytest.skip("aachenBomb-tutorial no longer existing")

        self.theFile=mktemp()
        copyfile(path.join(dieselAachenTutorial(),"0","spray"),self.theFile)

    def tearDown(self):
        remove(self.theFile)

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadTutorial(self):
        try:
            test=ParsedParameterFile(self.theFile)
        except PyFoamParserError:
            pass
Ejemplo n.º 36
0
class ParsedParameterFileCodeStreamTest(unittest.TestCase):
    def setUp(self):
        self.fileName=path.join(potentialCylinderTutorial(),"system","controlDict")

    def tearDown(self):
        pass

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testBasicInclude(self):
        test=ParsedParameterFile(self.fileName)
        if foamVersionNumber()<(2,):
            return
        if foamFork() in ["openfoam","openfoamplus"] and foamVersionNumber()>=(4,):
            key="error"
            code="codeEnd"
        else:
            key="difference"
            code="code"
        self.assertEqual(type(test["functions"][key][code]),Codestream)
Ejemplo n.º 37
0
class FoamFileGeneratorRoundtripZipped(unittest.TestCase):
    def setUp(self):
        self.theFile=mktemp()
        copyfile(path.join(damBreakTutorial(),"system","fvSolution"),self.theFile)
        system("gzip -f "+self.theFile)

    def tearDown(self):
        remove(self.theFile+".gz")

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testReadTutorial(self):
        test=ParsedParameterFile(self.theFile)
        data1=deepcopy(test.content)
        open(self.theFile,"w").write(str(FoamFileGenerator(data1,header=test.header)))
        del test
        test2=ParsedParameterFile(self.theFile)
        self.assertEqual(data1,test2.content)
        test3=ParsedParameterFile(self.theFile+".gz")
        self.assertEqual(data1,test3.content)
Ejemplo n.º 38
0
class ParsedParameterFileIncludeTest(unittest.TestCase):
    def setUp(self):
        if oldTutorialStructure():
            null="0"
        elif foamFork() in ["openfoam","openfoamplus"] and foamVersionNumber()>=(4,):
            null="0.orig"
        else:
            null="0.org"
        self.fileName=path.join(simpleBikeTutorial(),null,"U")

    def tearDown(self):
        pass

    @pytest.mark.skipif(foamTutorials()=='',reason="$FOAM_TUTORIALS is not defined")
    def testBasicInclude(self):
        test=ParsedParameterFile(self.fileName,doMacroExpansion=True)
        self.assertEqual(test["pressure"],0)
        self.assertEqual("upperWall" in test["boundaryField"],True)
        self.assertEqual(test["boundaryField"]["upperWall"]["type"],"slip")
 def setUp(self):
     self.theFile=mktemp()
     copyfile(path.join(foamTutorials(),"incompressible","simpleFoam","airFoil2D","constant","polyMesh","boundary"),self.theFile)
Ejemplo n.º 40
0
    def run(self):
        config=ConfigParser.ConfigParser()
        files=self.parser.getArgs()

        good=config.read(files)
        # will work with 2.4
        # if len(good)!=len(files):
        #    print "Problem while trying to parse files",files
        #    print "Only ",good," could be parsed"
        #    sys.exit(-1)

        benchName=config.get("General","name")
        if self.opts.nameAddition!=None:
            benchName+="_"+self.opts.nameAddition
        if self.opts.foamVersion!=None:
            benchName+="_v"+self.opts.foamVersion
            
        isParallel=config.getboolean("General","parallel")
        lam=None

        if isParallel:
            nrCpus=config.getint("General","nProcs")
            machineFile=config.get("General","machines")
            if not path.exists(machineFile):
                self.error("Machine file ",machineFile,"needed for parallel run")
            lam=LAMMachine(machineFile,nr=nrCpus)
            if lam.cpuNr()>nrCpus:
                self.error("Wrong number of CPUs: ",lam.cpuNr())

            print "Running parallel on",lam.cpuNr(),"CPUs"

        if config.has_option("General","casesDirectory"):
            casesDirectory=path.expanduser(config.get("General","casesDirectory"))
        else:
            casesDirectory=foamTutorials()

        if not path.exists(casesDirectory):
            self.error("Directory",casesDirectory,"needed with the benchmark cases is missing")
        else:
            print "Using cases from directory",casesDirectory

        benchCases=[]
        config.remove_section("General")

        for sec in config.sections():
            print "Reading: ",sec
            skipIt=False
            skipReason=""
            if config.has_option(sec,"skip"):
                skipIt=config.getboolean(sec,"skip")
                skipReason="Switched off in file"
            if self.opts.excases!=None and not skipIt:
                for p in self.opts.excases:
                    if fnmatch(sec,p):
                        skipIt=True
                        skipReason="Switched off by pattern '"+p+"'"
            if self.opts.cases!=None:
                for p in self.opts.cases:
                    if fnmatch(sec,p):
                        skipIt=False
                        skipReason=""
                
            if skipIt:
                print "Skipping case ..... Reason:"+skipReason
                continue
            sol=config.get(sec,"solver")
            cas=config.get(sec,"case")
            pre=eval(config.get(sec,"prepare"))
            preCon=[]
            if config.has_option(sec,"preControlDict"):
                preCon=eval(config.get(sec,"preControlDict"))
            con=eval(config.get(sec,"controlDict"))
            bas=config.getfloat(sec,"baseline")
            wei=config.getfloat(sec,"weight")
            add=[]
            if config.has_option(sec,"additional"):
                add=eval(config.get(sec,"additional"))
                print "Adding: ", add
            util=[]
            if config.has_option(sec,"utilities"):
                util=eval(config.get(sec,"utilities"))
                print "Utilities: ", util    
            nr=99999
            if config.has_option(sec,"nr"):
                nr=eval(config.get(sec,"nr"))
            sp=None
            if config.has_option(sec,"blockSplit"):
                sp=eval(config.get(sec,"blockSplit"))
            toRm=[]
            if config.has_option(sec,"filesToRemove"):
                toRm=eval(config.get(sec,"filesToRemove"))
            setInit=[]
            if config.has_option(sec,"setInitial"):
                setInit=eval(config.get(sec,"setInitial"))

            parallelOK=False
            if config.has_option(sec,"parallelOK"):
                parallelOK=config.getboolean(sec,"parallelOK")

            deMet=["metis"]
            if config.has_option(sec,"decomposition"):
                deMet=config.get(sec,"decomposition").split()

            if deMet[0]=="metis":
                pass
            elif deMet[0]=="simple":
                if len(deMet)<2:
                    deMet.append(0)
                else:
                    deMet[1]=int(deMet[1])
            else:
                print "Unimplemented decomposition method",deMet[0],"switching to metis"
                deMet=["metis"]

            if isParallel==False or parallelOK==True:
                if path.exists(path.join(casesDirectory,sol,cas)):
                    benchCases.append( (nr,sec,sol,cas,pre,con,preCon,bas,wei,add,util,sp,toRm,setInit,deMet) )
                else:
                    print "Skipping",sec,"because directory",path.join(casesDirectory,sol,cas),"could not be found"
            else:
                print "Skipping",sec,"because not parallel"

        benchCases.sort()

        parallelString=""
        if isParallel:
            parallelString=".cpus="+str(nrCpus)

        resultFile=open("Benchmark."+benchName+"."+uname()[1]+parallelString+".results","w")

        totalSpeedup=0
        minSpeedup=None
        maxSpeedup=None
        totalWeight =0
        runsOK=0
        currentEstimate = 1.

        print "\nStart Benching\n"
        
        csv=CSVCollection("Benchmark."+benchName+"."+uname()[1]+parallelString+".csv")
        
#        csvHeaders=["description","solver","case","caseDir","base",
#                    "benchmark","machine","arch","cpus","os","version",
#                    "wallclocktime","cputime","cputimeuser","cputimesystem","maxmemory","cpuusage","speedup"]

        for nr,description,solver,case,prepare,control,preControl,base,weight,additional,utilities,split,toRemove,setInit,decomposition in benchCases:
            #    control.append( ("endTime",-2000) )
            print "Running Benchmark: ",description
            print "Solver: ",solver
            print "Case: ",case
            caseName=solver+"_"+case+"_"+benchName+"."+uname()[1]+".case"
            print "Short name: ",caseName
            caseDir=caseName+".runDir"

            csv["description"]=description
            csv["solver"]=solver
            csv["case"]=case
            csv["caseDir"]=caseDir
            csv["base"]=base

            csv["benchmark"]=benchName
            csv["machine"]=uname()[1]
            csv["arch"]=uname()[4]
            if lam==None:
                csv["cpus"]=1
            else:
                csv["cpus"]=lam.cpuNr()
            csv["os"]=uname()[0]
            csv["version"]=uname()[2]
            
            workDir=path.realpath(path.curdir)

            orig=SolutionDirectory(path.join(casesDirectory,solver,case),
                                   archive=None,
                                   paraviewLink=False)
            for a in additional+utilities:
                orig.addToClone(a)
            orig.cloneCase(path.join(workDir,caseDir))

            if oldApp():
                argv=[solver,workDir,caseDir]
            else:
                argv=[solver,"-case",path.join(workDir,caseDir)]
                
            run=BasicRunner(silent=True,argv=argv,logname="BenchRunning",lam=lam)
            runDir=run.getSolutionDirectory()
            controlFile=ParameterFile(runDir.controlDict())

            for name,value in preControl:
                print "Setting parameter",name,"to",value,"in controlDict"
                controlFile.replaceParameter(name,value)

            for rm in toRemove:
                fn=path.join(caseDir,rm)
                print "Removing file",fn
                remove(fn)

            for field,bc,val in setInit:
                print "Setting",field,"on",bc,"to",val
                SolutionFile(runDir.initialDir(),field).replaceBoundary(bc,val)

            oldDeltaT=controlFile.replaceParameter("deltaT",0)

            for u in utilities:
                print "Building utility ",u
                execute("wmake 2>&1 >%s %s" % (path.join(caseDir,"BenchCompile."+u),path.join(caseDir,u)))

            print "Preparing the case: "
            if lam!=None:
                prepare=prepare+[("decomposePar","")]
                if decomposition[0]=="metis":
                    lam.writeMetis(SolutionDirectory(path.join(workDir,caseDir)))
                elif decomposition[0]=="simple":
                    lam.writeSimple(SolutionDirectory(path.join(workDir,caseDir)),decomposition[1])

            if split:
                print "Splitting the mesh:",split
                bm=BlockMesh(runDir.blockMesh())
                bm.refineMesh(split)

            for pre,post in prepare:
                print "Doing ",pre," ...."
                post=post.replace("%case%",caseDir)
                if oldApp():
                    args=string.split("%s %s %s %s" % (pre,workDir,caseDir,post))
                else:
                    args=string.split("%s -case %s %s" % (pre,path.join(workDir,caseDir),post))
                util=BasicRunner(silent=True,argv=args,logname="BenchPrepare_"+pre)
                util.start()

            controlFile.replaceParameter("deltaT",oldDeltaT)

            #    control.append(("endTime",-1000))
            for name,value in control:
                print "Setting parameter",name,"to",value,"in controlDict"
                controlFile.replaceParameter(name,value)

            print "Starting at ",asctime(localtime(time()))
            print " Baseline is %f, estimated speedup %f -> estimated end at %s " % (base,currentEstimate,asctime(localtime(time()+base/currentEstimate)))
            print "Running the case ...."
            run.start()

            speedup=None
            cpuUsage=0
            speedupOut=-1

            try:
                speedup=base/run.run.wallTime()
                cpuUsage=100.*run.run.cpuTime()/run.run.wallTime()
            except ZeroDivisionError:
                print "Division by Zero: ",run.run.wallTime()

            if not run.runOK():
                print "\nWARNING!!!!"
                print "Run had a problem, not using the results. Check the log\n"
                speedup=None

            if speedup!=None:
                speedupOut=speedup

                totalSpeedup+=speedup*weight
                totalWeight +=weight
                runsOK+=1
                if maxSpeedup==None:
                    maxSpeedup=speedup
                elif speedup>maxSpeedup:
                    maxSpeedup=speedup
                if minSpeedup==None:
                    minSpeedup=speedup
                elif speedup<minSpeedup:
                    minSpeedup=speedup

            print "Wall clock: ",run.run.wallTime()
            print "Speedup: ",speedup," (Baseline: ",base,")"
            print "CPU Time: ",run.run.cpuTime()
            print "CPU Time User: "******"CPU Time System: ",run.run.cpuSystemTime()
            print "Memory: ",run.run.usedMemory()
            print "CPU Usage: %6.2f%%" % (cpuUsage)

            csv["wallclocktime"]=run.run.wallTime()
            csv["cputime"]=run.run.cpuTime()
            csv["cputimeuser"]=run.run.cpuUserTime()
            csv["cputimesystem"]=run.run.cpuSystemTime()
            csv["maxmemory"]=run.run.usedMemory()
            csv["cpuusage"]=cpuUsage
            if speedup!=None:
                csv["speedup"]=speedup
            else:
                csv["speedup"]="##"
                
            csv.write()
            
            resultFile.write("Case %s WallTime %g CPUTime %g UserTime %g SystemTime %g Memory %g MB  Speedup %g\n" %(caseName,run.run.wallTime(),run.run.cpuTime(),run.run.cpuUserTime(),run.run.cpuSystemTime(),run.run.usedMemory(),speedupOut))

            resultFile.flush()
            
            if speedup!=None:
                currentEstimate=totalSpeedup/totalWeight

            if self.opts.removeCases:
                print "Clearing case",
                if speedup==None:
                    print "not ... because it failed"
                else:
                    print "completely"
                    rmtree(caseDir,ignore_errors=True)

            print
            print
        
        if lam!=None:
            lam.stop()

        print "Total Speedup: ",currentEstimate," ( ",totalSpeedup," / ",totalWeight, " ) Range: [",minSpeedup,",",maxSpeedup,"]"

        print runsOK,"of",len(benchCases),"ran OK"

        resultFile.write("Total Speedup: %g\n" % (currentEstimate))
        if minSpeedup and maxSpeedup:
            resultFile.write("Range: [ %g , %g ]\n" % (minSpeedup,maxSpeedup))

        resultFile.close()
    def test_with_moga(self):
        """
        moga test with pyopt_driver.
        create meta and optimization with nsga2.
        """
        if not foamVersionNumber() in [(2,3),(2,2)]:
            raise unittest.SkipTest("need ver.2.3 or 2.2 for this unittest.")
        
        cavityTut = os.path.join(foamTutorials(),
                                "incompressible/icoFoam/cavity")

        if not os.path.exists(cavityTut):
            raise unittest.SkipTest("need $FOAM_TUTORIALS/incompressible/cavity \
                               for unittest.")

        try:
            shutil.copytree(cavityTut, os.path.join(self.tmpDir,"cavity"))
            cavityCase = SolutionDirectory(os.path.join(self.tmpDir,"cavity"))
        except:
            raise unittest.SkipTest("can not copy cavity case to temp_dir.")   
                 
        #create Allrun 
        with open(os.path.join(cavityCase.name,"Allrun"),'w') as fp:
            fp.write('#!/bin/sh\nblockMesh>log.blockMesh\nicoFoam>log.icoFoam\n')
        os.chmod(os.path.join(cavityCase.name,"Allrun"),0777)
         
        #append controlDict
        fObj="""
functions
{
    probes
    {
        type            probes;
        functionObjectLibs ("libsampling.so");
        enabled         true;
        outputControl   timeStep;
        outputInterval  1;
        fields
        (
            p U
        );
        probeLocations
        (
            ( 0.015 0.015 0.005 )
            ( 0.085 0.015 0.005 )
        );
    }
}
"""
        with open(cavityCase.controlDict(),'a') as fp:
            fp.write(fObj)
        
        #test start
        sim = set_as_top(MultiObjectiveCavity())
        sim.DeformationCavity_meta.model.case_dir = cavityCase.name
        sim.DeformationCavity.case_dir = cavityCase.name
        try:
            sim.NSGA2.optimizer = 'NSGA2'
        except ValueError:
            raise SkipTest("NSGA2 not present on this system")
        sim.NSGA2.options['PrintOut'] = 0
        sim.run()        
Ejemplo n.º 42
0
def plateHoleTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"stressAnalysis")
    return path.join(prefix,"solidDisplacementFoam","plateHole")
 def setUp(self):
     self.dest=mktemp()
     wholePath=path.join(foamTutorials(),"incompressible","simpleFoam","airFoil2D")
     SolutionDirectory(wholePath,archive=None,paraviewLink=False).cloneCase(self.dest)
Ejemplo n.º 44
0
def simplePitzTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"incompressible")
    return path.join(prefix,"simpleFoam","pitzDaily")
Ejemplo n.º 45
0
def dieselAachenTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"combustion")
    return path.join(prefix,"dieselFoam","aachenBomb")
Ejemplo n.º 46
0
 def setUp(self):
     self.testDir=mkdtemp()
     self.dest=path.join(self.testDir,"0.org")
     copytree(path.join(foamTutorials(),"incompressible","simpleFoam","motorBike","0.org"),
              self.dest)
Ejemplo n.º 47
0
def buoyHotRoomTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"heatTransfer")            
    return path.join(prefix,"buoyantSimpleFoam","hotRoom")
Ejemplo n.º 48
0
def bubbleColumnTutorial():
    prefix=foamTutorials()
    if not oldTutorialStructure():
        prefix=path.join(prefix,"multiphase")            
    return path.join(prefix,"twoPhaseEulerFoam","bubbleColumn")