Back to index

salome-med  6.5.0
medutilities.py
Go to the documentation of this file.
00001 # -*- coding: iso-8859-1 -*-
00002 # --
00003 # Copyright (C) 2009-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00004 #
00005 # This library is free software; you can redistribute it and/or
00006 # modify it under the terms of the GNU Lesser General Public
00007 # License as published by the Free Software Foundation; either
00008 # version 2.1 of the License.
00009 #
00010 # This library is distributed in the hope that it will be useful,
00011 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013 # Lesser General Public License for more details.
00014 #
00015 # You should have received a copy of the GNU Lesser General Public
00016 # License along with this library; if not, write to the Free Software
00017 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00018 #
00019 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00020 #
00021 # Author : Erwan ADAM (CEA)
00022 # --
00023 
00024 from libMEDMEM_Swig import *
00025 
00026 def my_remove(f):
00027     from os import remove
00028     try:
00029         remove(f)
00030     except OSError:
00031         pass
00032     return
00033 
00034 def sauv2med(*argv):
00035     argv = list(argv)
00036     # argv = argv[1:]
00037     for arg in argv:
00038         convert(arg, "GIBI", "MED")
00039         pass
00040     return
00041 
00042 def med2sauv(*argv):
00043     argv = list(argv)
00044     # argv = argv[1:]
00045     format = 1
00046     for arg in argv[:]:
00047         if arg.find('--format') == 0:
00048             argv.remove(arg)
00049             try:
00050                 value = arg.split("=")[1]
00051             except IndexError:
00052                 usage(1)
00053                 pass
00054             try:
00055                 value = int(value)
00056             except ValueError:
00057                 usage(1)
00058                 pass
00059             format = value
00060             pass
00061         pass
00062     for arg in argv:
00063         convert(arg, "MED", "GIBI", format)
00064         pass
00065     return
00066 
00067 def convert(file_in, driver_in, driver_out, format=1, file_out=None):
00068     #
00069     print file_in
00070     #
00071     if file_out is None:
00072         file_out = file_in
00073 ##        if file_out.find('.') != -1:
00074 ##            suffix = file_in.split('.')[-1]
00075 ##            if driver_in == "GIBI":
00076 ##                test = "sauv"
00077 ##            else:
00078 ##                test = "med"
00079 ##                pass
00080 ##            if len(suffix) >= len(test):
00081 ##                suffix = suffix[:len(test)]
00082 ##                suffix = suffix.lower()
00083 ##                if suffix == test:
00084 ##                    file_out = '.'.join(file_in.split('.')[:-1])
00085 ##                    pass
00086 ##                pass
00087 ##            pass
00088         if driver_out == "GIBI":
00089             file_out += ".sauv"
00090         elif driver_out == "MED":
00091             file_out += ".med"
00092         else:
00093             msg = "Driver out %s is unknown"%(driver_out)
00094             raise NotImplementedError(msg)
00095         pass
00096     print file_out
00097     #
00098     meshes = []
00099     fields = []
00100     if driver_in == "GIBI":
00101         driver = GIBI_MED_RDONLY_DRIVER(file_in)
00102         fields = driver.read()
00103         mesh = driver.getMesh()
00104         if mesh:
00105             meshes.append( mesh )
00106     elif driver_in == "MED":
00107         med = MEDFILEBROWSER(file_in)
00108         for mesh_name in med.getMeshNames():
00109             if med.isStructuredMesh( mesh_name ):
00110                 mesh = GRID( MED_DRIVER, file_in, mesh_name )
00111             else:
00112                 mesh = MESH( MED_DRIVER, file_in, mesh_name )
00113             meshes.append( mesh )
00114         for field_name in med.getFieldNames():
00115             mesh_name = med.getMeshName( field_name )
00116             mesh = 0
00117             for m in meshes:
00118                 if m.getName() == mesh_name:
00119                     mesh = m; break
00120             for dtit in med.getFieldIteration( field_name ):
00121                 if med.getFieldType( field_name ) == MED_REEL64:
00122                     field = FIELDDOUBLE(MED_DRIVER, file_in, field_name, dtit.dt, dtit.it, mesh )
00123                 else:
00124                     field = FIELDINT(MED_DRIVER, file_in, field_name, dtit.dt, dtit.it, mesh )
00125                 fields.append( field )
00126     else:
00127         msg = "Driver in %s is unknown"%(driver_in)
00128         raise NotImplementedError(msg)
00129     #
00130     my_remove(file_out)
00131     #
00132     if driver_out == "GIBI":
00133         mesh = meshes[0]
00134         mesh_dim = mesh.getSpaceDimension()
00135         if format == 0:
00136             file_out = file_out+'__format__'
00137             my_remove(file_out)
00138             pass
00139         if fields:
00140             driver = GIBI_MED_WRONLY_DRIVER(file_out, fields, mesh)
00141         else:
00142             driver = GIBI_MESH_WRONLY_DRIVER(file_out, mesh)
00143         driver.open()
00144         driver.write()
00145         driver.close()
00146         #
00147         if mesh_dim >= 3:
00148             from sys import platform
00149             if platform in ["win32"]:
00150                 f = open(file_out)
00151                 content = f.read()
00152                 f.close()
00153                 content = content.replace("IFOUR  -1", "IFOUR   2")
00154                 content = content.replace("IFOMOD  -1", "IFOMOD   2")
00155                 f = open(file_out, "w")
00156                 f.write(content)
00157                 f.close()
00158             else:
00159                 cmd  = "sed"
00160                 cmd += ' -e "s/IFOUR  -1/IFOUR   2/g"'
00161                 cmd += ' -e "s/IFOMOD  -1/IFOMOD   2/g"'
00162                 # cmd += ' -e "s/IECHO   1/IECHO   0/g"'
00163                 cmd += ' %s > .dummy'%(file_out)
00164                 cmd += ' && '
00165                 cmd += ' mv -f .dummy %s'%(file_out)
00166                 from os import system
00167                 system(cmd)
00168                 pass
00169             pass
00170         #
00171         if format == 0:
00172             from castemlauncher import CastemLauncher
00173             dgibi_stream  = "\n"
00174             dgibi_stream += "OPTI REST FORMAT '%s' ;\n"%(file_out)
00175             dgibi_stream += "REST FORMAT;\n"
00176             file_out = file_out.replace('__format__', '')
00177             dgibi_stream += "OPTI SAUV '%s' ;\n"%(file_out)
00178             dgibi_stream += "SAUV ;\n"
00179             cl = CastemLauncher(dgibi_stream)
00180             cl.addTmpFiles(file_out+'__format__', "UTILNOTI", "UTILPROC")
00181             cl.run()
00182             pass
00183         return
00184     #
00185     for mesh in meshes:
00186         mesh.write(MED_DRIVER, file_out)
00187     for field in fields:
00188         typedField = field.castToTypedField();
00189         typedField.write(MED_DRIVER, file_out)
00190     #
00191     return
00192 
00193 def avs2med_one_file(file_in, file_out, mesh_name, field_name):
00194     """
00195     Convert an ucd avs inp file into a med file
00196     inp Specifications can be found at :
00197     http://people.scs.fsu.edu/~burkardt/data/ucd/ucd.html
00198     http://help.avs.com/Express/doc/help/reference/dvmac/UCD_Form.htm
00199     
00200     """
00201     my_remove(file_out)
00202     #
00203     meshing = MESHING()
00204     meshing.setName(mesh_name)
00205     #
00206     f = open(file_in)
00207     lines = f.readlines()
00208     f.close()
00209     nb_lines = len(lines)
00210     # ----
00211     # Skip the comments
00212     # ----
00213     while 1:
00214         l = lines[0]
00215         if l[0] != "#":
00216             break
00217         lines = lines[1:]
00218         pass
00219     # ----
00220     headers = [ int(i) for i in lines[0].split() ]
00221     lines = lines[1:]
00222     number_of_nodes = headers[0]
00223     number_of_cells = headers[1]
00224     number_of_nodes_data = headers[2]
00225     number_of_cells_data = headers[3]
00226     number_of_whole_data = headers[3]
00227     # ----------
00228     # Nodes
00229     # ----------
00230     nodes = lines[:number_of_nodes]
00231     lines = lines[number_of_nodes:]
00232     nodes = [ " ".join(l.split()[1:]) for l in nodes ]
00233     nodes = " ".join(nodes)
00234     nodes = [ float(v) for v in nodes.split() ]
00235     # --------
00236     # Space dimension
00237     # --------
00238     nodes_min = min(nodes)
00239     nodes_max = max(nodes)
00240     epsilon = 1.0e-5 * (nodes_max - nodes_min)
00241     nodes_z = [ nodes[i] for i in range(2, 3 * number_of_nodes, 3) ]
00242     nodes_z_min = min(nodes_z)
00243     nodes_z_max = max(nodes_z)
00244     space_dimension = 2
00245     if abs(nodes_z_max) > epsilon:
00246         space_dimension = 3
00247         pass
00248     if abs(nodes_z_min) > epsilon:
00249         space_dimension = 3
00250         pass
00251     #
00252     if space_dimension == 2:
00253         l = range(0, 3 * number_of_nodes, 3) + range(1, 3 * number_of_nodes, 3)
00254         l.sort()
00255         nodes = [ nodes[i] for i in l ]
00256         pass
00257     #
00258     meshing.setCoordinates(space_dimension, number_of_nodes, nodes, "CARTESIAN", MED_FULL_INTERLACE)
00259     # ----------
00260     # Cells
00261     # ----------
00262     cells = lines[:number_of_cells]
00263     lines = lines[number_of_cells:]
00264     cells = [ c.split() for c in cells ]
00265     #
00266     type2connectivity = {}
00267     for c in cells:
00268         cell_id = int(c[0])
00269         cell_mat = int(c[1])
00270         cell_type = c[2]
00271         cell_connectivity = c[3:]
00272         #
00273         avs_type = cell_type
00274         if 0:
00275             pass
00276         elif avs_type == 'tri':
00277             entity = MED_CELL
00278             nb2medtype = {
00279                 3: MED_TRIA3,
00280                 }
00281         elif avs_type == 'quad':
00282             entity = MED_CELL
00283             nb2medtype = {
00284                 4: MED_QUAD4,
00285                 8: MED_QUAD8,
00286                 }
00287         elif avs_type == 'tet':
00288             entity = MED_CELL
00289             nb2medtype = {
00290                 4: MED_TETRA4,
00291                 }
00292         elif avs_type == 'hex':
00293             entity = MED_CELL
00294             nb2medtype = {
00295                 8: MED_HEXA8,
00296                 }
00297         elif avs_type == 'pyr':
00298             entity = MED_CELL
00299             nb2medtype = {
00300                 5: MED_PYRA5,
00301                 }
00302         elif avs_type == 'prism':
00303             entity = MED_CELL
00304             nb2medtype = {
00305                 6: MED_PENTA6,
00306                 }
00307         else:
00308             raise Exception("unknown avs_type : %s"%(avs_type))
00309         #
00310         med_type = nb2medtype[len(cell_connectivity)]
00311         #
00312         try:
00313             d = type2connectivity[entity]
00314         except:
00315             type2connectivity[entity] = {}
00316             d = type2connectivity[entity]
00317             pass
00318         #
00319         try:
00320             l = d[med_type]
00321         except:
00322             d[med_type] = []
00323             l = d[med_type]
00324             pass
00325         #
00326         cell_connectivity = ' '.join(cell_connectivity)
00327         l.append(cell_connectivity)
00328         #
00329         pass
00330     #
00331     mesh_dimension = space_dimension
00332     #
00333     for entity, d in type2connectivity.items():
00334         meshing.setNumberOfTypes(len(d.keys()), entity)
00335         meshing.setTypes(d.keys(), entity)
00336         meshing.setNumberOfElements([len(v) for v in d.values()], entity)
00337         for key, value in d.items():
00338             connectivity = value
00339             connectivity = " ".join(connectivity)
00340             connectivity = [ int(v) for v in connectivity.split() ]
00341             meshing.setConnectivity(connectivity, entity, key)
00342             pass
00343         pass
00344     # -----------
00345     meshing.write(meshing.addDriver(MED_DRIVER,file_out,meshing.getName()))
00346     # -----------
00347     flag = -1
00348     for n in [number_of_nodes_data, number_of_cells_data]:
00349         flag += 1
00350         if n == 0:
00351             continue
00352         # -----------
00353         header = [ int(v) for v in lines[0].split() ]
00354         lines = lines[1:]
00355         nb_of_components = header[0]
00356         nb_of_values_by_component = header[1:]
00357         if len(nb_of_values_by_component) != nb_of_components:
00358             msg = "Error at line %d"%(nb_lines - len(lines))
00359             raise Exception(msg)
00360         #
00361         titles_by_component = []
00362         for i in range(nb_of_components):
00363             l = lines[0]
00364             lines = lines[1:]
00365             label = l.split(',')[0]
00366             unit = l[len(label)+1:]   # The +1 is for the comma
00367             label = label.strip()
00368             unit = unit.strip()
00369             labels_by_value = nb_of_values_by_component[i]*['']
00370             l = [label, unit, labels_by_value]
00371             titles_by_component.append(l)
00372             pass
00373         if nb_of_components > 1:
00374             if nb_of_values_by_component == nb_of_components * [1]:
00375                 nb_of_values_by_component = [ nb_of_components ]
00376                 nb_of_components = 1
00377                 if flag == 0:
00378                     if number_of_cells_data:
00379                         name = field_name + "_on_nodes"
00380                         pass
00381                     pass
00382                 else:
00383                     if number_of_nodes_data:
00384                         name = field_name + "_on_cells"
00385                         pass
00386                     pass
00387                 titles_by_component = [ [name, "", [t[0] for t in titles_by_component]] ]
00388                 pass
00389             pass
00390         if flag == 0:
00391             nb = number_of_nodes
00392         else:
00393             nb = number_of_cells
00394             pass
00395         values = lines[:nb]
00396         lines = lines[nb:]
00397         vals = []
00398         imin = 1
00399         for i in range(nb_of_components):
00400             imax = imin + nb_of_values_by_component[i]
00401             vals.append([ l.split()[imin:imax] for l in values ])
00402             imin = imax
00403             pass
00404         values = vals
00405         # ----------
00406         if flag == 0:
00407             support = SUPPORT(meshing, "support_on_nodes", MED_NODE)
00408         else:
00409             support = SUPPORT(meshing, "support_on_cells", MED_CELL)
00410             pass
00411         for i in range(nb_of_components):
00412             nb = nb_of_values_by_component[i]
00413             field = FIELDDOUBLE(support, nb)
00414             field.setName(titles_by_component[i][0])
00415             # field.setIterationNumber(-1)
00416             # field.setOrderNumber(-1)
00417             # field.setTime(0.0)
00418             for n in range(nb):
00419                 name = titles_by_component[i][2][n]
00420                 if name:
00421                     field.setComponentName(n+1,name)
00422                     pass
00423                 pass
00424             # ---------------
00425             value = values[i]
00426             value = [ " ".join(l) for l in value ]
00427             value = " ".join(value)
00428             value = [ float(v) for v in value.split() ]
00429             field.setValue(value)
00430             # -----
00431             field.write(field.addDriver(MED_DRIVER,file_out,field.getName()))
00432             # -------
00433             pass
00434         #
00435         pass
00436     return
00437 
00438 def avs2med(*argv):
00439     argv = list(argv)
00440     #
00441     mesh_name = "mesh"
00442     field_name = "field"
00443     #
00444     for arg in argv[:]:
00445         if ( arg.find('--mesh_name') == 0 ) or ( arg.find('--mesh-name') == 0 ) :
00446             argv.remove(arg)
00447             try:
00448                 mesh_name = arg.split("=")[1]
00449             except IndexError:
00450                 usage(1)
00451                 pass
00452             pass
00453         if ( arg.find('--field_name') == 0 ) or ( arg.find('--field-name') == 0 ) :
00454             argv.remove(arg)
00455             try:
00456                 field_name = arg.split("=")[1]
00457             except IndexError:
00458                 usage(1)
00459                 pass
00460             pass
00461         pass
00462     #
00463     for arg in argv:
00464         avs2med_one_file(arg, arg + ".med", mesh_name, field_name)
00465         pass
00466     #
00467     return
00468