コード例 #1
0
ファイル: verifyproblem.py プロジェクト: apdimier/Etumos
def regionPhysicalQuantitiesCheck(physicalQuantitiesList,regions,species=None):
    """
    raise an exception if a physical property, or an element of physicalQuantitiesList, 
    is not defined in one region of the list regions called list
    """
    #
    physicalQuantitiesList = toList(physicalQuantitiesList)
    physicalQuantitiesNames = []
    physicalQuantitiesNames = [getPhysicalQuantityName(physicalQuantity) for physicalQuantity in physicalQuantitiesList]
#    for physicalQuantity in physicalQuantitiesList:
#        physicalQuantitiesNames.append(getPhysicalQuantityName(physicalQuantity))
#        pass
    physicalQuantitiesNames = tuple(physicalQuantitiesNames)
    affichage='('+(len(physicalQuantitiesNames)-1)*'%s, '+'%s)'
    #
    #
    #
    for reg in regions:
        anzPhysQuant=0
        for PhysQuant in physicalQuantitiesList:
            anzPhysQuant+= verifyPhysicalQuantityOnRegion(PhysQuant,reg,species,option='boolean')
            pass
        if anzPhysQuant == 0:
            verbose = "no physical quantity of "
            verbose+= "is defined for material  '%s'."%reg.getMaterial().getName()
            raise Exception(verbose)
        pass
コード例 #2
0
 def __init__(self, zone, value, some_classes):
     """Zone condition initialisation"""
     self.value_species, self.value_property = _associateZoneValue(
         zone, value, some_classes)
     verifyZones(toList(zone))
     self.zone = zone
     return
コード例 #3
0
    def __init__(self,
                 name,
                 regions,
                 calculationTimes,
                 gravity,
                 density,
                 viscosity,
                 boundaryConditions,
                 initialConditions=None,
                 zoneConditions=None,
                 source=None,
                 outputs=None,
                 defaultBoundaryCondition=None,
                 defaultInitialCondition=None):
        """Problem initialisation with :
        - a name (string)
        - one or several regions (object Region or list of Region)
        - one or several boundary conditions (object BoundaryCondition
          or list of BoundaryCondition)
        - a gravity (object Gravity)
        - a density (object Density)
        - a viscosity (object Viscosity)
        - OPTIONAL :
          --> one or several zone conditions (object ZoneCondition
              or list of ZoneCondition)
          --> one or several sources (object Source or list of Source)
          --> one or several outputs (object ExpectedOutput or list of
              ExpectedOutput)
          --> a tuple to define default boundary condition.
              It will be used if boundaryConditions defined in the problem
              don't cover entire boundaries.
              First element of tuple contains a string which represent
                default boundary condition type ('Dirichlet' or 'Neumann' For example)
              Second Element represent a PhysicalQuantity with default Boundary Condition Value
                Head(0.) or HeadGradient(0.) for example
          --> a PhysiqualQuantity to define value of default initial condition
        """

        # regions treatment
        regions = toList(regions)
        from datamodel import Permeability, IntrinsicPermeability
        from datamodel import MatrixCompressibilityFactor, Porosity, LiquidResidualSaturation
        verifySomeOfPhysicalQuantitiesExists(
            [Permeability, IntrinsicPermeability], regions, option='exclusive')
        verifyPhysicalQuantityExists(
            [MatrixCompressibilityFactor, Porosity, LiquidResidualSaturation],
            regions)

        HydraulicProblem.__init__(self, 'unsaturated', name, regions,
                                  boundaryConditions, calculationTimes,
                                  gravity, density, viscosity,
                                  initialConditions, zoneConditions, source,
                                  outputs, defaultBoundaryCondition,
                                  defaultInitialCondition)

        # Consistance problem verification
        if self.density == None:
            raise Exception, " you have to define a density before launching the problem "

        return
コード例 #4
0
def getTimeUnifiedTables(*ttuple):
    """ principe :
    on envoie N tables dans la fonction, et on recupere
    N tables dont les instants sont l'union des instants
    de chacune des tables initiales
    """
    tablist = toList(ttuple)
    glue = tuple([x.getColumn(0).tolist() for x in tablist])
    if not len(glue): return
    temporary = glue[0]
    for element in glue[1:len(glue)]:
        for item in element:
            if item not in temporary:
                temporary.append(item)
                pass
            pass
        pass
    temporary.sort()

    new_tables = []
    for tabl in tablist:
        extravalues = interpolate(temporary, tabl)
        colt = tabl.getColumnTitles()
        tnew = Table(tabl.getTitle())
        tnew.addColumn(colt[0], temporary)
        tnew.addColumn(colt[1], extravalues)
        new_tables.append(tnew)
        pass
    return new_tables
コード例 #5
0
    def __init__(self,
                 boundary,
                 kind,
                 value,
                 bcdict,
                 porosity=None,
                 description=None):
        """Boundary condition initialisation with :
        - one boundary

        - a boundary condition type.
          We verify that it's a key of bcdict dictionnary
        - a boundary condition value. Value depend of boundary condition type.
        -bcdict : a dictionnary with key = type of boundary condition and value = Possible class of boundary condition value
        """
        self.value_species = None

        memberShip(boundary.support, [CartesianMesh, Body])

        #        verifyClass(boundary,[CartesianMesh,Body])
        self.boundary = boundary
        if type(kind) != StringType:
            raise TypeError(" type should be a string")
        if kind not in list(bcdict.keys()):
            raise Exception(" check the boundary condition type ")
        self.type = kind

        value = toList(value)
        for val in value:
            if type(val) is TupleType:
                checked = val[0]
                for i in range(1, len(val)):
                    memberShip(val[i], Species)
                    pass
                pass
            else:
                checked = val
                pass
            for definedtype in bcdict:
                if kind == definedtype:
                    memberShip(checked, bcdict[kind])
                    pass
                pass
            pass
        if not self.value_species:
            from PhysicalQuantities import PhysicalQuantity
            from species import createList
            print(value)
            self.value_species, self.value_property = createList(
                value, PhysicalQuantity)
            pass

        if description == None:
            self.description = ""
            pass
        else:
            self.description = description
            pass
        return
コード例 #6
0
def _associateZoneValue(zone, value, some_classes):
    zones = toList(zone)
    verifyClassList(zones, [CartesianMesh])
    value = toList(value)
    for val in value:
        if type(val) is TupleType:
            from datamodel import Species
            memberShip(val[0], some_classes)
            memberShip(val[1], Species)
            pass
        else:
            memberShip(val, some_classes)
            pass
        pass

    from datamodel import createList
    from datamodel import PhysicalQuantity
    value_species, value_property = createList(value, PhysicalQuantity)
    return value_species, value_property
コード例 #7
0
ファイル: commonproblem.py プロジェクト: apdimier/Etumos
def _associateZoneValue(zone,value,some_classes):
    zones=toList(zone)
    verifyClassList(zones,[CartesianMesh])
    value = toList(value)
    for val in value:
        if type(val) is TupleType:
            from datamodel import  Species
            memberShip(val[0], some_classes)
            memberShip(val[1], Species)
            pass
        else:
            memberShip(val, some_classes)
            pass
        pass

    from datamodel import createList
    from datamodel import PhysicalQuantity
    value_species, value_property = createList(value, PhysicalQuantity)
    return value_species, value_property
コード例 #8
0
ファイル: commonproblem.py プロジェクト: apdimier/Etumos
    def __init__(self, boundary, kind, value, bcdict, porosity = None, description = None):
        """Boundary condition initialisation with :
        - one boundary

        - a boundary condition type.
          We verify that it's a key of bcdict dictionnary
        - a boundary condition value. Value depend of boundary condition type.
        -bcdict : a dictionnary with key = type of boundary condition and value = Possible class of boundary condition value
        """        
        self.value_species =None

        memberShip(boundary.support,[CartesianMesh, Body])

#        verifyClass(boundary,[CartesianMesh,Body])
        self.boundary = boundary
        if type(kind) != StringType:
            raise TypeError(" type should be a string")
        if kind not in list(bcdict.keys()): raise Exception(" check the boundary condition type ")
        self.type = kind

        value = toList(value)
        for val in value:
            if type(val) is TupleType:
                checked = val[0] 
                for i in range(1,len(val)):
                    from datamodel import Species
                    memberShip(val[i], Species)
                    pass
                pass
            else:
                checked = val
                pass
            for definedtype in bcdict:
                if kind == definedtype:
                    memberShip(checked, bcdict[kind])
                    pass
                pass
            pass
        if not self.value_species:
            from PhysicalQuantities import PhysicalQuantity
            from species import createList
            print(value)
            self.value_species, self.value_property = createList(value, PhysicalQuantity)
            pass

        if description == None:
            self.description = ""
            pass
        else:
            self.description = description
            pass
        return
コード例 #9
0
    def __init__(self, name, regions,calculationTimes,
                 gravity,
                 density,
                 viscosity,                 
                 boundaryConditions,
                 initialConditions = None,
                 zoneConditions = None,
                 source=None,
                 outputs=None,
                 defaultBoundaryCondition=None,
                 defaultInitialCondition=None):
        """Problem initialisation with :
        - a name (string)
        - one or several regions (object Region or list of Region)
        - one or several boundary conditions (object BoundaryCondition
          or list of BoundaryCondition)
        - a gravity (object Gravity)
        - a density (object Density)
        - a viscosity (object Viscosity)
        - OPTIONAL :
          --> one or several zone conditions (object ZoneCondition
              or list of ZoneCondition)
          --> one or several sources (object Source or list of Source)
          --> one or several outputs (object ExpectedOutput or list of
              ExpectedOutput)
          --> a tuple to define default boundary condition.
              It will be used if boundaryConditions defined in the problem
              don't cover entire boundaries.
              First element of tuple contains a string which represent
                default boundary condition type ('Dirichlet' or 'Neumann' For example)
              Second Element represent a PhysicalQuantity with default Boundary Condition Value
                Head(0.) or HeadGradient(0.) for example
          --> a PhysiqualQuantity to define value of default initial condition
        """


        # regions treatment
        regions = toList(regions)
        from datamodel import Permeability, IntrinsicPermeability
        from datamodel import MatrixCompressibilityFactor,Porosity,LiquidResidualSaturation
        verifySomeOfPhysicalQuantitiesExists([Permeability, IntrinsicPermeability], regions,option='exclusive')
        verifyPhysicalQuantityExists([MatrixCompressibilityFactor,Porosity,LiquidResidualSaturation], regions)

        HydraulicProblem.__init__(self,'unsaturated',name, regions,boundaryConditions,calculationTimes,
                                  gravity,density,viscosity,
                                  initialConditions,zoneConditions,
                                  source,outputs,defaultBoundaryCondition,defaultInitialCondition)
        
        # Consistance problem verification
        if self.density == None: raise Exception, " you have to define a density before launching the problem "

        return
コード例 #10
0
    def __init__(self,
                 name,
                 regions,
                 boundaryConditions,
                 initialConditions = None,\
                 temperature = None,\
                 simulationType = None,\
                 calculationTimes = None,\
                 gravity = None,
                 density = None,
                 source = None,
                 intrinsicPermeability = None,\
                 viscosity = None,
                 outputs = None):
        """Problem initialisation with :
        - a name (string)
        - one or several regions (object Region or list of Region)
        - one or several boundary conditions (object BoundaryCondition
          or list of BoundaryCondition)
        - OPTIONAL :
          --> one or several zone conditions (object ZoneCondition
              or list of ZoneCondition)
          --> one or several sources (object Source or list of Source)
          --> a gravity (object Gravity) 
          --> a density (object Density)
          --> a viscosity (object Viscosity)
          --> one or several outputs (object ExpectedOutput or list of
              ExpectedOutput)
          """

        # regions treatment
        regions = toList(regions)
        verifySomeOfPhysicalQuantitiesExists(
            [Permeability, IntrinsicPermeability], regions, option="inclusive")

        HydraulicProblem.__init__(self,
                                  name = name,\
                                  saturation = "saturated",\
                                  regions = regions,
                                  boundaryConditions = boundaryConditions,\
                                  initialConditions = initialConditions,\
                                  temperature = temperature,\
                                  simulationType = simulationType,\
                                  calculationTimes = calculationTimes,\
                                  gravity = gravity,\
                                  density = density,\
                                  intrinsicPermeability =intrinsicPermeability,\
                                  viscosity = viscosity,\
                                  source = source,\
                                  outputs = outputs)
コード例 #11
0
ファイル: verifyproblem.py プロジェクト: apdimier/Etumos
def verifyPhysicalQuantityOnRegion(physicalQuantitiesList, region, species = None, option = None):
    physicalQuantitiesList = toList(physicalQuantitiesList)
    for physicalQuantity in physicalQuantitiesList:
        try:
            key = getPhysicalQuantityName(physicalQuantity)
        except:
            raise Exception("check the list of physical quantities")
        material = region.getMaterial()
        
        if material.hasProperty(key) == 0:
            message = " the material "%material.getName()+" has not the property named "%key
            raise Exception(message)
        else:
            return len(physicalQuantitiesList)
        pass
コード例 #12
0
    def __init__(self, zone, value, some_classes):
        """
        Initialisation of the source with:
        - one or several zones
        - value : instance of a class defined in some_classes
                  or a list of couple (Value,Species)
                  or a list with a default value and couples (Value,Species) 
                  for example [value,(value1,species1),(value2,species2)]
        - some_classes : list of possible classes of value
        """
        self.value_species, self.value_property = _associateZoneValue(
            zone, value, some_classes)
        verifyZones(toList(zone))
        self.zone = zone

        return
コード例 #13
0
ファイル: commonproblem.py プロジェクト: apdimier/Etumos
    def __init__(self, zone, value, some_classes):
        """
        Initialisation of the source with:
        - one or several zones
        - value : instance of a class defined in some_classes
                  or a list of couple (Value,Species)
                  or a list with a default value and couples (Value,Species) 
                  for example [value,(value1,species1),(value2,species2)]
        - some_classes : list of possible classes of value
        """
        self.value_species, self.value_property = _associateZoneValue(zone, value, some_classes)
        verifyZones(toList(zone))
        self.zone = zone


        return
