[PY3] Removing TAB issues

Via this command :
find . -name "*.py" | xargs grep -Prl "\t" | xargs python  /local00/home/J42254/Projets/SALOME/Installations/prerequisites/src/Python-352-tcl8513-tk8513/Tools/scripts/reindent.py
This commit is contained in:
Nicolas Geimer 2017-03-20 13:22:47 +01:00
parent d8428a892b
commit 84cf6c4911
25 changed files with 2734 additions and 2757 deletions

View File

@ -60,7 +60,7 @@ def set_env(args):
if plugin in plugin_list: continue if plugin in plugin_list: continue
# add paths of plugin # add paths of plugin
plugin_list.append(plugin) plugin_list.append(plugin)
if not os.environ.has_key("SALOME_"+plugin+"Resources"): if not os.environ.has_key("SALOME_"+plugin+"Resources"):
resource_path = os.path.join(plugin_root,"share",salome_subdir,"resources",plugin.lower()) resource_path = os.path.join(plugin_root,"share",salome_subdir,"resources",plugin.lower())
os.environ["SALOME_"+plugin+"Resources"] = resource_path os.environ["SALOME_"+plugin+"Resources"] = resource_path
@ -80,4 +80,3 @@ def set_env(args):
break break
os.environ["SMESH_MeshersList"] = ":".join(plugin_list) os.environ["SMESH_MeshersList"] = ":".join(plugin_list)
os.environ["SalomeAppConfig"] = os.environ["SalomeAppConfig"] + psep + psep.join(resource_path_list) os.environ["SalomeAppConfig"] = os.environ["SalomeAppConfig"] + psep + psep.join(resource_path_list)

View File

@ -132,17 +132,17 @@ for a in log:
elif comType == 2: elif comType == 2:
for i in range(a.number): for i in range(a.number):
ind = a.indexes[ii] ind = a.indexes[ii]
print ind print ind
ii = ii+1 ii = ii+1
print ii print ii
i1 = a.indexes[ii] i1 = a.indexes[ii]
ii = ii+1 ii = ii+1
i2 = a.indexes[ii] i2 = a.indexes[ii]
print i2 print i2
ii = ii+1 ii = ii+1
print "ii", ii print "ii", ii
i3 = a.indexes[ii] i3 = a.indexes[ii]
print i3 print i3
#ii = ii+1 #ii = ii+1
ii = ii+1 ii = ii+1
print "AddTriangle %i - %i %i %i" % (ind, i1, i2, i3) print "AddTriangle %i - %i %i %i" % (ind, i1, i2, i3)

View File

@ -38,16 +38,16 @@ smesh.SetCurrentStudy(myStudy)
myStudyBuilder = myStudy.NewBuilder() myStudyBuilder = myStudy.NewBuilder()
if myStudyBuilder is None: if myStudyBuilder is None:
raise RuntimeError, " Null myStudyBuilder" raise RuntimeError, " Null myStudyBuilder"
father = myStudy.FindComponent("SMESH") father = myStudy.FindComponent("SMESH")
if father is None: if father is None:
father = myStudyBuilder.NewComponent("SMESH") father = myStudyBuilder.NewComponent("SMESH")
FName = myStudyBuilder.FindOrCreateAttribute(father, "AttributeName") FName = myStudyBuilder.FindOrCreateAttribute(father, "AttributeName")
Comp = modulecatalog.GetComponent("SMESH") Comp = modulecatalog.GetComponent("SMESH")
FName.SetValue(Comp._get_componentusername()) FName.SetValue(Comp._get_componentusername())
aPixmap = myStudyBuilder.FindOrCreateAttribute(father, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(father, "AttributePixMap")
aPixmap.SetPixMap("ICON_OBJBROWSER_Mesh") aPixmap.SetPixMap("ICON_OBJBROWSER_Mesh")
myStudyBuilder.DefineComponentInstance(father,smesh) myStudyBuilder.DefineComponentInstance(father,smesh)
@ -70,255 +70,255 @@ Tag = {"HypothesisRoot":1,"AlgorithmsRoot":2,"RefOnShape":1,"RefOnAppliedHypothe
#------------------------------------------------------------ #------------------------------------------------------------
def Init(): def Init():
pass pass
#------------------------------------------------------------ #------------------------------------------------------------
def AddNewMesh(IOR): def AddNewMesh(IOR):
# VSR: added temporarily - objects are published automatically by the engine # VSR: added temporarily - objects are published automatically by the engine
aSO = myStudy.FindObjectIOR( IOR ) aSO = myStudy.FindObjectIOR( IOR )
if aSO is not None: if aSO is not None:
return aSO.GetID() return aSO.GetID()
# VSR ###################################################################### # VSR ######################################################################
res,HypothesisRoot = mySComponentMesh.FindSubObject ( Tag_HypothesisRoot ) res,HypothesisRoot = mySComponentMesh.FindSubObject ( Tag_HypothesisRoot )
if HypothesisRoot is None or res == 0: if HypothesisRoot is None or res == 0:
HypothesisRoot = myStudyBuilder.NewObjectToTag(mySComponentMesh, Tag_HypothesisRoot) HypothesisRoot = myStudyBuilder.NewObjectToTag(mySComponentMesh, Tag_HypothesisRoot)
aName = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributeName") aName = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributeName")
aName.SetValue("Hypotheses") aName.SetValue("Hypotheses")
aPixmap = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributePixMap")
aPixmap.SetPixMap( "mesh_tree_hypo.png" ) aPixmap.SetPixMap( "mesh_tree_hypo.png" )
aSelAttr = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributeSelectable") aSelAttr = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributeSelectable")
aSelAttr.SetSelectable(0) aSelAttr.SetSelectable(0)
res, AlgorithmsRoot = mySComponentMesh.FindSubObject (Tag_AlgorithmsRoot) res, AlgorithmsRoot = mySComponentMesh.FindSubObject (Tag_AlgorithmsRoot)
if AlgorithmsRoot is None or res == 0: if AlgorithmsRoot is None or res == 0:
AlgorithmsRoot = myStudyBuilder.NewObjectToTag (mySComponentMesh, Tag_AlgorithmsRoot) AlgorithmsRoot = myStudyBuilder.NewObjectToTag (mySComponentMesh, Tag_AlgorithmsRoot)
aName = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributeName") aName = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributeName")
aName.SetValue("Algorithms") aName.SetValue("Algorithms")
aPixmap = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributePixMap")
aPixmap.SetPixMap( "mesh_tree_algo.png" ) aPixmap.SetPixMap( "mesh_tree_algo.png" )
aSelAttr = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributeSelectable") aSelAttr = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributeSelectable")
aSelAttr.SetSelectable(0) aSelAttr.SetSelectable(0)
HypothesisRoot = HypothesisRoot._narrow(SALOMEDS.SObject) HypothesisRoot = HypothesisRoot._narrow(SALOMEDS.SObject)
newMesh = myStudyBuilder.NewObject(mySComponentMesh) newMesh = myStudyBuilder.NewObject(mySComponentMesh)
aPixmap = myStudyBuilder.FindOrCreateAttribute(newMesh, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(newMesh, "AttributePixMap")
aPixmap.SetPixMap( "mesh_tree_mesh.png" ) aPixmap.SetPixMap( "mesh_tree_mesh.png" )
anIOR = myStudyBuilder.FindOrCreateAttribute(newMesh, "AttributeIOR") anIOR = myStudyBuilder.FindOrCreateAttribute(newMesh, "AttributeIOR")
anIOR.SetValue(IOR) anIOR.SetValue(IOR)
return newMesh.GetID() return newMesh.GetID()
#------------------------------------------------------------ #------------------------------------------------------------
def AddNewHypothesis(IOR): def AddNewHypothesis(IOR):
# VSR: added temporarily - objects are published automatically by the engine # VSR: added temporarily - objects are published automatically by the engine
aSO = myStudy.FindObjectIOR( IOR ) aSO = myStudy.FindObjectIOR( IOR )
if aSO is not None: if aSO is not None:
return aSO.GetID() return aSO.GetID()
# VSR ###################################################################### # VSR ######################################################################
res, HypothesisRoot = mySComponentMesh.FindSubObject (Tag_HypothesisRoot) res, HypothesisRoot = mySComponentMesh.FindSubObject (Tag_HypothesisRoot)
if HypothesisRoot is None or res == 0: if HypothesisRoot is None or res == 0:
HypothesisRoot = myStudyBuilder.NewObjectToTag (mySComponentMesh, Tag_HypothesisRoot) HypothesisRoot = myStudyBuilder.NewObjectToTag (mySComponentMesh, Tag_HypothesisRoot)
aName = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributeName") aName = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributeName")
aName.SetValue("Hypotheses") aName.SetValue("Hypotheses")
aSelAttr = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributeSelectable") aSelAttr = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributeSelectable")
aSelAttr.SetSelectable(0) aSelAttr.SetSelectable(0)
aPixmap = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(HypothesisRoot, "AttributePixMap")
aPixmap.SetPixMap( "mesh_tree_hypo.png" ) aPixmap.SetPixMap( "mesh_tree_hypo.png" )
# Add New Hypothesis # Add New Hypothesis
newHypo = myStudyBuilder.NewObject(HypothesisRoot) newHypo = myStudyBuilder.NewObject(HypothesisRoot)
aPixmap = myStudyBuilder.FindOrCreateAttribute(newHypo, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(newHypo, "AttributePixMap")
H = orb.string_to_object(IOR) H = orb.string_to_object(IOR)
aType = H.GetName() aType = H.GetName()
aPixmap.SetPixMap( "mesh_tree_hypo.png_" + aType ) aPixmap.SetPixMap( "mesh_tree_hypo.png_" + aType )
anIOR = myStudyBuilder.FindOrCreateAttribute(newHypo, "AttributeIOR") anIOR = myStudyBuilder.FindOrCreateAttribute(newHypo, "AttributeIOR")
anIOR.SetValue(IOR) anIOR.SetValue(IOR)
return newHypo.GetID() return newHypo.GetID()
#------------------------------------------------------------ #------------------------------------------------------------
def AddNewAlgorithms(IOR): def AddNewAlgorithms(IOR):
# VSR: added temporarily - objects are published automatically by the engine # VSR: added temporarily - objects are published automatically by the engine
aSO = myStudy.FindObjectIOR( IOR ) aSO = myStudy.FindObjectIOR( IOR )
if aSO is not None: if aSO is not None:
return aSO.GetID() return aSO.GetID()
# VSR ###################################################################### # VSR ######################################################################
res, AlgorithmsRoot = mySComponentMesh.FindSubObject (Tag_AlgorithmsRoot) res, AlgorithmsRoot = mySComponentMesh.FindSubObject (Tag_AlgorithmsRoot)
if AlgorithmsRoot is None or res == 0: if AlgorithmsRoot is None or res == 0:
AlgorithmsRoot = myStudyBuilde.NewObjectToTag (mySComponentMesh, Tag_AlgorithmsRoot) AlgorithmsRoot = myStudyBuilde.NewObjectToTag (mySComponentMesh, Tag_AlgorithmsRoot)
aName = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributeName") aName = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributeName")
aName.SetValue("Algorithms") aName.SetValue("Algorithms")
aSelAttr = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributeSelectable") aSelAttr = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributeSelectable")
aSelAttr.SetSelectable(0) aSelAttr.SetSelectable(0)
aPixmap = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(AlgorithmsRoot, "AttributePixMap")
aPixmap.SetPixMap( "mesh_tree_algo.png" ) aPixmap.SetPixMap( "mesh_tree_algo.png" )
# Add New Algorithms # Add New Algorithms
newHypo = myStudyBuilder.NewObject(AlgorithmsRoot) newHypo = myStudyBuilder.NewObject(AlgorithmsRoot)
aPixmap = myStudyBuilder.FindOrCreateAttribute(newHypo, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(newHypo, "AttributePixMap")
aPixmap = anAttr._narrow(SALOMEDS.AttributePixMap) aPixmap = anAttr._narrow(SALOMEDS.AttributePixMap)
H = orb.string_to_object(IOR) H = orb.string_to_object(IOR)
aType = H.GetName(); #QString in fact aType = H.GetName(); #QString in fact
aPixmap.SetPixMap( "mesh_tree_algo.png_" + aType ) aPixmap.SetPixMap( "mesh_tree_algo.png_" + aType )
anIOR = myStudyBuilder.FindOrCreateAttribute(newHypo, "AttributeIOR") anIOR = myStudyBuilder.FindOrCreateAttribute(newHypo, "AttributeIOR")
anIOR.SetValue(IOR) anIOR.SetValue(IOR)
return newHypo.GetID() return newHypo.GetID()
#------------------------------------------------------------ #------------------------------------------------------------
def SetShape(ShapeEntry, MeshEntry): def SetShape(ShapeEntry, MeshEntry):
SO_MorSM = myStudy.FindObjectID( MeshEntry ) SO_MorSM = myStudy.FindObjectID( MeshEntry )
SO_GeomShape = myStudy.FindObjectID( ShapeEntry ) SO_GeomShape = myStudy.FindObjectID( ShapeEntry )
if SO_MorSM is not None and SO_GeomShape is not None : if SO_MorSM is not None and SO_GeomShape is not None :
# VSR: added temporarily - shape reference is published automatically by the engine # VSR: added temporarily - shape reference is published automatically by the engine
res, Ref = SO_MorSM.FindSubObject( Tag_RefOnShape ) res, Ref = SO_MorSM.FindSubObject( Tag_RefOnShape )
if res == 1 : if res == 1 :
return return
# VSR ###################################################################### # VSR ######################################################################
SO = myStudyBuilder.NewObjectToTag (SO_MorSM, Tag_RefOnShape) SO = myStudyBuilder.NewObjectToTag (SO_MorSM, Tag_RefOnShape)
myStudyBuilder.Addreference (SO,SO_GeomShape) myStudyBuilder.Addreference (SO,SO_GeomShape)
#------------------------------------------------------------ #------------------------------------------------------------
def SetHypothesis(Mesh_Or_SubMesh_Entry, Hypothesis_Entry): def SetHypothesis(Mesh_Or_SubMesh_Entry, Hypothesis_Entry):
SO_MorSM = myStudy.FindObjectID( Mesh_Or_SubMesh_Entry ) SO_MorSM = myStudy.FindObjectID( Mesh_Or_SubMesh_Entry )
SO_Hypothesis = myStudy.FindObjectID( Hypothesis_Entry ) SO_Hypothesis = myStudy.FindObjectID( Hypothesis_Entry )
if SO_MorSM is not None and SO_Hypothesis is not None : if SO_MorSM is not None and SO_Hypothesis is not None :
#Find or Create Applied Hypothesis root #Find or Create Applied Hypothesis root
res, AHR = SO_MorSM.FindSubObject (Tag_RefOnAppliedHypothesis) res, AHR = SO_MorSM.FindSubObject (Tag_RefOnAppliedHypothesis)
if AHR is None or res == 0: if AHR is None or res == 0:
AHR = myStudyBuilder.NewObjectToTag (SO_MorSM, Tag_RefOnAppliedHypothesis) AHR = myStudyBuilder.NewObjectToTag (SO_MorSM, Tag_RefOnAppliedHypothesis)
aName = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributeName") aName = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributeName")
# The same name as in SMESH_Mesh_i::AddHypothesis() ################## # The same name as in SMESH_Mesh_i::AddHypothesis() ##################
aName.SetValue("Applied hypotheses") aName.SetValue("Applied hypotheses")
aSelAttr = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributeSelectable") aSelAttr = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributeSelectable")
aSelAttr.SetSelectable(0) aSelAttr.SetSelectable(0)
aPixmap = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributePixMap")
aPixmap.SetPixMap( "mesh_tree_hypo.png" ) aPixmap.SetPixMap( "mesh_tree_hypo.png" )
# VSR: added temporarily - reference to applied hypothesis is published automatically by the engine # VSR: added temporarily - reference to applied hypothesis is published automatically by the engine
else : else :
it = myStudy.NewChildIterator(AHR) it = myStudy.NewChildIterator(AHR)
while it.More() : while it.More() :
res, Ref = it.Value().ReferencedObject() res, Ref = it.Value().ReferencedObject()
if res and Ref is not None and Ref.GetID() == Hypothesis_Entry : if res and Ref is not None and Ref.GetID() == Hypothesis_Entry :
return return
it.Next() it.Next()
# VSR ###################################################################### # VSR ######################################################################
SO = myStudyBuilder.NewObject(AHR) SO = myStudyBuilder.NewObject(AHR)
myStudyBuilder.Addreference (SO,SO_Hypothesis) myStudyBuilder.Addreference (SO,SO_Hypothesis)
#------------------------------------------------------------ #------------------------------------------------------------
def SetAlgorithms(Mesh_Or_SubMesh_Entry, Algorithms_Entry): def SetAlgorithms(Mesh_Or_SubMesh_Entry, Algorithms_Entry):
SO_MorSM = myStudy.FindObjectID( Mesh_Or_SubMesh_Entry ) SO_MorSM = myStudy.FindObjectID( Mesh_Or_SubMesh_Entry )
SO_Algorithms = myStudy.FindObjectID( Algorithms_Entry ) SO_Algorithms = myStudy.FindObjectID( Algorithms_Entry )
if SO_MorSM != None and SO_Algorithms != None : if SO_MorSM != None and SO_Algorithms != None :
#Find or Create Applied Algorithms root #Find or Create Applied Algorithms root
res, AHR = SO_MorSM.FindSubObject (Tag_RefOnAppliedAlgorithms) res, AHR = SO_MorSM.FindSubObject (Tag_RefOnAppliedAlgorithms)
if AHR is None or res == 0: if AHR is None or res == 0:
AHR = myStudyBuilder.NewObjectToTag (SO_MorSM, Tag_RefOnAppliedAlgorithms) AHR = myStudyBuilder.NewObjectToTag (SO_MorSM, Tag_RefOnAppliedAlgorithms)
aName = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributeName") aName = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributeName")
# The same name as in SMESH_Mesh_i::AddHypothesis() ################## # The same name as in SMESH_Mesh_i::AddHypothesis() ##################
aName.SetValue("Applied algorithms") aName.SetValue("Applied algorithms")
aSelAttr = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributeSelectable") aSelAttr = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributeSelectable")
aSelAttr.SetSelectable(0) aSelAttr.SetSelectable(0)
aPixmap = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributePixMap") aPixmap = myStudyBuilder.FindOrCreateAttribute(AHR, "AttributePixMap")
aPixmap.SetPixMap( "mesh_tree_algo.png" ) aPixmap.SetPixMap( "mesh_tree_algo.png" )
# VSR: added temporarily - reference to applied hypothesis is published automatically by the engine # VSR: added temporarily - reference to applied hypothesis is published automatically by the engine
else : else :
it = myStudy.NewChildIterator(AHR) it = myStudy.NewChildIterator(AHR)
while it.More() : while it.More() :
res, Ref = it.Value().ReferencedObject() res, Ref = it.Value().ReferencedObject()
if res and Ref is not None and Ref.GetID() == Algorithms_Entry : if res and Ref is not None and Ref.GetID() == Algorithms_Entry :
return return
it.Next() it.Next()
# VSR ###################################################################### # VSR ######################################################################
SO = myStudyBuilder.NewObject(AHR) SO = myStudyBuilder.NewObject(AHR)
myStudyBuilder.Addreference (SO,SO_Algorithms) myStudyBuilder.Addreference (SO,SO_Algorithms)
#------------------------------------------------------------ #------------------------------------------------------------
def UnSetHypothesis( Applied_Hypothesis_Entry ): def UnSetHypothesis( Applied_Hypothesis_Entry ):
SO_Applied_Hypothesis = myStudy.FindObjectID( Applied_Hypothesis_Entry ) SO_Applied_Hypothesis = myStudy.FindObjectID( Applied_Hypothesis_Entry )
if SO_Applied_Hypothesis : if SO_Applied_Hypothesis :
myStudyBuilder.RemoveObject(SO_Applied_Hypothesis) myStudyBuilder.RemoveObject(SO_Applied_Hypothesis)
#------------------------------------------------------------ #------------------------------------------------------------
def AddSubMesh ( SO_Mesh_Entry, SM_IOR, ST): def AddSubMesh ( SO_Mesh_Entry, SM_IOR, ST):
# VSR: added temporarily - objects are published automatically by the engine # VSR: added temporarily - objects are published automatically by the engine
aSO = myStudy.FindObjectIOR( SM_IOR ) aSO = myStudy.FindObjectIOR( SM_IOR )
if aSO is not None: if aSO is not None:
return aSO.GetID() return aSO.GetID()
# VSR ###################################################################### # VSR ######################################################################
SO_Mesh = myStudy.FindObjectID( SO_Mesh_Entry ) SO_Mesh = myStudy.FindObjectID( SO_Mesh_Entry )
if ( SO_Mesh ) : if ( SO_Mesh ) :
if ST == ShapeType["COMPSOLID"] : if ST == ShapeType["COMPSOLID"] :
Tag_Shape = Tag_SubMeshOnSolid Tag_Shape = Tag_SubMeshOnSolid
Name = "SubMeshes on Solid" Name = "SubMeshes on Solid"
elif ST == ShapeType["FACE"] : elif ST == ShapeType["FACE"] :
Tag_Shape = Tag_SubMeshOnFace Tag_Shape = Tag_SubMeshOnFace
Name = "SubMeshes on Face" Name = "SubMeshes on Face"
elif ST == ShapeType["EDGE"] : elif ST == ShapeType["EDGE"] :
Tag_Shape = Tag_SubMeshOnEdge Tag_Shape = Tag_SubMeshOnEdge
Name = "SubMeshes on Edge" Name = "SubMeshes on Edge"
elif ST == ShapeType["VERTEX"] : elif ST == ShapeType["VERTEX"] :
Tag_Shape = Tag_SubMeshOnVertex Tag_Shape = Tag_SubMeshOnVertex
Name = "SubMeshes on Vertex" Name = "SubMeshes on Vertex"
else : else :
Tag_Shape = Tag_SubMeshOnCompound Tag_Shape = Tag_SubMeshOnCompound
Name = "SubMeshes on Compound" Name = "SubMeshes on Compound"
res, SubmeshesRoot = SO_Mesh.FindSubObject (Tag_Shape) res, SubmeshesRoot = SO_Mesh.FindSubObject (Tag_Shape)
if SubmeshesRoot is None or res == 0: if SubmeshesRoot is None or res == 0:
SubmeshesRoot = myStudyBuilder.NewObjectToTag (SO_Mesh, Tag_Shape) SubmeshesRoot = myStudyBuilder.NewObjectToTag (SO_Mesh, Tag_Shape)
aName = myStudyBuilder.FindOrCreateAttribute(SubmeshesRoot, "AttributeName") aName = myStudyBuilder.FindOrCreateAttribute(SubmeshesRoot, "AttributeName")
aName.SetValue(Name) aName.SetValue(Name)
aSelAttr = myStudyBuilder.FindOrCreateAttribute(SubmeshesRoot, "AttributeSelectable") aSelAttr = myStudyBuilder.FindOrCreateAttribute(SubmeshesRoot, "AttributeSelectable")
aSelAttr.SetSelectable(0) aSelAttr.SetSelectable(0)
SO = myStudyBuilder.NewObject (SubmeshesRoot) SO = myStudyBuilder.NewObject (SubmeshesRoot)
anIOR = myStudyBuilder.FindOrCreateAttribute(SO, "AttributeIOR") anIOR = myStudyBuilder.FindOrCreateAttribute(SO, "AttributeIOR")
anIOR.SetValue(SM_IOR) anIOR.SetValue(SM_IOR)
return SO.GetID() return SO.GetID()
return None return None
#------------------------------------------------------------ #------------------------------------------------------------
def AddSubMeshOnShape (Mesh_Entry, GeomShape_Entry, SM_IOR, ST) : def AddSubMeshOnShape (Mesh_Entry, GeomShape_Entry, SM_IOR, ST) :
# VSR: added temporarily - objects are published automatically by the engine # VSR: added temporarily - objects are published automatically by the engine
aSO = myStudy.FindObjectIOR( SM_IOR ) aSO = myStudy.FindObjectIOR( SM_IOR )
if aSO is not None: if aSO is not None:
return aSO.GetID() return aSO.GetID()
# VSR ###################################################################### # VSR ######################################################################
SO_GeomShape = myStudy.FindObjectID( GeomShape_Entry ) SO_GeomShape = myStudy.FindObjectID( GeomShape_Entry )
if SO_GeomShape != None : if SO_GeomShape != None :
SM_Entry = AddSubMesh (Mesh_Entry,SM_IOR,ST) SM_Entry = AddSubMesh (Mesh_Entry,SM_IOR,ST)
SO_SM = myStudy.FindObjectID( SM_Entry ) SO_SM = myStudy.FindObjectID( SM_Entry )
if SO_SM != None : if SO_SM != None :
SetShape (GeomShape_Entry, SM_Entry) SetShape (GeomShape_Entry, SM_Entry)
return SM_Entry return SM_Entry
return None return None
#------------------------------------------------------------ #------------------------------------------------------------
def SetName(Entry, Name): def SetName(Entry, Name):
SO = myStudy.FindObjectID( Entry ) SO = myStudy.FindObjectID( Entry )
if SO != None : if SO != None :
aName = myStudyBuilder.FindOrCreateAttribute(SO, "AttributeName") aName = myStudyBuilder.FindOrCreateAttribute(SO, "AttributeName")
aName.SetValue(Name) aName.SetValue(Name)

View File

@ -82,8 +82,8 @@ del pluginName
# export the methods of smeshBuilder # export the methods of smeshBuilder
if smesh: if smesh:
for k in dir( smesh ): for k in dir( smesh ):
if k[0] == '_': continue if k[0] == '_': continue
globals()[k] = getattr( smesh, k ) globals()[k] = getattr( smesh, k )
del k del k
pass pass

View File

@ -374,8 +374,8 @@ class smeshBuilder(object, SMESH._objref_SMESH_Gen):
global created global created
#print "--------------- smeshbuilder __init__ ---", created #print "--------------- smeshbuilder __init__ ---", created
if not created: if not created:
created = True created = True
SMESH._objref_SMESH_Gen.__init__(self) SMESH._objref_SMESH_Gen.__init__(self)
## Dump component to the Python script ## Dump component to the Python script
# This method overrides IDL function to allow default values for the parameters. # This method overrides IDL function to allow default values for the parameters.
@ -1195,7 +1195,7 @@ def New( study, instance=None):
global doLcc global doLcc
engine = instance engine = instance
if engine is None: if engine is None:
doLcc = True doLcc = True
smeshInst = smeshBuilder() smeshInst = smeshBuilder()
assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__ assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
smeshInst.init_smesh(study) smeshInst.init_smesh(study)
@ -2152,7 +2152,7 @@ class Mesh:
# @return an instance of SMESH_Group # @return an instance of SMESH_Group
# @ingroup l2_grps_operon # @ingroup l2_grps_operon
def UnionListOfGroups(self, groups, name): def UnionListOfGroups(self, groups, name):
return self.mesh.UnionListOfGroups(groups, name) return self.mesh.UnionListOfGroups(groups, name)
## Prodice an intersection of two groups. ## Prodice an intersection of two groups.
# A new group is created. All mesh elements that are common # A new group is created. All mesh elements that are common
@ -2168,7 +2168,7 @@ class Mesh:
# @return an instance of SMESH_Group # @return an instance of SMESH_Group
# @ingroup l2_grps_operon # @ingroup l2_grps_operon
def IntersectListOfGroups(self, groups, name): def IntersectListOfGroups(self, groups, name):
return self.mesh.IntersectListOfGroups(groups, name) return self.mesh.IntersectListOfGroups(groups, name)
## Produce a cut of two groups. ## Produce a cut of two groups.
# A new group is created. All mesh elements that are present in # A new group is created. All mesh elements that are present in
@ -4406,9 +4406,9 @@ class Mesh:
if ( isinstance( thePoint, list )): if ( isinstance( thePoint, list )):
thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] ) thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
if ( isinstance( theScaleFact, float )): if ( isinstance( theScaleFact, float )):
theScaleFact = [theScaleFact] theScaleFact = [theScaleFact]
if ( isinstance( theScaleFact, int )): if ( isinstance( theScaleFact, int )):
theScaleFact = [ float(theScaleFact)] theScaleFact = [ float(theScaleFact)]
self.mesh.SetParameters(thePoint.parameters) self.mesh.SetParameters(thePoint.parameters)
@ -4434,9 +4434,9 @@ class Mesh:
if ( isinstance( thePoint, list )): if ( isinstance( thePoint, list )):
thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] ) thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
if ( isinstance( theScaleFact, float )): if ( isinstance( theScaleFact, float )):
theScaleFact = [theScaleFact] theScaleFact = [theScaleFact]
if ( isinstance( theScaleFact, int )): if ( isinstance( theScaleFact, int )):
theScaleFact = [ float(theScaleFact)] theScaleFact = [ float(theScaleFact)]
self.mesh.SetParameters(thePoint.parameters) self.mesh.SetParameters(thePoint.parameters)
mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact, mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
@ -4892,7 +4892,7 @@ class Mesh:
# @return TRUE if operation has been completed successfully, FALSE otherwise # @return TRUE if operation has been completed successfully, FALSE otherwise
# @ingroup l2_modif_duplicat # @ingroup l2_modif_duplicat
def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ): def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries ) return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
## Double nodes on some external faces and create flat elements. ## Double nodes on some external faces and create flat elements.
# Flat elements are mainly used by some types of mechanic calculations. # Flat elements are mainly used by some types of mechanic calculations.
@ -5276,8 +5276,8 @@ for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
try: try:
exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName)) exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
except Exception, e: except Exception, e:
from salome_utils import verbose from salome_utils import verbose
if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e ) if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
continue continue
exec( "from salome.%s import %s" % (pluginName, pluginBuilderName)) exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
plugin = eval( pluginBuilderName ) plugin = eval( pluginBuilderName )

