예제 #1
0
    def __run(self, args=None, with_gui=False):
        if args is None:
            args = []

        sys.argv = ['runSalome'] + args

        if with_gui:
            # :WARNING: NOT TESTED YET
            sys.argv += ["--gui"]
            sys.argv += ["--show-desktop=1"]
            sys.argv += ["--splash=0"]
            #sys.argv += ["--standalone=study"]
            #sys.argv += ["--embedded=SalomeAppEngine,cppContainer,registry,moduleCatalog"]
        else:
            sys.argv += ["--terminal"]
            #sys.argv += ["--shutdown-servers=1"]
            #sys.argv += ["--modules=MED,PARAVIS,GUI"]
            pass

        import setenv
        setenv.main(True)
        import runSalome
        runSalome.runSalome()

        if not with_gui:
            import salome
            salome.salome_init()
            session_server = salome.naming_service.Resolve('/Kernel/Session')
            if session_server:
                session_server.emitMessage("connect_to_study")
                session_server.emitMessage("activate_viewer/ParaView")
                pass
예제 #2
0
    def autosave(self):
        """Calls SALOME save mechanism"""

        # disable pylint, `salome` module only known within salome python shell
        import salome  # pragma pylint: disable=import-error
        salome.salome_init()  # necessary or not?
        salome.myStudyManager.Save(salome.myStudy, False)
예제 #3
0
def the8vertices(complaint="Shape1", pause=1):
    import salome
    salome.salome_init()
    import GEOM
    import time
    #
    delobjregex(".*phere.*$", "t")
    #
    # zoom
    obj_name1 = [complaint]  #zoom object
    obj_name2 = []  #environment object
    zoomobj(-1, -1, -1, -1, obj_name1, obj_name2, "OCCViewer")  # ok
    #
    Shape1 = salome.myStudy.FindObjectByName(complaint,
                                             "GEOM")[0].GetObject()  #.GetID()
    #def:
    VP = (geompy.SubShapeAll(Shape1, geompy.ShapeType["VERTEX"]))  #shape
    for i in range(0, len(VP)):
        sphere = geompy.MakeSpherePntR(VP[i], 20)
        sphere_id = geompy.addToStudy(sphere, "Sphere12" + str(i))
        salome.sg.updateObjBrowser(salome.myStudy._get_StudyId())
        gg.createAndDisplayGO(sphere_id)
        gg.setDisplayMode(sphere_id, 1)
        gg.setColor(sphere_id, 255 - 255 * i / len(VP), 165, 31)
        gg.setTransparency(sphere_id, 0.01)
        print "vertex" + str(i)
        time.sleep(pause)
예제 #4
0
def the8vertices(complaint="Shape1", pause=1):
    import salome

    salome.salome_init()
    import GEOM
    import time

    #
    delobjregex(".*phere.*$", "t")
    #
    # zoom
    obj_name1 = [complaint]  # zoom object
    obj_name2 = []  # environment object
    zoomobj(-1, -1, -1, -1, obj_name1, obj_name2, "OCCViewer")  # ok
    #
    Shape1 = salome.myStudy.FindObjectByName(complaint, "GEOM")[0].GetObject()  # .GetID()
    # def:
    VP = geompy.SubShapeAll(Shape1, geompy.ShapeType["VERTEX"])  # shape
    for i in range(0, len(VP)):
        sphere = geompy.MakeSpherePntR(VP[i], 20)
        sphere_id = geompy.addToStudy(sphere, "Sphere12" + str(i))
        salome.sg.updateObjBrowser(salome.myStudy._get_StudyId())
        gg.createAndDisplayGO(sphere_id)
        gg.setDisplayMode(sphere_id, 1)
        gg.setColor(sphere_id, 255 - 255 * i / len(VP), 165, 31)
        gg.setTransparency(sphere_id, 0.01)
        print "vertex" + str(i)
        time.sleep(pause)
예제 #5
0
def TEST_CreateGeometry():
    import salome
    salome.salome_init()
    import GEOM
    from salome.geom import geomBuilder
    geompy = geomBuilder.New(salome.myStudy)
    import SALOMEDS
    geompy.init_geom(salome.myStudy)
    Box_1 = geompy.MakeBoxDXDYDZ(200, 200, 200)
    edges = geompy.SubShapeAllSorted(Box_1, geompy.ShapeType["EDGE"])
    geompy.addToStudy(Box_1, "Box_1")
    for i in range(len(edges)):
        geompy.addToStudyInFather(Box_1, edges[i], "Edge_%d" % i)
    faces = geompy.SubShapeAllSorted(Box_1, geompy.ShapeType["FACE"])
    faces[3].SetColor(SALOMEDS.Color(1.0,0.5,0.0))
    faces[4].SetColor(SALOMEDS.Color(0.0,1.0,0.5))
    for i in range(len(faces)):
        geompy.addToStudyInFather(Box_1, faces[i], "Face_%d" % i)
    Cylinder_1 = geompy.MakeCylinderRH(50, 200)
    geompy.TranslateDXDYDZ(Cylinder_1, 300, 300, 0)
    cyl_faces = geompy.SubShapeAllSorted(Cylinder_1, geompy.ShapeType["FACE"])
    geompy.addToStudy(Cylinder_1, "Cylinder_1")
    for i in range(len(cyl_faces)):
        geompy.addToStudyInFather(Cylinder_1, cyl_faces[i], "CylFace_%d" % i)
    Cylinder_2 = geompy.MakeTranslation(Cylinder_1, 100, 100, 0)
    cyl_faces2 = geompy.SubShapeAllSorted(Cylinder_2,
                                          geompy.ShapeType["FACE"])
    geompy.addToStudy(Cylinder_2, "Cylinder_2")
    for i in range(len(cyl_faces2)):
        geompy.addToStudyInFather(Cylinder_2, cyl_faces2[i],
                                  "CylFace2_%d" % i)
예제 #6
0
def CreateRdExtGlobalVar(value, varName, scopeName):
    import salome
    salome.salome_init()
    dsm = salome.naming_service.Resolve("/DataServerManager")
    d2s, isCreated = dsm.giveADataScopeCalled(scopeName)
    return GetHandlerFromRef(
        d2s.createRdExtVar(varName,
                           cPickle.dumps(value, cPickle.HIGHEST_PROTOCOL)),
        False)
예제 #7
0
 def __init__(self, studyId = None):
     salome.salome_init()
     if studyId is None:
         studyId = getActiveStudyId()
     self.studyId = studyId
     self.study = salome.myStudyManager.GetStudyByID(studyId)
     if self.study is None:
         raise Exception("Can't create StudyEditor object: "
                         "Study %d doesn't exist" % studyId)
     self.builder = self.study.NewBuilder()
예제 #8
0
 def __init__(self, studyId=None):
     salome.salome_init()
     if studyId is None:
         studyId = getActiveStudyId()
     self.studyId = studyId
     self.study = salome.myStudyManager.GetStudyByID(studyId)
     if self.study is None:
         raise Exception("Can't create StudyEditor object: "
                         "Study %d doesn't exist" % studyId)
     self.builder = self.study.NewBuilder()
예제 #9
0
    def importPlugins(self):
        """Execute the salome_plugins file that contains plugins definition """
        studyId = sg.getActiveStudyId()
        if studyId == 0:
            self.menu.clear()
            self.menu.menuAction().setVisible(False)
            return
        elif self.lasttime == 0 or salome.myStudy == None:
            salome.salome_init(embedded=1)

        lasttime = 0

        plugins_files = []
        plugins_file_name = self.name + MATCH_ENDING_PATTERN
        for directory in self.plugindirs:
            plugins_file = os.path.join(directory, plugins_file_name)
            if os.path.isfile(plugins_file):
                plugins_files.append((directory, plugins_file))
                lasttime = max(lasttime, os.path.getmtime(plugins_file))

        plugins_files.sort()

        if not plugins_files:
            self.registry.clear()
            self.handlers.clear()
            self.entries = []
            self.lasttime = 0
            self.menu.clear()
            self.menu.menuAction().setVisible(False)
            return

        if self.plugins_files != plugins_files or lasttime > self.lasttime:
            global current_plugins_manager
            current_plugins_manager = self
            self.registry.clear()
            self.handlers.clear()
            self.entries = []
            self.lasttime = lasttime
            for directory, plugins_file in plugins_files:
                logger.debug("look for python path: %s" % directory)
                if directory not in sys.path:
                    sys.path.insert(0, directory)
                    logger.debug(
                        "The directory %s has been added to PYTHONPATH" %
                        directory)
                try:
                    execfile(plugins_file, globals(), {})
                except:
                    logger.fatal("Error while loading plugins from file %s" %
                                 plugins_file)
                    traceback.print_exc()

            self.updateMenu()
예제 #10
0
def getActiveStudyId():
    """
    Return the ID of the active study. In GUI mode, this function is equivalent
    to ``salome.sg.getActiveStudyId()``. Outside GUI, it returns
    ``salome.myStudyId`` variable.
    """
    salome.salome_init()
    # Warning: we don't use salome.getActiveStudy() here because it doesn't
    # work properly when called from Salome modules (multi-study interpreter
    # issue)
    if salome.hasDesktop():
        return salome.sg.getActiveStudyId()
    else:
        return salome.myStudyId
    def importPlugins(self):
        """Execute the salome_plugins file that contains plugins definition """
        studyId=sg.getActiveStudyId()
        if studyId == 0:
          self.menu.clear()
          self.menu.menuAction().setVisible(False)
          return
        elif self.lasttime ==0 or salome.myStudy == None:
          salome.salome_init(embedded=1)

        lasttime=0

        plugins_files=[]
        plugins_file_name=self.name+MATCH_ENDING_PATTERN
        for directory in self.plugindirs:
          plugins_file = os.path.join(directory,plugins_file_name)
          if os.path.isfile(plugins_file):
            plugins_files.append((directory,plugins_file))
            lasttime=max(lasttime,os.path.getmtime(plugins_file))

        plugins_files.sort()

        if not plugins_files:
          self.registry.clear()
          self.handlers.clear()
          self.entries=[]
          self.lasttime=0
          self.menu.clear()
          self.menu.menuAction().setVisible(False)
          return

        if self.plugins_files != plugins_files or lasttime > self.lasttime:
          global current_plugins_manager
          current_plugins_manager=self
          self.registry.clear()
          self.handlers.clear()
          self.entries=[]
          self.lasttime=lasttime
          for directory,plugins_file in plugins_files:
            logger.debug("look for python path: %s"%directory)
            if directory not in sys.path:
              sys.path.insert(0,directory)
              logger.debug("The directory %s has been added to PYTHONPATH"%directory)
            try:
              execfile(plugins_file,globals(),{})
            except:
              logger.fatal("Error while loading plugins from file %s"%plugins_file)
              traceback.print_exc()

          self.updateMenu()
예제 #12
0
def getActiveStudyId():
    """
    Return the ID of the active study. In GUI mode, this function is equivalent
    to ``salome.sg.getActiveStudyId()``. Outside GUI, it returns
    ``salome.myStudyId`` variable.
    """
    salome.salome_init()
    # Warning: we don't use salome.getActiveStudy() here because it doesn't
    # work properly when called from Salome modules (multi-study interpreter
    # issue)
    if salome.hasDesktop():
        return salome.sg.getActiveStudyId()
    else:
        return salome.myStudyId
예제 #13
0
def loadSpadderCatalog():
    import salome
    salome.salome_init()
    obj = salome.naming_service.Resolve('Kernel/ModulCatalog')
    import SALOME_ModuleCatalog
    catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
    if not catalog:
        raise RuntimeError, "Can't accesss module catalog"

    filename = getSpadderCatalogFilename()
    catalog.ImportXmlCatalogFile(filename)

    from salome.kernel import services
    print "The list of SALOME components is now:" 
    print services.getComponentList()