コード例 #14
0
ファイル: verifyproblem.py プロジェクト: apdimier/Etumos
def verifySomeOfPhysicalQuantitiesExists(listOfPhysicalQuantities,
                                         regions,
                                         species=None,
                                         option='exclusive'):
    """
    raise an exception if an element of listOfPhysicalQuantities
    is not defined in one region of the region list regions"""
    #
    listOfPhysicalQuantities = toList(listOfPhysicalQuantities)

    listOfNames = []
    listOfNames = [
        getPhysicalQuantityName(physicalQuantity)
        for physicalQuantity in listOfPhysicalQuantities
    ]
    #    for physicalQuantity in listOfPhysicalQuantities:
    #        listOfNames.append(getPhysicalQuantityName(physicalQuantity))
    #        pass
    listOfNames = tuple(listOfNames)
    affichage = '(' + (len(listOfNames) - 1) * '%s, ' + '%s)'
    #
    for reg in regions:
        regPhysicalQuantityAnz = 0
        for physicalQuantity in listOfPhysicalQuantities:
            print("dbg verifyPhysicalQuantityOnRegion",
                  verifyPhysicalQuantityOnRegion(physicalQuantity, reg))
            regPhysicalQuantityAnz +=\
                verifyPhysicalQuantityOnRegion(physicalQuantity,reg)
            pass
        if not regPhysicalQuantityAnz:
            msg = 'no physical quantity of \n('
            msg += affichage % listOfNames
            msg+="\nis defined for material  '%s'."\
                  %reg.getMaterial().getName()
            raise Exception(msg)
        elif regPhysicalQuantityAnz > 1 and option == 'exclusive':
            msg = 'more than one of physical quantities in \n'
            msg += affichage % listOfNames
            msg+="\nis defined for material : '%s'."\
                  %reg.getMaterial().getName()
            raise Exception(msg)
        else:
            pass
        pass
コード例 #15
0
ファイル: verifyproblem.py プロジェクト: apdimier/Etumos
def verifyPhysicalQuantityOnRegion(physicalQuantitiesList,
                                   region,
                                   species=None,
                                   option=None):
    physicalQuantitiesList = toList(physicalQuantitiesList)
    for physicalQuantity in physicalQuantitiesList:
        try:
            key = getPhysicalQuantityName(physicalQuantity)
        except:
            raise Exception("check the list of physical quantities")
        material = region.getMaterial()

        if material.hasProperty(key) == 0:
            message = " the material " % material.getName(
            ) + " has not the property named " % key
            raise Exception(message)
        else:
            return len(physicalQuantitiesList)
        pass
コード例 #16
0
ファイル: verifyproblem.py プロジェクト: apdimier/Etumos
def verifySomeOfPhysicalQuantitiesExists(listOfPhysicalQuantities,regions,species=None,option='exclusive'):
    """
    raise an exception if an element of listOfPhysicalQuantities
    is not defined in one region of the region list regions"""
    #
    listOfPhysicalQuantities = toList(listOfPhysicalQuantities)
    
    listOfNames = []
    listOfNames = [getPhysicalQuantityName(physicalQuantity) for physicalQuantity in listOfPhysicalQuantities]
#    for physicalQuantity in listOfPhysicalQuantities:
#        listOfNames.append(getPhysicalQuantityName(physicalQuantity))
#        pass
    listOfNames=tuple(listOfNames)
    affichage='('+(len(listOfNames)-1)*'%s, '+'%s)'
    #
    for reg in regions:
        regPhysicalQuantityAnz = 0
        for physicalQuantity in listOfPhysicalQuantities:
            print("dbg verifyPhysicalQuantityOnRegion",verifyPhysicalQuantityOnRegion(physicalQuantity,reg))
            regPhysicalQuantityAnz +=\
                verifyPhysicalQuantityOnRegion(physicalQuantity,reg)
            pass
        if not regPhysicalQuantityAnz:
            msg='no physical quantity of \n('
            msg+=  affichage%listOfNames
            msg+="\nis defined for material  '%s'."\
                  %reg.getMaterial().getName()
            raise Exception(msg)
        elif regPhysicalQuantityAnz>1 and option=='exclusive':
            msg='more than one of physical quantities in \n'
            msg+=  affichage%listOfNames
            msg+="\nis defined for material : '%s'."\
                  %reg.getMaterial().getName()
            raise Exception(msg)
        else:
            pass
        pass
コード例 #17
0
ファイル: verifyproblem.py プロジェクト: apdimier/Etumos
def regionPhysicalQuantitiesCheck(physicalQuantitiesList,
                                  regions,
                                  species=None):
    """
    raise an exception if a physical property, or an element of physicalQuantitiesList, 
    is not defined in one region of the list regions called list
    """
    #
    physicalQuantitiesList = toList(physicalQuantitiesList)
    physicalQuantitiesNames = []
    physicalQuantitiesNames = [
        getPhysicalQuantityName(physicalQuantity)
        for physicalQuantity in physicalQuantitiesList
    ]
    #    for physicalQuantity in physicalQuantitiesList:
    #        physicalQuantitiesNames.append(getPhysicalQuantityName(physicalQuantity))
    #        pass
    physicalQuantitiesNames = tuple(physicalQuantitiesNames)
    affichage = '(' + (len(physicalQuantitiesNames) - 1) * '%s, ' + '%s)'
    #
    #
    #
    for reg in regions:
        anzPhysQuant = 0
        for PhysQuant in physicalQuantitiesList:
            anzPhysQuant += verifyPhysicalQuantityOnRegion(PhysQuant,
                                                           reg,
                                                           species,
                                                           option='boolean')
            pass
        if anzPhysQuant == 0:
            verbose = "no physical quantity of "
            verbose += "is defined for material  '%s'." % reg.getMaterial(
            ).getName()
            raise Exception(verbose)
        pass
コード例 #18
0
ファイル: verifyproblem.py プロジェクト: apdimier/Etumos
def verifyZoneBoundaryConditionisUnique(boundaryConditions):
    """
    a boundary should be defined only once, it raises an exception if not
    """
    t0 = time()
    i = 1
    boundaryConditions = toList(boundaryConditions)
    for boundary in boundaryConditions:
        boundlist = boundary.getBoundary()
        boundlist = toList(boundlist)
        for bound in boundlist:
            mesh = None
            for bounds in boundaryConditions[i:]:
                boundslist = bounds.getBoundary()
                boundslist = toList(boundslist)
                for bou in boundslist:
                    if mesh:
                        test = ((bou == bound) or mesh.intersectSupports(
                            'test', entity, [bou, bound]))
                        pass
                    else:
                        test = (bou == bound)
                        pass
                    if test:
                        vars1 = None
                        vars2 = None
                        try:
                            vars1 = boundary.getDepend()
                            vars2 = bounds.getDepend()
                        except:
                            msg = "ERROR : Different boundary conditions "
                            boundname = bound.getName()
                            if bou == bound:
                                msg += "defined on the same boundary"
                                msg += " named %s" % boundname + "."
                                pass
                            else:
                                bouname = bou.getName()
                                msg += "defined on boundaries with common elements.\n"
                                msg += "Boundaries with common elements are named %s" % boundname + " and %s" % bouname + "."
                                t1 = time()
                                print(
                                    'temps de verifyZoneBoundaryConditionisUnique : '
                                    + str(t1 - t0) + 's')
                                print('used memory :', getMemory(), 'Ko \n')
                            raise msg
                        for var in vars1:
                            if (var in vars2) or var == 'ALL' or vars2 == [
                                    'ALL'
                            ]:
                                msg = "ERROR : Different boundary conditions "
                                msg += "for the same variable : %s" % var
                                boundname = bound.getName()
                                if bou == bound:
                                    msg += " defined on the same boundary"
                                    msg += " named %s" % boundname + "."
                                    pass
                                else:
                                    bouname = bou.getName()
                                    msg += " defined on boundaries with common elements.\n"
                                    msg += "Boundaries with common elements are named %s" % boundname + " and %s" % bouname
                                    t1 = time()
                                    print(
                                        'temps de verifyZoneBoundaryConditionisUnique : '
                                        + str(t1 - t0) + 's')
                                    print('used memory :', getMemory(),
                                          'Ko \n')
                                    pass
                                raise Warning(msg)
                            pass
                        pass
                    pass
                pass
            pass
        i = i + 1
        pass
    t1 = time()
    print('temps de verifyZoneBoundaryConditionisUnique : ' + str(t1 - t0) +
          's')
    print('used memory :', getMemory(), 'Ko \n')
    return
コード例 #19
0
    def setData(self, problem,\
                mesh = None,\
                dicobc = None,\
                dicoic = None):

        self.expectedOutput = None
        self.problem = problem
        #print problem.__class__.__name__
        if not isinstance(problem, MechanicalProblem) and not isinstance(
                problem, THMCProblem):
            raise Exception(" the problem must be a mechanical problem")
        self.problemName = problem.getName()
        self.regions = problem.getRegions()

        self.mesh = mesh
        mediumProperties = {
            "density": None,
            "gravity": None,
            "YoungModulus": None,
            "PoissonRatio": None,
        }
        #
        # regionProperties is a dictionnary. It is made of a list of tuples, each region is associated to a dictionnary,
        # the dictionnary containing the medium region properties.
        #
        self.regionProperties = {}
        #
        self.times = problem.getCalculationTimes()
        #
        if self.times == None:
            self.simulationType = "Steady"
        else:
            self.simulationType = "Transient"
        #
        self.boundaryConditions = {}
        #
        self.initialConditions = {}
        #
        # we fill the medium properties dictionnary
        #
        self.solidDensity = problem.getDensity()
        self.gravity = problem.getGravity()
        #
        for reg in self.regions:
            regionName = reg.support.getBodyName()
            material = reg.getMaterial()
            self.regionProperties[regionName] = mediumProperties

            youngModulus = material.youngModulus
            poissonRatio = material.poissonRatio
            intrinsicPermeability = material.getIntrinsicPermeability()
            self.regionProperties[regionName]["density"] = material.density
            self.regionProperties[regionName]["gravity"] = self.gravity
            self.regionProperties[regionName]["youngModulus"] = youngModulus
            self.regionProperties[regionName]["poissonRatio"] = poissonRatio
            pass
            #
            # We treat here the boundary conditions.
            # We establish a dictionnary independant
            # from the tool to be treated.
            #
        boundarySpecification = {
            "typ": None,
            "Displacement": None,
            "Normalforce": None,
            "material": None,
        }
        boundaryConditions = problem.getBoundaryConditions()
        from vector import V as Vector
        #
        ind = 0
        for boundaryCondition in boundaryConditions:
            #print "dir boundary",dir(boundaryCondition)
            #print "boundary name ",boundaryCondition.name
            #print boundaryCondition.getSupport()
            bodyToConsider = boundaryCondition.boundary
            #print(bodyToConsider)
            #print("entity ", bodyToConsider.getEntity())
            #print(" type " , boundaryCondition.getType())
            #print(" name " , bodyToConsider.getName())
            #print "material ",boundaryCondition.boundary.material
            #raw_input()
            dis = boundaryCondition.getDisplacementValue()
            #print (dis)
            #print (type(dis))

            #raw_input("dis")
            nf = boundaryCondition.getNormalForceValue()
            ok = 0
            for reg in self.regions:
                if reg.getSupport().getName() == bodyToConsider.getName():
                    #print "material ",reg.material;raw_input()
                    ok = 1
                    break
                pass
            if ok == 0:
                raise Warning("Check the definition of regions and boundaries")

            self.boundaryConditions[ind] = {"name": bodyToConsider.getName(),\
                                            "index": bodyToConsider.getEntity(),\
                                            "bodyName": bodyToConsider.getBodyName(),\
                                            "Displacement": dis,\
                                            "Normalforce": nf,\
                                            "Material":reg.material, # boundaryCondition.boundary.material,
                                            "type": boundaryCondition.getType()[0],
                                            "description": boundaryCondition.description
                                           }
            ind += 1
            pass
            #
            # We treat now the initial conditions
            #
        ind = 0
        initialConditions = problem.getInitialConditions()
        if initialConditions != None:
            for initialCondition in initialConditions:
                value = initialCondition.value  # a displacement
                initialConditionName = initialCondition.body.getBodyName()
                ok = 0
                for reg in self.regions:
                    if reg.getSupport().getName() == bodyToConsider.getName():
                        #print "material ",reg.material;raw_input()
                        ok = 1
                        break
                if ok == 0:
                    raise Warning(
                        "Check the definition of regions and boundaries")

                self.initialConditions[ind] = {"name": initialConditionName,\
                                               "Displacement": value,\
                                               "material": reg.getMaterial(),
                                               "index": initialCondition.body.getEntity(),\
                                               "description": initialCondition.description
                                              }
                pass
            pass
            #
            # We treat now the sources
            #
        sourceList = problem.getSources()
        sourceCtrl = 0
        if sourceList:
            from datamodel import Flowrate
            sourceFlowrate = NumericZoneField('source', mesh, ["source"])
            sourceList = toList(sourceList)
            for source in sourceList:

                value = source.getValue()
                if isInstance(value, Flowrate):
                    sourceFlowrate.setZone(source.getZone(),
                                           [value.getValue()])
                    sourceCtrl = 1
                    pass
                pass
            pass

        if sourceCtrl:
            self.sourceField = sourceFlowrate
            pass
            #
            # We treat outputs:
            # outputs -> list of dictionnary
            #
        if self.expectedOutput:
            for eo in self.expectedOutput:
                varnames = ['Pressure']
                eo['varnames'] = varnames
                pass
            pass
