From: Yoann AUDOUIN Date: Thu, 4 May 2017 07:55:08 +0000 (+0200) Subject: Modification for new interface of openturns + cleanup X-Git-Tag: Salome_8_3_Hydro_2_0rc1~14^2~14 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=d899b66b515f04d2e8522d8bb586693c22526914;p=modules%2Fhydrosolver.git Modification for new interface of openturns + cleanup --- diff --git a/src/salome_hydro/pytel/eficas/pytel_cata.py b/src/salome_hydro/pytel/eficas/pytel_cata.py index 200c552..db77f20 100644 --- a/src/salome_hydro/pytel/eficas/pytel_cata.py +++ b/src/salome_hydro/pytel/eficas/pytel_cata.py @@ -27,13 +27,13 @@ PYTEL = PROC( nom = "PYTEL", op = None, fr = u"Définition d'un cas pour le lanceur Pytel", ang = u"Definition of a case for the Pytel launcher", - CODE = SIMP(statut = "o", typ = "TXM", into = codelist, defaut = "telemac2d", + CODE = SIMP(statut = "o", typ = "TXM", into = codelist, defaut = "telemac2d", fr = u"Code à exécuter", ang = u"Code to run"), FICHIER_CAS = SIMP(statut = "o", typ = 'Fichier', fr = u"Fichier de description du cas", ang = u"Case description file"), - REPERTOIRE_TRAVAIL = SIMP(statut = "f", typ = 'Repertoire', + REPERTOIRE_TRAVAIL = SIMP(statut = "f", typ = 'Repertoire', fr = u"Répertoire de travail", ang = u"Working directory"), ) diff --git a/src/salome_hydro/pytel/genjob.py b/src/salome_hydro/pytel/genjob.py index edf5f31..a265a90 100644 --- a/src/salome_hydro/pytel/genjob.py +++ b/src/salome_hydro/pytel/genjob.py @@ -22,10 +22,6 @@ import glob import salome -convertion_script_template = """ -converter.py %(input_file)s -b %(log_file)s -o %(output_file)s -""" - job_script_template = """#!/bin/sh . %(env_file)s @@ -79,7 +75,7 @@ def generate_job(pytel_params, resource, telemac_root_dir, telemac_env_file, timestr = timestr.replace(' ', '_') work_dir = res_work_dir + "/" + job_params.job_name + "_" + timestr job_params.work_directory = work_dir - + # Create Launcher job launcher = salome.naming_service.Resolve('/SalomeLauncher') launcher.createJob(job_params) diff --git a/src/salome_hydro/pytel/genjobwindow.py b/src/salome_hydro/pytel/genjobwindow.py index 8e1b5f0..ee665f1 100644 --- a/src/salome_hydro/pytel/genjobwindow.py +++ b/src/salome_hydro/pytel/genjobwindow.py @@ -33,18 +33,18 @@ class GenJobDialog(QDialog, Ui_GenJobDialog): self.chooseInputDataDirectoryButton.clicked.connect( self.choose_input_dir) self.chooseResultDirectoryButton.clicked.connect(self.choose_result_dir) - self.telemacRootDirLE.setText("/home/projets-bgq/systel/V6P2") - self.telemacEnvFileLE.setText("/home/projets-bgq/systel/V6P2/config/pysource.zumbrota.xlf14.sh") + self.telemacRootDirLE.setText("/projets/systel/V7P2") + self.telemacEnvFileLE.setText("/projets/systel/V7P2/config/pysource.eole.intel.sh") casedir = os.path.dirname(pytel_params["FICHIER_CAS"]) self.inputDataDirectoryLE.setText(casedir) self.resultDirectoryLE.setText(casedir) - + # Populate resource combo box res_manager = salome.naming_service.Resolve("/ResourcesManager") res_params = salome.ResourceParameters() res_list = res_manager.GetFittingResources(res_params) self.resourceCB.addItems(res_list) - + self.pytel_params = pytel_params def choose_input_dir(self): diff --git a/src/salome_hydro/pytel/launcher.py b/src/salome_hydro/pytel/launcher.py index f1d2e32..0c27934 100644 --- a/src/salome_hydro/pytel/launcher.py +++ b/src/salome_hydro/pytel/launcher.py @@ -30,7 +30,7 @@ def run_pytel(param_dict): followed by data conversion scripts. """ interm_files = [] # Intermediate files that can eventually be deleted in the end - + # Get and eventually create working directory if "REPERTOIRE_TRAVAIL" in param_dict: wrkdir = param_dict["REPERTOIRE_TRAVAIL"] @@ -51,7 +51,7 @@ def run_pytel(param_dict): # Run the code itself code = param_dict["CODE"] - cmd += "$TELEMAC_DIR/scripts/python27/runcode.py -w %s -r $TELEMAC_DIR %s %s" % \ + cmd += "runcode.py -w %s %s %s" % \ (wrkdir, code, steering_filepath) cmd += " ; rc=$?" diff --git a/src/salome_hydro/study.py b/src/salome_hydro/study.py index e081e62..13237fd 100644 --- a/src/salome_hydro/study.py +++ b/src/salome_hydro/study.py @@ -171,18 +171,14 @@ class HydroStudyEditor: comment = str(filePath), typeId = TELEMAC2D_CASE_TYPE_ID) # Create "Variables" item + from TelApy.api.generate_study import generate_yacs with open(filePath) as jdcfile: jdc = jdcfile.read() params = jdc_to_dict(jdc, ["TELEMAC2D", "_F"]) - input_vars = get_jdc_dict_var_as_tuple(params, "VARIABLE_ENTREE") - output_vars = get_jdc_dict_var_as_tuple(params, "VARIABLE_SORTIE") - input_varname_list = [var["NOM"].strip() for var in input_vars] - # Remove duplicates - input_varname_list = list(set(input_varname_list)) - input_var_list = [study_exchange_vars.Variable(varname) for varname in input_varname_list] - output_var_list = [study_exchange_vars.Variable(var["NOM"].strip()) for var in output_vars] - exchange_vars = study_exchange_vars.ExchangeVariables(input_var_list, output_var_list) - study_exchange_vars.createSObjectForExchangeVariables(sobj, exchange_vars, icon = VARS_ICON) + + yacs_scheme = generate_yacs(params) + + # TODO: Replace that by adding yacs scheme and python script ? def find_or_create_coupling1d2d_case(self, filePath): self.find_or_create_hydro_component() diff --git a/src/salome_hydro/telemac2d/CMakeLists.txt b/src/salome_hydro/telemac2d/CMakeLists.txt index 181eca9..a4d3f5e 100644 --- a/src/salome_hydro/telemac2d/CMakeLists.txt +++ b/src/salome_hydro/telemac2d/CMakeLists.txt @@ -29,54 +29,3 @@ SET(INSTALL_DIR ${SALOME_INSTALL_PYTHON}/salome/hydro/telemac2d) # --- rules --- SALOME_INSTALL_SCRIPTS("${PYFILES}" ${INSTALL_DIR}) - -# # This macro is used to transform the list of libraries against which the -# # module is linked into a list of linker flags (-L and -l). If we just use the -# # list of libraries in the linker command, the full path of the libraries is -# # registered in the module dependencies, so it doesn't work when the installation -# # is moved. -# MACRO(LIB_LIST_TO_LINKER_FLAGS LINKER_FLAGS_VAR LIB_LIST) -# SET(${LINKER_FLAGS_VAR}) -# FOREACH(LIB ${LIB_LIST}) -# GET_FILENAME_COMPONENT(DIRNAME ${LIB} PATH) -# # Get the library filename without the shortest extension. We can't use -# # command GET_FILENAME_COMPONENT with option NAME_WE because it returns -# # the filename without the longest extension. For example, we need to get -# # "libpython2.7" from "libpython2.7.so" and not "libpython2". -# GET_FILENAME_COMPONENT(LIBFILENAME ${LIB} NAME) -# STRING(FIND ${LIBFILENAME} "." DOTPOS REVERSE) -# STRING(SUBSTRING ${LIBFILENAME} 0 ${DOTPOS} FILENAME_WO_EXT) -# STRING(SUBSTRING ${FILENAME_WO_EXT} 3 -1 LIBNAME) -# LIST(APPEND ${LINKER_FLAGS_VAR} "-L${DIRNAME}" "-l${LIBNAME}") -# ENDFOREACH(LIB ${LIB_LIST}) -# ENDMACRO(LIB_LIST_TO_LINKER_FLAGS) -# -# SET (MEDFILE_LIBRARIES ${MED3HOME}/lib/libmedC.so) -# LIB_LIST_TO_LINKER_FLAGS(LINKER_FLAGS "${TELEMAC_LIBRARIES};${HDF5_hdf5_LIBRARY};${MEDFILE_LIBRARIES};${PYTHON_LIBRARY}") -# -# # Python wrapping for Telemac2D created with f2py -# SET(T2D_WRAP_API_LIB _apit2d.so) -# SET(T2D_WRAP_API_PYF_FILE apit2d.pyf) -# SET(T2D_WRAP_API_SRC_FILES ${TELEMAC_API_SRC_DIR}/api_handle_var_t2d.f90 -# ${TELEMAC_API_SRC_DIR}/api_interface_t2d.f90 -# ${TELEMAC_API_SRC_DIR}/api_handle_error_t2d.f90) -# -# # This sed string is used to add necessary definitions to the pyf file -# SET(SEDSTRING "s:python module _apit2d ! in:python module _apit2d ! in\\nusercode '''const int nb_var_t2d=100\\;\\n''':") -# -# ADD_CUSTOM_COMMAND(OUTPUT ${T2D_WRAP_API_LIB} -# COMMAND f2py -c ${T2D_WRAP_API_PYF_FILE} -I${TELEMAC_INCLUDE_DIR} ${LINKER_FLAGS} -# MAIN_DEPENDENCY ${T2D_WRAP_API_PYF_FILE} -# ) -# -# ADD_CUSTOM_COMMAND(OUTPUT ${T2D_WRAP_API_PYF_FILE} -# COMMAND f2py -h ${T2D_WRAP_API_PYF_FILE} -m _apit2d ${T2D_WRAP_API_SRC_FILES} -# skip: get_boolean_t2d_d get_double_t2d_d get_integer_t2d_d get_string_t2d_d get_var_size_t2d_d -# set_boolean_t2d_d set_double_t2d_d set_integer_t2d_d set_string_t2d_d : -# COMMAND sed -i -e \"${SEDSTRING}\" ${T2D_WRAP_API_PYF_FILE} -# MAIN_DEPENDENCY ${T2D_WRAP_API_SRC_FILES} -# ) -# -# ADD_CUSTOM_TARGET(BUILD_T2D_WRAP_API_LIB ALL DEPENDS ${T2D_WRAP_API_LIB}) -# INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${T2D_WRAP_API_LIB} DESTINATION ${INSTALL_DIR}) -# diff --git a/src/salome_hydro/telemac2d/__init__.py b/src/salome_hydro/telemac2d/__init__.py index 6ce9b99..e4b3bfd 100644 --- a/src/salome_hydro/telemac2d/__init__.py +++ b/src/salome_hydro/telemac2d/__init__.py @@ -14,159 +14,3 @@ # # You should have received a copy of the GNU General Public License # along with SALOME HYDRO module. If not, see . - -import sys -import os -import tempfile -from ctypes import cdll - - -class Telemac2D(object): - - _instanciated = False - _api_module = None - - def __new__(cls, *args, **kwargs): - if cls._instanciated: - raise Exception("Telemac2D instance already exists") - instance = super(Telemac2D, cls).__new__(cls, *args, **kwargs) - cls._instanciated = True - return instance - - def __init__(self, user_fortran = None): - self.user_fortran_lib = None - self.user_fortran_lib_path = None - # User Fortran MUST be loaded before apit2d importation - if user_fortran is not None: - self._load_user_fortran(user_fortran) - if Telemac2D._api_module is None: - import salome.hydro.telemac2d._apit2d - Telemac2D._api_module = sys.modules["salome.hydro.telemac2d._apit2d"] - else: - reload(Telemac2D._api_module) - self.api = Telemac2D._api_module.api_interface_t2d - self.errapi = Telemac2D._api_module.api_handle_error_t2d - self.id, ierr = self.api.run_set_config_t2d(6, 2) - self.handle_error("run_set_config_t2d", ierr) - - def __del__(self): - # No way to cleanly unload user fortran lib, so I don't know if it's possible - # to reload and use another one in the same process (to be tested) - if self.user_fortran_lib_path is not None: - os.remove(self.user_fortran_lib_path) - Telemac2D._instanciated = False - - def _load_user_fortran(self, fortran_filename): - basename = os.path.basename(fortran_filename) - root = os.path.splitext(basename)[0] - (fd, self.user_fortran_lib_path) = tempfile.mkstemp(prefix = root + "_", suffix = ".so") - os.close(fd) - python_version = "%d.%d" % (sys.version_info[0], sys.version_info[1]) - t2d_ld_flags = "-L${TELEMAC_DIR}/builds/salome/wrap_api/lib -lapi -ltelemac2d -lsisyphe -ltomawac " - #t2d_ld_flags += "-lbief -lparallel -lpartel -lgretel -lhermes -ldamocles -lspecial " - t2d_ld_flags += "-lbief -lparallel -lhermes -ldamocles -lspecial " - t2d_ld_flags += "-L${MED3HOME}/lib -L${HDF5HOME}/lib -lhdf5 -lmed" - command = "gfortran %s -shared -o %s -L${PYTHONHOME}/lib -lpython%s %s -I${TELEMAC_DIR}/wrap_api/include -fPIC" % \ - (fortran_filename, self.user_fortran_lib_path, python_version, t2d_ld_flags) - ret = os.system(command) - if ret != 0: - raise Exception("Cannot compile user fortran file %s" % fortran_filename) - self.user_fortran_lib = cdll.LoadLibrary(self.user_fortran_lib_path) - - def handle_error(self, funcname, ierr): - if ierr != 0: - raise Exception('Error in function %s:\n Error code: %d\n Error message: %s' % - (funcname, ierr, self.errapi.err_mess.tostring().strip())) - - def run_read_case_t2d(self, steering_filename, dico_filename = None): - if dico_filename is None: - dico_filename = os.path.join(os.getenv("TELEMAC_DIR"), "sources", "telemac2d", "telemac2d.dico") - if not os.path.isfile(steering_filename): - raise Exception("Steering file {0} does not exist".format(steering_filename)) - if not os.path.isfile(dico_filename): - raise Exception("Dictionary file {0} does not exist".format(dico_filename)) - ierr = self.api.run_read_case_t2d(self.id, steering_filename, dico_filename) - self.handle_error("run_read_case_t2d", ierr) - - def get_double(self, varname, *args): - args = list(args) + [0] * (3 - len(args)) # Fill last parameters with 0 - value, ierr = self.api.get_double_t2d(self.id, varname, *args) - self.handle_error("get_double_t2d", ierr) - return value - - def set_double(self, varname, value, *args): - args = list(args) + [0] * (3 - len(args)) # Fill last parameters with 0 - ierr = self.api.set_double_t2d(self.id, varname, value, *args) - self.handle_error("set_double_t2d", ierr) - - def get_integer(self, varname, *args): - args = list(args) + [0] * (3 - len(args)) # Fill last parameters with 0 - value, ierr = self.api.get_integer_t2d(self.id, varname, *args) - self.handle_error("get_integer_t2d", ierr) - return value - - def set_integer(self, varname, value, *args): - args = list(args) + [0] * (3 - len(args)) # Fill last parameters with 0 - ierr = self.api.set_integer_t2d(self.id, varname, value, *args) - self.handle_error("set_integer_t2d", ierr) - - def get_string(self, varname): - value, ierr = self.api.get_string_t2d(self.id, varname, 144) - self.handle_error("get_string_t2d", ierr) - return value.tostring().strip() - - def set_string(self, varname, value): - padded_value = value + " " * (144 - len(value)) # Pad with spaces - ierr = self.api.set_string_t2d(self.id, varname, padded_value, 144) - self.handle_error("set_string_t2d", ierr) - - def run_all_timesteps(self): - ntimesteps = self.get_integer("MODEL.NTIMESTEPS") - for i in xrange(ntimesteps): - ierr = self.api.run_timestep_t2d(self.id) - self.handle_error("run_timestep_t2d", ierr) - - def finalize(self): - ierr = self.api.run_finalize_t2d(self.id) - self.handle_error("run_finalize_t2d", ierr) - - def save_state(self, state = None): - nbpoints = self.get_integer('MODEL.NPOIN') - if state is None: - state = Telemac2DState(nbpoints) - elif state.nbpoints != nbpoints: - raise Exception("Allocated state size (%d) is different from the size " - "of Telemac2D state (%d)" % (state.nbpoints, nbpoints)) - for i in xrange(nbpoints): - #state.h[i] = self.get_double('MODEL.WATERDEPTH', i+1) - #state.u[i] = self.get_double('MODEL.VELOCITYU' , i+1) - #state.v[i] = self.get_double('MODEL.VELOCITYV' , i+1) - # The following lines are an optimization of the previous ones, - # to be replaced by a proper array copy - state.h[i] = self.api.get_double_t2d(self.id, 'MODEL.WATERDEPTH', i+1, 0, 0)[0] - state.u[i] = self.api.get_double_t2d(self.id, 'MODEL.VELOCITYU' , i+1, 0, 0)[0] - state.v[i] = self.api.get_double_t2d(self.id, 'MODEL.VELOCITYV' , i+1, 0, 0)[0] - return state - - def restore_state(self, state): - nbpoints = self.get_integer('MODEL.NPOIN') - if state.nbpoints != nbpoints: - raise Exception("Allocated state size (%d) is different from the size " - "of Telemac2D state (%d)" % (state.nbpoints, nbpoints)) - for i in xrange(nbpoints): - #self.set_double('MODEL.WATERDEPTH', state.h[i], i+1) - #self.set_double('MODEL.VELOCITYU' , state.u[i], i+1) - #self.set_double('MODEL.VELOCITYV' , state.v[i], i+1) - # The following lines are an optimization of the previous ones, - # to be replaced by a proper array copy - self.api.set_double_t2d(self.id, 'MODEL.WATERDEPTH', state.h[i], i+1, 0, 0) - self.api.set_double_t2d(self.id, 'MODEL.VELOCITYU' , state.u[i], i+1, 0, 0) - self.api.set_double_t2d(self.id, 'MODEL.VELOCITYV' , state.v[i], i+1, 0, 0) - - -class Telemac2DState: - def __init__(self, nbpoints): - self.nbpoints = nbpoints - self.h = [0.0] * nbpoints - self.u = [0.0] * nbpoints - self.v = [0.0] * nbpoints diff --git a/src/salome_hydro/telemac2d/eficas/telemac2d_V6_cata.py b/src/salome_hydro/telemac2d/eficas/telemac2d_V6_cata.py index 3f22017..388c5b1 100644 --- a/src/salome_hydro/telemac2d/eficas/telemac2d_V6_cata.py +++ b/src/salome_hydro/telemac2d/eficas/telemac2d_V6_cata.py @@ -44,66 +44,83 @@ TELEMAC2D = PROC( nom = "TELEMAC2D", op = None, fr = u"Définition d'un cas d'étude Telemac2D", ang = u"Definition of a Telemac2D study case", - FICHIER_CAS = SIMP(statut = "o", typ = 'Fichier', + STEERING_FILE = SIMP(statut = "o", typ = 'Fichier', fr = u"Fichier de description du cas", ang = u"Case description file"), - FICHIER_GEOMETRIE = SIMP(statut = "f", typ = 'Fichier', - fr = u"Fichier de géométrie", - ang = u"Geometry file"), - FICHIER_CONDITIONS_LIMITES = SIMP(statut = "f", typ = 'Fichier', - fr = u"Fichier de conditions limites", - ang = u"Boundary conditions file"), - FICHIER_DICO = SIMP(statut = "f", typ = 'Fichier', - fr = "Fichier Dico", - ang = u"Dictionary file"), - FICHIER_FORTRAN_UTILISATEUR = SIMP(statut = "f", typ = 'Fichier', + USER_FORTRAN = SIMP(statut = "f", typ = 'Fichier', fr = "Fichier Fortran utilisateur", ang = u"Fortran user file"), - RESULTAT = SIMP(statut = "f", typ = ('Fichier', 'Tous les fichiers (*)', "Sauvegarde"), - fr = u"Fichier de résultat", - ang = u"Result file"), - VARIABLE_SORTIE = FACT(statut = 'f', max = '**', + OUTPUT_VARIABLE = FACT(statut = 'f', max = '**', fr = u"Variable de sortie du calcul", ang = u"Computation output variable", - NOM = SIMP(statut = "o", typ = 'TXM', + NAME = SIMP(statut = "o", typ = 'TXM', fr = u"Nom de la variable", ang = u"Variable name"), - VARIABLE_T2D = SIMP(statut = "o", typ = 'TXM', - fr = u'Variable Telemac2D (ex : "MODEL.VELOCITYU(2443)")', - ang = u'Telemac2D variable (ex : "MODEL.VELOCITYU(2443)")'), - ), - VARIABLE_ENTREE = FACT(statut = 'f', max = '**', - fr = u"Variable d'entrée du calcul", - ang = u"Computation input variable", - NOM = SIMP(statut = "o", typ = 'TXM', - fr = u"Nom de la variable", - ang = u"Variable name"), - VARIABLE_MODELE_T2D = FACT(statut = "o", + VAR_INFO = FACT(statut = "o", fr = u'Variable du modèle Telemac2D', ang = u'Telemac2D model variable', - NOM_VARIABLE_MODELE = SIMP(statut = "o", typ = 'TXM', + VAR_NAME = SIMP(statut = "o", typ = 'TXM', fr = u'Nom de la variable du modèle (ex: "MODEL.DEBIT")', ang = u'Model variable name (ex: "MODEL.DEBIT")'), - ZONE_DE_DEFINITION = FACT(statut = "o", + ZONE_DEF = FACT(statut = "o", ang = u'Variable definition area', fr = u'Zone de définition de la variable', - regles = (UN_PARMI('INDICE', 'POLYGONE')), - INDICE = SIMP(statut = "f", typ = "I", + regles = (UN_PARMI('INDEX', 'POLYGON')), + INDEX = SIMP(statut = "f", typ = Tuple(3), + defaut = (0,0,0), ang = "Index of the point / border", fr = u"Indice du point ou de la frontière", - ), - POLYGONE = SIMP(statut = "f", + validators = VerifTypeTuple(('I', 'I', 'I')), + ), + POLYGON = SIMP(statut = "f", + typ = Tuple(2), + max = '**', + fr = u"Liste des sommets (coordonnées X,Y) du " + u"polygone définissant le contour de la zone", + ang = "List of points (X,Y coordinates) of the " + "polygon defining the border of the area", + validators = VerifTypeTuple(('R', 'R')), + ), + ), + ), + ), + INPUT_VARIABLE = FACT(statut = 'f', max = '**', + fr = u"Variable d'entrée du calcul", + ang = u"Computation input variable", + NAME = SIMP(statut = "o", typ = 'TXM', + fr = u"Nom de la variable (format Python)", + ang = u"Variable name (Python format)"), + VAR_INFO = FACT(statut = "o", + fr = u'Variable du modèle Telemac2D', + ang = u'Telemac2D model variable', + VAR_NAME = SIMP(statut = "o", typ = 'TXM', + fr = u'Nom de la variable du modèle (ex: "MODEL.DEBIT")', + ang = u'Model variable name (ex: "MODEL.DEBIT")'), + DEFAULT_VALUE = SIMP(statut = "o", typ = 'TXM', + fr = u'Valeur par défaut', + ang = u'Default value'), + ZONE_DEF = FACT(statut = "o", + ang = u'Variable definition area', + fr = u'Zone de définition de la variable', + regles = (UN_PARMI('INDEX', 'POLYGON')), + INDEX = SIMP(statut = "f", typ = Tuple(3), + defaut = (0,0,0), + ang = "Index of the variable", + fr = u"Indice de la variabme", + validators = VerifTypeTuple(('I', 'I', 'I')), + ), + POLYGON = SIMP(statut = "f", typ = Tuple(2), - max = '**', + max = '**', fr = u"Liste des sommets (coordonnées X,Y) du " u"polygone définissant le contour de la zone", ang = "List of points (X,Y coordinates) of the " "polygon defining the border of the area", validators = VerifTypeTuple(('R', 'R')), - ), - ), - ), - ), + ), + ), + ), + ), ) TEXTE_NEW_JDC="TELEMAC2D()" diff --git a/src/salome_hydro/telemac2d/polygon.py b/src/salome_hydro/telemac2d/polygon.py deleted file mode 100644 index cd2d431..0000000 --- a/src/salome_hydro/telemac2d/polygon.py +++ /dev/null @@ -1,96 +0,0 @@ -# Copyright (C) 2012-2015 EDF -# -# This file is part of SALOME HYDRO module. -# -# SALOME HYDRO module is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# SALOME HYDRO module is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with SALOME HYDRO module. If not, see . - -import math -from itertools import izip,cycle - -EPS = 10**-9 - -def is_in_polygon(x,y,poly): - """ - Returns True if the point (x,y) is in the polygon poly - Warning the polygon must be distinct (no indentical points) - """ - angle = -1.0 - while True: - angle += 1.0 - if(angle > 360.0): - # Special case of a point on the contour - return True - a = math.cos(angle*math.pi/180.0) - b = math.sin(angle*math.pi/180.0) - nsect = 0 - # Loop on all the segment of the polygon - # TODO: Pythonize that loop - n = len(poly) - next_angle = False - for i in range(0,n): - xdep,ydep = poly[i] - # next element - xarr,yarr = poly[(i+1) % n] - # Case the point is on the polygon - if (abs(x-xdep)= -EPS and llambda >= -EPS and llambda <= (1.0+EPS)): - nsect += 1 - # If - if not next_angle: - break - - return (nsect % 2) == 1 - -def get_list_points_in_polygon(t2d_inst, poly): - """ - Returns the list of points from the mesh that are in the polygon poly - - t2d_inst : is the Telemac2D instance - poly : is a list of (x,y) coordiantes defining the polygon - """ - # Get the number of point in the mesh - npoin = t2d_inst.get_integer('MODEL.NPOIN') - point_in_polygon = [] - - # Loop on all mesh points - for i in range(1, npoin + 1): - # Get the cooridnates of point i - x = t2d_inst.get_double('MODEL.X', i) - y = t2d_inst.get_double('MODEL.Y', i) - # If point is in polygon add it to the list of points - if is_in_polygon(x,y,poly): - point_in_polygon.append(i) - return point_in_polygon - -if __name__ == "__main__": - l = [(0.0,0.0),(0.0,1.0),(1.0,2.0),(2.0,2.0),(2.0,0.0)] - print is_in_polygon(1.0,1.0,l),True - print is_in_polygon(0.0,0.0,l),True - print is_in_polygon(-1.0,1.0,l),False - print is_in_polygon(2.0,0.0,l),True