예제 #14
0
  def initNS( self, args ) :
    """
    Obtains a reference to the root naming context
    """
    try :
      # Try to connect to the existing SALOME session 
      obj = self.orb.resolve_initial_references( "NameService" )
      self.rootContext = obj._narrow( CosNaming.NamingContext )

      # Try to connect to already existing SALOME study
      from salome import salome_init
      salome_init( theStudyId = 1 )
    except :
      # Try to launch a new session of SALOME 

      # Obtain SALOME configuration parameters
      from setenv import get_config
      args, modules_list, modules_root_dir = get_config()

      from runSalome import kill_salome
      kill_salome( args )

      # To generate a new SALOME configuration
      from runSalome import searchFreePort
      searchFreePort( args, 0 )

      # Starting of SALOME application 
      from runSalome import startSalome
      startSalome( args, modules_list, modules_root_dir )

      # To call the carresponding method of base class
      orbmodule.client.initNS( self, args )

      # Try to create a new SALOME study
      from salome import salome_init
      salome_init( theStudyId = 0 )
      pass

    self.showNS() # Prints debug information (can be commented)

    # It is necessary to wait untill it will be possible 
    # to get access to some important SALOME services
    self.waitNS( "/Kernel/Session" )
    self.waitNS( "/Kernel/ModulCatalog" )
    self.waitNS( "/myStudyManager" )

    pass
    def __init__(self, case_dir, params_cfg, package, run_prefix=None):
        """
        Class constructor
        """

        # Initialize the salome services
        salome.salome_init()

        self.case_dir        = case_dir
        self.case_name       = os.path.split(self.case_dir)[1]

        self.study_dir       = os.path.split(self.case_dir)[0]
        self.study_name      = os.path.split(self.study_dir)[1]

        self.pkg             = package

        self.cfg             = params_cfg
        self.host            = self.cfg.get('host_parameters', 'host_name')
        self.host_arch_path  = self.cfg.get('host_parameters', 'arch_path')
        self.host_build_name = self.cfg.get('host_parameters', 'build_name')
        self.host_bin_path   = os.path.join(self.host_arch_path,
                                            self.host_build_name,
                                            'bin')

        self.dist_wdir       = self.cfg.get('batch_parameters', 'distant_workdir')
        self.package_name    = self.cfg.get('study_parameters', 'code_name')
        self.paramfile       = self.cfg.get('study_parameters', 'xmlfile')
        self.results_file    = "cs_uncertain_output.dat"

        self.run_prefix = None
        if run_prefix:
            self.run_prefix = run_prefix + "_"

        self.run_id = None
        tmp = os.getcwd()
        os.chdir(self.case_dir)
        self.__setRunId__()
        os.chdir(tmp)

        self.job_params = self.__getJobParameters__()

        self.job_id = -1
        self.job_failed = False
예제 #16
0
def start_client():
  try:
    clt = client()
  except Exception:
    import traceback
    traceback.print_exc()
    sys.exit(1)
  #

  session_server = clt.Resolve('/Kernel/Session')
  if session_server:
    session = clt.waitNS("/Kernel/Session")
  catalog = clt.waitNS("/Kernel/ModulCatalog")
  studyMgr = clt.waitNS("/myStudyManager")

  import salome
  salome.salome_init()
  from salome import lcc
  print "--> now connected to SALOME"
예제 #17
0
def start_client():
    try:
        clt = client()
    except Exception:
        import traceback
        traceback.print_exc()
        sys.exit(1)
    #

    session_server = clt.Resolve('/Kernel/Session')
    if session_server:
        session = clt.waitNS("/Kernel/Session")
    catalog = clt.waitNS("/Kernel/ModulCatalog")
    studyMgr = clt.waitNS("/myStudyManager")

    import salome
    salome.salome_init()
    from salome import lcc
    print "--> now connected to SALOME"
예제 #18
0
def TEST_StructuralElement():
    salome.salome_init()
    TEST_CreateGeometry()
    liste_commandes = [('Orientation', {'MeshGroups': 'Edge_4',
                                        'VECT_Y': (1.0, 0.0, 1.0)}),
                       ('Orientation', {'MeshGroups': 'Edge_5',
                                        'ANGL_VRIL': 45.0}),
                       ('GeneralBeam', {'MeshGroups': ['Edge_1', 'Edge_7'],
                                        'A': 1, 'IY1': 20, 'IY2': 40,
                                        'IZ1': 60, 'IZ2': 30}),
                       ('VisuPoutreCercle', {'MeshGroups': ['Edge_6'],
                                             'R1': 30, 'R2': 20}),
                       ('CircularBeam', {'MeshGroups': ['Edge_2', 'Edge_3'],
                                         'R': 40, 'EP': 20}),
                       ('RectangularBeam', {'MeshGroups': ['Edge_4', 'Edge_5'],
                                            'HZ1': 60, 'HY1': 40,
                                            'EPZ1': 15, 'EPY1': 10,
                                            'HZ2': 40, 'HY2': 60,
                                            'EPZ2': 10, 'EPY2': 15}),
                       ('VisuCable', {'MeshGroups': 'Edge_7', 'R': 5}),
                       ('VisuCoque', {'MeshGroups': 'Face_4',
                                      'Epais': 10, 'Excentre': 5,
                                      'angleAlpha': 45, 'angleBeta': 60}),
                       ('VisuCoque', {'MeshGroups': 'CylFace_2', 'Epais': 5}),
                       ('VisuGrille', {'MeshGroups': 'Face_5', 'Excentre': 5,
                                       'angleAlpha': 45, 'angleBeta': 60}),
                       ('VisuGrille', {'MeshGroups': 'CylFace2_2',
                                       'Excentre': 5, 'origAxeX': 400,
                                       'origAxeY': 400, 'origAxeZ': 0,
                                       'axeX': 0, 'axeY': 0, 'axeZ': 100}),
                      ]

    structElemManager = StructuralElementManager()
    elem = structElemManager.createElement(liste_commandes)
    if salome.hasDesktop():
        elem.display()
        salome.sg.updateObjBrowser(True)
예제 #19
0
 def setUp(self):
     import salome
     salome.salome_init()
예제 #20
0
def getStudyFromStudyId(studyId):
    salome.salome_init()
    study = salome.myStudyManager.GetStudyByID(studyId)
    return study
예제 #21
0
    def start_convtk(self, Flag_json=0):
        SystemSlash = self.SystemSlash
        list_load_path = self._creat_dic()  # 存储目录列表

        # 利用 salome 打开 stp 文件,并进行拆分,另存为 vtk 文件
        salome.salome_init()
        notebook = salome_notebook.NoteBook()
        sys.path.insert(0, list_load_path[7][0])
        geompy = geomBuilder.New()
        O = geompy.MakeVertex(0, 0, 0)
        OX = geompy.MakeVectorDXDYDZ(1, 0, 0)
        OY = geompy.MakeVectorDXDYDZ(0, 1, 0)
        OZ = geompy.MakeVectorDXDYDZ(0, 0, 1)
        try:
            if ".stp" == list_load_path[7][3]:
                Input = geompy.ImportSTEP(self.inputfilePath, False, True)
            elif ".brep" == list_load_path[7][3]:
                Input = geompy.ImportBREP(self.inputfilePath)
            elif ".iges" == list_load_path[7][3]:
                Input = geompy.ImportIGES(self.inputfilePath)

            print("Identification file type successful")
        except Exception:
            print("IOError: file type must be .stp .brep .iges")
            return None

        faces = geompy.ExtractShapes(Input, geompy.ShapeType["FACE"], True)
        face_time = 0
        for index, face in enumerate(faces):
            face_time = face_time + 1
            LoadVTKFPath = list_load_path[
                2] + self.SystemSlash + "Face_%d" % face_time + ".vtk"
            geompy.ExportVTK(face, LoadVTKFPath, 0.00001)

        # 遍历文件夹,查询拆分个数
        Face_file_NM = os.listdir(list_load_path[2])
        NM_files = len(Face_file_NM)
        print(NM_files)

        # 创建stl文件
        Face_stl_path = self.outputfilePath2
        Face_File_stl = open(Face_stl_path, 'w')

        # 创建vtm文件,并写入开头
        Face_VTM = self.outputfilePath1
        file_vtm = open(Face_VTM, 'w')
        file_vtm.write(
            '<VTKFile type="vtkMultiBlockDataSet" version="1.0" byte_order="LittleEndian" header_type="UInt64">'
            + '\n')
        file_vtm.write('  <vtkMultiBlockDataSet>' + '\n')
        file_vtm.write('    <Block index="0" name="face">' + '\n')

        try:
            # 删除vtk文件中的lines信息,将删除后的文件写进RFace文件夹中
            for i in range(NM_files):
                Flag_json = Flag_json + 1
                Read_Face_Path = list_load_path[
                    2] + SystemSlash + "Face_" + str(i + 1) + ".vtk"
                Read_RFace_Path = list_load_path[
                    4] + SystemSlash + "Face_" + str(i + 1) + ".vtk"

                print("rewrite face:{}".format(Read_Face_Path))
                Read_file = open(Read_Face_Path, "r")
                data_Face = Read_file.read()
                Read_file.close()
                with open(Read_RFace_Path, "w") as R_Face_file:
                    data_Face = re.sub("LINES[  \d\n]+", "", data_Face)
                    R_Face_file.write(data_Face)
                # 重写lines信息,并提出所有的cell的pointid构成lines
                RFace_write_path = open(Read_RFace_Path, 'a')
                Read_File_Path = Read_RFace_Path
                face_vtk = LegacyVTKReader(FileNames=Read_File_Path)
                Dict_keys = GetSources().keys()
                # 这里 solame 的GetSources不能直接取到key,需要转换一下key
                Dict_keys = str(Dict_keys)
                p1 = re.compile(r'[[](.*?)[]]', re.S)
                Dict_keys = re.findall(p1, Dict_keys)
                Dict_keys = Dict_keys[0]
                Dict_keys = eval(Dict_keys.replace(')(', '),('))
                facefirest = GetSources()[Dict_keys]
                UpdatePipeline()
                obj = facefirest.SMProxy.GetClientSideObject()
                block = obj.GetOutputDataObject(0)
                NM_Cells = block.GetNumberOfCells()
                list_afterPoint = []
                list_pointIdAll = []  # 所有单元构成的线
                for L in range(NM_Cells):
                    Cell_Point_NM = block.GetCellType(L)
                    while Cell_Point_NM == 5:
                        This_Cell = block.GetCell(L)
                        list_PointId = []
                        for T in range(Cell_Point_NM - 2):
                            pointID = This_Cell.GetPointId(T)
                            list_PointId.append(pointID)
                        list_PointId.sort()
                        list_PointId = list(
                            itertools.combinations(list_PointId, 2))
                        for R in range(3):
                            list_pointIdAll.append(list_PointId[R])
                        break
                # 将没有重复的点加入到list_afterPoint中
                list_afterPoint = [
                    item for item, count in collections.Counter(
                        list_pointIdAll).items() if count == 1
                ]
                RFace_write_path.write("LINES" + " " +
                                       str(len(list_afterPoint)) + " " +
                                       str(len(list_afterPoint) * 3) + "\n")
                for Q in range(len(list_afterPoint)):
                    Write_line = str(list_afterPoint[Q])
                    Write_line = Write_line.replace("L", '').replace(
                        "(", "").replace(")", "").replace(",", "")
                    RFace_write_path.write("2 " + Write_line + "\n")
                Delete()
                RFace_write_path.close()
                Read_file = open(Read_RFace_Path, "r")
                data_Wire = Read_file.read()
                Read_file.close()
                with open(
                        list_load_path[3] + SystemSlash + "Wire_" +
                        str(i + 1) + ".vtk", "w") as R_Wire_file:
                    data_Wire = re.sub("POLYGONS[  \d\n]+", "", data_Wire)
                    R_Wire_file.write(data_Wire)

                face_vtk = LegacyVTKReader(FileNames=Read_RFace_Path)
                # 使其表面光滑
                generateSurfaceNormals1 = GenerateSurfaceNormals(
                    Input=face_vtk)
                # 同时转换.stl文件
                Dict_keys = GetSources().keys()
                # 这里solame的GetSources不能直接取到key,需要转换一下key
                Dict_keys = str(Dict_keys)
                p1 = re.compile(r'[[](.*?)[]]', re.S)
                Dict_keys = re.findall(p1, Dict_keys)
                Dict_keys = Dict_keys[0]
                Dict_keys = eval(Dict_keys.replace(')(', '),('))
                facefirest = GetSources()[Dict_keys[0]]
                UpdatePipeline()
                obj = facefirest.SMProxy.GetClientSideObject()
                block = obj.GetOutputDataObject(0)
                NM_Cells = block.GetNumberOfCells()
                Face_File_stl.write('solid ' + 'Face_' + str(i + 1) + '\n')
                # 遍历vtk中所有的cell,并取每个cell的3个点
                for L in range(NM_Cells):
                    Cell_Point_NM = block.GetCellType(L)
                    while Cell_Point_NM == 5:
                        Face_File_stl.write(' facet normal 0 0 0' + '\n')
                        Face_File_stl.write('  outer loop' + '\n')
                        This_Cell = block.GetCell(L)
                        for T in range(Cell_Point_NM - 2):
                            pointID = This_Cell.GetPointId(T)
                            pointCon = block.GetPoint(pointID)
                            W_Line = str(pointCon)
                            W_Line = W_Line.replace("(", " ").replace(
                                ")", " ").replace(",", " ")  # 去除列表中的小括号和逗号
                            Face_File_stl.write('   vertex ' + W_Line + '\n')
                        Face_File_stl.write('  endloop' + '\n')
                        Face_File_stl.write(' endfacet' + '\n')
                        break
                Face_File_stl.write('endsolid' + '\n')
                # 转换.vtm
                Load_File_Path = list_load_path[
                    5] + SystemSlash + "Face_" + str(i + 1) + ".vtp"
                # 将相关信息写入.vtm中
                Write_file = 'face' + SystemSlash + 'Face_' + str(i +
                                                                  1) + '.vtp'
                file_vtm.write('      <DataSet index="' + str(i) + '"' +
                               ' name="' + 'Face_' + str(i + 1) + '" file="' +
                               Write_file + '">' + '\n')
                file_vtm.write('      </DataSet>' + '\n')
                SaveData(Load_File_Path, proxy=generateSurfaceNormals1)
                Delete()
                Delete(face_vtk)
            file_vtm.write('    </Block>' + '\n')
            file_vtm.write('    <Block index="1" name="Wires">' + '\n')
            for i in range(NM_files):
                Read_Wire_Path = list_load_path[
                    3] + SystemSlash + "Wire_" + str(i + 1) + ".vtk"
                wire_vtk = LegacyVTKReader(FileNames=Read_Wire_Path)
                # 转换.vtm
                Load_File_Path = list_load_path[
                    6] + SystemSlash + "Wire_" + str(i + 1) + ".vtp"
                Write_file = 'wire' + SystemSlash + 'Wire_' + str(i +
                                                                  1) + '.vtp'
                file_vtm.write('      <DataSet index="' + str(i) + '"' +
                               ' name="' + 'Wire_' + str(i + 1) + '" file="' +
                               Write_file + '">' + '\n')
                file_vtm.write('      </DataSet>' + '\n')
                SaveData(Load_File_Path, proxy=wire_vtk)
                Delete()

            file_vtm.write('    </Block>' + '\n')
            file_vtm.write('  </vtkMultiBlockDataSet>' + '\n')
            file_vtm.write('</VTKFile>' + '\n')
            print("rewrite face successful")
            print("rewrite wire successful")

            res_json = {"faceNumber": NM_files}
            print("result json|{}".format(json.dumps(res_json)))
        except Exception:
            print("Error:conversion died")
            return None
        del SystemSlash, list_load_path
        file_vtm.close()
        Face_File_stl.close()
        return Flag_json