コード例 #20
0
ファイル: commonproblem.py プロジェクト: apdimier/Etumos
    def __init__(self, boundary, btype, value, bcdict, porosity = None, description = None):
        """
        Boundary condition initialisation with :
        
        - one boundary

        - a boundary condition type.
          We verify that it's a key of bcdict dictionnary
        - a boundary condition value. Value depend of boundary condition type.
        
        - bcdict : a dictionnary with key = type of boundary condition and value = Possible class of boundary condition value
        
        All boundary conditions satisfy that format. It should enable the lecture of hydraulic, mechanical and chemical-transport boundary conditions.
        
        Exemple: bcdict = {'Flux': [class chemistry.ChemicalState , class PhysicalQuantities.HeadGradient],
                   'Dirichlet': [class chemistry.ChemicalState, class PhysicalQuantities.Head,\
                         class PhysicalQuantities.Displacement, class PhysicalQuantities.NormalForce], 
                   'Neumann': [class chemistry.ChemicalState, class PhysicalQuantities.HeadGradient]}
        
        """   
        self.value = None       
        self.value_species = None
        #print " here we are 1, bcdict ", bcdict
        #print " here we are 2, bcdict ", bcdict.keys()
        #print value
        #raw_input()
        #print("dbg bcdict ",list(bcdict.keys()))
        if isInstance(boundary,[CartesianMesh, Body]):
            pass
        else:
            memberShip(boundary.support,[CartesianMesh, Body])
            pass

        self.boundary = boundary
        if type(btype) != StringType: raise TypeError(" type should be a string ")
        if btype not in list(bcdict.keys()): 
            print("bcdict.keys():",list(bcdict.keys()))
            print("btype : ",btype)
            raise Exception(" check the boundary condition type ")
        self.type = btype
        print("value: ",type(value.__class__.__name__),value.__class__.__name__)
        #print "dbg bcdict ",bcdict.keys()
        #raw_input( "valuefffffffff     fff")
        #if value.__class__.__name__ == 'Head':
        #    print "valueeeee Head",value.__class__.__name__
        #else:
        #    print "valueeeef",value.__class__.__name__
        if isinstance(value,ListType):
            print(" value is of type ListType")
            for val in value:
                if isinstance(val,Displacement):
                    self.value = {"Displacement":val.getValue()}
                    pass
                elif isinstance(val,NormalForce):
                    if self.value != None:
                        self.value["NormalForce"] = val.getValue()
                        pass
                    else:
                        self.value = {"NormalForce":val.getValue()}
                        pass
                elif isinstance(value,Head):
                    valeurs=toList (val)
                    for vale in valeurs:
                        if type(val) is TupleType:
                            checked = val[0] 
                            for i in range(1,len(val)):
                                memberShip(val[i], Species)
                                pass
                            pass
                        else:
                            checked = val
                            pass
                        pass
                    pass

        elif isinstance(value,Displacement):
            print(" value is of type Displacement")
            self.value = {"Displacement":value.getValue()}
            pass
        elif isinstance(value,NormalForce):
            print(" value is of type NormalForce")
            if self.value != None:
                self.value["NormalForce"] = value.getValue()
                pass
            else:
                self.value = {"NormalForce":value.getValue()}
                pass
            pass
            
        elif isinstance(value,Head):
            print(" value is of type Head")
            from datamodel import Species
            value=toList (value)
            for val in value:
                if type(val) is TupleType:
                    checked = val[0] 
                    for i in range(1,len(val)):
                        memberShip(val[i], Species)
                        pass
                    pass
                else:
                    checked = val
                    pass
                for definedType in bcdict:
                    if btype == definedType:
                        memberShip(checked, bcdict[btype])
                        #raw_input("here we are")
                        pass
                    pass
                pass
            if not self.value_species:
                from PhysicalQuantities import PhysicalQuantity
                from species import createList
                print(value)
                self.value_species, self.value_property = createList(value, PhysicalQuantity)
                pass

        if description == None:
            self.description = None
            pass
        else:
            self.description = description
            pass
        return None
コード例 #21
0
ファイル: commonproblem.py プロジェクト: apdimier/Etumos
    def __init__(self, alltype,facetype,quantity, support, name = None, unit=None,
                 timeSpecification=None,where=None,variables=[]):
        """ExpectedOutput initialisation with :
        - all possible expected output quantity
        - expected output quantity which can be define with attribute 'where=face' or 'where = border'
        - an expected output quantity.
        - a support. Support depends on wanted quantity.
          If Flux, support is a tuple (boundary, zone) (possible type for
          boundary or for zone : MedSupport or CartesianMesh)
          If TotalFlux or TotalInflux, support can be MedSupport or CartesianMesh          
          If other quantities, support can be MedSupport, CartesianMesh
        - OPTIONAL :
          --> a name (string). If None given, name is set to quantity
          --> a unit (string)
          --> where (string) : represents expected output localisation. It's only
                               available if quantity is Pressure,, Saturation or DarcyVelocity
                               and support is MedSupport or CartesianMesh and on all elements.
                               Value can be center, face or border
          --> timeSpecification (TimeSpecification) : define times to get expected output
          --> variables (default value = []) : define specific wanted species
        """

        if type(quantity) != StringType:
            raise TypeError(" quantity for CommonExpectedOutput_old should be a string")
        if quantity not in alltype: raise Exception("check the quantity you want to plot ")
        self.quantity = quantity

        partialtype = alltype[:]
        partialtype.remove('Flux')
        partialtype.remove('TotalFlux')
        partialtype.remove('TotalInflux')

        if self.quantity in partialtype:
            supports=toList(support)
            if len(supports) != 1:
                raise Exception(" the support has not the good length")
            verifyClassList(supports, [CartesianMesh])
            for sup in supports:                    
                pass
            pass
        elif (self.quantity == 'Flux'):
            # Support should be TupleType of Boundary, Zone
            if type(support) != TupleType:
                raise TypeError(" support should be a tuple ")
            if (len(support) !=2):
                Message = repr(len(support[sup])) + ' MedSupport given, 2 wanted for a flux expected output'
                raise Message
            fzone = support[1]
            fbound =  support[0]
            memberShip(fbound, MedSupport)
            memberShip(fzone, MedSupport)
            verifyZones(toList(fzone))
            #verifyBoundaries(toList(fbound))
            pass
        elif self.quantity in ['TotalFlux','TotalInflux']:
            supports=toList(support)
            if len(supports) !=1:
                raise Exception(" the support has not the good length ")
            # Support should be Zone
            verifyClassList(supports, [MedSupport, CartesianMesh])
            for sup in supports:                    
                pass
            pass
        self.support = support

        if name:
            if type(name) != StringType:
                raise TypError("name should be a string  within CommonExpectedOutput_old")
            self.name = name
            pass
        else:
            self.name = self.quantity
        #
        if unit: 
            if type(unit)  != StringType:
                raise typeError(" unit should be a string ")
        self.unit = unit

        if timeSpecification:
            from timespecification import TimeSpecification
            memberShip(timeSpecification, TimeSpecification)
            mode=timeSpecification.getSpecification()
            if mode not in ['frequency','period','times']: raise Exception(" check the mode argument in CommonExpectedOutput")
            pass
        self.timespecification = timeSpecification

        self.where=where

        if len(variables):
            from datamodel import  Species
            verifyClassList(variables,Species)
        self.variables=variables
コード例 #22
0
ファイル: hydraulicmodule.py プロジェクト: apdimier/Etumos
    def setData(self, problem,\
                mesh = None,\
                dicobc = None,\
                dicoic = None):

        self.expectedOutput = None
        self.problem = problem
        self.saturation = self.problem.saturation
        if not isinstance(problem, HydraulicProblem):
            raise Exception(
                " the problem must be an hydraulic problem (SaturatedHydraulicProblem or an unSaturatedHydraulicProblem)"
            )
        self.problemName = problem.getName()
        self.regions = problem.getRegions()
        self.mesh = mesh
        #
        # Permeability
        #
        # The permeability is a real for the moment,
        # depending only on parameters to be treated
        # We introduce here a dictionnary,
        # to handle in the near future the "ad hoc" version.
        #
        mediumProperties = {
            "density": None,
            "gravity": None,
            "HydraulicConductivity": None,
            "intrinsicPermeability": None,
            "permeability": None,
            "viscosity": None,
        }
        #
        # regionProperties is a dictionnary. It is made of a list of tuples, each region is associated to a dictionnary,
        # the dictionnary containing the medium region properties.
        #
        self.regionProperties = {}
        #
        self.times = problem.getCalculationTimes()
        #
        if self.times == None:
            self.simulationType = "Steady"
            pass
        else:
            self.simulationType = "Transient"
            pass
        #
        self.boundaryConditions = {}
        #
        self.initialConditions = {}
        #
        # we fill the medium properties dictionnary
        #
        # Density
        self.density = problem.getDensity()
        # Gravity
        self.gravity = problem.getGravity()
        # gravity effect
        #viscosity
        self.viscosity = problem.getViscosity()
        self.intrinsicPermeability = problem.getIntrinsicPermeability()
        #
        for reg in self.regions:
            regionName = reg.support.getBodyName()
            material = reg.getMaterial()
            self.regionProperties[regionName] = mediumProperties

            if not self.problem.saturation:
                permeability = material.getPermeability()
                pass
            else:
                permeability = None
                pass
            hydraulicConductivity = material.getHydraulicConductivity()
            intrinsicPermeability = material.getIntrinsicPermeability()
            self.regionProperties[regionName]["density"] = self.density
            self.regionProperties[regionName]["gravity"] = self.gravity
            self.regionProperties[regionName][
                "HydraulicConductivity"] = hydraulicConductivity
            self.regionProperties[regionName][
                "intrinsicPermeability"] = intrinsicPermeability
            self.regionProperties[regionName]["permeability"] = permeability
            self.regionProperties[regionName]["viscosity"] = self.viscosity
            pass
#        print self.regionProperties
#
# We treat here the boundary conditions.
# We establish a dictionnary independant from
# the tool to be treated.
#
        boundarySpecification = {
            "typ": None,
            "head": None,
            "pressure": None,
            "temperature": None,
            "material": None,
        }
        boundaryconditions = problem.getBoundaryConditions()
        from vector import V as Vector
        #
        #
        #
        ind = 0
        for boundarycondition in boundaryconditions:
            #print ("dbh hydraulicmodule: ", type(boundarycondition), boundarycondition.__class__.__name__)
            #print ("debug hydraulicmodule type value: ", boundarycondition.value, boundarycondition.getValue().__class__.__name__)
            #raw_input("debug "+__name__)
            value = boundarycondition.getValue()
            print("debug type value: ", value.__class__.__name__,
                  boundarycondition.value)
            boundaryName = boundarycondition.getSupport().getBodyName()
            #print boundaryName
            #print " cont ",boundarycondition.boundary.support.body[0]
            #print " cont0 ",type(boundarycondition.boundary.support)
            #print (value)
            #print (boundarycondition.getType())
            #raw_input(__name__)
            #val = value.getValue()
            self.boundaryConditions[ind] = {  #"head":value.getValue(),\
                "typ": boundarycondition.getType(),
                "material": boundarycondition.getRegion().getMaterial(),
                "boundaryName": boundaryName,
                "ind": boundarycondition.getSupport().body[0]
            }
            print(" value type: ", __name__, type(value))
            print(" value: ", __name__, value)
            if type(value) is dict: print(" value dict: ", value.keys())
            #raw_input(" hydraulicmodule debug of value")
            if isinstance(value, Head):
                self.boundaryConditions[ind]["head"] = value.getValue()
            elif type(value) is dict and value.keys() == ["head"]:
                self.boundaryConditions[ind]["head"] = value["head"]
            elif isinstance(value, Pressure):
                self.boundaryConditions[ind]["pressure"] = value.getValue()
            elif type(value) is dict and value.keys() == ["pressure"]:
                self.boundaryConditions[ind]["head"] = value["pressure"]
            elif isinstance(
                    value, (ListType, TupleType, DictType)
            ):  # the only allowed list or tuple is made of Pressure and Temperature
                #print ("hydraulic module, we reach that point: ", value)
                #raw_input(__name__)
                if len(value) == 1:
                    self.boundaryConditions[ind]["pressure"] = value[
                        "pressure"]
                    pass
                elif len(value) == 2:
                    self.boundaryConditions[ind]["pressure"] = value[
                        "pressure"]
                    self.boundaryConditions[ind]["temperature"] = value[
                        "temperature"]
            ind += 1
            pass
#            self.boundaryConditions[boundaryName]["head"]       = value.getValue()
#            self.boundaryConditions[boundaryName]["typ"]        = boundarycondition.getType()
#            self.boundaryConditions[boundaryName]["material"]   = boundarycondition.getRegion().getMaterial()
#            print "D             ",self.boundaryConditions[boundaryName]

#        print self.boundaryConditions
#
# We treat here the initial conditions
#
        initialconditions = problem.getInitialConditions()
        for initialcondition in initialconditions:
            #print ("dbg hydraulicmodule initial condition: ", initialcondition)
            #raw_input("dbg hydraulicmodule initial condition")
            #value = initialcondition.getValue()
            value = initialcondition.value
            initialConditionName = initialcondition.domain.getSupport(
            ).getBodyName()
            #            print " dbg hm ",initialConditionName
            #            print " dbg hm ",type(value)
            #            print " dbg hm ",value
            #            raw_input()
            #self.initialConditions[initialConditionName] = {"head": value,\
            #                                                "material":initialcondition.getRegion().getMaterial(),
            #                                                "ind":initialcondition.getRegion().support.body[0]
            #                                        }
            self.initialConditions[initialConditionName] = {
                "material": initialcondition.getRegion().getMaterial(),
                "ind": initialcondition.getRegion().support.body[0]
            }
            #print (type(value))
            if type(value) is not DictType:
                self.initialConditions[initialConditionName][
                    value.__class__.__name__.lower()] = value
                #print (" value is not dict ", value.__class__.__name__.lower(), value)
            else:
                for val in value.keys():
                    self.initialConditions[initialConditionName][
                        val.lower()] = value[val]
                    pass
                pass
            #raw_input("initialconditions")

            #
            # We treat here the sources
            #

            pass
        sourceList = problem.getSource()
        sourceCtrl = 0
        if sourceList:
            from datamodel import Flowrate
            sourceFlowrate = NumericZoneField('source', mesh, ["source"])
            sourceList = toList(sourceList)
            for source in sourceList:

                value = source.getValue()
                if isInstance(value, Flowrate):
                    sourceFlowrate.setZone(source.getZone(),
                                           [value.getValue()])
                    sourceCtrl = 1
                    pass
                pass
            pass

        if sourceCtrl:
            self.sourceField = sourceFlowrate
            pass
            #
            # We treat outputs: outputs -> list of dictionnary
            #
        if self.expectedOutput:
            for eo in self.expectedOutput:
                varnames = ['Pressure']
                eo['varnames'] = varnames
                pass
            pass