View File

@ -18,12 +18,11 @@
# #
def Message (code) : def Message (code) :
import sys import sys
MessageString = { 1 : lambda x: "Successfully created \n", MessageString = { 1 : lambda x: "Successfully created \n",
2 : lambda x: "Fatal: Incorrect input \n", 2 : lambda x: "Fatal: Incorrect input \n",
3 : lambda x: "Fatal: Overlapping objects detected \n", 3 : lambda x: "Fatal: Overlapping objects detected \n",
4 : lambda x: "Fatal: Incompatible object type with neighbouring objects" }[code](str(code)) 4 : lambda x: "Fatal: Incompatible object type with neighbouring objects" }[code](str(code))
print MessageString print MessageString
#if code > 1 : sys.exit() #if code > 1 : sys.exit()
return 1 return 1

View File

@ -33,155 +33,155 @@ import Config, GenFunctions
def CentralUnrefine (X0 , Y0 , DX , DY , Orientation, **args ) : def CentralUnrefine (X0 , Y0 , DX , DY , Orientation, **args ) :
DirPar = {'SN' : lambda : ['NW', 'NE', 'EW', 'NW', 'SN', 'SN', 'NE', 'WE'], DirPar = {'SN' : lambda : ['NW', 'NE', 'EW', 'NW', 'SN', 'SN', 'NE', 'WE'],
'NS' : lambda : ['SE', 'SW', 'WE', 'SE', 'NS', 'NS', 'SW', 'EW'], 'NS' : lambda : ['SE', 'SW', 'WE', 'SE', 'NS', 'NS', 'SW', 'EW'],
'EW' : lambda : ['NW', 'SW', 'SN', 'NW', 'EW', 'EW', 'SW', 'NS'], 'EW' : lambda : ['NW', 'SW', 'SN', 'NW', 'EW', 'EW', 'SW', 'NS'],
'WE' : lambda : ['SE', 'NE', 'NS', 'SE', 'WE', 'WE', 'NE', 'SN'], }[Orientation]() 'WE' : lambda : ['SE', 'NE', 'NS', 'SE', 'WE', 'WE', 'NE', 'SN'], }[Orientation]()
CoefVer = {'SN' : lambda : 1., CoefVer = {'SN' : lambda : 1.,
'NS' : lambda : -1., 'NS' : lambda : -1.,
'EW' : lambda : 0., 'EW' : lambda : 0.,
'WE' : lambda : 0., }[Orientation]() 'WE' : lambda : 0., }[Orientation]()
CoefHor = {'SN' : lambda : 0., CoefHor = {'SN' : lambda : 0.,
'NS' : lambda : 0., 'NS' : lambda : 0.,
'EW' : lambda : -1., 'EW' : lambda : -1.,
'WE' : lambda : 1., }[Orientation]() 'WE' : lambda : 1., }[Orientation]()
MacObject('CompBoxF',[(X0+CoefHor*DX/2,Y0+CoefVer*DY/2),(DX,DY)],['auto'],publish=0) MacObject('CompBoxF',[(X0+CoefHor*DX/2,Y0+CoefVer*DY/2),(DX,DY)],['auto'],publish=0)
ToLook1 = {'SN' : lambda : 2, ToLook1 = {'SN' : lambda : 2,
'NS' : lambda : 3, 'NS' : lambda : 3,
'EW' : lambda : 1, 'EW' : lambda : 1,
'WE' : lambda : 0, }[Orientation]() 'WE' : lambda : 0, }[Orientation]()
ToLook2 = {'SN' : lambda : 0, ToLook2 = {'SN' : lambda : 0,
'NS' : lambda : 0, 'NS' : lambda : 0,
'EW' : lambda : 2, 'EW' : lambda : 2,
'WE' : lambda : 2, }[Orientation]() 'WE' : lambda : 2, }[Orientation]()
ToLook3 = {'SN' : lambda : [0,1,2,3], ToLook3 = {'SN' : lambda : [0,1,2,3],
'NS' : lambda : [1,0,3,2], 'NS' : lambda : [1,0,3,2],
'EW' : lambda : [3,2,1,0], 'EW' : lambda : [3,2,1,0],
'WE' : lambda : [2,3,0,1], }[Orientation]() 'WE' : lambda : [2,3,0,1], }[Orientation]()
if args.__contains__('groups') : if args.__contains__('groups') :
GroupNames = args['groups'] GroupNames = args['groups']
else : GroupNames = [None, None, None, None, None, None] else : GroupNames = [None, None, None, None, None, None]
ExistingSegments = Config.ListObj[-1].DirectionalMeshParams[ToLook1] ExistingSegments = Config.ListObj[-1].DirectionalMeshParams[ToLook1]
ObjIDs = Config.Connections[-1][ToLook1] ObjIDs = Config.Connections[-1][ToLook1]
RemoveLastObj() RemoveLastObj()
ExtensionSegments = math.ceil(ExistingSegments/12.)*12. ExtensionSegments = math.ceil(ExistingSegments/12.)*12.
Dmin = 1.E50 Dmin = 1.E50
Dmax = -1.E50 Dmax = -1.E50
for ObjID in ObjIDs : for ObjID in ObjIDs :
Boundaries = Config.ListObj[ObjID].Boundaries() Boundaries = Config.ListObj[ObjID].Boundaries()
if Boundaries[ToLook2] < Dmin : Dmin = Boundaries[ToLook2] if Boundaries[ToLook2] < Dmin : Dmin = Boundaries[ToLook2]
if Boundaries[ToLook2+1] > Dmax : Dmax = Boundaries[ToLook2+1] if Boundaries[ToLook2+1] > Dmax : Dmax = Boundaries[ToLook2+1]
dx = 0 dx = 0
if ExtensionSegments > ExistingSegments : if ExtensionSegments > ExistingSegments :
dn = (ExtensionSegments-ExistingSegments)/2. dn = (ExtensionSegments-ExistingSegments)/2.
dx = dn*(Dmax-Dmin)/ExistingSegments dx = dn*(Dmax-Dmin)/ExistingSegments
#MacObject('CompBoxF',[(X0-CoefHor*dx/2+CoefVer*(-X0+Dmin-dx/2),Y0-CoefVer*dx/2+CoefHor*(-Y0+Dmin-dx/2)),(dx,dx)],[(dn,dn)],publish=0) #MacObject('CompBoxF',[(X0-CoefHor*dx/2+CoefVer*(-X0+Dmin-dx/2),Y0-CoefVer*dx/2+CoefHor*(-Y0+Dmin-dx/2)),(dx,dx)],[(dn,dn)],publish=0)
#MacObject('CompBoxF',[(X0-CoefHor*dx/2+CoefVer*(-X0+Dmax+dx/2),Y0-CoefVer*dx/2+CoefHor*(-Y0+Dmax+dx/2)),(dx,dx)],[(dn,dn)],publish=0) #MacObject('CompBoxF',[(X0-CoefHor*dx/2+CoefVer*(-X0+Dmax+dx/2),Y0-CoefVer*dx/2+CoefHor*(-Y0+Dmax+dx/2)),(dx,dx)],[(dn,dn)],publish=0)
BoxSide = (Dmax-Dmin+2*dx)/2. BoxSide = (Dmax-Dmin+2*dx)/2.
Obj = [] Obj = []
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(BoxSide/2)+CoefVer*(-BoxSide/2),Y0+CoefVer*(BoxSide/2)+CoefHor*(-BoxSide/2)),(BoxSide,BoxSide)],[int(ExtensionSegments/6),DirPar[0]],groups=GroupArray(ToLook3[0],GroupNames[0]))) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(BoxSide/2)+CoefVer*(-BoxSide/2),Y0+CoefVer*(BoxSide/2)+CoefHor*(-BoxSide/2)),(BoxSide,BoxSide)],[int(ExtensionSegments/6),DirPar[0]],groups=GroupArray(ToLook3[0],GroupNames[0])))
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(BoxSide/2)+CoefVer*(BoxSide/2),Y0+CoefVer*(BoxSide/2)+CoefHor*(BoxSide/2)),(BoxSide,BoxSide)],[int(ExtensionSegments/6),DirPar[1]],groups=GroupArray(ToLook3[0],GroupNames[0]))) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(BoxSide/2)+CoefVer*(BoxSide/2),Y0+CoefVer*(BoxSide/2)+CoefHor*(BoxSide/2)),(BoxSide,BoxSide)],[int(ExtensionSegments/6),DirPar[1]],groups=GroupArray(ToLook3[0],GroupNames[0])))
NLevOpt = 0 NLevOpt = 0
for NLevels in range (1,100) : for NLevels in range (1,100) :
DX1 = abs(CoefVer)*BoxSide*2.**(NLevels+1)+abs(CoefHor)*BoxSide*2.**(NLevels) DX1 = abs(CoefVer)*BoxSide*2.**(NLevels+1)+abs(CoefHor)*BoxSide*2.**(NLevels)
DY1 = abs(CoefHor)*BoxSide*2.**(NLevels+1)+abs(CoefVer)*BoxSide*2.**(NLevels) DY1 = abs(CoefHor)*BoxSide*2.**(NLevels+1)+abs(CoefVer)*BoxSide*2.**(NLevels)
if DX1 > DX or DY1 > DY : if DX1 > DX or DY1 > DY :
NLevOpt = NLevels-1 NLevOpt = NLevels-1
DXinner = DX1/2. DXinner = DX1/2.
DYinner = DY1/2. DYinner = DY1/2.
break break
dummyArray = [DXinner,DYinner,DYinner,DXinner] dummyArray = [DXinner,DYinner,DYinner,DXinner]
D1inner = dummyArray[ToLook2] # = DXinner for SN and NS orientations D1inner = dummyArray[ToLook2] # = DXinner for SN and NS orientations
D2inner = dummyArray[ToLook2+1] # = DYinner for SN and NS orientations D2inner = dummyArray[ToLook2+1] # = DYinner for SN and NS orientations
dummyArray = [DX,DY,DY,DX] dummyArray = [DX,DY,DY,DX]
D1 = dummyArray[ToLook2] # = DX for SN and NS orientations D1 = dummyArray[ToLook2] # = DX for SN and NS orientations
D2 = dummyArray[ToLook2+1] # = DY for SN and NS orientations D2 = dummyArray[ToLook2+1] # = DY for SN and NS orientations
if D1inner < D1 : if D1inner < D1 :
GN0a = GroupArray(ToLook3[0],GroupNames[1]) GN0a = GroupArray(ToLook3[0],GroupNames[1])
GN0b = GroupArray(ToLook3[0],GroupNames[2]) GN0b = GroupArray(ToLook3[0],GroupNames[2])
GN01 = GroupArray(ToLook3[0],GroupNames[1]) GN01 = GroupArray(ToLook3[0],GroupNames[1])
GN02 = GroupArray(ToLook3[0],GroupNames[2]) GN02 = GroupArray(ToLook3[0],GroupNames[2])
if D2inner < D2 : if D2inner < D2 :
GN10 = [None,None,None,None] GN10 = [None,None,None,None]
GN11 = [None,None,None,None] GN11 = [None,None,None,None]
GN20 = [None,None,None,None] GN20 = [None,None,None,None]
else :
GN10 = GroupArray(ToLook3[1],GroupNames[3])
GN11 = GroupArray(ToLook3[1],GroupNames[3])
GN20 = GroupArray(ToLook3[1],GroupNames[3])
else : else :
GN0a = GroupArray(ToLook3[0],GroupNames[1]) GN10 = GroupArray(ToLook3[1],GroupNames[3])
GN0b = GroupArray(ToLook3[0],GroupNames[2]) GN11 = GroupArray(ToLook3[1],GroupNames[3])
GN01 = GroupArray([ToLook3[0],ToLook3[2]],[GroupNames[1],GroupNames[4]]) GN20 = GroupArray(ToLook3[1],GroupNames[3])
GN02 = GroupArray([ToLook3[0],ToLook3[3]],[GroupNames[2],GroupNames[5]]) else :
if D2inner < D2 : GN0a = GroupArray(ToLook3[0],GroupNames[1])
GN10 = GroupArray(ToLook3[2],GroupNames[4]) GN0b = GroupArray(ToLook3[0],GroupNames[2])
GN11 = GroupArray(ToLook3[3],GroupNames[5]) GN01 = GroupArray([ToLook3[0],ToLook3[2]],[GroupNames[1],GroupNames[4]])
GN20 = [None,None,None,None] GN02 = GroupArray([ToLook3[0],ToLook3[3]],[GroupNames[2],GroupNames[5]])
else : if D2inner < D2 :
GN10 = GroupArray([ToLook3[1],ToLook3[2]],[GroupNames[3],GroupNames[4]]) GN10 = GroupArray(ToLook3[2],GroupNames[4])
GN11 = GroupArray([ToLook3[1],ToLook3[3]],[GroupNames[3],GroupNames[5]]) GN11 = GroupArray(ToLook3[3],GroupNames[5])
GN20 = GroupArray(ToLook3[1],GroupNames[3]) GN20 = [None,None,None,None]
else :
GN10 = GroupArray([ToLook3[1],ToLook3[2]],[GroupNames[3],GroupNames[4]])
GN11 = GroupArray([ToLook3[1],ToLook3[3]],[GroupNames[3],GroupNames[5]])
GN20 = GroupArray(ToLook3[1],GroupNames[3])
for N in range (1,NLevOpt+1): for N in range (1,NLevOpt+1):
n=N-1 n=N-1
D = BoxSide*(2.**n) D = BoxSide*(2.**n)
if N < NLevOpt : if N < NLevOpt :
Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*1/2-CoefVer*3/2) , Y0+D*(CoefVer*1/2-CoefHor*3/2) ) , (D,D)],['auto',DirPar[2]], groups=GN0a)) Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*1/2-CoefVer*3/2) , Y0+D*(CoefVer*1/2-CoefHor*3/2) ) , (D,D)],['auto',DirPar[2]], groups=GN0a))
Obj.append(MacObject('BoxAng32',[(X0+D*(CoefHor*3/2-CoefVer*3/2) , Y0+D*(CoefVer*3/2-CoefHor*3/2) ) , (D,D)],['auto',DirPar[3]])) Obj.append(MacObject('BoxAng32',[(X0+D*(CoefHor*3/2-CoefVer*3/2) , Y0+D*(CoefVer*3/2-CoefHor*3/2) ) , (D,D)],['auto',DirPar[3]]))
Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*3/2-CoefVer*1/2) , Y0+D*(CoefVer*3/2-CoefHor*1/2) ) , (D,D)],['auto',DirPar[4]])) Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*3/2-CoefVer*1/2) , Y0+D*(CoefVer*3/2-CoefHor*1/2) ) , (D,D)],['auto',DirPar[4]]))
Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*3/2+CoefVer*1/2) , Y0+D*(CoefHor*1/2+CoefVer*3/2) ) , (D,D)],['auto',DirPar[5]])) Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*3/2+CoefVer*1/2) , Y0+D*(CoefHor*1/2+CoefVer*3/2) ) , (D,D)],['auto',DirPar[5]]))
Obj.append(MacObject('BoxAng32',[(X0+D*(CoefVer*3/2+CoefHor*3/2) , Y0+D*(CoefVer*3/2+CoefHor*3/2) ) , (D,D)],['auto',DirPar[6]])) Obj.append(MacObject('BoxAng32',[(X0+D*(CoefVer*3/2+CoefHor*3/2) , Y0+D*(CoefVer*3/2+CoefHor*3/2) ) , (D,D)],['auto',DirPar[6]]))
Obj.append(MacObject('Box42' ,[(X0+D*(CoefVer*3/2+CoefHor*1/2) , Y0+D*(CoefHor*3/2+CoefVer*1/2) ) , (D,D)],['auto',DirPar[7]], groups=GN0b)) Obj.append(MacObject('Box42' ,[(X0+D*(CoefVer*3/2+CoefHor*1/2) , Y0+D*(CoefHor*3/2+CoefVer*1/2) ) , (D,D)],['auto',DirPar[7]], groups=GN0b))
else : else :
Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*1/2-CoefVer*3/2) , Y0+D*(CoefVer*1/2-CoefHor*3/2) ) , (D,D)],['auto',DirPar[2]], groups=GN01)) Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*1/2-CoefVer*3/2) , Y0+D*(CoefVer*1/2-CoefHor*3/2) ) , (D,D)],['auto',DirPar[2]], groups=GN01))
Obj.append(MacObject('BoxAng32',[(X0+D*(CoefHor*3/2-CoefVer*3/2) , Y0+D*(CoefVer*3/2-CoefHor*3/2) ) , (D,D)],['auto',DirPar[3]], groups=GN10)) Obj.append(MacObject('BoxAng32',[(X0+D*(CoefHor*3/2-CoefVer*3/2) , Y0+D*(CoefVer*3/2-CoefHor*3/2) ) , (D,D)],['auto',DirPar[3]], groups=GN10))
Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*3/2-CoefVer*1/2) , Y0+D*(CoefVer*3/2-CoefHor*1/2) ) , (D,D)],['auto',DirPar[4]], groups=GN20)) Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*3/2-CoefVer*1/2) , Y0+D*(CoefVer*3/2-CoefHor*1/2) ) , (D,D)],['auto',DirPar[4]], groups=GN20))
Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*3/2+CoefVer*1/2) , Y0+D*(CoefHor*1/2+CoefVer*3/2) ) , (D,D)],['auto',DirPar[5]], groups=GN20)) Obj.append(MacObject('Box42' ,[(X0+D*(CoefHor*3/2+CoefVer*1/2) , Y0+D*(CoefHor*1/2+CoefVer*3/2) ) , (D,D)],['auto',DirPar[5]], groups=GN20))
Obj.append(MacObject('BoxAng32',[(X0+D*(CoefVer*3/2+CoefHor*3/2) , Y0+D*(CoefVer*3/2+CoefHor*3/2) ) , (D,D)],['auto',DirPar[6]], groups=GN11)) Obj.append(MacObject('BoxAng32',[(X0+D*(CoefVer*3/2+CoefHor*3/2) , Y0+D*(CoefVer*3/2+CoefHor*3/2) ) , (D,D)],['auto',DirPar[6]], groups=GN11))
Obj.append(MacObject('Box42' ,[(X0+D*(CoefVer*3/2+CoefHor*1/2) , Y0+D*(CoefHor*3/2+CoefVer*1/2) ) , (D,D)],['auto',DirPar[7]], groups=GN02)) Obj.append(MacObject('Box42' ,[(X0+D*(CoefVer*3/2+CoefHor*1/2) , Y0+D*(CoefHor*3/2+CoefVer*1/2) ) , (D,D)],['auto',DirPar[7]], groups=GN02))
if CoefVer and DX>DXinner : if CoefVer and DX>DXinner :
Obj.append(MacObject('CompBoxF',[(X0-CoefVer*0.25*(DX+DXinner),Y0+CoefVer*DYinner/2),((DX-DXinner)/2,DYinner)],['auto'], groups = GroupArray([ToLook3[0],ToLook3[2]],[GroupNames[1],GroupNames[4]]))) Obj.append(MacObject('CompBoxF',[(X0-CoefVer*0.25*(DX+DXinner),Y0+CoefVer*DYinner/2),((DX-DXinner)/2,DYinner)],['auto'], groups = GroupArray([ToLook3[0],ToLook3[2]],[GroupNames[1],GroupNames[4]])))
Obj.append(MacObject('CompBoxF',[(X0+CoefVer*0.25*(DX+DXinner),Y0+CoefVer*DYinner/2),((DX-DXinner)/2,DYinner)],['auto'], groups = GroupArray([ToLook3[0],ToLook3[3]],[GroupNames[2],GroupNames[5]]))) Obj.append(MacObject('CompBoxF',[(X0+CoefVer*0.25*(DX+DXinner),Y0+CoefVer*DYinner/2),((DX-DXinner)/2,DYinner)],['auto'], groups = GroupArray([ToLook3[0],ToLook3[3]],[GroupNames[2],GroupNames[5]])))
if DY>DYinner : if DY>DYinner :
Obj.append(MacObject('CompBoxF',[(X0-CoefVer*0.25*(DX+DXinner),Y0+CoefVer*(DY+DYinner)/2.),((DX-DXinner)/2,DY-DYinner)],['auto'], groups = GroupArray([ToLook3[1],ToLook3[2]],[GroupNames[3],GroupNames[4]]))) Obj.append(MacObject('CompBoxF',[(X0-CoefVer*0.25*(DX+DXinner),Y0+CoefVer*(DY+DYinner)/2.),((DX-DXinner)/2,DY-DYinner)],['auto'], groups = GroupArray([ToLook3[1],ToLook3[2]],[GroupNames[3],GroupNames[4]])))
Obj.append(MacObject('CompBoxF',[(X0+CoefVer*0.25*(DX+DXinner),Y0+CoefVer*(DY+DYinner)/2.),((DX-DXinner)/2,DY-DYinner)],['auto'], groups = GroupArray([ToLook3[1],ToLook3[3]],[GroupNames[3],GroupNames[5]]))) Obj.append(MacObject('CompBoxF',[(X0+CoefVer*0.25*(DX+DXinner),Y0+CoefVer*(DY+DYinner)/2.),((DX-DXinner)/2,DY-DYinner)],['auto'], groups = GroupArray([ToLook3[1],ToLook3[3]],[GroupNames[3],GroupNames[5]])))
Obj.append(MacObject('CompBoxF',[(X0,Y0+CoefVer*(DY+DYinner)/2.),(DXinner,DY-DYinner)],['auto'], groups = GroupArray(ToLook3[1],GroupNames[3]))) Obj.append(MacObject('CompBoxF',[(X0,Y0+CoefVer*(DY+DYinner)/2.),(DXinner,DY-DYinner)],['auto'], groups = GroupArray(ToLook3[1],GroupNames[3])))
elif CoefHor and DY>DYinner : elif CoefHor and DY>DYinner :
Obj.append(MacObject('CompBoxF',[(X0+CoefHor*DXinner/2,Y0-CoefHor*0.25*(DY+DYinner)),(DXinner,(DY-DYinner)/2)],['auto'], groups = GroupArray([ToLook3[0],ToLook3[2]],[GroupNames[1],GroupNames[4]]))) Obj.append(MacObject('CompBoxF',[(X0+CoefHor*DXinner/2,Y0-CoefHor*0.25*(DY+DYinner)),(DXinner,(DY-DYinner)/2)],['auto'], groups = GroupArray([ToLook3[0],ToLook3[2]],[GroupNames[1],GroupNames[4]])))
Obj.append(MacObject('CompBoxF',[(X0+CoefHor*DXinner/2,Y0+CoefHor*0.25*(DY+DYinner)),(DXinner,(DY-DYinner)/2)],['auto'], groups = GroupArray([ToLook3[0],ToLook3[3]],[GroupNames[2],GroupNames[5]]))) Obj.append(MacObject('CompBoxF',[(X0+CoefHor*DXinner/2,Y0+CoefHor*0.25*(DY+DYinner)),(DXinner,(DY-DYinner)/2)],['auto'], groups = GroupArray([ToLook3[0],ToLook3[3]],[GroupNames[2],GroupNames[5]])))
if DX>DXinner : if DX>DXinner :
Obj.append(MacObject('CompBoxF',[(X0+CoefHor*(DX+DXinner)/2.,Y0-CoefHor*0.25*(DY+DYinner)),(DX-DXinner,(DY-DYinner)/2)],['auto'], groups = GroupArray([ToLook3[1],ToLook3[2]],[GroupNames[3],GroupNames[4]]))) Obj.append(MacObject('CompBoxF',[(X0+CoefHor*(DX+DXinner)/2.,Y0-CoefHor*0.25*(DY+DYinner)),(DX-DXinner,(DY-DYinner)/2)],['auto'], groups = GroupArray([ToLook3[1],ToLook3[2]],[GroupNames[3],GroupNames[4]])))
Obj.append(MacObject('CompBoxF',[(X0+CoefHor*(DX+DXinner)/2.,Y0+CoefHor*0.25*(DY+DYinner)),(DX-DXinner,(DY-DYinner)/2)],['auto'], groups = GroupArray([ToLook3[1],ToLook3[3]],[GroupNames[3],GroupNames[5]]))) Obj.append(MacObject('CompBoxF',[(X0+CoefHor*(DX+DXinner)/2.,Y0+CoefHor*0.25*(DY+DYinner)),(DX-DXinner,(DY-DYinner)/2)],['auto'], groups = GroupArray([ToLook3[1],ToLook3[3]],[GroupNames[3],GroupNames[5]])))
Obj.append(MacObject('CompBoxF',[(X0+CoefHor*(DX+DXinner)/2.,Y0),(DX-DXinner,DYinner)],['auto'], groups = GroupArray(ToLook3[1],GroupNames[3]))) Obj.append(MacObject('CompBoxF',[(X0+CoefHor*(DX+DXinner)/2.,Y0),(DX-DXinner,DYinner)],['auto'], groups = GroupArray(ToLook3[1],GroupNames[3])))
return Obj return Obj
def RemoveLastObj() : def RemoveLastObj() :
Config.ListObj = Config.ListObj[:-1] Config.ListObj = Config.ListObj[:-1]
Config.Connections = Config.Connections[:-1] Config.Connections = Config.Connections[:-1]
def GroupArray(indices, GroupNames) : def GroupArray(indices, GroupNames) :
if type(indices) is int : if type(indices) is int :
indices = [indices] indices = [indices]
GroupNames = [GroupNames] GroupNames = [GroupNames]
Output = [None,None,None,None] Output = [None,None,None,None]
for i, ind in enumerate(indices) : for i, ind in enumerate(indices) :
Output[ind] = GroupNames[i] Output[ind] = GroupNames[i]
return Output return Output

View File