예제 #22
0
def GetHandlerFromName(varName, scopeName):
    import salome
    salome.salome_init()
    dsm = salome.naming_service.Resolve("/DataServerManager")
    d2s = dsm.retriveDataScope(scopeName)
    return GetHandlerFromRef(d2s.retrieveVar(varName), False)
 def setUp(self):
   salome.salome_init()
   pass
예제 #24
0
def TEST_createGeometry():
    salome.salome_init()
    theStudy = salome.myStudy
    createGeometry(theStudy)
예제 #25
0
def TEST_exportModel():
    salome.salome_init()
    theStudy=salome.myStudy
    shape = createGeometryWithPartition(theStudy)
    mesh  = createMesh(theStudy, shape)
    exportModel(mesh,"tubemesh.med")
예제 #26
0
def extractFeatureEdges(body, minFeatureAngle=5):
    '''
    Find all feature edges on the supplied body and return them as a list
    of edge ids.

        body - A Salome solid, compound, shell or face object to find all
                feature edges on.
        minFeatureAngle - the angle (in degrees) between adjacent surfaces
                above which the edge will be considered a feature angle.
    '''
    import salome
    salome.salome_init()

    import GEOM
    from salome.geom import geomBuilder
    geompy = geomBuilder.New(salome.myStudy)

    # Check the body type
    if not (body.GetShapeType()
            in [GEOM.SHELL, GEOM.SOLID, GEOM.FACE, GEOM.COMPOUND]):
        raise RuntimeError('Supplied object is not a solid, shell or face.')

    print 'Extracting edges of %s with feature angle > %g.' % (body.GetName(),
                                                               minFeatureAngle)

    # Extract basic info
    faces = geompy.SubShapeAll(body, geompy.ShapeType["FACE"])
    curves = geompy.SubShapeAll(body, geompy.ShapeType["EDGE"])
    points = geompy.SubShapeAll(body, geompy.ShapeType["VERTEX"])

    faceIds = geompy.GetSubShapesIDs(body, faces)
    curveIds = geompy.GetSubShapesIDs(body, curves)
    nodeIds = geompy.GetSubShapesIDs(body, points)

    maxFaceId = max(faceIds)
    maxCurveId = max(curveIds)
    maxNodeId = max(nodeIds)

    # Reverse mapping from curve id to local curve arrays
    faceMap = [-1 for i in xrange(maxFaceId + 1)]
    for localId, id in enumerate(faceIds):
        faceMap[id] = localId

    curveMap = [-1 for i in xrange(maxCurveId + 1)]
    for localId, id in enumerate(curveIds):
        curveMap[id] = localId

    nodeMap = [-1 for i in xrange(maxNodeId + 1)]
    for localId, id in enumerate(nodeIds):
        nodeMap[id] = localId

    # Get curves on each face
    faceCurveIds = [[
        curveMap[id] for id in geompy.GetSubShapesIDs(
            body, geompy.SubShapeAll(face, geompy.ShapeType["EDGE"]))
    ] for face in faces]

    # Get faces attached to each curve
    curveFaceIds = [[] for id in curveIds]

    for faceI, ids in enumerate(faceCurveIds):
        for id in ids:
            curveFaceIds[id].append(faceI)

    # Now that we have the connectivity for curves and faces find the
    # feature edges
    featureEdgeIds = []
    for curveId, curve, adjFaceIds in zip(curveIds, curves, curveFaceIds):
        if len(adjFaceIds) == 2:
            # Curve with 2 adjacent faces - Test feature angle
            # Determine break angle at each curve
            # If greater than the feature edge angle, add the curve to group featureEdges
            face1 = faces[adjFaceIds[0]]
            face2 = faces[adjFaceIds[1]]
            point = geompy.GetFirstVertex(curve)  # Test at the first vertex
            n1 = geompy.GetNormal(face1, point)
            n2 = geompy.GetNormal(face2, point)
            angle = geompy.GetAngle(n1, n2)
            if angle > minFeatureAngle:
                featureEdgeIds.append(curveId)

        elif len(adjFaceIds) == 1:
            # Curve on standalone face - Add by default
            featureEdgeIds.append(curveId)

        elif len(adjFaceIds) == 0:
            # Standalone curve - Ignore
            None

        else:
            raise RuntimeError(
                'Curve found sharing %d faces. This is unexpected for fully enclosed bodies.'
                % len(adjFaceIds))

    # Done
    print "%d feature edges found" % len(featureEdgeIds)

    return featureEdgeIds
예제 #27
0
def CreateRdExtGlobalVar(value,varName,scopeName):
    import salome
    salome.salome_init()
    dsm=salome.naming_service.Resolve("/DataServerManager")
    d2s,isCreated=dsm.giveADataScopeCalled(scopeName)
    return GetHandlerFromRef(d2s.createRdExtVar(varName,cPickle.dumps(value,cPickle.HIGHEST_PROTOCOL)),False)