コード例 #23
0
ファイル: mechanicalproblem.py プロジェクト: apdimier/Etumos
    def __init__(self,\
                 name,\
                 regions,\
                 boundaryConditions,\
                 initialConditions = None,\
                 state = None,\
                 simulationType = None,\
                 calculationTimes = None,\
                 gravity = None,\
                 density = None,\
                 sources = None,\
                 outputs = None,\
                 description = None):

        """
        Problem initialisation with :
        
        - name :                name given by the user to the problem

        - saturation:           determines the state to be modelled.
                                Depending on the way the problem is defined, it can be modified.
        - boundary conditions:  
        - initial conditions:   
        - regions:              all regions covering the entire mesh. Regions make up a partition of the mesh
                                
        - gravity:              default None

        - density:              default None

        - sources               default None

        - outputs               default None

        """                                                                                 #
        # name should be a string
        #
        if type(name) != bytes:
            raise TypeError("name should be a string ")
        self.name = name
        #
        # mechanical
        #
        self.problemType = "elasticity"
        #
        # regions treatment
        #
        verifyClassList(regions, Region)
        regions_zones = [region.getZone() for region in regions]
        self.regions = regions
        #
        # gravity treatment
        #
        check = -1
        if gravity:
            memberShip(gravity, Gravity)
            try:
                value = gravity.getValue()
                if type(value) not in [float, int]:
                    raise TypeError(" value should be a float or an int ")
                meshdim = regions_zones[0].getSpaceDimension()
                value = [0.] * meshdim
                value[-1] = 9.81
                if meshdim == 2:
                    value.append(0.)

                gravity = Vector(value)
            except:
                pass
            pass
        else:
            meshdim = regions_zones[0].getSpaceDimension()
            value = [0.] * meshdim
            value[-1] = 9.81
            if meshdim == 2:
                value.append(0.)
                pass
            gravity = Vector(value)
            print(value)
            pass
        #
        self.gravity = gravity
        #
        # density treatment
        #
        if density:
            if type(density) == FloatType:
                density = Density(density, 'kg/m**3')
                pass
            memberShip(density, Density)
            check = 2 * check
            pass
        self.solidDensity = density
        #
        # times definition
        #
        self.simulationType = simulationType
        #        #raw_input("calculation times ")
        if calculationTimes:
            self.calculationTimes = calculationTimes
            self.simulationType = "Transient"
            pass
        else:
            self.calculationTimes = None
            self.simulationType = "Steady"
            pass

        self.steadyState = 1
        if self.calculationTimes != None:
            if type(calculationTimes) != list:
                raise typeError(" calculationTimes should be a list ")
            CalculationTimes = toFloatList(self.calculationTimes)
            #
            for item in CalculationTimes:
                if type(item) != float:
                    raise TypeError(" item should be a float ")
                pass
            self.calculationTimes = sorted(CalculationTimes)
            #            print self.calculationTimes;#raw_input(" within the loop, calculation times are printed here")
            #
            # The simulation is transient
            #
            self.steadyState = 0
            pass
            #
            # boundaryConditions treatment
            #
        self.defaultBC = None
        boundaryConditions = toList(boundaryConditions)
        print(" problem type ", self.problemType)
        print(dir(boundaryConditions[0]))
        #
        # boundaryConditions treatment
        #
        boundaries = []
        for boundaryElement in boundaryConditions:
            boundary = toList(boundaryElement.getBoundary())
            for bound in boundary:
                boundaries.append(bound)
                pass
            pass
        if self.defaultBC:
            if not self.density:
                self.density = Density(1.)
                pass
            if not self.gravity:
                mesh_dim = regions[0].getZone().getMesh().getSpaceDimension()
                if mesh_dim == 2:
                    self.gravity = Gravity(Vector(0., 1.))
                    pass
                elif mesh_dim == 3:
                    self.gravity = Gravity(Vector(0., 0., 1.))
                    pass
                else:
                    raise Exception('Dimension ????')

                pass
            pass
        self.boundaryConditions = boundaryConditions
        #
        # initialConditions treatment
        #
        self.initialConditions = initialConditions
        #
        # sources treatment
        #
        if sources: verifyClassList(sources, Source)
        self.sources = sources
        #
        # outputs treatment
        #
        if outputs:
            outputs1 = toList(outputs)
            verifyClassList(outputs1, _dicoproblem[type].ExpectedOutput)

            if not hasattr(self, 'output_names'):
                self.output_names = []
                pass
            for output in outputs1:
                if output.getName() in self.output_names:
                    msg = '\n\nDifferent outputs should not share the same name.\n'
                    msg += 'End of the hydraulic problem run.\n\n'
                    raise Exception(msg)
                self.output_names.append(output.getName())
                pass
        #
        self.outputs = outputs
        #
        return None
コード例 #24
0
ファイル: generictools.py プロジェクト: apdimier/Etumos
def memberShip(x, liste, message=None):
    if not isinstance(x, tuple(toList(liste))):
        if message == None:
            message = "of " + x.__class__.__name__
        raise Exception("check instantiation %s %s" % (message, x))
コード例 #25
0
    def __init__(self,
                 boundary,
                 btype,
                 value,
                 bcdict,
                 porosity=None,
                 description=None):
        """
        Boundary condition initialisation with :
        
        - one boundary

        - a boundary condition type.
          We verify that it's a key of bcdict dictionnary
        - a boundary condition value. Value depend of boundary condition type.
        
        - bcdict : a dictionnary with key = type of boundary condition and value = Possible class of boundary condition value: 
        
            As an example, we can have for bcdict.keys() : ['Flux', 'Dirichlet', 'Neumann']
        
        All boundary conditions satisfy that format. It should enable the lecture of hydraulic, mechanical and chemical-transport boundary conditions.
        
        Exemple: bcdict = {'Flux': [class chemistry.ChemicalState , class PhysicalQuantities.HeadGradient],
                   'Dirichlet': [class chemistry.ChemicalState, class PhysicalQuantities.Head, class PhysicalQuantities.Pressure,\
                         class PhysicalQuantities.Displacement, class PhysicalQuantities.NormalForce], 
                   'Neumann': [class chemistry.ChemicalState, class PhysicalQuantities.HeadGradient]}
        
        """
        self.value = None
        self.value_species = None
        #print (" here we are 1, bcdict ", bcdict)
        #print (" here we are 2, bcdict ", bcdict.keys())
        #print value
        #raw_input()
        #print("dbg bcdict ",list(bcdict.keys()))
        if isInstance(boundary, [CartesianMesh, Body]):
            pass
        else:
            memberShip(boundary.support, [CartesianMesh, Body])
            pass
        self.boundary = boundary
        if type(btype) != StringType:
            raise TypeError(" type should be a string ")
        if btype not in list(bcdict.keys()):
            print("bcdict.keys() are:", list(bcdict.keys()))
            print("and btype %s is not in bdict: " % (btype))
            raise Exception(" check the boundary condition type ")
        self.type = btype
        print("debug commonproblem CommonBoundaryCondition value: ",
              type(value.__class__.__name__), value.__class__.__name__)
        #print "dbg bcdict ",bcdict.keys()
        #raw_input( "valuefffffffff     fff")
        #if value.__class__.__name__ == 'Head':
        #    print "valueeeee Head",value.__class__.__name__
        #else:
        #    print "valueeeef",value.__class__.__name__
        if isinstance(value, (ListType, TupleType)):
            #print(" debug commonproblem CommonBoundaryCondition, value is of type ListType", type(value), value)
            for val in value:
                print(
                    "debug commonproblem CommonBoundaryCondition, debug val: ",
                    val)
                if isinstance(val, Displacement):
                    self.value = {"Displacement": val.getValue()}
                    pass
                elif isinstance(val, NormalForce):
                    if self.value != None:
                        self.value["NormalForce"] = val.getValue()
                        pass
                    else:
                        self.value = {"NormalForce": val.getValue()}
                        pass
                elif isinstance(val, (Head, Pressure)):
                    valeurs = toList(val)
                    for vale in valeurs:
                        if type(val) is TupleType:
                            checked = val[0]
                            for i in range(1, len(val)):
                                memberShip(val[i], Species)
                                pass
                            pass
                        else:
                            checked = val
                            pass
                        pass
                    print("dbg commonproblem %s\n" %
                          (val.__class__.__name__.lower()))
                    if self.value != None:
                        self.value[
                            val.__class__.__name__.lower()] = val.getValue()
                    else:
                        self.value = {
                            val.__class__.__name__.lower(): val.getValue()
                        }
                    pass
                elif isinstance(val, Temperature):
                    if self.value != None:
                        self.value[
                            val.__class__.__name__.lower()] = val.getValue()
                    else:
                        self.value = {
                            val.__class__.__name__.lower(): val.getValue()
                        }
                    pass
                pass
            print("debug commonproblem CommonBoundaryCondition: ", self.value)
            pass
        elif isinstance(value, Displacement):
            #print("debug commonproblem  value is of type Displacement")
            self.value = {"Displacement": value.getValue()}
            pass
        elif isinstance(value, NormalForce):
            #print("debug commonproblem  value is of type NormalForce")
            if self.value != None:
                self.value["NormalForce"] = value.getValue()
                pass
            else:
                self.value = {"NormalForce": value.getValue()}
                pass
            pass

        elif isinstance(value, (Head, Pressure)):
            print("debug commonproblem  value is of type Head or Pressure")
            from datamodel import Species
            value = toList(value)
            #print("debug commonproblem  value is of type Head or Pressure: ", value)
            #print("debug commonproblem  value is of type Head or Pressure: ", bcdict)
            for val in value:
                if type(val) is TupleType:
                    checked = val[0]
                    for i in range(1, len(val)):
                        memberShip(val[i], Species)
                        pass
                    pass
                else:
                    checked = val
                    pass
                for definedType in bcdict:
                    if btype == definedType:
                        memberShip(checked, bcdict[btype])
                        #raw_input("here we are")
                        pass
                    pass
                pass
            if not self.value_species:
                from PhysicalQuantities import PhysicalQuantity
                from species import createList
                print(value)
                self.value_species, self.value_property = createList(
                    value, PhysicalQuantity)
                pass
            self.value = {
                value[0].__class__.__name__.lower(): value[0].getValue()
            }
        #print(" dbg commonproblem: valeur de self.value",self.value)
        #raw_input("dbg commonproblem: CommonBoundaryCondition")
        if description == None:
            self.description = None
            pass
        else:
            self.description = description
            pass
        return None
コード例 #26
0
    def __init__(self, zone, value, some_classes, some_solid_classes=None):
        """
        Initial condition initialisation with
        - one or several zones 
        - a value instance of a class defined in some_classes
                           or a list of couple (Value,Species)
                           or a list with a defaut value and couples (Value,Species) 
                           for example [c,(c1,species1),(c2,species2)]
        - some_classes : list of possible classes of value (soluble classes)
        - some_solid_classes : list of possible classes of value (solid classes)
        """
        zones = toList(zone)
        #verifyZones(zones)
        self.zone = zone
        if some_solid_classes:
            all_classes = some_classes + some_solid_classes
            pass
        else:
            all_classes = some_classes
            pass

        val_solub = []
        val_solid = []
        self.value_species = []
        self.value_property = []
        self.value_solid_species = []
        self.value_solid_property = []
        value = toList(value)
        for val in value:
            solubOK = 0
            if type(val) is TupleType:
                from datamodel import Species
                memberShip(val[0], all_classes)
                memberShip(val[1], Species)
                for sc in some_classes:
                    if isInstance(val[0], sc):
                        val_solub.append(val)
                        solub0K = 1
                        break
                    pass
                if some_solid_classes and not solubOK:
                    for sc in some_solid_classes:
                        if isInstance(val[0], sc):
                            val_solid.append(val)
                            break
                        pass
                    pass
                pass
            else:
                memberShip(val, all_classes)
                for sc in some_classes:
                    if isInstance(val, sc):
                        val_solub.append(val)
                        solub0K = 1
                        break
                if some_solid_classes and not solubOK:
                    for sc in some_solid_classes:
                        if isInstance(val, sc):
                            val_solid.append(val)
                            break
                    pass
                pass
            pass

        if val_solub:
            from datamodel import createList
            from datamodel import PhysicalQuantity
            self.value_species, self.value_property = createList(
                val_solub, PhysicalQuantity)
            pass
        if val_solid:
            from datamodel import createList
            from datamodel import PhysicalQuantity
            self.value_solid_species, self.value_solid_property = createList(
                val_solid, PhysicalQuantity)
            pass
        return
コード例 #27
0
    def __init__(self,\
                 name,\
                 regions,\
                 boundaryConditions,\
                 initialConditions,\
                 calculationTimes,\
                 chemistryDB,\
                 darcyVelocity = None,                                                      # darcy velocity
                 speciesBaseAddenda = None,\
                 kineticLaws =  None,\
                 timeUnit = None, \
                 activityLaw = None,\
                 porosityState = None,\
                 headVPorosity = None,
                 state = None,\
                 simulationType = None,\
                 gravity = None,\
                 density = None,\
                 diffusionLaw = None,\
                 permeabilityLaw = None,\
                 sources = None,\
                 outputs = None,\
                 userProcessing = None,\
                 userFunctionList = None,\
                 variablePorosity = None,\
                 variableElasticity = None,\
                 temperature = None,\
                 description = None):
                 
        """
        Problem initialisation with :
        
        - name :                name given by the user to the problem

        - saturation:           determines the state to be modelled.
                                Depending on the way the problem is defined, it can be modified.
        - boundary conditions:  
        - initial conditions:   
        - regions:              all regions covering the entire mesh. Regions make up a partition of the mesh
                                
        - gravity:              default None

        - density:              default None

        - sources               default None

        - outputs               default None

        """                                                                                 #
                                                                                            # name should be a string
                                                                                            #
        if type(name) != bytes:
            raise TypeError("name should be a string ")
        self.name = name
                                                                                            #
                                                                                            # Elsasticy modulus variation
                                                                                            #
        self.variableElasticity = variableElasticity                                                                                  
                                                                                            #
                                                                                            #
                                                                                            #
        self.mpiEnv = None
        # simulation times to be recovered
        if type(calculationTimes) != list: raise TypeError("  simulationTimes must be a list of times ")

        i = 0
        for item in calculationTimes:            
            if type(item) not in [float,int]:
                raise TypeError("  calculationTimes must be a list of times ")
            calculationTimes[i] = calculationTimes[i]
            i += 1
            pass

        previous = calculationTimes[0]            
        for item in calculationTimes:
            if item < 0.:
                raise Exception('Error : Negative calculation time unexpected')
            if item < previous:
                raise Exception('Error : Decreasing calculation time unexpected')
                previous = item
            self.calculationTimes = calculationTimes
            pass
                                                                                            #
                                                                                            # we dont' consider a wellbore
                                                                                            #
        self.wellbore = False                                                                                
                                                                                            #
                                                                                            # species Addenda
                                                                                            #
        if speciesBaseAddenda not in [None,[]]:
            verifyClassList(speciesBaseAddenda, Species)
            self.speciesBaseAddenda = speciesBaseAddenda
            pass
        else:
           self.speciesBaseAddenda = []
           pass                                                                                  
        if type(name) != bytes:
            raise TypeError("name should be a string ")
        self.name = name
                                                                                            #
                                                                                            # mechanical
                                                                                            #
        self.problemType = "thmc"
                                                                                            #
                                                                                            # Darcy and seepage Velocity treatment :
                                                                                            #
        if isinstance(darcyVelocity,Velocity):
            self.darcyVelocity = darcyVelocity 