@ -29,157 +29,154 @@ import Config, GenFunctions
def CompositeBox (X0 , Y0 , DX , DY , **args ) : def CompositeBox (X0 , Y0 , DX , DY , **args ) :
if args.__contains__('groups') : if args.__contains__('groups') :
GroupNames = args['groups'] GroupNames = args['groups']
else : GroupNames = [None, None, None, None] else : GroupNames = [None, None, None, None]
# Create a full Box just to inherit, globally, the mesh parameters of bounding objects # Create a full Box just to inherit, globally, the mesh parameters of bounding objects
MacObject('CompBoxF',[(X0,Y0),(DX,DY)],['auto'],publish=0) MacObject('CompBoxF',[(X0,Y0),(DX,DY)],['auto'],publish=0)
# Save the existing number of segments on each direction # Save the existing number of segments on each direction
ExistingSegments = Config.ListObj[-1].DirectionalMeshParams ExistingSegments = Config.ListObj[-1].DirectionalMeshParams
# Sort the connection list for the full Box # Sort the connection list for the full Box
ObjIDLists = SortObjLists(Config.Connections[-1],X0 , Y0 , DX , DY ) ObjIDLists = SortObjLists(Config.Connections[-1],X0 , Y0 , DX , DY )
RemoveLastObj() RemoveLastObj()
print "ObjIDLists: ", ObjIDLists print "ObjIDLists: ", ObjIDLists
RealSegments = [] RealSegments = []
Direction = [] Direction = []
flag = 0 flag = 0
if not(args.__contains__('recursive')) : Config.Count = 0 if not(args.__contains__('recursive')) : Config.Count = 0
print "Config.Count : ", Config.Count print "Config.Count : ", Config.Count
Config.Criterion = GetCriterion(ObjIDLists) Config.Criterion = GetCriterion(ObjIDLists)
for index, ObjList in enumerate(ObjIDLists) : for index, ObjList in enumerate(ObjIDLists) :
if not (ObjList[0] == -1 or Config.Count >= Config.Criterion): if not (ObjList[0] == -1 or Config.Count >= Config.Criterion):
if len(ObjList)>1 : flag = 1 if len(ObjList)>1 : flag = 1
else : flag = 0 else : flag = 0
for ObjID in ObjList: for ObjID in ObjList:
ToLook0 = [2,2,0,0][index] ToLook0 = [2,2,0,0][index]
ToLook1 = [3,2,1,0][index] ToLook1 = [3,2,1,0][index]
CommonSide = FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2]) CommonSide = FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2])
ToLook2 = [1,0,3,2][index] ToLook2 = [1,0,3,2][index]
RealSegments.append(Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]*IntLen(CommonSide)/IntLen(Config.ListObj[ObjID].DirBoundaries(ToLook1))) RealSegments.append(Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]*IntLen(CommonSide)/IntLen(Config.ListObj[ObjID].DirBoundaries(ToLook1)))
Direction.append(ToLook0/2) Direction.append(ToLook0/2)
if flag and Config.Count < Config.Criterion: if flag and Config.Count < Config.Criterion:
if index < 2 : if index < 2 :
if abs(CommonSide[0] - (Y0-DY/2.))<1e-7 : SouthGR = GroupNames[0] if abs(CommonSide[0] - (Y0-DY/2.))<1e-7 : SouthGR = GroupNames[0]
else : SouthGR = None else : SouthGR = None
if abs(CommonSide[1] - (Y0+DY/2.))<1e-7 : NorthGR = GroupNames[1] if abs(CommonSide[1] - (Y0+DY/2.))<1e-7 : NorthGR = GroupNames[1]
else : NorthGR = None else : NorthGR = None
CompositeBox (X0, CommonSide[0]+IntLen(CommonSide)/2., DX,IntLen(CommonSide), recursive=1, groups = [SouthGR,NorthGR]+GroupNames[2:4]) CompositeBox (X0, CommonSide[0]+IntLen(CommonSide)/2., DX,IntLen(CommonSide), recursive=1, groups = [SouthGR,NorthGR]+GroupNames[2:4])
else : else :
if abs(CommonSide[0] - (X0-DX/2.))<1e-7 : EastGR = GroupNames[2] if abs(CommonSide[0] - (X0-DX/2.))<1e-7 : EastGR = GroupNames[2]
else : EastGR = None else : EastGR = None
if abs(CommonSide[1] - (X0+DX/2.))<1e-7 : WestGR = GroupNames[3] if abs(CommonSide[1] - (X0+DX/2.))<1e-7 : WestGR = GroupNames[3]
else : WestGR = None else : WestGR = None
CompositeBox (CommonSide[0]+IntLen(CommonSide)/2., Y0, IntLen(CommonSide),DY, recursive=1, groups = GroupNames[0:2]+[EastGR,WestGR]) CompositeBox (CommonSide[0]+IntLen(CommonSide)/2., Y0, IntLen(CommonSide),DY, recursive=1, groups = GroupNames[0:2]+[EastGR,WestGR])
if Config.Count >= Config.Criterion : if Config.Count >= Config.Criterion :
break break
if flag == 0 and Config.Count < Config.Criterion: if flag == 0 and Config.Count < Config.Criterion:
#print "Dir : ", Direction #print "Dir : ", Direction
#print "RealSegments : ", RealSegments #print "RealSegments : ", RealSegments
#Xind = Direction.index(0) #Xind = Direction.index(0)
#Yind = Direction.index(1) #Yind = Direction.index(1)
#MacObject('CompBoxF',[(X0,Y0),(DX,DY)] ,[(RealSegments[Xind],RealSegments[Yind])], groups = GroupNames) #MacObject('CompBoxF',[(X0,Y0),(DX,DY)] ,[(RealSegments[Xind],RealSegments[Yind])], groups = GroupNames)
MacObject('CompBoxF',[(X0,Y0),(DX,DY)] ,['auto'], groups = GroupNames) MacObject('CompBoxF',[(X0,Y0),(DX,DY)] ,['auto'], groups = GroupNames)
Config.Count += 1 Config.Count += 1
def FindCommonSide (Int1, Int2) : def FindCommonSide (Int1, Int2) :
if abs(min(Int1[1],Int2[1])-max(Int1[0],Int2[0])) < 1e-5: return [0,0] if abs(min(Int1[1],Int2[1])-max(Int1[0],Int2[0])) < 1e-5: return [0,0]
else : return [max(Int1[0],Int2[0]), min(Int1[1],Int2[1])] else : return [max(Int1[0],Int2[0]), min(Int1[1],Int2[1])]
def IntLen (Interval) : def IntLen (Interval) :
return abs(Interval[1]-Interval[0]) return abs(Interval[1]-Interval[0])
def RemoveLastObj() : def RemoveLastObj() :
Config.ListObj = Config.ListObj[:-1] Config.ListObj = Config.ListObj[:-1]
Config.Connections = Config.Connections[:-1] Config.Connections = Config.Connections[:-1]
def GetCriterion (ObjListIDs): def GetCriterion (ObjListIDs):
return max(Config.Criterion, max(len(ObjListIDs[0]),len(ObjListIDs[1]))*max(len(ObjListIDs[2]),len(ObjListIDs[3]))) return max(Config.Criterion, max(len(ObjListIDs[0]),len(ObjListIDs[1]))*max(len(ObjListIDs[2]),len(ObjListIDs[3])))
def SortObjLists (List,X0,Y0,DX,DY) : def SortObjLists (List,X0,Y0,DX,DY) :
""" """
This function sorts the list of neighbouring objects on each side, according to their intersection This function sorts the list of neighbouring objects on each side, according to their intersection
with the object being created. From South to North and from East to West with the object being created. From South to North and from East to West
""" """
Output = List Output = List
# First find the directions where no neighbour exists # First find the directions where no neighbour exists
# Important : Here we assume that exactly two directions have no neighbours !!! # Important : Here we assume that exactly two directions have no neighbours !!!
# Should we change this to allow a more general case ???? # Should we change this to allow a more general case ????
dummy = IndexMultiOcc(List,(-1,)) dummy = IndexMultiOcc(List,(-1,))
# dummy[0] is either 0, meaning there is no neighbour on X- (West) # dummy[0] is either 0, meaning there is no neighbour on X- (West)
# or 1, meaning there is no neighbour on X+ (East) # or 1, meaning there is no neighbour on X+ (East)
# Similarly dummy[1] can be either 2 or 3 (South and North respectively) # Similarly dummy[1] can be either 2 or 3 (South and North respectively)
# In order to get back to the formalism of groups (SNWE) # In order to get back to the formalism of groups (SNWE)
# => we do the following to define Sense of no neighbours and then the Direction list # => we do the following to define Sense of no neighbours and then the Direction list
# is calculated as to include uniquely the directions where we DO have neighbours # is calculated as to include uniquely the directions where we DO have neighbours
if len(dummy) == 1 : if len(dummy) == 1 :
# This adds a second direction where neighbours are not regarded, it is either 0 or 2 # This adds a second direction where neighbours are not regarded, it is either 0 or 2
dummy.append(2*(dummy[0]+2<4)) dummy.append(2*(dummy[0]+2<4))
print("Careful, you have neighbours on 3 or more sides of the box, we will not check if on two parallel sides the boxes are compatible !!!") print("Careful, you have neighbours on 3 or more sides of the box, we will not check if on two parallel sides the boxes are compatible !!!")
if len(dummy) == 2 or len(dummy) == 1 : if len(dummy) == 2 or len(dummy) == 1 :
# Sense contains : Vertical then Horizontal # Sense contains : Vertical then Horizontal
Sense = [dummy[1]%2,dummy[0]] Sense = [dummy[1]%2,dummy[0]]
DirList = [[1,0][dummy[0]],[3,2][dummy[1]%2]] DirList = [[1,0][dummy[0]],[3,2][dummy[1]%2]]
for index,Direction in enumerate(DirList) : for index,Direction in enumerate(DirList) :
ObjList = List[Direction] ObjList = List[Direction]
RankMin = [] RankMin = []
ToLook0 = [2,2,0,0][Direction] ToLook0 = [2,2,0,0][Direction]
ToLook1 = [3,2,1,0][Direction] ToLook1 = [3,2,1,0][Direction]
for index1,ObjID in enumerate(ObjList) : for index1,ObjID in enumerate(ObjList) :
RankMin.append([-1.,1.][Sense[index]] * FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2])[Sense[index]]) RankMin.append([-1.,1.][Sense[index]] * FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2])[Sense[index]])
Output[Direction] = SortList(ObjList,RankMin) Output[Direction] = SortList(ObjList,RankMin)
elif len(dummy) == 3 : elif len(dummy) == 3 :
# We find the direction where we do have neighbours and then we sort the object list along it # We find the direction where we do have neighbours and then we sort the object list along it
Sense = dummy[0]%2 Sense = dummy[0]%2
Direction = [ i not in dummy for i in range(4) ].index(True) Direction = [ i not in dummy for i in range(4) ].index(True)
ObjList = List[Direction] ObjList = List[Direction]
RankMin = [] RankMin = []
ToLook0 = [2,2,0,0][Direction] ToLook0 = [2,2,0,0][Direction]
ToLook1 = [3,2,1,0][Direction] ToLook1 = [3,2,1,0][Direction]
for index1,ObjID in enumerate(ObjList) : for index1,ObjID in enumerate(ObjList) :
RankMin.append([-1.,1.][Sense] * FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2])[Sense]) RankMin.append([-1.,1.][Sense] * FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2])[Sense])
Output[Direction] = SortList(ObjList,RankMin) Output[Direction] = SortList(ObjList,RankMin)
else : else :
print ("Error : the composite box being created has no neighbours, how on earth do you want us to inherit its mesh parameters!!!") print ("Error : the composite box being created has no neighbours, how on earth do you want us to inherit its mesh parameters!!!")
return Output return Output
def IndexMultiOcc (Array,Element) : def IndexMultiOcc (Array,Element) :
""" """
This functions returns the occurrences indices of Element in Array. This functions returns the occurrences indices of Element in Array.
As opposed to Array.index(Element) method, this allows determining As opposed to Array.index(Element) method, this allows determining
multiple entries rather than just the first one! multiple entries rather than just the first one!
""" """
Output = [] Output = []
try : Array.index(Element) try : Array.index(Element)
except ValueError : print "No more occurrences" except ValueError : print "No more occurrences"
else : Output.append(Array.index(Element)) else : Output.append(Array.index(Element))
if not(Output == []) and len(Array) > 1 : if not(Output == []) and len(Array) > 1 :
for index, ArrElem in enumerate(Array[Output[0]+1:]) : for index, ArrElem in enumerate(Array[Output[0]+1:]) :
if ArrElem == Element : Output.append(index+Output[0]+1) if ArrElem == Element : Output.append(index+Output[0]+1)
return Output return Output
def SortList (ValList, CritList): def SortList (ValList, CritList):
Output = [] Output = []
SortedCritList = copy.copy(CritList) SortedCritList = copy.copy(CritList)
SortedCritList.sort() SortedCritList.sort()
for i in range(0,len(ValList)): for i in range(0,len(ValList)):
index = CritList.index(SortedCritList[i]) index = CritList.index(SortedCritList[i])
Output.append(ValList[index]) Output.append(ValList[index])
return Output return Output

View File

@ -28,223 +28,222 @@ from MacObject import *
import Config, GenFunctions import Config, GenFunctions
def CompositeBoxF (Pt1 , Pt2 , Pt3 , Pt4 , **args ) : def CompositeBoxF (Pt1 , Pt2 , Pt3 , Pt4 , **args ) :
[Pt1 , Pt2 , Pt3 , Pt4] = GenFunctions.SortPoints([Pt1 , Pt2 , Pt3 , Pt4]) [Pt1 , Pt2 , Pt3 , Pt4] = GenFunctions.SortPoints([Pt1 , Pt2 , Pt3 , Pt4])
if args.__contains__('groups') : if args.__contains__('groups') :
GroupNames = args['groups'] GroupNames = args['groups']
else : GroupNames = [None, None, None, None] else : GroupNames = [None, None, None, None]
# Create a full NonOrtho box just to inherit, globally, the mesh parameters of bounding objects # Create a full NonOrtho box just to inherit, globally, the mesh parameters of bounding objects
dummy = MacObject('NonOrtho',[Pt1,Pt2,Pt3,Pt4],['auto'],publish=0) dummy = MacObject('NonOrtho',[Pt1,Pt2,Pt3,Pt4],['auto'],publish=0)
# Save the existing number of segments on each direction # Save the existing number of segments on each direction
ExistingSeg0 = Config.ListObj[-1].DirectionalMeshParams ExistingSeg0 = Config.ListObj[-1].DirectionalMeshParams
Convention = [2,3,0,1] Convention = [2,3,0,1]
ExistingSegments = [ExistingSeg0[Convention[i]] for i in range(4)] ExistingSegments = [ExistingSeg0[Convention[i]] for i in range(4)]
# Save Boundary lengths on each direction # Save Boundary lengths on each direction
BoundaryLengths = [IntLen(dummy.DirBoundaries(i)) for i in range(4) ] BoundaryLengths = [IntLen(dummy.DirBoundaries(i)) for i in range(4) ]
# Calculate global mesh element size on each direction # Calculate global mesh element size on each direction
GlobalDelta = [1.*BoundaryLengths[i]/ExistingSegments[i] for i in range(4) ] GlobalDelta = [1.*BoundaryLengths[i]/ExistingSegments[i] for i in range(4) ]
print "GlobalDelta :",GlobalDelta print "GlobalDelta :",GlobalDelta
# Sort the connection list for the full Box # Sort the connection list for the full Box
[(X0,Y0),(DX,DY)] = dummy.GeoPar [(X0,Y0),(DX,DY)] = dummy.GeoPar
ObjIDLists = SortObjLists(Config.Connections[-1],X0 , Y0 , DX , DY ) ObjIDLists = SortObjLists(Config.Connections[-1],X0 , Y0 , DX , DY )
[Xmin,Xmax,Ymin,Ymax] = dummy.Boundaries() # Used for groups determination [Xmin,Xmax,Ymin,Ymax] = dummy.Boundaries() # Used for groups determination
RemoveLastObj() RemoveLastObj()
RealSegments = [] RealSegments = []
Direction = [] Direction = []
flag = 0 flag = 0
if not(args.__contains__('recursive')) : if not(args.__contains__('recursive')) :
Config.Count = 0 Config.Count = 0
Config.Criterion = GetCriterion(ObjIDLists) Config.Criterion = GetCriterion(ObjIDLists)
for index, ObjList in enumerate(ObjIDLists) : for index, ObjList in enumerate(ObjIDLists) :
if not (ObjList[0] == -1 or Config.Count >= Config.Criterion): if not (ObjList[0] == -1 or Config.Count >= Config.Criterion):
if not(args.__contains__('recursive')) : if not(args.__contains__('recursive')) :
Config.DirIndex = index Config.DirIndex = index
if index > 1 : Config.RefPts = [Pt2, Pt3] if index > 1 : Config.RefPts = [Pt2, Pt3]
elif index == 0 : Config.RefPts = [Pt1, Pt2] elif index == 0 : Config.RefPts = [Pt1, Pt2]
else : Config.RefPts = [Pt4, Pt3] else : Config.RefPts = [Pt4, Pt3]
if len(ObjList)>1 : flag = 1 if len(ObjList)>1 : flag = 1
else : flag = 0 else : flag = 0
for ObjID in ObjList: for ObjID in ObjList:
ToLook0 = [2,3,0,1][index] ToLook0 = [2,3,0,1][index]
ToLook1 = [3,2,1,0][index] ToLook1 = [3,2,1,0][index]
CommonSide = FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),dummy.DirBoundaries(ToLook0)) CommonSide = FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),dummy.DirBoundaries(ToLook0))
ToLook2 = [1,0,3,2][index] ToLook2 = [1,0,3,2][index]
RealSegments = Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]*IntLen(CommonSide)/IntLen(Config.ListObj[ObjID].DirBoundaries(ToLook1)) RealSegments = Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]*IntLen(CommonSide)/IntLen(Config.ListObj[ObjID].DirBoundaries(ToLook1))
LocalDelta = 1.*IntLen(CommonSide)/RealSegments LocalDelta = 1.*IntLen(CommonSide)/RealSegments
print "Direction:", ["West","East","South","North"][ToLook2] print "Direction:", ["West","East","South","North"][ToLook2]
print "IntLen(CommonSide):",IntLen(CommonSide) print "IntLen(CommonSide):",IntLen(CommonSide)
print "RealSegments:",RealSegments print "RealSegments:",RealSegments
print "LocalDelta:",LocalDelta print "LocalDelta:",LocalDelta
if flag and Config.Count < Config.Criterion: if flag and Config.Count < Config.Criterion:
if index ==0 : if index ==0 :
if abs(CommonSide[0] - Ymin)<1e-7 : SouthGR = GroupNames[0] if abs(CommonSide[0] - Ymin)<1e-7 : SouthGR = GroupNames[0]
else : SouthGR = None else : SouthGR = None
if abs(CommonSide[1] - Ymax)<1e-7 : NorthGR = GroupNames[1] if abs(CommonSide[1] - Ymax)<1e-7 : NorthGR = GroupNames[1]
else : NorthGR = None else : NorthGR = None
NDelta = Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]* (LocalDelta-GlobalDelta[Convention[index]]) NDelta = Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]* (LocalDelta-GlobalDelta[Convention[index]])
[Pt1,Pt2] = Config.RefPts [Pt1,Pt2] = Config.RefPts
Coef = [1.,-1.][index] Coef = [1.,-1.][index]
Vref1 = [Coef*(Pt2[0]-Pt1[0]),Coef*(Pt2[1]-Pt1[1])] Vref1 = [Coef*(Pt2[0]-Pt1[0]),Coef*(Pt2[1]-Pt1[1])]
Vref2 = NormalizeVector([Pt2[0]-Pt3[0],Pt2[1]-Pt3[1]]) Vref2 = NormalizeVector([Pt2[0]-Pt3[0],Pt2[1]-Pt3[1]])
Ptref = Config.ListObj[ObjID].PtCoor[[2,3][index]] Ptref = Config.ListObj[ObjID].PtCoor[[2,3][index]]
NewPt = ExtrapPoint (Ptref,Vref1,Vref2,NDelta) NewPt = ExtrapPoint (Ptref,Vref1,Vref2,NDelta)
CompositeBoxF (Pt1, Pt2, NewPt, Ptref, recursive=1, groups = [SouthGR,NorthGR]+GroupNames[2:4]) CompositeBoxF (Pt1, Pt2, NewPt, Ptref, recursive=1, groups = [SouthGR,NorthGR]+GroupNames[2:4])
elif index == 1: elif index == 1:
if abs(CommonSide[0] - Ymin)<1e-7 : SouthGR = GroupNames[0] if abs(CommonSide[0] - Ymin)<1e-7 : SouthGR = GroupNames[0]
else : SouthGR = None else : SouthGR = None
if abs(CommonSide[1] - Ymax)<1e-7 : NorthGR = GroupNames[1] if abs(CommonSide[1] - Ymax)<1e-7 : NorthGR = GroupNames[1]
else : NorthGR = None else : NorthGR = None
NDelta = Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]* (LocalDelta-GlobalDelta[Convention[index]]) NDelta = Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]* (LocalDelta-GlobalDelta[Convention[index]])
[Pt4,Pt3] = Config.RefPts [Pt4,Pt3] = Config.RefPts
Coef = 1. Coef = 1.
Vref1 = [Coef*(Pt4[0]-Pt3[0]),Coef*(Pt4[1]-Pt3[1])] Vref1 = [Coef*(Pt4[0]-Pt3[0]),Coef*(Pt4[1]-Pt3[1])]
Vref2 = NormalizeVector([Pt1[0]-Pt4[0],Pt1[1]-Pt4[1]]) Vref2 = NormalizeVector([Pt1[0]-Pt4[0],Pt1[1]-Pt4[1]])
Ptref = Config.ListObj[ObjID].PtCoor[0] Ptref = Config.ListObj[ObjID].PtCoor[0]
NewPt = ExtrapPoint (Ptref,Vref1,Vref2,NDelta) NewPt = ExtrapPoint (Ptref,Vref1,Vref2,NDelta)
CompositeBoxF (NewPt, Ptref, Pt3, Pt4, recursive=1, groups = [SouthGR,NorthGR]+GroupNames[2:4]) CompositeBoxF (NewPt, Ptref, Pt3, Pt4, recursive=1, groups = [SouthGR,NorthGR]+GroupNames[2:4])
else : else :
if abs(CommonSide[0] - Xmin)<1e-7 : WestGR = GroupNames[2] if abs(CommonSide[0] - Xmin)<1e-7 : WestGR = GroupNames[2]
else : WestGR = None else : WestGR = None
if abs(CommonSide[1] - Xmax)<1e-7 : EastGR = GroupNames[3] if abs(CommonSide[1] - Xmax)<1e-7 : EastGR = GroupNames[3]
else : EastGR = None else : EastGR = None
NDelta = Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]* (LocalDelta-GlobalDelta[Convention[index]]) NDelta = Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]* (LocalDelta-GlobalDelta[Convention[index]])
[Pt2,Pt3] = Config.RefPts [Pt2,Pt3] = Config.RefPts
Coef = [1.,-1.][index-2] Coef = [1.,-1.][index-2]
Vref1 = [Coef*(Pt3[0]-Pt2[0]),Coef*(Pt3[1]-Pt2[1])] Vref1 = [Coef*(Pt3[0]-Pt2[0]),Coef*(Pt3[1]-Pt2[1])]
Vref2 = NormalizeVector([Pt3[0]-Pt4[0],Pt3[1]-Pt4[1]]) Vref2 = NormalizeVector([Pt3[0]-Pt4[0],Pt3[1]-Pt4[1]])
Ptref = Config.ListObj[ObjID].PtCoor[[3,0][index-2]] Ptref = Config.ListObj[ObjID].PtCoor[[3,0][index-2]]
NewPt = ExtrapPoint (Ptref,Vref1,Vref2,NDelta) NewPt = ExtrapPoint (Ptref,Vref1,Vref2,NDelta)
CompositeBoxF (Ptref, Pt2, Pt3, NewPt, recursive=1, groups = GroupNames[0:2] + [WestGR,EastGR]) CompositeBoxF (Ptref, Pt2, Pt3, NewPt, recursive=1, groups = GroupNames[0:2] + [WestGR,EastGR])
if Config.Count >= Config.Criterion : if Config.Count >= Config.Criterion :
break break
if flag == 0 and Config.Count < Config.Criterion: if flag == 0 and Config.Count < Config.Criterion:
print "Creating NonOrtho object with the points:", Pt1,Pt2,Pt3,Pt4 print "Creating NonOrtho object with the points:", Pt1,Pt2,Pt3,Pt4
MacObject('NonOrtho',[Pt1,Pt2,Pt3,Pt4] ,['auto'], groups = GroupNames) MacObject('NonOrtho',[Pt1,Pt2,Pt3,Pt4] ,['auto'], groups = GroupNames)
Config.Count += 1 Config.Count += 1
if Config.DirIndex > 1 : Config.RefPts = [Pt1, Pt4] if Config.DirIndex > 1 : Config.RefPts = [Pt1, Pt4]
elif Config.DirIndex==0 : Config.RefPts = [Pt4, Pt3] elif Config.DirIndex==0 : Config.RefPts = [Pt4, Pt3]
else : Config.RefPts = [Pt1, Pt2] else : Config.RefPts = [Pt1, Pt2]
def FindCommonSide (Int1, Int2) : def FindCommonSide (Int1, Int2) :
if max(Int1[0],Int2[0])<min(Int1[1],Int2[1]): return [max(Int1[0],Int2[0]), min(Int1[1],Int2[1])] if max(Int1[0],Int2[0])<min(Int1[1],Int2[1]): return [max(Int1[0],Int2[0]), min(Int1[1],Int2[1])]
else : else :
print "Can not find interval intersection, returning [0,0]..." print "Can not find interval intersection, returning [0,0]..."
return [0,0] return [0,0]
def IntLen (Interval) : def IntLen (Interval) :
return float(abs(Interval[1]-Interval[0])) return float(abs(Interval[1]-Interval[0]))
def RemoveLastObj() : def RemoveLastObj() :
Config.ListObj = Config.ListObj[:-1] Config.ListObj = Config.ListObj[:-1]
Config.Connections = Config.Connections[:-1] Config.Connections = Config.Connections[:-1]
def NormalizeVector(V): def NormalizeVector(V):
Magnitude = math.sqrt(GenFunctions.DotProd(V,V)) Magnitude = math.sqrt(GenFunctions.DotProd(V,V))
return [ V[i]/Magnitude for i in range(len(V))] return [ V[i]/Magnitude for i in range(len(V))]
def GetCriterion (ObjListIDs): def GetCriterion (ObjListIDs):
return max(Config.Criterion, max(len(ObjListIDs[0]),len(ObjListIDs[1]))*max(len(ObjListIDs[2]),len(ObjListIDs[3]))) return max(Config.Criterion, max(len(ObjListIDs[0]),len(ObjListIDs[1]))*max(len(ObjListIDs[2]),len(ObjListIDs[3])))
def SortObjLists (List,X0,Y0,DX,DY) : def SortObjLists (List,X0,Y0,DX,DY) :
""" """
This function sorts the list of neighbouring objects on each side, according to their intersection This function sorts the list of neighbouring objects on each side, according to their intersection
with the object being created. From South to North and from East to West with the object being created. From South to North and from East to West
""" """
Output = List Output = List
# First find the directions where no neighbour exists # First find the directions where no neighbour exists
# Important : Here we assume that exactly two directions have no neighbours !!! # Important : Here we assume that exactly two directions have no neighbours !!!
# Should we change this to allow a more general case ???? # Should we change this to allow a more general case ????
dummy = IndexMultiOcc(List,(-1,)) dummy = IndexMultiOcc(List,(-1,))
# dummy[0] is either 0, meaning there is no neighbour on X- (West) # dummy[0] is either 0, meaning there is no neighbour on X- (West)
# or 1, meaning there is no neighbour on X+ (East) # or 1, meaning there is no neighbour on X+ (East)
# Similarly dummy[1] can be either 2 or 3 (South and North respectively) # Similarly dummy[1] can be either 2 or 3 (South and North respectively)
# In order to get back to the formalism of groups (SNWE) # In order to get back to the formalism of groups (SNWE)
# => we do the following to define Sense of no neighbours and then the Direction list # => we do the following to define Sense of no neighbours and then the Direction list
# is calculated as to include uniquely the directions where we DO have neighbours # is calculated as to include uniquely the directions where we DO have neighbours
if len(dummy) == 1 : if len(dummy) == 1 :
# This adds a second direction where neighbours are not regarded, it is either 0 or 2 # This adds a second direction where neighbours are not regarded, it is either 0 or 2
dummy.append(2*(dummy[0]+2<4)) dummy.append(2*(dummy[0]+2<4))
print("Careful, you have neighbours on 3 or more sides of the box, we will not check if on two parallel sides the boxes are compatible !!!") print("Careful, you have neighbours on 3 or more sides of the box, we will not check if on two parallel sides the boxes are compatible !!!")
if len(dummy) == 2 or len(dummy) == 1 : if len(dummy) == 2 or len(dummy) == 1 :
# Sense contains : Vertical then Horizontal # Sense contains : Vertical then Horizontal
Sense = [dummy[1]%2,dummy[0]] Sense = [dummy[1]%2,dummy[0]]
DirList = [[1,0][dummy[0]],[3,2][dummy[1]%2]] DirList = [[1,0][dummy[0]],[3,2][dummy[1]%2]]
for index,Direction in enumerate(DirList) : for index,Direction in enumerate(DirList) :
ObjList = List[Direction] ObjList = List[Direction]
RankMin = [] RankMin = []
ToLook0 = [2,2,0,0][Direction] ToLook0 = [2,2,0,0][Direction]
ToLook1 = [3,2,1,0][Direction] ToLook1 = [3,2,1,0][Direction]
for index1,ObjID in enumerate(ObjList) : for index1,ObjID in enumerate(ObjList) :
RankMin.append([-1.,1.][Sense[index]] * FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2])[Sense[index]]) RankMin.append([-1.,1.][Sense[index]] * FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2])[Sense[index]])
Output[Direction] = SortList(ObjList,RankMin) Output[Direction] = SortList(ObjList,RankMin)
elif len(dummy) == 3 : elif len(dummy) == 3 :
# We find the direction where we do have neighbours and then we sort the object list along it # We find the direction where we do have neighbours and then we sort the object list along it
Sense = dummy[0]%2 Sense = dummy[0]%2
Direction = [ i not in dummy for i in range(4) ].index(True) Direction = [ i not in dummy for i in range(4) ].index(True)
ObjList = List[Direction] ObjList = List[Direction]
RankMin = [] RankMin = []
ToLook0 = [2,2,0,0][Direction] ToLook0 = [2,2,0,0][Direction]
ToLook1 = [3,2,1,0][Direction] ToLook1 = [3,2,1,0][Direction]
for index1,ObjID in enumerate(ObjList) : for index1,ObjID in enumerate(ObjList) :
RankMin.append([-1.,1.][Sense] * FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2])[Sense]) RankMin.append([-1.,1.][Sense] * FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),[X0-DX/2.,X0+DX/2.,Y0-DY/2.,Y0+DY/2.][ToLook0:ToLook0+2])[Sense])
Output[Direction] = SortList(ObjList,RankMin) Output[Direction] = SortList(ObjList,RankMin)
else : else :
print ("Error : the composite box being created has no neighbours, how on earth do you want us to inherit its mesh parameters!!!") print ("Error : the composite box being created has no neighbours, how on earth do you want us to inherit its mesh parameters!!!")
return Output return Output
def IndexMultiOcc (Array,Element) : def IndexMultiOcc (Array,Element) :
""" """
This functions returns the occurrences indices of Element in Array. This functions returns the occurrences indices of Element in Array.
As opposed to Array.index(Element) method, this allows determining As opposed to Array.index(Element) method, this allows determining
multiple entries rather than just the first one! multiple entries rather than just the first one!
""" """
Output = [] Output = []
try : Array.index(Element) try : Array.index(Element)
except ValueError : print "No more occurrences" except ValueError : print "No more occurrences"
else : Output.append(Array.index(Element)) else : Output.append(Array.index(Element))
if not(Output == []) and len(Array) > 1 : if not(Output == []) and len(Array) > 1 :
for index, ArrElem in enumerate(Array[Output[0]+1:]) : for index, ArrElem in enumerate(Array[Output[0]+1:]) :
if ArrElem == Element : Output.append(index+Output[0]+1) if ArrElem == Element : Output.append(index+Output[0]+1)
return Output return Output
def SortList (ValList, CritList): def SortList (ValList, CritList):
Output = [] Output = []
SortedCritList = copy.copy(CritList) SortedCritList = copy.copy(CritList)
SortedCritList.sort() SortedCritList.sort()
for i in range(0,len(ValList)): for i in range(0,len(ValList)):
index = CritList.index(SortedCritList[i]) index = CritList.index(SortedCritList[i])
Output.append(ValList[index]) Output.append(ValList[index])
return Output return Output
def ExtrapPoint (Ptref,Vref1,Vref2,Delta): def ExtrapPoint (Ptref,Vref1,Vref2,Delta):
""" """
This function allows determining the absolute coordinates of an extrapolation point This function allows determining the absolute coordinates of an extrapolation point
as shown in the following : as shown in the following :
ExtrapPoint x---Vref2->--------o ExtrapPoint x---Vref2->--------o
/ delta_glob |Vref1 / delta_glob |Vref1
/ | / |
Ptref x---------------------+ Ptref x---------------------+
delta_loc * Nseg delta_loc * Nseg
Delta = (delta_loc - delta_glob) * Nseg Delta = (delta_loc - delta_glob) * Nseg
""" """
X = Ptref[0] + Vref1[0] + Delta*Vref2[0]
Y = Ptref[1] + Vref1[1] + Delta*Vref2[1]
return (X,Y,)
X = Ptref[0] + Vref1[0] + Delta*Vref2[0]
Y = Ptref[1] + Vref1[1] + Delta*Vref2[1]
return (X,Y,)