예제 #28
0
def createTunnel(fileName, kwargs, doGUI=False,doMeshing=True,killSalomeAfter=True):
    '''
    @author: Vance Turnewitsch
    @date: Feb 20, 2014
    This code is to be run with salome-meca 2014.1 not an earlier version.
    '''
    try:
        import salome
        import math
    
        salome.salome_init()
        import GEOM
        from salome.geom import geomBuilder
        theStudy = salome.myStudy
        #from SMESH_mechanic import SMESH
    
        geompy = geomBuilder.New(salome.myStudy)
        if doGUI:
            gg = salome.ImportComponentGUI("GEOM")
    
        #import SMESH
        #from salome.smesh import smeshBuilder
    
        # Get the parameters
        diskX = kwargs['diskX']
        diskY = kwargs['diskY']
        diskZ = kwargs['diskZ']
    
        diskHeight = kwargs['diskHeight']
        diskRadius = kwargs['diskRadius']
        tunnelHeight = kwargs['tunnelHeight']
        tunnelRadius = kwargs['tunnelRadius']
        '''
        tunnelFineness=kwargs['tunnelFineness']
        diskFineness=kwargs['diskFineness']
    
        tunnelMaxTetraSize=kwargs['tunnelMaxTetraSize']
        tunnelMinTetraSize=kwargs['tunnelMinTetraSize']
        diskMaxTetraSize=kwargs['diskMaxTetraSize']
        diskMinTetraSize=kwargs['diskMinTetraSize']
        '''
        tunnelMaxSize = kwargs['tunnelMaxSize']
        
        # These are the raw coordinates for the shroud points
        shroudCoords = kwargs['shroudPoints']
        # This is the thickness of the shroud material
        shroudThickness = kwargs['shroudThickness']
    
        print "Creating tunnel with following properties:",kwargs
    
        #smesh = smeshBuilder.New(salome.myStudy)
    
        # Make the actuator disk
        startDiskBase = geompy.MakeVertex(diskX, diskY, diskZ)
        startDiskBaseID = geompy.addToStudy(startDiskBase, 'StartDiskBase')
        if doGUI:
            gg.createAndDisplayGO(startDiskBaseID)
    
        vx = geompy.MakeVectorDXDYDZ(100, 0, 0)
        vxID = geompy.addToStudy(vx, 'vx')
    
    
        if doGUI:
            gg.createAndDisplayGO(vxID)
    
        diskCyl = geompy.MakeCylinder(startDiskBase, vx, diskRadius, diskHeight)
        diskCylID = geompy.addToStudy(diskCyl, 'Disk')
        #geompy.addToStudy(diskCyl,'Disk')
        if doGUI:
            gg.createAndDisplayGO(diskCylID)
    
        # Make the cyliner
        origin = geompy.MakeVertex(0, 0, 0)
        tunnelCyl = geompy.MakeCylinder(origin, vx, tunnelRadius, tunnelHeight)
        
        # Make the shroud
        # The actual shroud vertices created from the raw data points
        shroudPoints = []
        # We better sort the points first
        shroudCoords.sort(key=lambda item: item[0])
        print "The shroud points to be meshed>",shroudCoords
        print "The sorted shroud coords:",shroudCoords
        for raw in shroudCoords:
            # The points are in x and z
            vertex = geompy.MakeVertex(raw[0],0,raw[1])
            shroudPoints.append(vertex)
            geompy.addToStudy(vertex,'Point:'+str(raw[0]))
            
        # Now make the line that we will extrude for the base that gets revolved
        ShroudLine = geompy.MakePolyline(shroudPoints)
        geompy.addToStudy(ShroudLine,'ShroudLine')
        # Now make a vector so that we can extrude this line
        vz = geompy.MakeVectorDXDYDZ(0,0,1)
        geompy.addToStudy(vz,'vz')
        # This is the extruded shroud line
        ShroudOutline = geompy.MakePrismVecH(ShroudLine,vz,0.25)
        geompy.addToStudy(ShroudOutline,'ShroudOutline')
        # Let's make the shroud!
        Shroud = geompy.MakeRevolution2Ways(ShroudOutline,vx,180*math.pi/180.0)
        geompy.addToStudy(Shroud,'Shroud')
    
        # Now make the tunnel by cutting the disk from cylinder and then the shroud
        tunnel = geompy.MakeCut(tunnelCyl, diskCyl)
        tunnel = geompy.MakeCut(tunnel,Shroud)
        tunnelID = geompy.addToStudy(tunnel, 'Tunnel')
    
        if doGUI:
            gg.createAndDisplayGO(tunnelID)
            gg.setDisplayMode(tunnelID, 1)
    
        # Get the faces of the Tunnel
        inletFace = geompy.GetShapesOnPlaneWithLocationIDs(tunnel, geompy.ShapeType["FACE"], vx, origin, GEOM.ST_ON)
        if len(inletFace) == 1:
            print "Got inlet face:", inletFace[0]
            inletFace = inletFace[0]
    
        outletFace = geompy.GetShapesOnPlaneWithLocationIDs(tunnel, geompy.ShapeType["FACE"], vx,
                                                            geompy.MakeVertex(tunnelHeight, 0, 0), GEOM.ST_ON)
        if len(outletFace) == 1:
            print "Got outlet face:", outletFace[0]
            outletFace = outletFace[0]
    
        tunnelWall = geompy.GetShapesOnCylinderWithLocationIDs(tunnel, geompy.ShapeType["FACE"], vx, origin, tunnelRadius,GEOM.ST_ON)
        if len(tunnelWall) == 1:
            print "Got tunnelWall:", tunnelWall[0]
            tunnelWall = tunnelWall[0]
    
        diskInletFace = geompy.GetShapesOnPlaneWithLocationIDs(tunnel, geompy.ShapeType["FACE"], vx, startDiskBase,GEOM.ST_ON)
        if len(diskInletFace) == 1:
            print "Got inlet face:", diskInletFace[0]
            diskInletFace = diskInletFace[0]
    
        diskOutletFace = geompy.GetShapesOnPlaneWithLocationIDs(tunnel, geompy.ShapeType["FACE"], vx,geompy.MakeVertex(diskX + diskHeight, diskY, diskZ),GEOM.ST_ON)
        if len(diskOutletFace) == 1:
            print "Got outlet face:", diskOutletFace[0]
            diskOutletFace = diskOutletFace[0]
    
        diskWall = geompy.GetShapesOnCylinderWithLocationIDs(tunnel, geompy.ShapeType["FACE"], vx, startDiskBase,diskRadius, GEOM.ST_ON)
        if len(diskWall) == 1:
            print "Got diskWall:", diskWall[0]
            diskWall = diskWall[0]
    
        # Build the groups of the faces of the tunnel
        def createFaceGroup(theGeom, groupName, *faces):
            '''
            @Return: The group created
            '''
            print "Creating group:", groupName
            theGroup = geompy.CreateGroup(theGeom, geompy.ShapeType["FACE"])
            for face in faces:
                print "Adding a face to group:", groupName
                geompy.AddObject(theGroup, face)
            if doGUI:
                groupID = geompy.addToStudyInFather(theGeom, theGroup, groupName)
    
            if doGUI:
                gg.createAndDisplayGO(groupID)
            return theGroup
    
        inletGroup = createFaceGroup(tunnel, 'Inlet', inletFace)
        outletGroup = createFaceGroup(tunnel, 'Outlet', outletFace)
        wallGroup = createFaceGroup(tunnel, 'TunnelWall', tunnelWall)
    
        diskInletGroup = createFaceGroup(tunnel, 'DiskInlet', diskInletFace)
        diskOutletGroup = createFaceGroup(tunnel, 'DiskOutlet', diskOutletFace)
        diskWallGroup = createFaceGroup(tunnel, 'DiskWall', diskWall)
        
        # Create the group for the 
        AllFaces = geompy.CreateGroup(tunnel, geompy.ShapeType["FACE"])
        AllFaceIDs = geompy.SubShapeAllSortedCentresIDs(tunnel,geompy.ShapeType["FACE"])
        geompy.UnionIDs(AllFaces, AllFaceIDs)
        tunnelWallGroup = geompy.CutListOfGroups([AllFaces], [inletGroup,outletGroup,wallGroup,diskInletGroup,diskOutletGroup,diskWallGroup])
        geompy.addToStudyInFather(tunnel,AllFaces,'AllFaces')
        geompy.addToStudyInFather(tunnel,tunnelWallGroup,'TunnelWall')
    
        # Get faces on the disk
        diskInletFace_Orig = geompy.GetShapesOnPlaneWithLocationIDs(diskCyl, geompy.ShapeType["FACE"], vx, startDiskBase, GEOM.ST_ON)[0]
        diskOutletFace_Orig = geompy.GetShapesOnPlaneWithLocationIDs(diskCyl, geompy.ShapeType["FACE"], vx,geompy.MakeVertex(diskX + diskHeight, 0, 0),GEOM.ST_ON)[0]
        diskWallFace_Orig = geompy.GetShapesOnCylinderWithLocationIDs(diskCyl, geompy.ShapeType["FACE"], vx, startDiskBase, diskRadius,GEOM.ST_ON)[0]
    
        # Create the face groups of the disk
        diskInletGroup_Orig = createFaceGroup(diskCyl, 'DiskInletOrig', diskInletFace_Orig)
        diskOutletGroup_Orig = createFaceGroup(diskCyl, 'DiskOutletOrig', diskOutletFace_Orig)
        diskWallGroup_Orig = createFaceGroup(diskCyl, 'DiskWallOrig', diskWallFace_Orig)
    
        ###
        ### SMESH component
        ###
        if doMeshing:
            import  SMESH, SALOMEDS
            from salome.smesh import smeshBuilder
        
            # calculate the number of segments for the disk
            numOfSegments = round(60.0*3.0/tunnelMaxSize)
            smesh = smeshBuilder.New(theStudy)
            TunnelSansDisk = smesh.Mesh(tunnel)
            Regular_1D = TunnelSansDisk.Segment()
            Max1D_3 = Regular_1D.MaxSize(tunnelMaxSize)
            MEFISTO_2D = TunnelSansDisk.Triangle(algo=smeshBuilder.MEFISTO)
            MaxArea2D_5 = MEFISTO_2D.MaxElementArea(5)
            NETGEN_3D = TunnelSansDisk.Tetrahedron()
            Max2D_3 = smesh.CreateHypothesis('MaxElementArea')
            Max2D_3.SetMaxElementArea( 3 )
            a60_Segments1D = smesh.CreateHypothesis('NumberOfSegments')
            a60_Segments1D.SetNumberOfSegments( int(numOfSegments) )
            a60_Segments1D.SetDistrType( 0 )
            status = TunnelSansDisk.AddHypothesis(Regular_1D,diskInletGroup)
            status = TunnelSansDisk.AddHypothesis(a60_Segments1D,diskInletGroup)
            status = TunnelSansDisk.AddHypothesis(MEFISTO_2D,diskInletGroup)
            status = TunnelSansDisk.AddHypothesis(Max2D_3,diskInletGroup)
            status = TunnelSansDisk.AddHypothesis(Regular_1D,diskOutletGroup)
            status = TunnelSansDisk.AddHypothesis(a60_Segments1D,diskOutletGroup)
            status = TunnelSansDisk.AddHypothesis(MEFISTO_2D,diskOutletGroup)
            status = TunnelSansDisk.AddHypothesis(Max2D_3,diskOutletGroup)
            status = TunnelSansDisk.AddHypothesis(MEFISTO_2D,diskWallGroup)
            status = TunnelSansDisk.AddHypothesis(Max2D_3,diskWallGroup)
            MaxSize_1D_2 = smesh.CreateHypothesis('MaxLength')
            MaxSize_1D_2.SetLength( 2 )
            Disk_1 = smesh.Mesh(diskCyl)
            status = Disk_1.AddHypothesis(MaxSize_1D_2)
            status = Disk_1.AddHypothesis(Regular_1D)
            status = Disk_1.AddHypothesis(Max2D_3)
            status = Disk_1.AddHypothesis(MEFISTO_2D)
            status = Disk_1.AddHypothesis(NETGEN_3D)
            Inlet_1 = TunnelSansDisk.GroupOnGeom(inletGroup,'Inlet',SMESH.FACE)
            Outlet_1 = TunnelSansDisk.GroupOnGeom(outletGroup,'Outlet',SMESH.FACE)
            TunnelWall_1 = TunnelSansDisk.GroupOnGeom(wallGroup,'TunnelWall',SMESH.FACE)
            DiskInlet_1 = TunnelSansDisk.GroupOnGeom(diskInletGroup,'DiskInlet',SMESH.FACE)
            DiskOutlet_1 = TunnelSansDisk.GroupOnGeom(diskOutletGroup,'DiskOutlet',SMESH.FACE)
            DiskWall_1 = TunnelSansDisk.GroupOnGeom(diskWallGroup,'DiskWall',SMESH.FACE)
            ShroudWall_Mesh = TunnelSansDisk.GroupOnGeom(tunnelWallGroup,'ShroudWall',SMESH.FACE)
            Import_1D2D = Disk_1.UseExisting2DElements(geom=diskInletGroup_Orig)
            DiskInlet_Faces = Import_1D2D.SourceFaces([ DiskInlet_1 ],0,0)
            DiskOutlet_Faces = smesh.CreateHypothesis('ImportSource2D')
            DiskOutlet_Faces.SetSourceFaces( [ DiskOutlet_1 ] )
            DiskOutlet_Faces.SetCopySourceMesh( 0, 0 )
            status = Disk_1.AddHypothesis(Import_1D2D,diskOutletGroup_Orig)
            status = Disk_1.AddHypothesis(DiskOutlet_Faces,diskOutletGroup_Orig)
            DiskWall_Faces = smesh.CreateHypothesis('ImportSource2D')
            DiskWall_Faces.SetSourceFaces( [ DiskWall_1 ] )
            DiskWall_Faces.SetCopySourceMesh( 0, 0 )
            status = Disk_1.AddHypothesis(Import_1D2D,diskWallGroup_Orig)
            status = Disk_1.AddHypothesis(DiskWall_Faces,diskWallGroup_Orig)
            isDone = TunnelSansDisk.Compute()
            isDone = Disk_1.Compute()
            Tunnel_1 = smesh.Concatenate([TunnelSansDisk.GetMesh(), Disk_1.GetMesh()], 1, 1, 1e-05)
            [ Inlet_2, Outlet_2, TunnelWall_2, DiskInlet_2, DiskOutlet_2, DiskWall_2, ShroudWall_2 ] = Tunnel_1.GetGroups()
            aCriteria = []
            aCriterion = smesh.GetCriterion(SMESH.VOLUME,SMESH.FT_BelongToGeom,SMESH.FT_EqualTo,diskCyl)#SMESH.VOLUME,SMESH.FT_BelongToGeom,SMESH.FT_Undefined,'Disk')
            aCriteria.append(aCriterion)
            aFilter_1 = smesh.GetFilterFromCriteria(aCriteria)
            aFilter_1.SetMesh(Tunnel_1.GetMesh())
            Disk_2 = Tunnel_1.GroupOnFilter( SMESH.VOLUME, 'Group_1', aFilter_1 )
            Disk_2.SetColor( SALOMEDS.Color( 1, 0.666667, 0 ))
            Disk_2.SetName( 'Disk' )
            DiskInlet_Sub = TunnelSansDisk.GetSubMesh( diskInletGroup, 'DiskInlet_Sub' )
            DiskOutlet_Sub = TunnelSansDisk.GetSubMesh( diskOutletGroup, 'DiskOutlet_Sub' )
            DiskWall_Sub = TunnelSansDisk.GetSubMesh( diskWallGroup, 'DiskWall_Sub' )
            DiskInlet_3 = Import_1D2D.GetSubMesh()
            DiskOutlet_3 = Disk_1.GetSubMesh( diskOutletGroup_Orig, 'DiskOutlet' )
            DiskWall_3 = Disk_1.GetSubMesh( diskWallGroup_Orig, 'DiskWall' )
        
        
            ## Set names of Mesh objects
            smesh.SetName(Regular_1D.GetAlgorithm(), 'Regular_1D')
            smesh.SetName(NETGEN_3D.GetAlgorithm(), 'NETGEN_3D')
            smesh.SetName(MEFISTO_2D.GetAlgorithm(), 'MEFISTO_2D')
            smesh.SetName(MaxArea2D_5, 'MaxArea2D_5')
            smesh.SetName(Import_1D2D.GetAlgorithm(), 'Import_1D2D')
            smesh.SetName(Max1D_3, 'Max1D_3')
            smesh.SetName(a60_Segments1D, '60_Segments1D')
            smesh.SetName(MaxSize_1D_2, 'MaxSize_1D_2')
            smesh.SetName(Inlet_1, 'Inlet')
            smesh.SetName(Outlet_1, 'Outlet')
            smesh.SetName(Max2D_3, 'Max2D_3')
            smesh.SetName(TunnelWall_1, 'TunnelWall')
            smesh.SetName(DiskInlet_1, 'DiskInlet')
            smesh.SetName(DiskInlet_Sub, 'DiskInlet_Sub')
            smesh.SetName(DiskInlet_Faces, 'DiskInlet_Faces')
            smesh.SetName(DiskOutlet_1, 'DiskOutlet')
            smesh.SetName(DiskOutlet_Faces, 'DiskOutlet_Faces')
            smesh.SetName(DiskWall_1, 'DiskWall')
            smesh.SetName(DiskOutlet_3, 'DiskOutlet')
            smesh.SetName(DiskWall_Sub, 'DiskWall_Sub')
            smesh.SetName(DiskWall_3, 'DiskWall')
            smesh.SetName(DiskOutlet_Sub, 'DiskOutlet_Sub')
            smesh.SetName(DiskInlet_3, 'DiskInlet')
            smesh.SetName(TunnelSansDisk.GetMesh(), 'TunnelSansDisk')
            smesh.SetName(Tunnel_1.GetMesh(), 'Tunnel')
            smesh.SetName(Disk_1.GetMesh(), 'Disk')
            smesh.SetName(Disk_2, 'Disk')
            smesh.SetName(DiskWall_Faces, 'DiskWall_Faces')
            smesh.SetName(DiskWall_2, 'DiskWall')
            smesh.SetName(DiskInlet_2, 'DiskInlet')
            smesh.SetName(DiskOutlet_2, 'DiskOutlet')
            smesh.SetName(Outlet_2, 'Outlet')
            smesh.SetName(TunnelWall_2, 'TunnelWall')
            smesh.SetName(Inlet_2, 'Inlet')
            smesh.SetName(ShroudWall_2,'ShroudWall')
        
        
            if salome.sg.hasDesktop():
              salome.sg.updateObjBrowser(1)
        
            '''
            Old meshing stuff...
            # Now do the meshing
            cylinderMesh = smesh.Mesh(tunnel, 'Cylinder')
        
            cylAlgo3D = cylinderMesh.Tetrahedron(smeshBuilder.FULL_NETGEN)
            cylAlgo3DParams = cylAlgo3D.Parameters()
            cylAlgo3DParams.SetMaxSize(tunnelMaxTetraSize)
            cylAlgo3DParams.SetMinSize(tunnelMinTetraSize)
            cylAlgo3DParams.SetFineness(tunnelFineness)
            cylAlgo3DParams.SetOptimize(True)
            print "Computing Tunnel Mesh..."
            #cylinderMesh.Compute()
        
            # Now create groups on the mesh from the geometry
            meshInlet = cylinderMesh.GroupOnGeom(inletGroup, "Inlet")
            meshOutlet = cylinderMesh.GroupOnGeom(outletGroup, "Outlet")
            meshWall = cylinderMesh.GroupOnGeom(wallGroup, "TunnelWall")
            meshDiskInlet = cylinderMesh.GroupOnGeom(diskInletGroup, "DiskInlet")
            meshDiskOutlet = cylinderMesh.GroupOnGeom(diskOutletGroup, "DiskOutlet")
            meshDiskWall = cylinderMesh.GroupOnGeom(diskWallGroup, "DiskWall")
        
            # Now compute the disk using 2D elements from the tunnel so that the compound can be made later
            diskMesh = smesh.Mesh(diskCyl, 'Disk')
            print "Assigning inlet src..."
            diskInletAlgo = diskMesh.UseExisting2DElements(diskInletGroup_Orig)
            diskInletAlgo.SourceFaces([meshDiskInlet])
            print "Assigning outlet src..."
            diskOutletAlgo = diskMesh.UseExisting2DElements(diskOutletGroup_Orig)
            diskOutletAlgo.SourceFaces([meshDiskOutlet])
            print "Assigning wall src..."
            diskWallAlgo = diskMesh.UseExisting2DElements(diskWallGroup_Orig)
            diskWallAlgo.SourceFaces([meshDiskWall])
            diskMesh.SetMeshOrder([[diskWallAlgo.GetSubMesh(), diskOutletAlgo.GetSubMesh(), diskInletAlgo.GetSubMesh()]])
            print "Assigning Tetrahedron..."
            diskAlgo3D = diskMesh.Tetrahedron(smeshBuilder.FULL_NETGEN)
            diskAlgo3DParams = diskAlgo3D.Parameters()
            diskAlgo3DParams.SetMaxSize(diskMaxTetraSize)
            diskAlgo3DParams.SetMinSize(diskMinTetraSize)
            diskAlgo3DParams.SetFineness(diskFineness)
            #diskMesh.Compute()
        
            windTunnelMesh = smesh.Concatenate([cylinderMesh.GetMesh(), diskMesh.GetMesh()], False, True, 1e-05, False,
                                               'WindTunnel')
            # Create group of volumes that make up the actuator disk
            volumeFilter = smesh.GetFilter(SMESH.VOLUME,SMESH.FT_BelongToGeom,SMESH.FT_EqualTo,diskCyl)
            volumeGroup = windTunnelMesh.GroupOnFilter(SMESH.VOLUME,'Disk',volumeFilter)
            '''
            # Ok, let's spit it out!
            # Get Information About Mesh by GetMeshInfo
            print "\nInformation about mesh by GetMeshInfo:"
            info = smesh.GetMeshInfo(Tunnel_1)
            keys = info.keys(); keys.sort()
            for i in keys:
               print " %s : %d" % ( i, info[i] )
            # Silly salome-meca can only deal with strings not unicode types...so we have to make sure we have one.
            print "Saving MED to>",str(fileName),type(str(fileName))
            Tunnel_1.ExportMED(str(fileName), autoDimension=False)
    
        if doGUI:
            salome.sg.updateObjBrowser(1)
            
    except:
        print "Salome Failed!"

    #import runSalome
    #runSalome.kill_salome({'portkill':True,'kilall':False})
    if killSalomeAfter:
        import os
        from killSalomeWithPort import killMyPort
        killMyPort(os.getenv('NSPORT'))    