#        elif isinstance(seepageVelocity,Velocity):
#            self.darcyVelocity = seepageVelocity
#            warnings.warn("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\
#                           seepage velocity is not handled and is equivalent to Darcy velocity for Elmer\n\
#                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")         
        elif type(darcyVelocity) == bytes:
            if darcyVelocity.lower() == "read":
                                                                                            #
                                                                                            # The Darcy velocity will be read from
                                                                                            # the velocity.ep file
                                                                                            #
                self.darcyVelocity = "read"
                pass
            elif darcyVelocity.lower() == "computed":                                       # the Darcy velocity is transient
                self.darcyVelocity = "computed"
                pass
        else:
            self.darcyVelocity = None
            pass
                                                                                            #
                                                                                            # data Base
                                                                                            #
        if type(chemistryDB) != bytes: raise TypeError("The chemistryDB argument of the THMC Problem must be a string ")
        self.chemistryDB = chemistryDB
                                                                                            #
                                                                                            # regions treatment
                                                                                            #
        verifyClassList(regions, Region)
        regions_zones = [region.getZone() for region in regions]
        self.regions = regions
                                                                                            #
                                                                                            # gravity treatment
                                                                                            #
        check = -1
        if gravity:
            memberShip(gravity, Gravity)
            try:
                value=gravity.getValue()
                if type(value) not in [float, int]:
                    raise TypeError(" value should be a float or an int ")
                meshdim = regions_zones[0].getSpaceDimension()
                value=[0.]*meshdim
                value[-1] = 9.81
                if meshdim == 2:
                    value.append(0.)

                gravity=Vector(value)
            except:
                pass
            pass
        else:            
            meshdim = regions_zones[0].getSpaceDimension()
            value=[0.]*meshdim
            value[-1] = 9.81
            if meshdim == 2: value.append(0.)
            gravity=Vector(value)
            print(value)
            pass
        #
        self.gravity = gravity
                                                                                            #
                                                                                            # activity law
                                                                                            #
        if activityLaw:
            if not isinstance(activityLaw,ActivityLaw):
                raise Exception(" the activity law instantiation must be checked")
##        else:
##            self.activityLaw = TruncatedDavies()
            pass
        self.activityLaw = activityLaw
                                                                                            #
                                                                                            # density treatment
                                                                                            #
        if density:
            if type(density) in [int,float]:
               density = Density(density, 'kg/m**3')
            memberShip(density, Density)
            check = 2*check
            pass
        self.solidDensity = density
                                                                                            #
                                                                                            # variable porosity: diffusion law
                                                                                            #
        if diffusionLaw:
            if not isinstance(diffusionLaw,EffectiveDiffusionLaw):
                raise Exceptio(" the diffusion law instanciation must be checked")
            pass
        self.diffusionLaw = diffusionLaw
        self.permeabilityLaw = permeabilityLaw

        if headVPorosity!= None:
            if headVPorosity not in ["constant","variable","constante"]:
                self.headVPorosity = "constant"
                pass
            else:
                self.headVPorosity = headVPorosity
                pass
        else:
            self.headVPorosity = "constant"
            pass
                                                                                            #
                                                                                            # user processing set up
                                                                                            #
        if userProcessing and type(userFunctionList) == types.ListType:
            self.userProcessing = True
            self.processingList = userFunctionList
            for processingFunction in range(len(self.processingList)):
                self.processingList[processingFunction]+="(self)"
                print(self.processingList[processingFunction])
                pass
            pass

        else:
            self.userProcessing = False
            self.processingList = None
            pass
                                                                                            #
                                                                                            # Kinetics Laws
                                                                                            #
        if kineticLaws != None :
            verifyClassList(kineticLaws, KineticLaw)
            self.kineticLaws = kineticLaws
            pass
        else :
            self.kineticLaws = None
            pass
                                                                                            #        
                                                                                            # times definition
                                                                                            #        
        self.simulationType = simulationType
#        #raw_input("calculation times ")
        if calculationTimes:
            self.calculationTimes = calculationTimes
            self.simulationType = "Transient"
        else:
            self.calculationTimes = None
            self.simulationType = "Steady"

        self.steadyState = 1 
        if self.calculationTimes!= None:
            if type(calculationTimes) != list:
                raise typeError(" calculationTimes should be a list ")
            CalculationTimes=toFloatList( self.calculationTimes)
            #
            for item in CalculationTimes:
                if type(item) != float:
                    raise TypeError(" item should be a float ")
            self.calculationTimes = sorted( CalculationTimes)
                                                #
                                                                                            # The simulation is transient
                                                                                            #
            self.steadyState = 0
            pass
                                                                                            #        
                                                                                            # boundaryConditions treatment
                                                                                            #        
        self.defaultBC = None
        boundaryConditions = toList(boundaryConditions)
        print(" problem type ",self.problemType)
        print(dir(boundaryConditions[0])) 
                                                                                            #        
                                                                                            # boundaryConditions treatment
                                                                                            #        
        boundaries = []
        for boundaryElement in boundaryConditions:
            boundary = toList(boundaryElement.getBoundary())
            for bound in boundary: boundaries.append(bound)
            pass
        if self.defaultBC:
            if not self.density:
                self.density = Density(1.)
                pass
            if not self.gravity:
                mesh_dim=regions[0].getZone().getMesh().getSpaceDimension()
                if mesh_dim==2: self.gravity=Gravity(Vector(0.,1.))
                elif mesh_dim==3: self.gravity=Gravity(Vector(0.,0.,1.))
                else: raise Warning('Dimension ????')
                pass
            pass        
        self.boundaryConditions = boundaryConditions
                                                                                            #
                                                                                            # initialConditions treatment
                                                                                            #        
        self.initialConditions = initialConditions
                                                                                            #
                                                                                            # variable porosity
                                                                                            #
        if porosityState:
            if type(porosityState) != bytes:
                raise TypeError(" the porosityState argument of the ChemicalTransportProblem must be a string ")
            porosityState = porosityState.lower()
            if (porosityState == 'constant') or (porosityState == 'variable'):
                self.porosityState = porosityState
                pass
            elif porosityState in ['steady',"cst"]:
                self.porosityState = 'constant'
            elif porosityState in ['transient',"var"]:
                self.porosityState = 'constant'
            else:
##                self.porosityState = None
                mess = "porosityState badly defined (default : 'constant', else 'variable')"
                raise mess
            pass
        else:
            self.porosityState = 'constant'
            pass
                                                                                            #
                                                                                            # sources treatment
                                                                                            #
        if sources != None:
            verifyClassList(sources, Source)
            self.sources = sources
            pass
        else : 
            self.sources = None
            pass
                                                                                            #
                                                                                            # temperature
                                                                                            #
        if temperature == None:
            self.temperature = "constant"
            pass
        else:
            self.temperature = temperature
            pass
                                                                                            #
                                                                                            # time unit
                                                                                            #
        if timeUnit:
            if type(timeUnit) != bytes:
                raise TypeError(" the time unit argument of the ChemicalTransportProblem must be a string ")
            pass
        self.timeUnit = timeUnit
                                                                                            #
                                                                                            # outputs treatment
                                                                                            #
        if outputs:
            outputs1 = toList(outputs)
            verifyClassList(outputs1, ExpectedOutput)

            if not hasattr(self,'output_names'):
                self.output_names=[]
                pass
            for output in outputs1:
                if output.getName() in self.output_names:
                    msg = '\n\nDifferent outputs should not share the same name.\n'
                    msg+= 'End of the hydraulic problem run.\n\n'
                    raise msg
                self.output_names.append(output.getName())
                pass
        #
        self.outputs = outputs
        #
        return None
コード例 #28
0
ファイル: commonproblem.py プロジェクト: apdimier/Etumos
    def __init__(self, alltype, facetype, quantity, support = None,
                 name = None, unit = None, timeSpecification = None,
                 where = None, unknown = [],save = 'memory',chemical = 0):
        if type(quantity) != StringType:
            raise TypeError(" the quantity must be a string ")
        alltypeupper = [q.upper() for q in alltype]
        #print "alltypeupper",alltypeupper
        quantityupper = quantity.upper()
        if quantityupper not in alltypeupper: raise Exception("the quantity "+quantityupper+" must be checked in Output")
        self.quantity = quantity

        mecanic = ( chemical == 2)
        chemical = (chemical == 1)

        hydrau_transport_type = ['HEAD','PRESSURE','DARCYVELOCITY','SATURATION','CONCENTRATION','SOLIDCONCENTRATION']

        if quantityupper in hydrau_transport_type and not chemical:
            supports=toList(support)
            if len(supports) != 1:
                raise Exception("The support hans not the good length")
            # Support should be Point or Zone
            verifyClassList(supports, [CartesianMesh])
            pass
        elif (quantityupper == 'FLUX'):
            # Support should be TupleType of Boundary, Zone
            if type(support) != TupleType:
                raise TypeError(" support should be a tuple ")
            if (len(support) !=2):
                raise Exception("support must have a length of 2")
            fzone = support[1]
            fbound =  support[0]
            fbounds = toList(fbound)
            entity = fbounds[0].getMesh().getBoundariesEntity()
            memberShip(fbound, MedSupport)
            memberShip(fzone, MedSupport)
            verifyZones(toList(fzone))
            # verifyBoundaries verify now that bounds are borders. We use verifySupports in place
            verifySupports(fbounds,entity)
            pass
        elif quantityupper in ['TOTALFLUX','TOTALINFLUX']:
            supports=toList(support)
            if len(supports) != 1:
                raise Exception("the support has not the good length")
            # Support should be Zone
            verifyClassList(supports, [CartesianMesh])
            pass
        else:
            if support and chemical:
                # chemical transport quantity : support is optionnal
                memberShip(support, [CartesianMesh])
                pass
            elif mecanic:
                # mecanic quantity :    support class is verified by XData      
                pass
            pass
        self.support = support

        if name:
            if type(name) != StringType:
                raise TypeError("the name of a CommonExpectedOutput must be a string")
            self.name = name
            pass
        else:
            self.name = self.quantity
            pass
        #
        if unit:
            if type(unit) != StringType:
                raise TypeError(" unit should be a string ")
        self.unit = unit

        if timeSpecification:
            from timespecification import TimeSpecification
            memberShip(timeSpecification, TimeSpecification)
            mode=timeSpecification.getSpecification()
            if mode not in ['frequency','period','times']: raise Exception(" check the mode argument in CommonExpectedOutput")
            pass
        self.timeSpecification = timeSpecification

        self.where=where

        if save:
            if save not in ['memory','file']: raise Exception(" check the save argument in CommonExpectedOutput")
            pass
        self.save = save

        if unknown:
            if chemical:
                if type(unknown) is ListType:
                    for unbekannte in unknown:
                        if type(unbekannte) != StringType:
                            raise TypeError(" unknown should be a string ")
                            pass
                        pass
                    pass
                else:
                    if type(unknown) != StringType:
                        raise TypeError(" the unknown must be a string ")
                    pass
                pass
            elif mecanic:
                unknown=toList(unknown)
                for u in unknown:
                    if type(u) != StringType:
                        raise TypeError(" u should be a string ")
                    pass
                pass
            else:
                from datamodel import  Species
                verifyClassList(unknown,Species)
                pass
            pass
        self.unknown=unknown
コード例 #29
0
ファイル: hydraulicmodule.py プロジェクト: apdimier/Etumos
    def setData(self, problem,\
                mesh = None,\
                dicobc = None,\
                dicoic = None):

        self.expectedOutput = None
        self.problem = problem
        self.saturation = self.problem.saturation
        if not isinstance(problem, HydraulicProblem):
            raise Exception(" the problem must be an hydraulic problem (SaturatedHydraulicProblem or an unSaturatedHydraulicProblem)")
        self.problemName = problem.getName()
        self.regions = problem.getRegions()
        self.mesh = mesh
                                                                                            #
                                                                                            # Permeability
                                                                                            #
                                                                                            # The permeability is a real for the moment,
                                                                                            # depending only on parameters to be treated
                                                                                            # We introduce here a dictionnary,
                                                                                            # to handle in the near future the "ad hoc" version.
                                                                                            #
        mediumProperties = {
                           "density"                    : None,
                           "gravity"                    : None,
                           "HydraulicConductivity"      : None,
                           "intrinsicPermeability"      : None, 
                           "permeability"               : None, 
                           "viscosity"                  : None,
                           }
        #
        # regionProperties is a dictionnary. It is made of a list of tuples, each region is associated to a dictionnary,
        # the dictionnary containing the medium region properties.
        #                        
        self.regionProperties   = {}
        #
        self.times = problem.getCalculationTimes()
        #
        if self.times == None:
            self.simulationType = "Steady"
            pass
        else:
            self.simulationType = "Transient"
            pass
        #                        
        self.boundaryConditions = {}
        #                        
        self.initialConditions  = {}
                                                                                            #
                                                                                            # we fill the medium properties dictionnary
                                                                                            #
                                                                                            # Density
        self.density = problem.getDensity()
                                                                                            # Gravity
        self.gravity = problem.getGravity()
        # gravity effect
                                                                                            #viscosity
        self.viscosity = problem.getViscosity()
        #
        for reg in self.regions:
            regionName = reg.support.getBodyName()
            material = reg.getMaterial()
            self.regionProperties[regionName] = mediumProperties

            if not self.problem.saturation:
                permeability = material.getPermeability()
                pass
            else:
                permeability = None
                pass
            hydraulicConductivity = material.getHydraulicConductivity()
            intrinsicPermeability = material.getIntrinsicPermeability()
            self.regionProperties[regionName]["density"]                = self.density
            self.regionProperties[regionName]["gravity"]                = self.gravity
            self.regionProperties[regionName]["HydraulicConductivity"]  = hydraulicConductivity
            self.regionProperties[regionName]["intrinsicPermeability"]  = intrinsicPermeability
            self.regionProperties[regionName]["permeability"]           = permeability
            self.regionProperties[regionName]["viscosity"]              = self.viscosity
#        print self.regionProperties
                                                                                            #
                                                                                            # We treat here the boundary conditions.
                                                                                            # We establish a dictionnary independant from
                                                                                            # the tool to be treated.
                                                                                            #
        boundarySpecification = {
                                "typ"           : None,
                                "head"          : None,
                                "material"      : None,
                                }
        boundaryconditions = problem.getBoundaryConditions()
        from vector import V as Vector
        #
        #
        #
        ind = 0
        for boundarycondition in boundaryconditions:
            #print type(boundarycondition),boundarycondition.__class__.__name__
            #print "debug type value ",boundarycondition.getValue().__class__.__name__
            value = boundarycondition.getValue()
            #print "debug type value ",value.__class__.__name__
            boundaryName = boundarycondition.getSupport().getBodyName()
##            print boundaryName
#            print " cont ",boundarycondition.boundary.support.body[0]
#            print " cont0 ",type(boundarycondition.boundary.support)
#            print type(value)
#            print value.getValue()
#            print boundarycondition.getType()
#            raw_input(" hydraulic module")
            val = value.getValue()
            self.boundaryConditions[ind] = {"head":value.getValue(),\
                                            "typ":boundarycondition.getType(),
                                            "material":boundarycondition.getRegion().getMaterial(),
                                            "boundaryName": boundaryName,
                                            "ind":boundarycondition.getSupport().body[0]
                                           }
            ind+=1