View File

@ -28,199 +28,199 @@ geompy = geomBuilder.New( Config.theStudy )
def Go(GeoObj, CutPlnLst, OutLvlLst, PrefixLst, Publish): def Go(GeoObj, CutPlnLst, OutLvlLst, PrefixLst, Publish):
""" """
This function cuts any geometry (with infinite trim !) into several subgeometries that are cleanly saved inside the navigation tree. (Check GoTrim for the same functionality with custom trim size) This function cuts any geometry (with infinite trim !) into several subgeometries that are cleanly saved inside the navigation tree. (Check GoTrim for the same functionality with custom trim size)
- GeoObj is the geometrical object to be cut and grouped - GeoObj is the geometrical object to be cut and grouped
- CutPlnLst is a list of plane definitions. Each plane is a 6-tuple (contains 6 values). The first three represent the coordinates of the origin point and the second three represent the coordinates of the normal vector to the plane - CutPlnLst is a list of plane definitions. Each plane is a 6-tuple (contains 6 values). The first three represent the coordinates of the origin point and the second three represent the coordinates of the normal vector to the plane
Example 1: [(0,0,0,1,0,0)]: cut along a plane passing through the origin and normal to the x-axis Example 1: [(0,0,0,1,0,0)]: cut along a plane passing through the origin and normal to the x-axis
Example 2: [(0,0,0,1,0,0),(50,0,0,0,1,0)]: in addition to the first plane cut, cut through a plane passing by (50,0,0) and normal to the y axis. Example 2: [(0,0,0,1,0,0),(50,0,0,0,1,0)]: in addition to the first plane cut, cut through a plane passing by (50,0,0) and normal to the y axis.
Note that the plane size us determined automatically from the size of the geometry in question (using a very big trim size = 100 x length of geometry!) Note that the plane size us determined automatically from the size of the geometry in question (using a very big trim size = 100 x length of geometry!)
- OutLvlLst is a list containing integers that represent the inner sectioning level with respect to the original geometry type - OutLvlLst is a list containing integers that represent the inner sectioning level with respect to the original geometry type
A value of 1 means that the section will provide elements of one level lower than the original type. For example a solid sectioned at level 1 will produce faces. A Face sectioned at level 1 will produce edges. A value of 1 means that the section will provide elements of one level lower than the original type. For example a solid sectioned at level 1 will produce faces. A Face sectioned at level 1 will produce edges.
A value of 2 means that a deeper sectioning will be applied. A solid sectioned with level 2 will give faces and edges. A face will give edges and vertices. An edge will give only vertices A value of 2 means that a deeper sectioning will be applied. A solid sectioned with level 2 will give faces and edges. A face will give edges and vertices. An edge will give only vertices
The number of elements in this list should be (this is verified in the code) equal to the number of elements in the plane cut list. This is logical. The number of elements in this list should be (this is verified in the code) equal to the number of elements in the plane cut list. This is logical.
Example 1: [1] Example 1: [1]
Example 2: [1, 2], This means that the cut over the second plane will produce two types of elements unlike the first cut which will only output the first level objects. Example 2: [1, 2], This means that the cut over the second plane will produce two types of elements unlike the first cut which will only output the first level objects.
- PrefixLst is a list of strings that contains the naming Prefixes that are used by the script to generate the subshape names. This is very useful for relating the results to the sectioning requested. - PrefixLst is a list of strings that contains the naming Prefixes that are used by the script to generate the subshape names. This is very useful for relating the results to the sectioning requested.
Example 1: ['Entry'] Example 1: ['Entry']
Example 2: ['Entry','Exit'] The resulting groups from the sectioning with plane no.1 will then be saved as "Entry_FACE" and/or "Entry_EDGE" according to the original geometry object type and the cutting level Example 2: ['Entry','Exit'] The resulting groups from the sectioning with plane no.1 will then be saved as "Entry_FACE" and/or "Entry_EDGE" according to the original geometry object type and the cutting level
Imagine that we have a solid called ExampleSolid, an example command will be: Imagine that we have a solid called ExampleSolid, an example command will be:
CutnGroup.Go(ExampleSolid,[(0,0,0,1,0,0),(50,0,0,0,1,0)],[1, 2],['Entry','Exit']) CutnGroup.Go(ExampleSolid,[(0,0,0,1,0,0),(50,0,0,0,1,0)],[1, 2],['Entry','Exit'])
""" """
NumCuts = CheckInput(CutPlnLst, OutLvlLst, PrefixLst, 1) NumCuts = CheckInput(CutPlnLst, OutLvlLst, PrefixLst, 1)
OrigType = FindStandType(GeoObj,0) OrigType = FindStandType(GeoObj,0)
InvDictionary = dict((v,k) for k, v in geompy.ShapeType.iteritems()) # Give geometry type name as a function of standard type numbering, ex: 4=FACE, 6=EDGE, 7=VERTEX InvDictionary = dict((v,k) for k, v in geompy.ShapeType.iteritems()) # Give geometry type name as a function of standard type numbering, ex: 4=FACE, 6=EDGE, 7=VERTEX
TrimSize = geompy.BasicProperties(GeoObj)[0]*100 TrimSize = geompy.BasicProperties(GeoObj)[0]*100
CutPlane = [] ; Sections = [] ; Parts = [] CutPlane = [] ; Sections = [] ; Parts = []
if NumCuts: if NumCuts:
for i in range(0, NumCuts): # Loop over the cutting planes to create them one by one for i in range(0, NumCuts): # Loop over the cutting planes to create them one by one
CutPlane.append(CreatePlane(CutPlnLst[i],TrimSize)) CutPlane.append(CreatePlane(CutPlnLst[i],TrimSize))
OutFather = geompy.MakePartition([GeoObj],CutPlane, [], [],FindStandType(GeoObj,1), 0, [], 0) #Creating the partition object OutFather = geompy.MakePartition([GeoObj],CutPlane, [], [],FindStandType(GeoObj,1), 0, [], 0) #Creating the partition object
if Publish: geompy.addToStudy(OutFather,'SectionedObject') if Publish: geompy.addToStudy(OutFather,'SectionedObject')
for i in range(0, NumCuts): for i in range(0, NumCuts):
for j in range(OrigType+1+2, OrigType+1+2*(OutLvlLst[i]+1),2): for j in range(OrigType+1+2, OrigType+1+2*(OutLvlLst[i]+1),2):
if j == 8 : j = 7; # Exception for the vertex case (=7) if j == 8 : j = 7; # Exception for the vertex case (=7)
PossSubShapesID = geompy.SubShapeAllIDs(OutFather,j) # List of subshape IDs than correspond to the required cutting level (section type : face/wire/vertex) PossSubShapesID = geompy.SubShapeAllIDs(OutFather,j) # List of subshape IDs than correspond to the required cutting level (section type : face/wire/vertex)
PossSubShapes = geompy.ExtractShapes(OutFather,j) # and the corresponding objects PossSubShapes = geompy.ExtractShapes(OutFather,j) # and the corresponding objects
Accepted = [] Accepted = []
for k in range(0,len(PossSubShapesID)): # Loop over all the subshapes checking if they belong to the cutting plane! if yes add them to current list for k in range(0,len(PossSubShapesID)): # Loop over all the subshapes checking if they belong to the cutting plane! if yes add them to current list
if IsOnPlane(PossSubShapes[k], CutPlnLst[i], 1e-7): if IsOnPlane(PossSubShapes[k], CutPlnLst[i], 1e-7):
Accepted.append(PossSubShapesID[k]) Accepted.append(PossSubShapesID[k])
if Accepted : # If some element is found, save it as a group with the prescribed Prefix if Accepted : # If some element is found, save it as a group with the prescribed Prefix
dummyObj = geompy.CreateGroup(OutFather, j) dummyObj = geompy.CreateGroup(OutFather, j)
geompy.UnionIDs(dummyObj, Accepted) geompy.UnionIDs(dummyObj, Accepted)
Sections.append(dummyObj) Sections.append(dummyObj)
if Publish:geompy.addToStudyInFather(OutFather, dummyObj, PrefixLst[i]+"_"+InvDictionary[j][0:2]) if Publish:geompy.addToStudyInFather(OutFather, dummyObj, PrefixLst[i]+"_"+InvDictionary[j][0:2])
else : else :
print "Warning: For the section no.", i, ", No intersection of type " + InvDictionary[j] + " was found. Hence, no corresponding groups were created" print "Warning: For the section no.", i, ", No intersection of type " + InvDictionary[j] + " was found. Hence, no corresponding groups were created"
SubShapesID = geompy.SubShapeAllIDs(OutFather,OrigType+1) # Saving also the groups corresponding to the sectioned item of the same type: ex. A solid into n sub-solids due to the sections SubShapesID = geompy.SubShapeAllIDs(OutFather,OrigType+1) # Saving also the groups corresponding to the sectioned item of the same type: ex. A solid into n sub-solids due to the sections
for i in range(0,len(SubShapesID)): for i in range(0,len(SubShapesID)):
dummyObj = geompy.CreateGroup(OutFather, OrigType+1) dummyObj = geompy.CreateGroup(OutFather, OrigType+1)
geompy.UnionIDs(dummyObj, [SubShapesID[i]]) geompy.UnionIDs(dummyObj, [SubShapesID[i]])
Parts.append(dummyObj) Parts.append(dummyObj)
if Publish: geompy.addToStudyInFather(OutFather, dummyObj, "SB"+"_"+InvDictionary[OrigType+1][0:3]+"_"+str(i+1)) if Publish: geompy.addToStudyInFather(OutFather, dummyObj, "SB"+"_"+InvDictionary[OrigType+1][0:3]+"_"+str(i+1))
return OutFather, Sections, Parts return OutFather, Sections, Parts
else: else:
print("Fatal error, the routine cannot continue any further, check your input variables") print("Fatal error, the routine cannot continue any further, check your input variables")
return -1 return -1
def GoTrim(GeoObj, CutPlnLst, OutLvlLst, PrefixLst, Publish): def GoTrim(GeoObj, CutPlnLst, OutLvlLst, PrefixLst, Publish):
""" """
This function cuts any geometry into several subgeometries that are cleanly saved inside the navigation tree with a fully customizable trim size. This function cuts any geometry into several subgeometries that are cleanly saved inside the navigation tree with a fully customizable trim size.
- GeoObj is the geometrical object to be cut and grouped - GeoObj is the geometrical object to be cut and grouped
- CutPlnLst is a list of plane definitions. Each plane is a 7-tuple (contains 7 values). The first three represent the coordinates of the origin point and the second three represent the coordinates of the normal vector to the plane, the last value corresponds to the trim size of the planes - CutPlnLst is a list of plane definitions. Each plane is a 7-tuple (contains 7 values). The first three represent the coordinates of the origin point and the second three represent the coordinates of the normal vector to the plane, the last value corresponds to the trim size of the planes
Example 1: [(0,0,0,1,0,0,5)]: cut along a plane passing through the origin and normal to the x-axis with a trim size of 5 Example 1: [(0,0,0,1,0,0,5)]: cut along a plane passing through the origin and normal to the x-axis with a trim size of 5
Example 2: [(0,0,0,1,0,0,5),(50,0,0,0,1,0,10)]: in addition to the first plane cut, cut through a plane passing by (50,0,0) and normal to the y axis with a trim size of 10 Example 2: [(0,0,0,1,0,0,5),(50,0,0,0,1,0,10)]: in addition to the first plane cut, cut through a plane passing by (50,0,0) and normal to the y axis with a trim size of 10
- OutLvlLst is a list containing integers that represent the inner sectioning level with respect to the original geometry type - OutLvlLst is a list containing integers that represent the inner sectioning level with respect to the original geometry type
A value of 1 means that the section will provide elements of one level lower than the original type. For example a solid sectioned at level 1 will produce faces. A Face sectioned at level 1 will produce edges. A value of 1 means that the section will provide elements of one level lower than the original type. For example a solid sectioned at level 1 will produce faces. A Face sectioned at level 1 will produce edges.
A value of 2 means that a deeper sectioning will be applied. A solid sectioned with level 2 will give faces and edges. A face will give edges and vertices. An edge will give only vertices A value of 2 means that a deeper sectioning will be applied. A solid sectioned with level 2 will give faces and edges. A face will give edges and vertices. An edge will give only vertices
The number of elements in this list should be (this is verified in the code) equal to the number of elements in the plane cut list. This is logical. The number of elements in this list should be (this is verified in the code) equal to the number of elements in the plane cut list. This is logical.
Example 1: [1] Example 1: [1]
Example 2: [1, 2], This means that the cut over the second plane will produce two types of elements unlike the first cut which will only output the first level objects. Example 2: [1, 2], This means that the cut over the second plane will produce two types of elements unlike the first cut which will only output the first level objects.
- PrefixLst is a list of strings that contains the naming Prefixes that are used by the script to generate the subshape names. This is very useful for relating the results to the sectioning requested. - PrefixLst is a list of strings that contains the naming Prefixes that are used by the script to generate the subshape names. This is very useful for relating the results to the sectioning requested.
Example 1: ['Entry'] Example 1: ['Entry']
Example 2: ['Entry','Exit'] The resulting groups from the sectioning with plane no.1 will then be saved as "Entry_FACE" and/or "Entry_EDGE" according to the original geometry object type and the cutting level Example 2: ['Entry','Exit'] The resulting groups from the sectioning with plane no.1 will then be saved as "Entry_FACE" and/or "Entry_EDGE" according to the original geometry object type and the cutting level
Imagine that we have a solid called ExampleSolid, an example command will be: Imagine that we have a solid called ExampleSolid, an example command will be:
CutnGroup.Go(ExampleSolid,[(0,0,0,1,0,0,5),(50,0,0,0,1,0,10)],[1, 2],['Entry','Exit']) CutnGroup.Go(ExampleSolid,[(0,0,0,1,0,0,5),(50,0,0,0,1,0,10)],[1, 2],['Entry','Exit'])
""" """
NumCuts = CheckInput(CutPlnLst, OutLvlLst, PrefixLst, 0) NumCuts = CheckInput(CutPlnLst, OutLvlLst, PrefixLst, 0)
OrigType = FindStandType(GeoObj,0) OrigType = FindStandType(GeoObj,0)
InvDictionary = dict((v,k) for k, v in geompy.ShapeType.iteritems()) # Give geometry type name as a function of standard type numbering, ex: 4=FACE, 6=EDGE, 7=VERTEX InvDictionary = dict((v,k) for k, v in geompy.ShapeType.iteritems()) # Give geometry type name as a function of standard type numbering, ex: 4=FACE, 6=EDGE, 7=VERTEX
CutPlane = [] ; Sections = [] ; Parts = [] CutPlane = [] ; Sections = [] ; Parts = []
if NumCuts: if NumCuts:
for i in range(0, NumCuts): # Loop over the cutting planes to create them one by one for i in range(0, NumCuts): # Loop over the cutting planes to create them one by one
CutPlane.append(CreatePlane(CutPlnLst[i][0:6],CutPlnLst[i][6])) CutPlane.append(CreatePlane(CutPlnLst[i][0:6],CutPlnLst[i][6]))
OutFather = geompy.MakePartition([GeoObj],CutPlane, [], [],FindStandType(GeoObj,1), 0, [], 0) #Creating the partition object OutFather = geompy.MakePartition([GeoObj],CutPlane, [], [],FindStandType(GeoObj,1), 0, [], 0) #Creating the partition object
if Publish: geompy.addToStudy(OutFather,'SectionedObject') if Publish: geompy.addToStudy(OutFather,'SectionedObject')
for i in range(0, NumCuts): for i in range(0, NumCuts):
for j in range(OrigType+1+2, OrigType+1+2*(OutLvlLst[i]+1),2): for j in range(OrigType+1+2, OrigType+1+2*(OutLvlLst[i]+1),2):
if j == 8 : j = 7; # Exception for the vertex case (=7) if j == 8 : j = 7; # Exception for the vertex case (=7)
PossSubShapesID = geompy.SubShapeAllIDs(OutFather,j) # List of subshape IDs than correspond to the required cutting level (section type : face/wire/vertex) PossSubShapesID = geompy.SubShapeAllIDs(OutFather,j) # List of subshape IDs than correspond to the required cutting level (section type : face/wire/vertex)
PossSubShapes = geompy.ExtractShapes(OutFather,j) # and the corresponding objects PossSubShapes = geompy.ExtractShapes(OutFather,j) # and the corresponding objects
Accepted = [] Accepted = []
for k in range(0,len(PossSubShapesID)): # Loop over all the subshapes checking if they belong to the cutting plane WITH THE TRIM SIZE CONDITION! if yes add them to current list for k in range(0,len(PossSubShapesID)): # Loop over all the subshapes checking if they belong to the cutting plane WITH THE TRIM SIZE CONDITION! if yes add them to current list
if IsOnPlane(PossSubShapes[k], CutPlnLst[i], 1e-7) and Distance2Pt(geompy.PointCoordinates(geompy.MakeCDG(PossSubShapes[k])),CutPlnLst[i][0:3])<=CutPlnLst[i][-1]: if IsOnPlane(PossSubShapes[k], CutPlnLst[i], 1e-7) and Distance2Pt(geompy.PointCoordinates(geompy.MakeCDG(PossSubShapes[k])),CutPlnLst[i][0:3])<=CutPlnLst[i][-1]:
Accepted.append(PossSubShapesID[k]) Accepted.append(PossSubShapesID[k])
if Accepted : # If some element is found, save it as a group with the prescribed Prefix if Accepted : # If some element is found, save it as a group with the prescribed Prefix
dummyObj = geompy.CreateGroup(OutFather, j) dummyObj = geompy.CreateGroup(OutFather, j)
geompy.UnionIDs(dummyObj, Accepted) geompy.UnionIDs(dummyObj, Accepted)
Sections.append(dummyObj) Sections.append(dummyObj)
if Publish: geompy.addToStudyInFather(OutFather, dummyObj, PrefixLst[i]+"_"+InvDictionary[j][0:2]) if Publish: geompy.addToStudyInFather(OutFather, dummyObj, PrefixLst[i]+"_"+InvDictionary[j][0:2])
else : else :
print "Warning: For the section no.", i, ", No intersection of type " + InvDictionary[j] + " was found. Hence, no corresponding groups were created" print "Warning: For the section no.", i, ", No intersection of type " + InvDictionary[j] + " was found. Hence, no corresponding groups were created"
SubShapesID = geompy.SubShapeAllIDs(OutFather,OrigType+1) # Saving also the groups corresponding to the sectioned item of the same type: ex. A solid into n sub-solids due to the sections SubShapesID = geompy.SubShapeAllIDs(OutFather,OrigType+1) # Saving also the groups corresponding to the sectioned item of the same type: ex. A solid into n sub-solids due to the sections
for i in range(0,len(SubShapesID)): for i in range(0,len(SubShapesID)):
dummyObj = geompy.CreateGroup(OutFather, OrigType+1) dummyObj = geompy.CreateGroup(OutFather, OrigType+1)
geompy.UnionIDs(dummyObj, [SubShapesID[i]]) geompy.UnionIDs(dummyObj, [SubShapesID[i]])
Parts.append(dummyObj) Parts.append(dummyObj)
if Publish: geompy.addToStudyInFather(OutFather, dummyObj, "SB"+"_"+InvDictionary[OrigType+1][0:3]+"_"+str(i+1)) if Publish: geompy.addToStudyInFather(OutFather, dummyObj, "SB"+"_"+InvDictionary[OrigType+1][0:3]+"_"+str(i+1))
return OutFather, Sections, Parts return OutFather, Sections, Parts
else: else:
print("Fatal error, the routine cannot continue any further, check your input variables") print("Fatal error, the routine cannot continue any further, check your input variables")
return -1 return -1
def FindStandType(GeoObj, method): def FindStandType(GeoObj, method):
""" """
Find the standard index for the Geometrical object/compound type input, see dictionary in geompy.ShapeType Find the standard index for the Geometrical object/compound type input, see dictionary in geompy.ShapeType
""" """
TopType = GeoObj.GetMaxShapeType().__str__() TopType = GeoObj.GetMaxShapeType().__str__()
UnModType = geompy.ShapeType[TopType] UnModType = geompy.ShapeType[TopType]
if method == 0 : if method == 0 :
StandType = UnModType-int(not(UnModType%2)) # So that wires and edges and considered the same, faces and shells, and so on StandType = UnModType-int(not(UnModType%2)) # So that wires and edges and considered the same, faces and shells, and so on
else : else :
StandType = UnModType StandType = UnModType
return(StandType) return(StandType)
def CreatePlane(CutPlnVar,Trim): def CreatePlane(CutPlnVar,Trim):
""" """
Creates a temporary point and vector in salome in order to build the sectioning planes needed Creates a temporary point and vector in salome in order to build the sectioning planes needed
""" """
Temp_Vtx = geompy.MakeVertex(CutPlnVar[0], CutPlnVar[1], CutPlnVar[2]) Temp_Vtx = geompy.MakeVertex(CutPlnVar[0], CutPlnVar[1], CutPlnVar[2])
Temp_Vec = geompy.MakeVectorDXDYDZ(CutPlnVar[3], CutPlnVar[4], CutPlnVar[5]) Temp_Vec = geompy.MakeVectorDXDYDZ(CutPlnVar[3], CutPlnVar[4], CutPlnVar[5])
CutPlane = geompy.MakePlane(Temp_Vtx, Temp_Vec, Trim) CutPlane = geompy.MakePlane(Temp_Vtx, Temp_Vec, Trim)
return(CutPlane) return(CutPlane)
def CheckInput(CutPlnLst, OutLvlLst, PrefixLst, AutoTrim): def CheckInput(CutPlnLst, OutLvlLst, PrefixLst, AutoTrim):
""" """
Checks the user input specifically if all needed parameters are provided Checks the user input specifically if all needed parameters are provided
""" """
if not ((len(CutPlnLst) == len(OutLvlLst)) and (len(CutPlnLst) == len(PrefixLst))): if not ((len(CutPlnLst) == len(OutLvlLst)) and (len(CutPlnLst) == len(PrefixLst))):
print("Missing information about one or more of the cut planes") print("Missing information about one or more of the cut planes")
return 0 return 0
elif not ((len(CutPlnLst[0]) == 6+int(not AutoTrim))): elif not ((len(CutPlnLst[0]) == 6+int(not AutoTrim))):
print("For each cutting plane you need to specify 6 parameters = 2 x 3 coordinates") print("For each cutting plane you need to specify 6 parameters = 2 x 3 coordinates")
return 0 return 0
else: else:
return len(CutPlnLst) return len(CutPlnLst)
def IsOnPlane(GeoSubObj, CutPlnVar, tolerance): def IsOnPlane(GeoSubObj, CutPlnVar, tolerance):
""" """
Checks whether a geometry (vertex, segment, or face) belongs *completely* to the plane defined as a point and a normal vector Checks whether a geometry (vertex, segment, or face) belongs *completely* to the plane defined as a point and a normal vector
""" """
# lambda function that represents the plane equation, function = 0 <=> Pt defined with Coor belongs to plane # lambda function that represents the plane equation, function = 0 <=> Pt defined with Coor belongs to plane
PlaneEq = lambda Coor: CutPlnVar[3]*(Coor[0]-CutPlnVar[0])+CutPlnVar[4]*(Coor[1]-CutPlnVar[1])+CutPlnVar[5]*(Coor[2]-CutPlnVar[2]) PlaneEq = lambda Coor: CutPlnVar[3]*(Coor[0]-CutPlnVar[0])+CutPlnVar[4]*(Coor[1]-CutPlnVar[1])+CutPlnVar[5]*(Coor[2]-CutPlnVar[2])
OrigType = FindStandType(GeoSubObj,0) OrigType = FindStandType(GeoSubObj,0)
if (OrigType >= 7): # Vertex if (OrigType >= 7): # Vertex
NonTrimDecision = abs(PlaneEq(geompy.PointCoordinates(GeoSubObj))) < tolerance NonTrimDecision = abs(PlaneEq(geompy.PointCoordinates(GeoSubObj))) < tolerance
if len(CutPlnVar) == 6 : return NonTrimDecision # No trim condition used if len(CutPlnVar) == 6 : return NonTrimDecision # No trim condition used
else : return (NonTrimDecision and Distance2Pt(CutPlnVar[0:3],geompy.PointCoordinates(GeoSubObj))<=CutPlnVar[6]/2) else : return (NonTrimDecision and Distance2Pt(CutPlnVar[0:3],geompy.PointCoordinates(GeoSubObj))<=CutPlnVar[6]/2)
elif (OrigType >= 5): # Line, decompose into two points then call recursively IsOnPlane function! elif (OrigType >= 5): # Line, decompose into two points then call recursively IsOnPlane function!
Verdict = True Verdict = True
for i in range(0,2): for i in range(0,2):
Verdict = Verdict and IsOnPlane(geompy.GetVertexByIndex(GeoSubObj,i), CutPlnVar, tolerance) Verdict = Verdict and IsOnPlane(geompy.GetVertexByIndex(GeoSubObj,i), CutPlnVar, tolerance)
return Verdict return Verdict
elif (OrigType >= 3): # Face, decompose into three points then call recursively IsOnPlane function! elif (OrigType >= 3): # Face, decompose into three points then call recursively IsOnPlane function!
if IsOnPlane(geompy.MakeCDG(GeoSubObj),CutPlnVar, tolerance) : # Center of gravity belongs to plane, check if normal is parallel to plane if IsOnPlane(geompy.MakeCDG(GeoSubObj),CutPlnVar, tolerance) : # Center of gravity belongs to plane, check if normal is parallel to plane
NormalP1Coor = geompy.PointCoordinates(geompy.GetVertexByIndex(geompy.GetNormal(GeoSubObj),0)) NormalP1Coor = geompy.PointCoordinates(geompy.GetVertexByIndex(geompy.GetNormal(GeoSubObj),0))
NormalP2Coor = geompy.PointCoordinates(geompy.GetVertexByIndex(geompy.GetNormal(GeoSubObj),1)) NormalP2Coor = geompy.PointCoordinates(geompy.GetVertexByIndex(geompy.GetNormal(GeoSubObj),1))
Normal = [NormalP1Coor[0]-NormalP2Coor[0], NormalP1Coor[1]-NormalP2Coor[1], NormalP1Coor[2]-NormalP2Coor[2]] Normal = [NormalP1Coor[0]-NormalP2Coor[0], NormalP1Coor[1]-NormalP2Coor[1], NormalP1Coor[2]-NormalP2Coor[2]]
CrossP = CrossProd(CutPlnVar[3:6],Normal) # Checks whether normals (of section plane and of face) are parallel or not CrossP = CrossProd(CutPlnVar[3:6],Normal) # Checks whether normals (of section plane and of face) are parallel or not
if (abs(CrossP[0])<tolerance and abs(CrossP[1])<tolerance and abs(CrossP[2])<tolerance): # meaning zero cross product => parallel if (abs(CrossP[0])<tolerance and abs(CrossP[1])<tolerance and abs(CrossP[2])<tolerance): # meaning zero cross product => parallel
return True return True
else : else :
return False return False
else : else :
return False return False
def CrossProd(V1,V2): def CrossProd(V1,V2):
""" """
Determines the cross product of two 3D vectors Determines the cross product of two 3D vectors
""" """
return ([V1[1]*V2[2]-V1[2]*V2[1], V1[2]*V2[0]-V1[0]*V2[2], V1[0]*V2[1]-V1[1]*V2[0]]) return ([V1[1]*V2[2]-V1[2]*V2[1], V1[2]*V2[0]-V1[0]*V2[2], V1[0]*V2[1]-V1[1]*V2[0]])
def Distance2Pt(P1,P2): def Distance2Pt(P1,P2):
""" """
Returns the distance between two points Returns the distance between two points
""" """
return (math.sqrt((P1[0]-P2[0])**2+(P1[1]-P2[1])**2+(P1[2]-P2[2])**2)) return (math.sqrt((P1[0]-P2[0])**2+(P1[1]-P2[1])**2+(P1[2]-P2[2])**2))