예제 #29
0
파일: xalome.py 프로젝트: Sunqia/salome-gui
def TEST_createAndDeleteShape():
    """
    This test is a simple use case that illustrates how to create a
    GEOM shape in a SALOME session (create the GEOM object, put in in
    the study, and display the shape in a viewer) and delete a shape
    from a SALOME session (erase the shape from the viewer, delete the
    entry from the study, and finally destroy the underlying GEOM
    object).
    """
    import salome
    salome.salome_init()
    study = salome.myStudy
    studyId = salome.myStudyId

    from salome.geom import geomtools
    geompy = geomtools.getGeompy(studyId)

    # --------------------------------------------------
    # Create a first shape (GEOM object)
    radius = 5
    length = 100
    cylinder = geompy.MakeCylinderRH(radius, length)

    # Register the shape in the study, at the root of the GEOM
    # folder. A name must be specified. The register operation
    # (addToStudy) returns an identifier of the entry in the study.
    cylinderName = "cyl.r%s.l%s" % (radius, length)
    cylinderStudyEntry = addToStudy(study, cylinder, cylinderName)

    # Display the registered shape in a viewer
    displayShape(cylinderStudyEntry)

    # --------------------------------------------------
    # A second shape
    radius = 10
    sphere = geompy.MakeSphereR(radius)
    sphereName = "sph.r%s" % radius
    sphereStudyEntry = addToStudy(study, sphere, sphereName)
    displayShape(sphereStudyEntry)

    # --------------------------------------------------
    # This new shape is stored in the study, but in a specific
    # sub-folder, and is displayed in the viewer with a specific
    # color.
    length = 20
    box = geompy.MakeBoxDXDYDZ(length, length, length)
    boxName = "box.l%s" % length
    folderName = "boxset"
    boxStudyEntry = addToStudy(study, box, boxName, folderName)
    displayShape(boxStudyEntry, PreviewColor)

    # --------------------------------------------------
    # In this example, we illustrate how to erase a shape (the sphere)
    # from the viewer. After this operation, the sphere is no longer
    # displayed but still exists in the study. You can then redisplay
    # it using the context menu of the SALOME object browser.
    eraseShape(sphereStudyEntry)

    # --------------------------------------------------
    # In this last example, we completly delete an object from the
    # SALOME session (erase from viewer, remove from study and finnaly
    # destroy the object). This is done by a simple call to
    # deleteShape().
    deleteShape(study, cylinderStudyEntry)
# Minimum Distance

import salome
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
geompy = geomBuilder.New(salome.myStudy)

import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
smesh =  smeshBuilder.New(salome.myStudy)
import salome_notebook

from SMESH_mechanic import mesh as mesh1
from SMESH_test1 import mesh as mesh2

mesh1.Compute()
mesh2.Compute()

# compute min distance from mesh1 to the origin (not available yet)
smesh.MinDistance(mesh1)

# compute min distance from node 10 of mesh1 to the origin
smesh.MinDistance(mesh1, id1=10)
# ... or
mesh1.MinDistance(10)

# compute min distance between nodes 10 and 20 of mesh1
smesh.MinDistance(mesh1, id1=10, id2=20)
# ... or
mesh1.MinDistance(10, 20)
예제 #31
0
def TEST_createModel():
    salome.salome_init()
    theStudy = salome.myStudy
    createModel(theStudy)
예제 #32
0
 def setUp(self):
     salome.salome_init()
     pass
예제 #33
0
def TEST_createMesh():
    salome.salome_init()
    theStudy=salome.myStudy
    shape = createGeometryWithPartition(theStudy)
    mesh  = createMesh(theStudy, shape)
예제 #34
0
def TEST_createModel():
    salome.salome_init()
    theStudy=salome.myStudy
    createModel(theStudy)