#            self.boundaryConditions[boundaryName]["head"]       = value.getValue()
#            self.boundaryConditions[boundaryName]["typ"]        = boundarycondition.getType()
#            self.boundaryConditions[boundaryName]["material"]   = boundarycondition.getRegion().getMaterial()
#            print "D             ",self.boundaryConditions[boundaryName]
            
#        print self.boundaryConditions
                                                                                            #
                                                                                            # We treat here the initial conditions
                                                                                            #
        initialconditions = problem.getInitialConditions()
        for initialcondition in initialconditions:
#            print " dbg hm ",initialcondition
#            print " dbg hm ",initialcondition.domain.getSupport()
            value = initialcondition.getValue()
            initialConditionName = initialcondition.domain.getSupport().getBodyName()
#            print " dbg hm ",initialConditionName
#            print " dbg hm ",type(value)
#            print " dbg hm ",value
#            raw_input()
            self.initialConditions[initialConditionName] = {   "head":value,\
                                                        "material":initialcondition.getRegion().getMaterial(),
                                                        "ind":initialcondition.getRegion().support.body[0]
                                                    }

                                                                                            #
                                                                                            # We treat here the sources
                                                                                            #

            pass                                                                             
        sourceList = problem.getSource()
        sourceCtrl = 0
        if sourceList:
            from datamodel import Flowrate
            sourceFlowrate = NumericZoneField('source', mesh, ["source"])
            sourceList = toList(sourceList)
            for source in sourceList:

                value = source.getValue()
                if isInstance(value,Flowrate):
                    sourceFlowrate.setZone(source.getZone(), [value.getValue()])
                    sourceCtrl = 1
                    pass
                pass
            pass

        if sourceCtrl:
            self.sourceField = sourceFlowrate
            pass
                                                                                            #        
                                                                                            # We treat outputs: outputs -> list of dictionnary
                                                                                            #
        if self.expectedOutput:
            for eo in self.expectedOutput:
                varnames=['Pressure']
                eo['varnames'] = varnames
                pass
            pass
コード例 #30
0
ファイル: commonproblem.py プロジェクト: apdimier/Etumos
 def __init__(self, zone, value,some_classes):
     """Zone condition initialisation"""
     self.value_species, self.value_property = _associateZoneValue(zone, value,some_classes)
     verifyZones(toList(zone))
     self.zone = zone
     return
コード例 #31
0
    def __init__(self,
                 alltype,
                 facetype,
                 quantity,
                 support=None,
                 name=None,
                 unit=None,
                 timeSpecification=None,
                 where=None,
                 unknown=[],
                 save='memory',
                 chemical=0):
        if type(quantity) != StringType:
            raise TypeError(" the quantity must be a string ")
        alltypeupper = [q.upper() for q in alltype]
        #print "alltypeupper",alltypeupper
        quantityupper = quantity.upper()
        if quantityupper not in alltypeupper:
            raise Exception("the quantity " + quantityupper +
                            " must be checked in Output")
        self.quantity = quantity

        mecanic = (chemical == 2)
        chemical = (chemical == 1)

        hydrau_transport_type = [
            'HEAD', 'PRESSURE', 'DARCYVELOCITY', 'SATURATION', 'CONCENTRATION',
            'SOLIDCONCENTRATION'
        ]

        if quantityupper in hydrau_transport_type and not chemical:
            supports = toList(support)
            if len(supports) != 1:
                raise Exception("The support hans not the good length")
            # Support should be Point or Zone
            verifyClassList(supports, [CartesianMesh])
            pass
        elif (quantityupper == 'FLUX'):
            # Support should be TupleType of Boundary, Zone
            if type(support) != TupleType:
                raise TypeError(" support should be a tuple ")
            if (len(support) != 2):
                raise Exception("support must have a length of 2")
            fzone = support[1]
            fbound = support[0]
            fbounds = toList(fbound)
            entity = fbounds[0].getMesh().getBoundariesEntity()
            memberShip(fbound, MedSupport)
            memberShip(fzone, MedSupport)
            verifyZones(toList(fzone))
            # verifyBoundaries verify now that bounds are borders. We use verifySupports in place
            verifySupports(fbounds, entity)
            pass
        elif quantityupper in ['TOTALFLUX', 'TOTALINFLUX']:
            supports = toList(support)
            if len(supports) != 1:
                raise Exception("the support has not the good length")
            # Support should be Zone
            verifyClassList(supports, [CartesianMesh])
            pass
        else:
            if support and chemical:
                # chemical transport quantity : support is optionnal
                memberShip(support, [CartesianMesh])
                pass
            elif mecanic:
                # mecanic quantity :    support class is verified by XData
                pass
            pass
        self.support = support

        if name:
            if type(name) != StringType:
                raise TypeError(
                    "the name of a CommonExpectedOutput must be a string")
            self.name = name
            pass
        else:
            self.name = self.quantity
            pass
        #
        if unit:
            if type(unit) != StringType:
                raise TypeError(" unit should be a string ")
        self.unit = unit

        if timeSpecification:
            from timespecification import TimeSpecification
            memberShip(timeSpecification, TimeSpecification)
            mode = timeSpecification.getSpecification()
            if mode not in ['frequency', 'period', 'times']:
                raise Exception(
                    " check the mode argument in CommonExpectedOutput")
            pass
        self.timeSpecification = timeSpecification

        self.where = where

        if save:
            if save not in ['memory', 'file']:
                raise Exception(
                    " check the save argument in CommonExpectedOutput")
            pass
        self.save = save

        if unknown:
            if chemical:
                if type(unknown) is ListType:
                    for unbekannte in unknown:
                        if type(unbekannte) != StringType:
                            raise TypeError(" unknown should be a string ")
                            pass
                        pass
                    pass
                else:
                    if type(unknown) != StringType:
                        raise TypeError(" the unknown must be a string ")
                    pass
                pass
            elif mecanic:
                unknown = toList(unknown)
                for u in unknown:
                    if type(u) != StringType:
                        raise TypeError(" u should be a string ")
                    pass
                pass
            else:
                from datamodel import Species
                verifyClassList(unknown, Species)
                pass
            pass
        self.unknown = unknown
コード例 #32
0
ファイル: commonproblem.py プロジェクト: apdimier/Etumos
    def __init__(self, zone, value,some_classes,some_solid_classes=None):
        """
        Initial condition initialisation with
        - one or several zones 
        - a value instance of a class defined in some_classes
                           or a list of couple (Value,Species)
                           or a list with a defaut value and couples (Value,Species) 
                           for example [c,(c1,species1),(c2,species2)]
        - some_classes : list of possible classes of value (soluble classes)
        - some_solid_classes : list of possible classes of value (solid classes)
        """
        zones=toList(zone)
        #verifyZones(zones)
        self.zone = zone
        if some_solid_classes:
            all_classes = some_classes + some_solid_classes
            pass
        else:
            all_classes = some_classes
            pass

        val_solub=[]
        val_solid=[]     
        self.value_species=[] 
        self.value_property=[]
        self.value_solid_species=[]
        self.value_solid_property=[]
        value = toList(value)
        for val in value:
            solubOK = 0
            if type(val) is TupleType:
                from datamodel import  Species
                memberShip(val[0], all_classes)
                memberShip(val[1], Species)
                for sc in some_classes:
                    if isInstance(val[0], sc):
                        val_solub.append(val)
                        solub0K = 1
                        break
                    pass            
                if some_solid_classes and not solubOK:
                    for sc in some_solid_classes:
                        if isInstance(val[0], sc):
                            val_solid.append(val)
                            break
                        pass
                    pass
                pass
            else:
                memberShip(val, all_classes)
                for sc in some_classes:
                    if isInstance(val, sc):
                        val_solub.append(val)
                        solub0K = 1
                        break            
                if some_solid_classes and not solubOK:
                    for sc in some_solid_classes:
                        if isInstance(val, sc):
                            val_solid.append(val)
                            break
                    pass
                pass
            pass

        if val_solub:
            from datamodel import createList
            from datamodel import PhysicalQuantity
            self.value_species, self.value_property = createList(val_solub, PhysicalQuantity)
            pass
        if val_solid:
            from datamodel import createList
            from datamodel import PhysicalQuantity
            self.value_solid_species, self.value_solid_property = createList(val_solid, PhysicalQuantity)
            pass
        return
コード例 #33
0
ファイル: verifyproblem.py プロジェクト: apdimier/Etumos
def verifyZoneBoundaryConditionisUnique(boundaryConditions):
    """
    a boundary should be defined only once, it raises an exception if not
    """
    t0 = time()
    i = 1
    boundaryConditions = toList(boundaryConditions)
    for boundary in boundaryConditions:
        boundlist = boundary.getBoundary()
        boundlist = toList(boundlist)
        for bound in boundlist:
            mesh = None
            for bounds in boundaryConditions[i:]:
                boundslist = bounds.getBoundary()
                boundslist = toList(boundslist)
                for bou in boundslist:
                    if mesh:
                        test = ((bou == bound) or
                                mesh.intersectSupports('test',entity,[bou,bound]))
                        pass
                    else:
                        test = (bou == bound)
                        pass
                    if test:
                        vars1=None
                        vars2=None
                        try:
                            vars1=boundary.getDepend()
                            vars2=bounds.getDepend()
                        except:
                            msg="ERROR : Different boundary conditions "
                            boundname = bound.getName()
                            if bou == bound:
                                msg+="defined on the same boundary"
                                msg+=" named %s"%boundname+ "."
                                pass
                            else:
                                bouname = bou.getName()
                                msg+="defined on boundaries with common elements.\n"
                                msg+="Boundaries with common elements are named %s"%boundname + " and %s"%bouname + "."
                                t1 = time()
                                print('temps de verifyZoneBoundaryConditionisUnique : ' + str(t1- t0) +'s')
                                print('used memory :', getMemory() , 'Ko \n')
                            raise msg
                        for var in vars1:
                            if (var in vars2) or var=='ALL' or vars2==['ALL']:
                                msg="ERROR : Different boundary conditions "
                                msg+="for the same variable : %s"%var
                                boundname = bound.getName()
                                if bou == bound:
                                    msg+=" defined on the same boundary"
                                    msg+=" named %s"%boundname + "."
                                    pass
                                else:
                                    bouname = bou.getName()
                                    msg+=" defined on boundaries with common elements.\n"
                                    msg+="Boundaries with common elements are named %s"%boundname + " and %s"%bouname
                                    t1 = time()
                                    print('temps de verifyZoneBoundaryConditionisUnique : ' + str(t1- t0) +'s')
                                    print('used memory :', getMemory() , 'Ko \n')
                                    pass
                                raise Warning(msg)
                            pass
                        pass
                    pass
                pass
            pass                
        i = i+1
        pass
    t1 = time()
    print('temps de verifyZoneBoundaryConditionisUnique : ' + str(t1- t0) +'s')
    print('used memory :', getMemory() , 'Ko \n')
    return
コード例 #34
0
ファイル: generictools.py プロジェクト: apdimier/Etumos
def memberShip(x, liste, message=None):
    if not isinstance(x, tuple(toList(liste))):
        if message == None: message = "of " + x.__class__.__name__
        raise Exception("check instantiation %s %s" % (message, x))
コード例 #35
0
    def __init__(self,
                 alltype,
                 facetype,
                 quantity,
                 support,
                 name=None,
                 unit=None,
                 timeSpecification=None,
                 where=None,
                 variables=[]):
        """ExpectedOutput initialisation with :
        - all possible expected output quantity
        - expected output quantity which can be define with attribute 'where=face' or 'where = border'
        - an expected output quantity.
        - a support. Support depends on wanted quantity.
          If Flux, support is a tuple (boundary, zone) (possible type for
          boundary or for zone : MedSupport or CartesianMesh)
          If TotalFlux or TotalInflux, support can be MedSupport or CartesianMesh          
          If other quantities, support can be MedSupport, CartesianMesh
        - OPTIONAL :
          --> a name (string). If None given, name is set to quantity
          --> a unit (string)
          --> where (string) : represents expected output localisation. It's only
                               available if quantity is Pressure,, Saturation or DarcyVelocity
                               and support is MedSupport or CartesianMesh and on all elements.
                               Value can be center, face or border
          --> timeSpecification (TimeSpecification) : define times to get expected output
          --> variables (default value = []) : define specific wanted species
        """

        if type(quantity) != StringType:
            raise TypeError(
                " quantity for CommonExpectedOutput_old should be a string")
        if quantity not in alltype:
            raise Exception("check the quantity you want to plot ")
        self.quantity = quantity

        partialtype = alltype[:]
        partialtype.remove('Flux')
        partialtype.remove('TotalFlux')
        partialtype.remove('TotalInflux')

        if self.quantity in partialtype:
            supports = toList(support)
            if len(supports) != 1:
                raise Exception(" the support has not the good length")
            verifyClassList(supports, [CartesianMesh])
            for sup in supports:
                pass
            pass
        elif (self.quantity == 'Flux'):
            # Support should be TupleType of Boundary, Zone
            if type(support) != TupleType:
                raise TypeError(" support should be a tuple ")
            if (len(support) != 2):
                Message = repr(
                    len(support[sup])
                ) + ' MedSupport given, 2 wanted for a flux expected output'
                raise Message
            fzone = support[1]
            fbound = support[0]
            memberShip(fbound, MedSupport)
            memberShip(fzone, MedSupport)
            verifyZones(toList(fzone))
            #verifyBoundaries(toList(fbound))
            pass
        elif self.quantity in ['TotalFlux', 'TotalInflux']:
            supports = toList(support)
            if len(supports) != 1:
                raise Exception(" the support has not the good length ")
            # Support should be Zone
            verifyClassList(supports, [MedSupport, CartesianMesh])
            for sup in supports:
                pass
            pass
        self.support = support

        if name:
            if type(name) != StringType:
                raise TypError(
                    "name should be a string  within CommonExpectedOutput_old")
            self.name = name
            pass
        else:
            self.name = self.quantity
        #
        if unit:
            if type(unit) != StringType:
                raise typeError(" unit should be a string ")
        self.unit = unit

        if timeSpecification:
            from timespecification import TimeSpecification
            memberShip(timeSpecification, TimeSpecification)
            mode = timeSpecification.getSpecification()
            if mode not in ['frequency', 'period', 'times']:
                raise Exception(
                    " check the mode argument in CommonExpectedOutput")
            pass
        self.timespecification = timeSpecification

        self.where = where

        if len(variables):
            from datamodel import Species
            verifyClassList(variables, Species)
        self.variables = variables