View File

@ -34,82 +34,82 @@ from MacObject import *
import Config, GenFunctions import Config, GenFunctions
def Cylinder (X0 , Y0 , D , DX , DY , LocalMeshing , **args) : def Cylinder (X0 , Y0 , D , DX , DY , LocalMeshing , **args) :
if args.__contains__('DLocal') : DLocal = float(args['DLocal']) if args.__contains__('DLocal') : DLocal = float(args['DLocal'])
else : DLocal = float(min(DX,DY)) else : DLocal = float(min(DX,DY))
# K is the pitch ratio # K is the pitch ratio
K = float(D)/(DLocal-D) K = float(D)/(DLocal-D)
print "A local pitch ratio of K =", K ," will be used. " print "A local pitch ratio of K =", K ," will be used. "
NumCuts = 2*GenFunctions.QuarCylParam(K) NumCuts = 2*GenFunctions.QuarCylParam(K)
InternalMeshing = int(math.ceil(math.pi*D/(4*NumCuts*LocalMeshing))) InternalMeshing = int(math.ceil(math.pi*D/(4*NumCuts*LocalMeshing)))
if InternalMeshing == 0 : InternalMeshing = 1 # This sets a minimum meshing condition in order to avoid an error. The user is notified of the value considered for the local meshing if InternalMeshing == 0 : InternalMeshing = 1 # This sets a minimum meshing condition in order to avoid an error. The user is notified of the value considered for the local meshing
print "Possible Local meshing is :", math.pi*D/(4*NumCuts*InternalMeshing), "\nThis value is returned by this function for your convenience.\n" print "Possible Local meshing is :", math.pi*D/(4*NumCuts*InternalMeshing), "\nThis value is returned by this function for your convenience.\n"
if args.__contains__('groups') : if args.__contains__('groups') :
GroupNames = args['groups'] GroupNames = args['groups']
else : GroupNames = [None, None, None, None, None] else : GroupNames = [None, None, None, None, None]
if DY == DLocal : if DY == DLocal :
if DX == DLocal: if DX == DLocal:
GN1 = [None,GroupNames[1],None,GroupNames[3],GroupNames[4]] GN1 = [None,GroupNames[1],None,GroupNames[3],GroupNames[4]]
GN2 = [None,GroupNames[1],GroupNames[2],None,GroupNames[4]] GN2 = [None,GroupNames[1],GroupNames[2],None,GroupNames[4]]
GN3 = [GroupNames[0],None,GroupNames[2],None,GroupNames[4]] GN3 = [GroupNames[0],None,GroupNames[2],None,GroupNames[4]]
GN4 = [GroupNames[0],None,None,GroupNames[3],GroupNames[4]] GN4 = [GroupNames[0],None,None,GroupNames[3],GroupNames[4]]
else :
GN1 = [None,GroupNames[1],None,None,GroupNames[4]]
GN2 = [None,GroupNames[1],None,None,GroupNames[4]]
GN3 = [GroupNames[0],None,None,None,GroupNames[4]]
GN4 = [GroupNames[0],None,None,None,GroupNames[4]]
GN5 = [GroupNames[0],GroupNames[1],None,GroupNames[3]]
GN6 = [GroupNames[0],GroupNames[1],GroupNames[2],None]
else : else :
if DX == DLocal: GN1 = [None,GroupNames[1],None,None,GroupNames[4]]
GN1 = [None,None,None,GroupNames[3],GroupNames[4]] GN2 = [None,GroupNames[1],None,None,GroupNames[4]]
GN2 = [None,None,GroupNames[2],None,GroupNames[4]] GN3 = [GroupNames[0],None,None,None,GroupNames[4]]
GN3 = [None,None,GroupNames[2],None,GroupNames[4]] GN4 = [GroupNames[0],None,None,None,GroupNames[4]]
GN4 = [None,None,None,GroupNames[3],GroupNames[4]]
GN7 = [GroupNames[0],None,GroupNames[2],GroupNames[3]]
GN8 = [None,GroupNames[1],GroupNames[2],GroupNames[3]]
else :
GN1 = [None,None,None,None,GroupNames[4]]
GN2 = [None,None,None,None,GroupNames[4]]
GN3 = [None,None,None,None,GroupNames[4]]
GN4 = [None,None,None,None,GroupNames[4]]
GN5 = [None,None,None,GroupNames[3]] GN5 = [GroupNames[0],GroupNames[1],None,GroupNames[3]]
GN6 = [None,None,GroupNames[2],None] GN6 = [GroupNames[0],GroupNames[1],GroupNames[2],None]
else :
if DX == DLocal:
GN1 = [None,None,None,GroupNames[3],GroupNames[4]]
GN2 = [None,None,GroupNames[2],None,GroupNames[4]]
GN3 = [None,None,GroupNames[2],None,GroupNames[4]]
GN4 = [None,None,None,GroupNames[3],GroupNames[4]]
GN7 = [GroupNames[0],None,GroupNames[2],GroupNames[3]]
GN8 = [None,GroupNames[1],GroupNames[2],GroupNames[3]]
else :
GN1 = [None,None,None,None,GroupNames[4]]
GN2 = [None,None,None,None,GroupNames[4]]
GN3 = [None,None,None,None,GroupNames[4]]
GN4 = [None,None,None,None,GroupNames[4]]
GN9 = [GroupNames[0],None,None,GroupNames[3]] GN5 = [None,None,None,GroupNames[3]]
GN10 = [GroupNames[0],None,None,None] GN6 = [None,None,GroupNames[2],None]
GN11 = [GroupNames[0],None,GroupNames[2],None]
GN12 = [None,GroupNames[1],None,GroupNames[3]] GN9 = [GroupNames[0],None,None,GroupNames[3]]
GN13 = [None,GroupNames[1],None,None] GN10 = [GroupNames[0],None,None,None]
GN14 = [None,GroupNames[1],GroupNames[2],None] GN11 = [GroupNames[0],None,GroupNames[2],None]
Obj = [] GN12 = [None,GroupNames[1],None,GroupNames[3]]
GN13 = [None,GroupNames[1],None,None]
GN14 = [None,GroupNames[1],GroupNames[2],None]
Obj.append(MacObject('QuartCyl',[(X0+DLocal/4.,Y0+DLocal/4.),(DLocal/2.,DLocal/2.)],[InternalMeshing,'NE',K], groups = GN1)) Obj = []
Obj.append(MacObject('QuartCyl',[(X0-DLocal/4.,Y0+DLocal/4.),(DLocal/2.,DLocal/2.)],['auto','NW',K], groups = GN2))
Obj.append(MacObject('QuartCyl',[(X0-DLocal/4.,Y0-DLocal/4.),(DLocal/2.,DLocal/2.)],['auto','SW',K], groups = GN3))
Obj.append(MacObject('QuartCyl',[(X0+DLocal/4.,Y0-DLocal/4.),(DLocal/2.,DLocal/2.)],['auto','SE',K], groups = GN4))
if DX > DLocal : Obj.append(MacObject('QuartCyl',[(X0+DLocal/4.,Y0+DLocal/4.),(DLocal/2.,DLocal/2.)],[InternalMeshing,'NE',K], groups = GN1))
dX = (DX - DLocal)/2. Obj.append(MacObject('QuartCyl',[(X0-DLocal/4.,Y0+DLocal/4.),(DLocal/2.,DLocal/2.)],['auto','NW',K], groups = GN2))
Obj.append(MacObject('CompBoxF',[(X0+DLocal/2.+dX/2.,Y0),(dX,DLocal)],['auto'], groups = GN5)) Obj.append(MacObject('QuartCyl',[(X0-DLocal/4.,Y0-DLocal/4.),(DLocal/2.,DLocal/2.)],['auto','SW',K], groups = GN3))
Obj.append(MacObject('CompBoxF',[(X0-DLocal/2.-dX/2.,Y0),(dX,DLocal)],['auto'], groups = GN6)) Obj.append(MacObject('QuartCyl',[(X0+DLocal/4.,Y0-DLocal/4.),(DLocal/2.,DLocal/2.)],['auto','SE',K], groups = GN4))
if DY > DLocal : if DX > DLocal :
dY = (DY - DLocal)/2. dX = (DX - DLocal)/2.
if DX > DLocal : Obj.append(MacObject('CompBoxF',[(X0+DLocal/2.+dX/2.,Y0),(dX,DLocal)],['auto'], groups = GN5))
Obj.append(MacObject('CompBoxF',[(X0+DLocal/2.+dX/2.,Y0-DLocal/2.-dY/2.),(dX,dY)],['auto'], groups = GN9)) Obj.append(MacObject('CompBoxF',[(X0-DLocal/2.-dX/2.,Y0),(dX,DLocal)],['auto'], groups = GN6))
Obj.append(MacObject('CompBoxF',[(X0,Y0-DLocal/2.-dY/2.),(DLocal,dY)],['auto'], groups = GN10))
Obj.append(MacObject('CompBoxF',[(X0-DLocal/2.-dX/2.,Y0-DLocal/2.-dY/2.),(dX,dY)],['auto'], groups = GN11))
Obj.append(MacObject('CompBoxF',[(X0+DLocal/2.+dX/2.,Y0+DLocal/2.+dY/2.),(dX,dY)],['auto'], groups = GN12))
Obj.append(MacObject('CompBoxF',[(X0,Y0+DLocal/2.+dY/2.),(DLocal,dY)],['auto'], groups = GN13))
Obj.append(MacObject('CompBoxF',[(X0-DLocal/2.-dX/2.,Y0+DLocal/2.+dY/2.),(dX,dY)],['auto'], groups = GN14))
else:
Obj.append(MacObject('CompBoxF',[(X0,Y0-DLocal/2.-dY/2.),(DLocal,dY)],['auto'], groups = GN7))
Obj.append(MacObject('CompBoxF',[(X0,Y0+DLocal/2.+dY/2.),(DLocal,dY)],['auto'], groups = GN8))
return Obj if DY > DLocal :
dY = (DY - DLocal)/2.
if DX > DLocal :
Obj.append(MacObject('CompBoxF',[(X0+DLocal/2.+dX/2.,Y0-DLocal/2.-dY/2.),(dX,dY)],['auto'], groups = GN9))
Obj.append(MacObject('CompBoxF',[(X0,Y0-DLocal/2.-dY/2.),(DLocal,dY)],['auto'], groups = GN10))
Obj.append(MacObject('CompBoxF',[(X0-DLocal/2.-dX/2.,Y0-DLocal/2.-dY/2.),(dX,dY)],['auto'], groups = GN11))
Obj.append(MacObject('CompBoxF',[(X0+DLocal/2.+dX/2.,Y0+DLocal/2.+dY/2.),(dX,dY)],['auto'], groups = GN12))
Obj.append(MacObject('CompBoxF',[(X0,Y0+DLocal/2.+dY/2.),(DLocal,dY)],['auto'], groups = GN13))
Obj.append(MacObject('CompBoxF',[(X0-DLocal/2.-dX/2.,Y0+DLocal/2.+dY/2.),(dX,dY)],['auto'], groups = GN14))
else:
Obj.append(MacObject('CompBoxF',[(X0,Y0-DLocal/2.-dY/2.),(DLocal,dY)],['auto'], groups = GN7))
Obj.append(MacObject('CompBoxF',[(X0,Y0+DLocal/2.+dY/2.),(DLocal,dY)],['auto'], groups = GN8))
return Obj

File diff suppressed because it is too large Load Diff

View File

@ -20,281 +20,279 @@
class MacObject: class MacObject:
""" """
This represents a python class definition which contains This represents a python class definition which contains
all necessary information about the macro object being created all necessary information about the macro object being created
in Salome in Salome
""" """
def __init__( self, ObjectType, GeoParameters, MeshParameters, **args ): def __init__( self, ObjectType, GeoParameters, MeshParameters, **args ):
""" """
Initializes the macro object to be created, saves parameters inside of it, checks for neighboring objects, Initializes the macro object to be created, saves parameters inside of it, checks for neighboring objects,
determines meshing parameters if necessary and finally launches the generation process. determines meshing parameters if necessary and finally launches the generation process.
""" """
import Config,GenFunctions import Config,GenFunctions
if Config.debug : print "Initializing object No. " + str(len(Config.ListObj)+1) if Config.debug : print "Initializing object No. " + str(len(Config.ListObj)+1)
if 'publish' in args : if 'publish' in args :
if args['publish']==0 : Config.publish = 0 if args['publish']==0 : Config.publish = 0
else : Config.publish = 1 else : Config.publish = 1
else : Config.publish = 1 else : Config.publish = 1
if 'groups' in args : if 'groups' in args :
self.GroupNames = args['groups'] self.GroupNames = args['groups']
for group in args['groups'] : for group in args['groups'] :
if not(group in Config.Groups) and group : Config.Groups.append(group) if not(group in Config.Groups) and group : Config.Groups.append(group)
else : self.GroupNames = [None, None, None, None] else : self.GroupNames = [None, None, None, None]
if ObjectType == 'NonOrtho': if ObjectType == 'NonOrtho':
if not(len(GeoParameters)==4): print "Error: trying to construct a non-ortho object but the 4 constitutive vertices are not given!" if not(len(GeoParameters)==4): print "Error: trying to construct a non-ortho object but the 4 constitutive vertices are not given!"
else : else :
Xmin = min([GeoParameters[i][0] for i in range(4)]) Xmin = min([GeoParameters[i][0] for i in range(4)])
Xmax = max([GeoParameters[i][0] for i in range(4)]) Xmax = max([GeoParameters[i][0] for i in range(4)])
Ymin = min([GeoParameters[i][1] for i in range(4)]) Ymin = min([GeoParameters[i][1] for i in range(4)])
Ymax = max([GeoParameters[i][1] for i in range(4)]) Ymax = max([GeoParameters[i][1] for i in range(4)])
self.GeoPar = [(0.5*(Xmin+Xmax),0.5*(Ymin+Ymax)),(Xmax-Xmin,Ymax-Ymin)] self.GeoPar = [(0.5*(Xmin+Xmax),0.5*(Ymin+Ymax)),(Xmax-Xmin,Ymax-Ymin)]
self.PtCoor = GenFunctions.SortPoints(GeoParameters) self.PtCoor = GenFunctions.SortPoints(GeoParameters)
else: else:
self.GeoPar = GeoParameters self.GeoPar = GeoParameters
[Xmin,Ymin,Xmax,Ymax] = [ self.GeoPar[0][0]-0.5*self.GeoPar[1][0], self.GeoPar[0][1]-0.5*self.GeoPar[1][1] ] + [ self.GeoPar[0][0]+0.5*self.GeoPar[1][0], self.GeoPar[0][1]+0.5*self.GeoPar[1][1] ] [Xmin,Ymin,Xmax,Ymax] = [ self.GeoPar[0][0]-0.5*self.GeoPar[1][0], self.GeoPar[0][1]-0.5*self.GeoPar[1][1] ] + [ self.GeoPar[0][0]+0.5*self.GeoPar[1][0], self.GeoPar[0][1]+0.5*self.GeoPar[1][1] ]
self.PtCoor = [(Xmin,Ymin),(Xmax,Ymin),(Xmax,Ymax),(Xmin,Ymax)] self.PtCoor = [(Xmin,Ymin),(Xmax,Ymin),(Xmax,Ymax),(Xmin,Ymax)]
self.Type = ObjectType self.Type = ObjectType
self.LowBound = [ self.GeoPar[0][0]-0.5*self.GeoPar[1][0], self.GeoPar[0][1]-0.5*self.GeoPar[1][1] ] self.LowBound = [ self.GeoPar[0][0]-0.5*self.GeoPar[1][0], self.GeoPar[0][1]-0.5*self.GeoPar[1][1] ]
self.UpperBound = [ self.GeoPar[0][0]+0.5*self.GeoPar[1][0], self.GeoPar[0][1]+0.5*self.GeoPar[1][1] ] self.UpperBound = [ self.GeoPar[0][0]+0.5*self.GeoPar[1][0], self.GeoPar[0][1]+0.5*self.GeoPar[1][1] ]
self.MeshPar = MeshParameters self.MeshPar = MeshParameters
self.GeoChildren = [] self.GeoChildren = []
self.GeoChildrenNames = [] self.GeoChildrenNames = []
self.Mesh = [] self.Mesh = []
self.MeshGroups = [] self.MeshGroups = []
self.CheckInterfaces() self.CheckInterfaces()
if 'auto' in MeshParameters : self.AutoParam() if 'auto' in MeshParameters : self.AutoParam()
if not(self.MeshPar[0]<0): self.Generate() if not(self.MeshPar[0]<0): self.Generate()
else : else :
Config.ListObj.append(self) Config.ListObj.append(self)
print("Aborting object creation\n ") print("Aborting object creation\n ")
def Generate(self) : def Generate(self) :
""" """
This method generates the geometrical object with the corresponding mesh once all verifications (CheckInterfaces and AutoParam) This method generates the geometrical object with the corresponding mesh once all verifications (CheckInterfaces and AutoParam)
have been accomplished have been accomplished
""" """
import GenFunctions, Alarms, Config import GenFunctions, Alarms, Config
self = {'Box11' : lambda : GenFunctions.Box11(self), self = {'Box11' : lambda : GenFunctions.Box11(self),
'Box42' : lambda : GenFunctions.Box42(self), 'Box42' : lambda : GenFunctions.Box42(self),
'BoxAng32' : lambda : GenFunctions.BoxAng32(self), 'BoxAng32' : lambda : GenFunctions.BoxAng32(self),
'CompBox' : lambda : GenFunctions.CompBox(self), 'CompBox' : lambda : GenFunctions.CompBox(self),
'CompBoxF' : lambda : GenFunctions.CompBoxF(self), 'CompBoxF' : lambda : GenFunctions.CompBoxF(self),
'NonOrtho' : lambda : GenFunctions.NonOrtho(self), 'NonOrtho' : lambda : GenFunctions.NonOrtho(self),
'QuartCyl' : lambda : GenFunctions.QuartCyl(self) }[self.Type]() 'QuartCyl' : lambda : GenFunctions.QuartCyl(self) }[self.Type]()
if Config.debug : Alarms.Message(self.status) # notification on the result of the generation algorithm if Config.debug : Alarms.Message(self.status) # notification on the result of the generation algorithm
def CheckInterfaces(self): def CheckInterfaces(self):
""" """
This method searches for neighbours for the object being created and saves them inside the Config.Connections This method searches for neighbours for the object being created and saves them inside the Config.Connections
array. This array contains 4 entries per object corresponding to West, East, South, and North neighbours. array. This array contains 4 entries per object corresponding to West, East, South, and North neighbours.
Note that an object may have more than one neighbour for a given direction. Note that an object may have more than one neighbour for a given direction.
""" """
import Alarms, Config import Alarms, Config
from GenFunctions import AddIfDifferent from GenFunctions import AddIfDifferent
from CompositeBox import FindCommonSide from CompositeBox import FindCommonSide
Config.Connections.append([(-1,),(-1,),(-1,),(-1,)]) Config.Connections.append([(-1,),(-1,),(-1,),(-1,)])
itemID = len(Config.ListObj) itemID = len(Config.ListObj)
# In all cases except non ortho, PrincipleBoxes is unitary and contains the box in question # In all cases except non ortho, PrincipleBoxes is unitary and contains the box in question
# In the non-ortho case it contains all possible combinations of boxes with 3 vertices # In the non-ortho case it contains all possible combinations of boxes with 3 vertices
PrincipleBoxes = self.PrincipleBoxes() PrincipleBoxes = self.PrincipleBoxes()
for i, TestObj in enumerate(Config.ListObj): for i, TestObj in enumerate(Config.ListObj):
SecondaryBoxes = TestObj.PrincipleBoxes() SecondaryBoxes = TestObj.PrincipleBoxes()
ConnX = 0 ConnX = 0
ConnY = 0 ConnY = 0
for Box0 in PrincipleBoxes: for Box0 in PrincipleBoxes:
for Box1 in SecondaryBoxes: for Box1 in SecondaryBoxes:
# Along X # Along X
CenterDis = abs(Box1[0][0]-Box0[0][0]) CenterDis = abs(Box1[0][0]-Box0[0][0])
Extension = 0.5*(Box1[1][0]+Box0[1][0]) Extension = 0.5*(Box1[1][0]+Box0[1][0])
if CenterDis - Extension < -1e-7 : if CenterDis - Extension < -1e-7 :
ConnX = -1 ConnX = -1
elif CenterDis - Extension < 1e-7 : elif CenterDis - Extension < 1e-7 :
if not(FindCommonSide(self.DirBoundaries(2),TestObj.DirBoundaries(3))==[0,0]) and Box1[0][0] < Box0[0][0] : ConnX = 1 if not(FindCommonSide(self.DirBoundaries(2),TestObj.DirBoundaries(3))==[0,0]) and Box1[0][0] < Box0[0][0] : ConnX = 1
elif not(FindCommonSide(self.DirBoundaries(3),TestObj.DirBoundaries(2))==[0,0]) and Box1[0][0] >= Box0[0][0]: ConnX = 2 elif not(FindCommonSide(self.DirBoundaries(3),TestObj.DirBoundaries(2))==[0,0]) and Box1[0][0] >= Box0[0][0]: ConnX = 2
else : ConnX = 0 else : ConnX = 0
# Along Y # Along Y
CenterDis = abs(Box1[0][1]-Box0[0][1]) CenterDis = abs(Box1[0][1]-Box0[0][1])
Extension = 0.5*(Box1[1][1]+Box0[1][1]) Extension = 0.5*(Box1[1][1]+Box0[1][1])
if CenterDis - Extension < -1e-7 : if CenterDis - Extension < -1e-7 :
ConnY = -1 ConnY = -1
elif CenterDis - Extension < 1e-7 : elif CenterDis - Extension < 1e-7 :
if not(FindCommonSide(self.DirBoundaries(0),TestObj.DirBoundaries(1))==[0,0]) and Box1[0][1] < Box0[0][1] : ConnY = 1 if not(FindCommonSide(self.DirBoundaries(0),TestObj.DirBoundaries(1))==[0,0]) and Box1[0][1] < Box0[0][1] : ConnY = 1
elif not(FindCommonSide(self.DirBoundaries(1),TestObj.DirBoundaries(0))==[0,0]) and Box1[0][1] >= Box0[0][1]: ConnY = 2 elif not(FindCommonSide(self.DirBoundaries(1),TestObj.DirBoundaries(0))==[0,0]) and Box1[0][1] >= Box0[0][1]: ConnY = 2
else : ConnY = 0 else : ConnY = 0
if not (ConnX*ConnY == 0) : if not (ConnX*ConnY == 0) :
if max(ConnX,ConnY) == -1 and not('NonOrtho' in [self.Type,TestObj.Type]) : Alarms.Message(3) if max(ConnX,ConnY) == -1 and not('NonOrtho' in [self.Type,TestObj.Type]) : Alarms.Message(3)
else: else:
if ConnX == 1 and ConnY == -1: if ConnX == 1 and ConnY == -1:
if Config.Connections[i][1] == (-1,) : Config.Connections[i][1] = (itemID,) if Config.Connections[i][1] == (-1,) : Config.Connections[i][1] = (itemID,)
else : Config.Connections[i][1] = AddIfDifferent(Config.Connections[i][1],itemID) else : Config.Connections[i][1] = AddIfDifferent(Config.Connections[i][1],itemID)
if Config.Connections[itemID][0] == (-1,) : Config.Connections[itemID][0] = (i,) if Config.Connections[itemID][0] == (-1,) : Config.Connections[itemID][0] = (i,)
else : Config.Connections[itemID][0] = AddIfDifferent(Config.Connections[itemID][0],i) else : Config.Connections[itemID][0] = AddIfDifferent(Config.Connections[itemID][0],i)
elif ConnX == 2 and ConnY == -1: elif ConnX == 2 and ConnY == -1:
if Config.Connections[i][0] == (-1,) : Config.Connections[i][0] = (itemID,) if Config.Connections[i][0] == (-1,) : Config.Connections[i][0] = (itemID,)
else : Config.Connections[i][0] = AddIfDifferent(Config.Connections[i][0],itemID) else : Config.Connections[i][0] = AddIfDifferent(Config.Connections[i][0],itemID)
if Config.Connections[itemID][1] == (-1,) : Config.Connections[itemID][1] = (i,) if Config.Connections[itemID][1] == (-1,) : Config.Connections[itemID][1] = (i,)
else : Config.Connections[itemID][1] = AddIfDifferent(Config.Connections[itemID][1],i) else : Config.Connections[itemID][1] = AddIfDifferent(Config.Connections[itemID][1],i)
elif ConnY == 1 and ConnX == -1: elif ConnY == 1 and ConnX == -1:
if Config.Connections[i][3] == (-1,) : Config.Connections[i][3] = (itemID,) if Config.Connections[i][3] == (-1,) : Config.Connections[i][3] = (itemID,)
else : Config.Connections[i][3] = AddIfDifferent(Config.Connections[i][3],itemID) else : Config.Connections[i][3] = AddIfDifferent(Config.Connections[i][3],itemID)
if Config.Connections[itemID][2] == (-1,) : Config.Connections[itemID][2] = (i,) if Config.Connections[itemID][2] == (-1,) : Config.Connections[itemID][2] = (i,)
else : Config.Connections[itemID][2] = AddIfDifferent(Config.Connections[itemID][2],i) else : Config.Connections[itemID][2] = AddIfDifferent(Config.Connections[itemID][2],i)
elif ConnY ==2 and ConnX == -1: elif ConnY ==2 and ConnX == -1:
if Config.Connections[i][2] == (-1,) : Config.Connections[i][2] = (itemID,) if Config.Connections[i][2] == (-1,) : Config.Connections[i][2] = (itemID,)
else : Config.Connections[i][2] = AddIfDifferent(Config.Connections[i][2],itemID) else : Config.Connections[i][2] = AddIfDifferent(Config.Connections[i][2],itemID)
if Config.Connections[itemID][3] == (-1,) : Config.Connections[itemID][3] = (i,) if Config.Connections[itemID][3] == (-1,) : Config.Connections[itemID][3] = (i,)
else : Config.Connections[itemID][3] = AddIfDifferent(Config.Connections[itemID][3],i) else : Config.Connections[itemID][3] = AddIfDifferent(Config.Connections[itemID][3],i)
def AutoParam (self): def AutoParam (self):
""" """
This method is called only if the 'auto' keyword is used inside the meshing algorithm. It is based on the This method is called only if the 'auto' keyword is used inside the meshing algorithm. It is based on the
connection results per object and tries to find the correct parameters for obtaining a final compatible mesh connection results per object and tries to find the correct parameters for obtaining a final compatible mesh
between the objects already present and the one being created. If this is not possible, the method gives an error between the objects already present and the one being created. If this is not possible, the method gives an error
message. message.
""" """
import Alarms, Config, GenFunctions, CompositeBox import Alarms, Config, GenFunctions, CompositeBox
MeshPar = [0,0,0,0] # initialize the mesh parameter value to be used to -1 MeshPar = [0,0,0,0] # initialize the mesh parameter value to be used to -1
[(X0,Y0),(DX,DY)] = self.GeoPar [(X0,Y0),(DX,DY)] = self.GeoPar
ObjectsInvolved = [] ObjectsInvolved = []
for i, Conn in enumerate(Config.Connections[-1]): for i, Conn in enumerate(Config.Connections[-1]):
if not ( Conn == (-1,) ): # Meaning that there is one or more neighbors on this direction if not ( Conn == (-1,) ): # Meaning that there is one or more neighbors on this direction
for ObjID in Conn : for ObjID in Conn :
ToLook0 = [2,3,0,1][i] ToLook0 = [2,3,0,1][i]
ToLook1 = [3,2,1,0][i] ToLook1 = [3,2,1,0][i]
CommonSide = CompositeBox.FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),self.DirBoundaries(ToLook0)) CommonSide = CompositeBox.FindCommonSide(Config.ListObj[ObjID].DirBoundaries(ToLook1),self.DirBoundaries(ToLook0))
#print "Common Side is:", CommonSide #print "Common Side is:", CommonSide
ToLook2 = [1,0,3,2][i] ToLook2 = [1,0,3,2][i]
#print "Full Side is:", CompositeBox.IntLen(Config.ListObj[ObjID].DirBoundaries(ToLook1)) #print "Full Side is:", CompositeBox.IntLen(Config.ListObj[ObjID].DirBoundaries(ToLook1))
#print "Full Segments on this direction are:", Config.ListObj[ObjID].DirectionalMeshParams[ToLook2] #print "Full Segments on this direction are:", Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]
RealSegments = round(Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]*CompositeBox.IntLen(CommonSide)/CompositeBox.IntLen(Config.ListObj[ObjID].DirBoundaries(ToLook1))) RealSegments = round(Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]*CompositeBox.IntLen(CommonSide)/CompositeBox.IntLen(Config.ListObj[ObjID].DirBoundaries(ToLook1)))
#print "RealSegments :", RealSegments #print "RealSegments :", RealSegments
MeshPar[i] = MeshPar[i] + RealSegments MeshPar[i] = MeshPar[i] + RealSegments
ObjectsInvolved.append(ObjID+1) ObjectsInvolved.append(ObjID+1)
self.DirectionalMeshParams = MeshPar self.DirectionalMeshParams = MeshPar
self.MeshPar[0] = GenFunctions.CompatibilityTest(self) self.MeshPar[0] = GenFunctions.CompatibilityTest(self)
if self.MeshPar[0] < 0 : if self.MeshPar[0] < 0 :
Alarms.Message(4) Alarms.Message(4)
if self.MeshPar[0] == -1 : print ("Problem encountered with object(s) no. "+str(ObjectsInvolved)) if self.MeshPar[0] == -1 : print ("Problem encountered with object(s) no. "+str(ObjectsInvolved))
elif self.MeshPar[0] == -2 : print ("This object has no neighbours !!!") elif self.MeshPar[0] == -2 : print ("This object has no neighbours !!!")
def Boundaries (self): def Boundaries (self):
""" """
This method returns the global boundaries of the MacObject. [Xmin,Xmax,Ymin,Ymax] This method returns the global boundaries of the MacObject. [Xmin,Xmax,Ymin,Ymax]
""" """
Xmin = min([self.DirBoundaries(i)[0] for i in [0,1]]) Xmin = min([self.DirBoundaries(i)[0] for i in [0,1]])
Xmax = max([self.DirBoundaries(i)[1] for i in [0,1]]) Xmax = max([self.DirBoundaries(i)[1] for i in [0,1]])
Ymin = min([self.DirBoundaries(i)[0] for i in [2,3]]) Ymin = min([self.DirBoundaries(i)[0] for i in [2,3]])
Ymax = max([self.DirBoundaries(i)[1] for i in [2,3]]) Ymax = max([self.DirBoundaries(i)[1] for i in [2,3]])
return [Xmin,Xmax,Ymin,Ymax] return [Xmin,Xmax,Ymin,Ymax]
def DirBoundaries (self, Direction): def DirBoundaries (self, Direction):
""" """
This method returns a single interval giving [Xmin,Xmax] or [Ymin,Ymax] according to the required direction. This method returns a single interval giving [Xmin,Xmax] or [Ymin,Ymax] according to the required direction.
This works particularly well for nonorthogonal objects. This works particularly well for nonorthogonal objects.
Direction : [0,1,2,3] <=> [South, North, West, East] Direction : [0,1,2,3] <=> [South, North, West, East]
""" """
PtCoor = self.PtCoor PtCoor = self.PtCoor
PtCoor.append(self.PtCoor[0]) PtCoor.append(self.PtCoor[0])
if type(Direction) is str : if type(Direction) is str :
Dir = { 'South' : lambda : 0, Dir = { 'South' : lambda : 0,
'North' : lambda : 1, 'North' : lambda : 1,
'West' : lambda : 2, 'West' : lambda : 2,
'East' : lambda : 3,}[Direction]() 'East' : lambda : 3,}[Direction]()
else : Dir = int(Direction) else : Dir = int(Direction)
PtIndex = [0,2,3,1][Dir] PtIndex = [0,2,3,1][Dir]
DirIndex = [0,0,1,1][Dir] DirIndex = [0,0,1,1][Dir]
return sorted([PtCoor[PtIndex][DirIndex],PtCoor[PtIndex+1][DirIndex]]) return sorted([PtCoor[PtIndex][DirIndex],PtCoor[PtIndex+1][DirIndex]])
def DirVectors (self, Direction): def DirVectors (self, Direction):
""" """
This method returns for a given object, the real vectors which define a given direction This method returns for a given object, the real vectors which define a given direction
The interest in using this method is for non-orthogonal objects where the sides can be The interest in using this method is for non-orthogonal objects where the sides can be
deviated from the orthogonal basis vectors deviated from the orthogonal basis vectors
""" """
if type(Direction) is str : if type(Direction) is str :
Dir = { 'South' : lambda : 0, Dir = { 'South' : lambda : 0,
'North' : lambda : 1, 'North' : lambda : 1,
'West' : lambda : 2, 'West' : lambda : 2,
'East' : lambda : 3,}[Direction]() 'East' : lambda : 3,}[Direction]()
else : Dir = int(Direction) else : Dir = int(Direction)
PtCoor = self.PtCoor PtCoor = self.PtCoor
PtCoor.append(self.PtCoor[0]) PtCoor.append(self.PtCoor[0])
PtIndex = [0,2,3,1][Dir] PtIndex = [0,2,3,1][Dir]
return [PtCoor[PtIndex+1][0]-PtCoor[PtIndex][0],PtCoor[PtIndex+1][1]-PtCoor[PtIndex][1],0.] return [PtCoor[PtIndex+1][0]-PtCoor[PtIndex][0],PtCoor[PtIndex+1][1]-PtCoor[PtIndex][1],0.]
def GetBorder (self, Criterion): def GetBorder (self, Criterion):
import GenFunctions, Config import GenFunctions, Config
from salome.geom import geomBuilder from salome.geom import geomBuilder
geompy = geomBuilder.New( Config.theStudy ) geompy = geomBuilder.New( Config.theStudy )
if type(Criterion) is str : if type(Criterion) is str :
Crit = {'South' : lambda : 0, Crit = {'South' : lambda : 0,
'North' : lambda : 1, 'North' : lambda : 1,
'West' : lambda : 2, 'West' : lambda : 2,
'East' : lambda : 3,}[Criterion]() 'East' : lambda : 3,}[Criterion]()
else : Crit = int(Criterion) else : Crit = int(Criterion)
AcceptedObj = [] AcceptedObj = []
if Crit < 4 : if Crit < 4 :
Boundaries = self.Boundaries() Boundaries = self.Boundaries()
Research = {0 : lambda : [self.DirVectors(0),1,Boundaries[2]], Research = {0 : lambda : [self.DirVectors(0),1,Boundaries[2]],
1 : lambda : [self.DirVectors(1),1,Boundaries[3]], 1 : lambda : [self.DirVectors(1),1,Boundaries[3]],
2 : lambda : [self.DirVectors(2),0,Boundaries[0]], 2 : lambda : [self.DirVectors(2),0,Boundaries[0]],
3 : lambda : [self.DirVectors(3),0,Boundaries[1]], }[Crit]() 3 : lambda : [self.DirVectors(3),0,Boundaries[1]], }[Crit]()
for i,ElemObj in enumerate(self.GeoChildren): for i,ElemObj in enumerate(self.GeoChildren):
EdgeIDs = geompy.ExtractShapes(ElemObj,6)# List of Edge IDs belonging to ElemObj EdgeIDs = geompy.ExtractShapes(ElemObj,6)# List of Edge IDs belonging to ElemObj
for Edge in EdgeIDs: for Edge in EdgeIDs:
if GenFunctions.IsParallel(Edge,Research[0]): if GenFunctions.IsParallel(Edge,Research[0]):
if abs( geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,0))[Research[1]] - Research[2] )< 1e-6 or abs( geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,1))[Research[1]] - Research[2] )< 1e-6 : if abs( geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,0))[Research[1]] - Research[2] )< 1e-6 or abs( geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,1))[Research[1]] - Research[2] )< 1e-6 :
AcceptedObj.append(Edge) AcceptedObj.append(Edge)
else : else :
CenterSrchPar = {'NE' : lambda : [-1., -1.], CenterSrchPar = {'NE' : lambda : [-1., -1.],
'NW' : lambda : [ 1., -1.], 'NW' : lambda : [ 1., -1.],
'SW' : lambda : [ 1., 1.], 'SW' : lambda : [ 1., 1.],
'SE' : lambda : [-1., 1.], }[self.MeshPar[1]]() 'SE' : lambda : [-1., 1.], }[self.MeshPar[1]]()
Radius = self.GeoPar[1][1]*float(self.MeshPar[2])/(self.MeshPar[2]+1) Radius = self.GeoPar[1][1]*float(self.MeshPar[2])/(self.MeshPar[2]+1)
Center = (self.GeoPar[0][0]+CenterSrchPar[0]*self.GeoPar[1][0]/2.,self.GeoPar[0][1]+CenterSrchPar[1]*self.GeoPar[1][1]/2.,0.) Center = (self.GeoPar[0][0]+CenterSrchPar[0]*self.GeoPar[1][0]/2.,self.GeoPar[0][1]+CenterSrchPar[1]*self.GeoPar[1][1]/2.,0.)
for i,ElemObj in enumerate(self.GeoChildren): for i,ElemObj in enumerate(self.GeoChildren):
EdgeIDs = geompy.ExtractShapes(ElemObj,6)# List of Edge IDs belonging to ElemObj EdgeIDs = geompy.ExtractShapes(ElemObj,6)# List of Edge IDs belonging to ElemObj
for Edge in EdgeIDs: for Edge in EdgeIDs:
if GenFunctions.IsOnCircle(Edge,Center,Radius): if GenFunctions.IsOnCircle(Edge,Center,Radius):
AcceptedObj.append(Edge) AcceptedObj.append(Edge)
return AcceptedObj return AcceptedObj
def PrincipleBoxes (self):
"""
This function returns all possible combination rectangular shape objects that can contain at least 3 of the principle vertices
constituting the MacObject. This is indispensable for the Non-ortho types and shall return a number of 24 possible combinations
"""
from itertools import combinations
Boxes = []
if self.Type == 'NonOrtho':
for combi in combinations(range(4),3):
Xmin = min([self.PtCoor[i][0] for i in combi])
Xmax = max([self.PtCoor[i][0] for i in combi])
Ymin = min([self.PtCoor[i][1] for i in combi])
Ymax = max([self.PtCoor[i][1] for i in combi])
Boxes.append([(0.5*(Xmin+Xmax),0.5*(Ymin+Ymax)),(Xmax-Xmin,Ymax-Ymin)])
else :
Boxes = [self.GeoPar]
return Boxes
def PrincipleBoxes (self):
"""
This function returns all possible combination rectangular shape objects that can contain at least 3 of the principle vertices
constituting the MacObject. This is indispensable for the Non-ortho types and shall return a number of 24 possible combinations
"""
from itertools import combinations
Boxes = []
if self.Type == 'NonOrtho':
for combi in combinations(range(4),3):
Xmin = min([self.PtCoor[i][0] for i in combi])
Xmax = max([self.PtCoor[i][0] for i in combi])
Ymin = min([self.PtCoor[i][1] for i in combi])
Ymax = max([self.PtCoor[i][1] for i in combi])
Boxes.append([(0.5*(Xmin+Xmax),0.5*(Ymin+Ymax)),(Xmax-Xmin,Ymax-Ymin)])
else :
Boxes = [self.GeoPar]
return Boxes