예제 #35
0
    def create(self):
        # Read data from input file
        with open(self.dataFilename) as dataFile:
            data = json.load(dataFile)

        elements = data['elements']
        connections = data['connections']
        # --> Delete this reference data and repopulate it with the objects
        # while going through elements
        for conn in connections:
            conn['relatedElements'] = []
        # End <--

        meshSize = self.meshSize

        dec = 7  # 4 decimals for length in mm
        tol = 10**(-dec - 3 + 1)

        self.tolLoc = tol * 10 * 2
        tolLoc = self.tolLoc

        NEW_SALOME = int(salome_version.getVersion()[0]) >= 9
        salome.salome_init()
        theStudy = salome.myStudy
        notebook = salome_notebook.NoteBook(theStudy)

        ###
        ### GEOM component
        ###
        import GEOM
        from salome.geom import geomBuilder
        import math
        import SALOMEDS

        gg = salome.ImportComponentGUI('GEOM')
        if NEW_SALOME:
            geompy = geomBuilder.New()
        else:
            geompy = geomBuilder.New(theStudy)
        self.geompy = geompy

        O = geompy.MakeVertex(0, 0, 0)
        OX = geompy.MakeVectorDXDYDZ(1, 0, 0)
        OY = geompy.MakeVectorDXDYDZ(0, 1, 0)
        OZ = geompy.MakeVectorDXDYDZ(0, 0, 1)
        geompy.addToStudy(O, 'O')
        geompy.addToStudy(OX, 'OX')
        geompy.addToStudy(OY, 'OY')
        geompy.addToStudy(OZ, 'OZ')

        if len([e for e in elements if e['geometryType'] == 'line']) > 0:
            buildingShapeType = 'EDGE'
        if len([e for e in elements if e['geometryType'] == 'surface']) > 0:
            buildingShapeType = 'FACE'

        ### Define entities ###
        start_time = time.time()
        print('Defining Object Geometry')
        init_time = start_time

        # Loop 1
        for el in elements:
            el['elemObj'] = self.makeObject(el['geometry'], el['geometryType'])

            el['connObjs'] = [None for _ in el['connections']]
            el['linkObjs'] = [None for _ in el['connections']]
            el['linkPointObjs'] = [[None, None] for _ in el['connections']]
            for j, rel in enumerate(el['connections']):
                conn = [
                    c for c in connections
                    if c['ifcName'] == rel['relatedConnection']
                ][0]
                if rel['eccentricity']:
                    rel['index'] = len(conn['relatedElements']) + 1
                conn['relatedElements'].append(rel)

                if not rel['eccentricity']:
                    el['connObjs'][j] = self.makeObject(
                        conn['geometry'], conn['geometryType'])
                else:
                    if conn['geometryType'] == 'point':
                        geometry = self.getLinkGeometry(
                            rel['eccentricity'], el['orientation'],
                            conn['geometry'])
                        el['connObjs'][j] = self.makeObject(
                            geometry[0], conn['geometryType'])

                        el['linkPointObjs'][j][0] = self.geompy.MakeVertex(
                            geometry[0][0], geometry[0][1], geometry[0][2])
                        el['linkPointObjs'][j][1] = self.geompy.MakeVertex(
                            geometry[1][0], geometry[1][1], geometry[1][2])
                        el['linkObjs'][j] = self.geompy.MakeLineTwoPnt(
                            el['linkPointObjs'][j][0],
                            el['linkPointObjs'][j][1])
                    else:
                        print('Eccentricity defined for a %s geometryType' %
                              conn['geometryType'])

            el['partObj'] = self.makePartition(
                [el['elemObj']] + el['connObjs'], el['geometryType'])

            el['elemObj'] = geompy.GetInPlace(el['partObj'], el['elemObj'])
            for j, rel in enumerate(el['connections']):
                el['connObjs'][j] = geompy.GetInPlace(el['partObj'],
                                                      el['connObjs'][j])

        for conn in connections:
            conn['connObj'] = self.makeObject(conn['geometry'],
                                              conn['geometryType'])

        # Make assemble of Building Object
        bldObjs = []
        bldObjs.extend([el['partObj'] for el in elements])
        bldObjs.extend(
            flatten([[link for link in el['linkObjs'] if link]
                     for el in elements]))
        bldObjs.extend([conn['connObj'] for conn in connections])

        bldComp = geompy.MakeCompound(bldObjs)
        # bldComp = geompy.MakePartition(bldObjs, [], [], [], self.geompy.ShapeType[buildingShapeType], 0, [], 1)
        geompy.addToStudy(bldComp, 'bldComp')

        # Loop 2
        for el in elements:
            # geompy.addToStudy(el['partObj'], self.getGroupName(el['ifcName']))
            geompy.addToStudyInFather(el['partObj'], el['elemObj'],
                                      self.getGroupName(el['ifcName']))
            for j, rel in enumerate(el['connections']):
                conn = [
                    c for c in connections
                    if c['ifcName'] == rel['relatedConnection']
                ][0]
                rel['conn_string'] = None
                if conn['geometryType'] == 'point':
                    rel['conn_string'] = '_0DC_'
                if conn['geometryType'] == 'line':
                    rel['conn_string'] = '_1DC_'
                if conn['geometryType'] == 'surface':
                    rel['conn_string'] = '_2DC_'
                geompy.addToStudyInFather(
                    el['partObj'], el['connObjs'][j],
                    self.getGroupName(el['ifcName']) + rel['conn_string'] +
                    self.getGroupName(rel['relatedConnection']))
                if rel['eccentricity']:
                    pass
                    # geompy.addToStudy(el['linkObjs'][j], self.getGroupName(el['ifcName']) + '_1DR_' + self.getGroupName(rel['relatedConnection']))
                    # geompy.addToStudyInFather(el['linkObjs'][j], el['linkPointObjs'][j][0], self.getGroupName(rel['relatedConnection']) + '_0DC_' + self.getGroupName(el['ifcName']))
                    # geompy.addToStudyInFather(el['linkObjs'][j], el['linkPointObjs'][j][0], self.getGroupName(rel['relatedConnection']) + '_0DC_%g' % rel['index'])

        for conn in connections:
            # geompy.addToStudy(conn['connObj'], self.getGroupName(conn['ifcName']))
            geompy.addToStudyInFather(conn['connObj'], conn['connObj'],
                                      self.getGroupName(conn['ifcName']))

        elapsed_time = time.time() - init_time
        init_time += elapsed_time
        print('Building Geometry Defined in %g sec' % (elapsed_time))

        if len([e for e in elements if e['geometryType'] == 'line']) > 0:
            buildingShapeType = 'EDGE'
        if len([e for e in elements if e['geometryType'] == 'surface']) > 0:
            buildingShapeType = 'FACE'

        # Define and add groups for all curve and surface members
        if len([e for e in elements if e['geometryType'] == 'line']) > 0:
            # Make compound of requested group
            compoundTemp = geompy.MakeCompound([
                e['elemObj'] for e in elements if e['geometryType'] == 'line'
            ])
            # Define group object and add to study
            curveCompound = geompy.GetInPlace(bldComp, compoundTemp)
            geompy.addToStudyInFather(bldComp, curveCompound, 'CurveMembers')

        if len([e for e in elements if e['geometryType'] == 'surface']) > 0:
            # Make compound of requested group
            compoundTemp = geompy.MakeCompound([
                e['elemObj'] for e in elements
                if e['geometryType'] == 'surface'
            ])
            # Define group object and add to study
            surfaceCompound = geompy.GetInPlace(bldComp, compoundTemp)
            geompy.addToStudyInFather(bldComp, surfaceCompound,
                                      'SurfaceMembers')

        # Loop 3
        for el in elements:
            # el['partObj'] = geompy.RestoreGivenSubShapes(bldComp, [el['partObj']], GEOM.FSM_GetInPlace, False, False)[0]
            geompy.addToStudyInFather(bldComp, el['elemObj'],
                                      self.getGroupName(el['ifcName']))

            for j, rel in enumerate(el['connections']):
                geompy.addToStudyInFather(
                    bldComp, el['connObjs'][j],
                    self.getGroupName(el['ifcName']) + rel['conn_string'] +
                    self.getGroupName(rel['relatedConnection']))
                if rel['eccentricity']:  # point geometry
                    geompy.addToStudyInFather(
                        bldComp, el['linkObjs'][j],
                        self.getGroupName(el['ifcName']) + '_1DR_' +
                        self.getGroupName(rel['relatedConnection']))
                    geompy.addToStudyInFather(
                        bldComp, el['linkPointObjs'][j][0],
                        self.getGroupName(rel['relatedConnection']) + '_0DC_' +
                        self.getGroupName(el['ifcName']))
                    geompy.addToStudyInFather(
                        bldComp, el['linkPointObjs'][j][1],
                        self.getGroupName(rel['relatedConnection']) +
                        '_0DC_%g' % rel['index'])

        for conn in connections:
            # conn['connObj'] = geompy.RestoreGivenSubShapes(bldComp, [conn['connObj']], GEOM.FSM_GetInPlace, False, False)[0]
            geompy.addToStudyInFather(bldComp, conn['connObj'],
                                      self.getGroupName(conn['ifcName']))

        elapsed_time = time.time() - init_time
        init_time += elapsed_time
        print('Building Geometry Groups Defined in %g sec' % (elapsed_time))

        ###
        ### SMESH component
        ###

        import SMESH
        from salome.smesh import smeshBuilder

        print('Defining Mesh Components')

        if NEW_SALOME:
            smesh = smeshBuilder.New()
        else:
            smesh = smeshBuilder.New(theStudy)
        bldMesh = smesh.Mesh(bldComp)
        Regular_1D = bldMesh.Segment()
        Local_Length_1 = Regular_1D.LocalLength(meshSize, None, tolLoc)

        if buildingShapeType == 'FACE':
            NETGEN2D_ONLY = bldMesh.Triangle(algo=smeshBuilder.NETGEN_2D)
            NETGEN2D_Pars = NETGEN2D_ONLY.Parameters()
            NETGEN2D_Pars.SetMaxSize(meshSize)
            NETGEN2D_Pars.SetOptimize(1)
            NETGEN2D_Pars.SetFineness(2)
            NETGEN2D_Pars.SetMinSize(meshSize / 5.0)
            NETGEN2D_Pars.SetUseSurfaceCurvature(1)
            NETGEN2D_Pars.SetQuadAllowed(1)
            NETGEN2D_Pars.SetSecondOrder(0)
            NETGEN2D_Pars.SetFuseEdges(254)

        isDone = bldMesh.Compute()

        ## Set names of Mesh objects
        smesh.SetName(Regular_1D.GetAlgorithm(), 'Regular_1D')
        smesh.SetName(Local_Length_1, 'Local_Length_1')

        if buildingShapeType == 'FACE':
            smesh.SetName(NETGEN2D_ONLY.GetAlgorithm(), 'NETGEN2D_ONLY')
            smesh.SetName(NETGEN2D_Pars, 'NETGEN2D_Pars')

        smesh.SetName(bldMesh.GetMesh(), 'bldMesh')

        elapsed_time = time.time() - init_time
        init_time += elapsed_time
        print('Meshing Operations Completed in %g sec' % (elapsed_time))

        # Define and add groups for all curve and surface members
        if len([e for e in elements if e['geometryType'] == 'line']) > 0:
            tempgroup = bldMesh.GroupOnGeom(curveCompound, 'CurveMembers',
                                            SMESH.EDGE)
            smesh.SetName(tempgroup, 'CurveMembers')

        if len([e for e in elements if e['geometryType'] == 'surface']) > 0:
            tempgroup = bldMesh.GroupOnGeom(surfaceCompound, 'SurfaceMembers',
                                            SMESH.FACE)
            smesh.SetName(tempgroup, 'SurfaceMembers')

        # Define groups in Mesh
        for el in elements:
            if el['geometryType'] == 'line':
                shapeType = SMESH.EDGE
            if el['geometryType'] == 'surface':
                shapeType = SMESH.FACE
            tempgroup = bldMesh.GroupOnGeom(el['elemObj'],
                                            self.getGroupName(el['ifcName']),
                                            shapeType)
            smesh.SetName(tempgroup, self.getGroupName(el['ifcName']))

            for j, rel in enumerate(el['connections']):
                tempgroup = bldMesh.GroupOnGeom(
                    el['connObjs'][j],
                    self.getGroupName(el['ifcName']) + rel['conn_string'] +
                    self.getGroupName(rel['relatedConnection']), SMESH.NODE)
                smesh.SetName(
                    tempgroup,
                    self.getGroupName(el['ifcName']) + rel['conn_string'] +
                    self.getGroupName(rel['relatedConnection']))
                rel['node'] = (bldMesh.GetIDSource(tempgroup.GetNodeIDs(),
                                                   SMESH.NODE)).GetIDs()[0]
                if rel['eccentricity']:
                    tempgroup = bldMesh.GroupOnGeom(
                        el['linkObjs'][j],
                        self.getGroupName(el['ifcName']) + '_1DR_' +
                        self.getGroupName(rel['relatedConnection']),
                        SMESH.EDGE)
                    smesh.SetName(
                        tempgroup,
                        self.getGroupName(el['ifcName']) + '_1DR_' +
                        self.getGroupName(rel['relatedConnection']))

                    tempgroup = bldMesh.GroupOnGeom(
                        el['linkPointObjs'][j][0],
                        self.getGroupName(rel['relatedConnection']) + '_0DC_' +
                        self.getGroupName(el['ifcName']), SMESH.NODE)
                    smesh.SetName(
                        tempgroup,
                        self.getGroupName(rel['relatedConnection']) + '_0DC_' +
                        self.getGroupName(el['ifcName']))
                    rel['eccNode'] = (bldMesh.GetIDSource(
                        tempgroup.GetNodeIDs(), SMESH.NODE)).GetIDs()[0]

                    tempgroup = bldMesh.GroupOnGeom(
                        el['linkPointObjs'][j][1],
                        self.getGroupName(rel['relatedConnection']) + '_0DC_' +
                        self.getGroupName(rel['relatedConnection']),
                        SMESH.NODE)
                    smesh.SetName(
                        tempgroup,
                        self.getGroupName(rel['relatedConnection']) +
                        '_0DC_%g' % rel['index'])

        for conn in connections:
            tempgroup = bldMesh.GroupOnGeom(conn['connObj'],
                                            self.getGroupName(conn['ifcName']),
                                            SMESH.NODE)
            smesh.SetName(tempgroup, self.getGroupName(conn['ifcName']))
            nodesId = bldMesh.GetIDSource(tempgroup.GetNodeIDs(), SMESH.NODE)
            tempgroup = bldMesh.Add0DElementsToAllNodes(
                nodesId, self.getGroupName(conn['ifcName']))
            smesh.SetName(tempgroup,
                          self.getGroupName(conn['ifcName'] + '_0D'))
            if conn['geometryType'] == 'point':
                conn['node'] = nodesId.GetIDs()[0]
            if conn['geometryType'] == 'line':
                tempgroup = bldMesh.GroupOnGeom(
                    conn['connObj'], self.getGroupName(conn['ifcName']),
                    SMESH.EDGE)
                smesh.SetName(tempgroup, self.getGroupName(conn['ifcName']))
            if conn['geometryType'] == 'surface':
                tempgroup = bldMesh.GroupOnGeom(
                    conn['connObj'], self.getGroupName(conn['ifcName']),
                    SMESH.FACE)
                smesh.SetName(tempgroup, self.getGroupName(conn['ifcName']))

        # create 1D SEG2 spring elements
        for el in elements:
            for j, rel in enumerate(el['connections']):
                conn = [
                    c for c in connections
                    if c['ifcName'] == rel['relatedConnection']
                ][0]
                if conn['geometryType'] == 'point':
                    grpName = bldMesh.CreateEmptyGroup(
                        SMESH.EDGE,
                        self.getGroupName(el['ifcName']) + '_1DS_' +
                        self.getGroupName(rel['relatedConnection']))
                    smesh.SetName(
                        grpName,
                        self.getGroupName(el['ifcName']) + '_1DS_' +
                        self.getGroupName(rel['relatedConnection']))
                    if not rel['eccentricity']:
                        conn = [
                            conn for conn in connections
                            if conn['ifcName'] == rel['relatedConnection']
                        ][0]
                        grpName.Add(
                            [bldMesh.AddEdge([conn['node'], rel['node']])])
                    else:
                        grpName.Add(
                            [bldMesh.AddEdge([rel['eccNode'], rel['node']])])

        self.mesh = bldMesh
        self.meshNodes = bldMesh.GetNodesId()

        elapsed_time = time.time() - init_time
        init_time += elapsed_time
        print('Mesh Groups Defined in %g sec' % (elapsed_time))

        try:
            if NEW_SALOME:
                bldMesh.ExportMED(self.medFilename,
                                  auto_groups=0,
                                  minor=40,
                                  overwrite=1,
                                  meshPart=None,
                                  autoDimension=0)
            else:
                bldMesh.ExportMED(self.medFilename, 0, SMESH.MED_V2_2, 1, None,
                                  0)
        except:
            print('ExportMED() failed. Invalid file name?')

        if salome.sg.hasDesktop():
            if NEW_SALOME:
                salome.sg.updateObjBrowser()
            else:
                salome.sg.updateObjBrowser(1)

        elapsed_time = init_time - start_time
        print('ALL Operations Completed in %g sec' % (elapsed_time))