コード例 #36
0
ファイル: generictools.py プロジェクト: apdimier/Etumos
def _classesNameVerbose(liste):
    """returns a string made of the different classes names within a list,
       so it supposes each element has __name__ as attribute.
    """
    liste = toList(liste)
    return " ".join([elt.__name__ for elt in liste])
コード例 #37
0
ファイル: generictools.py プロジェクト: apdimier/Etumos
def _classesNameVerbose(liste):
    """returns a string made of the different classes names within a list,
       so it supposes each element has __name__ as attribute.
    """
    liste = toList(liste)
    return (' '.join([elt.__name__ for elt in liste]))
コード例 #38
0
ファイル: hydraulicproblem.py プロジェクト: apdimier/Etumos
    def __init__(self,\
                 name,\
                 saturation,\
                 regions,\
                 boundaryConditions,\
                 initialConditions = None,\
                 state = None,\
                 simulationType = None,\
                 calculationTimes = None,\
                 gravity = None,\
                 density = None,\
                 source = None,\
                 viscosity = None,\
                 outputs = None,\
                 description = None):
                 
        """
        Problem initialisation with :
        
        - name :                name given by the user to the problem

        - saturation:           determines the state to be modelled.
                                Depending on the way the problem is defined, it can be modified.
        - boundary conditions:  
        - initial conditions:   
        - regions:              all regions covering the entire mesh. Regions make up a partition of the mesh
                                
        - gravity:              default None
        
        - density:              default None
        
        - viscosity:            default None
        
        - sources               default None
        
        - outputs               default None

        """
                                                                                            # 
                                                                                            # name should be a string
                                                                                            #
        if type(name) != bytes:
            raise TypeError("name should be a string ")
        self.name = name
                                                                                            #
                                                                                            # saturation
                                                                                            #
        self.problemType = "saturated"
        self.saturation = "saturated"
        if type(saturation) == bytes:
            if saturation == "unsaturated" or saturation.lower()=="no":
                self.saturation = "unsaturated"
                self.problemType = "unsaturated"
                pass
            pass
                                                                                            #
                                                                                            # regions treatment
                                                                                            #
        verifyClassList(regions, Region)
        regions_zones = [region.getZone() for region in regions]
        self.regions = regions
                                                                                            #
                                                                                            # gravity treatment
                                                                                            #
        check = -1
        if gravity:
            memberShip(gravity, Gravity)
            try:
                value=gravity.getValue()
                if type(value) not in [float, int]:
                    raise TypeError(" value should be a float or an int ")
                meshdim = regions_zones[0].getSpaceDimension()
                value=[0.]*meshdim
                value[-1] = 9.81
                if meshdim == 2: value.append(0.)
                gravity=Vector(value)
            except:
                pass
            pass
        else:            
            meshdim = regions_zones[0].getSpaceDimension()
            value=[0.]*meshdim
            value[-1] = 9.81
            if meshdim == 2: value.append(0.)
            gravity=Vector(value)
            print(value)
        
        self.gravity = gravity
                                                                                            #
                                                                                            # density treatment
                                                                                            #        
        if density:
            if type(density) == FloatType: density = Density(density, 'kg/m**3') 
            memberShip(density, Density)
            check = 2*check
            pass
        self.density = density
                                                                                            #
                                                                                            # viscosity treatment
                                                                                            #
        print(" dbg viscosity ",viscosity);#raw_input()
        if viscosity:
            if type(viscosity) == FloatType: viscosity = Viscosity(viscosity, 'kg/m/s') 
            memberShip(viscosity, Viscosity)
            check = 3*check
            pass
        else:
            viscosity = Viscosity(1.0, 'kg/m/s')
            pass
        print(" dbg viscosity 1",viscosity);#raw_input()
        self.viscosity = viscosity
                                                                                            #
                                                                                            # Do we use intrinsic permeability
                                                                                            #
        if self.saturation == "unsaturated": intrinsicPermeabilityCheck(self.regions, check)
                                                                                            #        
                                                                                            # times definition
                                                                                            #        
        self.simulationType = simulationType
#        #raw_input("calculation times ")
        if calculationTimes:
            self.calculationTimes = calculationTimes
            self.simulationType = "Transient"
            pass
        else:
            self.calculationTimes = None
            self.simulationType = "Steady"
            pass
        self.steadyState = 1 
        if self.calculationTimes!= None:
            if type(calculationTimes) != list:
                raise TypeError(" calculationTimes should be a list ")
            CalculationTimes=toFloatList( self.calculationTimes)
            #
            for item in CalculationTimes:
                if type(item) != float:
                    raise TypeError(" item should be a float ")
                pass
            self.calculationTimes = sorted( CalculationTimes)
#            print self.calculationTimes;#raw_input(" within the loop, calculation times are printed here")
            self.steadyState = 0                                                            # The simulation is transient
            pass
                                                                                            #
                                                                                            # Permeability
                                                                                            #
        if self.saturation == "unsaturated":
            #
            # only Richards for the moment
            #
            pass
            #raise Exception, " for the moment, undersaturated flows are not implemented"
            #regionPhysicalQuantitiesCheck([Permeability, IntrinsicPermeability], regions)
                                                                                            #        
                                                                                            # boundaryConditions treatment
                                                                                            #        
        self.defaultBC = None
        boundaryConditions = toList(boundaryConditions)
        print(" problem type ",self.problemType)
#        raw_input(str(self.problemType))
        print(dir(boundaryConditions[0])) 

        # verification if all boundaries are treated.
        # If some are not, affect a default value (an homogeneous
        # neumann boundarycondition)
        boundaries = []
        for boundaryElement in boundaryConditions:
            boundary = toList(boundaryElement.getBoundary())
            for bound in boundary: boundaries.append(bound)
            pass
        # In case of structured mesh, not all the boundary could be defined for the problem
        if self.defaultBC:
            if not self.density:
                self.density = Density(1.)
                pass
            if not self.gravity:
                mesh_dim=regions[0].getZone().getMesh().getSpaceDimension()
                if mesh_dim==2: self.gravity=Gravity(Vector(0.,1.))
                elif mesh_dim==3: self.gravity=Gravity(Vector(0.,0.,1.))
                else:
                    raise Warning('Dimension ????')
                pass
            pass        
        # Verification if a pressure condition has been set
        # that density and gravity have been set
#        verifySomeOfPhysicalQuantitiesExists([Permeability, IntrinsicPermeability], regions)
        
#        verifyPressureBoundaryConditions(boundaryConditions, self.density, self.gravity)       
        self.boundaryConditions = boundaryConditions
                                                                                            #
                                                                                            # initialConditions treatment
                                                                                            #        
        self.initialConditions = initialConditions
#        print " initialConditions",initialConditions;raw_input()
                                                                                            #
                                                                                            # source treatment
                                                                                            #
        if source: verifyClassList(source, Source)
        self.source = source
                                                                                            #
                                                                                            # outputs treatment
                                                                                            #
        if outputs:
            outputs1 = toList(outputs)
            verifyClassList(outputs1, _dicoproblem[type].ExpectedOutput)

            if not hasattr(self,'output_names'): self.output_names=[]
            for output in outputs1:
                if output.getName() in self.output_names:
                    msg = '\n\nDifferent outputs should not share the same name.\n'
                    msg+= 'End of the hydraulic problem run.\n\n'
                    raise Warning(msg)
                self.output_names.append(output.getName())
                pass
            #
        self.outputs = outputs
        return
コード例 #39
0
    def __init__(self,
                 name,\
                 regions,\
                 calculationTimes,\
                 fluidCompressibility,\
                 gravity,\
                 density,\
                 viscosity,\
                 boundaryConditions,\
                 initialConditions = None,\
                 zoneConditions = None,\
                 source=None,\
                 densityLaw=None,\
                 viscosityLaw=None,\
                 outputs=None):
        """
        Problem initialisation with :
        
        - a name (string)
        - one or several regions (object Region or list of Region)
        - one or several boundary conditions (object BoundaryCondition
          or list of BoundaryCondition)
        - a fluidCompressibility (object FluidCompressibility)
        - a gravity (object Gravity)
        - a density (object Density)
        - a viscosity (object Viscosity)
        
        - OPTIONAL :
        
          --> one or several zone conditions (object ZoneCondition
              or list of ZoneCondition)
          --> one or several sources (object Source or list of Source)
          --> one or several outputs (object ExpectedOutput or list of
              ExpectedOutput)
          --> a density law  (object DensityLaw)
          --> a viscosity law (object ViscosityLaw)
        """
        #
        # regions treatment
        #
        regions = toList(regions)
        from datamodel import MatrixCompressibilityFactor
        from datamodel import HydraulicPorosity
        from datamodel import IntrinsicPermeability
        verifyPhysicalQuantityExists([MatrixCompressibilityFactor,HydraulicPorosity,IntrinsicPermeability], regions)

        HydraulicProblem.__init__(self,'transient',name, regions,                 
                                  boundaryConditions,calculationTimes,
                                  gravity,density,viscosity,
                                  initialConditions,zoneConditions,
                                  source,outputs)
        
        #
        # fluidCompressibility treatment
        #
        if fluidCompressibility:
            from datamodel import FluidCompressibility
            if not isinstance(fluidCompressibility, FluidCompressibility):
                raise Exception(" fluid compressibility must be an instance of the FluidCompressibility class")
            pass
        self.fluidCompressibility = fluidCompressibility

        # densityLaw treatment
        if densityLaw:
            from datamodel import DensityLaw
            if not isinstance(densityLaw, DensityLaw):
                raise Exception(" density must be an instance of the densityLaw class")
            pass
        self.densityLaw = densityLaw


        # viscosityLaw treatment
        if viscosityLaw:
            from datamodel import ViscosityLaw
            if not isinstance(viscosityLaw, ViscosityLaw):
                raise Exception(" the viscosity law must be an instance of the ViscosityLaw class")
            pass
        self.viscosityLaw = viscosityLaw
            
        #
        # Consistance problem verification
        #
        #msg='verification density,gravity,fluidCompressibility,viscosity'
        verifyExists(self.density,self.gravity,\
                     self.fluidCompressibility,self.viscosity)

        return
コード例 #40
0
ファイル: mechanicalmodule.py プロジェクト: apdimier/Etumos
    def setData(self, problem,\
                mesh = None,\
                dicobc = None,\
                dicoic = None):

        self.expectedOutput = None
        self.problem = problem
        #print problem.__class__.__name__
        if not isinstance(problem, MechanicalProblem) and not isinstance(problem, THMCProblem):
            raise Exception(" the problem must be a mechanical problem")
        self.problemName = problem.getName()
        self.regions = problem.getRegions()

        self.mesh = mesh
        mediumProperties = {
                            "density"                    : None,
                            "gravity"                    : None,
                            "YoungModulus"               : None,
                            "PoissonRatio"               : None, 
                           }
        #
        # regionProperties is a dictionnary. It is made of a list of tuples, each region is associated to a dictionnary,
        # the dictionnary containing the medium region properties.
        #                        
        self.regionProperties   = {}
        #
        self.times = problem.getCalculationTimes()
        #
        if self.times == None:
            self.simulationType = "Steady"
        else:
            self.simulationType = "Transient"
        #                        
        self.boundaryConditions = {}
        #                        
        self.initialConditions  = {}
                                                                                            #
                                                                                            # we fill the medium properties dictionnary
                                                                                            #
        self.solidDensity = problem.getDensity()
        self.gravity      = problem.getGravity()
        #
        for reg in self.regions:
            regionName = reg.support.getBodyName()
            material = reg.getMaterial()
            self.regionProperties[regionName] = mediumProperties

            youngModulus = material.youngModulus
            poissonRatio = material.poissonRatio
            intrinsicPermeability = material.getIntrinsicPermeability()
            self.regionProperties[regionName]["density"]                = material.density
            self.regionProperties[regionName]["gravity"]                = self.gravity
            self.regionProperties[regionName]["youngModulus"]           = youngModulus
            self.regionProperties[regionName]["poissonRatio"]           = poissonRatio
            pass
                                                                                            #
                                                                                            # We treat here the boundary conditions.
                                                                                            # We establish a dictionnary independant
                                                                                            # from the tool to be treated.
                                                                                            #
        boundarySpecification = {
                                "typ"           : None,
                                "Displacement"  : None,
                                "Normalforce"   : None,
                                "material"      : None,
                                }
        boundaryConditions = problem.getBoundaryConditions()
        from vector import V as Vector
        #
        ind = 0
        for boundaryCondition in boundaryConditions:
            #print "dir boundary",dir(boundaryCondition)
            #print "boundary name ",boundaryCondition.name
            #print boundaryCondition.getSupport()
            bodyToConsider = boundaryCondition.boundary
            print(bodyToConsider)
            print("entity ", bodyToConsider.getEntity())
            print(" type " , boundaryCondition.getType())
            print(" name " , bodyToConsider.getName())
            #print "material ",boundaryCondition.boundary.material
            #raw_input()
            dis = boundaryCondition.getDisplacementValue()
            #print type(dis)
            #raw_input("dis")
            nf = boundaryCondition.getNormalForceValue()
            ok = 0
            for reg in self.regions:
                if reg.getSupport().getName() == bodyToConsider.getName():
                    #print "material ",reg.material;raw_input()
                    ok = 1
                    break
                pass
            if ok == 0:
                raise Warning("Check the definition of regions and boundaries")
            
            self.boundaryConditions[ind] = {"name": bodyToConsider.getName(),\
                                            "index": bodyToConsider.getEntity(),\
                                            "bodyName": bodyToConsider.getBodyName(),\
                                            "Displacement": dis,\
                                            "Normalforce": nf,\
                                            "Material":reg.material, # boundaryCondition.boundary.material,
                                            "type": boundaryCondition.getType()[0],
                                            "description": boundaryCondition.description
                                           }
            ind+=1
            pass
                                                                                            #
                                                                                            # We treat now the initial conditions
                                                                                            #
        ind = 0
        initialConditions = problem.getInitialConditions()
        if initialConditions!= None:
            for initialCondition in initialConditions:
                value = initialCondition.value # a displacement
                initialConditionName = initialCondition.body.getBodyName()
                ok = 0
                for reg in self.regions:
                    if reg.getSupport().getName() == bodyToConsider.getName():
                        #print "material ",reg.material;raw_input()
                        ok = 1
                        break
                if ok == 0:
                    raise Warning("Check the definition of regions and boundaries")
            
                self.initialConditions[ind] = {"name": initialConditionName,\
                                               "Displacement": value,\
                                               "material": reg.getMaterial(),
                                               "index": initialCondition.body.getEntity(),\
                                               "description": initialCondition.description
                                              }
                pass
            pass
                                                                                            #
                                                                                            # We treat now the sources
                                                                                            #
        sourceList = problem.getSources()
        sourceCtrl = 0
        if sourceList:
            from datamodel import Flowrate
            sourceFlowrate = NumericZoneField('source', mesh, ["source"])
            sourceList = toList(sourceList)
            for source in sourceList:

                value = source.getValue()
                if isInstance(value,Flowrate):
                    sourceFlowrate.setZone(source.getZone(), [value.getValue()])
                    sourceCtrl = 1
                    pass
                pass
            pass

        if sourceCtrl:
            self.sourceField = sourceFlowrate
            pass
                                                                                            #        
                                                                                            # We treat outputs: 
                                                                                            # outputs -> list of dictionnary
                                                                                            #
        if self.expectedOutput:
            for eo in self.expectedOutput:
                varnames=['Pressure']
                eo['varnames'] = varnames
                pass
            pass