View File

@ -31,217 +31,216 @@ smesh = smeshBuilder.New( Config.theStudy )
########################################################################################################## ##########################################################################################################
def PublishGroups (): def PublishGroups ():
aFilterManager = smesh.CreateFilterManager() aFilterManager = smesh.CreateFilterManager()
# Building geometric and mesh compounds and groups ############################################## # Building geometric and mesh compounds and groups ##############################################
if Config.debug : print "Searching for geometric groups and publishing final compound" if Config.debug : print "Searching for geometric groups and publishing final compound"
TempGEOList = []
TempMESHList = []
for MacroObj in Config.ListObj :
TempGEOList += MacroObj.GeoChildren
TempMESHList += MacroObj.Mesh
FinalCompound = geompy.MakeCompound(TempGEOList)
geompy.addToStudy (FinalCompound,Config.StudyName)
MeshCompound = smesh.Concatenate(TempMESHList, 1, 1, 1e-5)
MeshCompound.SetName(Config.StudyName)
GroupGEO = []
for group in Config.Groups :
# Geometric groups definition
TempGEOList = [] TempGEOList = []
TempMESHList = [] TempNames = []
for MacroObj in Config.ListObj : for MacroObj in Config.ListObj :
TempGEOList += MacroObj.GeoChildren if group in MacroObj.GroupNames :
TempMESHList += MacroObj.Mesh Occurences = IndexMultiOcc(MacroObj.GroupNames, group)
for Occ in Occurences :
TempGEOList += MacroObj.GetBorder(Occ)
GroupGEO.append(geompy.MakeCompound(TempGEOList))
geompy.addToStudyInFather(FinalCompound,GroupGEO[-1],'GR_'+group)
FinalCompound = geompy.MakeCompound(TempGEOList) # Mesh groups definition
geompy.addToStudy (FinalCompound,Config.StudyName) Criterion = smesh.GetCriterion(SMESH.EDGE, SMESH.FT_BelongToGeom,'=',GroupGEO[-1],Tolerance=1e-06)
MeshCompound = smesh.Concatenate(TempMESHList, 1, 1, 1e-5) #Criterion = smesh.Filter.Criterion(18,39,0,'GR_'+group,'GR_'+group,39,39,1e-06,smesh.EDGE,7)
MeshCompound.SetName(Config.StudyName) MeshCompound.MakeGroupByCriterion(group,Criterion)
GroupGEO = [] StudyBuilder = Config.theStudy.NewBuilder()
for group in Config.Groups : for MeshObj in TempMESHList:
SO = Config.theStudy.FindObjectIOR(Config.theStudy.ConvertObjectToIOR(MeshObj))
if SO is not None: StudyBuilder.RemoveObjectWithChildren(SO)
# Geometric groups definition return MeshCompound
TempGEOList = []
TempNames = []
for MacroObj in Config.ListObj :
if group in MacroObj.GroupNames :
Occurences = IndexMultiOcc(MacroObj.GroupNames, group)
for Occ in Occurences :
TempGEOList += MacroObj.GetBorder(Occ)
GroupGEO.append(geompy.MakeCompound(TempGEOList))
geompy.addToStudyInFather(FinalCompound,GroupGEO[-1],'GR_'+group)
# Mesh groups definition
Criterion = smesh.GetCriterion(SMESH.EDGE, SMESH.FT_BelongToGeom,'=',GroupGEO[-1],Tolerance=1e-06)
#Criterion = smesh.Filter.Criterion(18,39,0,'GR_'+group,'GR_'+group,39,39,1e-06,smesh.EDGE,7)
MeshCompound.MakeGroupByCriterion(group,Criterion)
StudyBuilder = Config.theStudy.NewBuilder()
for MeshObj in TempMESHList:
SO = Config.theStudy.FindObjectIOR(Config.theStudy.ConvertObjectToIOR(MeshObj))
if SO is not None: StudyBuilder.RemoveObjectWithChildren(SO)
return MeshCompound
def IndexMultiOcc (Array,Element) : def IndexMultiOcc (Array,Element) :
""" """
This function returns the occurrences indices of Element in Array. This function returns the occurrences indices of Element in Array.
As opposed to Array.index(Element) method, this allows determining As opposed to Array.index(Element) method, this allows determining
multiple entries rather than just the first one! multiple entries rather than just the first one!
""" """
Output = [] Output = []
try : Array.index(Element) try : Array.index(Element)
except ValueError : print "No more occurrences" except ValueError : print "No more occurrences"
else : Output.append(Array.index(Element)) else : Output.append(Array.index(Element))
if not(Output == [-1]) and len(Array) > 1 : if not(Output == [-1]) and len(Array) > 1 :
for index, ArrElem in enumerate(Array[Output[0]+1:]) : for index, ArrElem in enumerate(Array[Output[0]+1:]) :
if ArrElem is Element : Output.append(index+Output[0]+1) if ArrElem is Element : Output.append(index+Output[0]+1)
return Output return Output
def Publish (ObjToPublish): def Publish (ObjToPublish):
for i,GeoObj in enumerate(ObjToPublish) : geompy.addToStudy(GeoObj,"Sub_"+str(i)) for i,GeoObj in enumerate(ObjToPublish) : geompy.addToStudy(GeoObj,"Sub_"+str(i))
def RevolveMesh(MainMesh,**args): def RevolveMesh(MainMesh,**args):
""" """
This function premits to revolute and scale a 2D mesh while transforming the edge This function premits to revolute and scale a 2D mesh while transforming the edge
groups into face groups. Moreover, the function automatically creates the face groups groups into face groups. Moreover, the function automatically creates the face groups
corresponding to the symmetry lower and upper faces corresponding to the symmetry lower and upper faces
Facultatif arguments are : Facultatif arguments are :
- Center [X,Y,Z], origin being the default - Center [X,Y,Z], origin being the default
- Direction [VX,VY,VZ], x-axis being the default - Direction [VX,VY,VZ], x-axis being the default
- AngleDeg or AngleRad : ALPHA, 10 degrees being the default - AngleDeg or AngleRad : ALPHA, 10 degrees being the default
- Scale : BETA, no scaling being default - Scale : BETA, no scaling being default
""" """
################################################################################ ################################################################################
# Reading input arguments and proceeding to defaults if necessary # Reading input arguments and proceeding to defaults if necessary
################################################################################ ################################################################################
if 'Center' in args : CenterCoor = [float(Coor) for Coor in args['Center']] if 'Center' in args : CenterCoor = [float(Coor) for Coor in args['Center']]
else : else :
print "\nThe coordinates of the center of revolution were not given\nThe origin is used by default." print "\nThe coordinates of the center of revolution were not given\nThe origin is used by default."
CenterCoor = [0.,0.,0.] CenterCoor = [0.,0.,0.]
if 'Direction' in args : Direction = [float(Dir) for Dir in args['Direction']] if 'Direction' in args : Direction = [float(Dir) for Dir in args['Direction']]
else : else :
print "\nThe axis vector of revolution was not given\nThe x-axis is used by default." print "\nThe axis vector of revolution was not given\nThe x-axis is used by default."
Direction = [1.,0.,0.] Direction = [1.,0.,0.]
if 'AngleDeg' in args : Angle = float(args['AngleDeg'])*math.pi/180. if 'AngleDeg' in args : Angle = float(args['AngleDeg'])*math.pi/180.
elif 'AngleRad' in args : Angle = float(args['AngleRad']) elif 'AngleRad' in args : Angle = float(args['AngleRad'])
else : else :
print "\nThe revolution angle was not given\nAn angle of 10 degrees is used by default." print "\nThe revolution angle was not given\nAn angle of 10 degrees is used by default."
Angle = 10.*math.pi/180. Angle = 10.*math.pi/180.
if 'Scale' in args : Scale = float(args['Scale']) if 'Scale' in args : Scale = float(args['Scale'])
else : Scale = 1. else : Scale = 1.
# Creating the lower face group LOFAC # Creating the lower face group LOFAC
LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' ) LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
LOFAC.AddFrom(MainMesh.GetMesh()) LOFAC.AddFrom(MainMesh.GetMesh())
GR_Names = MainMesh.GetGroupNames() GR_Names = MainMesh.GetGroupNames()
GRs = MainMesh.GetGroups() GRs = MainMesh.GetGroups()
Rev3DMeshGroups = MainMesh.RotationSweepObject2D( MainMesh, SMESH.AxisStruct( CenterCoor[0], CenterCoor[1], CenterCoor[2], Direction[0], Direction[1], Direction[2] ), Angle, 1, 1e-05 ,True) Rev3DMeshGroups = MainMesh.RotationSweepObject2D( MainMesh, SMESH.AxisStruct( CenterCoor[0], CenterCoor[1], CenterCoor[2], Direction[0], Direction[1], Direction[2] ), Angle, 1, 1e-05 ,True)
# Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...) # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
for GR in GRs: for GR in GRs:
CurrentName = GR.GetName() CurrentName = GR.GetName()
if CurrentName in GR_Names and not(CurrentName=='LOFAC'): # Meaning that this is an old edge group if CurrentName in GR_Names and not(CurrentName=='LOFAC'): # Meaning that this is an old edge group
GR.SetName(CurrentName+'_EDGE') GR.SetName(CurrentName+'_EDGE')
# Removing the _rotated prefix from the rotated FACE groups # Removing the _rotated prefix from the rotated FACE groups
for GR in Rev3DMeshGroups: for GR in Rev3DMeshGroups:
CurrentName = GR.GetName() CurrentName = GR.GetName()
if CurrentName.endswith( "_rotated"): if CurrentName.endswith( "_rotated"):
if CurrentName.startswith( 'LOFAC_' ): if CurrentName.startswith( 'LOFAC_' ):
GR.SetName('VOL') GR.SetName('VOL')
else: else:
GR.SetName(CurrentName[:-8]) GR.SetName(CurrentName[:-8])
elif CurrentName == 'LOFAC_top': elif CurrentName == 'LOFAC_top':
GR.SetName('HIFAC') GR.SetName('HIFAC')
#Index = [ GR_Names[i] in CurrentName for i in range(0,len(GR_Names)) ].index(True) #Index = [ GR_Names[i] in CurrentName for i in range(0,len(GR_Names)) ].index(True)
#GR.SetName(GR_Names[Index]) #GR.SetName(GR_Names[Index])
# Creating the upper face group HIFAC # Creating the upper face group HIFAC
ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' ) ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
ALLFAC.AddFrom(MainMesh.GetMesh()) ALLFAC.AddFrom(MainMesh.GetMesh())
#HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' ) #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
#HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if ( not(MeshGroup.GetName()=='VOL') and MeshGroup.GetType() == SMESH.FACE )], 'HIFAC' ) #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if ( not(MeshGroup.GetName()=='VOL') and MeshGroup.GetType() == SMESH.FACE )], 'HIFAC' )
# Scaling down the mesh to meter units # Scaling down the mesh to meter units
if not(Scale==1.): if not(Scale==1.):
MeshEditor = MainMesh.GetMeshEditor() MeshEditor = MainMesh.GetMeshEditor()
MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 ) MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
def ExtrudeMesh(MainMesh,**args): def ExtrudeMesh(MainMesh,**args):
""" """
This function premits to extrude and scale a 2D mesh while transforming the edge This function premits to extrude and scale a 2D mesh while transforming the edge
groups into face groups. Moreover, the function automatically creates the face groups groups into face groups. Moreover, the function automatically creates the face groups
corresponding to the symmetry lower and upper faces corresponding to the symmetry lower and upper faces
Facultatif arguments are : Facultatif arguments are :
- Direction [VX,VY,VZ], z-axis being default - Direction [VX,VY,VZ], z-axis being default
- Distance : D, default is 1 - Distance : D, default is 1
- NSteps : the object will be extruded by NSteps*Distance, default is Nsteps = 1 - NSteps : the object will be extruded by NSteps*Distance, default is Nsteps = 1
- Scale : BETA, no scaling being default - Scale : BETA, no scaling being default
""" """
################################################################################ ################################################################################
# Reading input arguments and proceeding to defaults if necessary # Reading input arguments and proceeding to defaults if necessary
################################################################################ ################################################################################
if 'Distance' in args : Distance = float(args['Distance']) if 'Distance' in args : Distance = float(args['Distance'])
else : else :
print "\nThe extrusion distance was not given\nA default value of 1 is used." print "\nThe extrusion distance was not given\nA default value of 1 is used."
Distance = 1. Distance = 1.
if 'Direction' in args : Direction = NormalizeVector([float(Dir) for Dir in args['Direction']],Distance) if 'Direction' in args : Direction = NormalizeVector([float(Dir) for Dir in args['Direction']],Distance)
else : else :
print "\nThe extrusion vector of revolution was not given\nThe z-axis is used by default." print "\nThe extrusion vector of revolution was not given\nThe z-axis is used by default."
Direction = NormalizeVector([0.,0.,1.],Distance) Direction = NormalizeVector([0.,0.,1.],Distance)
if 'Scale' in args : Scale = float(args['Scale']) if 'Scale' in args : Scale = float(args['Scale'])
else : Scale = 1. else : Scale = 1.
if 'NSteps' in args : NSteps = int(args['NSteps']) if 'NSteps' in args : NSteps = int(args['NSteps'])
else : NSteps = 1 else : NSteps = 1
# Creating the lower face group LOFAC # Creating the lower face group LOFAC
LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' ) LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
LOFAC.AddFrom(MainMesh.GetMesh()) LOFAC.AddFrom(MainMesh.GetMesh())
GR_Names = MainMesh.GetGroupNames() GR_Names = MainMesh.GetGroupNames()
GRs = MainMesh.GetGroups() GRs = MainMesh.GetGroups()
Ext3DMeshGroups = MainMesh.ExtrusionSweepObject2D(MainMesh,SMESH.DirStruct(SMESH.PointStruct(Direction[0],Direction[1],Direction[2])), NSteps, True) Ext3DMeshGroups = MainMesh.ExtrusionSweepObject2D(MainMesh,SMESH.DirStruct(SMESH.PointStruct(Direction[0],Direction[1],Direction[2])), NSteps, True)
# Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...) # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
for GR in GRs: for GR in GRs:
CurrentName = GR.GetName() CurrentName = GR.GetName()
if CurrentName in GR_Names and not(CurrentName=='LOFAC'): # Meaning that this is an old edge group if CurrentName in GR_Names and not(CurrentName=='LOFAC'): # Meaning that this is an old edge group
GR.SetName(CurrentName+'_EDGE') GR.SetName(CurrentName+'_EDGE')
# Removing the _extruded suffix from the extruded FACE groups # Removing the _extruded suffix from the extruded FACE groups
for GR in Ext3DMeshGroups: for GR in Ext3DMeshGroups:
CurrentName = GR.GetName() CurrentName = GR.GetName()
if CurrentName.endswith( "_extruded"): if CurrentName.endswith( "_extruded"):
if CurrentName.startswith( 'LOFAC_' ): if CurrentName.startswith( 'LOFAC_' ):
GR.SetName('VOL') GR.SetName('VOL')
else: else:
GR.SetName(CurrentName[:-9]) GR.SetName(CurrentName[:-9])
elif CurrentName == 'LOFAC_top': elif CurrentName == 'LOFAC_top':
GR.SetName('HIFAC') GR.SetName('HIFAC')
# Creating the upper face group HIFAC # Creating the upper face group HIFAC
ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' ) ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
ALLFAC.AddFrom(MainMesh.GetMesh()) ALLFAC.AddFrom(MainMesh.GetMesh())
#HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Ext3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' ) #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Ext3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
# Scaling down the mesh to meter units # Scaling down the mesh to meter units
if not(Scale==1.): if not(Scale==1.):
MeshEditor = MainMesh.GetMeshEditor() MeshEditor = MainMesh.GetMeshEditor()
MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 ) MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
def NormalizeVector (V,Norm): def NormalizeVector (V,Norm):
""" """
This function returns a normalized vector (magnitude = Norm), parallel to the entered one This function returns a normalized vector (magnitude = Norm), parallel to the entered one
""" """
V = [float(Coor) for Coor in V] V = [float(Coor) for Coor in V]
Norm = float(Norm) Norm = float(Norm)
MagV = math.sqrt(V[0]*V[0]+V[1]*V[1]+V[2]*V[2]) MagV = math.sqrt(V[0]*V[0]+V[1]*V[1]+V[2]*V[2])
return [Coor*Norm/MagV for Coor in V] return [Coor*Norm/MagV for Coor in V]

View File