예제 #36
0
def TEST_createGeometry():
    salome.salome_init()
    theStudy=salome.myStudy
    createGeometry(theStudy)
예제 #37
0
def useSalome(args, modules_list, modules_root_dir):
    """
    Launch all SALOME servers requested by args,
    save list of process, give info to user,
    show registered objects in Naming Service.
    """
    global process_id

    clt=None
    try:
        clt = startSalome(args, modules_list, modules_root_dir)
    except:
        import traceback
        traceback.print_exc()
        print
        print
        print "--- Error during Salome launch ---"

    #print process_id

    from addToKillList import addToKillList
    from killSalomeWithPort import getPiDict

    filedict = getPiDict(args['port'])
    for pid, cmd in process_id.items():
        addToKillList(pid, cmd, args['port'])
        pass

    if verbose(): print """
    Saving of the dictionary of Salome processes in %s
    To kill SALOME processes from a console (kill all sessions from all ports):
      python killSalome.py
    To kill SALOME from the present interpreter, if it is not closed :
      killLocalPort()      --> kill this session
                               (use CORBA port from args of runSalome)
      givenPortKill(port)  --> kill a specific session with given CORBA port
      killAllPorts()       --> kill all sessions

    runSalome, with --killall option, starts with killing
    the processes resulting from the previous execution.
    """%filedict

    #
    #  Print Naming Service directory list
    #

    if clt != None:
        if verbose():
            print
            print " --- registered objects tree in Naming Service ---"
            clt.showNS()
            pass

        if not args['gui'] or not args['session_gui']:
            if args['shutdown_servers']:
                class __utils__(object):
                    def __init__(self, port):
                        self.port = port
                        import killSalomeWithPort
                        self.killSalomeWithPort = killSalomeWithPort
                        return
                    def __del__(self):
                        self.killSalomeWithPort.killMyPort(self.port)
                        return
                    pass
                def func(s):
                    del s
                import atexit
                atexit.register(func, __utils__(args['port']))
                pass
            pass

        # run python scripts, passed as command line arguments
        toimport = []
        if args.has_key('gui') and args.has_key('session_gui'):
            if not args['gui'] or not args['session_gui']:
                if args.has_key('study_hdf'):
                    toopen = args['study_hdf']
                    if toopen:
                        import salome
                        salome.salome_init(toopen)
                if args.has_key('pyscript'):
                    toimport = args['pyscript']
        from salomeContextUtils import formatScriptsAndArgs
        command = formatScriptsAndArgs(toimport)
        if command:
            proc = subprocess.Popen(command, shell=True)
            addToKillList(proc.pid, command, args['port'])
            res = proc.wait()
            if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit

    return clt
예제 #38
0
orb, lcc, naming_service, cm = salome_kernel.salome_kernel_init()
obj = naming_service.Resolve('myStudyManager')
myStudyManager = obj._narrow(SALOMEDS.StudyManager)

root = os.path.normpath(
    os.path.dirname(os.path.abspath(os.path.realpath(sys.argv[0]))))
file1 = os.path.join(root, 'INPUTFILE1')
if not os.path.isfile(file1):
    raise Exception("Fichier %s non present!" % 'INPUTFILE1')

#%====================Initialisation etude================================%
if 'STUDY':
    # Si on a le nom de l'etude
    study = myStudyManager.GetStudyByName('STUDY')
    salome.salome_init(study._get_StudyId())
    import visu_gui
    import VISU
    import visu
    myVisu = visu_gui.myVisu
    myVisu.SetCurrentStudy(study)

else:
    # Sinon on choisit etude courante
    salome.salome_init()
    import visu_gui
    import VISU
    import visu
    myVisu = visu_gui.myVisu
    myVisu.SetCurrentStudy(salome.myStudy)
    # ou la premiere detectee ?
예제 #39
0
def GetHandlerFromName(varName,scopeName):
    import salome
    salome.salome_init()
    dsm=salome.naming_service.Resolve("/DataServerManager")
    d2s=dsm.retriveDataScope(scopeName)
    return GetHandlerFromRef(d2s.retrieveVar(varName),False)
예제 #40
0
    def create(self):
        # Read data from input file
        with open(self.dataFilename) as dataFile:
            data = json.load(dataFile)

        # print(len(data['elements']))
        # elements = self.select(data['elements'])
        # print(len(elements))
        elements = data["elements"]
        connections = data["connections"]
        # --> Delete this reference data and repopulate it with the objects
        # while going through elements
        for conn in connections:
            conn["relatedElements"] = []
        # End <--

        meshSize = self.meshSize
        zGround = self.zGround

        dec = 5  # 4 decimals for length in mm
        tol = 10**(-dec - 3 + 1)

        self.tolLoc = tol * 10 * 2
        tolLoc = self.tolLoc

        NEW_SALOME = int(salome_version.getVersion()[0]) >= 9
        salome.salome_init()
        theStudy = salome.myStudy
        notebook = salome_notebook.NoteBook(theStudy)

        ###
        ### GEOM component
        ###
        import GEOM
        from salome.geom import geomBuilder
        import math
        import SALOMEDS

        gg = salome.ImportComponentGUI("GEOM")
        if NEW_SALOME:
            geompy = geomBuilder.New()
        else:
            geompy = geomBuilder.New(theStudy)
        self.geompy = geompy

        O = geompy.MakeVertex(0, 0, 0)
        OX = geompy.MakeVectorDXDYDZ(1, 0, 0)
        OY = geompy.MakeVectorDXDYDZ(0, 1, 0)
        OZ = geompy.MakeVectorDXDYDZ(0, 0, 1)
        geompy.addToStudy(O, "O")
        geompy.addToStudy(OX, "OX")
        geompy.addToStudy(OY, "OY")
        geompy.addToStudy(OZ, "OZ")

        if len([e for e in elements if e["geometryType"] == "line"]) > 0:
            buildingShapeType = "EDGE"
        if len([e for e in elements if e["geometryType"] == "surface"]) > 0:
            buildingShapeType = "FACE"

        ### Define entities ###
        start_time = time.time()
        print("Defining Object Geometry")
        init_time = start_time

        # Loop 1
        for el in elements:
            el["elemObj"] = self.makeObject(el["geometry"], el["geometryType"])

            el["linkObjs"] = [None for _ in el["connections"]]
            for j, rel in enumerate(el["connections"]):
                conn = [
                    c for c in connections
                    if c["referenceName"] == rel["relatedConnection"]
                ][0]
                if rel["eccentricity"]:
                    rel["index"] = len(conn["relatedElements"]) + 1

                    geometry = self.getLinkGeometry(rel["eccentricity"],
                                                    el["orientation"],
                                                    conn["geometry"])
                    el["linkObjs"][j] = self.makeObject(geometry, "line")
                conn["relatedElements"].append(rel)

        # Make assemble of Building Object
        bldObjs = []
        bldObjs.extend([el["elemObj"] for el in elements])
        bldObjs.extend(
            flatten([[link for link in el["linkObjs"] if link]
                     for el in elements]))

        # bldComp = geompy.MakeCompound(bldObjs)
        bldComp = geompy.MakePartition(
            bldObjs, [], [], [], self.geompy.ShapeType[buildingShapeType], 0,
            [], 1)
        geompy.addToStudy(bldComp, "bldComp")

        elapsed_time = time.time() - init_time
        init_time += elapsed_time
        print("Building Geometry Defined in %g sec" % (elapsed_time))

        # Define and add groups for all curve, surface and rigid members
        if len([e for e in elements if e["geometryType"] == "line"]) > 0:
            # Make compound of requested group
            compoundTemp = geompy.MakeCompound([
                e["elemObj"] for e in elements if e["geometryType"] == "line"
            ])
            # Define group object and add to study
            curveCompound = geompy.GetInPlace(bldComp, compoundTemp, True)
            geompy.addToStudyInFather(bldComp, curveCompound, "CurveMembers")

        if len([e for e in elements if e["geometryType"] == "surface"]) > 0:
            # Make compound of requested group
            compoundTemp = geompy.MakeCompound([
                e["elemObj"] for e in elements
                if e["geometryType"] == "surface"
            ])
            # Define group object and add to study
            surfaceCompound = geompy.GetInPlace(bldComp, compoundTemp, True)
            geompy.addToStudyInFather(bldComp, surfaceCompound,
                                      "SurfaceMembers")

        linkObjs = list(
            flatten([[obj for obj in el["linkObjs"] if obj]
                     for el in elements]))
        if len(linkObjs) > 0:
            # Make compound of requested group
            compoundTemp = geompy.MakeCompound(linkObjs)
            # Define group object and add to study
            rigidCompound = geompy.GetInPlace(bldComp, compoundTemp, True)
            geompy.addToStudyInFather(bldComp, rigidCompound, "RigidMembers")

        for el in elements:
            # el['partObj'] = geompy.RestoreGivenSubShapes(bldComp, [el['partObj']], GEOM.FSM_GetInPlace, False, False)[0]
            el["elemObj"] = geompy.GetInPlace(bldComp, el["elemObj"], True)
            geompy.addToStudyInFather(bldComp, el["elemObj"],
                                      self.getGroupName(el["referenceName"]))

            for j, rel in enumerate(el["connections"]):
                if rel["eccentricity"]:  # point geometry
                    el["linkObjs"][j] = geompy.GetInPlace(
                        bldComp, el["linkObjs"][j], True)
                    geompy.addToStudyInFather(
                        bldComp,
                        el["linkObjs"][j],
                        self.getGroupName(el["referenceName"]) + "_1DR_" +
                        self.getGroupName(rel["relatedConnection"]),
                    )

        elapsed_time = time.time() - init_time
        init_time += elapsed_time
        print("Building Geometry Groups Defined in %g sec" % (elapsed_time))

        ###
        ### SMESH component
        ###

        import SMESH
        from salome.smesh import smeshBuilder

        print("Defining Mesh Components")

        if NEW_SALOME:
            smesh = smeshBuilder.New()
        else:
            smesh = smeshBuilder.New(theStudy)
        bldMesh = smesh.Mesh(bldComp)
        Regular_1D = bldMesh.Segment()
        Local_Length_1 = Regular_1D.LocalLength(meshSize, None, tolLoc)

        if buildingShapeType == "FACE":
            NETGEN2D_ONLY = bldMesh.Triangle(algo=smeshBuilder.NETGEN_2D)
            NETGEN2D_Pars = NETGEN2D_ONLY.Parameters()
            NETGEN2D_Pars.SetMaxSize(meshSize)
            NETGEN2D_Pars.SetOptimize(1)
            NETGEN2D_Pars.SetFineness(2)
            NETGEN2D_Pars.SetMinSize(meshSize / 5.0)
            NETGEN2D_Pars.SetUseSurfaceCurvature(1)
            NETGEN2D_Pars.SetQuadAllowed(1)
            NETGEN2D_Pars.SetSecondOrder(0)
            NETGEN2D_Pars.SetFuseEdges(254)

        isDone = bldMesh.Compute()
        coincident_nodes_on_part = bldMesh.FindCoincidentNodesOnPart([bldMesh],
                                                                     tolLoc,
                                                                     [], 0)
        if coincident_nodes_on_part:
            # bldMesh.MergeNodes(coincident_nodes_on_part, [], 0)
            # print(f'{len(coincident_nodes_on_part)} Sets of Coincident Nodes Found and Merged')
            print(
                f"{len(coincident_nodes_on_part)} Sets of Coincident Nodes Found"
            )
            print(f"{coincident_nodes_on_part}")

        ## Set names of Mesh objects
        smesh.SetName(Regular_1D.GetAlgorithm(), "Regular_1D")
        smesh.SetName(Local_Length_1, "Local_Length_1")

        if buildingShapeType == "FACE":
            smesh.SetName(NETGEN2D_ONLY.GetAlgorithm(), "NETGEN2D_ONLY")
            smesh.SetName(NETGEN2D_Pars, "NETGEN2D_Pars")

        smesh.SetName(bldMesh.GetMesh(), "bldMesh")

        elapsed_time = time.time() - init_time
        init_time += elapsed_time
        print("Meshing Operations Completed in %g sec" % (elapsed_time))

        # Define and add groups for all curve, surface and rigid members
        if len([e for e in elements if e["geometryType"] == "line"]) > 0:
            tempgroup = bldMesh.GroupOnGeom(curveCompound, "CurveMembers",
                                            SMESH.EDGE)
            smesh.SetName(tempgroup, "CurveMembers")

        if len([e for e in elements if e["geometryType"] == "surface"]) > 0:
            tempgroup = bldMesh.GroupOnGeom(surfaceCompound, "SurfaceMembers",
                                            SMESH.FACE)
            smesh.SetName(tempgroup, "SurfaceMembers")

        if len(linkObjs) > 0:
            tempgroup = bldMesh.GroupOnGeom(rigidCompound, "RigidMembers",
                                            SMESH.EDGE)
            smesh.SetName(tempgroup, "RigidMembers")

        # Define groups in Mesh
        for el in elements:
            if el["geometryType"] == "line":
                shapeType = SMESH.EDGE
            if el["geometryType"] == "surface":
                shapeType = SMESH.FACE
            tempgroup = bldMesh.GroupOnGeom(
                el["elemObj"], self.getGroupName(el["referenceName"]),
                shapeType)
            smesh.SetName(tempgroup, self.getGroupName(el["referenceName"]))

            for j, rel in enumerate(el["connections"]):
                if rel["eccentricity"]:
                    tempgroup = bldMesh.GroupOnGeom(
                        el["linkObjs"][j],
                        self.getGroupName(el["referenceName"]) + "_1DR_" +
                        self.getGroupName(rel["relatedConnection"]),
                        SMESH.EDGE,
                    )
                    smesh.SetName(
                        tempgroup,
                        self.getGroupName(el["referenceName"]) + "_1DR_" +
                        self.getGroupName(rel["relatedConnection"]),
                    )

        self.mesh = bldMesh
        self.meshNodes = bldMesh.GetNodesId()

        # Find ground supports and extract node coordinates
        grdSupps = bldMesh.CreateEmptyGroup(SMESH.NODE, "grdSupps")

        for node in self.meshNodes:
            coords = bldMesh.GetNodeXYZ(node)
            if abs(coords[2] - self.zGround) < tolLoc:
                grdSupps.Add([node])

        smesh.SetName(grdSupps, "grdSupps")

        elapsed_time = time.time() - init_time
        init_time += elapsed_time
        print("Mesh Groups Defined in %g sec" % (elapsed_time))

        try:
            if NEW_SALOME:
                bldMesh.ExportMED(
                    self.medFilename,
                    auto_groups=0,
                    minor=40,
                    overwrite=1,
                    meshPart=None,
                    autoDimension=0,
                )
            else:
                bldMesh.ExportMED(self.medFilename, 0, SMESH.MED_V2_2, 1, None,
                                  0)
        except:
            print("ExportMED() failed. Invalid file name?")

        if salome.sg.hasDesktop():
            if NEW_SALOME:
                salome.sg.updateObjBrowser()
            else:
                salome.sg.updateObjBrowser(1)

        elapsed_time = init_time - start_time
        print("ALL Operations Completed in %g sec" % (elapsed_time))