コード例 #41
0
ファイル: hydraulicproblem.py プロジェクト: apdimier/Etumos
    def __init__(self,\
                 name,\
                 saturation,\
                 regions,\
                 boundaryConditions,\
                 initialConditions = None,\
                 state = None,\
                 simulationType = None,\
                 calculationTimes = None,\
                 gravity = None,\
                 density = None,\
                 source = None,\
                 intrinsicPermeability = None,\
                 viscosity = None,\
                 outputs = None,\
                 description = None):
        """
        Problem initialisation with :
        
        - name :                name given by the user to the problem

        - saturation:           determines the state to be modelled.
                                Depending on the way the problem is defined, it can be modified.
        - boundary conditions:  
        - initial conditions:   
        - regions:              all regions covering the entire mesh. Regions make up a partition of the mesh
                                
        - gravity:                  default None
        
        - density:                  default None
        
        - intrinsicPermeability:    default None
        
        - viscosity:                default None
        
        - sources                   default None
        
        - outputs                   default None

        """
        #
        # name should be a string
        #
        if type(name) != bytes:
            raise TypeError("name should be a string ")
        self.name = name
        #
        # saturation
        #
        self.problemType = "saturated"
        self.saturation = "saturated"
        if type(saturation) == bytes:
            if saturation == "unsaturated" or saturation.lower() == "no":
                self.saturation = "unsaturated"
                self.problemType = "unsaturated"
                pass
            pass
            #
            # regions treatment
            #
        verifyClassList(regions, Region)
        regions_zones = [region.getZone() for region in regions]
        self.regions = regions
        #
        # gravity treatment
        #
        check = -1
        if gravity:
            memberShip(gravity, Gravity)
            try:
                value = gravity.getValue()
                if type(value) not in [float, int]:
                    raise TypeError(" value should be a float or an int ")
                meshdim = regions_zones[0].getSpaceDimension()
                value = [0.] * meshdim
                value[-1] = 9.81
                if meshdim == 2: value.append(0.)
                gravity = Vector(value)
            except:
                pass
            pass
        else:
            meshdim = regions_zones[0].getSpaceDimension()
            value = [0.] * meshdim
            value[-1] = 9.81
            if meshdim == 2: value.append(0.)
            gravity = Vector(value)
            print(value)
            pass
        self.gravity = gravity
        #
        # density treatment
        #
        if density:
            if type(density) == FloatType:
                density = Density(density, 'kg/m**3')
            memberShip(density, Density)
            check = 2 * check
            pass
        self.density = density
        #
        # intrinsicPermeability treatment
        # the introduction of the intrinsic permeability
        # is related to the introduction of the openfoam solver.
        #
        #print (intrinsicPermeability)
        #print (type(intrinsicPermeability))
        #raw_input("problem type intrinsicPermeability")
        if intrinsicPermeability:
            if type(intrinsicPermeability) == FloatType:
                intrinsicPermeability = IntrinsicPermeability(
                    intrinsicPermeability, 'm**2')
            memberShip(intrinsicPermeability, IntrinsicPermeability)
            check = 2 * check
            pass
        self.intrinsicPermeability = intrinsicPermeability
        #print (intrinsicPermeability)
        #print (type(intrinsicPermeability))
        #raw_input("problem type intrinsicPermeability b")
        #
        # viscosity treatment
        #
        #print(" dbg viscosity ",viscosity);#raw_input()
        if viscosity:
            if type(viscosity) == FloatType:
                viscosity = Viscosity(viscosity, 'kg/m/s')
            memberShip(viscosity, Viscosity)
            check = 3 * check
            pass
        else:
            viscosity = Viscosity(1.0, 'kg/m/s')
            pass
        #print(" dbg viscosity 1",viscosity);#raw_input()
        self.viscosity = viscosity
        #
        # Do we use intrinsic permeability
        #
        if self.saturation == "unsaturated":
            intrinsicPermeabilityCheck(self.regions, check)
        #
        # times definition
        #
        self.simulationType = simulationType
        #        #raw_input("calculation times ")
        if calculationTimes:
            self.calculationTimes = calculationTimes
            self.simulationType = "Transient"
            pass
        else:
            self.calculationTimes = None
            self.simulationType = "Steady"
            pass
        self.steadyState = 1
        if self.calculationTimes != None:
            if type(calculationTimes) != list:
                raise TypeError(" calculationTimes should be a list ")
            CalculationTimes = toFloatList(self.calculationTimes)
            #
            for item in CalculationTimes:
                if type(item) != float:
                    raise TypeError(" item should be a float ")
                pass
            self.calculationTimes = sorted(CalculationTimes)
            #            print self.calculationTimes;#raw_input(" within the loop, calculation times are printed here")
            self.steadyState = 0  # The simulation is transient
            pass
            #
            # Permeability
            #
        if self.saturation == "unsaturated":
            #
            # only Richards for the moment
            #
            pass
            #raise Exception, " for the moment, undersaturated flows are not implemented"
            #regionPhysicalQuantitiesCheck([Permeability, IntrinsicPermeability], regions)
            #
            # boundaryConditions treatment
            #
        self.defaultBC = None
        boundaryConditions = toList(boundaryConditions)
        print(" problem type ", self.problemType)
        #        raw_input(str(self.problemType))
        print(dir(boundaryConditions[0]))

        # verification if all boundaries are treated.
        # If some are not, affect a default value (an homogeneous
        # neumann boundarycondition)
        boundaries = []
        for boundaryElement in boundaryConditions:
            boundary = toList(boundaryElement.getBoundary())
            for bound in boundary:
                boundaries.append(bound)
            pass
        # In case of structured mesh, not all the boundary could be defined for the problem
        if self.defaultBC:
            if not self.density:
                self.density = Density(1.)
                pass
            if not self.gravity:
                mesh_dim = regions[0].getZone().getMesh().getSpaceDimension()
                if mesh_dim == 2: self.gravity = Gravity(Vector(0., 1.))
                elif mesh_dim == 3: self.gravity = Gravity(Vector(0., 0., 1.))
                else:
                    raise Warning('Dimension ????')
                pass
            pass
        # Verification if a pressure condition has been set
        # that density and gravity have been set


#        verifySomeOfPhysicalQuantitiesExists([Permeability, IntrinsicPermeability], regions)

#        verifyPressureBoundaryConditions(boundaryConditions, self.density, self.gravity)
        self.boundaryConditions = boundaryConditions
        #
        # initialConditions treatment
        #
        self.initialConditions = initialConditions
        #        print " initialConditions",initialConditions;raw_input()
        #
        # source treatment
        #
        if source: verifyClassList(source, Source)
        self.source = source
        #
        # outputs treatment
        #
        if outputs:
            outputs1 = toList(outputs)
            verifyClassList(outputs1, _dicoproblem[type].ExpectedOutput)

            if not hasattr(self, 'output_names'): self.output_names = []
            for output in outputs1:
                if output.getName() in self.output_names:
                    msg = '\n\nDifferent outputs should not share the same name.\n'
                    msg += 'End of the hydraulic problem run.\n\n'
                    raise Warning(msg)
                self.output_names.append(output.getName())
                pass
            pass
            #
        self.outputs = outputs
        return
コード例 #42
0
ファイル: tables.py プロジェクト: apdimier/Etumos
 def extractSubTable(self,**dico):
     """ Creates a subtable in different ways ordered by dico keys.
     1/ if somebody wants a table with several columns, the possibilities are:
          column = a number
          columns = a number (for only one column)
                  or
                  a list of numbers (where can be only
                                     one number)
          fromcolumn = a number
          tocolumn = a number
          columnname = 'a good column name'
          columnnames = a list of column names
     2/ if somebody wants a table with several rows, the possibilities are:
          row   = a number
          rows  = a number (for only one column)
                  or
                  a list of numbers (where can be only
                                     one number)
          fromrow = a number
          torow = a number
          withvaluesincolumn = a tuple (list of values, number of column
                                        or its name, a precision if wanted)
     """
     #
     if not len(dico):
         return self.copy()
     elif len(dico)>1:
         msg='only one argument allowed.'
         raise msg
     #
     cle=list(dico.keys())[0]
     val=dico[cle]
     cle=cle.lower()
     if cle=='withvaluesincolumn':
         model,numeroColonne=val[0],val[1]
         listTypeCheck(model,[IntType,FloatType])
         model=[float(x) for x in model]
         verifyType(numeroColonne,[StringType,\
                    IntType,FloatType])
         tttitres=self.getColumnNames()
         ttunits = self.getColumnUnits()
         if type(numeroColonne) is StringType:
             for tit in tttitres:
                 if tit==numeroColonne: numCol=tttitres.index(tit)
                 pass
         else:
             if numeroColonne>=len(tttitres):
                 msg='The table does not have\n'
                 msg+='that number of columns : %s'%numeroColonne
                 raise msg
             numCol=numeroColonne
             pass
             
         if len(val)==3:
             eps=val[2]
             pass
         else:
             eps=1.e-15
             pass
         new=Table(self.getName(),tttitres,ttunits)
         nlig=self.getNbRows()
         ip=0
         comp=[float(x) for x in self.getColumn(numCol)]
         for ip in range(len(model)):
             for i in range(len(comp)):
                 value=comp[i]
                 if ip==1 and i==len(comp)-1:
                     pass
                 if areClose(value,model[ip],eps,'rel'):
                     new.addRow(self.getRow(i))
                     pass
                 if ip==len(model):
                     break
                 pass
             pass
         pass           
     else:
         valeurs=toList(val)
         tttitres=self.getColumnNames()
         ttunits = self.getColumnUnits()
         for st in ['row','column']:
             if st=='row':nn=self.getNbRows()
             if st=='column':nn=self.getNbColumns()
             if cle.find(st)>=0:
                 cleOk=st
                 pass
             if cle==st:
                 if len(valeurs) != 1:
                     raise Exception(" list length problem within the extractSubTable function")
                 pass
             if cle=='from'+st:
                 valeurs=valeurs[valeurs[0]:nn-1]
                 pass
             if cle=='to'+st:
                 valeurs=valeurs[0:valeurs[0]]
                 pass
             if cle.find('name')>=0:
                 newv=[]
                 for v in valeurs:
                     for tit in tttitres:
                         if tit==v:
                             newv.append(tttitres.index(tit))
                             break
                         pass
                     pass
                 valeurs=newv
                 pass
             pass
         if cleOk=='row':
             newtitres=tttitres
             newunits = ttunits
             pass
         if cleOk=='column':
             newtitres=[]
             newunits = []
             for i in valeurs:
                 newtitres.append(tttitres[i])
                 if len(ttunits): newunits.append(ttunits[i])
                 pass
             pass
         new=Table(self.getName(),newtitres,newunits)
         for i in valeurs:
             if cleOk=='row':
                 liste=self.getRow(i)
                 new.addRow(liste)
                 pass
             if cleOk=='column':
                 liste=self.getColumn(i)
                 new.addColumnValues(liste)
                 pass
             pass
         pass
     return new
コード例 #43
0
    def __init__(self,
                 name,\
                 regions,\
                 calculationTimes,\
                 fluidCompressibility,\
                 gravity,\
                 density,\
                 viscosity,\
                 boundaryConditions,\
                 initialConditions = None,\
                 zoneConditions = None,\
                 source=None,\
                 densityLaw=None,\
                 viscosityLaw=None,\
                 outputs=None):
        """
        Problem initialisation with :
        
        - a name (string)
        - one or several regions (object Region or list of Region)
        - one or several boundary conditions (object BoundaryCondition
          or list of BoundaryCondition)
        - a fluidCompressibility (object FluidCompressibility)
        - a gravity (object Gravity)
        - a density (object Density)
        - a viscosity (object Viscosity)
        
        - OPTIONAL :
        
          --> one or several zone conditions (object ZoneCondition
              or list of ZoneCondition)
          --> one or several sources (object Source or list of Source)
          --> one or several outputs (object ExpectedOutput or list of
              ExpectedOutput)
          --> a density law  (object DensityLaw)
          --> a viscosity law (object ViscosityLaw)
        """
        #
        # regions treatment
        #
        regions = toList(regions)
        from datamodel import MatrixCompressibilityFactor
        from datamodel import HydraulicPorosity
        from datamodel import IntrinsicPermeability
        verifyPhysicalQuantityExists([
            MatrixCompressibilityFactor, HydraulicPorosity,
            IntrinsicPermeability
        ], regions)

        HydraulicProblem.__init__(self, 'transient', name, regions,
                                  boundaryConditions, calculationTimes,
                                  gravity, density, viscosity,
                                  initialConditions, zoneConditions, source,
                                  outputs)

        #
        # fluidCompressibility treatment
        #
        if fluidCompressibility:
            from datamodel import FluidCompressibility
            if not isinstance(fluidCompressibility, FluidCompressibility):
                raise Exception(
                    " fluid compressibility must be an instance of the FluidCompressibility class"
                )
            pass
        self.fluidCompressibility = fluidCompressibility

        # densityLaw treatment
        if densityLaw:
            from datamodel import DensityLaw
            if not isinstance(densityLaw, DensityLaw):
                raise Exception(
                    " density must be an instance of the densityLaw class")
            pass
        self.densityLaw = densityLaw

        # viscosityLaw treatment
        if viscosityLaw:
            from datamodel import ViscosityLaw
            if not isinstance(viscosityLaw, ViscosityLaw):
                raise Exception(
                    " the viscosity law must be an instance of the ViscosityLaw class"
                )
            pass
        self.viscosityLaw = viscosityLaw

        #
        # Consistance problem verification
        #
        #msg='verification density,gravity,fluidCompressibility,viscosity'
        verifyExists(self.density,self.gravity,\
                     self.fluidCompressibility,self.viscosity)

        return