@ -21,11 +21,11 @@
# This is an automation of the sharp angle object, with a corner at (X0,Y0), side length : Extension and a fine local meshing : LocalMeshing # This is an automation of the sharp angle object, with a corner at (X0,Y0), side length : Extension and a fine local meshing : LocalMeshing
# The corner orientation is defined as NE (North-East) , NW (North-West), SE, or SW. The object's "arm" is 8/14 of Extension # The corner orientation is defined as NE (North-East) , NW (North-West), SE, or SW. The object's "arm" is 8/14 of Extension
# | | 8 6 # | | 8 6
# ------- --------- # ------- ---------
# ----> | | <---- # ----> | | <----
# | NW NE | oo # | NW NE | oo
# _____| |_____ # _____| |_____
import sys, math, commands import sys, math, commands
CWD = commands.getoutput('pwd') CWD = commands.getoutput('pwd')
@ -36,212 +36,212 @@ from CompositeBox import *
import Config, GenFunctions import Config, GenFunctions
def SharpAngleOut (X0 , Y0 , DX , DY , DLocal, LocalMeshing , CornerOrientation , NLevels, **args) : def SharpAngleOut (X0 , Y0 , DX , DY , DLocal, LocalMeshing , CornerOrientation , NLevels, **args) :
if DLocal == 'auto' : DLocal = float(min(DX,DY)) if DLocal == 'auto' : DLocal = float(min(DX,DY))
BoxSide = DLocal/(2.**(NLevels+1)) BoxSide = DLocal/(2.**(NLevels+1))
InternalMeshing = int(math.ceil(BoxSide/(3*LocalMeshing))) InternalMeshing = int(math.ceil(BoxSide/(3*LocalMeshing)))
InternalMeshing = InternalMeshing+InternalMeshing%2 # An even number is needed, otherwise the objects would not be compatible once created InternalMeshing = InternalMeshing+InternalMeshing%2 # An even number is needed, otherwise the objects would not be compatible once created
if InternalMeshing == 0 : InternalMeshing = 2 # This sets a minimum meshing condition in order to avoid an error. The user is notified of the value considered for the local meshing if InternalMeshing == 0 : InternalMeshing = 2 # This sets a minimum meshing condition in order to avoid an error. The user is notified of the value considered for the local meshing
print "Possible Local meshing is :", BoxSide/(3*InternalMeshing), "\nThis value is returned by this function for your convenience" print "Possible Local meshing is :", BoxSide/(3*InternalMeshing), "\nThis value is returned by this function for your convenience"
DirPar = {'NE' : lambda : ['NE', 'NW', 'SE', 'EW', 'NW', 'SN', 'SN', 'NE', 'WE', 'WE', 'SE', 'NS'], DirPar = {'NE' : lambda : ['NE', 'NW', 'SE', 'EW', 'NW', 'SN', 'SN', 'NE', 'WE', 'WE', 'SE', 'NS'],
'NW' : lambda : ['NW', 'NE', 'SW', 'WE', 'NE', 'SN', 'SN', 'NW', 'EW', 'EW', 'SW', 'NS'], 'NW' : lambda : ['NW', 'NE', 'SW', 'WE', 'NE', 'SN', 'SN', 'NW', 'EW', 'EW', 'SW', 'NS'],
'SE' : lambda : ['SE', 'SW', 'NE', 'EW', 'SW', 'NS', 'NS', 'SE', 'WE', 'WE', 'NE', 'SN'], 'SE' : lambda : ['SE', 'SW', 'NE', 'EW', 'SW', 'NS', 'NS', 'SE', 'WE', 'WE', 'NE', 'SN'],
'SW' : lambda : ['SW', 'SE', 'NW', 'WE', 'SE', 'NS', 'NS', 'SW', 'EW', 'EW', 'NW', 'SN'], }[CornerOrientation]() 'SW' : lambda : ['SW', 'SE', 'NW', 'WE', 'SE', 'NS', 'NS', 'SW', 'EW', 'EW', 'NW', 'SN'], }[CornerOrientation]()
CoefVer = {'NE' : lambda : 1, CoefVer = {'NE' : lambda : 1,
'NW' : lambda : 1, 'NW' : lambda : 1,
'SE' : lambda : -1, 'SE' : lambda : -1,
'SW' : lambda : -1, }[CornerOrientation]() 'SW' : lambda : -1, }[CornerOrientation]()
CoefHor = {'NE' : lambda : 1, CoefHor = {'NE' : lambda : 1,
'NW' : lambda : -1, 'NW' : lambda : -1,
'SE' : lambda : 1, 'SE' : lambda : 1,
'SW' : lambda : -1, }[CornerOrientation]() 'SW' : lambda : -1, }[CornerOrientation]()
ToLook = {'NE' : lambda : [0,2,1,3], ToLook = {'NE' : lambda : [0,2,1,3],
'NW' : lambda : [0,3,1,2], 'NW' : lambda : [0,3,1,2],
'SE' : lambda : [1,2,0,3], 'SE' : lambda : [1,2,0,3],
'SW' : lambda : [1,3,0,2], }[CornerOrientation]() 'SW' : lambda : [1,3,0,2], }[CornerOrientation]()
if args.__contains__('groups') : if args.__contains__('groups') :
GroupNames = args['groups'] GroupNames = args['groups']
else : GroupNames = [None, None, None, None, None, None] else : GroupNames = [None, None, None, None, None, None]
GN00 = GroupArray(ToLook[0],GroupNames[0]) GN00 = GroupArray(ToLook[0],GroupNames[0])
GN01 = GroupArray(ToLook[1],GroupNames[1]) GN01 = GroupArray(ToLook[1],GroupNames[1])
GN1 = GroupArray([ToLook[0],ToLook[1]],[GroupNames[0],GroupNames[5]]) GN1 = GroupArray([ToLook[0],ToLook[1]],[GroupNames[0],GroupNames[5]])
GN7 = GroupArray([ToLook[0],ToLook[1]],[GroupNames[4],GroupNames[1]]) GN7 = GroupArray([ToLook[0],ToLook[1]],[GroupNames[4],GroupNames[1]])
if DY == DLocal : if DY == DLocal :
GN2 = GroupArray([ToLook[1],ToLook[2]],[GroupNames[5],GroupNames[2]]) GN2 = GroupArray([ToLook[1],ToLook[2]],[GroupNames[5],GroupNames[2]])
GN3 = GroupArray(ToLook[2],GroupNames[2]) GN3 = GroupArray(ToLook[2],GroupNames[2])
if DX == DLocal: if DX == DLocal:
GN4 = GroupArray([ToLook[2],ToLook[3]],[GroupNames[2],GroupNames[3]]) GN4 = GroupArray([ToLook[2],ToLook[3]],[GroupNames[2],GroupNames[3]])
GN5 = GroupArray(ToLook[3],GroupNames[3]) GN5 = GroupArray(ToLook[3],GroupNames[3])
GN6 = GroupArray([ToLook[3],ToLook[0]],[GroupNames[3],GroupNames[4]]) GN6 = GroupArray([ToLook[3],ToLook[0]],[GroupNames[3],GroupNames[4]])
else :
GN4 = GroupArray(ToLook[2],GroupNames[2])
GN5 = [None,None,None,None]
GN6 = GroupArray(ToLook[0],GroupNames[4])
GN21 = GroupArray([ToLook[3],ToLook[0],ToLook[2]],[GroupNames[3],GroupNames[4],GroupNames[2]])
else : else :
GN2 = GroupArray(ToLook[1],GroupNames[5]) GN4 = GroupArray(ToLook[2],GroupNames[2])
GN3 = [None,None,None,None] GN5 = [None,None,None,None]
if DX == DLocal: GN6 = GroupArray(ToLook[0],GroupNames[4])
GN4 = GroupArray(ToLook[3],GroupNames[3]) GN21 = GroupArray([ToLook[3],ToLook[0],ToLook[2]],[GroupNames[3],GroupNames[4],GroupNames[2]])
GN5 = GroupArray(ToLook[3],GroupNames[3]) else :
GN6 = GroupArray([ToLook[3],ToLook[0]],[GroupNames[3],GroupNames[4]]) GN2 = GroupArray(ToLook[1],GroupNames[5])
GN22 = GroupArray([ToLook[1],ToLook[2],ToLook[3]],[GroupNames[5],GroupNames[2],GroupNames[3]]) GN3 = [None,None,None,None]
else : if DX == DLocal:
GN4 = [None,None,None,None] GN4 = GroupArray(ToLook[3],GroupNames[3])
GN5 = [None,None,None,None] GN5 = GroupArray(ToLook[3],GroupNames[3])
GN6 = GroupArray(ToLook[0],GroupNames[4]) GN6 = GroupArray([ToLook[3],ToLook[0]],[GroupNames[3],GroupNames[4]])
GN21 = GroupArray([ToLook[3],ToLook[0]],[GroupNames[3],GroupNames[4]]) GN22 = GroupArray([ToLook[1],ToLook[2],ToLook[3]],[GroupNames[5],GroupNames[2],GroupNames[3]])
GN22 = GroupArray([ToLook[1],ToLook[2]],[GroupNames[5],GroupNames[2]]) else :
GN23 = GroupArray([ToLook[2],ToLook[3]],[GroupNames[2],GroupNames[3]]) GN4 = [None,None,None,None]
GN5 = [None,None,None,None]
GN6 = GroupArray(ToLook[0],GroupNames[4])
GN21 = GroupArray([ToLook[3],ToLook[0]],[GroupNames[3],GroupNames[4]])
GN22 = GroupArray([ToLook[1],ToLook[2]],[GroupNames[5],GroupNames[2]])
GN23 = GroupArray([ToLook[2],ToLook[3]],[GroupNames[2],GroupNames[3]])
Obj = [] Obj = []
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*BoxSide/2,Y0+CoefVer*BoxSide/2),(BoxSide,BoxSide)],[InternalMeshing,DirPar[0]])) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*BoxSide/2,Y0+CoefVer*BoxSide/2),(BoxSide,BoxSide)],[InternalMeshing,DirPar[0]]))
Obj.append(MacObject('BoxAng32',[(X0-CoefHor*BoxSide/2,Y0+CoefVer*BoxSide/2),(BoxSide,BoxSide)],['auto',DirPar[1]], groups = GroupArray(ToLook[0],GroupNames[0]))) Obj.append(MacObject('BoxAng32',[(X0-CoefHor*BoxSide/2,Y0+CoefVer*BoxSide/2),(BoxSide,BoxSide)],['auto',DirPar[1]], groups = GroupArray(ToLook[0],GroupNames[0])))
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*BoxSide/2,Y0-CoefVer*BoxSide/2),(BoxSide,BoxSide)],['auto',DirPar[2]], groups = GroupArray(ToLook[1],GroupNames[1]))) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*BoxSide/2,Y0-CoefVer*BoxSide/2),(BoxSide,BoxSide)],['auto',DirPar[2]], groups = GroupArray(ToLook[1],GroupNames[1])))
for N in range (1,NLevels+1): for N in range (1,NLevels+1):
n = N-1 n = N-1
if N < NLevels : if N < NLevels :
Obj.append(MacObject('Box42',[(X0-CoefHor*BoxSide*(2**n)*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[3]] , groups = GN00)) Obj.append(MacObject('Box42',[(X0-CoefHor*BoxSide*(2**n)*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[3]] , groups = GN00))
Obj.append(MacObject('BoxAng32',[(X0-CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[4]] )) Obj.append(MacObject('BoxAng32',[(X0-CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[4]] ))
Obj.append(MacObject('Box42',[(X0-CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[5]] )) Obj.append(MacObject('Box42',[(X0-CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[5]] ))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[6]] )) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[6]] ))
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[7]] )) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[7]] ))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[8]] )) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[8]] ))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0-CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[9]] )) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0-CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[9]] ))
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0-CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[10]] )) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0-CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[10]] ))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0-CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[11]] , groups = GN01)) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0-CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[11]] , groups = GN01))
else : else :
Obj.append(MacObject('Box42',[(X0-CoefHor*BoxSide*(2**n)*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[3]] , groups = GN1)) Obj.append(MacObject('Box42',[(X0-CoefHor*BoxSide*(2**n)*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[3]] , groups = GN1))
Obj.append(MacObject('BoxAng32',[(X0-CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[4]] , groups = GN2)) Obj.append(MacObject('BoxAng32',[(X0-CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[4]] , groups = GN2))
Obj.append(MacObject('Box42',[(X0-CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[5]] , groups = GN3)) Obj.append(MacObject('Box42',[(X0-CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[5]] , groups = GN3))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[6]] , groups = GN3)) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[6]] , groups = GN3))
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[7]] , groups = GN4)) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[7]] , groups = GN4))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[8]] , groups = GN5)) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[8]] , groups = GN5))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0-CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[9]] , groups = GN5)) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0-CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[9]] , groups = GN5))
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0-CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[10]], groups = GN6)) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0-CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[10]], groups = GN6))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0-CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[11]] , groups = GN7)) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0-CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[11]] , groups = GN7))
OuterMeshing = (3/2)*InternalMeshing*2**(NLevels-1) OuterMeshing = (3/2)*InternalMeshing*2**(NLevels-1)
OuterSegLength = (DLocal/OuterMeshing) OuterSegLength = (DLocal/OuterMeshing)
if DX > DLocal : if DX > DLocal :
dX = DX - DLocal dX = DX - DLocal
Obj.append(MacObject('CompBoxF',[(X0+CoefHor*(DX)/2.,Y0),(dX,DLocal)],['auto'], groups = GN21)) Obj.append(MacObject('CompBoxF',[(X0+CoefHor*(DX)/2.,Y0),(dX,DLocal)],['auto'], groups = GN21))
if DY > DLocal : if DY > DLocal :
dY = DY - DLocal dY = DY - DLocal
if DX > DLocal : if DX > DLocal :
Obj.append(MacObject('CompBoxF',[(X0+CoefHor*DX/2.,Y0+CoefVer*(DY)/2.),(DX-DLocal,dY)],['auto'], groups = GN23)) Obj.append(MacObject('CompBoxF',[(X0+CoefHor*DX/2.,Y0+CoefVer*(DY)/2.),(DX-DLocal,dY)],['auto'], groups = GN23))
Obj.append(MacObject('CompBoxF',[(X0,Y0+CoefVer*(DY)/2.),(DLocal,dY)],['auto'], groups = GN22)) Obj.append(MacObject('CompBoxF',[(X0,Y0+CoefVer*(DY)/2.),(DLocal,dY)],['auto'], groups = GN22))
return Obj return Obj
def SharpAngleIn (X0 , Y0 , DX , DY , DLocal, LocalMeshing , CornerOrientation , NLevels, **args) : def SharpAngleIn (X0 , Y0 , DX , DY , DLocal, LocalMeshing , CornerOrientation , NLevels, **args) :
if DLocal == 'auto' : DLocal = float(min(DX,DY)) if DLocal == 'auto' : DLocal = float(min(DX,DY))
BoxSide = DLocal/(2.**(NLevels)) BoxSide = DLocal/(2.**(NLevels))
InternalMeshing = int(math.ceil(BoxSide/(3*LocalMeshing))) InternalMeshing = int(math.ceil(BoxSide/(3*LocalMeshing)))
InternalMeshing = InternalMeshing+InternalMeshing%2 # An even number is needed, otherwise the objects would not be compatible once created InternalMeshing = InternalMeshing+InternalMeshing%2 # An even number is needed, otherwise the objects would not be compatible once created
if InternalMeshing == 0 : InternalMeshing = 2 # This sets a minimum meshing condition in order to avoid an error. The user is notified of the value considered for the local meshing if InternalMeshing == 0 : InternalMeshing = 2 # This sets a minimum meshing condition in order to avoid an error. The user is notified of the value considered for the local meshing
print "Possible Local meshing is :", BoxSide/(3*InternalMeshing), "\nThis value is returned by this function for your convenience..." print "Possible Local meshing is :", BoxSide/(3*InternalMeshing), "\nThis value is returned by this function for your convenience..."
DirPar = {'NE' : lambda : ['NE', 'SN', 'NE', 'WE'], DirPar = {'NE' : lambda : ['NE', 'SN', 'NE', 'WE'],
'NW' : lambda : ['NW', 'SN', 'NW', 'EW'], 'NW' : lambda : ['NW', 'SN', 'NW', 'EW'],
'SE' : lambda : ['SE', 'NS', 'SE', 'WE'], 'SE' : lambda : ['SE', 'NS', 'SE', 'WE'],
'SW' : lambda : ['SW', 'NS', 'SW', 'EW'], }[CornerOrientation]() 'SW' : lambda : ['SW', 'NS', 'SW', 'EW'], }[CornerOrientation]()
CoefVer = {'NE' : lambda : 1, CoefVer = {'NE' : lambda : 1,
'NW' : lambda : 1, 'NW' : lambda : 1,
'SE' : lambda : -1, 'SE' : lambda : -1,
'SW' : lambda : -1, }[CornerOrientation]() 'SW' : lambda : -1, }[CornerOrientation]()
CoefHor = {'NE' : lambda : 1, CoefHor = {'NE' : lambda : 1,
'NW' : lambda : -1, 'NW' : lambda : -1,
'SE' : lambda : 1, 'SE' : lambda : 1,
'SW' : lambda : -1, }[CornerOrientation]() 'SW' : lambda : -1, }[CornerOrientation]()
ToLook = {'NE' : lambda : [0,2,1,3], ToLook = {'NE' : lambda : [0,2,1,3],
'NW' : lambda : [0,3,1,2], 'NW' : lambda : [0,3,1,2],
'SE' : lambda : [1,2,0,3], 'SE' : lambda : [1,2,0,3],
'SW' : lambda : [1,3,0,2], }[CornerOrientation]() 'SW' : lambda : [1,3,0,2], }[CornerOrientation]()
if args.__contains__('groups') : if args.__contains__('groups') :
GroupNames = args['groups'] GroupNames = args['groups']
else : GroupNames = [None, None, None, None] else : GroupNames = [None, None, None, None]
GN01 = GroupArray([ToLook[0],ToLook[1]],[GroupNames[ToLook[0]],GroupNames[ToLook[1]]]) GN01 = GroupArray([ToLook[0],ToLook[1]],[GroupNames[ToLook[0]],GroupNames[ToLook[1]]])
GN02 = GroupArray(ToLook[1],GroupNames[ToLook[1]]) GN02 = GroupArray(ToLook[1],GroupNames[ToLook[1]])
GN03 = [None, None, None, None] GN03 = [None, None, None, None]
GN04 = GroupArray(ToLook[0],GroupNames[ToLook[0]]) GN04 = GroupArray(ToLook[0],GroupNames[ToLook[0]])
if DY == DLocal : if DY == DLocal :
GN05 = GroupArray([ToLook[1],ToLook[2]],[GroupNames[ToLook[1]],GroupNames[ToLook[2]]]) GN05 = GroupArray([ToLook[1],ToLook[2]],[GroupNames[ToLook[1]],GroupNames[ToLook[2]]])
GN08 = GroupArray([ToLook[0],ToLook[2],ToLook[3]],[GroupNames[ToLook[0]],GroupNames[ToLook[2]],GroupNames[ToLook[3]]]) GN08 = GroupArray([ToLook[0],ToLook[2],ToLook[3]],[GroupNames[ToLook[0]],GroupNames[ToLook[2]],GroupNames[ToLook[3]]])
if DX == DLocal: if DX == DLocal:
GN06 = GroupArray([ToLook[2],ToLook[3]],[GroupNames[ToLook[2]],GroupNames[ToLook[3]]]) GN06 = GroupArray([ToLook[2],ToLook[3]],[GroupNames[ToLook[2]],GroupNames[ToLook[3]]])
GN07 = GroupArray([ToLook[0],ToLook[3]],[GroupNames[ToLook[0]],GroupNames[ToLook[3]]]) GN07 = GroupArray([ToLook[0],ToLook[3]],[GroupNames[ToLook[0]],GroupNames[ToLook[3]]])
else :
GN06 = GroupArray(ToLook[2],GroupNames[ToLook[2]])
GN07 = GroupArray(ToLook[0],GroupNames[ToLook[0]])
else : else :
GN05 = GroupArray(ToLook[1],GroupNames[ToLook[1]]) GN06 = GroupArray(ToLook[2],GroupNames[ToLook[2]])
if DX == DLocal : GN07 = GroupArray(ToLook[0],GroupNames[ToLook[0]])
GN06 = GroupArray(ToLook[3],GroupNames[ToLook[3]]) else :
GN07 = GroupArray([ToLook[0],ToLook[3]],[GroupNames[ToLook[0]],GroupNames[ToLook[3]]]) GN05 = GroupArray(ToLook[1],GroupNames[ToLook[1]])
GN10 = GroupArray([ToLook[1],ToLook[2],ToLook[3]],[GroupNames[ToLook[1]],GroupNames[ToLook[2]],GroupNames[ToLook[3]]]) if DX == DLocal :
else : GN06 = GroupArray(ToLook[3],GroupNames[ToLook[3]])
GN06 = [None, None, None, None] GN07 = GroupArray([ToLook[0],ToLook[3]],[GroupNames[ToLook[0]],GroupNames[ToLook[3]]])
GN07 = GroupArray(ToLook[0],GroupNames[ToLook[0]]) GN10 = GroupArray([ToLook[1],ToLook[2],ToLook[3]],[GroupNames[ToLook[1]],GroupNames[ToLook[2]],GroupNames[ToLook[3]]])
GN08 = GroupArray([ToLook[0],ToLook[3]],[GroupNames[ToLook[0]],GroupNames[ToLook[3]]]) else :
GN09 = GroupArray([ToLook[2],ToLook[3]],[GroupNames[ToLook[2]],GroupNames[ToLook[3]]]) GN06 = [None, None, None, None]
GN10 = GroupArray([ToLook[1],ToLook[2]],[GroupNames[ToLook[1]],GroupNames[ToLook[2]]]) GN07 = GroupArray(ToLook[0],GroupNames[ToLook[0]])
GN08 = GroupArray([ToLook[0],ToLook[3]],[GroupNames[ToLook[0]],GroupNames[ToLook[3]]])
GN09 = GroupArray([ToLook[2],ToLook[3]],[GroupNames[ToLook[2]],GroupNames[ToLook[3]]])
GN10 = GroupArray([ToLook[1],ToLook[2]],[GroupNames[ToLook[1]],GroupNames[ToLook[2]]])
Obj = [] Obj = []
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*BoxSide/2,Y0+CoefVer*BoxSide/2),(BoxSide,BoxSide)],[InternalMeshing,DirPar[0]],groups = GN01)) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*BoxSide/2,Y0+CoefVer*BoxSide/2),(BoxSide,BoxSide)],[InternalMeshing,DirPar[0]],groups = GN01))
for N in range (1,NLevels+1): for N in range (1,NLevels+1):
n = N-1 n = N-1
if N < NLevels : if N < NLevels :
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[1]],groups = GN02)) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[1]],groups = GN02))
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[2]],groups = GN03)) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[2]],groups = GN03))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[3]],groups = GN04)) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[3]],groups = GN04))
else : else :
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[1]],groups = GN05)) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[1]],groups = GN05))
Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[2]],groups = GN06)) Obj.append(MacObject('BoxAng32',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide*3/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[2]],groups = GN06))
Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[3]],groups = GN07)) Obj.append(MacObject('Box42',[(X0+CoefHor*(2**n)*BoxSide*3/2,Y0+CoefVer*(2**n)*BoxSide/2),((2**n)*BoxSide,(2**n)*BoxSide)],['auto',DirPar[3]],groups = GN07))
OuterMeshing = (3/2)*InternalMeshing*2**(NLevels-1) OuterMeshing = (3/2)*InternalMeshing*2**(NLevels-1)
OuterSegLength = (DLocal/OuterMeshing) OuterSegLength = (DLocal/OuterMeshing)
if DX > DLocal : if DX > DLocal :
dX = DX - DLocal dX = DX - DLocal
Obj = Obj + CompositeBox(X0+CoefHor*(DLocal+dX/2.),Y0+CoefVer*(DLocal)/2.,dX,DLocal, groups = GN08) Obj = Obj + CompositeBox(X0+CoefHor*(DLocal+dX/2.),Y0+CoefVer*(DLocal)/2.,dX,DLocal, groups = GN08)
if DY > DLocal : if DY > DLocal :
dY = DY - DLocal dY = DY - DLocal
if DX > DLocal : if DX > DLocal :
Obj = Obj + CompositeBox(X0+CoefHor*(DLocal+(DX-DLocal)/2.),Y0+CoefVer*(DLocal+dY/2.),DX-DLocal,dY, groups = GN09) Obj = Obj + CompositeBox(X0+CoefHor*(DLocal+(DX-DLocal)/2.),Y0+CoefVer*(DLocal+dY/2.),DX-DLocal,dY, groups = GN09)
Obj = Obj + CompositeBox(X0+CoefHor*DLocal/2,Y0+CoefVer*(DLocal+dY/2.),DLocal,dY,groups = GN10) Obj = Obj + CompositeBox(X0+CoefHor*DLocal/2,Y0+CoefVer*(DLocal+dY/2.),DLocal,dY,groups = GN10)
return Obj return Obj
def GroupArray(indices, GroupNames) : def GroupArray(indices, GroupNames) :
if type(indices) is int : if type(indices) is int :
indices = [indices] indices = [indices]
GroupNames = [GroupNames] GroupNames = [GroupNames]
Output = [None,None,None,None] Output = [None,None,None,None]
for i, ind in enumerate(indices) : for i, ind in enumerate(indices) :
Output[ind] = GroupNames[i] Output[ind] = GroupNames[i]
return Output return Output

View File

@ -8,24 +8,23 @@ from dataBase import Base
if __name__ == "__main__": if __name__ == "__main__":
from optparse import OptionParser from optparse import OptionParser
p=OptionParser() p=OptionParser()
p.add_option('-p',dest='partiel',action="store_true", default=False,help='import de machine, groupe, ratio Maille et Perf uniquement') p.add_option('-p',dest='partiel',action="store_true", default=False,help='import de machine, groupe, ratio Maille et Perf uniquement')
p.add_option('-f',dest='force',action="store_true", default=False,help='ecrasement des valeurs dans la base par les valeurs dans les fichiers en cas de meme clef primaire') p.add_option('-f',dest='force',action="store_true", default=False,help='ecrasement des valeurs dans la base par les valeurs dans les fichiers en cas de meme clef primaire')
p.add_option('-d',dest='database',default="myMesh.db",help='nom de la database') p.add_option('-d',dest='database',default="myMesh.db",help='nom de la database')
options, args = p.parse_args() options, args = p.parse_args()
if len(args) != 1 : if len(args) != 1 :
print "entrer SVP le nom de la directory ou sont rangees les fichiers a charger" print "entrer SVP le nom de la directory ou sont rangees les fichiers a charger"
exit() exit()
folder=args[0] folder=args[0]
if not(os.path.isdir(folder)): if not(os.path.isdir(folder)):
print folder , " n existe pas" print folder , " n existe pas"
exit() exit()
maBase=Base(options.database)
maBase.create()
maBase.initialise()
maBase.importFromCSV(folder,options.partiel,options.force)
maBase.close()
maBase=Base(options.database)
maBase.create()
maBase.initialise()
maBase.importFromCSV(folder,options.partiel,options.force)
maBase.close()

View File

@ -2,114 +2,112 @@ from qtsalome import QSqlQuery
import datetime import datetime
class TableDeBase : class TableDeBase :
def __init__(self,nom): def __init__(self,nom):
self.nom=nom self.nom=nom
def setField(self,FieldStringList): def setField(self,FieldStringList):
self.FieldStringList=FieldStringList self.FieldStringList=FieldStringList
self.idName=FieldStringList[0] self.idName=FieldStringList[0]
def setTypeField(self,FieldTypeListe,clef): def setTypeField(self,FieldTypeListe,clef):
self.FieldTypeListe = FieldTypeListe self.FieldTypeListe = FieldTypeListe
self.clef=clef self.clef=clef
def getFields(self): def getFields(self):
return self.FieldStringList return self.FieldStringList
def insereLigne(self,valeurs,debug=False): def insereLigne(self,valeurs,debug=False):
if self.verifieExitenceId(valeurs[0])!=0 : if self.verifieExitenceId(valeurs[0])!=0 :
print "impossible d inserer " , valeurs, "dans ", self.nom print "impossible d inserer " , valeurs, "dans ", self.nom
print "l id est deja existant" print "l id est deja existant"
return False return False
texteQuery='insert into ' + self.nom + " values "+ str(valeurs)+ ';' texteQuery='insert into ' + self.nom + " values "+ str(valeurs)+ ';'
maQuery=QSqlQuery() maQuery=QSqlQuery()
if debug : print texteQuery, " " , maQuery.exec_(texteQuery) if debug : print texteQuery, " " , maQuery.exec_(texteQuery)
else : maQuery.exec_(texteQuery) else : maQuery.exec_(texteQuery)
def insereLigneAutoId(self,valeurs,debug=False): def insereLigneAutoId(self,valeurs,debug=False):
texteQuery='insert into ' + self.nom + self.cols+ " values "+ str(valeurs)+ ';' texteQuery='insert into ' + self.nom + self.cols+ " values "+ str(valeurs)+ ';'
maQuery=QSqlQuery() maQuery=QSqlQuery()
if debug : print texteQuery, " " , maQuery.exec_(texteQuery) if debug : print texteQuery, " " , maQuery.exec_(texteQuery)
else : maQuery.exec_(texteQuery) else : maQuery.exec_(texteQuery)
def insereOuRemplaceLigne(self,valeurs,debug=False): def insereOuRemplaceLigne(self,valeurs,debug=False):
texteQuery='insert or replace into ' + self.nom + " values "+ str(valeurs)+ ';' texteQuery='insert or replace into ' + self.nom + " values "+ str(valeurs)+ ';'
maQuery=QSqlQuery() maQuery=QSqlQuery()
if debug : print texteQuery, " " , maQuery.exec_(texteQuery) if debug : print texteQuery, " " , maQuery.exec_(texteQuery)
else : maQuery.exec_(texteQuery) else : maQuery.exec_(texteQuery)
def verifieExitenceId(self,valeur): def verifieExitenceId(self,valeur):
# ne fonctionne pas correctement, il faudrait se servir de la clef # ne fonctionne pas correctement, il faudrait se servir de la clef
texteQuery= "select * from " + self.nom + " where "+ self.idName+'='+str(valeur) +';' texteQuery= "select * from " + self.nom + " where "+ self.idName+'='+str(valeur) +';'
maQuery=QSqlQuery() maQuery=QSqlQuery()
maQuery.exec_(texteQuery) maQuery.exec_(texteQuery)
nb=0 nb=0
while(maQuery.next()): nb=nb+1 while(maQuery.next()): nb=nb+1
return nb return nb
def remplit(self): def remplit(self):
print "Pas de remplissage sauf si cette methode est surchargee" print "Pas de remplissage sauf si cette methode est surchargee"
def createSqlTable(self): def createSqlTable(self):
print "Pas de creation par defaut : cette methode doit etre surchargee" print "Pas de creation par defaut : cette methode doit etre surchargee"
# On ne se sert pas du csv python entre autre parcequ'il ne gere pas les entetes # On ne se sert pas du csv python entre autre parcequ'il ne gere pas les entetes
def exportToCSV(self): def exportToCSV(self):
aujourdhui=datetime.date.today() aujourdhui=datetime.date.today()
monFolder="ExportDB"+str(aujourdhui) monFolder="ExportDB"+str(aujourdhui)
monFichier=monFolder+"/Sauve_"+str(self.nom)+'.csv' monFichier=monFolder+"/Sauve_"+str(self.nom)+'.csv'
texteQuery= "select * from " + self.nom +';' texteQuery= "select * from " + self.nom +';'
texteSauve="" texteSauve=""
for col in self.FieldStringList: for col in self.FieldStringList:
texteSauve+=col+";" texteSauve+=col+";"
texteSauve=texteSauve[0:-1] # on enleve le dernier ";" texteSauve=texteSauve[0:-1] # on enleve le dernier ";"
texteSauve+="\n" texteSauve+="\n"
maQuery=QSqlQuery() maQuery=QSqlQuery()
maQuery.exec_(texteQuery) maQuery.exec_(texteQuery)
asauver=0 asauver=0
while(maQuery.next()): while(maQuery.next()):
asauver=1 asauver=1
for i in range(len(self.FieldStringList)): for i in range(len(self.FieldStringList)):
texteSauve+=str(maQuery.value(i).toString())+";" texteSauve+=str(maQuery.value(i).toString())+";"
texteSauve=texteSauve[0:-1] # on enleve le dernier ";" texteSauve=texteSauve[0:-1] # on enleve le dernier ";"
texteSauve+="\n" texteSauve+="\n"
if asauver == 0 : if asauver == 0 :
print "pas de sauvegarde de : " , self.nom , " table vide" print "pas de sauvegarde de : " , self.nom , " table vide"
return return
from Stats.utiles import writeFile
Bok=writeFile(monFichier,texteSauve)
if Bok :
print "sauvegarde de : " , self.nom , " effectuee "
else :
print "pas de sauvegarde de : " , self.nom , " IOerror"
def importFromCSV(self,folder,force):
monFichier=folder+"/Sauve_"+str(self.nom)+'.csv'
try :
f=open(monFichier,'r')
except:
print "Pas de chargement de la table ", self.nom
print "Impossible d'ouvrir le fichier ", monFichier
return 0
lignes=f.readlines()
enTete=tuple(lignes[0][0:-1].split(";"))
if enTete!=self.FieldStringList:
print "Pas de chargement de la table ", self.nom
print "les entetes ne correspondent pas"
return 0
for StrVal in lignes[1:]:
listeVal=tuple(StrVal[0:-1].split(";"))
listeValTypee=[]
for i in range(len(listeVal)):
if self.FieldTypeListe[i]=='int' : listeValTypee.append(int(listeVal[i]))
if self.FieldTypeListe[i]=='float': listeValTypee.append(float(listeVal[i]))
if self.FieldTypeListe[i]=='str' : listeValTypee.append(listeVal[i])
if force==1 : self.insereOuRemplaceLigne(tuple(listeValTypee))
if force==0 : self.insereLigne(tuple(listeValTypee))
from Stats.utiles import writeFile
Bok=writeFile(monFichier,texteSauve)
if Bok :
print "sauvegarde de : " , self.nom , " effectuee "
else :
print "pas de sauvegarde de : " , self.nom , " IOerror"
def importFromCSV(self,folder,force):
monFichier=folder+"/Sauve_"+str(self.nom)+'.csv'
try :
f=open(monFichier,'r')
except:
print "Pas de chargement de la table ", self.nom
print "Impossible d'ouvrir le fichier ", monFichier
return 0
lignes=f.readlines()
enTete=tuple(lignes[0][0:-1].split(";"))
if enTete!=self.FieldStringList:
print "Pas de chargement de la table ", self.nom
print "les entetes ne correspondent pas"
return 0
for StrVal in lignes[1:]:
listeVal=tuple(StrVal[0:-1].split(";"))
listeValTypee=[]
for i in range(len(listeVal)):
if self.FieldTypeListe[i]=='int' : listeValTypee.append(int(listeVal[i]))
if self.FieldTypeListe[i]=='float': listeValTypee.append(float(listeVal[i]))
if self.FieldTypeListe[i]=='str' : listeValTypee.append(listeVal[i])
if force==1 : self.insereOuRemplaceLigne(tuple(listeValTypee))
if force==0 : self.insereLigne(tuple(listeValTypee))