예제 #41
0
def TEST_createMesh():
    salome.salome_init()
    theStudy = salome.myStudy
    shape = createGeometryWithPartition(theStudy)
    mesh = createMesh(theStudy, shape)
예제 #42
0
def getStudyFromStudyId(studyId):
    salome.salome_init()
    study = salome.myStudyManager.GetStudyByID(studyId)
    return study
예제 #43
0
def TEST_exportModel():
    salome.salome_init()
    theStudy = salome.myStudy
    shape = createGeometryWithPartition(theStudy)
    mesh = createMesh(theStudy, shape)
    exportModel(mesh, "tubemesh.med")
예제 #44
0
def useSalome(args, modules_list, modules_root_dir):
    """
    Launch all SALOME servers requested by args,
    save list of process, give info to user,
    show registered objects in Naming Service.
    """
    global process_id

    clt = None
    try:
        clt = startSalome(args, modules_list, modules_root_dir)
    except:
        import traceback
        traceback.print_exc()
        print
        print
        print "--- Error during Salome launch ---"

    #print process_id

    from addToKillList import addToKillList
    from killSalomeWithPort import getPiDict

    filedict = getPiDict(args['port'])
    for pid, cmd in process_id.items():
        addToKillList(pid, cmd, args['port'])
        pass

    if verbose():
        print """
    Saving of the dictionary of Salome processes in %s
    To kill SALOME processes from a console (kill all sessions from all ports):
      python killSalome.py
    To kill SALOME from the present interpreter, if it is not closed :
      killLocalPort()      --> kill this session
                               (use CORBA port from args of runSalome)
      givenPortKill(port)  --> kill a specific session with given CORBA port
      killAllPorts()       --> kill all sessions

    runSalome, with --killall option, starts with killing
    the processes resulting from the previous execution.
    """ % filedict

    #
    #  Print Naming Service directory list
    #

    if clt != None:
        if verbose():
            print
            print " --- registered objects tree in Naming Service ---"
            clt.showNS()
            pass

        if not args['gui'] or not args['session_gui']:
            if args['shutdown_servers']:

                class __utils__(object):
                    def __init__(self, port):
                        self.port = port
                        import killSalomeWithPort
                        self.killSalomeWithPort = killSalomeWithPort
                        return

                    def __del__(self):
                        self.killSalomeWithPort.killMyPort(self.port)
                        return

                    pass

                def func(s):
                    del s

                import atexit
                atexit.register(func, __utils__(args['port']))
                pass
            pass

        # run python scripts, passed as command line arguments
        toimport = []
        if args.has_key('gui') and args.has_key('session_gui'):
            if not args['gui'] or not args['session_gui']:
                if args.has_key('study_hdf'):
                    toopen = args['study_hdf']
                    if toopen:
                        import salome
                        salome.salome_init(toopen)
                if args.has_key('pyscript'):
                    toimport = args['pyscript']
        from salomeContextUtils import formatScriptsAndArgs
        command = formatScriptsAndArgs(toimport)
        if command:
            proc = subprocess.Popen(command, shell=True)
            addToKillList(proc.pid, command, args['port'])
            res = proc.wait()
            if res:
                sys.exit(
                    1
                )  # if there's an error when executing script, we should explicitly exit

    return clt
예제 #45
0
# -*- coding: utf-8 -*-

###
### This file is generated automatically by SALOME v8.3.0 with dump python functionality
###### Run with DPS_lead_position_V9.py

import sys
import salome

salome.salome_init()
theStudy = salome.myStudy

import salome_notebook
notebook = salome_notebook.NoteBook(theStudy)
sys.path.insert( 0, r'/home/trieu/electrode_dir')

###
### GEOM component
###
########################################### extra code 1 V10 15/12/18#############################################
###### This file runs with DBS_lead_position_V10.py
import os
sys.path.insert( 0, r'{}'.format(os.getcwd()))
sys.path.append('/usr/local/lib/python2.7/dist-packages')
#from pandas import read_csv

##### DEFAULT LIST #####

#Lead2nd_Enable = True
#Xt = 0
#Yt = 5
def extractFeatureEdges(body, minFeatureAngle = 5):
    '''
    Find all feature edges on the supplied body and return them as a list
    of edge ids.

        body - A Salome solid, compound, shell or face object to find all
                feature edges on.
        minFeatureAngle - the angle (in degrees) between adjacent surfaces
                above which the edge will be considered a feature angle.
    '''
    import salome
    salome.salome_init()

    import GEOM
    from salome.geom import geomBuilder
    geompy = geomBuilder.New(salome.myStudy)

    # Check the body type
    if not (body.GetShapeType() in [GEOM.SHELL, GEOM.SOLID, GEOM.FACE, GEOM.COMPOUND]):
       raise RuntimeError('Supplied object is not a solid, shell or face.')

    print 'Extracting edges of %s with feature angle > %g.' % (body.GetName(), minFeatureAngle)

    # Extract basic info
    faces = geompy.SubShapeAll(body, geompy.ShapeType["FACE"])
    curves = geompy.SubShapeAll(body, geompy.ShapeType["EDGE"])
    points = geompy.SubShapeAll(body, geompy.ShapeType["VERTEX"])

    faceIds = geompy.GetSubShapesIDs(body, faces)
    curveIds = geompy.GetSubShapesIDs(body, curves)
    nodeIds = geompy.GetSubShapesIDs(body, points)

    maxFaceId = max(faceIds)
    maxCurveId = max(curveIds)
    maxNodeId = max(nodeIds)

    # Reverse mapping from curve id to local curve arrays
    faceMap = [-1 for i in xrange(maxFaceId+1)]
    for localId, id in enumerate(faceIds):
        faceMap[id] = localId

    curveMap = [-1 for i in xrange(maxCurveId+1)]
    for localId, id in enumerate(curveIds):
        curveMap[id] = localId

    nodeMap = [-1 for i in xrange(maxNodeId+1)]
    for localId, id in enumerate(nodeIds):
        nodeMap[id] = localId


    # Get curves on each face
    faceCurveIds = [[curveMap[id] for id in geompy.GetSubShapesIDs(
            body,
            geompy.SubShapeAll(face, geompy.ShapeType["EDGE"])
        )] for face in faces]

    # Get faces attached to each curve
    curveFaceIds = [[] for id in curveIds]

    for faceI, ids in enumerate(faceCurveIds):
        for id in ids:
            curveFaceIds[id].append(faceI)

    # Now that we have the connectivity for curves and faces find the
    # feature edges
    featureEdgeIds = []
    for curveId, curve, adjFaceIds in zip(curveIds, curves, curveFaceIds):
        if len(adjFaceIds) == 2:
            # Curve with 2 adjacent faces - Test feature angle
            # Determine break angle at each curve
            # If greater than the feature edge angle, add the curve to group featureEdges
            face1 = faces[adjFaceIds[0]]
            face2 = faces[adjFaceIds[1]]
            point = geompy.GetFirstVertex(curve)    # Test at the first vertex
            n1 = geompy.GetNormal(face1, point)
            n2 = geompy.GetNormal(face2, point)
            angle = geompy.GetAngle(n1, n2)
            if angle > minFeatureAngle:
                featureEdgeIds.append(curveId)

        elif len(adjFaceIds) == 1:
            # Curve on standalone face - Add by default
            featureEdgeIds.append(curveId)

        elif len(adjFaceIds) == 0:
            # Standalone curve - Ignore
            None

        else:
            raise RuntimeError('Curve found sharing %d faces. This is unexpected for fully enclosed bodies.' % len(adjFaceIds))

    # Done
    print "%d feature edges found" % len(featureEdgeIds)

    return featureEdgeIds