View File

@ -2,26 +2,26 @@ from qtsalome import QSqlQuery
from tableDeBase import TableDeBase from tableDeBase import TableDeBase
class TableGroupesRef (TableDeBase): class TableGroupesRef (TableDeBase):
def __init__(self): def __init__(self):
TableDeBase.__init__(self,"GroupesRef") TableDeBase.__init__(self,"GroupesRef")
self.setField(("nomGroupe","idMaillage")) self.setField(("nomGroupe","idMaillage"))
self.setTypeField(('str','int'),('nomGroupe')) self.setTypeField(('str','int'),('nomGroupe'))
def createSqlTable(self): def createSqlTable(self):
query=QSqlQuery() query=QSqlQuery()
texteQuery ="create table GroupesRef(nomGroupe varchar(40), idMaillage int," texteQuery ="create table GroupesRef(nomGroupe varchar(40), idMaillage int,"
texteQuery+="foreign key (idMaillage) references Maillages(idMaillage)," texteQuery+="foreign key (idMaillage) references Maillages(idMaillage),"
texteQuery+="primary key (nomGroupe,idMaillage));" texteQuery+="primary key (nomGroupe,idMaillage));"
print "Creation de TableGroupesRef : " , query.exec_(texteQuery) print "Creation de TableGroupesRef : " , query.exec_(texteQuery)
def getVals(self,idMaillage): def getVals(self,idMaillage):
query=QSqlQuery() query=QSqlQuery()
texteQuery ='select NomGroupe from GroupesRef where idMaillage='+str(idMaillage) +";" texteQuery ='select NomGroupe from GroupesRef where idMaillage='+str(idMaillage) +";"
listeGroupes=[] listeGroupes=[]
query.exec_(texteQuery) query.exec_(texteQuery)
while (query.next()) : while (query.next()) :
listeGroupes.append(str(query.value(0).toString())) listeGroupes.append(str(query.value(0).toString()))
return listeGroupes return listeGroupes
# def remplit(self): # def remplit(self):

View File

@ -3,29 +3,28 @@ from tableDeBase import TableDeBase
import os import os
class TableMachines (TableDeBase): class TableMachines (TableDeBase):
def __init__(self): def __init__(self):
TableDeBase.__init__(self,"Machines") TableDeBase.__init__(self,"Machines")
self.setField(("nomMachine","Os")) self.setField(("nomMachine","Os"))
self.setTypeField(('str','str'),('nomMachine')) self.setTypeField(('str','str'),('nomMachine'))
def createSqlTable(self): def createSqlTable(self):
query=QSqlQuery() query=QSqlQuery()
print "creation de TableMachine : ", query.exec_("create table Machines( nomMachine varchar(10) primary key, os varchar(10));") print "creation de TableMachine : ", query.exec_("create table Machines( nomMachine varchar(10) primary key, os varchar(10));")
def creeMachine(self): def creeMachine(self):
nomMachine=os.uname()[1] nomMachine=os.uname()[1]
nomOs=os.uname()[2] nomOs=os.uname()[2]
self.insereLigne((nomMachine,nomOs)) self.insereLigne((nomMachine,nomOs))
def chercheMachine(self):
query=QSqlQuery()
machine=os.uname()[1]
texteQuery ="select nomMachine from Machines where nomMachine ='" + machine +"' ;"
query.exec_(texteQuery)
nb=0
while(query.next()):
nb=nb+1
nom=str(query.value(0).toString())
if nb != 1 : return 0, ""
return 1, nom
def chercheMachine(self):
query=QSqlQuery()
machine=os.uname()[1]
texteQuery ="select nomMachine from Machines where nomMachine ='" + machine +"' ;"
query.exec_(texteQuery)
nb=0
while(query.next()):
nb=nb+1
nom=str(query.value(0).toString())
if nb != 1 : return 0, ""
return 1, nom

View File

@ -2,99 +2,99 @@ from qtsalome import QSqlQuery
from tableDeBase import TableDeBase from tableDeBase import TableDeBase
class TableMaillages (TableDeBase): class TableMaillages (TableDeBase):
def __init__(self): def __init__(self):
TableDeBase.__init__(self,"Maillages") TableDeBase.__init__(self,"Maillages")
self.setField(("id","nomMaillage","Script","fichier","idMailleur","Dimension","Seuil CPU","Seuil Ratio","Seuil Taille","Seuil Nb Maille","Commentaire")) self.setField(("id","nomMaillage","Script","fichier","idMailleur","Dimension","Seuil CPU","Seuil Ratio","Seuil Taille","Seuil Nb Maille","Commentaire"))
self.cols="(nomMaillage,nomScript,medResultat,idMailleur,dimension,seuilCPU,seuilRatio,seuilTaille,seuilNbMaille,commentaire)" self.cols="(nomMaillage,nomScript,medResultat,idMailleur,dimension,seuilCPU,seuilRatio,seuilTaille,seuilNbMaille,commentaire)"
self.setTypeField(('int','str','str','str','int','int','int','int','int','int','str'),('id')) self.setTypeField(('int','str','str','str','int','int','int','int','int','int','str'),('id'))
def createSqlTable(self): def createSqlTable(self):
query=QSqlQuery() query=QSqlQuery()
texteQuery ="create table Maillages(id integer primary key autoincrement, nomMaillage varchar(10), " texteQuery ="create table Maillages(id integer primary key autoincrement, nomMaillage varchar(10), "
texteQuery+="nomScript varchar(40), medResultat varchar(15), idMailleur int, dimension int," texteQuery+="nomScript varchar(40), medResultat varchar(15), idMailleur int, dimension int,"
texteQuery+="seuilCPU int, seuilRatio int, seuilTaille int, seuilNbMaille int, commentaire varchar(60), " texteQuery+="seuilCPU int, seuilRatio int, seuilTaille int, seuilNbMaille int, commentaire varchar(60), "
texteQuery+="foreign key (idMailleur) references Mailleur(id));" texteQuery+="foreign key (idMailleur) references Mailleur(id));"
print "creation de TableMaillages : " , query.exec_(texteQuery) print "creation de TableMaillages : " , query.exec_(texteQuery)
def getVal(self,idMaillage, nomChamp): def getVal(self,idMaillage, nomChamp):
query=QSqlQuery() query=QSqlQuery()
valeur=None valeur=None
texteQuery ='select '+ nomChamp + ' from Maillages where id=' + str(idMaillage) + ";" texteQuery ='select '+ nomChamp + ' from Maillages where id=' + str(idMaillage) + ";"
query.exec_(texteQuery) query.exec_(texteQuery)
while (query.next()) : while (query.next()) :
valeur=query.value(0).toInt()[0] valeur=query.value(0).toInt()[0]
while (query.next()) : while (query.next()) :
print "plusieurs enregistrements dans Maillages pour ",str(idMaillage) print "plusieurs enregistrements dans Maillages pour ",str(idMaillage)
exit() exit()
return valeur return valeur
def dejaRemplie(self): def dejaRemplie(self):
texteQuery="select * from Maillages where medResultat='/tmp/tetra.med';" texteQuery="select * from Maillages where medResultat='/tmp/tetra.med';"
maQuery=QSqlQuery() maQuery=QSqlQuery()
maQuery.exec_(texteQuery) maQuery.exec_(texteQuery)
nb=0 nb=0
while(maQuery.next()): nb=nb+1 while(maQuery.next()): nb=nb+1
return nb return nb
def remplit(self): def remplit(self):
if self.dejaRemplie(): if self.dejaRemplie():
print "table Maillage deja initialisee" print "table Maillage deja initialisee"
return return
# self.insereLigneAutoId(('Fiche_7566_TUNNEL', '/home/H77945/CAS_TEST/MAILLEUR/FICHE_7566_TUNNEL/Fiche_7566_TUNNEL.py', '/tmp/Fiche_7566_TUNNEL.med', 3,3,10,10,10,10, 'Maillage d un tunnel')) # self.insereLigneAutoId(('Fiche_7566_TUNNEL', '/home/H77945/CAS_TEST/MAILLEUR/FICHE_7566_TUNNEL/Fiche_7566_TUNNEL.py', '/tmp/Fiche_7566_TUNNEL.med', 3,3,10,10,10,10, 'Maillage d un tunnel'))
# self.insereLigneAutoId(('Fiche_7957_AILETTE', '/home/H77945/CAS_TEST/MAILLEUR/FICHE_7957_AILETTE/Fiche_7957_AILETTE.py', '/tmp/Fiche_7957_AILETTE.med', 1,2,10,10,10,10, 'Maillage d une attache d aillette')) # self.insereLigneAutoId(('Fiche_7957_AILETTE', '/home/H77945/CAS_TEST/MAILLEUR/FICHE_7957_AILETTE/Fiche_7957_AILETTE.py', '/tmp/Fiche_7957_AILETTE.med', 1,2,10,10,10,10, 'Maillage d une attache d aillette'))
def construitListeMaillages(self): def construitListeMaillages(self):
maQuery=QSqlQuery() maQuery=QSqlQuery()
texteQuery="select id, nomScript,medResultat from Maillages;" texteQuery="select id, nomScript,medResultat from Maillages;"
maQuery.exec_(texteQuery) maQuery.exec_(texteQuery)
listeMaillages=[] listeMaillages=[]
while(maQuery.next()): while(maQuery.next()):
listeMaillages.append((maQuery.value(0).toInt()[0], maQuery.value(1).toString(), maQuery.value(2).toString())) listeMaillages.append((maQuery.value(0).toInt()[0], maQuery.value(1).toString(), maQuery.value(2).toString()))
return listeMaillages return listeMaillages
def verifieListeMaillages(self,listeMaillage): def verifieListeMaillages(self,listeMaillage):
newListeMaillages=[] newListeMaillages=[]
maQuery=QSqlQuery() maQuery=QSqlQuery()
for idM in listeMaillage: for idM in listeMaillage:
texteQuery="select id, nomScript,medResultat from Maillages where id = " + str(idM) +';' texteQuery="select id, nomScript,medResultat from Maillages where id = " + str(idM) +';'
maQuery.exec_(texteQuery)
maSize=0
while(maQuery.next()):
maSize+=1
newListeMaillages.append((maQuery.value(0).toInt()[0], maQuery.value(1).toString(), maQuery.value(2).toString()))
if maSize != 1 :
print "impossible de traiter le maillage : ", idM
return newListeMaillages
def getSeuilsPourMaillage(self,idMaillage):
texteQuery="select id,nomMaillage,seuilCPU,seuilRatio,seuilTaille,seuilNbMaille from Maillages where id = "+ str(idMaillage) +" ;"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery) maQuery.exec_(texteQuery)
maSize=0
while(maQuery.next()): while(maQuery.next()):
l1 = maQuery.value(0).toInt()[0] maSize+=1
l2 = maQuery.value(1).toString() newListeMaillages.append((maQuery.value(0).toInt()[0], maQuery.value(1).toString(), maQuery.value(2).toString()))
l3 = maQuery.value(2).toInt()[0] if maSize != 1 :
l4 = maQuery.value(3).toInt()[0] print "impossible de traiter le maillage : ", idM
l5 = maQuery.value(4).toInt()[0] return newListeMaillages
l6 = maQuery.value(5).toInt()[0]
return l1,l2,l3,l4,l5,l6
def getTous(self): def getSeuilsPourMaillage(self,idMaillage):
maillagesIdListe=[]; maillagesNomListe=[] texteQuery="select id,nomMaillage,seuilCPU,seuilRatio,seuilTaille,seuilNbMaille from Maillages where id = "+ str(idMaillage) +" ;"
texteQuery="select id,nomMaillage from Maillages order by id;" maQuery=QSqlQuery()
maQuery=QSqlQuery() maQuery.exec_(texteQuery)
maQuery.exec_(texteQuery) while(maQuery.next()):
while(maQuery.next()): l1 = maQuery.value(0).toInt()[0]
maillagesIdListe.append( maQuery.value(0).toInt()[0]) l2 = maQuery.value(1).toString()
maillagesNomListe.append( maQuery.value(1).toString()) l3 = maQuery.value(2).toInt()[0]
return maillagesIdListe, maillagesNomListe l4 = maQuery.value(3).toInt()[0]
l5 = maQuery.value(4).toInt()[0]
l6 = maQuery.value(5).toInt()[0]
return l1,l2,l3,l4,l5,l6
def getMailleurId(self,idMaillage): def getTous(self):
texteQuery="select idMailleur from Maillages where id = "+ str(idMaillage) +" ;" maillagesIdListe=[]; maillagesNomListe=[]
maQuery=QSqlQuery() texteQuery="select id,nomMaillage from Maillages order by id;"
print texteQuery maQuery=QSqlQuery()
print maQuery.exec_(texteQuery) maQuery.exec_(texteQuery)
maQuery.exec_(texteQuery) while(maQuery.next()):
while(maQuery.next()): maillagesIdListe.append( maQuery.value(0).toInt()[0])
idMailleur = maQuery.value(0).toInt()[0] maillagesNomListe.append( maQuery.value(1).toString())
return idMailleur return maillagesIdListe, maillagesNomListe
def getMailleurId(self,idMaillage):
texteQuery="select idMailleur from Maillages where id = "+ str(idMaillage) +" ;"
maQuery=QSqlQuery()
print texteQuery
print maQuery.exec_(texteQuery)
maQuery.exec_(texteQuery)
while(maQuery.next()):
idMailleur = maQuery.value(0).toInt()[0]
return idMailleur

View File

@ -2,58 +2,56 @@ from qtsalome import QSqlQuery
from tableDeBase import TableDeBase from tableDeBase import TableDeBase
class TableMailleurs (TableDeBase): class TableMailleurs (TableDeBase):
def __init__(self): def __init__(self):
TableDeBase.__init__(self,"Mailleurs") TableDeBase.__init__(self,"Mailleurs")
self.cols=" (nomMailleur) " self.cols=" (nomMailleur) "
self.setField(("id","nomMailleur")) self.setField(("id","nomMailleur"))
self.setTypeField(("int","str"),('id')) self.setTypeField(("int","str"),('id'))
def createSqlTable(self): def createSqlTable(self):
query=QSqlQuery() query=QSqlQuery()
print "Creation de TableMailleurs", query.exec_("create table Mailleurs(id integer primary key autoincrement, nomMailleur varchar(40));") print "Creation de TableMailleurs", query.exec_("create table Mailleurs(id integer primary key autoincrement, nomMailleur varchar(40));")
def dejaRemplie(self): def dejaRemplie(self):
texteQuery="select * from Mailleurs where nomMailleur='Blsurf+Ghs3D';" texteQuery="select * from Mailleurs where nomMailleur='Blsurf+Ghs3D';"
maQuery=QSqlQuery() maQuery=QSqlQuery()
maQuery.exec_(texteQuery) maQuery.exec_(texteQuery)
nb=0 nb=0
while(maQuery.next()): nb=nb+1 while(maQuery.next()): nb=nb+1
return nb return nb
def remplit(self): def remplit(self):
if self.dejaRemplie() : if self.dejaRemplie() :
print "Table Mailleurs deja initialisee" print "Table Mailleurs deja initialisee"
return return
self.insereLigneAutoId(('BLSURF',)) self.insereLigneAutoId(('BLSURF',))
self.insereLigneAutoId(('NETGEN1D2D',)) self.insereLigneAutoId(('NETGEN1D2D',))
self.insereLigneAutoId(('GHS3D+BLSURF',)) self.insereLigneAutoId(('GHS3D+BLSURF',))
self.insereLigneAutoId(('GHS3D+NETGEN1D2D',)) self.insereLigneAutoId(('GHS3D+NETGEN1D2D',))
self.insereLigneAutoId(('NETGEN1D2D3D',)) self.insereLigneAutoId(('NETGEN1D2D3D',))
def insereLigneAutoId(self,valeurs,debug=False): def insereLigneAutoId(self,valeurs,debug=False):
# difficulte a construire le texte avec une seule valeur # difficulte a construire le texte avec une seule valeur
texteQuery='insert into Mailleurs (nomMailleur) values ("'+ str(valeurs[0])+ '");' texteQuery='insert into Mailleurs (nomMailleur) values ("'+ str(valeurs[0])+ '");'
maQuery=QSqlQuery() maQuery=QSqlQuery()
if debug : print texteQuery, " " , maQuery.exec_(texteQuery) if debug : print texteQuery, " " , maQuery.exec_(texteQuery)
else : maQuery.exec_(texteQuery) else : maQuery.exec_(texteQuery)
def getTous(self):
l1=[]
l2=[]
texteQuery="select * from Mailleurs;"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
while(maQuery.next()):
l1.append( maQuery.value(0).toInt()[0])
l2.append( maQuery.value(1).toString())
return l1,l2
def getName(self,mailleurId):
texteQuery="select nomMailleur from Mailleurs where id = " + str(mailleurId) + " ;"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
while(maQuery.next()):
mailleurName=maQuery.value(0).toString()
return mailleurName
def getTous(self):
l1=[]
l2=[]
texteQuery="select * from Mailleurs;"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
while(maQuery.next()):
l1.append( maQuery.value(0).toInt()[0])
l2.append( maQuery.value(1).toString())
return l1,l2
def getName(self,mailleurId):
texteQuery="select nomMailleur from Mailleurs where id = " + str(mailleurId) + " ;"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
while(maQuery.next()):
mailleurName=maQuery.value(0).toString()
return mailleurName

View File

@ -2,43 +2,40 @@ from qtsalome import QSqlQuery
from tableDeBase import TableDeBase from tableDeBase import TableDeBase
class TableVersions (TableDeBase): class TableVersions (TableDeBase):
def __init__(self): def __init__(self):
TableDeBase.__init__(self,"Versions") TableDeBase.__init__(self,"Versions")
self.setField(("id","nomVersion","commentaire")) self.setField(("id","nomVersion","commentaire"))
self.setTypeField(('int','str','str'),('id',)) self.setTypeField(('int','str','str'),('id',))
self.cols=" (nomVersion, commentaire) " self.cols=" (nomVersion, commentaire) "
def createSqlTable(self): def createSqlTable(self):
query=QSqlQuery() query=QSqlQuery()
texteQuery ="create table Versions(id integer primary key autoincrement, nomVersion varchar(10)," texteQuery ="create table Versions(id integer primary key autoincrement, nomVersion varchar(10),"
texteQuery+="commentaire varchar(30));" texteQuery+="commentaire varchar(30));"
print "Creation de TableVersions : " , query.exec_(texteQuery) print "Creation de TableVersions : " , query.exec_(texteQuery)
def remplit(self): def remplit(self):
self.insereLigneAutoId(('Salome7.2.0','')) self.insereLigneAutoId(('Salome7.2.0',''))
self.insereLigneAutoId(('Salome7.3.0','')) self.insereLigneAutoId(('Salome7.3.0',''))
self.insereLigneAutoId(('Salome7.4.0','')) self.insereLigneAutoId(('Salome7.4.0',''))
def creeVersion(self,version,commentaire=""):
self.insereLigneAutoId((version,commentaire))
def chercheVersion(self,version):
query=QSqlQuery()
version=str(version)
if bool(version) == True :
texteQuery ="select id, nomVersion from Versions where id = " + str(version) +";"
else:
texteQuery ="select id, nomVersion from Versions where nomVersion ='" + version +"' ;"
query.exec_(texteQuery)
nb=0
while(query.next()):
nb=nb+1
id=query.value(0).toInt()[0]
nom=query.value(1).toString()
if nb != 1 : return 0, 0, ""
return 1, id, nom
def creeVersion(self,version,commentaire=""):
self.insereLigneAutoId((version,commentaire))
def chercheVersion(self,version):
query=QSqlQuery()
version=str(version)
if bool(version) == True :
texteQuery ="select id, nomVersion from Versions where id = " + str(version) +";"
else:
texteQuery ="select id, nomVersion from Versions where nomVersion ='" + version +"' ;"
query.exec_(texteQuery)
nb=0
while(query.next()):
nb=nb+1
id=query.value(0).toInt()[0]
nom=query.value(1).toString()
if nb != 1 : return 0, 0, ""
return 1, id, nom

View File

@ -8,25 +8,24 @@ from Base.versions import Chercheversion
if __name__ == "__main__": if __name__ == "__main__":
from optparse import OptionParser from optparse import OptionParser
p=OptionParser() p=OptionParser()
p.add_option('-a',dest='all',action="store_true", default=False,help='passe l ensemble des Tests') p.add_option('-a',dest='all',action="store_true", default=False,help='passe l ensemble des Tests')
p.add_option('-s',dest='salomePath',help='chemin du runAppli',default="Appli") p.add_option('-s',dest='salomePath',help='chemin du runAppli',default="Appli")
p.add_option('-v',dest='version',help='id de la version') p.add_option('-v',dest='version',help='id de la version')
p.add_option('-d',dest='database',default="myMesh.db",help='nom de la database') p.add_option('-d',dest='database',default="myMesh.db",help='nom de la database')
p.add_option('-f',dest='force',default=True,help='force la passage des jobs meme si l execution a deja eu lieu sur cette machine pour cette version de salome') p.add_option('-f',dest='force',default=True,help='force la passage des jobs meme si l execution a deja eu lieu sur cette machine pour cette version de salome')
options, args = p.parse_args() options, args = p.parse_args()
if len(args) == 0 and options.all== False: if len(args) == 0 and options.all== False:
print "Enter -a ou un numero de job" print "Enter -a ou un numero de job"
print 2 print 2
exit() exit()
if options.salomePath==None : if options.salomePath==None :
print "chemin du runAppli obligatoire" print "chemin du runAppli obligatoire"
exit() exit()
if options.version==None : if options.version==None :
options.version=Chercheversion(options.salomePath) options.version=Chercheversion(options.salomePath)
maBase=Base(options.database) maBase=Base(options.database)
maBase.initialise() maBase.initialise()
maBase.passeJobs(options.all,options.salomePath,options.version,options.force,args) maBase.passeJobs(options.all,options.salomePath,options.version,options.force,args)
maBase.close() maBase.close()

View File

@ -35,8 +35,8 @@ verbose = True
force = os.getenv("FORCE_DISTENE_LICENSE_FILE") force = os.getenv("FORCE_DISTENE_LICENSE_FILE")
if force != None: if force != None:
os.environ["DISTENE_LICENSE_FILE"] = force os.environ["DISTENE_LICENSE_FILE"] = force
os.environ["DLIM8VAR"] = "NOTHING" os.environ["DLIM8VAR"] = "NOTHING"
class MonViewText(Ui_ViewExe, QDialog): class MonViewText(Ui_ViewExe, QDialog):
""" """
@ -76,7 +76,7 @@ class MonViewText(Ui_ViewExe, QDialog):
nomFichier = os.path.splitext(self.parent().fichierOut)[0] + ext nomFichier = os.path.splitext(self.parent().fichierOut)[0] + ext
with open(nomFichier, 'w') as f: with open(nomFichier, 'w') as f:
f.write(cmds) f.write(cmds)
self.make_executable(nomFichier) self.make_executable(nomFichier)
if verbose: print("INFO: MGSurfOpt launch script file: %s" % nomFichier) if verbose: print("INFO: MGSurfOpt launch script file: %s" % nomFichier)
@ -98,12 +98,12 @@ class MonViewText(Ui_ViewExe, QDialog):
if fn.isNull() : return if fn.isNull() : return
ulfile = os.path.abspath(unicode(fn)) ulfile = os.path.abspath(unicode(fn))
try: try:
f = open(fn, 'wb') f = open(fn, 'wb')
f.write(str(self.TB_Exe.toPlainText())) f.write(str(self.TB_Exe.toPlainText()))
f.close() f.close()
except IOError, why: except IOError, why:
QMessageBox.critical(self, 'Save File', QMessageBox.critical(self, 'Save File',
'The file <b>%1</b> could not be saved.<br>Reason: %2'%(unicode(fn), str(why))) 'The file <b>%1</b> could not be saved.<br>Reason: %2'%(unicode(fn), str(why)))
def readFromStdErr(self): def readFromStdErr(self):
a=self.monExe.readAllStandardError() a=self.monExe.readAllStandardError()
@ -119,7 +119,7 @@ class MonViewText(Ui_ViewExe, QDialog):
self.enregistreResultatsDone=True self.enregistreResultatsDone=True
def theClose(self): def theClose(self):
if not self.enregistreResultatsDone: if not self.enregistreResultatsDone:
self.parent().enregistreResultat() self.parent().enregistreResultat()
self.enregistreResultatsDone=True self.enregistreResultatsDone=True
self.close() self.close()

View File

@ -86,7 +86,7 @@ class PluginDialog(QDialog):
self.__ui.btnClear.setIcon(icon) self.__ui.btnClear.setIcon(icon)
# Then, we can connect the slot to there associated button event # Then, we can connect the slot to there associated button event
self.__ui.btnInput.clicked.connect( self.onInput ) self.__ui.btnInput.clicked.connect( self.onInput )
self.__ui.btnCompute.clicked.connect( self.onCompute ) self.__ui.btnCompute.clicked.connect( self.onCompute )
self.__ui.btnRefresh.clicked.connect( self.onRefresh ) self.__ui.btnRefresh.clicked.connect( self.onRefresh )
self.__ui.btnPublish.clicked.connect( self.onPublish ) self.__ui.btnPublish.clicked.connect( self.onPublish )
@ -139,7 +139,7 @@ class PluginDialog(QDialog):
self.__inputDialog.windowFlags() | Qt.WindowStaysOnTopHint) self.__inputDialog.windowFlags() | Qt.WindowStaysOnTopHint)
# The signal inputValidated emitted from inputDialog is # The signal inputValidated emitted from inputDialog is
# connected to the slot function onProcessInput: # connected to the slot function onProcessInput:
self.__inputDialog.inputValidated.connect( self.onProcessInput ) self.__inputDialog.inputValidated.connect( self.onProcessInput )
else: else:
self.__ui.frameInput.setVisible(True) self.__ui.frameInput.setVisible(True)
@ -401,6 +401,3 @@ def TEST_PluginDialog():
if __name__ == "__main__": if __name__ == "__main__":
TEST_PluginDialog() TEST_PluginDialog()