[cig-commits] r22807 - in seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT: . doc doc/media example geocubitlib geocubitlib/dev geocubitlib/obsolete utility

dkomati1 at geodynamics.org dkomati1 at geodynamics.org
Fri Sep 20 10:32:11 PDT 2013


Author: dkomati1
Date: 2013-09-20 10:32:11 -0700 (Fri, 20 Sep 2013)
New Revision: 22807

Added:
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/GEOCUBIT.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/MANIFEST.in
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.pdf
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.pdfsync
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.tex
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/geocubitmanual_grid.jpg
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/geocubitmanual_grid2.jpg
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/geometryvolume.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/grid.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/iterative.mov
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/meshvolume.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/netsurface.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/refcurve_1.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/refcurve_2.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/regrid.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/regrid_coarse.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/skinsurface.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/strombolisurface.png
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/abruzzo.cfg
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/data.zip
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/grid.cfg
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/stromboli.cfg
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/topo.dat
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/volume.cfg
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/LatLongUTMconversion.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/__init__.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/boundary_definition.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/cubit2specfem3d.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/dev/
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/dev/cubit2googleearth.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/dev/material.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/exportlib.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/hex_metric.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/local_volume.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/menu.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/mesh_volume.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/bc.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/boundary_check.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/boundary_definition.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/mpi_geocubit.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/partitioner.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/select_in_out.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/quality_log.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/read_parameter_cfg.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/start.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/surfaces.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/utilities.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/volumes.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/setup.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/jq.sh
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/jq_single.sh
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/run.sh
Removed:
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/LatLongUTMconversion.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/README.txt
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/__init__.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/absorbing_boundary.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/boundary_definition.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/cubit2specfem3d.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/exportlib.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/functions.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/hex_metric.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/local_volume.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/menu.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/mesh_volume.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/quality_log.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/read_parameter_cfg.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/save_fault_nodes_elements.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/start.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/surfaces.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utilities.py
   seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/volumes.py
Log:
moved the final SVN version of GEOCUBIT at CIG to the SPECFEM3D_Cartesian package, to make it easier to maintain and to avoid having two different versions, none of them working fine in all cases and for all users


Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/GEOCUBIT.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/GEOCUBIT.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/GEOCUBIT.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+"""
+GEOCUBIT.py
+this file is part of GEOCUBIT
+
+Created by Emanuele Casarotti 
+Copyright (c) 2011 Istituto Nazionale di Geofisica e Vulcanologia 
+
+---------------------------------------------------------------------------
+ GEOCUBIT 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.
+
+ GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.
+
+---------------------------------------------------------------------------
+
+GEOCUBIT requires:
+
+- CUBIT 12.2 - www.cubit.sandia.gov
+- python 2.5 
+- numpy 1.0+  - http://downloads.sourceforge.net/numpy
+
+  -- optional for parallel mesh
+- pympi - http://downloads.sourceforge.net/pympi
+
+"""
+import geocubitlib.menu as menu
+import geocubitlib.start as start
+mpiflag,iproc,numproc,mpi   = start.start_mpi()
+if menu.build_surface or menu.build_volume or menu.meshing:
+    cubit                   = start.start_cubit(init=True)
+else:
+    cubit                   = start.start_cubit()
+
+if __name__ == '__main__':
+    
+    #GEOMETRY
+    if menu.build_surface:              
+        from geocubitlib import surfaces
+        surfaces.surfaces()                 
+    if menu.build_volume:                   
+        from geocubitlib import volumes     
+        volumes.volumes()                   
+               
+    #MESHING
+    if menu.meshing:
+        from geocubitlib import mesh_volume
+        mesh_volume.mesh()             
+    
+    #EXPORT
+    if menu.collect:
+        from geocubitlib.exportlib import collect
+        try:
+            output=menu.output
+        except:
+            output='totalmesh_merged'
+        output=output.upper()
+        #
+        print menu.cpuxmin,menu.cpuxmax,menu.cpuymin,menu.cpuymax,menu.cpux,menu.cpuy
+        collect(menu.cpuxmin,menu.cpuxmax,menu.cpuymin,menu.cpuymax,menu.cpux,menu.cpuy,menu.cubfiles,menu.ckbound_method1,menu.ckbound_method2,menu.merge_tolerance,curverefining=menu.curverefining,outfilename=output,qlog=menu.qlog,export2SPECFEM3D=menu.export2SPECFEM3D,listblock=menu.listblock,listflag=menu.listflag,outdir=menu.SPECFEM3D_output_dir)
+        
+    if menu.export2SPECFEM3D and not menu.collect:
+        from geocubitlib.exportlib import e2SEM
+        print menu.cubfiles
+        e2SEM(files=menu.cubfiles,listblock=menu.listblock,listflag=menu.listflag,outdir=menu.SPECFEM3D_output_dir)

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/LatLongUTMconversion.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/LatLongUTMconversion.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/LatLongUTMconversion.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,211 +0,0 @@
-#!/usr/bin/env python
-
-# Lat Long - UTM, UTM - Lat Long conversions
-
-from math import pi, sin, cos, tan, sqrt
-
-#LatLong- UTM conversion..h
-#definitions for lat/long to UTM and UTM to lat/lng conversions
-#include <string.h>
-
-_deg2rad = pi / 180.0
-_rad2deg = 180.0 / pi
-
-_EquatorialRadius = 2
-_eccentricitySquared = 3
-
-_ellipsoid = [
-#  id, Ellipsoid name, Equatorial Radius, square of eccentricity	
-# first once is a placeholder only, To allow array indices to match id numbers
-	[ -1, "Placeholder", 0, 0],
-	[ 1, "Airy", 6377563, 0.00667054],
-	[ 2, "Australian National", 6378160, 0.006694542],
-	[ 3, "Bessel 1841", 6377397, 0.006674372],
-	[ 4, "Bessel 1841 (Nambia] ", 6377484, 0.006674372],
-	[ 5, "Clarke 1866", 6378206, 0.006768658],
-	[ 6, "Clarke 1880", 6378249, 0.006803511],
-	[ 7, "Everest", 6377276, 0.006637847],
-	[ 8, "Fischer 1960 (Mercury] ", 6378166, 0.006693422],
-	[ 9, "Fischer 1968", 6378150, 0.006693422],
-	[ 10, "GRS 1967", 6378160, 0.006694605],
-	[ 11, "GRS 1980", 6378137, 0.00669438],
-	[ 12, "Helmert 1906", 6378200, 0.006693422],
-	[ 13, "Hough", 6378270, 0.00672267],
-	[ 14, "International", 6378388, 0.00672267],
-	[ 15, "Krassovsky", 6378245, 0.006693422],
-	[ 16, "Modified Airy", 6377340, 0.00667054],
-	[ 17, "Modified Everest", 6377304, 0.006637847],
-	[ 18, "Modified Fischer 1960", 6378155, 0.006693422],
-	[ 19, "South American 1969", 6378160, 0.006694542],
-	[ 20, "WGS 60", 6378165, 0.006693422],
-	[ 21, "WGS 66", 6378145, 0.006694542],
-	[ 22, "WGS-72", 6378135, 0.006694318],
-	[ 23, "WGS-84", 6378137, 0.00669438]
-]
-
-#Reference ellipsoids derived from Peter H. Dana's website- 
-#http://www.utexas.edu/depts/grg/gcraft/notes/datum/elist.html
-#Department of Geography, University of Texas at Austin
-#Internet: pdana at mail.utexas.edu
-#3/22/95
-
-#Source
-#Defense Mapping Agency. 1987b. DMA Technical Report: Supplement to Department of Defense World Geodetic System
-#1984 Technical Report. Part I and II. Washington, DC: Defense Mapping Agency
-
-def LLtoUTM(ReferenceEllipsoid, Lat, Long):
-#converts lat/long to UTM coords.  Equations from USGS Bulletin 1532 
-#East Longitudes are positive, West longitudes are negative. 
-#North latitudes are positive, South latitudes are negative
-#Lat and Long are in decimal degrees
-#Written by Chuck Gantz- chuck.gantz at globalstar.com
-
-    a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
-    eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
-    k0 = 0.9996
-
-#Make sure the longitude is between -180.00 .. 179.9
-    LongTemp = (Long+180)-int((Long+180)/360)*360-180 # -180.00 .. 179.9
-
-    LatRad = Lat*_deg2rad
-    LongRad = LongTemp*_deg2rad
-
-    ZoneNumber = int((LongTemp + 180)/6) + 1
-  
-    if Lat >= 56.0 and Lat < 64.0 and LongTemp >= 3.0 and LongTemp < 12.0:
-        ZoneNumber = 32
-
-    # Special zones for Svalbard
-    if Lat >= 72.0 and Lat < 84.0:
-        if  LongTemp >= 0.0  and LongTemp <  9.0:ZoneNumber = 31
-        elif LongTemp >= 9.0  and LongTemp < 21.0: ZoneNumber = 33
-        elif LongTemp >= 21.0 and LongTemp < 33.0: ZoneNumber = 35
-        elif LongTemp >= 33.0 and LongTemp < 42.0: ZoneNumber = 37
-
-    LongOrigin = (ZoneNumber - 1)*6 - 180 + 3 #+3 puts origin in middle of zone
-    LongOriginRad = LongOrigin * _deg2rad
-
-    #compute the UTM Zone from the latitude and longitude
-    UTMZone = "%d%c" % (ZoneNumber, _UTMLetterDesignator(Lat))
-
-    eccPrimeSquared = (eccSquared)/(1-eccSquared)
-    N = a/sqrt(1-eccSquared*sin(LatRad)*sin(LatRad))
-    T = tan(LatRad)*tan(LatRad)
-    C = eccPrimeSquared*cos(LatRad)*cos(LatRad)
-    A = cos(LatRad)*(LongRad-LongOriginRad)
-
-    M = a*((1
-            - eccSquared/4
-            - 3*eccSquared*eccSquared/64
-            - 5*eccSquared*eccSquared*eccSquared/256)*LatRad 
-           - (3*eccSquared/8
-              + 3*eccSquared*eccSquared/32
-              + 45*eccSquared*eccSquared*eccSquared/1024)*sin(2*LatRad)
-           + (15*eccSquared*eccSquared/256 + 45*eccSquared*eccSquared*eccSquared/1024)*sin(4*LatRad) 
-           - (35*eccSquared*eccSquared*eccSquared/3072)*sin(6*LatRad))
-    
-    UTMEasting = (k0*N*(A+(1-T+C)*A*A*A/6
-                        + (5-18*T+T*T+72*C-58*eccPrimeSquared)*A*A*A*A*A/120)
-                  + 500000.0)
-
-    UTMNorthing = (k0*(M+N*tan(LatRad)*(A*A/2+(5-T+9*C+4*C*C)*A*A*A*A/24
-                                        + (61
-                                           -58*T
-                                           +T*T
-                                           +600*C
-                                           -330*eccPrimeSquared)*A*A*A*A*A*A/720)))
-
-    if Lat < 0:
-        UTMNorthing = UTMNorthing + 10000000.0; #10000000 meter offset for southern hemisphere
-    return (UTMZone, UTMEasting, UTMNorthing)
-
-
-def _UTMLetterDesignator(Lat):
-#This routine determines the correct UTM letter designator for the given latitude
-#returns 'Z' if latitude is outside the UTM limits of 84N to 80S
-#Written by Chuck Gantz- chuck.gantz at globalstar.com
-
-    if 84 >= Lat >= 72: return 'X'
-    elif 72 > Lat >= 64: return 'W'
-    elif 64 > Lat >= 56: return 'V'
-    elif 56 > Lat >= 48: return 'U'
-    elif 48 > Lat >= 40: return 'T'
-    elif 40 > Lat >= 32: return 'S'
-    elif 32 > Lat >= 24: return 'R'
-    elif 24 > Lat >= 16: return 'Q'
-    elif 16 > Lat >= 8: return 'P'
-    elif  8 > Lat >= 0: return 'N'
-    elif  0 > Lat >= -8: return 'M'
-    elif -8> Lat >= -16: return 'L'
-    elif -16 > Lat >= -24: return 'K'
-    elif -24 > Lat >= -32: return 'J'
-    elif -32 > Lat >= -40: return 'H'
-    elif -40 > Lat >= -48: return 'G'
-    elif -48 > Lat >= -56: return 'F'
-    elif -56 > Lat >= -64: return 'E'
-    elif -64 > Lat >= -72: return 'D'
-    elif -72 > Lat >= -80: return 'C'
-    else: return 'Z'	# if the Latitude is outside the UTM limits
-
-#void UTMtoLL(int ReferenceEllipsoid, const double UTMNorthing, const double UTMEasting, const char* UTMZone,
-#			  double& Lat,  double& Long )
-
-def UTMtoLL(ReferenceEllipsoid, northing, easting, zone):
-
-#converts UTM coords to lat/long.  Equations from USGS Bulletin 1532 
-#East Longitudes are positive, West longitudes are negative. 
-#North latitudes are positive, South latitudes are negative
-#Lat and Long are in decimal degrees. 
-#Written by Chuck Gantz- chuck.gantz at globalstar.com
-#Converted to Python by Russ Nelson <nelson at crynwr.com>
-
-    k0 = 0.9996
-    a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
-    eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
-    e1 = (1-sqrt(1-eccSquared))/(1+sqrt(1-eccSquared))
-    #NorthernHemisphere; //1 for northern hemispher, 0 for southern
-
-    x = easting - 500000.0 #remove 500,000 meter offset for longitude
-    y = northing
-
-    ZoneLetter = zone[-1]
-    ZoneNumber = int(zone[:-1])
-    if ZoneLetter >= 'N':
-        NorthernHemisphere = 1  # point is in northern hemisphere
-    else:
-        NorthernHemisphere = 0  # point is in southern hemisphere
-        y -= 10000000.0         # remove 10,000,000 meter offset used for southern hemisphere
-
-    LongOrigin = (ZoneNumber - 1)*6 - 180 + 3  # +3 puts origin in middle of zone
-
-    eccPrimeSquared = (eccSquared)/(1-eccSquared)
-
-    M = y / k0
-    mu = M/(a*(1-eccSquared/4-3*eccSquared*eccSquared/64-5*eccSquared*eccSquared*eccSquared/256))
-
-    phi1Rad = (mu + (3*e1/2-27*e1*e1*e1/32)*sin(2*mu) 
-               + (21*e1*e1/16-55*e1*e1*e1*e1/32)*sin(4*mu)
-               +(151*e1*e1*e1/96)*sin(6*mu))
-    phi1 = phi1Rad*_rad2deg;
-
-    N1 = a/sqrt(1-eccSquared*sin(phi1Rad)*sin(phi1Rad))
-    T1 = tan(phi1Rad)*tan(phi1Rad)
-    C1 = eccPrimeSquared*cos(phi1Rad)*cos(phi1Rad)
-    R1 = a*(1-eccSquared)/pow(1-eccSquared*sin(phi1Rad)*sin(phi1Rad), 1.5)
-    D = x/(N1*k0)
-
-    Lat = phi1Rad - (N1*tan(phi1Rad)/R1)*(D*D/2-(5+3*T1+10*C1-4*C1*C1-9*eccPrimeSquared)*D*D*D*D/24
-                                          +(61+90*T1+298*C1+45*T1*T1-252*eccPrimeSquared-3*C1*C1)*D*D*D*D*D*D/720)
-    Lat = Lat * _rad2deg
-
-    Long = (D-(1+2*T1+C1)*D*D*D/6+(5-2*C1+28*T1-3*C1*C1+8*eccPrimeSquared+24*T1*T1)
-            *D*D*D*D*D/120)/cos(phi1Rad)
-    Long = LongOrigin + Long * _rad2deg
-    return (Lat, Long)
-
-if __name__ == '__main__':
-    (z, e, n) = LLtoUTM(23, 45.00, -75.00)
-    print z, e, n
-    (lat, lon) = UTMtoLL(23, n, e, z)
-    print lat, lon
-

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/MANIFEST.in
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/MANIFEST.in	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/MANIFEST.in	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,22 @@
+include GEOCUBIT.py
+include setup.py
+include geocubitlib/LatLongUTMconversion.py
+include geocubitlib/__init__.py
+include geocubitlib/boundary_check.py
+include geocubitlib/boundary_definition.py
+include geocubitlib/cubit2specfem3d.py
+include geocubitlib/geocubitlib.py
+include geocubitlib/hex_metric.py
+include geocubitlib/start.py
+include geocubitlib/local_volume.py
+include geocubitlib/menu.py
+include geocubitlib/merginglib.py
+include geocubitlib/mesh_volume.py
+include geocubitlib/mpi_geocubit.py
+include geocubitlib/partitioner.py
+include geocubitlib/quality_log.py
+include geocubitlib/read_parameter_cfg.py
+include geocubitlib/select_in_out.py
+include geocubitlib/surfaces.py
+include geocubitlib/volumes.py
+recursive-include example *

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/README.txt
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/README.txt	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/README.txt	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,6 +0,0 @@
-
-The original version of file cubit2specfem3d.py is in the "GEOCUBIT" project, which on the SVN server at CIG
-is in GEOCUBIT/geocubitlib/cubit2specfem3d.py.
-
-The version in this directory is a copy.
-

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/__init__.py
===================================================================
Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/absorbing_boundary.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/absorbing_boundary.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/absorbing_boundary.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,350 +0,0 @@
-#!python
-# Retrieving absorbing boundaries.
-#    P. Galvez (ETH-Zurich, 10.09.2011):
-#    This function is based on Emmanuele Cassarotti , boundary_definition.py routine. 
-#    
-#    It returns absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,
-#    absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,topo_surf
-#    where absorbing_surf is the list of all the absorbing boundary surf
-#    absorbing_surf_xmin is the list of the absorbing boundary surfaces that correnspond to x=xmin
-#    ...
-#    absorbing_surf_bottom is the list of the absorbing boundary surfaces that correspond to z=zmin
-
-class abs_surface:
-   def __init__(self,xmin,xmax,ymin,ymax): 
-       self.xmin = xmin
-       self.xmax = xmax
-       self.ymin = ymin
-       self.ymax = ymax
-
-class abs_surface_topo:
-   def __init__(self,xmin,xmax,ymin,ymax,bottom,topo): 
-       self.xmin = xmin
-       self.xmax = xmax
-       self.ymin = ymin
-       self.ymax = ymax
-       self.bottom = bottom
-       self.topo = topo
- 
-# Emmanuele Cassarotti function for Parallel absorbing boundaries.
-# WARNING : absorbing.surf deleted due to CUBIT 13.0 does not allow elements beloging to diferent blocks.
-
-def define_parallel_absorbing_surf():
-    """
-    define the absorbing surfaces for a layered topological box where boundary are surfaces parallel to the axis.
-    it returns absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,topo_surf
-    where
-    absorbing_surf is the list of all the absorbing boundary surf
-    absorbing_surf_xmin is the list of the absorbing boundary surfaces that correnspond to x=xmin
-    ...
-    absorbing_surf_bottom is the list of the absorbing boundary surfaces that correspond to z=zmin
-    """
-    try:
-        cubit.cmd('comment')
-    except:
-        try:
-            import cubit
-            cubit.init([""])
-        except:
-            print 'error importing cubit'
-            import sys
-            sys.exit()
-    absorbing_surf_xmin=[]
-    absorbing_surf_xmax=[]
-    absorbing_surf_ymin=[]
-    absorbing_surf_ymax=[]
-    absorbing_surf_bottom=[]
-    top_surf=[]
-    
-    
-    list_vol=cubit.parse_cubit_list("volume","all")
-    init_n_vol=len(list_vol)
-    zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
-    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...    
-    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
-    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
-    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
-    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
-    list_surf=cubit.parse_cubit_list("surface","all")
-    print '##boundary box: '
-    print '##  x min: ' + str(xmin_box)
-    print '##  y min: ' + str(ymin_box)
-    print '##  z min: ' + str(zmin_box)
-    print '##  x max: ' + str(xmax_box)
-    print '##  y max: ' + str(ymax_box)
-    print '##  z max: ' + str(zmax_box)
-
-    #box lengths
-    x_len = abs( xmax_box - xmin_box)
-    y_len = abs( ymax_box - ymin_box)
-    z_len = abs( zmax_box - zmin_box)
-    
-    print '##boundary box: '
-    print '##  x length: ' + str(x_len)
-    print '##  y length: ' + str(y_len)
-    print '##  z length: ' + str(z_len)
-    
-    # tolerance parameters 
-    absorbing_surface_distance_tolerance=0.005
-    topographic_surface_distance_tolerance=0.001
-    topographic_surface_normal_tolerance=0.2
-        
-    for k in list_surf:
-        center_point = cubit.get_center_point("surface", k)
-        if abs((center_point[0] - xmin_box)/x_len) <= absorbing_surface_distance_tolerance:
-             absorbing_surf_xmin.append(k)
-        elif abs((center_point[0] - xmax_box)/x_len) <= absorbing_surface_distance_tolerance:
-             absorbing_surf_xmax.append(k)
-        elif abs((center_point[1] - ymin_box)/y_len) <= absorbing_surface_distance_tolerance:
-             absorbing_surf_ymin.append(k)
-        elif abs((center_point[1] - ymax_box)/y_len) <= absorbing_surface_distance_tolerance:
-             absorbing_surf_ymax.append(k)
-        elif abs((center_point[2] - zmin_box)/z_len) <= absorbing_surface_distance_tolerance:
-             print 'center_point[2]' + str(center_point[2])
-             print 'kz:' + str(k)
-             absorbing_surf_bottom.append(k)
-                       
-        else:
-            sbox=cubit.get_bounding_box('surface',k)
-            dz=abs((sbox[7] - zmax_box)/z_len)
-            normal=cubit.get_surface_normal(k)
-            zn=normal[2]
-            dn=abs(zn-1)
-            if dz <= topographic_surface_distance_tolerance and dn < topographic_surface_normal_tolerance:
-                top_surf.append(k)
-
-    return absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,top_surf
-
-def define_top_bottom_absorbing_surf(zmin_box,zmax_box):
-    """
-      absorbing_surf_bottom is the list of the absorbing boundary surfaces that correspond to z=zmin
-    """
-    try:
-        cubit.cmd('comment')
-    except:
-        try:
-            import cubit
-            cubit.init([""])
-        except:
-            print 'error importing cubit'
-            import sys
-            sys.exit()
-    absorbing_surf_bottom=[]
-    top_surf = []
-    
-    list_vol=cubit.parse_cubit_list("volume","all")
-    init_n_vol=len(list_vol)
-#   TO DO : Make zmin_box work properly.
-#   zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
-#   zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...
-    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
-    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
-    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
-    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
-    list_surf=cubit.parse_cubit_list("surface","all")
-   
-    print '##boundary box: '
-    print '##  x min: ' + str(xmin_box)
-    print '##  y min: ' + str(ymin_box)
-    print '##  z min: ' + str(zmin_box)
-    print '##  x max: ' + str(xmax_box)
-    print '##  y max: ' + str(ymax_box)
-    print '##  z max: ' + str(zmax_box)
-
-    #box lengths
-    x_len = abs( xmax_box - xmin_box)
-    y_len = abs( ymax_box - ymin_box)
-    z_len = abs( zmax_box - zmin_box)
-    
-    print '##boundary box: '
-    print '##  x length: ' + str(x_len)
-    print '##  y length: ' + str(y_len)
-    print '##  z length: ' + str(z_len)
-    
-    # tolerance parameters 
-    absorbing_surface_distance_tolerance=0.005
-    topographic_surface_distance_tolerance=0.001
-    topographic_surface_normal_tolerance=0.2
-
-    for k in list_surf:
-        center_point = cubit.get_center_point("surface", k)
-        if abs((center_point[2] - zmin_box)/z_len) <= absorbing_surface_distance_tolerance:
-             print 'center_point[2]' + str(center_point[2])
-             print 'kz:' + str(k)
-             absorbing_surf_bottom.append(k)
-   
-        else:
-            sbox=cubit.get_bounding_box('surface',k)
-            dz=abs((sbox[7] - zmax_box)/z_len)
-            normal=cubit.get_surface_normal(k)
-            zn=normal[2]
-            dn=abs(zn-1)
-            if dz <= topographic_surface_distance_tolerance and dn < topographic_surface_normal_tolerance:
-                top_surf.append(k)
-    
-    return absorbing_surf_bottom,top_surf
-
-
-def build_block(vol_list,name):
-    from sets import Set
-    try:
-            cubit.cmd('comment')
-    except:
-            try:
-                import cubit
-                cubit.init([""])
-            except:
-                print 'error importing cubit'
-                import sys
-                sys.exit()
-    block_list=cubit.get_block_id_list()
-    if len(block_list) > 0:
-        id_block=max(block_list)
-    else:
-        id_block=0
-    for v,n in zip(vol_list,name):
-       id_block+=1
-       v_other=Set(vol_list)-Set([v])
-       command= 'block '+str(id_block)+' hex in vol '+str(v)
-       command = command.replace("["," ").replace("]"," ")
-       cubit.cmd(command) 
-       command = "block "+str(id_block)+" name '"+n+"'"
-       cubit.cmd(command)
-
-
-def define_block():
-    """ 
-     Renumbering number of volumes from 1 to NVOLUMES.
-    """ 
-    try:
-            cubit.cmd('comment')
-    except:
-            try:
-                import cubit
-                cubit.init([""])
-            except:
-                print 'error importing cubit'
-                import sys
-                sys.exit()
-    list_vol=cubit.parse_cubit_list("volume","all")
-    init_n_vol=len(list_vol)
-    list_name=map(lambda x: 'vol'+x,map(str,list_vol))
-    return list_vol,list_name
-
- 
-def build_block_side(surf_list,name,obj='surface'):
-    try:
-            cubit.cmd('comment')
-    except:
-            try:
-                import cubit
-                cubit.init([""])
-            except:
-                print 'error importing cubit'
-                import sys
-                sys.exit()
-    id_nodeset=cubit.get_next_nodeset_id()
-    id_block=cubit.get_next_block_id()
-    
-    if obj == 'hex':
-        txt='hex in node in surface'
-        txt1='block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
-        txt2="block "+str(id_block)+" name '"+name+"'"
-        txt1=txt1.replace("["," ").replace("]"," ")
-    elif obj == 'node':
-         txt=obj+' in surface'
-         txt1= 'nodeset '+str(id_nodeset)+ ' '+ txt +' '+str(list(surf_list))
-         txt1 = txt1.replace("["," ").replace("]"," ")
-         txt2 = "nodeset "+str(id_nodeset)+" name '"+name+"'"
-    elif obj == 'face' or obj == 'edge':
-        txt=obj+' in surface'
-        txt1= 'block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
-        txt1 = txt1.replace("["," ").replace("]"," ")
-        txt2 = "block "+str(id_block)+" name '"+name+"'"
-    else:
-        txt1=''
-        # do not execute: block id might be wrong
-        print "##block "+str(id_block)+" name '"+name+"_notsupported (only hex,face,edge,node)'"
-        txt2=''
-   
- 
-    cubit.cmd(txt1)
-    cubit.cmd(txt2)
-
-
-def define_bc(entities,zmin,zmax,self):
-     # Temporal : Variable zmin should be obtained automatically. 
-     xmin = self.xmin
-     xmax = self.xmax
-     ymin = self.ymin
-     ymax = self.ymax
-     bottom,topo=define_top_bottom_absorbing_surf(zmin,zmax)
-     v_list,name_list=define_block()
-     build_block(v_list,name_list)
-     print entities
-     for entity in entities:
-         print "##entity: "+str(entity)
-         build_block_side(xmin,entity+'_abs_xmin',obj=entity)
-         build_block_side(xmax,entity+'_abs_xmax',obj=entity)
-         build_block_side(ymin,entity+'_abs_ymin',obj=entity)
-         build_block_side(ymax,entity+'_abs_ymax',obj=entity)
-         build_block_side(bottom,entity+'_abs_bottom',obj=entity)
-         build_block_side(topo,entity+'_topo',obj=entity)
-
-def define_parallel_bc(entities):
-     xmax = []
-     ymin = []
-     ymax = []
-     zmin = []
-     zmax = []
-     #Extracting parallel surfaces.
-     xmin,xmax,ymin,ymax,bottom,topo=define_parallel_absorbing_surf()
-     v_list,name_list=define_block()
-     build_block(v_list,name_list)
-     print entities
-     for entity in entities:
-         print "##entity: "+str(entity)
-         build_block_side(xmin,entity+'_abs_xmin',obj=entity)
-         build_block_side(xmax,entity+'_abs_xmax',obj=entity)
-         build_block_side(ymin,entity+'_abs_ymin',obj=entity)
-         build_block_side(ymax,entity+'_abs_ymax',obj=entity)
-         build_block_side(bottom,entity+'_abs_bottom',obj=entity)
-         build_block_side(topo,entity+'_topo',obj=entity)
-
-
-def define_boundaries(entities,xmin,xmax,ymin,ymax,zmin,zmax):
-     bottom=zmin
-     topo=zmax
-     v_list,name_list=define_block()
-     build_block(v_list,name_list)
-     print entities
-     for entity in entities:
-         print "##entity: "+str(entity)
-         build_block_side(xmin,entity+'_abs_xmin',obj=entity)
-         build_block_side(xmax,entity+'_abs_xmax',obj=entity)
-         build_block_side(ymin,entity+'_abs_ymin',obj=entity)
-         build_block_side(ymax,entity+'_abs_ymax',obj=entity)
-         build_block_side(bottom,entity+'_abs_bottom',obj=entity)
-         build_block_side(topo,entity+'_topo',obj=entity)
-
-def define_bc_topo(entities,self):
-     # Temporal : Variable zmin should be obtained automatically. 
-     xmin = self.xmin
-     xmax = self.xmax
-     ymin = self.ymin
-     ymax = self.ymax
-     bottom = self.bottom
-     topo = self.topo
-     v_list,name_list=define_block()
-     build_block(v_list,name_list)
-     print entities
-     for entity in entities:
-         print "##entity: "+str(entity)
-         build_block_side(xmin,entity+'_abs_xmin',obj=entity)
-         build_block_side(xmax,entity+'_abs_xmax',obj=entity)
-         build_block_side(ymin,entity+'_abs_ymin',obj=entity)
-         build_block_side(ymax,entity+'_abs_ymax',obj=entity)
-         build_block_side(bottom,entity+'_abs_bottom',obj=entity)
-         build_block_side(topo,entity+'_topo',obj=entity)
-
-

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/boundary_definition.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/boundary_definition.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/boundary_definition.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,531 +0,0 @@
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-
-def list2str(l):
-    if not isinstance(l,list): l=list(l)
-    return ' '.join(str(x) for x in l)
-
-
-def map_boundary(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1):
-    ymin=[]
-    xmax=[]
-    xmin=[]
-    ymax=[]
-    listfull=[]
-    #
-    for ix in range(cpuxmin,cpuxmax):
-        for iy in range(cpuymin,cpuymax):
-            ip=iy*cpux+ix
-            if ix == cpuxmin:
-                xmin.append(ip)
-            if ix == cpuxmax-1:
-                xmax.append(ip)
-            if iy == cpuymin:
-                ymin.append(ip)
-            if iy == cpuymax-1:
-                ymax.append(ip)
-                #
-            listfull.append(ip)
-    return xmin,xmax,ymin,ymax,listfull
-
-
-def define_4side_lateral_surfaces():
-    list_vol=cubit.parse_cubit_list("volume","all")
-    surf_xmin=[]
-    surf_ymin=[]
-    surf_xmax=[]
-    surf_ymax=[]
-    for id_vol in list_vol:
-        surf_vertical=[]
-        xsurf=[]
-        ysurf=[]
-        tres=0.3
-        lsurf=cubit.get_relatives("volume",id_vol,"surface")
-        for k in lsurf:
-            normal=cubit.get_surface_normal(k)
-            center_point = cubit.get_center_point("surface", k)
-            if normal[2] >= -1*tres and normal[2] <= tres:
-                surf_vertical.append(k)
-                xsurf.append(center_point[0])
-                ysurf.append(center_point[1])
-        surf_xmin.append(surf_vertical[xsurf.index(min(xsurf))])
-        surf_ymin.append(surf_vertical[ysurf.index(min(ysurf))])
-        surf_xmax.append(surf_vertical[xsurf.index(max(xsurf))])
-        surf_ymax.append(surf_vertical[ysurf.index(max(ysurf))])
-    return surf_xmin,surf_ymin,surf_xmax,surf_ymax
-
-
-
-
-def lateral_boundary_are_absorbing(ip=0,cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1):
-    #
-    xmin,ymin,xmax,ymax=define_4side_lateral_surfaces()
-    ip_xmin,ip_xmax,ip_ymin,ip_ymax,listfull=map_boundary(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
-    if  not isinstance(ip_xmin, list): ip_xmin=[ip_xmin]
-    if  not isinstance(ip_ymin, list): ip_ymin=[ip_ymin]
-    if  not isinstance(ip_xmax, list): ip_xmax=[ip_xmax]
-    if  not isinstance(ip_ymax, list): ip_ymax=[ip_ymax]
-    #
-    abs_xmin=[]
-    abs_ymin=[]
-    abs_xmax=[]
-    abs_ymax=[]
-    #
-    if ip in ip_xmin: 
-        abs_xmin=xmin
-        print 'proc ',ip,' is has absorbing boundary xmin'
-    if ip in ip_ymin:     
-        print 'proc ',ip,' is has absorbing boundary ymin'
-        abs_ymin=ymin
-    if ip in ip_xmax:     
-        print 'proc ',ip,' is has absorbing boundary xmax'
-        abs_xmax=xmax
-    if ip in ip_ymax:     
-        print 'proc ',ip,' is has absorbing boundary ymax'
-        abs_ymax=ymax
-    return abs_xmin,abs_xmax,abs_ymin,abs_ymax
-
-
-def define_surf(ip=0,cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1):
-    """
-    define the surfaces defining the boundaries of the volume
-    """
-    #
-    from sets import Set
-    def product(*args, **kwds):
-        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
-        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
-        pools = map(tuple, args) * kwds.get('repeat', 1)
-        result = [[]]
-        for pool in pools:
-            result = [x+[y] for x in result for y in pool]
-        return result
-    absorbing_surf=[]
-    xmin=[]
-    xmax=[]
-    ymin=[]
-    ymax=[]
-    #
-    top_surf=[]
-    bottom_surf=[]
-    list_vol=cubit.parse_cubit_list("volume","all")
-    zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
-    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...    
-    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
-    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
-    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
-    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
-    list_surf=cubit.parse_cubit_list("surface","all")
-    lv=[]
-    for k in list_surf:
-        sbox=cubit.get_bounding_box('surface',k)
-        if zmax_box == 0 and sbox[7] == 0:
-             dzmax=0
-        elif zmax_box == 0 or sbox[7] == 0:
-            dzmax=abs(sbox[7] - zmax_box)
-        else:
-            dzmax=abs(sbox[7] - zmax_box)/max(abs(sbox[7]),abs(zmax_box))
-        if zmin_box == 0 and sbox[6] == 0:
-             dzmin=0
-        elif zmin_box == 0 or sbox[6] == 0:
-            dzmin=abs(sbox[6] - zmin_box)                                            
-        else:                                                    
-            dzmin=abs(sbox[6] - zmin_box)/max(abs(sbox[6]),abs(zmin_box))
-        normal=cubit.get_surface_normal(k)
-        zn=normal[2]
-        if dzmax <= 0.1 and zn > 0.4:
-            top_surf.append(k)
-            list_vertex=cubit.get_relatives('surface',k,'vertex')
-            for v in list_vertex:
-                valence=cubit.get_valence(v)
-                if valence <= 4: #valence 3 is a corner, 4 is a vertex between 2 volumes, > 4 is a vertex not in the boundaries
-                    lv.append(v)
-        elif dzmin <= 0.001 and zn < -0.7:
-            bottom_surf.append(k)
-    lp=[]
-    combs=product(lv,lv)
-    for comb in combs:
-        v1=comb[0]
-        v2=comb[1]
-        c=Set(cubit.get_relatives("vertex",v1,"curve")) & Set(cubit.get_relatives("vertex",v2,"curve"))
-        if len(c) == 1:
-            p=cubit.get_center_point("curve",list(c)[0])
-            lp.append(p)
-    for k in list_surf: 
-        center_point = cubit.get_center_point("surface", k)
-        for p in lp:
-            if abs((center_point[0] - p[0])/p[0]) <= 0.001 and abs((center_point[1] - p[1])/p[1]) <= 0.001:
-                absorbing_surf.append(k)
-                break
-    #
-    four_side=True
-    if four_side:
-        xmin,ymin,xmax,ymax=define_4side_lateral_surfaces()
-        abs_xmin,abs_xmax,abs_ymin,abs_ymax=lateral_boundary_are_absorbing(ip,cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
-
-    return absorbing_surf,abs_xmin,abs_xmax,abs_ymin,abs_ymax,top_surf,bottom_surf,xmin,ymin,xmax,ymax
-
-
-
-def define_block():
-    list_vol=cubit.parse_cubit_list("volume","all")
-    init_n_vol=len(list_vol)
-    list_name=map(lambda x: 'vol'+x,map(str,list_vol))
-    return list_vol,list_name
-
-def build_block(vol_list,name,id_0=1):
-    #
-    from sets import Set
-    #
-    block_list=cubit.get_block_id_list()
-    if len(block_list) > 0:
-        id_block=max(max(block_list),2)+id_0
-    else:
-        id_block=2+id_0
-    for v,n in zip(vol_list,name):
-        id_block+=1
-        v_other=Set(vol_list)-Set([v])
-        #command= 'block '+str(id_block)+' hex in node in vol '+str(v)+' except hex in vol '+str(list(v_other))
-        command= 'block '+str(id_block)+' hex in vol '+str(v)+' except hex in vol '+str(list(v_other))
-        print command
-        command = command.replace("["," ").replace("]"," ")
-        cubit.cmd(command) 
-        command = "block "+str(id_block)+" name '"+n+"'"
-        cubit.cmd(command)
-
-def build_block_side(surf_list,name,obj='surface',id_0=1):
-    id_nodeset=cubit.get_next_nodeset_id()
-    id_block=id_0
-    if obj == 'hex':
-        txt='hex in node in surface'
-        txt1='block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
-        txt2="block "+str(id_block)+" name '"+name+"'"
-        txt1=txt1.replace("["," ").replace("]"," ")
-        cubit.cmd(txt1)
-        cubit.cmd(txt2)
-    elif obj == 'node':
-        txt=obj+' in surface'
-        txt1= 'nodeset '+str(id_nodeset)+ ' '+ txt +' '+str(list(surf_list))
-        txt1 = txt1.replace("["," ").replace("]"," ")
-        txt2 = "nodeset "+str(id_nodeset)+" name '"+name+"'"
-        cubit.cmd(txt1)
-        cubit.cmd(txt2)
-    elif obj == 'face' or obj == 'edge':
-        txt=obj+' in surface'
-        txt1= 'block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
-        txt1 = txt1.replace("["," ").replace("]"," ")
-        txt2 = "block "+str(id_block)+" name '"+name+"'"
-        cubit.cmd(txt1)
-        cubit.cmd(txt2)
-    else:
-        txt1=''
-        txt2="block "+str(id_block)+" name "+name+"_notsupported (only hex,face,edge,node)"
-        try:
-            cubit.cmd('comment "'+txt1+'"')
-            cubit.cmd('comment "'+txt2+'"')
-        except:
-            pass
-
-def define_bc(*args,**keys):
-    id_0=1
-    #
-    #
-    parallel=keys.get('parallel',True)
-    closed=keys.get('closed',False)
-    ip=keys.get("iproc",0)
-    cpuxmin=keys.get("cpuxmin",0)
-    cpuymin=keys.get("cpuymin",0)
-    cpux=keys.get("cpux",1)
-    cpuy=keys.get("cpuy",1)
-    cpuxmax=keys.get("cpuxmax",cpux)
-    cpuymax=keys.get("cpuymax",cpuy)
-    #
-    if parallel:
-        absorbing_surf,abs_xmin,abs_xmax,abs_ymin,abs_ymax,top_surf,bottom_surf,xmin,ymin,xmax,ymax=define_surf(ip=ip,cpuxmin=cpuxmin,cpuxmax=cpuxmax,cpuymin=cpuymin,cpuymax=cpuymax,cpux=cpux,cpuy=cpuy)
-        #
-        #id_side=cubit.get_next_block_id()
-        #try:
-        #    entities=args[0]
-        #except:
-        #    entities=['face']
-        #for entity in entities:
-        #    build_block_side(top_surf,entity+'_topo',obj=entity,id_0=1) #topo is block 1 so id_0=1
-        #    build_block_side(bottom_surf,entity+'_abs_bottom',obj=entity,id_0=2)
-        #    build_block_side(xmin,entity+'_xmin',obj=entity,id_0=3)
-        #    build_block_side(ymin,entity+'_ymin',obj=entity,id_0=4)
-        #    build_block_side(xmax,entity+'_xmax',obj=entity,id_0=5)
-        #    build_block_side(ymax,entity+'_ymax',obj=entity,id_0=6)
-        #     
-        id_0=cubit.get_next_block_id()
-        v_list,name_list=define_block()
-        build_block(v_list,name_list,id_0)
-        #
-    elif closed:
-        surf=define_absorbing_surf_sphere()
-        v_list,name_list=define_block()
-        build_block(v_list,name_list,id_0)
-        entities=args[0]
-        id_side=1
-        for entity in entities:
-            build_block_side(surf,entity+'_closedvol',obj=entity,id_0=id_side)
-            id_side=id_side+1
-            
-#########################################
-
-
-def extract_bottom_curves(surf_xmin,surf_ymin,surf_xmax,surf_ymax):
-    curve_xmin=[]
-    curve_ymin=[]
-    curve_xmax=[]
-    curve_ymax=[]
-    from sets import Set #UPGRADE.... the sets module is deprecated after python 2.6
-    for s in surf_xmin:
-        lcs=cubit.get_relatives("surface",s,"curve")
-        for lc in lcs:
-            curve_xmin.append(lc)
-    for s in surf_xmax:
-        lcs=cubit.get_relatives("surface",s,"curve")
-        for lc in lcs:
-            curve_xmax.append(lc)
-    for s in surf_ymin:
-        lcs=cubit.get_relatives("surface",s,"curve")
-        for lc in lcs:
-            curve_ymin.append(lc)
-    for s in surf_ymax:
-        lcs=cubit.get_relatives("surface",s,"curve")
-        for lc in lcs:
-            curve_ymax.append(lc)
-    curve_xmin=list(Set(curve_xmin))
-    curve_ymin=list(Set(curve_ymin))
-    curve_xmax=list(Set(curve_xmax))
-    curve_ymax=list(Set(curve_ymax))
-    curve_bottom_xmin=select_bottom_curve(curve_xmin)
-    curve_bottom_ymin=select_bottom_curve(curve_ymin)
-    curve_bottom_xmax=select_bottom_curve(curve_xmax)
-    curve_bottom_ymax=select_bottom_curve(curve_ymax)
-    #
-    return curve_bottom_xmin,curve_bottom_ymin,curve_bottom_xmax,curve_bottom_ymax
-
-def select_bottom_curve(lc):
-    z=[]
-    for l in lc:
-        center_point = cubit.get_center_point("curve", l)
-        z.append(center_point[2])
-    result=zip(z,lc)
-    result.sort()
-    return result[0][1]
-
-
-def get_ordered_node_surf(lsurface,icurve):
-    if not isinstance(lsurface,str): 
-        lsurf=list2str(lsurface)
-    #
-    if not isinstance(icurve,str): 
-        icurvestr=str(icurve)
-    orient_nodes_surf=[]
-    #
-    cubit.cmd('del group sl')
-    cubit.cmd("group 'sl' add node in surf "+lsurf)
-    group1 = cubit.get_id_from_name("sl")
-    nodes_ls =list(cubit.get_group_nodes(group1))
-    nnode=len(nodes_ls)
-    #
-    orient=[]
-    cubit.cmd('del group n1')
-    cubit.cmd("group 'n1' add node in curve "+icurvestr)
-    x=cubit.get_bounding_box('curve', icurve)
-    if x[2]>x[5]:
-        idx=0
-    else:
-        idx=1
-    group1 = cubit.get_id_from_name("n1")
-    nodes1 = list(cubit.get_group_nodes(group1))
-    for n in nodes1:
-        v = cubit.get_nodal_coordinates(n)
-        orient.append(v[idx])
-    result=zip(orient,nodes1)
-    result.sort()
-    nodes2=[c[1] for c in result]
-    for n in nodes2:
-        try:
-            nodes_ls.remove(n)
-        except:
-            pass             
-    orient_nodes_surf=orient_nodes_surf+nodes2
-    #
-    while len(orient_nodes_surf) < nnode:
-        cubit.cmd('del group n1')
-        cubit.cmd("group 'n1' add node in edge in node "+str(nodes2).replace('[',' ').replace(']',' '))
-        group1 = cubit.get_id_from_name("n1")
-        nodes1 = list(cubit.get_group_nodes(group1))
-        orient=[]
-        nd=[]
-        for n in nodes1:
-            if n in nodes_ls:
-                v = cubit.get_nodal_coordinates(n)
-                orient.append(v[idx])
-                nd.append(n)
-        result=zip(orient,nd)
-        result.sort()
-        nodes2=[c[1] for c in result]
-        for n in nodes2:
-            try:
-                nodes_ls.remove(n)
-            except:
-                pass
-        orient_nodes_surf=orient_nodes_surf+nodes2
-    #get the vertical curve
-    curve_vertical=[]
-    for s in lsurface:
-        lcs=cubit.get_relatives("surface",s,"curve")
-        for l in lcs:
-            x=cubit.get_bounding_box('curve', l)
-            length=[(x[2],1),(x[5],2),(x[8],3)]
-            length.sort()
-            if length[-1][1] == 3:
-                curve_vertical.append(l)
-    #
-    icurve=list2str(curve_vertical)
-    cubit.cmd('del group curve_vertical')
-    cubit.cmd("group 'curve_vertical' add node in curve "+icurve)
-    group1 = cubit.get_id_from_name('curve_vertical')
-    nodes_curve = list(cubit.get_group_nodes(group1))
-    for n in nodes_curve:
-        try:
-            orient_nodes_surf.remove(n)
-        except:
-            pass
-    #
-    return nodes_curve,orient_nodes_surf
-
-
-
-def check_bc(iproc,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax):
-    """
-    boundary=check_bc(iproc,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
-    #
-    set the boundary condition during the collecting phase and group the nodes of the vertical surface in groups for the merging phase
-    iproc is the value of the processor 
-    xmin,ymin,ymax,ymin are the list of iproc that have at least one absorbing boundary condition
-    """
-    #
-    absorbing_surf,abs_xmin,abs_xmax,abs_ymin,abs_ymax,top_surf,bottom_surf,surf_xmin,surf_ymin,surf_xmax,surf_ymax=define_surf(ip=iproc,cpuxmin=cpuxmin,cpuxmax=cpuxmax,cpuymin=cpuymin,cpuymax=cpuymax,cpux=cpux,cpuy=cpuy)
-    curve_bottom_xmin,curve_bottom_ymin,curve_bottom_xmax,curve_bottom_ymax=extract_bottom_curves(surf_xmin,surf_ymin,surf_xmax,surf_ymax)
-    print absorbing_surf,abs_xmin,abs_xmax,abs_ymin,abs_ymax,top_surf,bottom_surf,surf_xmin,surf_ymin,surf_xmax,surf_ymax
-    #
-    #
-    #
-    from sets import Set #UPGRADE.... the sets module is deprecated after python 2.6
-    
-    cubit.cmd('set info off')
-    cubit.cmd('set echo off')
-    nodes_curve_ymax,orient_nodes_surf_ymax=get_ordered_node_surf(surf_ymax,curve_bottom_ymax)
-    nodes_curve_xmax,orient_nodes_surf_xmax=get_ordered_node_surf(surf_xmax,curve_bottom_xmax)
-    nodes_curve_ymin,orient_nodes_surf_ymin=get_ordered_node_surf(surf_ymin,curve_bottom_ymin)
-    nodes_curve_xmin,orient_nodes_surf_xmin=get_ordered_node_surf(surf_xmin,curve_bottom_xmin)
-    c_xminymin=Set(nodes_curve_xmin).intersection(nodes_curve_ymin)
-    c_xminymax=Set(nodes_curve_xmin).intersection(nodes_curve_ymax)
-    c_xmaxymin=Set(nodes_curve_xmax).intersection(nodes_curve_ymin)
-    c_xmaxymax=Set(nodes_curve_xmax).intersection(nodes_curve_ymax)
-    cubit.cmd('set info on')
-    cubit.cmd('set echo on')
-    
-    
-    #
-    orient=[]
-    nd=[]
-    for n in c_xminymin:
-        v = cubit.get_nodal_coordinates(n)
-        orient.append(v[2])
-        nd.append(n)
-    result=zip(orient,nd)
-    result.sort()
-    c_xminymin=[c[1] for c in result]
-    #
-    orient=[]
-    nd=[]    
-    for n in c_xminymax:
-        v = cubit.get_nodal_coordinates(n)
-        orient.append(v[2])
-        nd.append(n)
-    result=zip(orient,nd)
-    result.sort()
-    c_xminymax=[c[1] for c in result]
-    #
-    orient=[]
-    nd=[]
-    for n in c_xmaxymin:
-        v = cubit.get_nodal_coordinates(n)
-        orient.append(v[2])
-        nd.append(n)
-    result=zip(orient,nd)
-    result.sort()
-    c_xmaxymin=[c[1] for c in result]
-    #
-    orient=[]
-    nd=[]
-    for n in c_xmaxymax:
-        v = cubit.get_nodal_coordinates(n)
-        orient.append(v[2])
-        nd.append(n)
-    result=zip(orient,nd)
-    result.sort()
-    c_xmaxymax=[c[1] for c in result]
-    #
-    boundary={}
-    boundary['id']=iproc
-    #
-    boundary['nodes_surf_xmin']=orient_nodes_surf_xmin
-    boundary['nodes_surf_xmax']=orient_nodes_surf_xmax
-    boundary['nodes_surf_ymin']=orient_nodes_surf_ymin
-    boundary['nodes_surf_ymax']=orient_nodes_surf_ymax
-    #
-    boundary['node_curve_xminymin']=c_xminymin
-    boundary['node_curve_xminymax']=c_xminymax
-    boundary['node_curve_xmaxymin']=c_xmaxymin
-    boundary['node_curve_xmaxymax']=c_xmaxymax
-    #
-    #
-    #
-    entities=['face']
-    #
-    for entity in entities:
-        if len(abs_xmin) != 0:
-            refname=entity+'_abs_xmin'
-            build_block_side(abs_xmin,refname,obj=entity,id_0=1003)
-        #
-        if len(abs_ymin) != 0:
-            refname=entity+'_abs_ymin'
-            build_block_side(abs_ymin,refname,obj=entity,id_0=1004)
-        #
-        if len(abs_xmax) != 0:
-            refname=entity+'_abs_xmax'
-            build_block_side(abs_xmax,refname,obj=entity,id_0=1005)
-        #
-        if len(abs_ymax) != 0:
-            refname=entity+'_abs_ymax'
-            build_block_side(abs_ymax,refname,obj=entity,id_0=1006)
-        ##
-        refname=entity+'_topo'
-        block=3 #change here..... must be 1 @@@@@@@@@
-        ty=None
-        ty=cubit.get_block_element_type(block)
-        if ty != 'HEX8': cubit.cmd('del block '+str(block))
-        build_block_side(top_surf,refname,obj=entity,id_0=1001)
-        #
-        refname=entity+'_bottom'
-        block=4 #change here..... must be 2 @@@@@@@@
-        ty=None
-        ty=cubit.get_block_element_type(block)
-        if ty != 'HEX8': cubit.cmd('del block '+str(block))
-        build_block_side(bottom_surf,refname,obj=entity,id_0=1002)
-    #
-    #
-    return boundary
\ No newline at end of file

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/cubit2specfem3d.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/cubit2specfem3d.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/cubit2specfem3d.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,794 +0,0 @@
-#!python
-#############################################################################
-# cubit2specfem3d.py                                                           #
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-#
-#for a complete definition of the format of the mesh in SPECFEM3D check the manual (http://www.geodynamics.org/cig/software/specfem3d):
-#
-#USAGE 
-#
-#############################################################################
-#PREREQUISITE
-#The mesh must be prepared 
-#   automatically using the module boundary_definition (see boundary_definition.py for more information)
-#or 
-#   manually following the convention:
-#     - each material should have a block defined by material domain_flag (acoustic/elastic/poroelastic) name,flag of the material (integer),p velocity 
-#       (or the full description: name, flag, vp, vs, rho, Q ... if not present these last 3 parameters will be interpolated by module mat_parameter)
-#     - each mesh should have the block definition for the face on the free_surface (topography), 
-#       the name of this block must be 'face_topo' or you can change the default name in mesh.topo defined in profile.
-#     - each mesh should have the block definition for the faces on the absorbing boundaries, 
-#       one block for each surface with x=Xmin,x=Xmax,y=Ymin,y=Ymax and z=bottom. The names of the blocks should contain the strings "xmin,xmax,ymin,ymax,bottom"
-#
-#############################################################################
-#RUN
-#In a python script or in the cubit python tab call:
-#           
-#           export2SPECFEM3D(path_exporting_mesh_SPECFEM3D) 
-#
-#the module creates a python class for the mesh: ex. profile=mesh()
-#and it export the files of the mesh needed by the partitioner of SPECFEM3D
-#
-#############################################################################
-#OUTPUT
-#The default output are 11 ASCII files:
-#__________________________________________________________________________________________
-#mesh_name='mesh_file' -> the file that contains the connectity of the all mesh
-#    format:
-#        number of elements
-#        id_elements id_node1 id_node2 id_node3 id_node4 id_node5 id_node6 id_node7 id_node8
-#        .....
-#
-#__________________________________________________________________________________________        
-##nodecoord_name='nodes_coords_file' -> the file that contains the coordinates of the nodes of the all mesh
-#    format:
-#        number of nodes
-#        id_node x_coordinate y_coordinate z_coordinate
-#        .....
-#
-#__________________________________________________________________________________________        
-##material_name='materials_file' -> the file that contains the material flag of the elements
-#    format:
-#        id_element flag
-#        .....
-#
-#__________________________________________________________________________________________        
-##nummaterial_name='nummaterial_velocity_file' -> table of the material properties
-#    format:
-#        #material_domain_id #material_id #rho #vp #vs #Q_mu #anisotropy
-#        .....
-#        #material_domain_id 'tomography' file_name #for interpolation with tomography
-#        .....
-#        #material_domain_id 'interface' file_name flag_for_the_gll_below_the_interface flag_for_the_gll_above_the_interface #for interpolation with interface
-#__________________________________________________________________________________________        
-##absname='absorbing_surface_file' -> this file contains all the face in all the absorbing  boundaries
-##absname_local='absorbing_surface_file'+'_xmin' -> this file contains all the face in the absorbing  boundary defined by x=Xmin
-##absname_local='absorbing_surface_file'+'_xmax' -> this file contains all the face in the absorbing  boundary defined by x=Xmax
-##absname_local='absorbing_surface_file'+'_ymin' -> this file contains all the face in the absorbing  boundary defined by y=Ymin
-##absname_local='absorbing_surface_file'+'_ymax' -> this file contains all the face in the absorbing  boundary defined by y=Ymax
-##absname_local='absorbing_surface_file'+'_bottom' -> this file contains all the face in the absorbing  boundary defined by z=bottom
-#    format:
-#        number of faces
-#        id_(element containg the face) id_node1_face id_node2_face id_node3_face id_node4_face
-#        ....
-#
-#__________________________________________________________________________________________
-##freename='free_surface_file' -> file with the hex on the free surface (usually the topography)
-#    format:
-#        number of faces
-#        id_(element containg the face) id_node1_face id_node2_face id_node3_face id_node4_face
-#
-#__________________________________________________________________________________________
-#__________________________________________________________________________________________
-##surface='*_surface_file' -> file with the hex on any surface (define by the word 'surface' in the name of the block, ex: moho_surface)
-# optional surfaces, e.g. moho_surface
-# should be created like e.g.:
-#  > block 10 face in surface 2
-#  > block 10 name 'moho_surface'
-#
-#
-#    format:
-#        number of faces
-#        id_(element containg the face) id_node1_face id_node2_face id_node3_face id_node4_face
-#
-#__________________________________________________________________________________________
-# it is possible save only one (or more) file singularly: for example if you want only the nodecoord_file call the module mesh.nodescoord_write(full path name)
-#
-#############################################################################
-
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-
-class mtools(object):
-    def __init__(self,frequency,list_surf,list_vp):
-        super(mtools, self).__init__()
-        self.frequency = frequency
-        self.list_surf = list_surf
-        self.list_vp = list_vp
-        self.ngll=5
-        self.percent_gll=0.172
-        self.point_wavelength=5
-    def __repr__(self):
-        txt='Meshing for frequency up to '+str(self.frequency)+'Hz\n'
-        for surf,vp in zip(self.list_surf,self.list_vp):
-            txt=txt+'surface '+str(surf)+', vp ='+str(vp)+'  -> size '+str(self.freq2meshsize(vp)[0])+' -> dt '+str(self.freq2meshsize(vp)[0])+'\n' 
-        return txt
-    def freq2meshsize(self,vp):
-        velocity=vp*.5
-        self.size=(1/2.5)*velocity/self.frequency*(self.ngll-1)/self.point_wavelength
-        self.dt=.4*self.size/vp*self.percent_gll
-        return self.size,self.dt
-    def mesh_it(self):
-        for surf,vp in zip(self.list_surf,self.list_vp):
-            command = "surface "+str(surf)+" size "+str(self.freq2meshsize(vp)[0])
-            cubit.cmd(command)
-            command = "surface "+str(surf)+ 'scheme pave'
-            cubit.cmd(command)
-            command = "mesh surf "+str(surf)
-            cubit.cmd(command)
-
-class block_tools():
-    def __int__(self):
-        pass
-    def create_blocks(self,mesh_entity,list_entity=None,):
-        if mesh_entity =='surface':
-            txt=' face in surface '
-        elif mesh_entity == 'curve':
-            txt=' edge in curve '
-        elif mesh_entity == 'group':
-            txt=' face in group '
-        if list_entity:
-            if not isinstance(list_entity,list):
-                list_entity=[list_entity]
-        for entity in list_entity:
-            iblock=cubit.get_next_block_id()
-            command = "block "+str(iblock)+ txt +str(entity)
-            cubit.cmd(command)
-    def material_file(self,filename):
-        matfile=open(filename,'w')
-        material=[]
-        for record in matfile:
-            mat_name,vp_str=record.split()
-            vp=float(vp_str)
-            material.append([mat_name,vp])
-        self.material=dict(material)
-    def assign_block_material(self,id_block,mat_name,vp=None):
-        try:
-            material=self.material
-        except:
-            material=None
-        cubit.cmd('block '+str(id_block)+' attribute count 2')
-        cubit.cmd('block '+str(id_block)+'  attribute index 1 '+str(id_block))
-        if material:
-            if material.has_key(mat_name):
-                cubit.cmd('block '+str(id_block)+'  attribute index 2 '+str(material[mat_name]))
-                print 'block '+str(id_block)+' - material '+mat_name+' - vp '+str(material[mat_name])+' from database'
-        elif vp:
-            cubit.cmd('block '+str(id_block)+'  attribute index 2 '+str(vp))
-            print 'block '+str(id_block)+' - material '+mat_name+' - vp '+str(vp)
-        else:
-            print 'assignment impossible: check if '+mat_name+' is in the database or specify vp'
-
-class mesh_tools(block_tools):
-    """Tools for the mesh
-    #########
-    dt,edge_dt,freq,edge_freq=seismic_resolution(edges,velocity,bins_d=None,bins_u=None,sidelist=None,ngll=5,np=8)
-        Given the velocity of a list of edges, seismic_resolution provides the minimum Dt required for the stability condition (and the corrisponding edge).
-        Furthermore, given the number of gll point in the element (ngll) and the number of GLL point for wavelength, it provide the maximum resolved frequency.
-    #########
-    length=edge_length(edge)
-        return the length of a edge
-    #########
-    edge_min,length=edge_min_length(surface)
-        given the cubit id of a surface, it return the edge with minimun length 
-    #########
-    """
-    def __int__(self):
-        pass
-    def seismic_resolution(self,edges,velocity,bins_d=None,bins_u=None,sidelist=None):
-        """
-        dt,edge_dt,freq,edge_freq=seismic_resolution(edges,velocity,bins_d=None,bins_u=None,sidelist=None,ngll=5,np=8)
-            Given the velocity of a list of edges, seismic_resolution provides the minimum Dt required for the stability condition (and the corrisponding edge).
-            Furthermore, given the number of gll point in the element (ngll) and the number of GLL point for wavelength, it provide the maximum resolved frequency.
-        """
-        ratiostore=1e10
-        dtstore=1e10
-        edgedtstore=-1
-        edgeratiostore=-1
-        for edge in edges:
-            d=self.edge_length(edge)
-            ratio=(1/2.5)*velocity/d*(self.ngll-1)/self.point_wavelength
-            dt=.4*d/velocity*self.percent_gll
-            if dt<dtstore:
-               dtstore=dt
-               edgedtstore=edge
-            if ratio < ratiostore:
-                ratiostore=ratio
-                edgeratiostore=edge
-            try:
-                for bin_d,bin_u,side in zip(bins_d,bins_u,sidelist):
-                    if ratio >= bin_d and ratio < bin_u:
-                        command = "sideset "+str(side)+" edge "+str(edge)
-                        cubit.cmd(command)
-                        break
-            except:
-                pass
-        return dtstore,edgedtstore,ratiostore,edgeratiostore
-    def edge_length(self,edge):
-        """
-        length=edge_length(edge)
-            return the length of a edge
-        """
-        from math import sqrt
-        nodes=cubit.get_connectivity('Edge',edge)
-        x0,y0,z0=cubit.get_nodal_coordinates(nodes[0])
-        x1,y1,z1=cubit.get_nodal_coordinates(nodes[1])
-        d=sqrt((x1-x0)**2+(y1-y0)**2+(z1-z0)**2)
-        return d
-    def edge_min_length(self,surface):
-        """
-        edge_min,length=edge_min_length(surface)
-            given the cubit id of a surface, it return the edge with minimun length 
-        """
-        from math import sqrt
-        self.dmin=99999
-        edge_store=0
-        command = "group 'list_edge' add edge in surf "+str(surface)
-        command = command.replace("["," ").replace("]"," ")
-        cubit.cmd(command)
-        group=cubit.get_id_from_name("list_edge")
-        edges=cubit.get_group_edges(group)
-        command = "delete group "+ str(group)
-        cubit.cmd(command)
-        for edge in edges:
-            d=self.edge_length(edge)
-            if d<dmin:
-                self.dmin=d
-                edge_store=edge
-        self.edgemin=edge_store
-        return self.edgemin,self.dmin
-    def normal_check(self,nodes,normal):
-        tres=.2
-        p0=cubit.get_nodal_coordinates(nodes[0])
-        p1=cubit.get_nodal_coordinates(nodes[1])
-        p2=cubit.get_nodal_coordinates(nodes[2])
-        a=[p1[0]-p0[0],p1[1]-p0[1],p1[2]-p0[2]]
-        b=[p2[0]-p1[0],p2[1]-p1[1],p2[2]-p1[2]]
-        axb=[a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]
-        dot=0.0 
-        for i in (0,1,2): 
-            dot=dot+axb[i]*normal[i]
-        if  dot > 0:
-            return nodes
-        elif dot < 0:
-            return nodes[0],nodes[3],nodes[2],nodes[1]
-        else:
-            print 'error: surface normal, dot=0', axb,normal,dot,p0,p1,p2
-    def mesh_analysis(self,frequency):
-        from sets import Set
-        cubit.cmd('set info off')
-        cubit.cmd('set echo off')
-        cubit.cmd('set journal off')
-        bins_d=[0.0001]+range(0,int(frequency)+1)+[1000]
-        bins_u=bins_d[1:]
-        dt=[]
-        ed_dt=[]
-        r=[]
-        ed_r=[]
-        nstart=cubit.get_next_sideset_id()
-        command = "del sideset all"
-        cubit.cmd(command)
-        for bin_d,bin_u in zip(bins_d,bins_u):
-            nsideset=cubit.get_next_sideset_id()
-            command='create sideset '+str(nsideset)
-            cubit.cmd(command)
-            command = "sideset "+str(nsideset)+ " name "+ "'ratio-["+str(bin_d)+"_"+str(bin_u)+"['"
-            cubit.cmd(command)
-        nend=cubit.get_next_sideset_id()            
-        sidelist=range(nstart,nend)
-        for block in self.block_mat:
-            name=cubit.get_exodus_entity_name('block',block)
-            velocity=self.material[name][1]
-            if velocity > 0:
-                faces=cubit.get_block_faces(block)
-                edges=[]
-                for face in faces:
-                    es=cubit.get_sub_elements("face", face, 1)
-                    edges=edges+list(es)
-                edges=Set(edges)
-                dtstore,edgedtstore,ratiostore,edgeratiostore=self.seismic_resolution(edges,velocity,bins_d,bins_u,sidelist)
-                dt.append(dtstore)
-                ed_dt.append(edgedtstore)
-                r.append(ratiostore)
-                ed_r.append(edgeratiostore)
-        self.ddt=zip(ed_dt,dt)
-        self.dr=zip(ed_r,r)
-        def sorter(x, y):
-            return cmp(x[1],y[1])
-        self.ddt.sort(sorter)
-        self.dr.sort(sorter)
-        print self.ddt,self.dr
-        print 'Deltat minimum => edge:'+str(self.ddt[0][0])+' dt: '+str(self.ddt[0][1])
-        print 'minimum frequency resolved => edge:'+str(self.dr[0][0])+' frequency: '+str(self.dr[0][1])
-        return self.ddt[0],self.dr[0]
-
-class mesh(object,mesh_tools):
-    def __init__(self):
-        super(mesh, self).__init__()
-        self.mesh_name='mesh_file'
-        self.nodecoord_name='nodes_coords_file'
-        self.material_name='materials_file'
-        self.nummaterial_name='nummaterial_velocity_file'
-        self.absname='absorbing_surface_file'
-        self.freename='free_surface_file'
-        self.recname='STATIONS'
-        version_cubit=float(cubit.get_version())
-        if version_cubit >= 12:
-            self.face='SHELL4'
-        else:
-            self.face='QUAD4'
-        self.hex='HEX'
-        self.edge='BAR2'
-        self.topo='face_topo'
-        self.rec='receivers'
-        self.block_definition()
-        self.ngll=5
-        self.percent_gll=0.172
-        self.point_wavelength=5
-        cubit.cmd('compress all')
-    def __repr__(self):
-        pass
-    def block_definition(self):
-        block_flag=[]
-        block_mat=[]
-        block_bc=[]
-        block_bc_flag=[]
-        material={}
-        bc={}
-        blocks=cubit.get_block_id_list()
-        for block in blocks:
-            name=cubit.get_exodus_entity_name('block',block)
-            ty=cubit.get_block_element_type(block)
-            #print block,blocks,ty,self.hex,self.face
-            if self.hex in ty:
-                nattrib=cubit.get_block_attribute_count(block)
-                flag=None
-                vel=None
-                vs=None
-                rho=None
-                q=0
-                ani=0
-                # material domain id
-                if "acoustic" in name :
-                  imaterial = 1
-                elif "elastic"  in name:
-                  imaterial = 2
-                elif "poroelastic"  in name:
-                  imaterial = 3
-                else :
-                  imaterial = 0
-                #
-                if nattrib > 1:
-                    # material flag:
-                    #   positive => material properties,
-                    #   negative => interface/tomography domain
-                    flag=int(cubit.get_block_attribute_value(block,0))
-                    if flag > 0 and nattrib >= 2:
-                        vel=cubit.get_block_attribute_value(block,1)
-                        if nattrib >= 3:
-                            vs=cubit.get_block_attribute_value(block,2)
-                            if nattrib >= 4:
-                                rho=cubit.get_block_attribute_value(block,3)
-                                if nattrib >= 5:
-                                    q=cubit.get_block_attribute_value(block,4)
-                                    # for q to be valid: it must be positive
-                                    if q < 0 :
-                                      print 'error, q value invalid:', q
-                                      break                                                   
-                                    if nattrib == 6:
-                                        ani=cubit.get_block_attribute_value(block,5)
-                    elif flag < 0:
-                        vel=name
-                        attrib=cubit.get_block_attribute_value(block,1)
-                        if attrib == 1: 
-                            kind='interface'
-                            flag_down=cubit.get_block_attribute_value(block,2)
-                            flag_up=cubit.get_block_attribute_value(block,3)
-                        elif attrib == 2:
-                            kind='tomography'
-                elif  nattrib == 1:
-                    flag=cubit.get_block_attribute_value(block,0)
-                    print 'only 1 attribute ', name,block,flag
-                    vel,vs,rho,q,ani=(0,0,0,0,0)
-                else:
-                    flag=block
-                    vel,vs,rho,q,ani=(name,0,0,0,0)
-                block_flag.append(int(flag))
-                block_mat.append(block)
-                if flag > 0 and nattrib != 1:
-                    par=tuple([imaterial,flag,vel,vs,rho,q,ani])
-                elif flag < 0 and nattrib != 1:
-                    if kind=='interface':
-                        par=tuple([imaterial,flag,kind,name,flag_down,flag_up])
-                    elif kind=='tomography':
-                        par=tuple([imaterial,flag,kind,name])
-                elif flag==0 or nattrib == 1:
-                    par=tuple([imaterial,flag,name])
-                material[block]=par
-            elif ty == self.face: #Stacey condition, we need hex here for pml
-                block_bc_flag.append(4)
-                block_bc.append(block)
-                bc[block]=4 #face has connectivity = 4
-                if name == self.topo or block == 1001: topography_face=block
-            elif ty == 'SPHERE':
-                pass
-            else:
-                # block elements differ from HEX8/QUAD4/SHELL4
-                print '****************************************'
-                print 'block not properly defined:'
-                print '  name:',name
-                print '  type:',type
-                print
-                print 'please check your block definitions!'
-                print
-                print 'only supported types are:'
-                print '  HEX/HEX8  for volumes'
-                print '  QUAD4 for surface'
-                print '  SHELL4 for surface'
-                print '****************************************'
-                continue
-                return None, None,None,None,None,None,None,None
-        nsets=cubit.get_nodeset_id_list()
-        if len(nsets) == 0: self.receivers=None
-        for nset in nsets:
-            name=cubit.get_exodus_entity_name('nodeset',nset)
-            if name == self.rec:
-                self.receivers=nset
-            else:
-                print 'nodeset '+name+' not defined'
-                self.receivers=None
-        print block_mat
-        print block_flag
-        print block_bc
-        print block_bc_flag
-        print material
-        print bc
-        print topography_face
-        #
-        try:
-            self.block_mat=block_mat
-            self.block_flag=block_flag
-            self.block_bc=block_bc
-            self.block_bc_flag=block_bc_flag
-            self.material=material
-            self.bc=bc
-            self.topography=topography_face
-        except:
-            print '****************************************'
-            print 'sorry, no blocks or blocks not properly defined'
-            print block_mat
-            print block_flag
-            print block_bc
-            print block_bc_flag
-            print material
-            print bc
-            print topography
-            print '****************************************'
-    def mat_parameter(self,properties): 
-        print properties
-        #format nummaterials file: #material_domain_id #material_id #rho #vp #vs #Q_mu #anisotropy_flag
-        imaterial=properties[0]
-        flag=properties[1]
-        if flag > 0:
-            vel=properties[2]
-            if properties[2] is None and type(vel) != str:
-                if vel >= 30:
-                    m2km=1000.
-                else:
-                    m2km=1.
-                vp=vel/m2km
-                rho=(1.6612*vp-0.472*vp**2+0.0671*vp**3-0.0043*vp**4+0.000106*vp**4)*m2km
-                txt='%1i %3i %20f %20f %20f %1i %1i\n' % (properties[0],properties[1],rho,vel,vel/(3**.5),0,0)     
-            elif type(vel) != str and vel != 0.:
-                try: 
-                    q=properties[5]
-                except:
-                    q=0.
-                try:
-                    ani=properties[6]
-                except:
-                    ani=0.
-                #print properties[0],properties[3],properties[1],properties[2],q,ani
-                txt='%1i %3i %20f %20f %20f %20f %20f\n' % (properties[0],properties[1],properties[4],properties[2],properties[3],q,ani)
-            elif type(vel) != str and vel != 0.:
-                helpstring="#material_domain_id #material_id #rho #vp #vs #Q_mu #anisotropy"
-                txt='%1i %3i %s \n' % (properties[0],properties[1],helpstring)
-            else:
-                helpstring=" -->       sintax: #material_domain_id #material_id #rho #vp #vs #Q_mu #anisotropy"
-                txt='%1i %3i %s %s\n' % (properties[0],properties[1],properties[2],helpstring)
-        elif flag < 0:
-            if properties[2] == 'tomography':
-                txt='%1i %3i %s %s\n' % (properties[0],properties[1],properties[2],properties[3])
-            elif properties[2] == 'interface':
-                txt='%1i %3i %s %s %1i %1i\n' % (properties[0],properties[1],properties[2],properties[3],properties[4],properties[5])
-            else:
-                helpstring=" -->       sintax: #material_domain_id 'tomography' #file_name "
-                txt='%1i %3i %s %s \n' % (properties[0],properties[1],properties[2],helpstring)
-                #
-        return txt
-    def nummaterial_write(self,nummaterial_name):
-        print 'Writing '+nummaterial_name+'.....'
-        nummaterial=open(nummaterial_name,'w')
-        for block in self.block_mat:
-            #name=cubit.get_exodus_entity_name('block',block)
-            nummaterial.write(str(self.mat_parameter(self.material[block])))
-        nummaterial.close()
-    def mesh_write(self,mesh_name):
-        meshfile=open(mesh_name,'w')
-        print 'Writing '+mesh_name+'.....'
-        num_elems=cubit.get_hex_count()
-        print '  number of elements:',str(num_elems)
-        meshfile.write(str(num_elems)+'\n')
-        for block,flag in zip(self.block_mat,self.block_flag):
-            #print block,flag
-            hexes=cubit.get_block_hexes(block)
-            #print len(hexes)
-            for hexa in hexes:
-                #print hexa
-                nodes=cubit.get_connectivity('Hex',hexa)
-                #nodes=self.jac_check(nodes) #is it valid for 3D? TODO
-                txt=('%10i ')% hexa
-                txt=txt+('%10i %10i %10i %10i %10i %10i %10i %10i\n')% nodes[:]
-                meshfile.write(txt)
-        meshfile.close()
-    def material_write(self,mat_name):
-        mat=open(mat_name,'w')
-        print 'Writing '+mat_name+'.....'
-        for block,flag in zip(self.block_mat,self.block_flag):
-                hexes=cubit.get_block_hexes(block)
-                for hexa in hexes:
-                    mat.write(('%10i %10i\n') % (hexa,flag))
-        mat.close()
-    def nodescoord_write(self,nodecoord_name):
-        nodecoord=open(nodecoord_name,'w')
-        print 'Writing '+nodecoord_name+'.....'
-        node_list=cubit.parse_cubit_list('node','all')
-        num_nodes=len(node_list)
-        print '  number of nodes:',str(num_nodes)
-        nodecoord.write('%10i\n' % num_nodes)
-        #
-        for node in node_list:
-            x,y,z=cubit.get_nodal_coordinates(node)
-            txt=('%10i %20f %20f %20f\n') % (node,x,y,z)
-            nodecoord.write(txt)
-        nodecoord.close()
-    def free_write(self,freename=None):
-        cubit.cmd('set info off')
-        cubit.cmd('set echo off')
-        cubit.cmd('set journal off')
-        from sets import Set
-        normal=(0,0,1)
-        if not freename: freename=self.freename
-        freehex=open(freename,'w')
-        print 'Writing '+freename+'.....'
-        #
-        #
-        for block,flag in zip(self.block_bc,self.block_bc_flag):
-            if block == self.topography:
-                name=cubit.get_exodus_entity_name('block',block)
-                print '  block name:',name,'id:',block
-                quads_all=cubit.get_block_faces(block)
-                print '  number of faces = ',len(quads_all)
-                dic_quads_all=dict(zip(quads_all,quads_all))
-                freehex.write('%10i\n' % len(quads_all))
-                list_hex=cubit.parse_cubit_list('hex','all')
-                for h in list_hex:
-                    faces=cubit.get_sub_elements('hex',h,2)
-                    for f in faces:
-                        if dic_quads_all.has_key(f):
-                            #print f
-                            nodes=cubit.get_connectivity('face',f)
-                            nodes_ok=self.normal_check(nodes,normal)
-                            txt='%10i %10i %10i %10i %10i\n' % (h,nodes_ok[0],nodes_ok[1],nodes_ok[2],nodes_ok[3])
-                            freehex.write(txt)
-                freehex.close()   
-        cubit.cmd('set info on')
-        cubit.cmd('set echo on')
-    def abs_write(self,absname=None):
-        import re
-        cubit.cmd('set info off')
-        cubit.cmd('set echo off')
-        cubit.cmd('set journal off')
-        from sets import Set
-        if not absname: absname=self.absname
-        #
-        #
-        list_hex=cubit.parse_cubit_list('hex','all')
-        for block,flag in zip(self.block_bc,self.block_bc_flag):
-            if block != self.topography:
-                name=cubit.get_exodus_entity_name('block',block)
-                print '  block name:',name,'id:',block
-                cknormal=True
-                if re.search('xmin',name):
-                    print 'xmin'
-                    abshex_local=open(absname+'_xmin','w')
-                    normal=(-1,0,0)
-                elif re.search('xmax',name):
-                    print "xmax"
-                    abshex_local=open(absname+'_xmax','w')
-                    normal=(1,0,0)
-                elif re.search('ymin',name):
-                    print "ymin"
-                    abshex_local=open(absname+'_ymin','w')
-                    normal=(0,-1,0)
-                elif re.search('ymax',name):
-                    print "ymax"
-                    abshex_local=open(absname+'_ymax','w')
-                    normal=(0,1,0)
-                elif re.search('bottom',name):
-                    print "bottom"
-                    abshex_local=open(absname+'_bottom','w')
-                    normal=(0,0,-1)
-                elif re.search('abs',name):
-                    print "abs all - no implemented yet"
-                    cknormal=False
-                    abshex_local=open(absname,'w')
-                else:
-                    if block == 1003:
-                        print 'xmin'
-                        abshex_local=open(absname+'_xmin','w')
-                        normal=(-1,0,0)
-                    elif block == 1004:
-                        print "ymin"
-                        abshex_local=open(absname+'_ymin','w')
-                        normal=(0,-1,0)
-                    elif block == 1005:
-                        print "xmax"
-                        abshex_local=open(absname+'_xmax','w')
-                        normal=(1,0,0)
-                    elif block == 1006:
-                        print "ymax"
-                        abshex_local=open(absname+'_ymax','w')
-                        normal=(0,1,0)
-                    elif block == 1002:
-                        print "bottom"
-                        abshex_local=open(absname+'_bottom','w')
-                        normal=(0,0,-1)
-                #
-                #
-                quads_all=cubit.get_block_faces(block)
-                dic_quads_all=dict(zip(quads_all,quads_all))
-                print '  number of faces = ',len(quads_all)
-                abshex_local.write('%10i\n' % len(quads_all))
-                #command = "group 'list_hex' add hex in face "+str(quads_all)
-                #command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
-                #cubit.cmd(command)
-                #group=cubit.get_id_from_name("list_hex")
-                #list_hex=cubit.get_group_hexes(group)
-                #command = "delete group "+ str(group)
-                #cubit.cmd(command)
-                for h in list_hex:
-                    faces=cubit.get_sub_elements('hex',h,2)
-                    for f in faces:
-                        if dic_quads_all.has_key(f):
-                            nodes=cubit.get_connectivity('face',f)
-                            if cknormal:
-                                nodes_ok=self.normal_check(nodes,normal)
-                            else:
-                                nodes_ok=nodes
-                            txt='%10i %10i %10i %10i %10i\n' % (h,nodes_ok[0],nodes_ok[1],nodes_ok[2],nodes_ok[3])
-                            abshex_local.write(txt)
-                abshex_local.close()   
-        cubit.cmd('set info on')
-        cubit.cmd('set echo on')
-    def surface_write(self,pathdir=None):
-        # optional surfaces, e.g. moho_surface
-        # should be created like e.g.:
-        #  > block 10 face in surface 2
-        #  > block 10 name 'moho_surface'
-        import re
-        from sets import Set
-        for block in self.block_bc :
-            if block != self.topography:
-                name=cubit.get_exodus_entity_name('block',block)
-                # skips block names like face_abs**, face_topo**
-                if re.search('abs',name):
-                  continue
-                elif re.search('topo',name):
-                  continue
-                elif re.search('surface',name):
-                  filename=pathdir+name+'_file'
-                else:
-                  continue
-                # gets face elements
-                print '  surface block name: ',name,'id: ',block
-                quads_all=cubit.get_block_faces(block)
-                print '  face = ',len(quads_all)
-                if len(quads_all) == 0 :
-                  continue
-                # writes out surface infos to file
-                print 'Writing '+filename+'.....'
-                surfhex_local=open(filename,'w')
-                dic_quads_all=dict(zip(quads_all,quads_all))
-                # writes number of surface elements
-                surfhex_local.write('%10i\n' % len(quads_all))
-                # writes out element node ids
-                list_hex=cubit.parse_cubit_list('hex','all')
-                for h in list_hex:
-                    faces=cubit.get_sub_elements('hex',h,2)
-                    for f in faces:
-                        if dic_quads_all.has_key(f):
-                            nodes=cubit.get_connectivity('face',f)
-                            txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\
-                                             nodes[1],nodes[2],nodes[3])
-                            surfhex_local.write(txt)
-                # closes file
-                surfhex_local.close()
-    def rec_write(self,recname):
-        print 'Writing '+self.recname+'.....'
-        recfile=open(self.recname,'w')
-        nodes=cubit.get_nodeset_nodes(self.receivers)
-        for i,n in enumerate(nodes):
-            x,y,z=cubit.get_nodal_coordinates(n)
-            recfile.write('ST%i XX %20f %20f 0.0 0.0 \n' % (i,x,z))
-        recfile.close()
-    def write(self,path=''):
-        cubit.cmd('set info off')
-        cubit.cmd('set echo off')
-        cubit.cmd('set journal off')
-        cubit.cmd('compress all')
-        if len(path) != 0:
-            if path[-1] != '/': path=path+'/'
-        self.mesh_write(path+self.mesh_name)
-        self.material_write(path+self.material_name)
-        self.nodescoord_write(path+self.nodecoord_name)
-        self.free_write(path+self.freename)
-        self.abs_write(path+self.absname)
-        self.nummaterial_write(path+self.nummaterial_name)
-        # any other surfaces: ***surface***
-        self.surface_write(path)
-        if self.receivers: self.rec_write(path+self.recname)
-        cubit.cmd('set info on')
-        cubit.cmd('set echo on')
-
-def export2SPECFEM3D(path_exporting_mesh_SPECFEM3D='.'):
-    sem_mesh=mesh()
-    #sem_mesh.block_definition()
-    #print sem_mesh.block_mat
-    #print sem_mesh.block_flag
-    #
-    sem_mesh.write(path=path_exporting_mesh_SPECFEM3D)
-    print 'END SPECFEM3D exporting process......'
-    
-
-
-if __name__ == '__main__':
-    path='.'
-    export2SPECFEM3D(path)

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.pdf
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.pdf
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.pdfsync
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.pdfsync	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.pdfsync	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,1788 @@
+geocubit_manual
+version 1
+(nameref.sty
+(refcount.sty
+)
+(gettitlestring.sty
+(gettitlestring.cfg
+)
+)
+)
+(.geocubit_manual.out
+)
+(.geocubit_manual.out
+)
+l 0 41
+l 1 41
+l 2 41
+l 3 41
+l 4 41
+l 5 41
+l 6 41
+l 7 41
+l 8 41
+l 9 41
+l 10 41
+l 11 41
+l 12 41
+l 13 41
+l 14 41
+l 15 42
+l 16 42
+l 17 42
+l 18 42
+l 19 42
+l 20 42
+l 21 2
+l 22 2
+l 23 2
+l 24 3
+l 25 3
+l 26 3
+l 27 4
+l 28 4
+l 29 4
+l 30 4
+l 31 4
+l 32 4
+l 33 4
+l 34 5
+l 35 5
+l 36 5
+l 37 5
+l 38 5
+l 39 5
+l 40 5
+l 41 6
+l 42 6
+l 43 6
+l 44 7
+l 45 7
+l 46 7
+l 47 7
+l 48 7
+l 49 7
+l 50 7
+l 51 8
+l 52 8
+l 53 8
+l 54 8
+l 55 8
+l 56 8
+l 57 8
+l 58 9
+l 59 9
+l 60 9
+l 61 9
+l 62 9
+l 63 9
+l 64 9
+l 65 10
+l 66 10
+l 67 10
+l 68 10
+l 69 10
+l 70 10
+l 71 10
+l 72 11
+l 73 11
+l 74 11
+l 75 12
+l 76 12
+l 77 12
+l 78 13
+l 79 13
+l 80 13
+l 81 13
+l 82 13
+l 83 13
+l 84 13
+l 85 14
+l 86 14
+l 87 14
+l 88 14
+l 89 14
+l 90 14
+l 91 14
+l 92 15
+l 93 15
+l 94 15
+l 95 15
+l 96 15
+l 97 15
+l 98 15
+l 99 16
+l 100 16
+l 101 16
+l 102 16
+l 103 16
+l 104 16
+l 105 16
+l 106 17
+l 107 17
+l 108 17
+l 109 17
+l 110 17
+l 111 17
+l 112 17
+l 113 18
+l 114 18
+l 115 18
+l 116 18
+l 117 18
+l 118 18
+l 119 18
+l 120 19
+l 121 19
+l 122 19
+l 123 19
+l 124 19
+l 125 19
+l 126 19
+l 127 20
+l 128 20
+l 129 20
+l 130 20
+l 131 20
+l 132 20
+l 133 20
+l 134 21
+l 135 21
+l 136 21
+l 137 22
+l 138 22
+l 139 22
+l 140 43
+l 141 43
+l 142 43
+l 143 43
+l 144 43
+l 145 43
+l 146 43
+l 147 43
+l 148 43
+l 149 43
+l 150 43
+l 151 43
+l 152 43
+l 153 43
+s 1
+p 153 4736286 50644704
+p 149 4736286 50644704
+p 150 4736286 50644704
+p 151 4736286 49530837
+p 141 4736286 50644704
+p 143 4736286 49465056
+p 144 4736286 49465056
+p 145 4736286 48678624
+p 140 4736286 47040224
+p 5 12334523 43450440
+p 2 12334523 43450440
+p 3 11975713 43450440
+p 1 11975713 43450440
+p 7 15755887 41462614
+p 8 15755887 41462614
+p 9 15755887 41462614
+p 11 15755887 42104864
+p 10 15755887 41462614
+p 12 16149103 41462614
+p 14 16450632 39857776
+p 17 4736286 36810553
+p 16 4736286 36810553
+p 18 4736286 36810553
+p 19 4736286 36810553
+p 20 4736286 37990201
+p 21 5806608 35205715
+p 22 4736286 35205715
+p 23 32956737 35205715
+p 24 5806608 33600877
+p 25 4736286 33600877
+p 26 32956737 33600877
+p 27 7447770 32709587
+p 29 5806608 32709587
+p 33 33121485 32709587
+p 34 7447770 31818297
+p 36 5806608 31818297
+p 40 33121485 31818297
+p 41 5806608 30213459
+p 42 4736286 30213459
+p 43 32956737 30213459
+p 44 7447770 29322169
+p 46 5806608 29322169
+p 50 33121485 29322169
+p 51 7447770 28430879
+p 53 5806608 28430879
+p 57 33121485 28430879
+p 58 7447770 27539589
+p 60 5806608 27539589
+p 64 33121485 27539589
+p 65 7447770 26648299
+p 67 5806608 26648299
+p 71 33121485 26648299
+p 72 5806608 25043461
+p 73 4736286 25043461
+p 74 32956737 25043461
+p 75 5806608 23438623
+p 76 4736286 23438623
+p 77 32956737 23438623
+p 78 7447770 22547333
+p 80 5806608 22547333
+p 84 33121485 22547333
+p 85 7447770 21656043
+p 87 5806608 21656043
+p 91 33121485 21656043
+p 92 7447770 20764753
+p 94 5806608 20764753
+p 98 33121485 20764753
+p 99 7447770 19873463
+p 101 5806608 19873463
+p 105 33121485 19873463
+p 106 7447770 18982173
+p 108 5806608 18982173
+p 112 33121485 18982173
+p 113 7447770 18090883
+p 115 5806608 18090883
+p 119 33121485 18090883
+p 120 7447770 17199593
+p 122 5806608 17199593
+p 126 33121485 17199593
+p 127 7447770 16308303
+p 129 5806608 16308303
+p 133 33121485 16308303
+p 134 5806608 14703465
+p 135 4736286 14703465
+p 136 32956737 14703465
+p 137 5806608 13098627
+p 138 4736286 13098627
+p 139 32956737 11316047
+p 147 4736286 6027778
+p 148 4736286 6027778
+l 154 45
+l 155 45
+l 156 45
+l 157 47
+l 158 52
+l 159 52
+(omscmr.fd
+)
+l 160 52
+l 161 52
+l 162 52
+l 163 53
+l 164 53
+l 165 53
+l 166 53
+l 167 53
+l 168 54
+l 169 54
+l 170 54
+l 171 54
+l 172 54
+l 173 56
+l 174 56
+l 175 56
+l 176 56
+l 177 56
+l 178 60
+l 179 64
+l 180 64
+l 181 64
+l 182 64
+l 183 64
+l 184 64
+l 185 64
+l 186 64
+l 187 64
+l 188 64
+l 189 64
+l 190 64
+l 191 64
+s 2
+p 191 4736286 6027778
+p 188 4736286 50644704
+p 189 4736286 50644704
+p 190 4736286 49530837
+p 180 4736286 50644704
+p 182 4736286 49465056
+p 183 4736286 49465056
+p 184 4736286 48678624
+p 179 4736286 47040224
+p 156 4736286 46319328
+p 155 4736286 46319328
+p 157 4736286 44717572
+p 162 6530338 39474690
+p 160 6530338 39474690
+p 161 4736286 39474690
+p 158 4736286 39474690
+p 159 6171528 39474690
+p 167 6530338 37993576
+p 165 6530338 37993576
+p 166 4736286 37993576
+p 163 4736286 37993576
+p 164 6171528 37993576
+p 172 6530338 36512462
+p 170 6530338 36512462
+p 171 4736286 36512462
+p 168 4736286 36512462
+p 169 6171528 36512462
+p 177 6530338 34140058
+p 175 6530338 34140058
+p 176 4736286 34140058
+p 173 4736286 34140058
+p 174 6171528 34140058
+p 178 4736286 30679756
+p 186 4736286 6027778
+p 187 4736286 6027778
+l 192 65
+l 193 65
+l 194 65
+l 195 68
+l 196 68
+l 197 68
+l 198 70
+l 199 73
+l 200 73
+l 201 73
+l 202 73
+l 203 73
+l 204 74
+l 205 74
+l 206 74
+l 207 74
+l 208 74
+l 209 75
+l 210 75
+l 211 75
+l 212 75
+l 213 75
+l 214 78
+l 215 80
+l 216 80
+l 217 80
+l 218 80
+l 219 80
+l 220 83
+l 221 83
+l 222 83
+l 223 85
+(t1cmtt.fd
+)
+l 224 86
+l 225 86
+l 226 86
+l 227 87
+l 228 90
+l 229 92
+l 230 92
+l 231 92
+l 232 93
+l 233 94
+l 234 95
+l 235 96
+l 236 97
+l 237 101
+l 238 101
+l 239 101
+l 240 101
+l 241 101
+l 242 101
+l 243 101
+l 244 101
+l 245 101
+l 246 101
+l 247 101
+l 248 101
+l 249 101
+s 3
+p 249 4736286 6027778
+p 246 4736286 50644704
+p 247 4736286 50644704
+p 248 4736286 49530837
+p 238 4736286 50644704
+p 240 4736286 49465056
+p 241 4736286 49465056
+p 242 4736286 48678624
+p 237 4736286 47040224
+p 194 4736286 46319328
+p 193 4736286 46319328
+p 197 4736286 44691358
+p 196 4736286 44691358
+p 198 4736286 43336721
+p 203 6530338 41658999
+p 201 6530338 41658999
+p 202 4736286 41658999
+p 199 4736286 41658999
+p 200 6171528 41658999
+p 208 6530338 40177885
+p 206 6530338 40177885
+p 207 4736286 40177885
+p 204 4736286 40177885
+p 205 6171528 40177885
+p 213 6530338 38696771
+p 211 6530338 38696771
+p 212 4736286 38696771
+p 209 4736286 38696771
+p 210 6171528 38696771
+p 214 4736286 37019049
+p 219 6530338 35537935
+p 217 6530338 35537935
+p 218 4736286 35537935
+p 215 4736286 35537935
+p 216 6171528 35537935
+p 222 4736286 33616513
+p 221 4736286 33616513
+p 223 4736286 32261876
+p 227 6530338 30584154
+p 225 6530338 30584154
+p 226 4736286 30584154
+p 224 4736286 30584154
+p 228 4736286 28906432
+p 232 6530338 27228710
+p 230 6530338 27228710
+p 231 4736286 27228710
+p 229 4736286 27228710
+p 233 6530338 26337420
+p 234 6530338 25446130
+p 235 6530338 24554840
+p 236 6530338 23663550
+p 244 4736286 6027778
+p 245 4736286 6027778
+l 250 102
+l 251 102
+l 252 102
+l 253 104
+l 254 104
+l 255 104
+l 256 106
+l 257 106
+l 258 106
+l 259 106
+l 260 106
+l 261 107
+l 262 107
+l 263 107
+l 264 108
+l 265 111
+l 266 111
+l 267 111
+l 268 111
+l 269 111
+l 270 112
+l 271 112
+l 272 112
+l 273 113
+l 274 117
+l 275 117
+l 276 117
+l 277 118
+l 278 121
+l 279 121
+l 280 121
+l 281 121
+l 282 121
+l 283 122
+l 284 122
+l 285 122
+l 286 123
+l 287 128
+l 288 128
+l 289 128
+l 290 128
+l 291 128
+l 292 129
+l 293 129
+l 294 129
+l 295 130
+l 296 134
+l 297 136
+l 298 136
+l 299 136
+l 300 136
+l 301 136
+l 302 137
+l 303 137
+l 304 137
+l 305 138
+l 306 143
+l 307 143
+l 308 143
+l 309 143
+l 310 143
+l 311 144
+l 312 144
+l 313 144
+l 314 145
+l 315 149
+l 316 149
+l 317 149
+l 318 149
+l 319 149
+l 320 149
+l 321 149
+l 322 151
+l 323 151
+l 324 151
+l 325 151
+l 326 151
+l 327 151
+l 328 151
+l 329 151
+l 330 151
+l 331 151
+l 332 151
+l 333 151
+l 334 151
+l 335 151
+l 336 152
+l 337 152
+l 338 153
+l 339 153
+l 340 153
+l 341 153
+l 342 153
+l 343 153
+l 344 153
+l 345 153
+l 346 153
+l 347 153
+l 348 153
+l 349 153
+l 350 153
+l 351 154
+l 352 154
+l 353 154
+l 354 154
+l 355 154
+l 356 154
+l 357 154
+l 358 157
+l 359 157
+l 360 157
+l 361 159
+l 362 162
+l 363 162
+l 364 162
+l 365 164
+l 366 164
+l 367 164
+l 368 164
+l 369 164
+l 370 165
+l 371 165
+l 372 165
+l 373 166
+l 374 171
+l 375 171
+l 376 171
+l 377 171
+l 378 171
+l 379 172
+l 380 172
+l 381 172
+l 382 173
+l 383 175
+l 384 175
+l 385 179
+l 386 179
+l 387 179
+l 388 179
+l 389 179
+l 390 180
+l 391 180
+l 392 180
+l 393 181
+l 394 182
+l 395 182
+l 396 182
+l 397 182
+l 398 182
+l 399 182
+l 400 182
+l 401 182
+l 402 182
+l 403 182
+l 404 182
+l 405 182
+l 406 182
+s 4
+p 406 4736286 6027778
+p 403 4736286 50644704
+p 404 4736286 50644704
+p 405 4736286 49530837
+p 395 4736286 50644704
+p 397 4736286 49465056
+p 398 4736286 49465056
+p 399 4736286 48678624
+p 394 4736286 47040224
+p 360 4736286 46319328
+p 358 4736286 46319328
+p 252 4736286 45598432
+p 251 4736286 45598432
+p 255 4736286 43970462
+p 254 4736286 43970462
+p 260 6530338 42615825
+p 258 6530338 42615825
+p 259 4736286 42615825
+p 256 4736286 42615825
+p 257 6171528 42615825
+p 264 8109102 40938103
+p 262 8109102 40938103
+p 263 6530338 40938103
+p 261 6530338 40938103
+p 269 6530338 39260381
+p 267 6530338 39260381
+p 268 4736286 39260381
+p 265 4736286 39260381
+p 266 6171528 39260381
+p 273 8109102 37582659
+p 271 8109102 37582659
+p 272 6530338 37582659
+p 270 6530338 37582659
+p 276 4736286 35661237
+p 275 4736286 35661237
+p 277 4736286 34306600
+p 282 6530338 32628878
+p 280 6530338 32628878
+p 281 4736286 32628878
+p 278 4736286 32628878
+p 279 6171528 32628878
+p 286 8109102 30951156
+p 284 8109102 30951156
+p 285 6530338 30951156
+p 283 6530338 30951156
+p 291 6530338 29273434
+p 289 6530338 29273434
+p 290 4736286 29273434
+p 287 4736286 29273434
+p 288 6171528 29273434
+p 295 8109102 27595712
+p 293 8109102 27595712
+p 294 6530338 27595712
+p 292 6530338 27595712
+p 296 4736286 25917990
+p 301 6530338 24436876
+p 299 6530338 24436876
+p 300 4736286 24436876
+p 297 4736286 24436876
+p 298 6171528 24436876
+p 305 8109102 22759154
+p 303 8109102 22759154
+p 304 6530338 22759154
+p 302 6530338 22759154
+p 310 6530338 21081432
+p 308 6530338 21081432
+p 309 4736286 21081432
+p 306 4736286 21081432
+p 307 6171528 21081432
+p 314 8109102 19403710
+p 312 8109102 19403710
+p 313 6530338 19403710
+p 311 6530338 19403710
+p 361 6530338 17725988
+p 364 4736286 14913276
+p 363 4736286 14913276
+p 369 6530338 13558639
+p 367 6530338 13558639
+p 368 4736286 13558639
+p 365 4736286 13558639
+p 366 6171528 13558639
+p 373 8109102 11880917
+p 371 8109102 11880917
+p 372 6530338 11880917
+p 370 6530338 11880917
+p 378 6530338 10203195
+p 376 6530338 10203195
+p 377 4736286 10203195
+p 374 4736286 10203195
+p 375 6171528 10203195
+p 382 8109102 8525473
+p 380 8109102 8525473
+p 381 6530338 8525473
+p 379 6530338 8525473
+p 401 4736286 6027778
+p 402 4736286 6027778
+l 407 185
+l 408 185
+l 409 185
+l 410 187
+l 411 190
+l 412 190
+l 413 190
+l 414 190
+l 415 190
+l 416 191
+l 417 191
+l 418 191
+l 419 192
+l 420 194
+l 421 195
+l 422 197
+l 423 197
+l 424 197
+l 425 197
+l 426 197
+l 427 198
+l 428 198
+l 429 198
+l 430 199
+l 431 201
+l 432 201
+l 433 205
+l 434 205
+l 435 205
+l 436 205
+l 437 205
+l 438 205
+l 439 205
+l 440 206
+l 441 206
+l 442 206
+l 443 206
+l 444 206
+l 445 206
+l 446 206
+l 447 206
+l 448 207
+l 449 207
+l 450 207
+l 451 207
+l 452 207
+l 453 207
+l 454 207
+l 455 208
+l 456 208
+l 457 208
+l 458 208
+l 459 208
+l 460 211
+l 461 211
+l 462 211
+l 463 211
+l 464 211
+l 465 211
+l 466 211
+l 467 211
+l 468 211
+l 469 211
+l 470 211
+l 471 211
+l 472 211
+l 473 211
+l 474 211
+l 475 211
+l 476 211
+l 477 211
+l 478 211
+s 5
+p 478 4736286 6027778
+p 475 4736286 50644704
+p 476 4736286 50644704
+p 477 4736286 49530837
+p 467 4736286 50644704
+p 469 4736286 49465056
+p 470 4736286 49465056
+p 471 4736286 48678624
+p 466 4736286 47040224
+p 465 4736286 47040224
+p 464 4736286 47040224
+p 315 4736286 47040224
+p 316 4736286 47040224
+p 322 8574223 38128105
+p 320 8574223 38128105
+p 321 8215413 38128105
+p 319 8215413 38128105
+p 331 8574223 45791660
+p 332 8574223 45791660
+p 323 8574223 38128105
+p 324 8574223 38128105
+p 326 8574223 38128105
+p 327 8574223 38128105
+p 329 8574223 38128105
+p 330 8574223 38128105
+p 328 8574223 38128105
+p 335 8574223 37236815
+p 333 12612061 37236815
+p 336 17659778 38128105
+p 337 17659778 39019395
+p 346 17659778 47040224
+p 347 17659778 47040224
+p 338 17659778 38128105
+p 339 17659778 38128105
+p 341 17659778 38128105
+p 342 17659778 38128105
+p 344 17659778 38128105
+p 345 17659778 38128105
+p 343 17659778 38128105
+p 350 17659778 37236815
+p 348 23502889 37236815
+p 355 4736286 35502730
+p 356 8022359 35502730
+p 357 8022359 36394020
+p 462 4736286 31720892
+p 460 4736286 31720892
+p 384 6530338 30999996
+p 389 6530338 29482571
+p 387 6530338 29482571
+p 388 4736286 29482571
+p 385 4736286 29482571
+p 386 6171528 29482571
+p 393 8109102 27884998
+p 391 8109102 27884998
+p 392 6530338 27884998
+p 390 6530338 27884998
+p 409 4736286 25097470
+p 408 4736286 25097470
+p 410 4736286 23742833
+p 415 6530338 21504010
+p 413 6530338 21504010
+p 414 4736286 21504010
+p 411 4736286 21504010
+p 412 6171528 21504010
+p 419 8109102 19015147
+p 417 8109102 19015147
+p 418 6530338 19015147
+p 416 6530338 19015147
+p 420 6530338 16526284
+p 421 6530338 14743704
+p 426 6530338 11533442
+p 424 6530338 11533442
+p 425 4736286 11533442
+p 422 4736286 11533442
+p 423 6171528 11533442
+p 430 8109102 9044579
+p 428 8109102 9044579
+p 429 6530338 9044579
+p 427 6530338 9044579
+p 473 4736286 6027778
+p 474 4736286 6027778
+l 479 214
+l 480 214
+l 481 214
+l 482 214
+l 483 214
+l 484 215
+l 485 215
+l 486 215
+l 487 216
+l 488 218
+l 489 218
+l 490 221
+l 491 221
+l 492 221
+l 493 221
+l 494 221
+l 495 221
+l 496 221
+l 497 221
+l 498 221
+l 499 221
+l 500 221
+l 501 221
+l 502 221
+l 503 221
+l 504 221
+l 505 221
+s 6
+p 505 4736286 6027778
+p 502 4736286 50644704
+p 503 4736286 50644704
+p 504 4736286 49530837
+p 494 4736286 50644704
+p 496 4736286 49465056
+p 497 4736286 49465056
+p 498 4736286 48678624
+p 493 4736286 47040224
+p 492 4736286 47040224
+p 491 4736286 47040224
+p 433 4736286 47040224
+p 434 4736286 47040224
+p 440 8695633 32629812
+p 438 8695633 32629812
+p 439 8336823 32629812
+p 437 8336823 32629812
+p 441 8695633 32629812
+p 443 8695633 32629812
+p 444 8695633 32629812
+p 446 8695633 32629812
+p 447 8695633 32629812
+p 445 8695633 32629812
+p 448 18528536 32629812
+p 450 18528536 32629812
+p 451 18528536 32629812
+p 453 18528536 32629812
+p 454 18528536 32629812
+p 452 18528536 32629812
+p 459 4736286 31083162
+p 456 17920895 31083162
+p 457 21042878 31083162
+p 458 21042878 31974452
+p 432 6530338 28912044
+p 483 6530338 26644498
+p 481 6530338 26644498
+p 482 4736286 26644498
+p 479 4736286 26644498
+p 480 6171528 26644498
+p 487 8109102 24966776
+p 485 8109102 24966776
+p 486 6530338 24966776
+p 484 6530338 24966776
+p 489 6530338 21676868
+p 500 4736286 6027778
+p 501 4736286 6027778
+l 506 222
+l 507 222
+l 508 222
+l 509 223
+l 510 225
+l 511 225
+l 512 225
+l 513 226
+l 514 226
+l 515 226
+l 516 229
+l 517 229
+l 518 229
+l 519 230
+l 520 230
+l 521 230
+l 522 231
+l 523 232
+l 524 235
+l 525 235
+l 526 235
+l 527 236
+l 528 236
+l 529 236
+l 530 237
+l 531 237
+l 532 237
+l 533 238
+l 534 238
+l 535 238
+l 536 239
+l 537 239
+l 538 239
+l 539 240
+l 540 240
+l 541 240
+l 542 242
+l 543 245
+l 544 245
+l 545 245
+l 546 246
+l 547 248
+l 548 248
+l 549 248
+l 550 250
+l 551 253
+l 552 255
+l 553 255
+l 554 255
+l 555 256
+l 556 257
+l 557 257
+l 558 257
+l 559 258
+l 560 258
+l 561 258
+l 562 259
+l 563 259
+l 564 259
+l 565 260
+l 566 260
+l 567 260
+l 568 261
+l 569 261
+l 570 261
+l 571 262
+l 572 262
+l 573 262
+l 574 263
+l 575 263
+l 576 263
+l 577 264
+l 578 264
+l 579 264
+l 580 265
+l 581 265
+l 582 265
+l 583 267
+l 584 267
+l 585 267
+l 586 268
+l 587 269
+l 588 269
+l 589 269
+l 590 273
+l 591 273
+l 592 273
+l 593 274
+l 594 274
+l 595 274
+l 596 274
+l 597 274
+l 598 274
+l 599 274
+l 600 274
+l 601 274
+l 602 274
+l 603 274
+l 604 274
+l 605 274
+s 7
+p 605 4736286 6027778
+p 602 4736286 50644704
+p 603 4736286 50644704
+p 604 4736286 49530837
+p 594 4736286 50644704
+p 596 4736286 49465056
+p 597 4736286 49465056
+p 598 4736286 48678624
+p 593 4736286 47040224
+p 508 4736286 46319328
+p 507 4736286 46319328
+p 509 4736286 44717572
+p 513 6530338 43039850
+p 511 6530338 43039850
+p 512 4736286 43039850
+p 510 4736286 43039850
+p 514 12463570 43039850
+p 519 6530338 41362128
+p 517 6530338 41362128
+p 518 4736286 41362128
+p 516 4736286 41362128
+p 520 18767629 41362128
+p 522 6530338 40470838
+p 523 6530338 39579548
+p 527 6530338 37901826
+p 525 6530338 37901826
+p 526 4736286 37901826
+p 524 4736286 37901826
+p 528 13576051 37901826
+p 530 6530338 37010536
+p 531 13946878 37010536
+p 536 6530338 35332814
+p 534 6530338 35332814
+p 535 4736286 35332814
+p 533 4736286 35332814
+p 537 13946878 35332814
+p 539 6530338 34441524
+p 540 19509283 34441524
+p 542 4736286 31872512
+p 545 4736286 29611721
+p 544 4736286 29611721
+p 546 4736286 28009965
+p 549 4736286 25197253
+p 548 4736286 25197253
+p 550 4736286 23842616
+p 551 4736286 22060036
+p 555 6530338 19491024
+p 553 6530338 19491024
+p 554 4736286 19491024
+p 552 4736286 19491024
+p 556 6530338 18599734
+p 557 12092743 18599734
+p 559 6530338 17708444
+p 560 11721916 17708444
+p 562 6530338 16817154
+p 563 12092743 16817154
+p 565 6530338 15925864
+p 566 11721916 15925864
+p 568 6530338 15034574
+p 569 12463570 15034574
+p 571 6530338 14143284
+p 572 13205224 14143284
+p 574 6530338 13251994
+p 575 16542667 13251994
+p 577 6530338 12360704
+p 578 16542667 12360704
+p 580 6530338 11469414
+p 581 16171840 11469414
+p 600 4736286 6027778
+p 601 4736286 6027778
+l 606 275
+l 607 275
+l 608 275
+l 609 276
+l 610 276
+l 611 276
+l 612 276
+l 613 277
+l 614 278
+l 615 278
+l 616 278
+l 617 280
+l 618 280
+l 619 280
+l 620 281
+l 621 282
+l 622 282
+l 623 284
+l 624 284
+l 625 284
+l 626 285
+l 627 286
+l 628 286
+l 629 286
+l 630 287
+l 631 287
+l 632 287
+l 633 288
+l 634 288
+l 635 288
+l 636 289
+l 637 289
+l 638 289
+l 639 290
+l 640 291
+l 641 291
+l 642 291
+l 643 294
+l 644 294
+l 645 294
+l 646 295
+l 647 295
+l 648 295
+l 649 296
+l 650 296
+l 651 297
+l 652 297
+l 653 297
+l 654 298
+l 655 298
+l 656 298
+l 657 299
+l 658 299
+l 659 299
+l 660 300
+l 661 303
+l 662 303
+l 663 303
+l 664 303
+l 665 303
+l 666 303
+l 667 303
+l 668 305
+l 669 305
+l 670 305
+l 671 305
+l 672 305
+l 673 305
+l 674 305
+l 675 305
+l 676 305
+l 677 305
+l 678 305
+l 679 305
+l 680 305
+l 681 305
+l 682 306
+l 683 306
+l 684 307
+l 685 307
+l 686 307
+l 687 307
+l 688 307
+l 689 307
+l 690 307
+l 691 307
+l 692 307
+l 693 307
+l 694 307
+l 695 307
+l 696 307
+l 697 308
+l 698 308
+l 699 309
+l 700 309
+l 701 309
+l 702 309
+l 703 309
+l 704 309
+l 705 309
+l 706 309
+l 707 309
+l 708 309
+l 709 309
+l 710 309
+l 711 309
+l 712 310
+l 713 310
+l 714 310
+l 715 310
+l 716 310
+l 717 310
+l 718 310
+l 719 313
+l 720 313
+l 721 313
+l 722 316
+l 723 316
+l 724 316
+l 725 317
+l 726 317
+l 727 317
+l 728 317
+l 729 318
+l 730 319
+l 731 321
+l 732 321
+l 733 321
+l 734 321
+l 735 321
+l 736 321
+l 737 321
+l 738 322
+l 739 322
+l 740 322
+l 741 322
+l 742 322
+l 743 322
+l 744 322
+l 745 322
+l 746 323
+l 747 323
+l 748 323
+l 749 323
+l 750 323
+l 751 323
+l 752 323
+l 753 324
+l 754 324
+l 755 324
+l 756 324
+l 757 324
+l 758 328
+l 759 328
+l 760 328
+l 761 332
+l 762 332
+l 763 332
+l 764 333
+l 765 334
+l 766 334
+l 767 334
+l 768 334
+l 769 334
+l 770 334
+l 771 334
+l 772 334
+l 773 334
+l 774 334
+l 775 334
+l 776 334
+l 777 334
+s 8
+p 777 4736286 6027778
+p 774 4736286 50644704
+p 775 4736286 50644704
+p 776 4736286 49530837
+p 766 4736286 50644704
+p 768 4736286 49465056
+p 769 4736286 49465056
+p 770 4736286 48678624
+p 765 4736286 47040224
+p 760 4736286 46319328
+p 758 4736286 46319328
+p 721 4736286 45598432
+p 719 4736286 45598432
+p 586 6530338 44877536
+p 584 6530338 44877536
+p 585 4736286 44877536
+p 583 4736286 44877536
+p 587 6530338 43986246
+p 588 10238608 43986246
+p 591 4736286 42540090
+p 608 4736286 40655049
+p 607 4736286 40655049
+p 610 4736286 39300412
+p 613 4736286 38409122
+p 614 4736286 37517832
+p 620 6530338 35180385
+p 618 6530338 35180385
+p 619 4736286 35180385
+p 617 4736286 35180385
+p 621 17655148 35180385
+p 626 6530338 33734229
+p 624 6530338 33734229
+p 625 4736286 33734229
+p 623 4736286 33734229
+p 627 6530338 32842939
+p 628 18396802 32842939
+p 630 6530338 31951649
+p 631 12092743 31951649
+p 633 6530338 28386489
+p 634 12092743 28386489
+p 636 6530338 27495199
+p 637 12092743 27495199
+p 639 6530338 25712619
+p 640 6530338 24821329
+p 641 9867781 24821329
+p 646 6530338 22483882
+p 644 6530338 22483882
+p 645 4736286 22483882
+p 643 4736286 22483882
+p 647 14688532 22483882
+p 649 19138456 21592592
+p 651 6530338 20701302
+p 652 15059359 20701302
+p 654 6530338 17136142
+p 655 12092743 17136142
+p 657 6530338 16244852
+p 658 8384473 16244852
+p 660 6530338 14462272
+p 724 4736286 12022365
+p 723 4736286 12022365
+p 726 4736286 10667728
+p 729 4736286 9776438
+p 730 4736286 8885148
+p 772 4736286 6027778
+p 773 4736286 6027778
+l 778 334
+l 779 334
+l 780 334
+l 781 334
+l 782 334
+l 783 334
+l 784 334
+l 785 334
+l 786 334
+l 787 334
+l 788 334
+l 789 334
+l 790 334
+l 791 334
+l 792 334
+l 793 334
+s 9
+p 793 4736286 6027778
+p 790 4736286 50644704
+p 791 4736286 50644704
+p 792 4736286 49530837
+p 782 4736286 50644704
+p 784 4736286 49465056
+p 785 4736286 49465056
+p 786 4736286 48678624
+p 781 4736286 47040224
+p 780 4736286 51336253
+p 779 4736286 51336253
+p 661 4736286 43268483
+p 662 4736286 43268483
+p 668 6620039 36389056
+p 666 6620039 36389056
+p 667 6261229 36389056
+p 665 6261229 36389056
+p 677 6620039 42625056
+p 678 6620039 42625056
+p 669 6620039 36389056
+p 670 6620039 36389056
+p 672 6620039 36389056
+p 673 6620039 36389056
+p 675 6620039 36389056
+p 676 6620039 36389056
+p 674 6620039 36389056
+p 681 6620039 35497766
+p 679 10509803 35497766
+p 682 15409447 36389056
+p 683 15409447 37280346
+p 692 15409447 43268483
+p 693 15409447 43268483
+p 684 15409447 36389056
+p 685 15409447 36389056
+p 687 15409447 36389056
+p 688 15409447 36389056
+p 690 15409447 36389056
+p 691 15409447 36389056
+p 689 15409447 36389056
+p 696 15409447 35497766
+p 694 19256064 35497766
+p 697 24146230 36389056
+p 698 24146230 37280346
+p 707 24146230 43097551
+p 708 24146230 43097551
+p 699 24146230 36389056
+p 700 24146230 36389056
+p 702 24146230 36389056
+p 703 24146230 36389056
+p 705 24146230 36389056
+p 706 24146230 36389056
+p 704 24146230 36389056
+p 711 24146230 35497766
+p 709 27756878 35497766
+p 716 4736286 33763681
+p 717 8585921 33763681
+p 718 8585921 34654971
+p 731 4736286 22947533
+p 732 4736286 22947533
+p 738 7781060 14238183
+p 736 7781060 14238183
+p 737 7422250 14238183
+p 735 7422250 14238183
+p 739 7781060 14238183
+p 741 7781060 14238183
+p 742 7781060 14238183
+p 744 7781060 14238183
+p 745 7781060 14238183
+p 743 7781060 14238183
+p 746 19700503 14238183
+p 748 19700503 14238183
+p 749 19700503 14238183
+p 751 19700503 14238183
+p 752 19700503 14238183
+p 750 19700503 14238183
+p 757 4736286 12691533
+p 754 14051817 12691533
+p 755 17173800 12691533
+p 756 17173800 13582823
+p 788 4736286 6027778
+p 789 4736286 6027778
+l 794 334
+l 795 335
+l 796 336
+l 797 337
+l 798 338
+l 799 339
+l 800 340
+l 801 341
+l 802 344
+l 803 344
+l 804 344
+l 805 345
+l 806 346
+l 807 347
+l 808 348
+l 809 349
+l 810 350
+l 811 353
+l 812 354
+l 813 355
+l 814 356
+l 815 357
+l 816 359
+l 817 359
+l 818 359
+l 819 360
+l 820 361
+l 821 362
+l 822 362
+l 823 362
+l 824 363
+l 825 364
+l 826 365
+l 827 366
+l 828 366
+l 829 366
+l 830 367
+l 831 370
+l 832 372
+l 833 374
+l 834 375
+l 835 376
+l 836 377
+l 837 380
+l 838 380
+l 839 380
+l 840 382
+l 841 382
+l 842 382
+l 843 383
+l 844 383
+l 845 383
+l 846 383
+l 847 383
+l 848 383
+l 849 383
+l 850 383
+l 851 383
+l 852 383
+l 853 383
+l 854 383
+l 855 383
+s 10
+p 855 4736286 6027778
+p 852 4736286 50644704
+p 853 4736286 50644704
+p 854 4736286 49530837
+p 844 4736286 50644704
+p 846 4736286 49465056
+p 847 4736286 49465056
+p 848 4736286 48678624
+p 843 4736286 47040224
+p 764 6530338 46319328
+p 762 6530338 46319328
+p 763 4736286 46319328
+p 761 4736286 46319328
+p 794 6530338 45428038
+p 795 6530338 44536748
+p 796 6530338 43645458
+p 797 6530338 42754168
+p 798 6530338 41862878
+p 799 6530338 40971588
+p 800 6530338 40080298
+p 801 6530338 39189008
+p 805 6530338 37891931
+p 803 6530338 37891931
+p 804 4736286 37891931
+p 802 4736286 37891931
+p 806 6530338 37000641
+p 807 6530338 36109351
+p 808 6530338 35218061
+p 809 6530338 34326771
+p 810 6530338 33435481
+p 811 4736286 32138404
+p 812 4736286 30355824
+p 813 4736286 29464534
+p 814 4736286 28573244
+p 815 4736286 26790664
+p 819 6530338 24602296
+p 817 6530338 24602296
+p 818 4736286 24602296
+p 816 4736286 24602296
+p 820 6530338 23711006
+p 821 6530338 22819716
+p 822 12092743 22819716
+p 824 6530338 21928426
+p 825 6530338 21037136
+p 826 6530338 20145846
+p 827 6530338 19254556
+p 828 9867781 19254556
+p 830 6530338 18363266
+p 831 4736286 17066189
+p 832 4736286 14392319
+p 833 4736286 12609739
+p 834 4736286 10827159
+p 835 4736286 9935869
+p 836 4736286 8153289
+p 850 4736286 6027778
+p 851 4736286 6027778
+l 856 383
+l 857 385
+l 858 388
+l 859 388
+l 860 388
+l 861 389
+l 862 389
+l 863 390
+l 864 391
+l 865 391
+l 866 392
+l 867 393
+l 868 393
+l 869 394
+l 870 395
+l 871 395
+l 872 396
+l 873 399
+l 874 404
+l 875 404
+l 876 404
+l 877 406
+l 878 406
+l 879 406
+l 880 407
+l 881 409
+l 882 411
+l 883 411
+l 884 411
+l 885 411
+l 886 411
+l 887 411
+l 888 411
+l 889 413
+l 890 413
+l 891 413
+l 892 413
+l 893 413
+l 894 413
+l 895 413
+l 896 413
+l 897 413
+l 898 413
+l 899 413
+l 900 413
+l 901 413
+l 902 413
+l 903 414
+l 904 414
+l 905 415
+l 906 415
+l 907 415
+l 908 415
+l 909 415
+l 910 415
+l 911 415
+l 912 415
+l 913 415
+l 914 415
+l 915 415
+l 916 415
+l 917 415
+l 918 416
+l 919 416
+l 920 416
+l 921 416
+l 922 416
+l 923 416
+l 924 416
+l 925 419
+l 926 419
+l 927 419
+l 928 422
+l 929 422
+l 930 422
+l 931 423
+l 932 425
+l 933 428
+l 934 428
+l 935 428
+l 936 429
+l 937 431
+l 938 431
+l 939 431
+l 940 431
+l 941 431
+l 942 431
+l 943 431
+l 944 431
+l 945 431
+l 946 431
+l 947 431
+l 948 431
+l 949 431
+s 11
+p 949 4736286 6027778
+p 946 4736286 50644704
+p 947 4736286 50644704
+p 948 4736286 49530837
+p 938 4736286 50644704
+p 940 4736286 49465056
+p 941 4736286 49465056
+p 942 4736286 48678624
+p 937 4736286 47040224
+p 927 4736286 46319328
+p 925 4736286 46319328
+p 839 4736286 45598432
+p 838 4736286 45598432
+p 841 4736286 43326291
+p 856 4736286 41543711
+p 857 4736286 40652421
+p 861 6530338 38974699
+p 859 6530338 38974699
+p 860 4736286 38974699
+p 858 4736286 38974699
+p 862 6530338 38974699
+p 863 6530338 38083409
+p 864 6530338 37192119
+p 865 6530338 37192119
+p 866 6530338 36300829
+p 867 6530338 35409539
+p 868 6530338 35409539
+p 869 6530338 34518249
+p 870 6530338 33626959
+p 871 6530338 33626959
+p 872 6530338 32735669
+p 873 4736286 31057947
+p 876 4736286 24680075
+p 875 4736286 24680075
+p 878 4736286 23325438
+p 880 4736286 21542858
+p 881 4736286 20651568
+p 930 4736286 12491116
+p 929 4736286 12491116
+p 931 4736286 11136479
+p 932 4736286 10245189
+p 944 4736286 6027778
+p 945 4736286 6027778
+l 950 431
+l 951 433
+l 952 433
+l 953 433
+l 954 435
+l 955 439
+l 956 439
+l 957 439
+l 958 441
+l 959 443
+l 960 443
+l 961 443
+l 962 445
+(.geocubit_manual.bbl
+)
+l 963 447
+l 964 447
+l 965 447
+l 966 447
+l 967 447
+l 968 447
+l 969 447
+l 970 447
+l 971 447
+l 972 447
+l 973 447
+l 974 447
+l 975 447
+l 976 447
+l 977 447
+l 978 447
+s 12
+p 978 4736286 6027778
+p 975 4736286 50644704
+p 976 4736286 50644704
+p 977 4736286 49530837
+p 967 4736286 50644704
+p 969 4736286 49465056
+p 970 4736286 49465056
+p 971 4736286 48678624
+p 966 4736286 47040224
+p 965 4736286 47040224
+p 964 4736286 47040224
+p 882 4736286 47040224
+p 883 4736286 47040224
+p 889 10040492 40096214
+p 887 10040492 40096214
+p 888 9681682 40096214
+p 886 9681682 40096214
+p 898 10040492 46661117
+p 899 10040492 46661117
+p 890 10040492 40096214
+p 891 10040492 40096214
+p 893 10040492 40096214
+p 894 10040492 40096214
+p 896 10040492 40096214
+p 897 10040492 40096214
+p 895 10040492 40096214
+p 902 10040492 39204924
+p 900 13200092 39204924
+p 903 17369571 40096214
+p 904 17369571 40987504
+p 913 17369571 47040224
+p 914 17369571 47040224
+p 905 17369571 40096214
+p 906 17369571 40096214
+p 908 17369571 40096214
+p 909 17369571 40096214
+p 911 17369571 40096214
+p 912 17369571 40096214
+p 910 17369571 40096214
+p 917 17369571 39204924
+p 915 22624651 39204924
+p 922 4736286 37470839
+p 923 8093734 37470839
+p 924 8093734 38362129
+p 935 4736286 32710780
+p 934 4736286 32710780
+p 936 4736286 31356143
+p 950 4736286 30464853
+p 953 4736286 28543431
+p 952 4736286 28543431
+p 954 4736286 27188794
+p 957 4736286 24928003
+p 956 4736286 24928003
+p 958 4736286 23326247
+p 961 4736286 21065456
+p 960 4736286 21065456
+p 962 4736286 17104404
+p 973 4736286 6027778
+p 974 4736286 6027778
+l 979 447
+l 980 447

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.tex
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.tex	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/geocubit_manual.tex	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,470 @@
+% Preview source code
+
+%% LyX 2.0.0beta3 created this file.  For more info, see http://www.lyx.org/.
+%% Do not edit unless you really know what you are doing.
+\documentclass[a4paper,11pt,english]{article}
+\setlength{\textwidth}{450pt}
+\setlength{\oddsidemargin}{0pt}
+\setlength{\marginparwidth}{0pt}
+\setcounter{secnumdepth}{3}
+\setcounter{tocdepth}{3}
+\usepackage[T1]{fontenc}
+\usepackage[latin9]{inputenc}
+\usepackage{babel}
+\usepackage{setspace}
+\usepackage{listings}
+\usepackage{graphicx,subfigure}
+\usepackage{pdfsync}
+\usepackage{colortbl}
+\usepackage[unicode=true,pdfusetitle,
+ bookmarks=true,bookmarksnumbered=true,bookmarksopen=false,
+ breaklinks=false,pdfborder={0 0 0},backref=section,colorlinks=true,pdfpagemode=None]
+ {hyperref}
+\hypersetup{
+ pdftex,pdfstartview=FitH,pdfpagelayout=SinglePage}
+
+
+\newenvironment{lyxcode}
+{\par\begin{list}{}{
+\setlength{\rightmargin}{\leftmargin}
+\setlength{\listparindent}{0pt}% needed for AMS classes
+\setlength{\itemsep}{0pt}
+\setlength{\parsep}{0pt}
+\normalfont\ttfamily}% 
+\item[]}
+{\end{list}}
+
+\begin{document}
+
+\title{GEOCUBIT USER MANUAL}
+\author{Emanuele Casarotti}
+
+\maketitle
+
+\tableofcontents
+\newpage{}
+
+\section{WHY}
+
+GEOCUBIT is a python library wrapping around the \href{http://cubit.sandia.gov} {CUBIT} Python Interface and it aims to facilitate the meshing
+process in some common problems in seismic wave propagation.\\ 
+In particular, it is focused on the meshing requests of SPECFEM3D and it is helpful for some tedious tasks as:\\
+
+\begin{itemize}
+\item Creation of geophysical surfaces and volumes (ex. topography).
+\item Mesh of layered volumes with hexahedral.
+\item Creation of an anisotropic mesh suitable for cases where some alluvial
+basin (or slow velocity zones) are present.
+\item It can be used as serial or parallel process. The parallel meshing
+capabilities are fundamental for large geophysical problems (ex. mesh
+of Southern California using SRTM topography).
+\end{itemize}
+GEOCUBIT can be use inside the graphical interface of \href{http://cubit.sandia.gov} {CUBIT} (i.e.
+as python object in the script tab) or as unix command. We refer to the \href{http://cubit.sandia.gov} {CUBIT} help appendix for more information about the python interface.
+
+
+\newpage{}
+\section{FIRST STEPS}
+
+
+\subsection{Requirements}
+
+The minimum requirements for using GEOCUBIT are:
+
+\begin{itemize}
+\item \href{http://cubit.sandia.gov} {CUBIT 12.2}
+\item \href{http://downloads.sourceforge.net/numpy} {numpy 1.0+}
+\item \href{http://www.python.org} {python 2.5}
+ (strictly! it depends on the cubit library that refers to this version of python)
+\end{itemize}
+\raggedright{and  for using the parallel meshing capabilities:}
+\begin{itemize}
+\item \href{http://downloads.sourceforge.net/pympi/pyMPI-2.4b4.tar.gz} {pyMPI}
+\end{itemize}
+
+\subsection{Installation}
+
+For installing, download the code and type in the GEOCUBIT directory:
+\begin{lyxcode}
+python2.5 setup.py install~
+\end{lyxcode}
+
+Check that the following variables are set:
+
+\begin{lyxcode}
+CUBITDIR=/usr/local/CUBIT\\
+CUBITLIB=\$CUBITDIR/bin:\$CUBITDIR/structure:\$CUBITDIR/components\\
+PYTHONPATH=\$CUBITDIR/components/cubit:\$CUBITDIR/structure:\$CUBITDIR/bin\\
+LD\_LIBRARY\_PATH=\$CUBITDIR/bin\\
+PATH=\$CUBITDIR/bin:\$CUBITDIR/components/cubit \\
+\end{lyxcode}
+
+
+\newpage{}
+\section{USING GEOCUBIT AT COMMAND LINE:}
+
+\subsection{UTILITIES}
+\begin{itemize}
+\item checking the configuration of the libraries and dependencies:\\
+\begin{lyxcode}
+GEOCUBIT.py --chklib
+\end{lyxcode}
+
+\item checking the parameter file:\\
+\begin{lyxcode}
+GEOCUBIT.py --chkcfg --cfg=[file]
+\end{lyxcode}
+\end{itemize}
+
+\subsection{CREATE GEOMETRY}
+SURFACES
+
+\begin{itemize}
+\item creating acis surfaces using a parameter file:\\
+\begin{lyxcode}
+ GEOCUBIT.py --build\_surface --cfg=[filename]
+\end{lyxcode}
+\end{itemize}
+
+\begin{itemize}
+\item creating a surface from regular ascii grid or ascii lines that define a "skin":\\
+\begin{lyxcode}
+ GEOCUBIT.py --surface=[file] (--regulargrid=[opts] | --skin=[opts])
+\end{lyxcode}
+\end{itemize}
+
+VOLUMES
+\begin{itemize}
+\item **serial** command: creating cubit volumes using a parameter file:\\
+\begin{lyxcode}
+GEOCUBIT.py --surface=[file] (--regulargrid=[opts] | --skin=[opts])
+\end{lyxcode}
+\end{itemize}
+
+\begin{itemize}
+\item **parallel** command: creating cubit volumes using a parameter file:\\
+\begin{lyxcode}
+mpirun -n [numproc] pyMPI GEOCUBIT.py --build\_volume --cfg=[file]
+\end{lyxcode}
+
+
+\begin{figure}\begin{center}
+    \subfigure[]{\includegraphics[scale=.5]{media/geocubitmanual_grid2.jpg}
+    \label{fig:vol}}%
+    \subfigure[]{\includegraphics[scale=.9]{media/geocubitmanual_grid.jpg}
+    \label{fig:table}}%
+\caption{a) Volume divided in slices. b) Parallel map of the IDs for volume in Figure~\ref{fig:vol} divided in (16 slices, 4 along x-axis and 4 along y-axis).}
+\label{fig:grid}
+\end{center}
+\end{figure}
+
+In this parallel application, the volume is separated in N slices, each one is assigned at a single process and one file for each slice is created (see Figure~\ref{fig:grid} as example).
+\end{itemize}
+
+\subsection{MESHING}
+\begin{itemize}
+\item **serial** command: building a volume and meshing it.\\
+\begin{lyxcode}
+GEOCUBIT.py --build\_volume --mesh --cfg=[file] (--id\_proc=n)
+\end{lyxcode}
+\end{itemize}
+
+\begin{itemize}
+\item **serial** command : meshing a volume\\
+\begin{lyxcode}
+GEOCUBIT.py --mesh --cfg=[file] (--id\_proc=[n, def=0])
+\end{lyxcode}
+\footnotesize note: without the --build\_volume flag the script recall an old "geometry\_vol\_[id\_proc].cub" file\\
+\end{itemize}
+
+\begin{itemize}
+\item **parallel** command: meshing a volume from a parameter file\\
+\begin{lyxcode}
+mpirun -n [nproc] pyMPI GEOCUBIT.py --build\_volume --mesh --cfg=[file]
+\end{lyxcode}
+\end{itemize}
+
+\subsection{FINALIZING AND EXPORTING}
+
+It is possible to collect, merge, set the absorbing boundary conditions and to export the resulting mesh in a format readable by SPECFEM3D.
+\begin{itemize}
+\item
+Collecting some cubit files, setting the absorbing boundary conditions and merging in a single free mesh cubitfile
+\begin{lyxcode}
+GEOCUBIT.py --collect --merge --meshfiles=[files] --cpux=N --cpuy=N (--rangecpux=[cpuxmin,cpuxmax] --rangecpuy=[cpuymin,cpuymax])
+\end{lyxcode}
+\texttt{cpuy, cpux} set the number of cpus used for creating the mesh files; \texttt{rangecpux} and \texttt{rangecpuy} set the range of slices that are used in the mesh.\\
+Following the example in Figure~\ref{fig:grid}, the parameters \texttt{--cpux=4 --cpuy=4 --rangecpux=1,2 --rangecpuy=2,3} select the slices with id 10 11 14 15. Only these slices are going to be collect and merged with the appropriated absorbing boundary conditions.
+
+\item Collecting a single free mesh cubitfile and refine the hex inside some curves (ex. alluvial basin, Figure~\ref{fig:refcurve})
+\begin{lyxcode}
+GEOCUBIT.py --collect --meshfiles=[list of files] --curverefining=[file]\\
+\end{lyxcode}
+\footnotesize note: the curves must be stored in acis format (sat) and must be closed.
+
+\end{itemize}
+
+\begin{figure}\center
+\includegraphics[scale=.37]{media/refcurve_1.png}%
+\includegraphics[scale=.303]{media/refcurve_2.png}%
+\caption{}
+
+\label{fig:refcurve}
+\end{figure}
+
+\begin{itemize}
+\item Exporting a cubit mesh file in a SPECFEM3D mesh
+\begin{lyxcode}
+GEOCUBIT.py --export2SPECFEM3D=[output directory] --meshfiles=[filename] (--listblock=[list of cubit blocks] --listflag=[list of specfem3d flags])
+\end{lyxcode}
+\footnotesize If required, it is possible to assign personalized flags to each block using --listblock and the correspondent 	listflag (for example: --listblock=3,4 --listflag=1,-1)
+\end{itemize}
+
+\newpage{}
+\section{GEOCUBIT and CUBIT GRAPHICAL INTERFACE}
+In the python script tab of CUBIT GUI, type:
+
+\begin{lyxcode}
+>f="volume.cfg" $\to$  \textrm{\small{\textit{store the name of the configuration file, see next section}}}\\
+\end{lyxcode}
+
+\begin{lyxcode}
+>from geocubitlib import volumes $\to$  \textrm{\small{\textit{load the geocubit modules}}}\\
+>from geocubitlib import mesh\_volume\\
+>from geocubitlib import exportlib\\
+\end{lyxcode}
+
+\begin{lyxcode}
+volumes.volumes(f) $\to$  \textrm{\small{\textit{create the volumes, the parameters are stored in the cfg file}}}\\
+mesh\_volume.mesh(f) $\to$  \textrm{\small{\textit{mesh the volume}}}\\
+\end{lyxcode}\begin{lyxcode}
+exportlib.collect() $\to$  \textrm{\small{\textit{set the boundary conditions, see SPECFEM3D manual}}}\\
+exportlib.e2SEM(outdir="./output") $\to$  \textrm{\small{\textit{save the mesh in the SPECFEM3D format}}}\\
+\end{lyxcode}
+See the media/iterative.mov for a live example. 
+
+
+\section{EXAMPLES of CONFIGURATION FILES}
+In the current section a few configuration files will be described. Please, see the files in the examples directory of the GEOCUBIT distribution for reference.\\
+
+\subsection{GENERAL OPTIONS}
+
+A cfg file has a format similar to ini windows files.
+They are divided in \texttt{[sections]}. There is no order in the position or in the name of the sections.
+
+Generally, the parameters that control the general options are in the first section, called \texttt{[cubit.options]} and \texttt{[simulation.cpu\_parameters]}. For example:
+
+\begin{lyxcode}
+[cubit.options]\\
+cubit\_info=off $\to$  \textrm{\small{\textit{turn on/off the information of the cubit command}}}\\
+echo\_info=off $\to$   \textrm{\small{\textit{turn on/off the echo of the cubit command}}}\\
+cubit\_info=off $\to$   \textrm{\small{\textit{turn on/off the cubit journaling}}}\\
+echo\_info=off $\to$   \textrm{\small{\textit{turn on/off the cubit error journaling}}}\\
+working\_dir=tmp $\to$   \textrm{\small{\textit{set the working directory}}}\\
+output\_dir=output $\to$   \textrm{\small{\textit{set the output directory}}}\\
+save\_geometry\_cubit = True $\to$   \textrm{\small{\textit{true if it saves the geometry files}}}\\
+save\_surface\_cubit = False $\to$   \textrm{\small{\textit{true if it saves the surfaces in a cubit files}}}\\
+export\_exodus\_mesh = True $\to$   \textrm{\small{\textit{true if it saves the mesh also in exodus format. The default is the cubit format (cub), that contains both the geometry and the meshing information. In case of complex geometry, the cub file could be enormous and a more light exodus file become important.}}}\\
+\end{lyxcode}
+\begin{lyxcode}
+[simulation.cpu\_parameters]\\
+nodes = 1  $\to$   \textrm{\small{\textit{number of nodes/process}}}\\
+
+\end{lyxcode}
+
+\footnotesize note: Usually the *\_info options are turn off by default for improving the performances.\normalsize\\
+
+\subsection{CREATING A TOPOGRAPHIC SURFACE}
+\footnotesize See stromboli.cfg, execute with: \verb!GEOCUBIT.py --build\_surface --cfg=./example/stromboli.cfg. !\normalsize\\
+~\\
+GEOCUBIT is able to create a topographic surface based upon the CUBIT command \verb!create skin curve! and \verb!create surface net! (Figure~\ref{fig:surfacetype}). See the CUBIT manual for details.
+
+\begin{lyxcode}
+[geometry.surfaces]
+nsurf = 2 $\to$   \textrm{\small{\textit{number of surfaces that will be created}}}\\
+\end{lyxcode}
+\begin{lyxcode}
+[surface\textbf{1}.parameters]\\
+name=example/data/stromboli.xyz  $\to$   \textrm{\small{\textit{the name of the file defining the surface}}}\\
+surf\_type=skin $\to$   \textrm{\small{\textit{the type of surface:} \texttt{skin} \textit{, the file is a sequence of parallel points that span the surface in the order describer by the following direction parameters} \texttt{regular\_grid} \emph{the points are structured distritibuted. see Cubit Manual for details(skin surface and net surface) }}}\\
+unit\_surf= utm $\to$   \textrm{\small{\textit{unit of the points,} \texttt{utm} \emph{or} \texttt{geo} \emph{(geographical) coordinates}}}\\
+directionx = 0 $\to$   \textrm{\small{\textit{if} \texttt{surf\_type=skin}\emph{:} \texttt{directionx} \emph{and} \texttt{directiony} \emph{define how the points span the surface}}}\\
+directiony = 1\\
+step = 1 $\to$   \textrm{\small{\textit{the script creates a vertex each} \texttt{step} \emph{points: in this case} \texttt{step=1} \textit{means a vertex for all the points}}}\\
+\end{lyxcode}
+
+\begin{lyxcode}
+[surface2.parameters] $\to$ \textrm{\small{\emph{note the different number of surface in the section name}}}
+name=./examples/surfaces/topo.dat $\to$   \textrm{\small{\textit{the name of the file defining the surface}}}\\
+surf\_type=regular\_grid $\to$   \textrm{\small{\textit{the type of surface:} \texttt{skin} \textit{, the file is a sequence of parallel points that span the surface in the order describer by the following direction parameters} \texttt{regular\_grid} \emph{the points are structured distritibuted. See see Cubit Manual for details (skin surface and net surface) }}}\\
+unit\_surf= geo $\to$   \textrm{\small{\textit{unit of the points,} \texttt{utm} \emph{or} \texttt{geo} \emph{(geographical) coordinates}}}\\
+nx=5 $\to$   \textrm{\small{\textit{In case of} \texttt{regular\_grid}: \texttt{nx} \emph{and} \texttt{ny} \emph{are the number of points along x and y direction.}}}\\
+ny=5
+\end{lyxcode}
+
+\begin{figure}\begin{center}
+    \subfigure[]{\includegraphics[scale=.4]{media/skinsurface.png}
+    \label{fig:skin}}%
+    \subfigure[]{\includegraphics[scale=.4]{media/netsurface.png}
+    \label{fig:net}}%
+    \subfigure[]{\includegraphics[scale=.25]{media/strombolisurface.png}
+    \label{fig:stromboli}}%
+\caption{GEOCUBIT creates a topographic surface in 2 ways: a) skin topography, \texttt{directionx=0} and \texttt{directiony=1}, b) topography from a net of structured distritibuted points, \texttt{nx=4} and \texttt{ny=4}, c) Topography of Stromboli volcano (Italy) using the net surface method.}
+\label{fig:surfacetype}
+\end{center}
+\end{figure}
+
+
+\subsection{CREATING and MESHING A VOLUME}
+\footnotesize see volume.cfg, for executioning: \verb!GEOCUBIT.py --build\_volume --mesh --cfg=./example/volume.cfg !\normalsize\\
+~\\
+The example is for a volume with topography with dimension of the hexahedra increasing with depth by means of a refinement layer (Figure~\ref{fig:volume}).
+
+\begin{figure}\begin{center}
+\includegraphics[scale=.4]{media/geometryvolume.png}%
+\includegraphics[scale=.377]{media/meshvolume.png}%
+\caption{Mesh of a simple volume}
+
+\label{fig:volume}
+\end{center}
+\end{figure}
+
+
+
+\begin{lyxcode}
+[geometry.volumes]\\
+volume\_type = layercake\_volume\_ascii\_regulargrid\_regularmap\\
+latitude\_min                    = 13.879\\
+latitude\_max                    = 14.279\\
+longitude\_min                   = 40.619\\
+longitude\_max                   = 40.969\\
+nx = 5 \\
+ny = 5\\
+unit                            = geo\\
+\end{lyxcode}
+
+\begin{lyxcode}
+[geometry.volumes.layercake]\\
+nz = 2\\
+bottomflat = True\\
+depth\_bottom = -7000\\
+filename = ./example/topo.dat\\
+geometry\_format=ascii\\
+\end{lyxcode}
+
+\texttt{nz} is the number of the horizontal surfaces in the volume (in this case: topography and bottom).\\
+\texttt{bottomflat} is True if the bottom is flat.\\
+\texttt{depth\_bottom} is the depth of the bottom.\\
+\texttt{filename} is a list of files. Each one defines a surface (in this case there is only the topography file in a regular\_grid format).\\
+\texttt{geometry\_format} is set to ascii since the definition of the surfaces comes from ascii files (structured xyz points). \\
+
+\begin{lyxcode}
+[meshing]\\
+map\_meshing\_type=regularmap\\
+iv\_interval=5, $\to$   \textrm{\small{\textit{if only one value is present, append the comma}}}\\
+size=2000\\
+or\_mesh\_scheme=map\\
+ntripl=1\\
+tripl=2, $\to$   \textrm{\small{\textit{if only one value is present, append the comma}}}\\
+smoothing=False\\
+\end{lyxcode}
+
+The \texttt{meshing} section contains the parameters request for the meshing process.
+\texttt{map\_meshing\_type} set the meshing scheme and is regularmap by default (other schemes are in preliminary phase).\\
+\texttt{iv\_interval} set the number of "horizontal" hex sheets for each layer.
+\texttt{size} is the dimension of hexahedral (horizontally)\\
+\texttt{or\_mesh\_scheme} is the meshing scheme for the topography (\texttt{map} or \texttt{pave} are possible, see the CUBIT manual for more information).\\
+\texttt{ntripl} is the number of tripling layer in the mesh (in this case 1).\\
+\texttt{tripl} means in this case that the the refinement layer is located at the second surface (the topography). The surfaces are ordered from the bottom (surface 1) to the top (surface 2).\\
+\texttt{smoothing} performes the smoothing command in Cubit.\\
+
+
+\subsection{LAYERED VOLUME and MESH FOR CENTRAL ITALY (PARALLEL)}
+
+\footnotesize In the example abruzzo.cfg, the layers are 2. For execution type: \texttt{mpirun -n 150 GEOCUBIT.py --build\_volume --mesh --cfg=./example/abruzzo.cfg}.\normalsize\\
+~\\
+
+Comparing the previous cfg files, there are few modification:
+
+
+\begin{lyxcode}
+$\cdots $\\
+nz = 3 \\
+$\cdots $\\
+filename = example/data/moho\_int.xyz,example/data/topo.xyz\\
+$\cdots $\\
+iv\_interval=8,8 (one value for each layer)\\
+$\cdots $\\
+refinement\_depth=1,\\
+\end{lyxcode}
+
+The volume has \texttt{nz=3} interfaces: bottom, moho, and topography. The bottom is flat and  his z-coordinate position is set by \texttt{depth\_bottom}. 
+The name of the files that storage the data for the other interfaces are listed in \texttt{filename}.
+The interfaces defines 2 geological layers. Each layer has \texttt{iv\_interval=8} "horizontal" hex sheets. There is only a refinement and it is set in the \texttt{refinement\_depth=1} hex sheet, i.e just below the topography (\texttt{refinement\_depth=8} means just below the moho).
+
+
+\subsection{CREATION OF A REGULAR MESH}
+
+\footnotesize In the example grid.cfg, the layers are 3. For execution type: \texttt{GEOCUBIT.py --build\_volume --mesh --cfg=./example/grid.cfg}.\normalsize\\
+~\\
+
+In this example we create a simple layercake box \texttt{geometry\_format=regmesh} with 3 layers at depth defined by \texttt{zdepth=-7000,-3000,-600,0}. The initial mesh has hex with horizontal size \texttt{size=2000} and the numbers of vertical hex sheets is iv\_interval=3,1,1 respectively for the bottom, middle and top layer. We include a refinement layer (\texttt{ntripl=1}) at \texttt{tripl=2,} interface (the second from the bottom). Since the refinement occurs on the vertical direction, the vertical dimensions of the hexes in the top layer is too small and the quality of the mesh decreases. \texttt{coarsening\_top\_layer=True} remesh the top layer and the number of vertical hex sheet in the vertical is defined by \texttt{actual\_vertical\_interval\_top\_layer=1}. (see Figure~\ref{fig:regrid}) 
+
+\begin{figure}\begin{center}
+    \subfigure[]{\includegraphics[scale=.2]{media/regrid.png}
+    \label{fig:regrid_nocoarse}}%
+    \subfigure[]{\includegraphics[scale=.47]{media/regrid_coarse.png}
+    \label{fig:regrid_coarse}}%
+\caption{Regular mesh with one tripling layer, a) mesh with coarsening\_top\_layer=False, b) mesh with \texttt{coarsening\_top\_layer=True}, the top layer is remeshed with \texttt{actual\_vertical\_interval\_top\_layer=1} vertical hex sheet.}
+\label{fig:regrid}
+\end{center}
+\end{figure}
+
+
+\subsection{TODO: MESH for SOUTHERN CALIFORNIA}
+Mesh with high number of hexes and high resolution topography. Mesh in Parallel.
+
+TO DO
+
+
+\subsection{TODO MESH for SANTA MONICA OVERTRUST}
+Using part of the mesh for Southern California, stitching together several slices. 
+
+TO DO
+
+\subsection{TODO Grouping the hexes with different period resolved}
+
+Checking the stability
+For execution type: \texttt{GEOCUBIT.py --meshfiles=[filename] --stability (--tomofile=[tomographic file]/--vp=[vp text value] --vs=[vs text value])}.
+
+or
+
+in the script tab of the CUBIT GUI, type:
+
+\begin{lyxcode}
+>from geocubitlib.hex_metric import SEM_stability_3D $\to$  \textrm{\small{\textit{load the geocubit modules}}}\\
+>mesh=SEM_stability_3D()\\
+>mesh.check_simulation_parameter(vp_static=vp,vs_static=vs) $\to$  \textrm{\small{\textit{text the mesh against some homogeneous velocity model}}}\\
+or\\
+>mesh.check_simulation_parameter(tomofile=tomofile) $\to$  \textrm{\small{\textit{text the mesh against a tomographic file}}}\\
+mesh.group_timestep() $\to$  \textrm{\small{\textit{grouping hex with similar timestep}}}\\
+mesh.group_period() $\to$  \textrm{\small{\textit{grouping hex with similar period}}}\\
+\end{lyxcode}
+
+
+
+TO DO: picture
+
+ 
+
+
+
+\section{TODO SPECFEM3D MESH FORMAT}
+
+TO DO
+
+\section{TODO NOTES ABOUT THE DIMENSION OF THE HEXES, THE MINIMUM PERIOD RESOLVED AND THE TIME STEP OF THE SIMULATION}
+
+TO DO
+\bibliography{bibliography.bib}
+\end{document}
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/geocubitmanual_grid.jpg
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/geocubitmanual_grid.jpg
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/geocubitmanual_grid2.jpg
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/geocubitmanual_grid2.jpg
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/geometryvolume.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/geometryvolume.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/grid.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/grid.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/iterative.mov
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/iterative.mov
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/meshvolume.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/meshvolume.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/netsurface.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/netsurface.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/refcurve_1.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/refcurve_1.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/refcurve_2.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/refcurve_2.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/regrid.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/regrid.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/regrid_coarse.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/regrid_coarse.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/skinsurface.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/skinsurface.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/strombolisurface.png
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/doc/media/strombolisurface.png
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/abruzzo.cfg
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/abruzzo.cfg	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/abruzzo.cfg	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,44 @@
+[cubit.options]
+cubit_info=on
+echo_info=on
+jou_info=on
+jer_info=on
+working_dir=.
+output_dir=./output
+save_geometry_cubit = False
+save_surface_cubit = False
+export_exodus_mesh = True
+
+[simulation.cpu_parameters]
+number_processor_xi                        =15
+number_processor_eta                       =10
+#
+[geometry.volumes]
+volume_type                     = layercake_volume_ascii_regulargrid_regularmap
+latitude_min                    = 41.10
+latitude_max                    = 42.90
+longitude_min                   = 12.04
+longitude_max                   = 14.45
+nx                              = 2411
+ny                              = 1801
+unit                            = geo
+
+
+# geo or utm
+
+[geometry.volumes.layercake]
+nz = 3
+#included the bottom
+bottomflat = True
+depth_bottom = -60000
+filename = example/data/moho_int.xyz,example/data/topo.xyz,
+geometry_format=ascii
+
+[meshing]
+map_meshing_type=regularmap
+iv_interval=8,8
+size=3000
+or_mesh_scheme=map
+ntripl=1
+smoothing=True
+refinement_depth=1,

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/data.zip
===================================================================
(Binary files differ)


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/data.zip
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/grid.cfg
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/grid.cfg	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/grid.cfg	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,44 @@
+[cubit.options]
+cubit_info=on
+echo_info=on
+jou_info=on
+jer_info=on
+working_dir=tmp
+output_dir=output
+save_geometry_cubit = True
+save_surface_cubit = True
+monitored_cpu=0
+
+[simulation.cpu_parameters]
+nodes=1
+#number_processor_xi                        =1
+#number_processor_eta                      =1
+#
+[geometry.volumes]
+volume_type                     = layercake_volume_ascii_regulargrid_regularmap
+latitude_min                    = 40.
+latitude_max                    = 40.5
+longitude_min                   = 11.
+longitude_max                   = 11.5
+unit                            = geo
+# geo or utm
+
+[geometry.volumes.layercake]
+nz = 4
+#included the bottom
+bottomflat = True
+depth_bottom = -7000
+geometry_format=regmesh
+zdepth=-7000,-3000,-600,0
+
+[meshing]
+map_meshing_type=regularmap
+iv_interval=3,1,1
+size=2000
+or_mesh_scheme=map
+ntripl=1
+tripl=2,
+smoothing=False
+coarsening_top_layer=True
+actual_vertical_interval_top_layer=1
+

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/stromboli.cfg
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/stromboli.cfg	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/stromboli.cfg	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,22 @@
+[cubit.options]
+cubit_info=on
+echo_info=on
+jou_info=on
+jer_info=on
+working_dir=tmp
+output_dir=output
+
+[simulation.cpu_parameters]
+nodes = 1
+
+[geometry.surfaces]
+nsurf = 1
+
+[surface1.parameters]
+name=example/data/stromboli.xyz
+surf_type=skin
+unit_surf= utm
+directionx                     = 0
+directiony                     = 1
+step                           = 1
+

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/topo.dat
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/topo.dat	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/topo.dat	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,25 @@
+13.879 40.619 1920
+13.979 40.619 1060
+14.079 40.619 2390
+14.179 40.619 1600
+14.279 40.619 1310
+13.879 40.719 2240
+13.979 40.719 1410
+14.079 40.719 1610
+14.179 40.719 38
+14.279 40.719 22
+13.879 40.819 1190
+13.979 40.819 2500
+14.079 40.819 2840
+14.179 40.819 1230
+14.279 40.819 2720
+13.879 40.919 1720
+13.979 40.919 2460
+14.079 40.919 1580
+14.179 40.919 1810
+14.279 40.919 1580
+13.879 40.969 87
+13.979 40.969 87
+14.079 40.969 1400
+14.179 40.969 37
+14.279 40.969 21

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/volume.cfg
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/volume.cfg	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/example/volume.cfg	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,41 @@
+[cubit.options]
+cubit_info=off
+echo_info=off
+jou_info=off
+jer_info=off
+working_dir=tmp
+output_dir=output
+save_geometry_cubit = True
+save_surface_cubit = False
+
+[simulation.cpu_parameters]
+nodes = 1
+#
+[geometry.volumes]
+volume_type                     = layercake_volume_ascii_regulargrid_regularmap
+latitude_min                    = 13.879
+latitude_max                    = 14.279 
+longitude_min                   = 40.619 
+longitude_max                   = 40.969
+nx = 5 
+ny = 5
+unit                            = geo
+# geo or utm
+
+[geometry.volumes.layercake]
+nz = 2
+#included the bottom
+bottomflat = True
+depth_bottom = -7000
+filename = example/topo.dat
+geometry_format=ascii
+
+[meshing]
+map_meshing_type=regularmap
+iv_interval=5,
+size=2000
+or_mesh_scheme=map
+ntripl=1
+smoothing=False
+coarsening_top_layer=False
+tripl=2,
\ No newline at end of file

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/exportlib.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/exportlib.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/exportlib.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,667 +0,0 @@
-#!/usr/bin/env python
-#############################################################################
-# exportlib.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-#
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-
-def refine_closecurve(block=1001,closed_filenames=None,acis=True):
-    from utilities import load_curves
-    from boundary_definition import build_block_side,define_surf
-    from mesh_volume import refine_inside_curve
-    #
-    #
-    curves=[]
-    if not isinstance(closed_filenames,list): closed_filenames=[closed_filenames]
-    for f in closed_filenames:
-        print f
-        if acis: 
-            curves=curves+load_curves(f)
-    print curves
-    blist=list(cubit.get_block_id_list())
-    try:
-        blist.remove(1001)
-    except:
-        pass
-    try:
-        blist.remove(1002)
-    except:
-        pass
-    try:
-        blist.remove(1003)
-    except:
-        pass        
-    try:
-        blist.remove(1004)    
-    except:                             
-        pass             
-    try:
-        blist.remove(1005)
-    except:
-        pass
-    try:
-        blist.remove(1006)
-    except:
-        pass
-    id_top=max(blist)
-    cmd='group "coi" add node in hex in block '+str(id_top)
-    cubit.cmd(cmd)
-    #
-    id_inside_arc=None
-    for c in map(int,curves[0].split()):   #curves is a list of one string
-        c1001 = cubit.get_exodus_element_count(1001, "block")
-        c1002 = cubit.get_exodus_element_count(1002, "block")
-        c1003 = cubit.get_exodus_element_count(1003, "block")
-        c1004 = cubit.get_exodus_element_count(1004, "block")
-        c1005 = cubit.get_exodus_element_count(1005, "block")
-        c1006 = cubit.get_exodus_element_count(1006, "block")
-        #
-        refine_inside_curve(c,ntimes=1,depth=1,block=block,surface=False)
-        blist=list(cubit.get_block_id_list())
-        cmd='create mesh geometry hex all except hex in block all feature_angle 135'
-        cubit.cmd(cmd)
-        blist_after=list(cubit.get_block_id_list())
-        [blist_after.remove(x) for x in blist]
-        id_inside=max(blist_after)
-        cmd='group "coi" add node in hex in block '+str(id_inside)
-        cubit.cmd(cmd)
-        if id_inside_arc: 
-                cmd='del block '+str(id_inside-1)
-                cubit.cmd(cmd)
-        cmd='block '+str(id_inside)+' name "refined"'
-        cubit.cmd(cmd)
-        id_inside_arc=id_inside                                            
-        #
-        _,_,_,_,_,top_surf,bottom_surf,surf_xmin,surf_ymin,surf_xmax,surf_ymax=define_surf()
-        #
-        c1001_after = cubit.get_exodus_element_count(1001, "block")
-        c1002_after = cubit.get_exodus_element_count(1002, "block")
-        c1003_after = cubit.get_exodus_element_count(1003, "block")
-        c1004_after = cubit.get_exodus_element_count(1004, "block")
-        c1005_after = cubit.get_exodus_element_count(1005, "block")
-        c1006_after = cubit.get_exodus_element_count(1006, "block")
-        entity='face'
-        if c1001_after != c1001:
-            refname=entity+'_topo'
-            build_block_side(top_surf,refname,obj=entity,id_0=1001)
-        #
-        if c1002_after != c1002:
-            refname=entity+'_bottom'
-            build_block_side(bottom_surf,refname,obj=entity,id_0=1002)
-        #
-        if c1003_after != c1003:
-            refname=entity+'_abs_xmin'
-            build_block_side(surf_xmin,refname,obj=entity,id_0=1003)
-        #                                                              
-        if c1004_after != c1004:
-            refname=entity+'_abs_ymin'
-            build_block_side(surf_ymin,refname,obj=entity,id_0=1004)
-        #                                                              
-        if c1005_after != c1005:  
-            refname=entity+'_abs_xmax'                                     
-            build_block_side(surf_xmax,refname,obj=entity,id_0=1005)
-        #
-        if c1006_after != c1006:    
-            refname=entity+'_abs_ymax'                                   
-            build_block_side(surf_ymax,refname,obj=entity,id_0=1006)
-        #
-        cmd='disassociate mesh from volume all'
-        cubit.cmd(cmd)
-        cmd='group "coi" add node in face in block 1001 1002 1003 1004 1005 1006'
-        cubit.cmd(cmd)
-        cubit.cmd('del vol all')
-        cubit.cmd('group "removedouble" add hex all except hex in block all')
-        cubit.cmd('delete hex in removedouble')
-        cubit.cmd('delet group removedouble')
-        cmd='equivalence node in group coi tolerance 20'
-        cubit.cmd(cmd)
-    cmd='equivalence node all tolerance 10'
-    cubit.cmd(cmd)
-    cubit.cmd('del curve '+' '.join(str(x) for x in curves) )
-
-
-
-
-def collecting_merging(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,ckbound_method1=False,ckbound_method2=False,merge_tolerance=None):
-    import glob
-    import re
-    #
-    rule_st=re.compile("(.+)_[0-9]+\.")
-    rule_ex=re.compile(".+_[0-9]+\.(.+)")
-    rule_int=re.compile(".+_([0-9]+)\.")
-    boundary_dict={}
-    ##
-    try:
-        from boundary_definition import check_bc, map_boundary
-    except:
-        pass
-    #
-    xmin,xmax,ymin,ymax,listfull=map_boundary(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
-    #
-    if cubfiles:
-        filenames=glob.glob(cubfiles)
-        try:
-            st = rule_st.findall(filenames[0])[0]
-            ex = rule_ex.findall(filenames[0])[0]
-            listflag=True
-        except:
-            ex=''
-            listflag=False
-        
-        if ex == 'cub':
-            cubflag=True
-        else:
-            cubflag=False
-        list_int=[]
-        fs=[]
-        try:
-            for f in filenames:
-                i=int(rule_int.findall(f)[0])
-                list_int.append(i)
-            list_int.sort()
-            for i,ind in enumerate(list_int):
-                f=st+'_'+str(ind)+'.'+ex
-                fs.append(f)
-        except:
-            pass
-        if listflag:
-            filenames=fs
-        else:
-            pass
-        print len(filenames),filenames
-    else:
-        filenames=[]
-        ip=0
-    #
-    if len(filenames) > 0:
-        for filename in filenames[:]:
-            try:
-                ip=int(rule_int.findall(filename)[0])
-                if ip in listfull:
-                    if cubflag:
-                        cubit.cmd('import cubit "'+filename+'"')
-                    else:
-                        cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
-                    boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
-                    boundary_dict[ip]=boundary
-                    list_vol=list(cubit.parse_cubit_list('volume','all'))
-                    for v in list_vol:
-                        cubit.cmd("disassociate mesh from volume "+str(v))
-                        command = "del vol "+str(v)
-                        cubit.cmd(command)
-            except:
-                cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
-                ip=0
-                boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
-                boundary_dict[ip]=boundary
-                list_vol=list(cubit.parse_cubit_list('volume','all'))
-                for v in list_vol:
-                    cubit.cmd("disassociate mesh from volume "+str(v))
-                    command = "del vol "+str(v)
-                    cubit.cmd(command)
-        cubit.cmd('export mesh "tmp_collect_NOmerging.e" dimension 3 block all overwrite')
-    else:
-        boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
-    #
-    #
-    block_list=cubit.get_block_id_list()
-    for block in block_list:
-        ty=cubit.get_block_element_type(block)
-        if ty == 'HEX8':
-            cubit.cmd('block '+str(block)+' name "vol'+str(block)+'"')
-    #
-    #
-    print 'chbound',ckbound_method1,ckbound_method2
-    if ckbound_method1 and not ckbound_method2:
-        if isinstance(merge_tolerance,list):
-            tol=merge_tolerance[0]
-        elif merge_tolerance:
-            tol=merge_tolerance
-        else:
-            tol=100000
-        #
-        idiag=None
-        #cubit.cmd('set info off')
-        #cubit.cmd('set journal off')
-        #cubit.cmd('set echo off')
-        ind=0
-        for ix in range(cpuxmin,cpuxmax):
-            for iy in range(cpuymin,cpuymax):
-                ind=ind+1
-                ip=iy*cpux+ix
-                print '******************* ',ip, ind,'/',len(listfull)
-                #
-                #   ileft    |   ip
-                #  --------------------
-                #   idiag    |   idown
-                #
-                #
-                if ip not in xmin and ip not in ymin:
-                    ileft=iy*cpux+ix-1
-                    idown=(iy-1)*cpux+ix
-                    idiag=idown-1
-                elif ip in xmin and ip in ymin:
-                    ileft=ip
-                    idown=ip
-                    idiag=None
-                elif ip in xmin:
-                    ileft=ip
-                    idown=(iy-1)*cpux+ix
-                    idiag=idown
-                elif ip in ymin:
-                    ileft=iy*cpux+ix-1
-                    idown=ip
-                    idiag=ileft
-                #
-                if ip != idown:
-                    nup=boundary_dict[ip]['nodes_surf_ymin']
-                    ndow=boundary_dict[idown]['nodes_surf_ymax']
-                    merge_node(nup,ndow)
-                    
-                    if idiag != idown:
-                        if ip in ymax and ip not in xmin:
-                            nlu=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck left up... r u
-                            nru=boundary_dict[ileft]['node_curve_xmaxymax']
-                            merge_node(nlu,nru)
-                        if ip in xmax:
-                            nrd=boundary_dict[ip]['node_curve_xmaxymin'] #node in curve chunck left up... r u
-                            nru=boundary_dict[idown]['node_curve_xmaxymax']
-                            merge_node(nrd,nru)
-                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
-                        nrd=boundary_dict[idown]['node_curve_xminymax']
-                        nld=boundary_dict[idiag]['node_curve_xmaxymax']
-                        nlu=boundary_dict[ileft]['node_curve_xmaxymin']
-                        merge_node_4(nru,nrd,nld,nlu)
-                    elif ip in xmin:
-                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
-                        nrd=boundary_dict[idown]['node_curve_xminymax']
-                        merge_node(nrd,nru)
-                        
-                #
-                if ip != ileft:
-                    nright=boundary_dict[ip]['nodes_surf_xmin']
-                    nleft=boundary_dict[ileft]['nodes_surf_xmax']
-                    merge_node(nright,nleft)
-                    #
-                    #
-                    if ip in ymin:
-                        nrd=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right down... r u
-                        nld=boundary_dict[ileft]['node_curve_xmaxymin']
-                        merge_node(nrd,nld)
-                    if ip in ymax:
-                        nru=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck right up... r u
-                        nlu=boundary_dict[ileft]['node_curve_xmaxymax']
-                        merge_node(nlu,nru)
-        
-        cubit.cmd('set info on')
-        cubit.cmd('set echo on')
-        cubit.cmd('set journal on')
-        
-        
-        #
-        #
-        cmd='group "negativejac" add quality hex all Jacobian high'
-        cubit.cmd(cmd) 
-        group_id_1=cubit.get_id_from_name("negativejac")
-        n1=cubit.get_group_nodes(group_id_1)
-        if len(n1) != 0:
-            print 'error, negative jacobian after the equivalence node command, use --merge2 instead of --equivalence/--merge/--merge1'
-    elif ckbound_method2 and not ckbound_method1:
-        if isinstance(merge_tolerance,list):
-            tol=merge_tolerance[0]
-        elif merge_tolerance:
-            tol=merge_tolerance
-        else:
-            tol=100000
-        #
-        idiag=None
-        for ix in range(cpuxmin,cpuxmax):
-            for iy in range(cpuymin,cpuymax):
-                ip=iy*cpux+ix
-                print '******************* ',ip
-                #
-                #   ileft    |   ip
-                #  --------------------
-                #   idiag    |   idown
-                #
-                #
-                if ip not in xmin and ip not in ymin:
-                    ileft=iy*cpux+ix-1
-                    idown=(iy-1)*cpux+ix
-                    idiag=idown-1
-                elif ip in xmin and ip in ymin:
-                    ileft=ip
-                    idown=ip
-                elif ip in xmin:
-                    ileft=ip
-                    idown=(iy-1)*cpux+ix
-                    idiag=idown
-                elif ip in ymin:
-                    ileft=iy*cpux+ix-1
-                    idown=ip
-                    idiag=ileft
-                #
-                #
-                if ip != idown:
-                    nup=boundary_dict[ip]['nodes_surf_ymin']
-                    ndow=boundary_dict[idown]['nodes_surf_ymax']
-                    for n1,n2 in zip(nup,ndow):
-                        cubit.cmd('equivalence node '+str(n1)+' '+str(n2)+' tolerance '+str(tol))
-                    if idiag != idown:
-                        if ip in ymax and ip not in xmin:
-                            nlu=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck left up... r u
-                            nru=boundary_dict[ileft]['node_curve_xmaxymax']
-                            for n in zip(nlu,nru):
-                                cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
-                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
-                        nrd=boundary_dict[idown]['node_curve_xminymax']
-                        nld=boundary_dict[idiag]['node_curve_xmaxymax']
-                        nlu=boundary_dict[ileft]['node_curve_xmaxymin']
-                        for n in zip(nru,nrd,nlu,nld):
-                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
-                    elif ip in xmin:
-                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
-                        nrd=boundary_dict[idown]['node_curve_xminymax']
-                        for n in zip(nru,nrd):
-                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
-                #
-                #
-                if ip != ileft:
-                    nright=boundary_dict[ip]['nodes_surf_xmin']
-                    nleft=boundary_dict[ileft]['nodes_surf_xmax']
-                    for n1,n2 in zip(nleft,nright):
-                        cubit.cmd('equivalence node '+str(n1)+' '+str(n2)+' tolerance '+str(tol))
-                    #
-                    #
-                    if ip in ymin:
-                        nrd=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right down... r u
-                        nld=boundary_dict[ileft]['node_curve_xmaxymin']
-                        for n in zip(nrd,nld):
-                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
-                    if ip in ymax:
-                        nru=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck right up... r u
-                        nlu=boundary_dict[ileft]['node_curve_xmaxymax']
-                        for n in zip(nru,nlu):
-                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
-        #
-        #
-        cmd='topology check coincident node face all tolerance '+str(tol*2)+' nodraw brief result group "checkcoinc"' 
-        cubit.silent_cmd(cmd)
-        group_id_1=cubit.get_id_from_name("checkcoinc")
-        if group_id_1 != 0:
-            n1=cubit.get_group_nodes(group_id_1)
-            if len(n1) != 0:
-                print 'error, coincident nodes after the equivalence node command, check the tolerance'
-                import sys
-                sys.exit()
-        cmd='group "negativejac" add quality hex all Jacobian high'
-        cubit.cmd(cmd) 
-        group_id_1=cubit.get_id_from_name("negativejac")
-        n1=cubit.get_group_nodes(group_id_1)
-        if len(n1) != 0:
-            print 'error, negative jacobian after the equivalence node command, check the mesh'
-    elif ckbound_method1 and  ckbound_method2:
-        block_list=cubit.get_block_id_list()
-        i=-1
-        for block in block_list:
-            ty=cubit.get_block_element_type(block)
-            if ty == 'HEX8':
-                i=i+1
-                if isinstance(merge_tolerance,list):
-                    try:
-                        tol=merge_tolerance[i]
-                    except:
-                        tol=merge_tolerance[-1]
-                elif merge_tolerance:
-                    tol=merge_tolerance
-                else:
-                    tol=1
-                cmd='topology check coincident node face in hex in block '+str(block)+' tolerance '+str(tol)+' nodraw brief result group "b'+str(block)+'"'
-                cubit.cmd(cmd)
-                print cmd
-                cmd='equivalence node in group b'+str(block)+' tolerance '+str(tol)
-                cubit.cmd(cmd)
-                print cmd
-        if isinstance(merge_tolerance,list):
-            tol=max(merge_tolerance)
-        elif merge_tolerance:
-            tol=merge_tolerance
-        else:
-            tol=1
-        #
-        #
-        cmd='topology check coincident node face all tolerance '+str(tol)+' nodraw brief result group "checkcoinc"' 
-        cubit.silent_cmd(cmd)
-        group_id_1=cubit.get_id_from_name("checkcoinc")
-        if group_id_1 != 0:
-            n1=cubit.get_group_nodes(group_id_1)
-            if len(n1) != 0:
-                print 'error, coincident nodes after the equivalence node command, check the tolerance'
-                import sys
-                sys.exit()
-        cmd='group "negativejac" add quality hex all Jacobian high'
-        cubit.silent_cmd(cmd) 
-        group_id_1=cubit.get_id_from_name("negativejac")
-        n1=cubit.get_group_nodes(group_id_1)
-        if len(n1) != 0:
-            print 'error, negative jacobian after the equivalence node command, use --merge instead of --equivalence'
-
-def collect(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,ckbound_method1=False,ckbound_method2=False,merge_tolerance=None,curverefining=False,outfilename='totalmesh_merged',qlog=False,export2SPECFEM3D=False,listblock=None,listflag=None,outdir='.'):
-    #
-    collecting_merging(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy,cubfiles=cubfiles,ckbound_method1=ckbound_method1,ckbound_method2=ckbound_method2,merge_tolerance=merge_tolerance)
-    #
-    if curverefining:
-        block=1001 #topography
-        refine_closecurve(block,curverefining,acis=True)
-    #
-    #
-    cubit.cmd('compress all')
-    command="export mesh '"+outfilename+".e' block all overwrite xml '"+outfilename+".xml'"
-    cubit.cmd(command)
-    outdir2='/'.join(x for x in outfilename.split('/')[:-1])
-    if outdir2 == '': outdir2='.'
-    f=open(outdir2+'/'+'blocks.dat','w')
-    blocks=cubit.get_block_id_list()
-    #
-    for block in blocks:
-        name=cubit.get_exodus_entity_name('block',block)
-        element_count = cubit.get_exodus_element_count(block, "block")
-        nattrib=cubit.get_block_attribute_count(block)
-        attr=[cubit.get_block_attribute_value(block,x) for x in range(0,nattrib)]
-        ty=cubit.get_block_element_type(block)
-        f.write(str(block)+' ; '+name+' ; nattr '+str(nattrib)+' ; '+' '.join(str(x) for x in attr)+' ; '+ty+' '+str(element_count)+'\n')
-    f.close()
-    #
-    #
-    cubit.cmd('set info echo journ off')
-    cmd='del group all'
-    cubit.silent_cmd(cmd)
-    cubit.cmd('set info echo journ on')
-    #
-    command = "save as '"+outfilename+".cub' overwrite"
-    cubit.cmd(command)
-    #
-    print 'end meshing'
-    #
-    #
-    if qlog:
-        print '\n\nQUALITY CHECK.... ***************\n\n'
-        import quality_log
-        tq=open(outfilename+'.quality','w')
-        max_skewness,min_length=quality_log.quality_log(tq)
-    #
-    #
-    #
-    if export2SPECFEM3D:
-        e2SEM(files=False,listblock=listblock,listflag=listflag,outdir=outdir)
-                                            
-def e2SEM(files=False,listblock=None,listflag=None,outdir='.'):
-    import glob
-    if files:
-        filenames=glob.glob(files)
-        for f in filenames:
-            print f
-            extension=f.split('.')[-1]
-            if extension == 'cub':
-                cubit.cmd('open "'+f+'"')
-            elif extension== 'e':
-                cubit.cmd('import mesh "'+f+'" no_geom')
-            else:
-                print extension
-    if listblock and listflag:
-        pass
-    else:
-        listblock=[]
-        listflag=[]
-        block_list=list(cubit.get_block_id_list())
-        for block in block_list:
-            ty=cubit.get_block_element_type(block)
-            if 'HEX' in ty:
-                listblock.append(block)
-                #listflag.append(block)
-        listflag=range(1,len(listflag)+1)  
-    #       
-    for ib,iflag in zip(listblock,listflag):
-        cubit.cmd("block "+str(ib)+" attribute count 1")
-        cubit.cmd("block "+str(ib)+" attribute index 1 "+ str(iflag)            )
-    #
-    import cubit2specfem3d
-    cubit2specfem3d.export2SPECFEM3D(outdir)
-
-def invert_dict(d):
-     inv = {}
-     for k,v in d.iteritems():
-         keys = inv.setdefault(v, [])
-         keys.append(k)
-     return inv
-     
-     
-     
-def prepare_equivalence(nodes1,nodes2):
-    cubit.cmd('set info off')
-    cubit.cmd('set echo off')
-    cubit.cmd('set journal off')
-    length={}
-    for ns in zip(nodes1,nodes2):
-        cmd='group "tmpn" add edge in node '+' '.join(str(n) for n in ns )
-        cubit.cmd(cmd)
-        ge=cubit.get_id_from_name("tmpn")
-        e1=cubit.get_group_edges(ge)
-        lengthmin=1e9
-        for e in e1:
-            lengthmin=min(lengthmin,cubit.get_mesh_edge_length(e))
-        length[ns]=lengthmin*.5
-        cubit.cmd('delete group '+str(ge))
-    minvalue=min(length.values())
-    maxvalue=max(length.values())
-    print 'min lentgh: ',minvalue,'max lentgh: ',maxvalue
-    nbin= int((maxvalue/minvalue)/2.)+1
-    factor=(maxvalue-minvalue)/nbin
-    dic_new={}
-    for k in length.keys():
-        dic_new[k]=int((length[k]-minvalue)/factor)
-    inv_length=invert_dict(dic_new)
-    print inv_length.keys(),factor,minvalue
-    ks=inv_length.keys()
-    ks.sort()
-    for k in range(0,len(inv_length.keys())-1):
-        inv_length[ks[k]]=inv_length[ks[k]]+inv_length[ks[k+1]]
-    cubit.cmd('set info on')
-    cubit.cmd('set echo on')
-    cubit.cmd('set journal on')
-    return factor,minvalue,inv_length
-
-
-def merge_node(n1,n2):
-    factor,minvalue,inv_length=prepare_equivalence(n1,n2)
-    
-    for k in inv_length.keys()[:-1]:
-        if len(inv_length[k]) > 0:
-            cmd='equivalence node '+' '.join(' '.join(str(n) for n in x) for x in inv_length[k])+' tolerance '+str(k*factor+minvalue/2.)
-            cubit.cmd(cmd)
-            print 'equivalence '+str(len(inv_length[k]))+' couples of nodes -  tolerance '+str(k*factor+minvalue/2.)
-
-
-def prepare_equivalence_4(nodes1,nodes2,nodes3,nodes4):
-    cubit.cmd('set info off')
-    cubit.cmd('set echo off')
-    cubit.cmd('set journal off')
-    length={}
-    for ns in zip(nodes1,nodes2,nodes3,nodes4):
-        cmd='group "tmpn" add edge in node '+' '.join(str(n) for n in ns )
-        cubit.cmd(cmd)
-        ge=cubit.get_id_from_name("tmpn")
-        e1=cubit.get_group_edges(ge)
-        lengthmin=1e9
-        for e in e1:
-            lengthmin=min(lengthmin,cubit.get_mesh_edge_length(e))
-        length[ns]=lengthmin*.5
-        cubit.cmd('delete group '+str(ge))
-    try:
-        minvalue=min(length.values())
-        maxvalue=max(length.values())
-    except:
-        print nodes1,nodes2,nodes3,nodes4
-        print 'edges ', e1
-        minvalue=100.
-        maxvalue=2000.
-    print 'min lentgh: ',minvalue,'max lentgh: ',maxvalue
-    nbin= int((maxvalue/minvalue)/2.)+1
-    factor=(maxvalue-minvalue)/nbin
-    dic_new={}
-    for k in length.keys():
-        dic_new[k]=int((length[k]-minvalue)/factor)
-    inv_length=invert_dict(dic_new)
-    print inv_length.keys(),factor,minvalue
-    ks=inv_length.keys()
-    ks.sort()
-    for k in range(0,len(inv_length.keys())-1):
-        inv_length[ks[k]]=inv_length[ks[k]]+inv_length[ks[k+1]]
-    cubit.cmd('set info on')
-    cubit.cmd('set echo on')
-    cubit.cmd('set journal on')
-    return factor,minvalue,inv_length
-
-
-def merge_node_4(n1,n2,n3,n4):
-    factor,minvalue,inv_length=prepare_equivalence_4(n1,n2,n3,n4)
-    
-    for k in inv_length.keys()[:-1]:
-        if len(inv_length[k]) > 0:
-            cmd='equivalence node '+' '.join(' '.join(str(n) for n in x) for x in inv_length[k])+' tolerance '+str(k*factor+minvalue/2.)
-            cubit.cmd(cmd)
-            print 'equivalence '+str(len(inv_length[k]))+' couples of nodes -  tolerance '+str(k*factor+minvalue/2.)
-
-
-
-
-
-    
\ No newline at end of file

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/functions.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/functions.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/functions.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,131 +0,0 @@
-#!python
-
-# Pg , functions Read_fault_nodes and nodes_coords_fault_open has been modified
-#  to read properly fault_file_xxx.dat .
-# Convention : Side up   = side 2   (+)
-#            : Side down = side 1 (-)
-import os
-
-def read_nodes_coord_file(filein):
-    file = open(filein,'r')
-    nnodes = file.readline()
-    nodxyzlist = file.readlines()
-    x=[]
-    y=[]
-    z=[]
-    node=[]
-    for nodxyz in nodxyzlist:
-        nodxyzsplit = nodxyz.split()
-        node.append(int(nodxyzsplit[0]))
-        x.append(float(nodxyzsplit[1]))
-        y.append(float(nodxyzsplit[2]))
-        z.append(float(nodxyzsplit[3]))
-    file.close() 
-    return node,x,y,z
-
-def read_fault_nodes(filein):
-    file = open(filein,'r')
-    nodes_side1_side2 = file.readline()
-    nside_du = nodes_side1_side2.split()
-    nnodes_d = int(nside_du[0])
-    nnodes_u = int(nside_du[1])
-    nodes_u=[]
-    nodes_d=[]
-   
-    for i in range(nnodes_d):
-        hnodes = file.readline()
-        hnodesplit = hnodes.split()
-        nodes_d.append(int(hnodesplit[1]))
-        nodes_d.append(int(hnodesplit[2]))
-        nodes_d.append(int(hnodesplit[3]))
-        nodes_d.append(int(hnodesplit[4]))
-
-    for i in range(nnodes_u):
-        hnodes = file.readline()
-        hnodesplit = hnodes.split()
-        nodes_u.append(int(hnodesplit[1]))
-        nodes_u.append(int(hnodesplit[2]))
-        nodes_u.append(int(hnodesplit[3]))
-        nodes_u.append(int(hnodesplit[4]))
-
-    nodes_d  = set(nodes_d)     # save unique fault nodes side u
-    nodes_u  = set(nodes_u)     # save unique fault nodes side d
-    ncommond = nodes_u&nodes_d  # glue nodes . 
-    nodes_d  = nodes_d^ncommond # saving only split nodes side d
-    nodes_u  = nodes_u^ncommond # saving only split nodes side u
-    file.close()
-    return nodes_u,nodes_d
-
-# INPUTS :
-#file_nodes_coord = 'MESH/nodes_coords_file'
-#fault_file =       'MESH/fault_file_1.dat'
-# OUTPUTS :
-#name_out = 'MESH/nodes_coords_file_open_fault'
-#fsideu   = 'MESH/fault_sideu.dat'
-#fsided   = 'MESH/fault_sided.dat'
-#nodes_coords_fault_open(file_nodes_coord,fault_file,name_out,fsideu,fsided,delta)
-def nodes_coords_fault_open(file_nodes_coord,fault_file,name_out,fsideUP,fsideDW,delta): 
-    x=[]
-    y=[]
-    z=[]
-    node=[]
-    nodes_u=[]
-    nodes_d=[]
-    txt = ''
-    txt_fault = ''
-    output_file = open(name_out,'w')
-    fsideu = open(fsideUP,'w')
-    fsided = open(fsideDW,'w')
-    node,x,y,z = read_nodes_coord_file(file_nodes_coord)
-    output_file.write('%10i\n' % len(node))
-    node_u,node_d = read_fault_nodes(fault_file)
-    
-    for i in range(len(node)):
-        if node[i] in node_u:
-             z[i] = z[i] + delta/2.0
-            # x[i] = x[i] + delta/2.0
-             print "node_u",node[i]
-             txt_fault=('%10i %20f %20f %20f\n') % (node[i],x[i],y[i],z[i])
-             fsideu.write(txt_fault)
-        if node[i] in node_d:
-             z[i] = z[i] - delta/2.0
-            # x[i] = x[i] - delta/2.0
-             print "node_d",node[i]
-             txt_fault=('%10i %20f %20f %20f\n') % (node[i],x[i],y[i],z[i])
-             fsided.write(txt_fault)
-        txt=('%10i %20f %20f %20f\n') % (node[i],x[i],y[i],z[i])
-        output_file.write(txt)
-
-    output_file.close()
-    fsideu.close()
-    fsided.close()
-    return
-
-
-delta = 0.5 # WARNING: Make sure that this delta is smaller than FAULT_GAP_TOLERANCE 
-            # defined in decompose_mesh_SCOTH/fault_scotch.f90 (usually FAULT_GAP_TOLERANCE=1.0d0)
-            # and larger than SMALLVAL_TOL defined in constants.h (usually SMALLVAL_TOL=1.d-10*dabs(UTM_X_MAX - UTM_X_MIN))
-
-def m2km():
-   name_in = 'MESH/nodes_coords_file'
-   name_out = 'MESH/nodes_coords_file'
-   txt =''
-   km = 1000
-   input_file  = open(name_in,'r')
-   nnodes      = input_file.readline()
-   nodes_list  = input_file.readlines()
-   input_file.close()
-   output_file = open(name_out,'w')
-   nodes_num   = int(nnodes)
-   output_file.write('%10i\n' % nodes_num)
-   nodes       = []
-   for node in nodes_list:
-       nodes   = node.split()
-       node_id = int(nodes[0])
-       x= float(nodes[1])*km
-       y= float(nodes[2])*km
-       z= float(nodes[3])*km
-       txt=('%10i %20f %20f %20f\n') % (node_id,x,y,z)
-       output_file.write(txt)
-   output_file.close()
-   return

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/LatLongUTMconversion.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/LatLongUTMconversion.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/LatLongUTMconversion.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,211 @@
+#!/usr/bin/env python
+
+# Lat Long - UTM, UTM - Lat Long conversions
+
+from math import pi, sin, cos, tan, sqrt
+
+#LatLong- UTM conversion..h
+#definitions for lat/long to UTM and UTM to lat/lng conversions
+#include <string.h>
+
+_deg2rad = pi / 180.0
+_rad2deg = 180.0 / pi
+
+_EquatorialRadius = 2
+_eccentricitySquared = 3
+
+_ellipsoid = [
+#  id, Ellipsoid name, Equatorial Radius, square of eccentricity	
+# first once is a placeholder only, To allow array indices to match id numbers
+	[ -1, "Placeholder", 0, 0],
+	[ 1, "Airy", 6377563, 0.00667054],
+	[ 2, "Australian National", 6378160, 0.006694542],
+	[ 3, "Bessel 1841", 6377397, 0.006674372],
+	[ 4, "Bessel 1841 (Nambia] ", 6377484, 0.006674372],
+	[ 5, "Clarke 1866", 6378206, 0.006768658],
+	[ 6, "Clarke 1880", 6378249, 0.006803511],
+	[ 7, "Everest", 6377276, 0.006637847],
+	[ 8, "Fischer 1960 (Mercury] ", 6378166, 0.006693422],
+	[ 9, "Fischer 1968", 6378150, 0.006693422],
+	[ 10, "GRS 1967", 6378160, 0.006694605],
+	[ 11, "GRS 1980", 6378137, 0.00669438],
+	[ 12, "Helmert 1906", 6378200, 0.006693422],
+	[ 13, "Hough", 6378270, 0.00672267],
+	[ 14, "International", 6378388, 0.00672267],
+	[ 15, "Krassovsky", 6378245, 0.006693422],
+	[ 16, "Modified Airy", 6377340, 0.00667054],
+	[ 17, "Modified Everest", 6377304, 0.006637847],
+	[ 18, "Modified Fischer 1960", 6378155, 0.006693422],
+	[ 19, "South American 1969", 6378160, 0.006694542],
+	[ 20, "WGS 60", 6378165, 0.006693422],
+	[ 21, "WGS 66", 6378145, 0.006694542],
+	[ 22, "WGS-72", 6378135, 0.006694318],
+	[ 23, "WGS-84", 6378137, 0.00669438]
+]
+
+#Reference ellipsoids derived from Peter H. Dana's website- 
+#http://www.utexas.edu/depts/grg/gcraft/notes/datum/elist.html
+#Department of Geography, University of Texas at Austin
+#Internet: pdana at mail.utexas.edu
+#3/22/95
+
+#Source
+#Defense Mapping Agency. 1987b. DMA Technical Report: Supplement to Department of Defense World Geodetic System
+#1984 Technical Report. Part I and II. Washington, DC: Defense Mapping Agency
+
+def LLtoUTM(ReferenceEllipsoid, Lat, Long):
+#converts lat/long to UTM coords.  Equations from USGS Bulletin 1532 
+#East Longitudes are positive, West longitudes are negative. 
+#North latitudes are positive, South latitudes are negative
+#Lat and Long are in decimal degrees
+#Written by Chuck Gantz- chuck.gantz at globalstar.com
+
+    a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
+    eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
+    k0 = 0.9996
+
+#Make sure the longitude is between -180.00 .. 179.9
+    LongTemp = (Long+180)-int((Long+180)/360)*360-180 # -180.00 .. 179.9
+
+    LatRad = Lat*_deg2rad
+    LongRad = LongTemp*_deg2rad
+
+    ZoneNumber = int((LongTemp + 180)/6) + 1
+  
+    if Lat >= 56.0 and Lat < 64.0 and LongTemp >= 3.0 and LongTemp < 12.0:
+        ZoneNumber = 32
+
+    # Special zones for Svalbard
+    if Lat >= 72.0 and Lat < 84.0:
+        if  LongTemp >= 0.0  and LongTemp <  9.0:ZoneNumber = 31
+        elif LongTemp >= 9.0  and LongTemp < 21.0: ZoneNumber = 33
+        elif LongTemp >= 21.0 and LongTemp < 33.0: ZoneNumber = 35
+        elif LongTemp >= 33.0 and LongTemp < 42.0: ZoneNumber = 37
+
+    LongOrigin = (ZoneNumber - 1)*6 - 180 + 3 #+3 puts origin in middle of zone
+    LongOriginRad = LongOrigin * _deg2rad
+
+    #compute the UTM Zone from the latitude and longitude
+    UTMZone = "%d%c" % (ZoneNumber, _UTMLetterDesignator(Lat))
+
+    eccPrimeSquared = (eccSquared)/(1-eccSquared)
+    N = a/sqrt(1-eccSquared*sin(LatRad)*sin(LatRad))
+    T = tan(LatRad)*tan(LatRad)
+    C = eccPrimeSquared*cos(LatRad)*cos(LatRad)
+    A = cos(LatRad)*(LongRad-LongOriginRad)
+
+    M = a*((1
+            - eccSquared/4
+            - 3*eccSquared*eccSquared/64
+            - 5*eccSquared*eccSquared*eccSquared/256)*LatRad 
+           - (3*eccSquared/8
+              + 3*eccSquared*eccSquared/32
+              + 45*eccSquared*eccSquared*eccSquared/1024)*sin(2*LatRad)
+           + (15*eccSquared*eccSquared/256 + 45*eccSquared*eccSquared*eccSquared/1024)*sin(4*LatRad) 
+           - (35*eccSquared*eccSquared*eccSquared/3072)*sin(6*LatRad))
+    
+    UTMEasting = (k0*N*(A+(1-T+C)*A*A*A/6
+                        + (5-18*T+T*T+72*C-58*eccPrimeSquared)*A*A*A*A*A/120)
+                  + 500000.0)
+
+    UTMNorthing = (k0*(M+N*tan(LatRad)*(A*A/2+(5-T+9*C+4*C*C)*A*A*A*A/24
+                                        + (61
+                                           -58*T
+                                           +T*T
+                                           +600*C
+                                           -330*eccPrimeSquared)*A*A*A*A*A*A/720)))
+
+    if Lat < 0:
+        UTMNorthing = UTMNorthing + 10000000.0; #10000000 meter offset for southern hemisphere
+    return (UTMZone, UTMEasting, UTMNorthing)
+
+
+def _UTMLetterDesignator(Lat):
+#This routine determines the correct UTM letter designator for the given latitude
+#returns 'Z' if latitude is outside the UTM limits of 84N to 80S
+#Written by Chuck Gantz- chuck.gantz at globalstar.com
+
+    if 84 >= Lat >= 72: return 'X'
+    elif 72 > Lat >= 64: return 'W'
+    elif 64 > Lat >= 56: return 'V'
+    elif 56 > Lat >= 48: return 'U'
+    elif 48 > Lat >= 40: return 'T'
+    elif 40 > Lat >= 32: return 'S'
+    elif 32 > Lat >= 24: return 'R'
+    elif 24 > Lat >= 16: return 'Q'
+    elif 16 > Lat >= 8: return 'P'
+    elif  8 > Lat >= 0: return 'N'
+    elif  0 > Lat >= -8: return 'M'
+    elif -8> Lat >= -16: return 'L'
+    elif -16 > Lat >= -24: return 'K'
+    elif -24 > Lat >= -32: return 'J'
+    elif -32 > Lat >= -40: return 'H'
+    elif -40 > Lat >= -48: return 'G'
+    elif -48 > Lat >= -56: return 'F'
+    elif -56 > Lat >= -64: return 'E'
+    elif -64 > Lat >= -72: return 'D'
+    elif -72 > Lat >= -80: return 'C'
+    else: return 'Z'	# if the Latitude is outside the UTM limits
+
+#void UTMtoLL(int ReferenceEllipsoid, const double UTMNorthing, const double UTMEasting, const char* UTMZone,
+#			  double& Lat,  double& Long )
+
+def UTMtoLL(ReferenceEllipsoid, northing, easting, zone):
+
+#converts UTM coords to lat/long.  Equations from USGS Bulletin 1532 
+#East Longitudes are positive, West longitudes are negative. 
+#North latitudes are positive, South latitudes are negative
+#Lat and Long are in decimal degrees. 
+#Written by Chuck Gantz- chuck.gantz at globalstar.com
+#Converted to Python by Russ Nelson <nelson at crynwr.com>
+
+    k0 = 0.9996
+    a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
+    eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
+    e1 = (1-sqrt(1-eccSquared))/(1+sqrt(1-eccSquared))
+    #NorthernHemisphere; //1 for northern hemispher, 0 for southern
+
+    x = easting - 500000.0 #remove 500,000 meter offset for longitude
+    y = northing
+
+    ZoneLetter = zone[-1]
+    ZoneNumber = int(zone[:-1])
+    if ZoneLetter >= 'N':
+        NorthernHemisphere = 1  # point is in northern hemisphere
+    else:
+        NorthernHemisphere = 0  # point is in southern hemisphere
+        y -= 10000000.0         # remove 10,000,000 meter offset used for southern hemisphere
+
+    LongOrigin = (ZoneNumber - 1)*6 - 180 + 3  # +3 puts origin in middle of zone
+
+    eccPrimeSquared = (eccSquared)/(1-eccSquared)
+
+    M = y / k0
+    mu = M/(a*(1-eccSquared/4-3*eccSquared*eccSquared/64-5*eccSquared*eccSquared*eccSquared/256))
+
+    phi1Rad = (mu + (3*e1/2-27*e1*e1*e1/32)*sin(2*mu) 
+               + (21*e1*e1/16-55*e1*e1*e1*e1/32)*sin(4*mu)
+               +(151*e1*e1*e1/96)*sin(6*mu))
+    phi1 = phi1Rad*_rad2deg;
+
+    N1 = a/sqrt(1-eccSquared*sin(phi1Rad)*sin(phi1Rad))
+    T1 = tan(phi1Rad)*tan(phi1Rad)
+    C1 = eccPrimeSquared*cos(phi1Rad)*cos(phi1Rad)
+    R1 = a*(1-eccSquared)/pow(1-eccSquared*sin(phi1Rad)*sin(phi1Rad), 1.5)
+    D = x/(N1*k0)
+
+    Lat = phi1Rad - (N1*tan(phi1Rad)/R1)*(D*D/2-(5+3*T1+10*C1-4*C1*C1-9*eccPrimeSquared)*D*D*D*D/24
+                                          +(61+90*T1+298*C1+45*T1*T1-252*eccPrimeSquared-3*C1*C1)*D*D*D*D*D*D/720)
+    Lat = Lat * _rad2deg
+
+    Long = (D-(1+2*T1+C1)*D*D*D/6+(5-2*C1+28*T1-3*C1*C1+8*eccPrimeSquared+24*T1*T1)
+            *D*D*D*D*D/120)/cos(phi1Rad)
+    Long = LongOrigin + Long * _rad2deg
+    return (Lat, Long)
+
+if __name__ == '__main__':
+    (z, e, n) = LLtoUTM(23, 45.00, -75.00)
+    print z, e, n
+    (lat, lon) = UTMtoLL(23, n, e, z)
+    print lat, lon
+

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/__init__.py
===================================================================
Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/boundary_definition.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/boundary_definition.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/boundary_definition.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,531 @@
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+
+def list2str(l):
+    if not isinstance(l,list): l=list(l)
+    return ' '.join(str(x) for x in l)
+
+
+def map_boundary(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1):
+    ymin=[]
+    xmax=[]
+    xmin=[]
+    ymax=[]
+    listfull=[]
+    #
+    for ix in range(cpuxmin,cpuxmax):
+        for iy in range(cpuymin,cpuymax):
+            ip=iy*cpux+ix
+            if ix == cpuxmin:
+                xmin.append(ip)
+            if ix == cpuxmax-1:
+                xmax.append(ip)
+            if iy == cpuymin:
+                ymin.append(ip)
+            if iy == cpuymax-1:
+                ymax.append(ip)
+                #
+            listfull.append(ip)
+    return xmin,xmax,ymin,ymax,listfull
+
+
+def define_4side_lateral_surfaces():
+    list_vol=cubit.parse_cubit_list("volume","all")
+    surf_xmin=[]
+    surf_ymin=[]
+    surf_xmax=[]
+    surf_ymax=[]
+    for id_vol in list_vol:
+        surf_vertical=[]
+        xsurf=[]
+        ysurf=[]
+        tres=0.3
+        lsurf=cubit.get_relatives("volume",id_vol,"surface")
+        for k in lsurf:
+            normal=cubit.get_surface_normal(k)
+            center_point = cubit.get_center_point("surface", k)
+            if normal[2] >= -1*tres and normal[2] <= tres:
+                surf_vertical.append(k)
+                xsurf.append(center_point[0])
+                ysurf.append(center_point[1])
+        surf_xmin.append(surf_vertical[xsurf.index(min(xsurf))])
+        surf_ymin.append(surf_vertical[ysurf.index(min(ysurf))])
+        surf_xmax.append(surf_vertical[xsurf.index(max(xsurf))])
+        surf_ymax.append(surf_vertical[ysurf.index(max(ysurf))])
+    return surf_xmin,surf_ymin,surf_xmax,surf_ymax
+
+
+
+
+def lateral_boundary_are_absorbing(ip=0,cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1):
+    #
+    xmin,ymin,xmax,ymax=define_4side_lateral_surfaces()
+    ip_xmin,ip_xmax,ip_ymin,ip_ymax,listfull=map_boundary(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
+    if  not isinstance(ip_xmin, list): ip_xmin=[ip_xmin]
+    if  not isinstance(ip_ymin, list): ip_ymin=[ip_ymin]
+    if  not isinstance(ip_xmax, list): ip_xmax=[ip_xmax]
+    if  not isinstance(ip_ymax, list): ip_ymax=[ip_ymax]
+    #
+    abs_xmin=[]
+    abs_ymin=[]
+    abs_xmax=[]
+    abs_ymax=[]
+    #
+    if ip in ip_xmin: 
+        abs_xmin=xmin
+        print 'proc ',ip,' is has absorbing boundary xmin'
+    if ip in ip_ymin:     
+        print 'proc ',ip,' is has absorbing boundary ymin'
+        abs_ymin=ymin
+    if ip in ip_xmax:     
+        print 'proc ',ip,' is has absorbing boundary xmax'
+        abs_xmax=xmax
+    if ip in ip_ymax:     
+        print 'proc ',ip,' is has absorbing boundary ymax'
+        abs_ymax=ymax
+    return abs_xmin,abs_xmax,abs_ymin,abs_ymax
+
+
+def define_surf(ip=0,cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1):
+    """
+    define the surfaces defining the boundaries of the volume
+    """
+    #
+    from sets import Set
+    def product(*args, **kwds):
+        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
+        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
+        pools = map(tuple, args) * kwds.get('repeat', 1)
+        result = [[]]
+        for pool in pools:
+            result = [x+[y] for x in result for y in pool]
+        return result
+    absorbing_surf=[]
+    xmin=[]
+    xmax=[]
+    ymin=[]
+    ymax=[]
+    #
+    top_surf=[]
+    bottom_surf=[]
+    list_vol=cubit.parse_cubit_list("volume","all")
+    zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
+    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...    
+    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
+    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
+    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
+    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
+    list_surf=cubit.parse_cubit_list("surface","all")
+    lv=[]
+    for k in list_surf:
+        sbox=cubit.get_bounding_box('surface',k)
+        if zmax_box == 0 and sbox[7] == 0:
+             dzmax=0
+        elif zmax_box == 0 or sbox[7] == 0:
+            dzmax=abs(sbox[7] - zmax_box)
+        else:
+            dzmax=abs(sbox[7] - zmax_box)/max(abs(sbox[7]),abs(zmax_box))
+        if zmin_box == 0 and sbox[6] == 0:
+             dzmin=0
+        elif zmin_box == 0 or sbox[6] == 0:
+            dzmin=abs(sbox[6] - zmin_box)                                            
+        else:                                                    
+            dzmin=abs(sbox[6] - zmin_box)/max(abs(sbox[6]),abs(zmin_box))
+        normal=cubit.get_surface_normal(k)
+        zn=normal[2]
+        if dzmax <= 0.1 and zn > 0.4:
+            top_surf.append(k)
+            list_vertex=cubit.get_relatives('surface',k,'vertex')
+            for v in list_vertex:
+                valence=cubit.get_valence(v)
+                if valence <= 4: #valence 3 is a corner, 4 is a vertex between 2 volumes, > 4 is a vertex not in the boundaries
+                    lv.append(v)
+        elif dzmin <= 0.001 and zn < -0.7:
+            bottom_surf.append(k)
+    lp=[]
+    combs=product(lv,lv)
+    for comb in combs:
+        v1=comb[0]
+        v2=comb[1]
+        c=Set(cubit.get_relatives("vertex",v1,"curve")) & Set(cubit.get_relatives("vertex",v2,"curve"))
+        if len(c) == 1:
+            p=cubit.get_center_point("curve",list(c)[0])
+            lp.append(p)
+    for k in list_surf: 
+        center_point = cubit.get_center_point("surface", k)
+        for p in lp:
+            if abs((center_point[0] - p[0])/p[0]) <= 0.001 and abs((center_point[1] - p[1])/p[1]) <= 0.001:
+                absorbing_surf.append(k)
+                break
+    #
+    four_side=True
+    if four_side:
+        xmin,ymin,xmax,ymax=define_4side_lateral_surfaces()
+        abs_xmin,abs_xmax,abs_ymin,abs_ymax=lateral_boundary_are_absorbing(ip,cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
+
+    return absorbing_surf,abs_xmin,abs_xmax,abs_ymin,abs_ymax,top_surf,bottom_surf,xmin,ymin,xmax,ymax
+
+
+
+def define_block():
+    list_vol=cubit.parse_cubit_list("volume","all")
+    init_n_vol=len(list_vol)
+    list_name=map(lambda x: 'vol'+x,map(str,list_vol))
+    return list_vol,list_name
+
+def build_block(vol_list,name,id_0=1):
+    #
+    from sets import Set
+    #
+    block_list=cubit.get_block_id_list()
+    if len(block_list) > 0:
+        id_block=max(max(block_list),2)+id_0
+    else:
+        id_block=2+id_0
+    for v,n in zip(vol_list,name):
+        id_block+=1
+        v_other=Set(vol_list)-Set([v])
+        #command= 'block '+str(id_block)+' hex in node in vol '+str(v)+' except hex in vol '+str(list(v_other))
+        command= 'block '+str(id_block)+' hex in vol '+str(v)+' except hex in vol '+str(list(v_other))
+        print command
+        command = command.replace("["," ").replace("]"," ")
+        cubit.cmd(command) 
+        command = "block "+str(id_block)+" name '"+n+"'"
+        cubit.cmd(command)
+
+def build_block_side(surf_list,name,obj='surface',id_0=1):
+    id_nodeset=cubit.get_next_nodeset_id()
+    id_block=id_0
+    if obj == 'hex':
+        txt='hex in node in surface'
+        txt1='block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
+        txt2="block "+str(id_block)+" name '"+name+"'"
+        txt1=txt1.replace("["," ").replace("]"," ")
+        cubit.cmd(txt1)
+        cubit.cmd(txt2)
+    elif obj == 'node':
+        txt=obj+' in surface'
+        txt1= 'nodeset '+str(id_nodeset)+ ' '+ txt +' '+str(list(surf_list))
+        txt1 = txt1.replace("["," ").replace("]"," ")
+        txt2 = "nodeset "+str(id_nodeset)+" name '"+name+"'"
+        cubit.cmd(txt1)
+        cubit.cmd(txt2)
+    elif obj == 'face' or obj == 'edge':
+        txt=obj+' in surface'
+        txt1= 'block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
+        txt1 = txt1.replace("["," ").replace("]"," ")
+        txt2 = "block "+str(id_block)+" name '"+name+"'"
+        cubit.cmd(txt1)
+        cubit.cmd(txt2)
+    else:
+        txt1=''
+        txt2="block "+str(id_block)+" name "+name+"_notsupported (only hex,face,edge,node)"
+        try:
+            cubit.cmd('comment "'+txt1+'"')
+            cubit.cmd('comment "'+txt2+'"')
+        except:
+            pass
+
+def define_bc(*args,**keys):
+    id_0=1
+    #
+    #
+    parallel=keys.get('parallel',True)
+    closed=keys.get('closed',False)
+    ip=keys.get("iproc",0)
+    cpuxmin=keys.get("cpuxmin",0)
+    cpuymin=keys.get("cpuymin",0)
+    cpux=keys.get("cpux",1)
+    cpuy=keys.get("cpuy",1)
+    cpuxmax=keys.get("cpuxmax",cpux)
+    cpuymax=keys.get("cpuymax",cpuy)
+    #
+    if parallel:
+        absorbing_surf,abs_xmin,abs_xmax,abs_ymin,abs_ymax,top_surf,bottom_surf,xmin,ymin,xmax,ymax=define_surf(ip=ip,cpuxmin=cpuxmin,cpuxmax=cpuxmax,cpuymin=cpuymin,cpuymax=cpuymax,cpux=cpux,cpuy=cpuy)
+        #
+        #id_side=cubit.get_next_block_id()
+        #try:
+        #    entities=args[0]
+        #except:
+        #    entities=['face']
+        #for entity in entities:
+        #    build_block_side(top_surf,entity+'_topo',obj=entity,id_0=1) #topo is block 1 so id_0=1
+        #    build_block_side(bottom_surf,entity+'_abs_bottom',obj=entity,id_0=2)
+        #    build_block_side(xmin,entity+'_xmin',obj=entity,id_0=3)
+        #    build_block_side(ymin,entity+'_ymin',obj=entity,id_0=4)
+        #    build_block_side(xmax,entity+'_xmax',obj=entity,id_0=5)
+        #    build_block_side(ymax,entity+'_ymax',obj=entity,id_0=6)
+        #     
+        id_0=cubit.get_next_block_id()
+        v_list,name_list=define_block()
+        build_block(v_list,name_list,id_0)
+        #
+    elif closed:
+        surf=define_absorbing_surf_sphere()
+        v_list,name_list=define_block()
+        build_block(v_list,name_list,id_0)
+        entities=args[0]
+        id_side=1
+        for entity in entities:
+            build_block_side(surf,entity+'_closedvol',obj=entity,id_0=id_side)
+            id_side=id_side+1
+            
+#########################################
+
+
+def extract_bottom_curves(surf_xmin,surf_ymin,surf_xmax,surf_ymax):
+    curve_xmin=[]
+    curve_ymin=[]
+    curve_xmax=[]
+    curve_ymax=[]
+    from sets import Set #UPGRADE.... the sets module is deprecated after python 2.6
+    for s in surf_xmin:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for lc in lcs:
+            curve_xmin.append(lc)
+    for s in surf_xmax:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for lc in lcs:
+            curve_xmax.append(lc)
+    for s in surf_ymin:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for lc in lcs:
+            curve_ymin.append(lc)
+    for s in surf_ymax:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for lc in lcs:
+            curve_ymax.append(lc)
+    curve_xmin=list(Set(curve_xmin))
+    curve_ymin=list(Set(curve_ymin))
+    curve_xmax=list(Set(curve_xmax))
+    curve_ymax=list(Set(curve_ymax))
+    curve_bottom_xmin=select_bottom_curve(curve_xmin)
+    curve_bottom_ymin=select_bottom_curve(curve_ymin)
+    curve_bottom_xmax=select_bottom_curve(curve_xmax)
+    curve_bottom_ymax=select_bottom_curve(curve_ymax)
+    #
+    return curve_bottom_xmin,curve_bottom_ymin,curve_bottom_xmax,curve_bottom_ymax
+
+def select_bottom_curve(lc):
+    z=[]
+    for l in lc:
+        center_point = cubit.get_center_point("curve", l)
+        z.append(center_point[2])
+    result=zip(z,lc)
+    result.sort()
+    return result[0][1]
+
+
+def get_ordered_node_surf(lsurface,icurve):
+    if not isinstance(lsurface,str): 
+        lsurf=list2str(lsurface)
+    #
+    if not isinstance(icurve,str): 
+        icurvestr=str(icurve)
+    orient_nodes_surf=[]
+    #
+    cubit.cmd('del group sl')
+    cubit.cmd("group 'sl' add node in surf "+lsurf)
+    group1 = cubit.get_id_from_name("sl")
+    nodes_ls =list(cubit.get_group_nodes(group1))
+    nnode=len(nodes_ls)
+    #
+    orient=[]
+    cubit.cmd('del group n1')
+    cubit.cmd("group 'n1' add node in curve "+icurvestr)
+    x=cubit.get_bounding_box('curve', icurve)
+    if x[2]>x[5]:
+        idx=0
+    else:
+        idx=1
+    group1 = cubit.get_id_from_name("n1")
+    nodes1 = list(cubit.get_group_nodes(group1))
+    for n in nodes1:
+        v = cubit.get_nodal_coordinates(n)
+        orient.append(v[idx])
+    result=zip(orient,nodes1)
+    result.sort()
+    nodes2=[c[1] for c in result]
+    for n in nodes2:
+        try:
+            nodes_ls.remove(n)
+        except:
+            pass             
+    orient_nodes_surf=orient_nodes_surf+nodes2
+    #
+    while len(orient_nodes_surf) < nnode:
+        cubit.cmd('del group n1')
+        cubit.cmd("group 'n1' add node in edge in node "+str(nodes2).replace('[',' ').replace(']',' '))
+        group1 = cubit.get_id_from_name("n1")
+        nodes1 = list(cubit.get_group_nodes(group1))
+        orient=[]
+        nd=[]
+        for n in nodes1:
+            if n in nodes_ls:
+                v = cubit.get_nodal_coordinates(n)
+                orient.append(v[idx])
+                nd.append(n)
+        result=zip(orient,nd)
+        result.sort()
+        nodes2=[c[1] for c in result]
+        for n in nodes2:
+            try:
+                nodes_ls.remove(n)
+            except:
+                pass
+        orient_nodes_surf=orient_nodes_surf+nodes2
+    #get the vertical curve
+    curve_vertical=[]
+    for s in lsurface:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for l in lcs:
+            x=cubit.get_bounding_box('curve', l)
+            length=[(x[2],1),(x[5],2),(x[8],3)]
+            length.sort()
+            if length[-1][1] == 3:
+                curve_vertical.append(l)
+    #
+    icurve=list2str(curve_vertical)
+    cubit.cmd('del group curve_vertical')
+    cubit.cmd("group 'curve_vertical' add node in curve "+icurve)
+    group1 = cubit.get_id_from_name('curve_vertical')
+    nodes_curve = list(cubit.get_group_nodes(group1))
+    for n in nodes_curve:
+        try:
+            orient_nodes_surf.remove(n)
+        except:
+            pass
+    #
+    return nodes_curve,orient_nodes_surf
+
+
+
+def check_bc(iproc,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax):
+    """
+    boundary=check_bc(iproc,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
+    #
+    set the boundary condition during the collecting phase and group the nodes of the vertical surface in groups for the merging phase
+    iproc is the value of the processor 
+    xmin,ymin,ymax,ymin are the list of iproc that have at least one absorbing boundary condition
+    """
+    #
+    absorbing_surf,abs_xmin,abs_xmax,abs_ymin,abs_ymax,top_surf,bottom_surf,surf_xmin,surf_ymin,surf_xmax,surf_ymax=define_surf(ip=iproc,cpuxmin=cpuxmin,cpuxmax=cpuxmax,cpuymin=cpuymin,cpuymax=cpuymax,cpux=cpux,cpuy=cpuy)
+    curve_bottom_xmin,curve_bottom_ymin,curve_bottom_xmax,curve_bottom_ymax=extract_bottom_curves(surf_xmin,surf_ymin,surf_xmax,surf_ymax)
+    print absorbing_surf,abs_xmin,abs_xmax,abs_ymin,abs_ymax,top_surf,bottom_surf,surf_xmin,surf_ymin,surf_xmax,surf_ymax
+    #
+    #
+    #
+    from sets import Set #UPGRADE.... the sets module is deprecated after python 2.6
+    
+    cubit.cmd('set info off')
+    cubit.cmd('set echo off')
+    nodes_curve_ymax,orient_nodes_surf_ymax=get_ordered_node_surf(surf_ymax,curve_bottom_ymax)
+    nodes_curve_xmax,orient_nodes_surf_xmax=get_ordered_node_surf(surf_xmax,curve_bottom_xmax)
+    nodes_curve_ymin,orient_nodes_surf_ymin=get_ordered_node_surf(surf_ymin,curve_bottom_ymin)
+    nodes_curve_xmin,orient_nodes_surf_xmin=get_ordered_node_surf(surf_xmin,curve_bottom_xmin)
+    c_xminymin=Set(nodes_curve_xmin).intersection(nodes_curve_ymin)
+    c_xminymax=Set(nodes_curve_xmin).intersection(nodes_curve_ymax)
+    c_xmaxymin=Set(nodes_curve_xmax).intersection(nodes_curve_ymin)
+    c_xmaxymax=Set(nodes_curve_xmax).intersection(nodes_curve_ymax)
+    cubit.cmd('set info on')
+    cubit.cmd('set echo on')
+    
+    
+    #
+    orient=[]
+    nd=[]
+    for n in c_xminymin:
+        v = cubit.get_nodal_coordinates(n)
+        orient.append(v[2])
+        nd.append(n)
+    result=zip(orient,nd)
+    result.sort()
+    c_xminymin=[c[1] for c in result]
+    #
+    orient=[]
+    nd=[]    
+    for n in c_xminymax:
+        v = cubit.get_nodal_coordinates(n)
+        orient.append(v[2])
+        nd.append(n)
+    result=zip(orient,nd)
+    result.sort()
+    c_xminymax=[c[1] for c in result]
+    #
+    orient=[]
+    nd=[]
+    for n in c_xmaxymin:
+        v = cubit.get_nodal_coordinates(n)
+        orient.append(v[2])
+        nd.append(n)
+    result=zip(orient,nd)
+    result.sort()
+    c_xmaxymin=[c[1] for c in result]
+    #
+    orient=[]
+    nd=[]
+    for n in c_xmaxymax:
+        v = cubit.get_nodal_coordinates(n)
+        orient.append(v[2])
+        nd.append(n)
+    result=zip(orient,nd)
+    result.sort()
+    c_xmaxymax=[c[1] for c in result]
+    #
+    boundary={}
+    boundary['id']=iproc
+    #
+    boundary['nodes_surf_xmin']=orient_nodes_surf_xmin
+    boundary['nodes_surf_xmax']=orient_nodes_surf_xmax
+    boundary['nodes_surf_ymin']=orient_nodes_surf_ymin
+    boundary['nodes_surf_ymax']=orient_nodes_surf_ymax
+    #
+    boundary['node_curve_xminymin']=c_xminymin
+    boundary['node_curve_xminymax']=c_xminymax
+    boundary['node_curve_xmaxymin']=c_xmaxymin
+    boundary['node_curve_xmaxymax']=c_xmaxymax
+    #
+    #
+    #
+    entities=['face']
+    #
+    for entity in entities:
+        if len(abs_xmin) != 0:
+            refname=entity+'_abs_xmin'
+            build_block_side(abs_xmin,refname,obj=entity,id_0=1003)
+        #
+        if len(abs_ymin) != 0:
+            refname=entity+'_abs_ymin'
+            build_block_side(abs_ymin,refname,obj=entity,id_0=1004)
+        #
+        if len(abs_xmax) != 0:
+            refname=entity+'_abs_xmax'
+            build_block_side(abs_xmax,refname,obj=entity,id_0=1005)
+        #
+        if len(abs_ymax) != 0:
+            refname=entity+'_abs_ymax'
+            build_block_side(abs_ymax,refname,obj=entity,id_0=1006)
+        ##
+        refname=entity+'_topo'
+        block=3 #change here..... must be 1 @@@@@@@@@
+        ty=None
+        ty=cubit.get_block_element_type(block)
+        if ty != 'HEX8': cubit.cmd('del block '+str(block))
+        build_block_side(top_surf,refname,obj=entity,id_0=1001)
+        #
+        refname=entity+'_bottom'
+        block=4 #change here..... must be 2 @@@@@@@@
+        ty=None
+        ty=cubit.get_block_element_type(block)
+        if ty != 'HEX8': cubit.cmd('del block '+str(block))
+        build_block_side(bottom_surf,refname,obj=entity,id_0=1002)
+    #
+    #
+    return boundary
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/cubit2specfem3d.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/cubit2specfem3d.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/cubit2specfem3d.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,794 @@
+#!python
+#############################################################################
+# cubit2specfem3d.py                                                           #
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+#
+#for a complete definition of the format of the mesh in SPECFEM3D check the manual (http://www.geodynamics.org/cig/software/specfem3d):
+#
+#USAGE 
+#
+#############################################################################
+#PREREQUISITE
+#The mesh must be prepared 
+#   automatically using the module boundary_definition (see boundary_definition.py for more information)
+#or 
+#   manually following the convention:
+#     - each material should have a block defined by material domain_flag (acoustic/elastic/poroelastic) name,flag of the material (integer),p velocity 
+#       (or the full description: name, flag, vp, vs, rho, Q ... if not present these last 3 parameters will be interpolated by module mat_parameter)
+#     - each mesh should have the block definition for the face on the free_surface (topography), 
+#       the name of this block must be 'face_topo' or you can change the default name in mesh.topo defined in profile.
+#     - each mesh should have the block definition for the faces on the absorbing boundaries, 
+#       one block for each surface with x=Xmin,x=Xmax,y=Ymin,y=Ymax and z=bottom. The names of the blocks should contain the strings "xmin,xmax,ymin,ymax,bottom"
+#
+#############################################################################
+#RUN
+#In a python script or in the cubit python tab call:
+#           
+#           export2SPECFEM3D(path_exporting_mesh_SPECFEM3D) 
+#
+#the module creates a python class for the mesh: ex. profile=mesh()
+#and it export the files of the mesh needed by the partitioner of SPECFEM3D
+#
+#############################################################################
+#OUTPUT
+#The default output are 11 ASCII files:
+#__________________________________________________________________________________________
+#mesh_name='mesh_file' -> the file that contains the connectity of the all mesh
+#    format:
+#        number of elements
+#        id_elements id_node1 id_node2 id_node3 id_node4 id_node5 id_node6 id_node7 id_node8
+#        .....
+#
+#__________________________________________________________________________________________        
+##nodecoord_name='nodes_coords_file' -> the file that contains the coordinates of the nodes of the all mesh
+#    format:
+#        number of nodes
+#        id_node x_coordinate y_coordinate z_coordinate
+#        .....
+#
+#__________________________________________________________________________________________        
+##material_name='materials_file' -> the file that contains the material flag of the elements
+#    format:
+#        id_element flag
+#        .....
+#
+#__________________________________________________________________________________________        
+##nummaterial_name='nummaterial_velocity_file' -> table of the material properties
+#    format:
+#        #material_domain_id #material_id #rho #vp #vs #Q_mu #anisotropy
+#        .....
+#        #material_domain_id 'tomography' file_name #for interpolation with tomography
+#        .....
+#        #material_domain_id 'interface' file_name flag_for_the_gll_below_the_interface flag_for_the_gll_above_the_interface #for interpolation with interface
+#__________________________________________________________________________________________        
+##absname='absorbing_surface_file' -> this file contains all the face in all the absorbing  boundaries
+##absname_local='absorbing_surface_file'+'_xmin' -> this file contains all the face in the absorbing  boundary defined by x=Xmin
+##absname_local='absorbing_surface_file'+'_xmax' -> this file contains all the face in the absorbing  boundary defined by x=Xmax
+##absname_local='absorbing_surface_file'+'_ymin' -> this file contains all the face in the absorbing  boundary defined by y=Ymin
+##absname_local='absorbing_surface_file'+'_ymax' -> this file contains all the face in the absorbing  boundary defined by y=Ymax
+##absname_local='absorbing_surface_file'+'_bottom' -> this file contains all the face in the absorbing  boundary defined by z=bottom
+#    format:
+#        number of faces
+#        id_(element containg the face) id_node1_face id_node2_face id_node3_face id_node4_face
+#        ....
+#
+#__________________________________________________________________________________________
+##freename='free_surface_file' -> file with the hex on the free surface (usually the topography)
+#    format:
+#        number of faces
+#        id_(element containg the face) id_node1_face id_node2_face id_node3_face id_node4_face
+#
+#__________________________________________________________________________________________
+#__________________________________________________________________________________________
+##surface='*_surface_file' -> file with the hex on any surface (define by the word 'surface' in the name of the block, ex: moho_surface)
+# optional surfaces, e.g. moho_surface
+# should be created like e.g.:
+#  > block 10 face in surface 2
+#  > block 10 name 'moho_surface'
+#
+#
+#    format:
+#        number of faces
+#        id_(element containg the face) id_node1_face id_node2_face id_node3_face id_node4_face
+#
+#__________________________________________________________________________________________
+# it is possible save only one (or more) file singularly: for example if you want only the nodecoord_file call the module mesh.nodescoord_write(full path name)
+#
+#############################################################################
+
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+
+class mtools(object):
+    def __init__(self,frequency,list_surf,list_vp):
+        super(mtools, self).__init__()
+        self.frequency = frequency
+        self.list_surf = list_surf
+        self.list_vp = list_vp
+        self.ngll=5
+        self.percent_gll=0.172
+        self.point_wavelength=5
+    def __repr__(self):
+        txt='Meshing for frequency up to '+str(self.frequency)+'Hz\n'
+        for surf,vp in zip(self.list_surf,self.list_vp):
+            txt=txt+'surface '+str(surf)+', vp ='+str(vp)+'  -> size '+str(self.freq2meshsize(vp)[0])+' -> dt '+str(self.freq2meshsize(vp)[0])+'\n' 
+        return txt
+    def freq2meshsize(self,vp):
+        velocity=vp*.5
+        self.size=(1/2.5)*velocity/self.frequency*(self.ngll-1)/self.point_wavelength
+        self.dt=.4*self.size/vp*self.percent_gll
+        return self.size,self.dt
+    def mesh_it(self):
+        for surf,vp in zip(self.list_surf,self.list_vp):
+            command = "surface "+str(surf)+" size "+str(self.freq2meshsize(vp)[0])
+            cubit.cmd(command)
+            command = "surface "+str(surf)+ 'scheme pave'
+            cubit.cmd(command)
+            command = "mesh surf "+str(surf)
+            cubit.cmd(command)
+
+class block_tools():
+    def __int__(self):
+        pass
+    def create_blocks(self,mesh_entity,list_entity=None,):
+        if mesh_entity =='surface':
+            txt=' face in surface '
+        elif mesh_entity == 'curve':
+            txt=' edge in curve '
+        elif mesh_entity == 'group':
+            txt=' face in group '
+        if list_entity:
+            if not isinstance(list_entity,list):
+                list_entity=[list_entity]
+        for entity in list_entity:
+            iblock=cubit.get_next_block_id()
+            command = "block "+str(iblock)+ txt +str(entity)
+            cubit.cmd(command)
+    def material_file(self,filename):
+        matfile=open(filename,'w')
+        material=[]
+        for record in matfile:
+            mat_name,vp_str=record.split()
+            vp=float(vp_str)
+            material.append([mat_name,vp])
+        self.material=dict(material)
+    def assign_block_material(self,id_block,mat_name,vp=None):
+        try:
+            material=self.material
+        except:
+            material=None
+        cubit.cmd('block '+str(id_block)+' attribute count 2')
+        cubit.cmd('block '+str(id_block)+'  attribute index 1 '+str(id_block))
+        if material:
+            if material.has_key(mat_name):
+                cubit.cmd('block '+str(id_block)+'  attribute index 2 '+str(material[mat_name]))
+                print 'block '+str(id_block)+' - material '+mat_name+' - vp '+str(material[mat_name])+' from database'
+        elif vp:
+            cubit.cmd('block '+str(id_block)+'  attribute index 2 '+str(vp))
+            print 'block '+str(id_block)+' - material '+mat_name+' - vp '+str(vp)
+        else:
+            print 'assignment impossible: check if '+mat_name+' is in the database or specify vp'
+
+class mesh_tools(block_tools):
+    """Tools for the mesh
+    #########
+    dt,edge_dt,freq,edge_freq=seismic_resolution(edges,velocity,bins_d=None,bins_u=None,sidelist=None,ngll=5,np=8)
+        Given the velocity of a list of edges, seismic_resolution provides the minimum Dt required for the stability condition (and the corrisponding edge).
+        Furthermore, given the number of gll point in the element (ngll) and the number of GLL point for wavelength, it provide the maximum resolved frequency.
+    #########
+    length=edge_length(edge)
+        return the length of a edge
+    #########
+    edge_min,length=edge_min_length(surface)
+        given the cubit id of a surface, it return the edge with minimun length 
+    #########
+    """
+    def __int__(self):
+        pass
+    def seismic_resolution(self,edges,velocity,bins_d=None,bins_u=None,sidelist=None):
+        """
+        dt,edge_dt,freq,edge_freq=seismic_resolution(edges,velocity,bins_d=None,bins_u=None,sidelist=None,ngll=5,np=8)
+            Given the velocity of a list of edges, seismic_resolution provides the minimum Dt required for the stability condition (and the corrisponding edge).
+            Furthermore, given the number of gll point in the element (ngll) and the number of GLL point for wavelength, it provide the maximum resolved frequency.
+        """
+        ratiostore=1e10
+        dtstore=1e10
+        edgedtstore=-1
+        edgeratiostore=-1
+        for edge in edges:
+            d=self.edge_length(edge)
+            ratio=(1/2.5)*velocity/d*(self.ngll-1)/self.point_wavelength
+            dt=.4*d/velocity*self.percent_gll
+            if dt<dtstore:
+               dtstore=dt
+               edgedtstore=edge
+            if ratio < ratiostore:
+                ratiostore=ratio
+                edgeratiostore=edge
+            try:
+                for bin_d,bin_u,side in zip(bins_d,bins_u,sidelist):
+                    if ratio >= bin_d and ratio < bin_u:
+                        command = "sideset "+str(side)+" edge "+str(edge)
+                        cubit.cmd(command)
+                        break
+            except:
+                pass
+        return dtstore,edgedtstore,ratiostore,edgeratiostore
+    def edge_length(self,edge):
+        """
+        length=edge_length(edge)
+            return the length of a edge
+        """
+        from math import sqrt
+        nodes=cubit.get_connectivity('Edge',edge)
+        x0,y0,z0=cubit.get_nodal_coordinates(nodes[0])
+        x1,y1,z1=cubit.get_nodal_coordinates(nodes[1])
+        d=sqrt((x1-x0)**2+(y1-y0)**2+(z1-z0)**2)
+        return d
+    def edge_min_length(self,surface):
+        """
+        edge_min,length=edge_min_length(surface)
+            given the cubit id of a surface, it return the edge with minimun length 
+        """
+        from math import sqrt
+        self.dmin=99999
+        edge_store=0
+        command = "group 'list_edge' add edge in surf "+str(surface)
+        command = command.replace("["," ").replace("]"," ")
+        cubit.cmd(command)
+        group=cubit.get_id_from_name("list_edge")
+        edges=cubit.get_group_edges(group)
+        command = "delete group "+ str(group)
+        cubit.cmd(command)
+        for edge in edges:
+            d=self.edge_length(edge)
+            if d<dmin:
+                self.dmin=d
+                edge_store=edge
+        self.edgemin=edge_store
+        return self.edgemin,self.dmin
+    def normal_check(self,nodes,normal):
+        tres=.2
+        p0=cubit.get_nodal_coordinates(nodes[0])
+        p1=cubit.get_nodal_coordinates(nodes[1])
+        p2=cubit.get_nodal_coordinates(nodes[2])
+        a=[p1[0]-p0[0],p1[1]-p0[1],p1[2]-p0[2]]
+        b=[p2[0]-p1[0],p2[1]-p1[1],p2[2]-p1[2]]
+        axb=[a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]
+        dot=0.0 
+        for i in (0,1,2): 
+            dot=dot+axb[i]*normal[i]
+        if  dot > 0:
+            return nodes
+        elif dot < 0:
+            return nodes[0],nodes[3],nodes[2],nodes[1]
+        else:
+            print 'error: surface normal, dot=0', axb,normal,dot,p0,p1,p2
+    def mesh_analysis(self,frequency):
+        from sets import Set
+        cubit.cmd('set info off')
+        cubit.cmd('set echo off')
+        cubit.cmd('set journal off')
+        bins_d=[0.0001]+range(0,int(frequency)+1)+[1000]
+        bins_u=bins_d[1:]
+        dt=[]
+        ed_dt=[]
+        r=[]
+        ed_r=[]
+        nstart=cubit.get_next_sideset_id()
+        command = "del sideset all"
+        cubit.cmd(command)
+        for bin_d,bin_u in zip(bins_d,bins_u):
+            nsideset=cubit.get_next_sideset_id()
+            command='create sideset '+str(nsideset)
+            cubit.cmd(command)
+            command = "sideset "+str(nsideset)+ " name "+ "'ratio-["+str(bin_d)+"_"+str(bin_u)+"['"
+            cubit.cmd(command)
+        nend=cubit.get_next_sideset_id()            
+        sidelist=range(nstart,nend)
+        for block in self.block_mat:
+            name=cubit.get_exodus_entity_name('block',block)
+            velocity=self.material[name][1]
+            if velocity > 0:
+                faces=cubit.get_block_faces(block)
+                edges=[]
+                for face in faces:
+                    es=cubit.get_sub_elements("face", face, 1)
+                    edges=edges+list(es)
+                edges=Set(edges)
+                dtstore,edgedtstore,ratiostore,edgeratiostore=self.seismic_resolution(edges,velocity,bins_d,bins_u,sidelist)
+                dt.append(dtstore)
+                ed_dt.append(edgedtstore)
+                r.append(ratiostore)
+                ed_r.append(edgeratiostore)
+        self.ddt=zip(ed_dt,dt)
+        self.dr=zip(ed_r,r)
+        def sorter(x, y):
+            return cmp(x[1],y[1])
+        self.ddt.sort(sorter)
+        self.dr.sort(sorter)
+        print self.ddt,self.dr
+        print 'Deltat minimum => edge:'+str(self.ddt[0][0])+' dt: '+str(self.ddt[0][1])
+        print 'minimum frequency resolved => edge:'+str(self.dr[0][0])+' frequency: '+str(self.dr[0][1])
+        return self.ddt[0],self.dr[0]
+
+class mesh(object,mesh_tools):
+    def __init__(self):
+        super(mesh, self).__init__()
+        self.mesh_name='mesh_file'
+        self.nodecoord_name='nodes_coords_file'
+        self.material_name='materials_file'
+        self.nummaterial_name='nummaterial_velocity_file'
+        self.absname='absorbing_surface_file'
+        self.freename='free_surface_file'
+        self.recname='STATIONS'
+        version_cubit=float(cubit.get_version())
+        if version_cubit >= 12:
+            self.face='SHELL4'
+        else:
+            self.face='QUAD4'
+        self.hex='HEX'
+        self.edge='BAR2'
+        self.topo='face_topo'
+        self.rec='receivers'
+        self.block_definition()
+        self.ngll=5
+        self.percent_gll=0.172
+        self.point_wavelength=5
+        cubit.cmd('compress all')
+    def __repr__(self):
+        pass
+    def block_definition(self):
+        block_flag=[]
+        block_mat=[]
+        block_bc=[]
+        block_bc_flag=[]
+        material={}
+        bc={}
+        blocks=cubit.get_block_id_list()
+        for block in blocks:
+            name=cubit.get_exodus_entity_name('block',block)
+            ty=cubit.get_block_element_type(block)
+            #print block,blocks,ty,self.hex,self.face
+            if self.hex in ty:
+                nattrib=cubit.get_block_attribute_count(block)
+                flag=None
+                vel=None
+                vs=None
+                rho=None
+                q=0
+                ani=0
+                # material domain id
+                if "acoustic" in name :
+                  imaterial = 1
+                elif "elastic"  in name:
+                  imaterial = 2
+                elif "poroelastic"  in name:
+                  imaterial = 3
+                else :
+                  imaterial = 0
+                #
+                if nattrib > 1:
+                    # material flag:
+                    #   positive => material properties,
+                    #   negative => interface/tomography domain
+                    flag=int(cubit.get_block_attribute_value(block,0))
+                    if flag > 0 and nattrib >= 2:
+                        vel=cubit.get_block_attribute_value(block,1)
+                        if nattrib >= 3:
+                            vs=cubit.get_block_attribute_value(block,2)
+                            if nattrib >= 4:
+                                rho=cubit.get_block_attribute_value(block,3)
+                                if nattrib >= 5:
+                                    q=cubit.get_block_attribute_value(block,4)
+                                    # for q to be valid: it must be positive
+                                    if q < 0 :
+                                      print 'error, q value invalid:', q
+                                      break                                                   
+                                    if nattrib == 6:
+                                        ani=cubit.get_block_attribute_value(block,5)
+                    elif flag < 0:
+                        vel=name
+                        attrib=cubit.get_block_attribute_value(block,1)
+                        if attrib == 1: 
+                            kind='interface'
+                            flag_down=cubit.get_block_attribute_value(block,2)
+                            flag_up=cubit.get_block_attribute_value(block,3)
+                        elif attrib == 2:
+                            kind='tomography'
+                elif  nattrib == 1:
+                    flag=cubit.get_block_attribute_value(block,0)
+                    print 'only 1 attribute ', name,block,flag
+                    vel,vs,rho,q,ani=(0,0,0,0,0)
+                else:
+                    flag=block
+                    vel,vs,rho,q,ani=(name,0,0,0,0)
+                block_flag.append(int(flag))
+                block_mat.append(block)
+                if flag > 0 and nattrib != 1:
+                    par=tuple([imaterial,flag,vel,vs,rho,q,ani])
+                elif flag < 0 and nattrib != 1:
+                    if kind=='interface':
+                        par=tuple([imaterial,flag,kind,name,flag_down,flag_up])
+                    elif kind=='tomography':
+                        par=tuple([imaterial,flag,kind,name])
+                elif flag==0 or nattrib == 1:
+                    par=tuple([imaterial,flag,name])
+                material[block]=par
+            elif ty == self.face: #Stacey condition, we need hex here for pml
+                block_bc_flag.append(4)
+                block_bc.append(block)
+                bc[block]=4 #face has connectivity = 4
+                if name == self.topo or block == 1001: topography_face=block
+            elif ty == 'SPHERE':
+                pass
+            else:
+                # block elements differ from HEX8/QUAD4/SHELL4
+                print '****************************************'
+                print 'block not properly defined:'
+                print '  name:',name
+                print '  type:',type
+                print
+                print 'please check your block definitions!'
+                print
+                print 'only supported types are:'
+                print '  HEX/HEX8  for volumes'
+                print '  QUAD4 for surface'
+                print '  SHELL4 for surface'
+                print '****************************************'
+                continue
+                return None, None,None,None,None,None,None,None
+        nsets=cubit.get_nodeset_id_list()
+        if len(nsets) == 0: self.receivers=None
+        for nset in nsets:
+            name=cubit.get_exodus_entity_name('nodeset',nset)
+            if name == self.rec:
+                self.receivers=nset
+            else:
+                print 'nodeset '+name+' not defined'
+                self.receivers=None
+        print block_mat
+        print block_flag
+        print block_bc
+        print block_bc_flag
+        print material
+        print bc
+        print topography_face
+        #
+        try:
+            self.block_mat=block_mat
+            self.block_flag=block_flag
+            self.block_bc=block_bc
+            self.block_bc_flag=block_bc_flag
+            self.material=material
+            self.bc=bc
+            self.topography=topography_face
+        except:
+            print '****************************************'
+            print 'sorry, no blocks or blocks not properly defined'
+            print block_mat
+            print block_flag
+            print block_bc
+            print block_bc_flag
+            print material
+            print bc
+            print topography
+            print '****************************************'
+    def mat_parameter(self,properties): 
+        print properties
+        #format nummaterials file: #material_domain_id #material_id #rho #vp #vs #Q_mu #anisotropy_flag
+        imaterial=properties[0]
+        flag=properties[1]
+        if flag > 0:
+            vel=properties[2]
+            if properties[2] is None and type(vel) != str:
+                if vel >= 30:
+                    m2km=1000.
+                else:
+                    m2km=1.
+                vp=vel/m2km
+                rho=(1.6612*vp-0.472*vp**2+0.0671*vp**3-0.0043*vp**4+0.000106*vp**4)*m2km
+                txt='%1i %3i %20f %20f %20f %1i %1i\n' % (properties[0],properties[1],rho,vel,vel/(3**.5),0,0)     
+            elif type(vel) != str and vel != 0.:
+                try: 
+                    q=properties[5]
+                except:
+                    q=0.
+                try:
+                    ani=properties[6]
+                except:
+                    ani=0.
+                #print properties[0],properties[3],properties[1],properties[2],q,ani
+                txt='%1i %3i %20f %20f %20f %20f %20f\n' % (properties[0],properties[1],properties[4],properties[2],properties[3],q,ani)
+            elif type(vel) != str and vel != 0.:
+                helpstring="#material_domain_id #material_id #rho #vp #vs #Q_mu #anisotropy"
+                txt='%1i %3i %s \n' % (properties[0],properties[1],helpstring)
+            else:
+                helpstring=" -->       sintax: #material_domain_id #material_id #rho #vp #vs #Q_mu #anisotropy"
+                txt='%1i %3i %s %s\n' % (properties[0],properties[1],properties[2],helpstring)
+        elif flag < 0:
+            if properties[2] == 'tomography':
+                txt='%1i %3i %s %s\n' % (properties[0],properties[1],properties[2],properties[3])
+            elif properties[2] == 'interface':
+                txt='%1i %3i %s %s %1i %1i\n' % (properties[0],properties[1],properties[2],properties[3],properties[4],properties[5])
+            else:
+                helpstring=" -->       sintax: #material_domain_id 'tomography' #file_name "
+                txt='%1i %3i %s %s \n' % (properties[0],properties[1],properties[2],helpstring)
+                #
+        return txt
+    def nummaterial_write(self,nummaterial_name):
+        print 'Writing '+nummaterial_name+'.....'
+        nummaterial=open(nummaterial_name,'w')
+        for block in self.block_mat:
+            #name=cubit.get_exodus_entity_name('block',block)
+            nummaterial.write(str(self.mat_parameter(self.material[block])))
+        nummaterial.close()
+    def mesh_write(self,mesh_name):
+        meshfile=open(mesh_name,'w')
+        print 'Writing '+mesh_name+'.....'
+        num_elems=cubit.get_hex_count()
+        print '  number of elements:',str(num_elems)
+        meshfile.write(str(num_elems)+'\n')
+        for block,flag in zip(self.block_mat,self.block_flag):
+            #print block,flag
+            hexes=cubit.get_block_hexes(block)
+            #print len(hexes)
+            for hexa in hexes:
+                #print hexa
+                nodes=cubit.get_connectivity('Hex',hexa)
+                #nodes=self.jac_check(nodes) #is it valid for 3D? TODO
+                txt=('%10i ')% hexa
+                txt=txt+('%10i %10i %10i %10i %10i %10i %10i %10i\n')% nodes[:]
+                meshfile.write(txt)
+        meshfile.close()
+    def material_write(self,mat_name):
+        mat=open(mat_name,'w')
+        print 'Writing '+mat_name+'.....'
+        for block,flag in zip(self.block_mat,self.block_flag):
+                hexes=cubit.get_block_hexes(block)
+                for hexa in hexes:
+                    mat.write(('%10i %10i\n') % (hexa,flag))
+        mat.close()
+    def nodescoord_write(self,nodecoord_name):
+        nodecoord=open(nodecoord_name,'w')
+        print 'Writing '+nodecoord_name+'.....'
+        node_list=cubit.parse_cubit_list('node','all')
+        num_nodes=len(node_list)
+        print '  number of nodes:',str(num_nodes)
+        nodecoord.write('%10i\n' % num_nodes)
+        #
+        for node in node_list:
+            x,y,z=cubit.get_nodal_coordinates(node)
+            txt=('%10i %20f %20f %20f\n') % (node,x,y,z)
+            nodecoord.write(txt)
+        nodecoord.close()
+    def free_write(self,freename=None):
+        cubit.cmd('set info off')
+        cubit.cmd('set echo off')
+        cubit.cmd('set journal off')
+        from sets import Set
+        normal=(0,0,1)
+        if not freename: freename=self.freename
+        freehex=open(freename,'w')
+        print 'Writing '+freename+'.....'
+        #
+        #
+        for block,flag in zip(self.block_bc,self.block_bc_flag):
+            if block == self.topography:
+                name=cubit.get_exodus_entity_name('block',block)
+                print '  block name:',name,'id:',block
+                quads_all=cubit.get_block_faces(block)
+                print '  number of faces = ',len(quads_all)
+                dic_quads_all=dict(zip(quads_all,quads_all))
+                freehex.write('%10i\n' % len(quads_all))
+                list_hex=cubit.parse_cubit_list('hex','all')
+                for h in list_hex:
+                    faces=cubit.get_sub_elements('hex',h,2)
+                    for f in faces:
+                        if dic_quads_all.has_key(f):
+                            #print f
+                            nodes=cubit.get_connectivity('face',f)
+                            nodes_ok=self.normal_check(nodes,normal)
+                            txt='%10i %10i %10i %10i %10i\n' % (h,nodes_ok[0],nodes_ok[1],nodes_ok[2],nodes_ok[3])
+                            freehex.write(txt)
+                freehex.close()   
+        cubit.cmd('set info on')
+        cubit.cmd('set echo on')
+    def abs_write(self,absname=None):
+        import re
+        cubit.cmd('set info off')
+        cubit.cmd('set echo off')
+        cubit.cmd('set journal off')
+        from sets import Set
+        if not absname: absname=self.absname
+        #
+        #
+        list_hex=cubit.parse_cubit_list('hex','all')
+        for block,flag in zip(self.block_bc,self.block_bc_flag):
+            if block != self.topography:
+                name=cubit.get_exodus_entity_name('block',block)
+                print '  block name:',name,'id:',block
+                cknormal=True
+                if re.search('xmin',name):
+                    print 'xmin'
+                    abshex_local=open(absname+'_xmin','w')
+                    normal=(-1,0,0)
+                elif re.search('xmax',name):
+                    print "xmax"
+                    abshex_local=open(absname+'_xmax','w')
+                    normal=(1,0,0)
+                elif re.search('ymin',name):
+                    print "ymin"
+                    abshex_local=open(absname+'_ymin','w')
+                    normal=(0,-1,0)
+                elif re.search('ymax',name):
+                    print "ymax"
+                    abshex_local=open(absname+'_ymax','w')
+                    normal=(0,1,0)
+                elif re.search('bottom',name):
+                    print "bottom"
+                    abshex_local=open(absname+'_bottom','w')
+                    normal=(0,0,-1)
+                elif re.search('abs',name):
+                    print "abs all - no implemented yet"
+                    cknormal=False
+                    abshex_local=open(absname,'w')
+                else:
+                    if block == 1003:
+                        print 'xmin'
+                        abshex_local=open(absname+'_xmin','w')
+                        normal=(-1,0,0)
+                    elif block == 1004:
+                        print "ymin"
+                        abshex_local=open(absname+'_ymin','w')
+                        normal=(0,-1,0)
+                    elif block == 1005:
+                        print "xmax"
+                        abshex_local=open(absname+'_xmax','w')
+                        normal=(1,0,0)
+                    elif block == 1006:
+                        print "ymax"
+                        abshex_local=open(absname+'_ymax','w')
+                        normal=(0,1,0)
+                    elif block == 1002:
+                        print "bottom"
+                        abshex_local=open(absname+'_bottom','w')
+                        normal=(0,0,-1)
+                #
+                #
+                quads_all=cubit.get_block_faces(block)
+                dic_quads_all=dict(zip(quads_all,quads_all))
+                print '  number of faces = ',len(quads_all)
+                abshex_local.write('%10i\n' % len(quads_all))
+                #command = "group 'list_hex' add hex in face "+str(quads_all)
+                #command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
+                #cubit.cmd(command)
+                #group=cubit.get_id_from_name("list_hex")
+                #list_hex=cubit.get_group_hexes(group)
+                #command = "delete group "+ str(group)
+                #cubit.cmd(command)
+                for h in list_hex:
+                    faces=cubit.get_sub_elements('hex',h,2)
+                    for f in faces:
+                        if dic_quads_all.has_key(f):
+                            nodes=cubit.get_connectivity('face',f)
+                            if cknormal:
+                                nodes_ok=self.normal_check(nodes,normal)
+                            else:
+                                nodes_ok=nodes
+                            txt='%10i %10i %10i %10i %10i\n' % (h,nodes_ok[0],nodes_ok[1],nodes_ok[2],nodes_ok[3])
+                            abshex_local.write(txt)
+                abshex_local.close()   
+        cubit.cmd('set info on')
+        cubit.cmd('set echo on')
+    def surface_write(self,pathdir=None):
+        # optional surfaces, e.g. moho_surface
+        # should be created like e.g.:
+        #  > block 10 face in surface 2
+        #  > block 10 name 'moho_surface'
+        import re
+        from sets import Set
+        for block in self.block_bc :
+            if block != self.topography:
+                name=cubit.get_exodus_entity_name('block',block)
+                # skips block names like face_abs**, face_topo**
+                if re.search('abs',name):
+                  continue
+                elif re.search('topo',name):
+                  continue
+                elif re.search('surface',name):
+                  filename=pathdir+name+'_file'
+                else:
+                  continue
+                # gets face elements
+                print '  surface block name: ',name,'id: ',block
+                quads_all=cubit.get_block_faces(block)
+                print '  face = ',len(quads_all)
+                if len(quads_all) == 0 :
+                  continue
+                # writes out surface infos to file
+                print 'Writing '+filename+'.....'
+                surfhex_local=open(filename,'w')
+                dic_quads_all=dict(zip(quads_all,quads_all))
+                # writes number of surface elements
+                surfhex_local.write('%10i\n' % len(quads_all))
+                # writes out element node ids
+                list_hex=cubit.parse_cubit_list('hex','all')
+                for h in list_hex:
+                    faces=cubit.get_sub_elements('hex',h,2)
+                    for f in faces:
+                        if dic_quads_all.has_key(f):
+                            nodes=cubit.get_connectivity('face',f)
+                            txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\
+                                             nodes[1],nodes[2],nodes[3])
+                            surfhex_local.write(txt)
+                # closes file
+                surfhex_local.close()
+    def rec_write(self,recname):
+        print 'Writing '+self.recname+'.....'
+        recfile=open(self.recname,'w')
+        nodes=cubit.get_nodeset_nodes(self.receivers)
+        for i,n in enumerate(nodes):
+            x,y,z=cubit.get_nodal_coordinates(n)
+            recfile.write('ST%i XX %20f %20f 0.0 0.0 \n' % (i,x,z))
+        recfile.close()
+    def write(self,path=''):
+        cubit.cmd('set info off')
+        cubit.cmd('set echo off')
+        cubit.cmd('set journal off')
+        cubit.cmd('compress all')
+        if len(path) != 0:
+            if path[-1] != '/': path=path+'/'
+        self.mesh_write(path+self.mesh_name)
+        self.material_write(path+self.material_name)
+        self.nodescoord_write(path+self.nodecoord_name)
+        self.free_write(path+self.freename)
+        self.abs_write(path+self.absname)
+        self.nummaterial_write(path+self.nummaterial_name)
+        # any other surfaces: ***surface***
+        self.surface_write(path)
+        if self.receivers: self.rec_write(path+self.recname)
+        cubit.cmd('set info on')
+        cubit.cmd('set echo on')
+
+def export2SPECFEM3D(path_exporting_mesh_SPECFEM3D='.'):
+    sem_mesh=mesh()
+    #sem_mesh.block_definition()
+    #print sem_mesh.block_mat
+    #print sem_mesh.block_flag
+    #
+    sem_mesh.write(path=path_exporting_mesh_SPECFEM3D)
+    print 'END SPECFEM3D exporting process......'
+    
+
+
+if __name__ == '__main__':
+    path='.'
+    export2SPECFEM3D(path)

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/dev/cubit2googleearth.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/dev/cubit2googleearth.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/dev/cubit2googleearth.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,297 @@
+#!python
+#############################################################################
+# cubit2specfem3d.py                                                           #
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+#
+#
+try:
+    cubit.cmd('comment')
+except:
+    import cubit
+
+KMLstart='<kml xmlns="http://earth.google.com/kml/2.2">\n<Folder><name>prova</name>\n'
+placemarkstart='<Placemark>\n      <name></name>\n      <description></description>\n<TimeStamp><begin>%s</begin><end>%s</end></TimeStamp>\n        <MultiGeometry>\n            <altitudeMode>absolute</altitudeMode>\n'
+placemarkend='        </MultiGeometry>\n</Placemark>\n'
+templatepoly='                <Polygon>\n                    <altitudeMode>absolute</altitudeMode>\n                    <outerBoundaryIs>\n                        <LinearRing>\n                            <coordinates>\n                            %s,%s,%s\n                            %s,%s,%s\n                            %s,%s,%s\n                            %s,%s,%s\n                            %s,%s,%s \n                            </coordinates>\n                        </LinearRing>\n                    </outerBoundaryIs>\n                </Polygon>\n'
+
+KMLend='    </Folder>\n</kml>\n'
+
+
+import datetime
+now=datetime.datetime.now().year
+
+import random
+
+# Lat Long - UTM, UTM - Lat Long conversions
+
+from math import pi, sin, cos, tan, sqrt
+
+#LatLong- UTM conversion..h
+#definitions for lat/long to UTM and UTM to lat/lng conversions
+#include <string.h>
+
+_deg2rad = pi / 180.0
+_rad2deg = 180.0 / pi
+
+_EquatorialRadius = 2
+_eccentricitySquared = 3
+
+_ellipsoid = [[ -1, "Placeholder", 0, 0],[ 1, "Airy", 6377563, 0.00667054],[ 2, "Australian National", 6378160, 0.006694542],[ 3, "Bessel 1841", 6377397, 0.006674372],[ 4, "Bessel 1841 (Nambia] ", 6377484, 0.006674372],[ 5, "Clarke 1866", 6378206, 0.006768658],[ 6, "Clarke 1880", 6378249, 0.006803511],[ 7, "Everest", 6377276, 0.006637847],[ 8, "Fischer 1960 (Mercury] ", 6378166, 0.006693422],[ 9, "Fischer 1968", 6378150, 0.006693422],[ 10, "GRS 1967", 6378160, 0.006694605],[ 11, "GRS 1980", 6378137, 0.00669438],[ 12, "Helmert 1906", 6378200, 0.006693422],[ 13, "Hough", 6378270, 0.00672267],[ 14, "International", 6378388, 0.00672267],[ 15, "Krassovsky", 6378245, 0.006693422],[ 16, "Modified Airy", 6377340, 0.00667054],[ 17, "Modified Everest", 6377304, 0.006637847],[ 18, "Modified Fischer 1960", 6378155, 0.006693422],[ 19, "South American 1969", 6378160, 0.006694542],[ 20, "WGS 60", 6378165, 0.006693422],[ 21, "WGS 66", 6378145, 0.006694542],[ 22, "WGS-72", 6378135, 0.006694318],[ 23, "WGS-84", 6378137, 0.00669438]]
+
+#Reference ellipsoids derived from Peter H. Dana's website- 
+#http://www.utexas.edu/depts/grg/gcraft/notes/datum/elist.htmlV
+#Department of Geography, University of Texas at Austin
+#Internet: pdana at mail.utexas.edu
+#3/22/95
+
+#Source
+#Defense Mapping Agency. 1987b. DMA Technical Report: Supplement to Department of Defense World Geodetic System
+#1984 Technical Report. Part I and II. Washington, DC: Defense Mapping Agency
+
+def LLtoUTM(ReferenceEllipsoid, Lat, Long):
+    #converts lat/long to UTM coords.  Equations from USGS Bulletin 1532 
+    #East Longitudes are positive, West longitudes are negative. 
+    #North latitudes are positive, South latitudes are negative
+    #Lat and Long are in decimal degrees
+    #Written by Chuck Gantz- chuck.gantz at globalstar.com
+    a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
+    eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
+    k0 = 0.9996#Make sure the longitude is between -180.00 .. 179.9
+    LongTemp = (Long+180)-int((Long+180)/360)*360-180 # -180.00 .. 179.9
+    LatRad = Lat*_deg2rad
+    LongRad = LongTemp*_deg2rad
+    ZoneNumber = int((LongTemp + 180)/6) + 1
+    if Lat >= 56.0 and Lat < 64.0 and LongTemp >= 3.0 and LongTemp < 12.0:
+        ZoneNumber = 32
+    # Special zones for Svalbard
+    if Lat >= 72.0 and Lat < 84.0:
+        if  LongTemp >= 0.0  and LongTemp <  9.0:ZoneNumber = 31
+        elif LongTemp >= 9.0  and LongTemp < 21.0: ZoneNumber = 33
+        elif LongTemp >= 21.0 and LongTemp < 33.0: ZoneNumber = 35
+        elif LongTemp >= 33.0 and LongTemp < 42.0: ZoneNumber = 37
+    LongOrigin = (ZoneNumber - 1)*6 - 180 + 3 #+3 puts origin in middle of zone
+    LongOriginRad = LongOrigin * _deg2rad
+    #compute the UTM Zone from the latitude and longitude
+    UTMZone = "%d%c" % (ZoneNumber, _UTMLetterDesignator(Lat))
+    eccPrimeSquared = (eccSquared)/(1-eccSquared)
+    N = a/sqrt(1-eccSquared*sin(LatRad)*sin(LatRad))
+    T = tan(LatRad)*tan(LatRad)
+    C = eccPrimeSquared*cos(LatRad)*cos(LatRad)
+    A = cos(LatRad)*(LongRad-LongOriginRad)
+    M = a*((1
+            - eccSquared/4
+            - 3*eccSquared*eccSquared/64
+            - 5*eccSquared*eccSquared*eccSquared/256)*LatRad 
+           - (3*eccSquared/8
+              + 3*eccSquared*eccSquared/32
+              + 45*eccSquared*eccSquared*eccSquared/1024)*sin(2*LatRad)
+           + (15*eccSquared*eccSquared/256 + 45*eccSquared*eccSquared*eccSquared/1024)*sin(4*LatRad) 
+           - (35*eccSquared*eccSquared*eccSquared/3072)*sin(6*LatRad))
+    UTMEasting = (k0*N*(A+(1-T+C)*A*A*A/6
+                        + (5-18*T+T*T+72*C-58*eccPrimeSquared)*A*A*A*A*A/120)
+                  + 500000.0)
+    UTMNorthing = (k0*(M+N*tan(LatRad)*(A*A/2+(5-T+9*C+4*C*C)*A*A*A*A/24
+                                        + (61
+                                           -58*T
+                                           +T*T
+                                           +600*C
+                                           -330*eccPrimeSquared)*A*A*A*A*A*A/720)))
+    if Lat < 0:
+        UTMNorthing = UTMNorthing + 10000000.0; #10000000 meter offset for southern hemisphere
+    return (UTMZone, UTMEasting, UTMNorthing)
+
+
+def _UTMLetterDesignator(Lat):
+#This routine determines the correct UTM letter designator for the given latitude
+#returns 'Z' if latitude is outside the UTM limits of 84N to 80S
+#Written by Chuck Gantz- chuck.gantz at globalstar.com
+    if 84 >= Lat >= 72: return 'X'
+    elif 72 > Lat >= 64: return 'W'
+    elif 64 > Lat >= 56: return 'V'
+    elif 56 > Lat >= 48: return 'U'
+    elif 48 > Lat >= 40: return 'T'
+    elif 40 > Lat >= 32: return 'S'
+    elif 32 > Lat >= 24: return 'R'
+    elif 24 > Lat >= 16: return 'Q'
+    elif 16 > Lat >= 8: return 'P'
+    elif  8 > Lat >= 0: return 'N'
+    elif  0 > Lat >= -8: return 'M'
+    elif -8> Lat >= -16: return 'L'
+    elif -16 > Lat >= -24: return 'K'
+    elif -24 > Lat >= -32: return 'J'
+    elif -32 > Lat >= -40: return 'H'
+    elif -40 > Lat >= -48: return 'G'
+    elif -48 > Lat >= -56: return 'F'
+    elif -56 > Lat >= -64: return 'E'
+    elif -64 > Lat >= -72: return 'D'
+    elif -72 > Lat >= -80: return 'C'
+    else: return 'Z'	# if the Latitude is outside the UTM limits
+
+#void UTMtoLL(int ReferenceEllipsoid, const double UTMNorthing, const double UTMEasting, const char* UTMZone,
+#			  double& Lat,  double& Long )
+
+def UTMtoLL(ReferenceEllipsoid, northing, easting, zone):
+    #converts UTM coords to lat/long.  Equations from USGS Bulletin 1532 
+    #East Longitudes are positive, West longitudes are negative. 
+    #North latitudes are positive, South latitudes are negative
+    #Lat and Long are in decimal degrees. 
+    #Written by Chuck Gantz- chuck.gantz at globalstar.com
+    #Converted to Python by Russ Nelson <nelson at crynwr.com>
+    k0 = 0.9996
+    a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
+    eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
+    e1 = (1-sqrt(1-eccSquared))/(1+sqrt(1-eccSquared))
+    #NorthernHemisphere; //1 for northern hemispher, 0 for southern
+    x = easting - 500000.0 #remove 500,000 meter offset for longitude
+    y = northing
+    ZoneLetter = zone[-1]
+    ZoneNumber = int(zone[:-1])
+    if ZoneLetter >= 'N':
+        NorthernHemisphere = 1  # point is in northern hemisphere
+    else:
+        NorthernHemisphere = 0  # point is in southern hemisphere
+        y -= 10000000.0         # remove 10,000,000 meter offset used for southern hemisphere
+    LongOrigin = (ZoneNumber - 1)*6 - 180 + 3  # +3 puts origin in middle of zone
+    eccPrimeSquared = (eccSquared)/(1-eccSquared)
+    M = y / k0
+    mu = M/(a*(1-eccSquared/4-3*eccSquared*eccSquared/64-5*eccSquared*eccSquared*eccSquared/256))
+    phi1Rad = (mu + (3*e1/2-27*e1*e1*e1/32)*sin(2*mu) 
+               + (21*e1*e1/16-55*e1*e1*e1*e1/32)*sin(4*mu)
+               +(151*e1*e1*e1/96)*sin(6*mu))
+    phi1 = phi1Rad*_rad2deg;
+    N1 = a/sqrt(1-eccSquared*sin(phi1Rad)*sin(phi1Rad))
+    T1 = tan(phi1Rad)*tan(phi1Rad)
+    C1 = eccPrimeSquared*cos(phi1Rad)*cos(phi1Rad)
+    R1 = a*(1-eccSquared)/pow(1-eccSquared*sin(phi1Rad)*sin(phi1Rad), 1.5)
+    D = x/(N1*k0)
+    Lat = phi1Rad - (N1*tan(phi1Rad)/R1)*(D*D/2-(5+3*T1+10*C1-4*C1*C1-9*eccPrimeSquared)*D*D*D*D/24
+                                          +(61+90*T1+298*C1+45*T1*T1-252*eccPrimeSquared-3*C1*C1)*D*D*D*D*D*D/720)
+    Lat = Lat * _rad2deg
+    Long = (D-(1+2*T1+C1)*D*D*D/6+(5-2*C1+28*T1-3*C1*C1+8*eccPrimeSquared+24*T1*T1)
+            *D*D*D*D*D/120)/cos(phi1Rad)
+    Long = LongOrigin + Long * _rad2deg
+    return (Lat, Long)
+
+class cubit2GE(object):
+    def __init__(self,unit='utm',x_origin=None,y_origin=None,z_origin=None):
+        super(cubit2GE, self).__init__()
+        self.unit=unit
+        self.xo=x_origin
+        self.yo=y_origin
+        self.zo=z_origin
+        cubit.cmd('compress all')
+    def __repr__(self):
+        pass
+    def create_blocks(self,list_entity=None):
+        txt=' face in surface '                                 
+        if list_entity:                                         
+            if not isinstance(list_entity,list):                
+                list_entity=[list_entity]
+        iblock=cubit.get_next_block_id()                       
+        for entity in list_entity:                                                  
+            command = "block "+str(iblock)+ txt +str(entity)    
+            cubit.cmd(command)
+        command = "block "+str(iblock)+ "name 'toGE'"
+        cubit.cmd(command)
+        self.iblock=iblock 
+    def geo2utm(self,lon,lat,unit,ellipsoid=23):
+        if unit == 'geo' :          
+           (zone, x, y) = LLtoUTM(ellipsoid, lat, lon)
+        elif unit == 'utm' : 
+           x=lon
+           y=lat
+           zone=0
+        return zone,x,y
+    def utm2geo(self,lon,lat,zone,unit='utm'):
+        if unit == 'utm' and zone:          
+           (y, x) = UTMtoLL(23, lat, lon,zone)
+        else: 
+           x=lon
+           y=lat
+        return x,y                            
+    def write(self,GEname=None,t1=0,t2=1):
+        cubit.cmd('set info off')
+        cubit.cmd('set echo off')
+        cubit.cmd('set journal off')
+        from sets import Set
+        if not GEname: GEname='cubit2GE.kml'
+        if self.xo and self.yo:
+            zone_utm,xo_utm,yo_utm=self.geo2utm(self.xo,self.yo,'geo')
+        else:
+            xo_utm=0.
+            yo_utm=0.
+            zone_utm=None
+        if self.zo:
+            zo=self.zo
+        else:
+            zo=0
+        #
+        GE=open(GEname,'w')
+        print 'Writing '+GEname+'.....'
+        #
+        #
+        GE.write(KMLstart)
+        for it in range(int(t1),int(t2),1):
+            tbegin=now+seconds*it
+            tafter=now+(seconds*(it+1))
+            print tbegin.isoformat()
+            GE.write(placemarkstart%(str(tbegin.isoformat()),str(tafter.isoformat())))
+            #
+            block=self.iblock
+            nameb=cubit.get_exodus_entity_name('block',block)
+            print nameb,block
+            quads_all=cubit.get_block_faces(block)
+            print len(quads_all)
+            for f in quads_all:
+                nodes=cubit.get_connectivity('Face',f)
+                coord=[]
+                for n in [nodes[0],nodes[1],nodes[2],nodes[3],nodes[0]]:
+                    x,y,z=cubit.get_nodal_coordinates(n)
+                    if self.unit == 'geo':
+                        zone,x,y=self.geo2utm(x,y,'geo')
+                    new_x=x+xo_utm+sin(it)*3
+                    new_y=y+yo_utm+cos(it)*3
+                    new_z=z+zo+sin(it)*3
+                    lon,lat=self.utm2geo(new_x,new_y,zone_utm,unit='utm')
+                    coord.append(str(lon))
+                    coord.append(str(lat))
+                    coord.append(str(new_z))
+                GE.write(templatepoly % tuple(coord))
+            GE.write(placemarkend)
+        GE.write(KMLend)
+        GE.close()
+        #
+        print 'Ok'
+        cubit.cmd('set info on')
+        cubit.cmd('set echo on')
+
+def toGE(name='c2GE.kml',list_entity=None,unit='utm',x_origin=None,y_origin=None,z_origin=None,t1=0,t2=5):
+    GE=cubit2GE(unit=unit,x_origin=x_origin,y_origin=y_origin,z_origin=z_origin)
+    GE.create_blocks(list_entity=list_entity)
+    GE.write(GEname=name,t1=t1,t2=t2)
+
+name='/Users/emanuele/Desktop/c2GE.kml'
+toGE(name,list_entity='1 to 493',x_origin=8.767022,y_origin= 44.460383, z_origin=220)
+
+
+

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/dev/material.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/dev/material.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/dev/material.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,80 @@
+#############################################################################
+# material.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+
+
+
+class material():
+    def __init__(self,name,vp,vs,rho,q,ani):
+        self.name=name
+        self.vp=vp
+        self.vs=vs
+        self.rho=rho
+        self.qp=q
+        self.qs=ani
+    def __repr__(self):
+        print self.name
+        print 'vp',self.vp
+        print 'vs',self.vs
+        print 'rho',self.rho
+        print 'Qp',self.qp
+        print 'Qs',self.qs
+        return
+    def __str__(self):
+        txt=self.name+' vp '+str(self.vp)+ ' vs '+str(self.vs)+ ' rho '+str(self.rho)+ ' Qp '+str(self.qp)+ ' Qs '+str(self.qs)
+        return txt
+
+
+def read_material_archive(archivefile='material_archive.dat'):
+    archive=open(archivefile,'r')
+    archive_dict={}
+    for record in archive:
+        m=material(*record.split())
+        archive_dict[m.name]=m
+    return archive_dict
+
+
+def block_description(archivefile='material_archive.dat'):
+    try:
+        import initializing as initializing
+        cubit   = initializing.initializing_cubit()
+    except:
+        pass
+    import menu as menu
+    archive=read_material_archive(archivefile=menu.material_file)
+    b_assign=menu.material_assignement
+    print b_assign
+    if len(b_assign) != 0:
+        for block in b_assign:
+            mat=archive[block[1]]
+            print mat
+            cubit.cmd("block "+block[0]+" attribute count 6")
+            cubit.cmd("block "+block[0]+" name             '"+ mat.name   +'"')
+            cubit.cmd("block "+block[0]+" attribute index 1 "+ '1'            )
+            cubit.cmd("block "+block[0]+" attribute index 2 "+ str(mat.vp)    )
+            cubit.cmd("block "+block[0]+" attribute index 3 "+ str(mat.vs)    )
+            cubit.cmd("block "+block[0]+" attribute index 4 "+ str(mat.rho)   )
+            cubit.cmd("block "+block[0]+" attribute index 5 "+ str(mat.qp)    )
+            cubit.cmd("block "+block[0]+" attribute index 5 "+ str(mat.qs)    )
+    
+    
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/exportlib.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/exportlib.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/exportlib.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,667 @@
+#!/usr/bin/env python
+#############################################################################
+# exportlib.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+#
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+
+def refine_closecurve(block=1001,closed_filenames=None,acis=True):
+    from utilities import load_curves
+    from boundary_definition import build_block_side,define_surf
+    from mesh_volume import refine_inside_curve
+    #
+    #
+    curves=[]
+    if not isinstance(closed_filenames,list): closed_filenames=[closed_filenames]
+    for f in closed_filenames:
+        print f
+        if acis: 
+            curves=curves+load_curves(f)
+    print curves
+    blist=list(cubit.get_block_id_list())
+    try:
+        blist.remove(1001)
+    except:
+        pass
+    try:
+        blist.remove(1002)
+    except:
+        pass
+    try:
+        blist.remove(1003)
+    except:
+        pass        
+    try:
+        blist.remove(1004)    
+    except:                             
+        pass             
+    try:
+        blist.remove(1005)
+    except:
+        pass
+    try:
+        blist.remove(1006)
+    except:
+        pass
+    id_top=max(blist)
+    cmd='group "coi" add node in hex in block '+str(id_top)
+    cubit.cmd(cmd)
+    #
+    id_inside_arc=None
+    for c in map(int,curves[0].split()):   #curves is a list of one string
+        c1001 = cubit.get_exodus_element_count(1001, "block")
+        c1002 = cubit.get_exodus_element_count(1002, "block")
+        c1003 = cubit.get_exodus_element_count(1003, "block")
+        c1004 = cubit.get_exodus_element_count(1004, "block")
+        c1005 = cubit.get_exodus_element_count(1005, "block")
+        c1006 = cubit.get_exodus_element_count(1006, "block")
+        #
+        refine_inside_curve(c,ntimes=1,depth=1,block=block,surface=False)
+        blist=list(cubit.get_block_id_list())
+        cmd='create mesh geometry hex all except hex in block all feature_angle 135'
+        cubit.cmd(cmd)
+        blist_after=list(cubit.get_block_id_list())
+        [blist_after.remove(x) for x in blist]
+        id_inside=max(blist_after)
+        cmd='group "coi" add node in hex in block '+str(id_inside)
+        cubit.cmd(cmd)
+        if id_inside_arc: 
+                cmd='del block '+str(id_inside-1)
+                cubit.cmd(cmd)
+        cmd='block '+str(id_inside)+' name "refined"'
+        cubit.cmd(cmd)
+        id_inside_arc=id_inside                                            
+        #
+        _,_,_,_,_,top_surf,bottom_surf,surf_xmin,surf_ymin,surf_xmax,surf_ymax=define_surf()
+        #
+        c1001_after = cubit.get_exodus_element_count(1001, "block")
+        c1002_after = cubit.get_exodus_element_count(1002, "block")
+        c1003_after = cubit.get_exodus_element_count(1003, "block")
+        c1004_after = cubit.get_exodus_element_count(1004, "block")
+        c1005_after = cubit.get_exodus_element_count(1005, "block")
+        c1006_after = cubit.get_exodus_element_count(1006, "block")
+        entity='face'
+        if c1001_after != c1001:
+            refname=entity+'_topo'
+            build_block_side(top_surf,refname,obj=entity,id_0=1001)
+        #
+        if c1002_after != c1002:
+            refname=entity+'_bottom'
+            build_block_side(bottom_surf,refname,obj=entity,id_0=1002)
+        #
+        if c1003_after != c1003:
+            refname=entity+'_abs_xmin'
+            build_block_side(surf_xmin,refname,obj=entity,id_0=1003)
+        #                                                              
+        if c1004_after != c1004:
+            refname=entity+'_abs_ymin'
+            build_block_side(surf_ymin,refname,obj=entity,id_0=1004)
+        #                                                              
+        if c1005_after != c1005:  
+            refname=entity+'_abs_xmax'                                     
+            build_block_side(surf_xmax,refname,obj=entity,id_0=1005)
+        #
+        if c1006_after != c1006:    
+            refname=entity+'_abs_ymax'                                   
+            build_block_side(surf_ymax,refname,obj=entity,id_0=1006)
+        #
+        cmd='disassociate mesh from volume all'
+        cubit.cmd(cmd)
+        cmd='group "coi" add node in face in block 1001 1002 1003 1004 1005 1006'
+        cubit.cmd(cmd)
+        cubit.cmd('del vol all')
+        cubit.cmd('group "removedouble" add hex all except hex in block all')
+        cubit.cmd('delete hex in removedouble')
+        cubit.cmd('delet group removedouble')
+        cmd='equivalence node in group coi tolerance 20'
+        cubit.cmd(cmd)
+    cmd='equivalence node all tolerance 10'
+    cubit.cmd(cmd)
+    cubit.cmd('del curve '+' '.join(str(x) for x in curves) )
+
+
+
+
+def collecting_merging(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,ckbound_method1=False,ckbound_method2=False,merge_tolerance=None):
+    import glob
+    import re
+    #
+    rule_st=re.compile("(.+)_[0-9]+\.")
+    rule_ex=re.compile(".+_[0-9]+\.(.+)")
+    rule_int=re.compile(".+_([0-9]+)\.")
+    boundary_dict={}
+    ##
+    try:
+        from boundary_definition import check_bc, map_boundary
+    except:
+        pass
+    #
+    xmin,xmax,ymin,ymax,listfull=map_boundary(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
+    #
+    if cubfiles:
+        filenames=glob.glob(cubfiles)
+        try:
+            st = rule_st.findall(filenames[0])[0]
+            ex = rule_ex.findall(filenames[0])[0]
+            listflag=True
+        except:
+            ex=''
+            listflag=False
+        
+        if ex == 'cub':
+            cubflag=True
+        else:
+            cubflag=False
+        list_int=[]
+        fs=[]
+        try:
+            for f in filenames:
+                i=int(rule_int.findall(f)[0])
+                list_int.append(i)
+            list_int.sort()
+            for i,ind in enumerate(list_int):
+                f=st+'_'+str(ind)+'.'+ex
+                fs.append(f)
+        except:
+            pass
+        if listflag:
+            filenames=fs
+        else:
+            pass
+        print len(filenames),filenames
+    else:
+        filenames=[]
+        ip=0
+    #
+    if len(filenames) > 0:
+        for filename in filenames[:]:
+            try:
+                ip=int(rule_int.findall(filename)[0])
+                if ip in listfull:
+                    if cubflag:
+                        cubit.cmd('import cubit "'+filename+'"')
+                    else:
+                        cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
+                    boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
+                    boundary_dict[ip]=boundary
+                    list_vol=list(cubit.parse_cubit_list('volume','all'))
+                    for v in list_vol:
+                        cubit.cmd("disassociate mesh from volume "+str(v))
+                        command = "del vol "+str(v)
+                        cubit.cmd(command)
+            except:
+                cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
+                ip=0
+                boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
+                boundary_dict[ip]=boundary
+                list_vol=list(cubit.parse_cubit_list('volume','all'))
+                for v in list_vol:
+                    cubit.cmd("disassociate mesh from volume "+str(v))
+                    command = "del vol "+str(v)
+                    cubit.cmd(command)
+        cubit.cmd('export mesh "tmp_collect_NOmerging.e" dimension 3 block all overwrite')
+    else:
+        boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
+    #
+    #
+    block_list=cubit.get_block_id_list()
+    for block in block_list:
+        ty=cubit.get_block_element_type(block)
+        if ty == 'HEX8':
+            cubit.cmd('block '+str(block)+' name "vol'+str(block)+'"')
+    #
+    #
+    print 'chbound',ckbound_method1,ckbound_method2
+    if ckbound_method1 and not ckbound_method2:
+        if isinstance(merge_tolerance,list):
+            tol=merge_tolerance[0]
+        elif merge_tolerance:
+            tol=merge_tolerance
+        else:
+            tol=100000
+        #
+        idiag=None
+        #cubit.cmd('set info off')
+        #cubit.cmd('set journal off')
+        #cubit.cmd('set echo off')
+        ind=0
+        for ix in range(cpuxmin,cpuxmax):
+            for iy in range(cpuymin,cpuymax):
+                ind=ind+1
+                ip=iy*cpux+ix
+                print '******************* ',ip, ind,'/',len(listfull)
+                #
+                #   ileft    |   ip
+                #  --------------------
+                #   idiag    |   idown
+                #
+                #
+                if ip not in xmin and ip not in ymin:
+                    ileft=iy*cpux+ix-1
+                    idown=(iy-1)*cpux+ix
+                    idiag=idown-1
+                elif ip in xmin and ip in ymin:
+                    ileft=ip
+                    idown=ip
+                    idiag=None
+                elif ip in xmin:
+                    ileft=ip
+                    idown=(iy-1)*cpux+ix
+                    idiag=idown
+                elif ip in ymin:
+                    ileft=iy*cpux+ix-1
+                    idown=ip
+                    idiag=ileft
+                #
+                if ip != idown:
+                    nup=boundary_dict[ip]['nodes_surf_ymin']
+                    ndow=boundary_dict[idown]['nodes_surf_ymax']
+                    merge_node(nup,ndow)
+                    
+                    if idiag != idown:
+                        if ip in ymax and ip not in xmin:
+                            nlu=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck left up... r u
+                            nru=boundary_dict[ileft]['node_curve_xmaxymax']
+                            merge_node(nlu,nru)
+                        if ip in xmax:
+                            nrd=boundary_dict[ip]['node_curve_xmaxymin'] #node in curve chunck left up... r u
+                            nru=boundary_dict[idown]['node_curve_xmaxymax']
+                            merge_node(nrd,nru)
+                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
+                        nrd=boundary_dict[idown]['node_curve_xminymax']
+                        nld=boundary_dict[idiag]['node_curve_xmaxymax']
+                        nlu=boundary_dict[ileft]['node_curve_xmaxymin']
+                        merge_node_4(nru,nrd,nld,nlu)
+                    elif ip in xmin:
+                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
+                        nrd=boundary_dict[idown]['node_curve_xminymax']
+                        merge_node(nrd,nru)
+                        
+                #
+                if ip != ileft:
+                    nright=boundary_dict[ip]['nodes_surf_xmin']
+                    nleft=boundary_dict[ileft]['nodes_surf_xmax']
+                    merge_node(nright,nleft)
+                    #
+                    #
+                    if ip in ymin:
+                        nrd=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right down... r u
+                        nld=boundary_dict[ileft]['node_curve_xmaxymin']
+                        merge_node(nrd,nld)
+                    if ip in ymax:
+                        nru=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck right up... r u
+                        nlu=boundary_dict[ileft]['node_curve_xmaxymax']
+                        merge_node(nlu,nru)
+        
+        cubit.cmd('set info on')
+        cubit.cmd('set echo on')
+        cubit.cmd('set journal on')
+        
+        
+        #
+        #
+        cmd='group "negativejac" add quality hex all Jacobian high'
+        cubit.cmd(cmd) 
+        group_id_1=cubit.get_id_from_name("negativejac")
+        n1=cubit.get_group_nodes(group_id_1)
+        if len(n1) != 0:
+            print 'error, negative jacobian after the equivalence node command, use --merge2 instead of --equivalence/--merge/--merge1'
+    elif ckbound_method2 and not ckbound_method1:
+        if isinstance(merge_tolerance,list):
+            tol=merge_tolerance[0]
+        elif merge_tolerance:
+            tol=merge_tolerance
+        else:
+            tol=100000
+        #
+        idiag=None
+        for ix in range(cpuxmin,cpuxmax):
+            for iy in range(cpuymin,cpuymax):
+                ip=iy*cpux+ix
+                print '******************* ',ip
+                #
+                #   ileft    |   ip
+                #  --------------------
+                #   idiag    |   idown
+                #
+                #
+                if ip not in xmin and ip not in ymin:
+                    ileft=iy*cpux+ix-1
+                    idown=(iy-1)*cpux+ix
+                    idiag=idown-1
+                elif ip in xmin and ip in ymin:
+                    ileft=ip
+                    idown=ip
+                elif ip in xmin:
+                    ileft=ip
+                    idown=(iy-1)*cpux+ix
+                    idiag=idown
+                elif ip in ymin:
+                    ileft=iy*cpux+ix-1
+                    idown=ip
+                    idiag=ileft
+                #
+                #
+                if ip != idown:
+                    nup=boundary_dict[ip]['nodes_surf_ymin']
+                    ndow=boundary_dict[idown]['nodes_surf_ymax']
+                    for n1,n2 in zip(nup,ndow):
+                        cubit.cmd('equivalence node '+str(n1)+' '+str(n2)+' tolerance '+str(tol))
+                    if idiag != idown:
+                        if ip in ymax and ip not in xmin:
+                            nlu=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck left up... r u
+                            nru=boundary_dict[ileft]['node_curve_xmaxymax']
+                            for n in zip(nlu,nru):
+                                cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
+                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
+                        nrd=boundary_dict[idown]['node_curve_xminymax']
+                        nld=boundary_dict[idiag]['node_curve_xmaxymax']
+                        nlu=boundary_dict[ileft]['node_curve_xmaxymin']
+                        for n in zip(nru,nrd,nlu,nld):
+                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
+                    elif ip in xmin:
+                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
+                        nrd=boundary_dict[idown]['node_curve_xminymax']
+                        for n in zip(nru,nrd):
+                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
+                #
+                #
+                if ip != ileft:
+                    nright=boundary_dict[ip]['nodes_surf_xmin']
+                    nleft=boundary_dict[ileft]['nodes_surf_xmax']
+                    for n1,n2 in zip(nleft,nright):
+                        cubit.cmd('equivalence node '+str(n1)+' '+str(n2)+' tolerance '+str(tol))
+                    #
+                    #
+                    if ip in ymin:
+                        nrd=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right down... r u
+                        nld=boundary_dict[ileft]['node_curve_xmaxymin']
+                        for n in zip(nrd,nld):
+                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
+                    if ip in ymax:
+                        nru=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck right up... r u
+                        nlu=boundary_dict[ileft]['node_curve_xmaxymax']
+                        for n in zip(nru,nlu):
+                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
+        #
+        #
+        cmd='topology check coincident node face all tolerance '+str(tol*2)+' nodraw brief result group "checkcoinc"' 
+        cubit.silent_cmd(cmd)
+        group_id_1=cubit.get_id_from_name("checkcoinc")
+        if group_id_1 != 0:
+            n1=cubit.get_group_nodes(group_id_1)
+            if len(n1) != 0:
+                print 'error, coincident nodes after the equivalence node command, check the tolerance'
+                import sys
+                sys.exit()
+        cmd='group "negativejac" add quality hex all Jacobian high'
+        cubit.cmd(cmd) 
+        group_id_1=cubit.get_id_from_name("negativejac")
+        n1=cubit.get_group_nodes(group_id_1)
+        if len(n1) != 0:
+            print 'error, negative jacobian after the equivalence node command, check the mesh'
+    elif ckbound_method1 and  ckbound_method2:
+        block_list=cubit.get_block_id_list()
+        i=-1
+        for block in block_list:
+            ty=cubit.get_block_element_type(block)
+            if ty == 'HEX8':
+                i=i+1
+                if isinstance(merge_tolerance,list):
+                    try:
+                        tol=merge_tolerance[i]
+                    except:
+                        tol=merge_tolerance[-1]
+                elif merge_tolerance:
+                    tol=merge_tolerance
+                else:
+                    tol=1
+                cmd='topology check coincident node face in hex in block '+str(block)+' tolerance '+str(tol)+' nodraw brief result group "b'+str(block)+'"'
+                cubit.cmd(cmd)
+                print cmd
+                cmd='equivalence node in group b'+str(block)+' tolerance '+str(tol)
+                cubit.cmd(cmd)
+                print cmd
+        if isinstance(merge_tolerance,list):
+            tol=max(merge_tolerance)
+        elif merge_tolerance:
+            tol=merge_tolerance
+        else:
+            tol=1
+        #
+        #
+        cmd='topology check coincident node face all tolerance '+str(tol)+' nodraw brief result group "checkcoinc"' 
+        cubit.silent_cmd(cmd)
+        group_id_1=cubit.get_id_from_name("checkcoinc")
+        if group_id_1 != 0:
+            n1=cubit.get_group_nodes(group_id_1)
+            if len(n1) != 0:
+                print 'error, coincident nodes after the equivalence node command, check the tolerance'
+                import sys
+                sys.exit()
+        cmd='group "negativejac" add quality hex all Jacobian high'
+        cubit.silent_cmd(cmd) 
+        group_id_1=cubit.get_id_from_name("negativejac")
+        n1=cubit.get_group_nodes(group_id_1)
+        if len(n1) != 0:
+            print 'error, negative jacobian after the equivalence node command, use --merge instead of --equivalence'
+
+def collect(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,ckbound_method1=False,ckbound_method2=False,merge_tolerance=None,curverefining=False,outfilename='totalmesh_merged',qlog=False,export2SPECFEM3D=False,listblock=None,listflag=None,outdir='.'):
+    #
+    collecting_merging(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy,cubfiles=cubfiles,ckbound_method1=ckbound_method1,ckbound_method2=ckbound_method2,merge_tolerance=merge_tolerance)
+    #
+    if curverefining:
+        block=1001 #topography
+        refine_closecurve(block,curverefining,acis=True)
+    #
+    #
+    cubit.cmd('compress all')
+    command="export mesh '"+outfilename+".e' block all overwrite xml '"+outfilename+".xml'"
+    cubit.cmd(command)
+    outdir2='/'.join(x for x in outfilename.split('/')[:-1])
+    if outdir2 == '': outdir2='.'
+    f=open(outdir2+'/'+'blocks.dat','w')
+    blocks=cubit.get_block_id_list()
+    #
+    for block in blocks:
+        name=cubit.get_exodus_entity_name('block',block)
+        element_count = cubit.get_exodus_element_count(block, "block")
+        nattrib=cubit.get_block_attribute_count(block)
+        attr=[cubit.get_block_attribute_value(block,x) for x in range(0,nattrib)]
+        ty=cubit.get_block_element_type(block)
+        f.write(str(block)+' ; '+name+' ; nattr '+str(nattrib)+' ; '+' '.join(str(x) for x in attr)+' ; '+ty+' '+str(element_count)+'\n')
+    f.close()
+    #
+    #
+    cubit.cmd('set info echo journ off')
+    cmd='del group all'
+    cubit.silent_cmd(cmd)
+    cubit.cmd('set info echo journ on')
+    #
+    command = "save as '"+outfilename+".cub' overwrite"
+    cubit.cmd(command)
+    #
+    print 'end meshing'
+    #
+    #
+    if qlog:
+        print '\n\nQUALITY CHECK.... ***************\n\n'
+        import quality_log
+        tq=open(outfilename+'.quality','w')
+        max_skewness,min_length=quality_log.quality_log(tq)
+    #
+    #
+    #
+    if export2SPECFEM3D:
+        e2SEM(files=False,listblock=listblock,listflag=listflag,outdir=outdir)
+                                            
+def e2SEM(files=False,listblock=None,listflag=None,outdir='.'):
+    import glob
+    if files:
+        filenames=glob.glob(files)
+        for f in filenames:
+            print f
+            extension=f.split('.')[-1]
+            if extension == 'cub':
+                cubit.cmd('open "'+f+'"')
+            elif extension== 'e':
+                cubit.cmd('import mesh "'+f+'" no_geom')
+            else:
+                print extension
+    if listblock and listflag:
+        pass
+    else:
+        listblock=[]
+        listflag=[]
+        block_list=list(cubit.get_block_id_list())
+        for block in block_list:
+            ty=cubit.get_block_element_type(block)
+            if 'HEX' in ty:
+                listblock.append(block)
+                #listflag.append(block)
+        listflag=range(1,len(listflag)+1)  
+    #       
+    for ib,iflag in zip(listblock,listflag):
+        cubit.cmd("block "+str(ib)+" attribute count 1")
+        cubit.cmd("block "+str(ib)+" attribute index 1 "+ str(iflag)            )
+    #
+    import cubit2specfem3d
+    cubit2specfem3d.export2SPECFEM3D(outdir)
+
+def invert_dict(d):
+     inv = {}
+     for k,v in d.iteritems():
+         keys = inv.setdefault(v, [])
+         keys.append(k)
+     return inv
+     
+     
+     
+def prepare_equivalence(nodes1,nodes2):
+    cubit.cmd('set info off')
+    cubit.cmd('set echo off')
+    cubit.cmd('set journal off')
+    length={}
+    for ns in zip(nodes1,nodes2):
+        cmd='group "tmpn" add edge in node '+' '.join(str(n) for n in ns )
+        cubit.cmd(cmd)
+        ge=cubit.get_id_from_name("tmpn")
+        e1=cubit.get_group_edges(ge)
+        lengthmin=1e9
+        for e in e1:
+            lengthmin=min(lengthmin,cubit.get_mesh_edge_length(e))
+        length[ns]=lengthmin*.5
+        cubit.cmd('delete group '+str(ge))
+    minvalue=min(length.values())
+    maxvalue=max(length.values())
+    print 'min lentgh: ',minvalue,'max lentgh: ',maxvalue
+    nbin= int((maxvalue/minvalue)/2.)+1
+    factor=(maxvalue-minvalue)/nbin
+    dic_new={}
+    for k in length.keys():
+        dic_new[k]=int((length[k]-minvalue)/factor)
+    inv_length=invert_dict(dic_new)
+    print inv_length.keys(),factor,minvalue
+    ks=inv_length.keys()
+    ks.sort()
+    for k in range(0,len(inv_length.keys())-1):
+        inv_length[ks[k]]=inv_length[ks[k]]+inv_length[ks[k+1]]
+    cubit.cmd('set info on')
+    cubit.cmd('set echo on')
+    cubit.cmd('set journal on')
+    return factor,minvalue,inv_length
+
+
+def merge_node(n1,n2):
+    factor,minvalue,inv_length=prepare_equivalence(n1,n2)
+    
+    for k in inv_length.keys()[:-1]:
+        if len(inv_length[k]) > 0:
+            cmd='equivalence node '+' '.join(' '.join(str(n) for n in x) for x in inv_length[k])+' tolerance '+str(k*factor+minvalue/2.)
+            cubit.cmd(cmd)
+            print 'equivalence '+str(len(inv_length[k]))+' couples of nodes -  tolerance '+str(k*factor+minvalue/2.)
+
+
+def prepare_equivalence_4(nodes1,nodes2,nodes3,nodes4):
+    cubit.cmd('set info off')
+    cubit.cmd('set echo off')
+    cubit.cmd('set journal off')
+    length={}
+    for ns in zip(nodes1,nodes2,nodes3,nodes4):
+        cmd='group "tmpn" add edge in node '+' '.join(str(n) for n in ns )
+        cubit.cmd(cmd)
+        ge=cubit.get_id_from_name("tmpn")
+        e1=cubit.get_group_edges(ge)
+        lengthmin=1e9
+        for e in e1:
+            lengthmin=min(lengthmin,cubit.get_mesh_edge_length(e))
+        length[ns]=lengthmin*.5
+        cubit.cmd('delete group '+str(ge))
+    try:
+        minvalue=min(length.values())
+        maxvalue=max(length.values())
+    except:
+        print nodes1,nodes2,nodes3,nodes4
+        print 'edges ', e1
+        minvalue=100.
+        maxvalue=2000.
+    print 'min lentgh: ',minvalue,'max lentgh: ',maxvalue
+    nbin= int((maxvalue/minvalue)/2.)+1
+    factor=(maxvalue-minvalue)/nbin
+    dic_new={}
+    for k in length.keys():
+        dic_new[k]=int((length[k]-minvalue)/factor)
+    inv_length=invert_dict(dic_new)
+    print inv_length.keys(),factor,minvalue
+    ks=inv_length.keys()
+    ks.sort()
+    for k in range(0,len(inv_length.keys())-1):
+        inv_length[ks[k]]=inv_length[ks[k]]+inv_length[ks[k+1]]
+    cubit.cmd('set info on')
+    cubit.cmd('set echo on')
+    cubit.cmd('set journal on')
+    return factor,minvalue,inv_length
+
+
+def merge_node_4(n1,n2,n3,n4):
+    factor,minvalue,inv_length=prepare_equivalence_4(n1,n2,n3,n4)
+    
+    for k in inv_length.keys()[:-1]:
+        if len(inv_length[k]) > 0:
+            cmd='equivalence node '+' '.join(' '.join(str(n) for n in x) for x in inv_length[k])+' tolerance '+str(k*factor+minvalue/2.)
+            cubit.cmd(cmd)
+            print 'equivalence '+str(len(inv_length[k]))+' couples of nodes -  tolerance '+str(k*factor+minvalue/2.)
+
+
+
+
+
+    
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/hex_metric.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/hex_metric.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/hex_metric.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,772 @@
+#############################################################################
+# hex_metric.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+##mesh=SEM_metric_3D
+##mesh.check_metric()
+##print mesh
+#
+#
+import math
+
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+
+class SEM_metric_3D(object):
+    def __init__(self,list_hex=None,volume=None):
+        super(SEM_metric_3D, self).__init__()
+        self.list_hex=list_hex
+        self.volume=volume
+        self.skew_hystogram=None
+        self.max_skewness=None
+        self.max_angle=None
+        self.min_angle=None
+        self.min_edge_length=None
+        self.cubit_skew=0
+        self.max_valence=None
+        self.node_with_max_valence=None
+        self.valence_threshold=7
+        self.resolution=.05
+        self.resolution_edge_length=.1
+        self.nbin=10
+        self.spatial_unit=1
+        self.gll=0.17267316464601141
+        self.dt=None
+    def __repr__(self):
+        if self.max_skewness is not None:
+            self.skew_hystogram=self.hyst(0,self.max_skewness,self.skew_hyst)
+            print '-'*70
+            print 'SKEWNESS'
+            print 
+            if len(self.hex_max_skewness) <= 30:
+                print 'max = ',self.max_skewness,' in hexes ',self.hex_max_skewness
+                print '(angle -> minimun =', self.min_angle, ' maximun =', self.max_angle,')'
+            else:
+                print 'max = ',self.max_skewness,' in ', len(self.hex_max_skewness), ' hexes '
+                print '(angle -> minimun =', self.min_angle, ' maximun =', self.max_angle,')'
+            print 
+            print 'skew hystogram'
+            print 
+            tot=0
+            for i in self.skew_hystogram.values():
+                tot=tot+len(i)
+            #k=self.skew_hystogram.keys()
+            #k.sort()
+            factor=self.max_skewness/self.nbin
+            for i in range(0,self.nbin+1):
+                if self.skew_hystogram.has_key(i):
+                    if (i+1)*factor <= 1:
+                        print i,' [',i*factor,'->',(i+1)*factor,'[ : ',len(self.skew_hystogram[i]),'/',tot,' hexes (',len(self.skew_hystogram[i])/float(tot)*100.,'%)'
+                else:
+                    if (i+1)*factor <= 1:
+                        print i,' [',i*factor,'->',(i+1)*factor,'[ : ',0,'/',tot,' hexes (0%)'
+            print
+        ###############################################
+        if self.min_edge_length is not None:
+            self.edgemin_hystogram=self.hyst(self.min_edge_length,self.max_edge_length,self.edgemin_hyst)
+            self.edgemax_hystogram=self.hyst(self.min_edge_length,self.max_edge_length,self.edgemax_hyst)
+            print '-'*70
+            print 'edge length'
+            print 
+            if len(self.hex_min_edge_length) <= 30:
+                print 'minimum edge length: ', self.min_edge_length, ' in hexes ',  self.hex_min_edge_length
+            else:
+                print 'minimum edge length: ', self.min_edge_length, ' in ',  len(self.hex_min_edge_length), ' hexes.'
+            if len(self.hex_max_edge_length) <= 30:
+                print 'maximum edge length: ', self.max_edge_length, ' in hexes ',  self.hex_max_edge_length              
+            else:                                                                                                                        
+                print 'maximum edge length: ', self.max_edge_length, ' in ',  len(self.hex_max_edge_length), ' hexes.'    
+            print
+            print 'edge length hystogram'
+            print 
+            factor=(self.max_edge_length-self.min_edge_length)/self.nbin
+            print 'minimum edge length'
+            tot=0
+            for i in self.edgemin_hystogram.values():
+                tot=tot+len(i)
+            #k=self.edgemin_hystogram.keys()
+            #k.sort()
+            for i in range(0,self.nbin+1):
+                if self.edgemin_hystogram.has_key(i):
+                    print i,' [',i*factor+self.min_edge_length,'->',(i+1)*factor+self.min_edge_length,'[ : ',len(self.edgemin_hystogram[i]),'/',tot,' hexes (',len(self.edgemin_hystogram[i])/float(tot)*100.,'%)'
+                else:
+                    print i,' [',i*factor+self.min_edge_length,'->',(i+1)*factor+self.min_edge_length,'[ : ',0,'/',tot,' hexes (0%)'
+            print 
+            print 'maximum edge length'
+            tot=0
+            for i in self.edgemax_hystogram.values():
+                tot=tot+len(i)
+            #k=self.edgemax_hystogram.keys()
+            #k.sort()
+            for i in range(0,self.nbin+1):
+                if self.edgemax_hystogram.has_key(i):
+                    print i,' [',i*factor+self.min_edge_length,'->',(i+1)*factor+self.min_edge_length,'[ : ',len(self.edgemax_hystogram[i]),'/',tot,' hexes (',len(self.edgemax_hystogram[i])/float(tot)*100.,'%)'
+                else:
+                    print i,' [',i*factor+self.min_edge_length,'->',(i+1)*factor+self.min_edge_length,'[ : ',0,'/',tot,' hexes (0%)'
+        if self.dt is not None:
+            print '-'*70
+            print
+            print 'STABILITY'
+            print
+            print 'time step < ',self.dt,'s, for velocity = ',self.velocity
+            print 
+        try:
+            return str(len(self.list_hex))+' hexes checked'
+        except:
+            return 'please performe a metric check: ex ... object.check_metric()'
+    #
+    #
+    def invert_dict(self,d):
+         inv = {}
+         for k,v in d.iteritems():
+             keys = inv.setdefault(v, [])
+             keys.append(k)
+         return inv
+    def hex_metric(self,h):
+        nodes=cubit.get_connectivity('Hex',h)
+        equiangle_skewness=None
+        min_angle=float('infinity')
+        edge_length_min=float('infinity')
+        max_angle=None
+        edge_length_max=None
+        #loopnode=[(i,j) for i in range(8) for j in range(i+1,8)]
+        if len(nodes) == 4:
+            faces=[[0,1,2,3]]
+        elif len(nodes) == 8:
+            faces=[[0,1,2,3],[4,5,6,7],[1,5,6,2],[0,4,7,3],[2,6,7,3],[1,5,4,0]]
+        else:
+            print 'bad definition of nodes'
+            return None,None,None
+        x=[]
+        y=[]
+        z=[]
+        for i in nodes:
+            n=cubit.get_nodal_coordinates(i)
+            x.append(n[0])
+            y.append(n[1])
+            z.append(n[2])
+        for face in faces:
+            for i in range(-1,3):
+                vx1=x[face[i-1]]-x[face[i]]
+                vy1=y[face[i-1]]-y[face[i]]
+                vz1=z[face[i-1]]-z[face[i]]
+                #
+                vx2=x[face[i+1]]-x[face[i]]
+                vy2=y[face[i+1]]-y[face[i]]
+                vz2=z[face[i+1]]-z[face[i]]
+                #
+                norm1=math.sqrt(vx1*vx1+vy1*vy1+vz1*vz1)
+                norm2=math.sqrt(vx2*vx2+vy2*vy2+vz2*vz2)
+                #
+                if norm1 == 0 or norm2 == 0:
+                    print 'degenerated mesh, 0 length edge'
+                    import sys
+                    sys.exit()
+                angle=math.acos((vx1*vx2+vy1*vy2+vz1*vz2)/(norm1*norm2))
+                #
+                equiangle_skewness=max(equiangle_skewness,math.fabs(2.*angle-math.pi)/math.pi)
+                min_angle=min(min_angle,angle*180./math.pi)
+                max_angle=max(max_angle,angle*180./math.pi)
+                edge_length_min=min(edge_length_min,norm1)
+                edge_length_max=max(edge_length_max,norm1)
+        return round(equiangle_skewness,5),min_angle,max_angle,round(edge_length_min,5),round(edge_length_max,5)
+    def show(self,minvalue,maxvalue,dic):
+        hexlist=[]
+        for k in dic.keys():
+            if minvalue <= dic[k] <= maxvalue: hexlist.extend([k])
+        #command = "draw hex "+str(hexlist)
+        #command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
+        #cubit.cmd(command)
+        return hexlist
+    def hyst(self,minvalue,maxvalue,dic):
+        if maxvalue != minvalue:
+            factor=(maxvalue-minvalue)/self.nbin
+        else:
+            factor=1
+        dic_new={}
+        for k in dic.keys():
+            dic_new[k]=int((dic[k]-minvalue)/factor)
+        inv_dic=self.invert_dict(dic_new)
+        return inv_dic                                                                                          
+    #
+    #
+    #
+    #
+    #
+    ############################################################################################
+    def pick_hex(self,list_hex=None,volume=None):
+        if self.cubit_skew > 0:
+            command = "del group skew_top"
+            cubit.cmd(command)
+            command = "group 'skew_top' add quality volume all skew low "+str(self.cubit_skew)
+            cubit.silent_cmd(command)
+            group=cubit.get_id_from_name("skew_top")
+            self.list_hex=cubit.get_group_hexes(group)
+        elif list_hex is not None:
+            self.list_hex=list_hex
+        elif volume is not None:
+            command = "group 'hextmp' add hex in volume "+str(volume)    
+            cubit.silent_cmd(command)                                           
+            group=cubit.get_id_from_name("hextmp")                       
+            self.list_hex=cubit.get_group_hexes(group)
+            command = "del group hextmp"
+            cubit.silent_cmd(command)   
+        elif self.volume is not None:
+            command = "group 'hextmp' add hex in volume "+str(self.volume) 
+            cubit.silent_cmd(command)                                        
+            group=cubit.get_id_from_name("hextmp")                    
+            self.list_hex=cubit.get_group_hexes(group)
+            command = "del group hextmp"
+            cubit.silent_cmd(command)                 
+        elif list_hex is None and self.list_hex is None:
+            self.list_hex=cubit.parse_cubit_list('hex','all')
+        print 'list_hex: ',len(self.list_hex),' hexes'
+    #
+    #
+    ############################################################################################
+    #SKEWNESS
+    def check_skew(self,list_hex=None,volume=None):
+        self.pick_hex(list_hex=list_hex,volume=volume)
+        global_max_skew=None
+        global_max_angle=None
+        global_min_angle=float('infinity')
+        tmp=int(1./self.resolution)+1
+        skew_hyst={}
+        for i in range(0,tmp):
+            if i*self.resolution < 1:
+                skew_hyst[i]=[]
+        h_global_max_skew=[]
+        h_global_max_angle=[]
+        h_global_min_angle=[]
+        for h in self.list_hex:
+            equiangle_skewness,min_angle,max_angle,tmp,tmp2=self.hex_metric(h)
+            skew_hyst[h]=equiangle_skewness
+            #
+            if equiangle_skewness > global_max_skew: 
+                global_max_skew=equiangle_skewness
+                h_global_max_shew=[]
+                h_global_max_shew.append(h)
+                global_min_angle=min_angle
+                global_max_angle=max_angle
+            elif equiangle_skewness == global_max_skew:
+                h_global_max_shew.append(h)
+            s=h_global_max_shew
+        self.skew_hyst=skew_hyst
+        self.max_skewness=global_max_skew
+        self.max_angle=global_max_angle
+        self.min_angle=global_min_angle
+        self.hex_max_skewness=s
+    def show_skew(self,low=None,high=None):
+        if low is None and high is not None:
+            hexlist=self.show(low,self.max_skewness,self.skew_hyst)
+        elif low is not None and high is None:
+            hexlist=self.show(0,high,self.skew_hyst)
+        if low is not None and high is not None:
+            hexlist=self.show(low,high,self.skew_hyst)
+        else:
+            hexlist=self.hex_min_edge_length
+        command = "draw hex "+str(hexlist)
+        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
+        cubit.silent_cmd(command)
+    def list_skew(self,low=None,high=None):
+        if low is None and high is not None:
+            hexlist=self.show(low,self.max_skewness,self.skew_hyst)
+        elif low is not None and high is None:
+            hexlist=self.show(0,high,self.skew_hyst)
+        if low is not None and high is not None:
+            hexlist=self.show(low,high,self.skew_hyst)
+        else:
+            hexlist=self.hex_min_edge_length
+        return hexlist
+    def highlight_skew(self,low=None,high=None):
+        if low is None and high is not None:
+            hexlist=self.show(low,self.max_skewness,self.skew_hyst)
+        elif low is not None and high is None:
+            hexlist=self.show(0,high,self.skew_hyst)
+        if low is not None and high is not None:
+            hexlist=self.show(low,high,self.skew_hyst)
+        else:
+            hexlist=self.hex_min_edge_length
+        command = "highlight hex "+str(hexlist)
+        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
+        cubit.silent_cmd(command)
+    #
+    #
+    #
+    #############################################################################################
+    #HEX VALENCE
+    def check_valence(self):
+        #usage: hex_valence()
+        #
+        list_hex=cubit.parse_cubit_list('hex','all')
+        list_node=cubit.parse_cubit_list('node','all')
+        lookup=dict(zip(list_node,[0]*len(list_node)))
+        for h in list_hex:
+            n=cubit.get_connectivity('Hex',h)
+            for i in n:
+                if lookup.has_key(i): lookup[i]=lookup[i]+1
+        inv_lookup=self.invert_dict(lookup)
+        #
+        vmax=max(inv_lookup.keys())
+        nmax=inv_lookup[max(inv_lookup.keys())]
+        print 'max hex valence ',vmax,' at node ',nmax
+        print '_____'
+        for v in inv_lookup.keys():
+            print ('valence %2i - %9i hexes '% (v,len(inv_lookup[v])))
+        self.valence_summary=inv_lookup
+        self.max_valence=vmax
+        self.node_with_max_valence=nmax
+    #
+    #
+    ###########################################################################################
+    #EDGE LENGTH
+    def check_edge_length(self,list_hex=None,volume=None):
+        self.pick_hex(list_hex=list_hex,volume=volume)
+        global_min_edge_length=float('infinity')
+        h_global_min_edge_length=[]
+        global_max_edge_length=None
+        h_global_max_edge_length=[]
+        edgemin_hyst={}
+        edgemax_hyst={}     
+        for h in self.list_hex:
+            tmp,tmp2,tmp3,edge_length_min,edge_length_max=self.hex_metric(h)
+            edgemax_hyst[h]=edge_length_max
+            edgemin_hyst[h]=edge_length_min
+            if edge_length_min < global_min_edge_length:
+                global_min_edge_length=edge_length_min
+                h_global_min_edge_length=[]
+                h_global_min_edge_length.append(h)
+            elif edge_length_min == global_min_edge_length:
+                h_global_min_edge_length.append(h)
+            if edge_length_max > global_max_edge_length:
+                global_max_edge_length=edge_length_max
+                h_global_max_edge_length=[]
+                h_global_max_edge_length.append(h)      
+            elif edge_length_max == global_max_edge_length:    
+                h_global_max_edge_length.append(h)
+        self.min_edge_length=global_min_edge_length
+        self.hex_min_edge_length=h_global_min_edge_length
+        self.max_edge_length=global_max_edge_length
+        self.hex_max_edge_length=h_global_max_edge_length
+        self.edgemin_hyst=edgemin_hyst
+        self.edgemax_hyst=edgemax_hyst        
+    def show_edgemin(self,low=None,high=None):
+        if low is None and high is not None:
+            hexlist=self.show(low,self.max_edge_length,self.edgemin_hyst)
+        elif low is not None and high is None:
+            hexlist=self.show(self.min_edge_length,high,self.edgemin_hyst)
+        if low is not None and high is not None:
+            hexlist=self.show(low,high,self.edgemin_hyst)
+        else:
+            hexlist=self.hex_min_edge_length
+        command = "draw hex "+str(hexlist)
+        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
+        cubit.cmd(command)
+    def show_edgemax(self,low=None,high=None):
+        if low is None and high is not None:
+            hexlist=self.show(low,self.max_edge_length,self.edgemax_hyst)
+        elif low is not None and high is None:
+            hexlist=self.show(self.min_edge_length,high,self.edgemax_hyst)
+        if low is not None and high is not None:
+            hexlist=self.show(low,high,self.edgemax_hyst)
+        else:
+            hexlist=self.hex_max_edge_length
+        command = "draw hex "+str(hexlist)
+        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
+        cubit.cmd(command)
+    def list_edgemax(self,low=None,high=None):
+        if low is None and high is not None:
+            hexlist=self.show(low,self.max_edge_length,self.edgemax_hyst)
+        elif low is not None and high is None:
+            hexlist=self.show(self.min_edge_length,high,self.edgemax_hyst)
+        if low is not None and high is not None:
+            hexlist=self.show(low,high,self.edgemax_hyst)
+        else:
+            hexlist=self.hex_max_edge_length        
+        return hexlist
+    def list_edgemin(self,low=None,high=None):
+        if low is None and high is not None:
+            hexlist=self.show(low,self.max_edge_length,self.edgemin_hyst)
+        elif low is not None and high is None:
+            hexlist=self.show(self.min_edge_length,high,self.edgemin_hyst)
+        if low is not None and high is not None:
+            hexlist=self.show(low,high,self.edgemin_hyst)
+        else:
+            hexlist=self.hex_min_edge_length
+        return hexlist
+    def highlight_edgemin(self,low=None,high=None):
+        if low is None and high is not None:
+            hexlist=self.show(low,self.max_edge_length,self.edgemin_hyst)
+        elif low is not None and high is None:
+            hexlist=self.show(self.min_edge_length,high,self.edgemin_hyst)
+        if low is not None and high is not None:
+            hexlist=self.show(low,high,self.edgemin_hyst)
+        else:
+            hexlist=self.hex_min_edge_length
+        command = "highlight hex "+str(hexlist)
+        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
+        cubit.cmd(command)
+    def highlight_edgemax(self,low=None,high=None):
+        if low is None and high is not None:
+            hexlist=self.show(low,self.max_edge_length,self.edgemax_hyst)
+        elif low is not None and high is None:
+            hexlist=self.show(self.min_edge_length,high,self.edgemax_hyst)
+        if low is not None and high is not None:
+            hexlist=self.show(low,high,self.edgemax_hyst)
+        else:
+            hexlist=self.hex_max_edge_length
+        command = "highlight hex "+str(hexlist)
+        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
+        cubit.cmd(command)    #
+    #
+    #
+    #
+    #
+    ############################################################################################
+    def check_metric(self,list_hex=None,volume=None):
+        self.pick_hex(list_hex=list_hex,volume=volume)
+        skew_hyst={}
+        edata={}
+        edgemin_hyst={}
+        edgemax_hyst={}
+        edgemaxdata={}
+        edgemindata={}
+        #
+        global_min_edge_length=float('infinity')
+        h_global_min_edge_length=[]
+        global_max_edge_length=None
+        h_global_max_edge_length=[]
+        #
+        global_max_skew=None
+        global_max_angle=None
+        global_min_angle=float('infinity')
+        h_global_max_skew=[]
+        h_global_max_angle=[]
+        h_global_min_angle=[]
+        #
+        s=0.
+        for h in self.list_hex:
+            equiangle_skewness,min_angle,max_angle,edge_length_min,edge_length_max=self.hex_metric(h)
+            skew_hyst[h]=equiangle_skewness
+            edgemax_hyst[h]=edge_length_max
+            edgemin_hyst[h]=edge_length_min
+            if edge_length_min < global_min_edge_length:
+                global_min_edge_length=edge_length_min
+                h_global_min_edge_length=[]
+                h_global_min_edge_length.append(h)
+            elif edge_length_min == global_min_edge_length:
+                h_global_min_edge_length.append(h)
+            if edge_length_max > global_max_edge_length:
+                global_max_edge_length=edge_length_max
+                h_global_max_edge_length=[]
+                h_global_max_edge_length.append(h)     
+            elif edge_length_max == global_max_edge_length:   
+                h_global_max_edge_length.append(h)
+            if equiangle_skewness > global_max_skew: 
+                global_max_skew=equiangle_skewness
+                h_global_max_shew=[]
+                h_global_max_shew.append(h)
+                global_min_angle=min_angle
+                global_max_angle=max_angle
+            elif equiangle_skewness == global_max_skew:
+                h_global_max_shew.append(h)
+            s=h_global_max_shew
+        #
+        self.max_skewness=global_max_skew    
+        self.max_angle=global_max_angle      
+        self.min_angle=global_min_angle      
+        self.hex_max_skewness=s
+        self.skew_hyst=skew_hyst
+        #                
+        self.min_edge_length=global_min_edge_length
+        self.hex_min_edge_length=h_global_min_edge_length
+        self.max_edge_length=global_max_edge_length
+        self.hex_max_edge_length=h_global_max_edge_length
+        self.edgemin_hyst=edgemin_hyst
+        self.edgemax_hyst=edgemax_hyst
+        #
+        
+class SEM_stability_3D(SEM_metric_3D):
+    def __init__(self,list_hex=None,volume=None):
+        super(SEM_metric_3D, self).__init__()
+        self.list_hex=list_hex
+        self.volume=volume
+        self.Ngll_per_wavelength=5
+        self.gllcoeff=.17
+        self.maxgllcoeff=0.5-.17
+        self.Cmax=.3
+        self.nbin=10
+        self.period_hyst=None
+        self.dt=None
+        self.cubit_skew =0
+        #
+        #
+        #
+    def __repr__(self):
+        print 'check mesh stability'
+        #
+    def check_simulation_parameter(self,list_hex=None,volume=None,tomofile=None,vp_static=None,vs_static=None):
+        self.pick_hex(list_hex=list_hex,volume=volume)
+        timestep_hyst={}
+        stability_hyst={}
+        global_min_timestep=float(1)
+        global_max_periodresolved=None
+        if tomofile: 
+            self.read_tomo(tomofile)
+        #
+        #
+        for ind,h in enumerate(self.list_hex):
+            if ind%10000==0: print 'hex checked: '+str(int(float(ind)/len(self.list_hex)*100))+'%'
+            dt_tmp,pmax_tmp,_,_=self.hex_simulation_parameter(h,vp_static=vp_static,vs_static=vs_static)
+            timestep_hyst[h]=dt_tmp
+            stability_hyst[h]=pmax_tmp
+            if dt_tmp < global_min_timestep:
+                global_min_timestep=dt_tmp
+            if pmax_tmp > global_max_periodresolved:
+                global_max_periodresolved=pmax_tmp   
+        #
+        self.period=global_max_periodresolved    
+        self.dt=global_min_timestep      
+        self.dt_hyst=timestep_hyst
+        self.period_hyst=stability_hyst
+        #                
+    def read_tomo(self,tomofile=None):
+        if tomofile:
+            print 'reading tomography file ',tomofile
+            import numpy
+            #xtomo,ytomo,ztomo,vp,vs,rho=numpy.loadtxt(tomofile,skiprows=4)
+            print 'tomography file loaded'
+            tf=open(tomofile,'r')
+            orig_x, orig_y, orig_z, end_x, end_y, end_z        =map(float,tf.readline().split())
+            spacing_x, spacing_y, spacing_z                    =map(float,tf.readline().split())
+            nx, ny, nz                                         =map(int,tf.readline().split())
+            vp_min, vp_max, vs_min, vs_max, rho_min, rho_max   =map(float,tf.readline().split())
+            #
+            ind=0
+            import sys
+            xtomo,ytomo,ztomo,vp,vs=[],[],[],[],[]
+            while ind<nx*ny*nz:
+                ind=ind+1
+                if ind%100000==0: sys.stdout.write("reading progress: %i/%i   \r" % (ind,(nx*ny*nz)) )
+                x,y,z,v1,v2,_=map(float,tf.readline().split())
+                xtomo.append(x)
+                ytomo.append(y)
+                ztomo.append(z)
+                vp.append(v1)
+                vs.append(v2)
+            tf.close()
+            print 'tomography file loaded'
+            #
+            self.orig_x, self.orig_y, self.orig_z, self.end_x, self.end_y, self.end_z        = orig_x, orig_y, orig_z, end_x, end_y, end_z        
+            self.spacing_x, self.spacing_y, self.spacing_z                    = spacing_x, spacing_y, spacing_z                    
+            self.nx, self.ny, self.nz                                         = nx, ny, nz                                         
+            self.vp_min, self.vp_max, self.vs_min, self.vs_max = vp_min, vp_max, vs_min, vs_max
+            self.xtomo,self.ytomo,self.ztomo,self.vp,self.vs=xtomo,ytomo,ztomo,vp,vs
+        else:
+            print 'no tomofile!!!!'
+            #
+            #
+            #
+    def tomo(self,x,y,z,vp_static=None,vs_static=None):
+        if not vp_static:
+            spac_x = (x - self.orig_x) / self.spacing_x
+            spac_y = (y - self.orig_y) / self.spacing_y
+            spac_z = (z - self.orig_z) / self.spacing_z
+            #
+            ix = int(spac_x)
+            iy = int(spac_y)
+            iz = int(spac_z)
+            #
+            gamma_interp_x = spac_x - float(ix)
+            gamma_interp_y = spac_y - float(iy)
+            #
+            NX=self.nx
+            NY=self.ny
+            NZ=self.nz
+            if(ix < 0):
+                ix = 0
+                gamma_interp_x = 0.
+            if(ix > NX-2):         
+                ix = NX-2          
+                gamma_interp_x = 1.
+            if(iy < 0):            
+                iy = 0             
+                gamma_interp_y = 0.
+            if(iy > NY-2):         
+                iy = NY-2          
+                gamma_interp_y = 1.
+            if(iz < 0):            
+                 iz = 0
+            if(iz > NZ-2):
+                 iz = NZ-2
+            #
+            p0 = ix+iy*NX+iz*(NX*NY)
+            p1 = (ix+1)+iy*NX+iz*(NX*NY)
+            p2 = (ix+1)+(iy+1)*NX+iz*(NX*NY)
+            p3 = ix+(iy+1)*NX+iz*(NX*NY)
+            p4 = ix+iy*NX+(iz+1)*(NX*NY)
+            p5 = (ix+1)+iy*NX+(iz+1)*(NX*NY)
+            p6 = (ix+1)+(iy+1)*NX+(iz+1)*(NX*NY)
+            p7 = ix+(iy+1)*NX+(iz+1)*(NX*NY)
+            #
+            if self.ztomo[p4]==self.ztomo[p0]:
+                gamma_interp_z1 = 1
+            else:
+                gamma_interp_z1 = (z-self.ztomo[p0])/(self.ztomo[p4]-self.ztomo[p0])
+            if(gamma_interp_z1 > 1.): gamma_interp_z1 = 1.
+            if(gamma_interp_z1 < 0.): gamma_interp_z1 = 0.
+            #
+            if self.ztomo[p5]==self.ztomo[p1]:
+                gamma_interp_z2 = 1
+            else:
+                gamma_interp_z2 = (z-self.ztomo[p1])/(self.ztomo[p5]-self.ztomo[p1])
+            if(gamma_interp_z2 > 1.): gamma_interp_z2 = 1.
+            if(gamma_interp_z2 < 0.): gamma_interp_z2 = 0.
+            #
+            if self.ztomo[p6]==self.ztomo[p2]:
+                gamma_interp_z3 = 1
+            else:
+                gamma_interp_z3 = (z-self.ztomo[p2])/(self.ztomo[p6]-self.ztomo[p2])
+            if(gamma_interp_z3 > 1.): gamma_interp_z3 = 1.
+            if(gamma_interp_z3 < 0.): gamma_interp_z3 = 0.
+            #
+            if self.ztomo[p7]==self.ztomo[p3]:
+                gamma_interp_z4 = 1
+            else:
+                gamma_interp_z4 = (z-self.ztomo[p3])/(self.ztomo[p7]-self.ztomo[p3])
+            if(gamma_interp_z4 > 1.): gamma_interp_z4 = 1.
+            if(gamma_interp_z4 < 0.): gamma_interp_z4 = 0.
+            #
+            gamma_interp_z5 = 1. - gamma_interp_z1
+            gamma_interp_z6 = 1. - gamma_interp_z2
+            gamma_interp_z7 = 1. - gamma_interp_z3
+            gamma_interp_z8 = 1. - gamma_interp_z4
+            #
+            vp1 = self.vp[p0]
+            vp2 = self.vp[p1]
+            vp3 = self.vp[p2]
+            vp4 = self.vp[p3]
+            vp5 = self.vp[p4]
+            vp6 = self.vp[p5]
+            vp7 = self.vp[p6]
+            vp8 = self.vp[p7]
+            #       [  ]
+            vs1 = self.vs[p0]
+            vs2 = self.vs[p1]
+            vs3 = self.vs[p2]
+            vs4 = self.vs[p3]
+            vs5 = self.vs[p4]
+            vs6 = self.vs[p5]
+            vs7 = self.vs[p6]
+            vs8 = self.vs[p7]
+            #
+            vp_final = vp1*(1.-gamma_interp_x)*(1.-gamma_interp_y)*(1.-gamma_interp_z1) + \
+               vp2*gamma_interp_x*(1.-gamma_interp_y)*(1.-gamma_interp_z2) + \
+               vp3*gamma_interp_x*gamma_interp_y*(1.-gamma_interp_z3) + \
+               vp4*(1.-gamma_interp_x)*gamma_interp_y*(1.-gamma_interp_z4) + \
+               vp5*(1.-gamma_interp_x)*(1.-gamma_interp_y)*gamma_interp_z1 + \
+               vp6*gamma_interp_x*(1.-gamma_interp_y)*gamma_interp_z2 + \
+               vp7*gamma_interp_x*gamma_interp_y*gamma_interp_z3 + \
+               vp8*(1.-gamma_interp_x)*gamma_interp_y*gamma_interp_z4
+            #
+            vs_final = vs1*(1.-gamma_interp_x)*(1.-gamma_interp_y)*(1.-gamma_interp_z1) + \
+               vs2*gamma_interp_x*(1.-gamma_interp_y)*(1.-gamma_interp_z2) + \
+               vs3*gamma_interp_x*gamma_interp_y*(1.-gamma_interp_z3) + \
+               vs4*(1.-gamma_interp_x)*gamma_interp_y*(1.-gamma_interp_z4) + \
+               vs5*(1.-gamma_interp_x)*(1.-gamma_interp_y)*gamma_interp_z1 + \
+               vs6*gamma_interp_x*(1.-gamma_interp_y)*gamma_interp_z2 + \
+               vs7*gamma_interp_x*gamma_interp_y*gamma_interp_z3 + \
+               vs8*(1.-gamma_interp_x)*gamma_interp_y*gamma_interp_z4
+            #
+            if(vp_final < self.vp_min): vp_final = self.vp_min
+            if(vs_final < self.vs_min): vs_final = self.vs_min
+            if(vp_final > self.vp_max): vp_final = self.vp_max
+            if(vs_final > self.vs_max): vs_final = self.vs_max
+            return vp_final,vs_final
+        else:
+            return vp_static,vs_static
+    #
+    def hex_simulation_parameter(self,h,vp_static=None,vs_static=None):
+        nodes=cubit.get_connectivity('Hex',h)
+        id_nodes=[0,1,2,3,4,5,6,7]
+        id_faces=[[1,3,4],[0,2,5],[1,3,6],[0,2,7],[5,7],[4,6],[5,7],[4,6]]
+        dt=[]
+        pmax=[]
+        vmax=[]
+        vmin=[]
+        for i in id_nodes[:-1]:
+            for j in id_nodes[i+1:]:
+                x1,y1,z1=cubit.get_nodal_coordinates(nodes[i])
+                x2,y2,z2=cubit.get_nodal_coordinates(nodes[j])
+                nvp1,nvs1=self.tomo(x1,y1,z1,vp_static,vs_static)
+                nvp2,nvs2=self.tomo(x2,y2,z2,vp_static,vs_static)
+                d=math.sqrt((x2-x1)**2+(y2-y1)**2+(z2-z1)**2)
+                #pmax_tmp=d*self.gllcoeff/min(nvp1,nvp2,nvs1,nvs2)*self.Ngll_per_wavelength
+                pmax_tmp=d*(.5-self.gllcoeff)/min(nvp1,nvp2,nvs1,nvs2)*self.Ngll_per_wavelength #more conservative.....
+                dt_tmp=self.Cmax*d*self.gllcoeff/max(nvp1,nvp2,nvs1,nvs2)
+                dt.append(dt_tmp)
+                pmax.append(pmax_tmp)
+                vmax.append(max(nvp1,nvp2,nvs1,nvs2))
+                vmin.append(min(nvp1,nvp2,nvs1,nvs2))
+        return min(dt),max(pmax),min(vmin),max(vmax)
+    #
+    def group_period(self):
+        tot=0.
+        if self.period_hyst is not None:
+            pmin=min(self.period_hyst.values())
+            period=self.hyst(pmin,self.period,self.period_hyst)
+            factor=(self.period-pmin)/self.nbin
+            for i in range(0,self.nbin+1):
+                if period.has_key(i):
+                    txt='group "period_%.1e_%.1e" add hex ' %(pmin+factor*i,pmin+factor*(i+1))
+                    txt=txt+' '.join(str(hh) for hh in period[i])
+                    cubit.cmd(txt)
+    def group_timestep(self):
+         tot=0.
+         if self.dt_hyst is not None:
+             dtmax=max(self.dt_hyst.values())
+             dt=self.hyst(self.dt,dtmax,self.dt_hyst)
+             factor=(dtmax-self.dt)/self.nbin
+             for i in range(0,self.nbin+1):
+                 if dt.has_key(i):
+                     txt='group "timestep_%.1e_%.1e" add hex ' %(self.dt+factor*i,self.dt+factor*(i+1))
+                     txt=txt+' '.join(str(hh) for hh in dt[i])
+                     cubit.cmd(txt)
+
+
+#cubit.cmd('brick x 10000')
+#cubit.cmd('mesh vol 1')
+#cubit.cmd('refine hex in node in surf 1')
+#cubit.cmd('refine hex in node in surf 3')
+#vp=1000
+#vs=600
+#mesh=SEM_stability_3D()
+#mesh.check_simulation_parameter(vp_static=vp,vs_static=vs)
+#mesh.group_timestep()
+#mesh.group_period()
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/local_volume.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/local_volume.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/local_volume.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,242 @@
+#############################################################################
+# local_volume.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+
+def read_grid(filename=None):
+    import sys
+    import start as start
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    #
+    numpy                       = start.start_numpy()
+    cfg                         = start.start_cfg(filename=filename)
+    from utilities import geo2utm
+    
+    #     
+    if cfg.nx and cfg.ny:
+        nx=cfg.nx
+        ny=cfg.ny
+        if cfg.nstep:
+            nx=min(cfg.nx,int(cfg.nx/cfg.nstep)+1)
+            ny=min(cfg.ny,int(cfg.ny/cfg.nstep)+1)
+            nstep=cfg.nstep
+        else:
+            nstep=1
+    else:
+        try:
+            xstep=cfg.step
+            ystep=cfg.step
+        except:
+            xstep=cfg.xstep
+            ystep=cfg.ystep
+        nx= int((cfg.longitude_max-cfg.longitude_min)/xstep)+1
+        ny= int((cfg.latitude_max-cfg.latitude_min)/ystep)+1
+        nstep=1
+    #
+    elev=numpy.zeros([nx,ny,cfg.nz],float)
+    coordx=numpy.zeros([nx,ny],float)
+    coordy=numpy.zeros([nx,ny],float)
+    #
+    if  cfg.bottomflat: 
+        elev[:,:,0] = cfg.depth_bottom
+        bottomsurface=1
+    else:
+        bottomsurface=0
+            #
+    for inz in range(bottomsurface,cfg.nz):
+        try:
+             grdfile = open(cfg.filename[inz-bottomsurface], 'r')
+             print 'reading ',cfg.filename[inz-bottomsurface]
+        except:
+             txt='error reading: '+  str( cfg.filename[inz-bottomsurface] )
+             raise NameError, txt
+        #
+        icoord=0
+        for iy in range(0,ny):
+            for ix in range(0,nx):
+                txt=grdfile.readline()
+                try:
+                    if len(txt) != 0:
+                        x,y,z=map(float,txt.split())
+                        if iy%nstep == 0 and ix%nstep == 0:
+                            icoord=icoord+1
+                            x_current,y_current=geo2utm(x,y,cfg.unit)
+                            jx=min(nx-1,ix/nstep)
+                            jy=min(ny-1,iy/nstep)
+                            coordx[jx,jy]=x_current
+                            coordy[jx,jy]=y_current
+                            elev[jx,jy,inz]=z      
+                except:
+                    print 'error reading point ',iy*cfg.nx+ix,txt, cfg.filename[inz-bottomsurface], ' proc ',iproc
+                    raise NameError, 'error reading point'
+                    #
+        if  (nx)*(ny) != icoord: 
+            if iproc == 0: print 'error in the surface file '+cfg.filename[inz-bottomsurface]
+            if iproc == 0: print 'x points ' +str(nx)+ ' y points ' +str(ny)+ ' tot points '+str((nx)*(ny)) 
+            if iproc == 0: print 'points read in '+cfg.filename[inz-bottomsurface]+': '+str(icoord)
+            raise NameError
+            
+        #if iproc == 0: print 'end of reading grd ascii file '+cfg.filename[inz-bottomsurface]+' '+str(icoord)+ ' points'
+        grdfile.close()
+    
+    
+    return coordx,coordy,elev,nx,ny
+    
+
+def extract_volume(xmin,ymin,xmax,ymax,coordx,coordy,elev,nx,ny,filename=None):
+    import sys
+    import start as start
+    #
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    #
+    numpy                       = start.start_numpy()
+    cfg                         = start.start_cfg(filename=filename)             
+    
+    from utilities import geo2utm
+    #
+    rxstep=coordx[1,0]-coordx[0,0]
+    rystep=coordy[0,1]-coordy[0,0]
+    
+    nxmin_cpu=min(0,int((x0-cfg.xmin)/rxstep)+1-10)
+    nymin_cpu=min(0,int((y0-cfg.ymin)/rxstep)+1-10)
+    nxmax_cpu=min(nx,int((x0-cfg.xmin)/rystep)+1+10)
+    nymax_cpu=min(ny,int((y0-cfg.ymin)/rystep)+1+10)
+    #
+    #
+    icurve=0
+    isurf=0
+    ivertex=0
+    #
+    #create vertex
+    last_surface=cubit.get_last_id('surface')
+    for inz in range(0,cfg.nz):
+        if  cfg.bottomflat and inz == 0: #bottom layer
+                    
+                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],cfg.unit)
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)
+                    #
+                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],cfg.unit)
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)                                                                              
+                    #
+                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],cfg.unit)
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)
+                    #
+                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],cfg.unit)
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)
+                    #
+                    cubitcommand= 'create surface vertex 1 2 3 4'
+                    cubit.cmd(cubitcommand)
+                    #
+                    isurf = isurf + 1
+                    
+        else:
+                vertex=[]
+                
+                for iy in range(nymin_cpu,nymax_cpu+1):
+                    ivx=0
+                    for ix in range(nxmin_cpu,nxmax_cpu+1):
+                        zvertex=elev[ix,iy,inz]
+                        x_current,y_current=geo2utm(coordx[ix,iy],coordy[ix,iy],cfg.unit)
+                        #
+                        vertex.append(' Position '+ str( x_current ) +' '+ str( y_current )+' '+ str( zvertex ) )
+                #
+                print iproc, 'vertex created....'
+                n=max(nx,ny)
+                uline=[]
+                vline=[]
+                iv=0
+                
+                cubit.cmd("set info off")
+                cubit.cmd("set echo off")
+                cubit.cmd("set journal off")
+                
+                for iy in range(0,nymax_cpu-nymin_cpu+1):
+                    positionx=''
+                    for ix in range(0,nxmax_cpu-nxmin_cpu+1):
+                        positionx=positionx+vertex[iv]
+                        iv=iv+1
+                    command='create curve spline '+positionx
+                    cubit.cmd(command)
+                    uline.append( cubit.get_last_id("curve") )
+                for ix in range(0,nxmax_cpu-nxmin_cpu+1):
+                    positiony=''
+                    for iy in range(0,nymax_cpu-nymin_cpu+1):
+                        positiony=positiony+vertex[ix+iy*(nxmax_cpu-nxmin_cpu+1)]
+                    command='create curve spline '+positiony
+                    cubit.cmd(command)
+                    vline.append( cubit.get_last_id("curve") )
+                #
+                cubit.cmd("set info "+cfg.cubit_info)
+                cubit.cmd("set echo "+cfg.echo_info)
+                cubit.cmd("set journal "+cfg.jou_info)
+                #
+                #
+                print iproc,'line created....'
+                umax=max(uline)
+                umin=min(uline)
+                vmax=max(vline)
+                vmin=min(vline)
+                cubitcommand= 'create surface net u curve '+ str( umin )+' to '+str( umax )+ ' v curve '+ str( vmin )+ ' to '+str( vmax )+' heal'
+                cubit.cmd(cubitcommand)
+                command = "del curve all"
+                cubit.cmd(command)
+                isurf=isurf+1
+                #
+                #
+        cubitcommand= 'del vertex all'
+        cubit.cmd(cubitcommand)
+        #cubit_error_stop(iproc,cubitcommand,ner)
+    cubitcommand= 'del curve all'
+    cubit.cmd(cubitcommand)
+    #
+    last_surface_2=cubit.get_last_id('surface')
+    #
+    for inz in range(1,cfg.nz):
+        #!cubit cmd
+        cubitcommand= 'create volume loft surface '+ str( inz+1 )+' '+str( inz )
+        cubit.cmd(cubitcommand)
+        #cubit_error_stop(iproc,cubitcommand,ner)
+        isurf=isurf+6
+    cubitcommand= 'del surface '+str(last_surface+1)+' to '+ str( last_surface_2 )
+    cubit.cmd(cubitcommand)
+    #cubit_error_stop(iproc,cubitcommand,ner)
+    #
+    #        
+    cubit.cmd("set info "+cfg.cubit_info)
+    cubit.cmd("set echo "+cfg.echo_info)
+    cubit.cmd("set journal "+cfg.jou_info)
+    command = "compress all"
+    cubit.cmd(command)
+    
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/menu.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/menu.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/menu.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,315 @@
+#############################################################################
+# menu.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+
+import getopt, sys
+
+def usage():
+    print """
+    GEOCUBIT HELP...
+    
+    1) UTILITIES
+    
+         check the configuration of the libraries and dependencies:
+         GEOCUBIT.py --chklib
+         
+         check the parameter file:
+         GEOCUBIT.py --chkcfg --cfg=[filename]
+         
+    2) CREATE GEOMETRY
+    
+         create a surface from regular ascii grid or ascii lines defining a skin:
+         GEOCUBIT.py --surface=[surface file] (--regulargrid=[options]) (--skin=[options])
+         
+         create a plane surface
+         GEOCUBIT.py --plane --x1=[x,y,z] --x2=[x,y,z] --x3=[x,y,z] --x4=[x,y,z] --unit=[utm/geo]
+         
+         create acis surfaces using a parameter file:
+         GEOCUBIT.py --build_surface --cfg=[filename]
+         
+         **SERIAL**: create cubit volumes using a parameter file:
+         GEOCUBIT.py --build_volume --cfg=[filename] (--id_proc=[num_processor, default=0])
+         
+         **PARALLEL**: create a volume from a parameter file
+         mpirun -n [numproc] pyMPI GEOCUBIT.py --build_volume --cfg=[filename
+         
+    3) MESHING
+    
+         **SERIAL**: meshing a volumes
+         GEOCUBIT.py --mesh --cfg=[filename] (--id_proc=[num_processor, default=0])       - note: without the --build_volume flag the script recall an old 'geometry_vol_[id_proc].cub' file
+         
+         build a volume and mesh it....
+         GEOCUBIT.py --build_volume --mesh --cfg=[filename] (--id_proc=[num_processor, default=0])
+         
+         **PARALLEL**: meshing a volume from a parameter file (it is possible to skip the build_volume and use some geometry files already created, but only with a parallel file system and it is risky)
+         mpirun -n [numproc] pyMPI GEOCUBIT.py --build_volume --mesh --cfg=[filename]
+         
+    4) FINALIZING AND EXPORTING
+    
+         collect some cubit files and merge in a single free mesh cubitfile
+         GEOCUBIT.py --collect   --merge --meshfiles=[list of files] --cpux=N --cpuy=N (--rangecpux=[cpuxmin,cpuxmax], --rangecpuy=[cpuymin,cpuymax])
+         
+         collect a single free mesh cubitfile and refine the hex inside some curve (ex. basin)
+         GEOCUBIT.py --collect --meshfiles=[list of files] --curverefining=[list of SAT files]       
+         
+         export a cubit mesh file (with blocks defined following the note)  in a SPECFEM3D_SESAME mesh
+         GEOCUBIT.py --export2SPECFEM3D --meshfiles=[filename] (--listblock=block1,block2,..,blockN --listflag=[list of specfem flag, i.e. --listflag=1,2,3,-1])
+         
+    """
+try:
+    opts, args = getopt.getopt(sys.argv[1:], "sjmohbp1", ["SEMoutput=","qlog","mfast","curverefining=","output=","rangecpux=","rangecpuy=","equivalence","listflag=","listblock=","cpux=","cpuy=","exofiles=","partitioner","plane","x1=","x2=","x3=","x4=","unit=","chkcfg","mat=","merge_tolerance=","export2SPECFEM3D=","mesh","chklib","cfg=","job=","basin","help", "id_proc=", "surface=","script","jou","strat","MPI","regulargrid=",'skin=',"build_surface","build_volume","merge1","merge2","merge","collect","meshfiles="])
+    print opts, args
+except getopt.GetoptError,errmsg:
+    if str(errmsg) == 'option --export2SPECFEM3D requires argument':
+        for i,xop in enumerate(sys.argv[1:]):
+            if 'export2SPECFEM3D' in xop:
+                sys.argv[i+1]=sys.argv[i+1]+'=.'
+        try:
+            opts, args = getopt.getopt(sys.argv[1:], "sjmohbp1", ["SEMoutput=","qlog","mfast","curverefining=","output=","rangecpux=","rangecpuy=","equivalence","listflag=","listblock=","cpux=","cpuy=","exofiles=","partitioner","plane","x1=","x2=","x3=","x4=","unit=","chkcfg","mat=","merge_tolerance=","export2SPECFEM3D=","mesh","chklib","cfg=","job=","basin","help", "id_proc=", "surface=","script","jou","strat","MPI","regulargrid=",'skin=',"build_surface","build_volume","merge1","merge2","merge","collect","meshfiles="])
+            print opts, args
+        except getopt.GetoptError,errmsg:
+            print str(errmsg)
+            usage()
+            sys.exit(2)
+    else:
+        print str(errmsg)
+        usage()
+        sys.exit()
+except AttributeError:
+    opts=None
+    args=None
+    print opts, args
+    
+output='totalmesh_merged'
+SPECFEM3D_output_dir='.'
+verbose = False
+surface = False
+script = False
+mesh = False
+basin = False
+configuration = None
+id_proc=0
+single=False
+nomesh=False
+jobid=0
+build_surface=False
+build_volume=False
+meshing=False
+ckbound_method1=False
+ckbound_method2=False
+collect=False
+export2SPECFEM3D=False
+merge_tolerance=0
+material_file='material_archive.dat'
+material_assignement=[]
+chkcfg=False
+create_plane=False
+create_partitioner=False
+cubfiles=None
+exofiles=None
+listflag=None
+listblock=None
+cpux=0
+cpuy=0
+cpuxmin=0
+cpuymin=0
+cpuxmax=None
+cpuymax=None
+curverefining=False
+
+
+
+
+
+qlog=False
+
+
+if opts: 
+    for o, value in opts:
+        #print o,value
+        if o in ('--partitioner'):
+            create_partitioner=True
+        if o == ('--surface'):
+            surface=True
+            surface_name=value
+        if o == ('--build_surface'):
+            build_surface=True
+        if o == ('--build_volume'):
+            build_volume=True
+        if surface and o == ('--regular_grid'):
+            surface_type='regular_grid'
+            tmp=value.split('/')
+            if len(tmp)==4:
+                num_x,num_y,unit,delimiter=value.split('/')
+            elif len(tmp)==3:
+                num_x,num_y,unit=value.split('/')
+            num_x=int(num_x)
+            num_y=int(num_y)
+            delimiter=' '
+        if surface and o == ('--skin'):
+            surface_type='skin'
+            tmp=value.split('/')
+            if len(tmp)==4:
+                directionx,directiony,unit,delimiter=value.split('/')
+            elif len(tmp)==3:
+                directionx,directiony,unit=value.split('/')
+            directiony=int(directiony)
+            directionx=int(directionx)
+        if o in ('--plane'):
+            create_plane=True
+            cfg_name=False
+        if o in ('--x1'):
+            x1=value
+        if o in ('--x2'):
+            x2=value
+        if o in ('--x3'):         
+            x3=value
+        if o in ('--x4'):         
+            x4=value
+        if o in ('--unit'):
+           unit=value
+        #
+        if o in ('--build_volume'):
+            build_volume=True
+        if o in ("-h", "--help"):
+            usage()
+            sys.exit(2)
+        #chec   k the configuration
+        if o in ("--chklib"):
+            import start as start
+            mpiflag,iproc,numproc,mpi   = start.start_mpi()
+            if mpiflag:
+                print '--------, MPI ON, parallel mesher ready'
+            else:
+                print '--------, MPI OFF, serial mesher ready'
+            numpy                       = start.start_numpy()
+            print '--------, Numpy ON'
+            cubit                  = start.start_cubit()
+            print '--------, CUBIT ON'
+            sys.exit()
+        if o in ("--cfg"):
+            cfg_name=value
+        if o == ('--surface'):
+            surface=True
+            surface_name=value
+        if o == ("--mesh"):
+            meshing=True
+        if o in ("-1"):
+            single=True
+        if o in ("--collect"):
+            collect=True
+        if o in ("--merge2") and o != '--merge':
+            ckbound_method2=True
+        if o in ("--equivalence","--merge1","--merge"):
+            ckbound_method1=True
+        if o in ("--mfast"):
+            ckbound_method1=True
+            ckbound_method2=True
+        if o in ("--meshfiles"):
+            cubfiles=value
+        if o in ("--exofiles"):
+            exofiles=value
+        if o in ("--export2SPECFEM3D"):
+               export2SPECFEM3D=True
+               SPECFEM3D_output_dir=value
+               import os
+               try:
+                   os.makedirs(SPECFEM3D_output_dir)
+               except OSError:
+                   pass
+        if o in ("--merge_tolerance") and o != '--merge' and o != '--merge2' and o != '--merge1':
+             merge_tolerance=map(float,value.split(','))
+        if o in ("--mat"):
+            material_assignement.append([value.split(',')[0],value.split(',')[1]])
+        if o in ("--listblock"):
+            listblock=map(int,value.split(','))
+        if o in ("--listflag"):
+            listflag=map(int,value.split(','))
+        if o in ("--chkcfg"):
+            chkcfg=True
+        if o in ('--id_proc'):
+            id_proc=int(value)
+        if o in ('--rangecpux'):
+            cpuxmin=int(value.split(',')[0])
+            cpuxmax=int(value.split(',')[1])+1
+        if o in ('--rangecpuy'):
+            cpuymin=int(value.split(',')[0])
+            cpuymax=int(value.split(',')[1])+1
+        if o in ('--cpux'):
+            cpux=int(value)
+        if o in ('--cpuy'):
+            cpuy=int(value)
+        if o in ("--qlog"):
+            qlog=True
+        if o in ("--output","-o"):
+            output=value
+        if o in ("--curverefining"):
+            curverefining=value.split(',')
+        if o in ("SEMoutput"):
+            SPECFEM3D_output_dir=value
+    print cpuxmax,cpuymax
+    if cpuymax:
+        pass
+    elif cpuy > 1:
+        cpuymax=cpuy
+    else:
+        cpuymax=1
+    if cpuxmax:
+        pass
+    elif cpux > 1:
+        cpuxmax=cpux
+    else:
+        cpuxmax=1	    
+    print cpuxmax,cpuymax
+    if chkcfg==True:        
+        import start as start
+        cfg=start.start_cfg()
+        d=cfg.__dict__
+        ks=d.keys()                                                              
+        ks.sort()                                                                
+        for k in ks:                                                             
+            if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
+                txt=str(k)+' -----> '+str(d[k])                              #    
+                txt=txt.replace("'","").replace('"','')                      #    
+                print txt                               #
+    else:
+        try:
+            import start as start
+            cfg=start.start_cfg()
+            f=open('cfg.log','w')
+            print>>f, 'CFG FILE: ',cfg_name
+            d=cfg.__dict__
+            ks=d.keys()                                                              
+            ks.sort()                                                                
+            for k in ks:                                                             
+                if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
+                    txt=str(k)+' -----> '+str(d[k])                              #    
+                    txt=txt.replace("'","").replace('"','')                      #    
+                    print>>f, txt
+            f.close()                               #
+        except:
+            pass
+elif opts == []:
+    print __name__
+    usage()
+    raise AttributeError('no options')

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/mesh_volume.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/mesh_volume.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/mesh_volume.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,443 @@
+#############################################################################
+# mesh_volume.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+    
+
+def mesh(filename=None):
+    """create the mesh"""
+    import start as start
+    cfg                     = start.start_cfg(filename=filename)
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    #
+    if cfg.map_meshing_type == 'regularmap':
+            mesh_layercake_regularmap(filename=filename)
+            #elif cfg.map_meshing_type == 'partitioner':
+            #        mesh_partitioner()
+    else:
+        print 'error: map_meshing_type ', cfg.map_meshing_type,' not implemented'
+
+
+def mesh_layercake_regularmap(filename=None):
+    import sys,os
+    import start as start
+    #
+    class cubitvolume:
+          def __init__(self,ID,intervalv,centerpoint,dimension):
+              self.ID=ID
+              self.intervalv=intervalv
+              self.centerpoint=centerpoint
+              self.dim=dimension
+          
+          def __repr__(self):
+              msg="(vol:%3i, vertical interval: %4i, centerpoint: %8.2f)" % (self.ID, self.intervalv,self.centerpoint)
+              return msg       
+    #
+    def by_z(x,y):
+        return cmp(x.centerpoint,y.centerpoint)
+    #
+    #
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    from utilities import  importgeometry,savemesh,get_v_h_list
+    #
+    numpy                       = start.start_numpy()
+    cfg                         = start.start_cfg(filename=filename)
+    from math import sqrt
+    from sets import Set
+    #
+    list_vol=cubit.parse_cubit_list("volume","all")
+    if len(list_vol) != 0:
+        pass
+    else:
+        geometryfile='geometry_vol_'+str(iproc)+'.cub'
+        importgeometry(geometryfile,iproc=iproc)
+    #
+    command = 'composite create curve all'
+    cubit.cmd(command)
+    print 'NO CRITICAL ERROR: "No valid composites can be created from the specified curves."  is not critical. \n It means that your model is clean and you don"t need a virtual geometry'
+    #
+    command = "compress all"
+    cubit.cmd(command)
+    list_vol=cubit.parse_cubit_list("volume","all")
+    nvol=len(list_vol)                                 
+    vol=[]
+    for id_vol in list_vol:
+        p=cubit.get_center_point("volume",id_vol)
+        vol.append(cubitvolume(id_vol,1,p[2],0))
+    vol.sort(by_z)
+    #
+    for id_vol in range(0,nvol):
+        vol[id_vol].intervalv=cfg.iv_interval[id_vol]
+    #
+    #
+    surf_vertical=[]
+    surf_or=[]
+    top_surface=0
+    top_surface_add=''
+    bottom_surface=0
+    #
+    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6]
+    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
+    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
+    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
+    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
+    #
+    #
+    #interval assignement
+    surf_or,surf_vertical,list_curve_or,list_curve_vertical,bottom,top = get_v_h_list(list_vol)
+    
+    for k in surf_vertical:
+        command = "surface "+str(k)+" scheme submap"
+        cubit.cmd(command)
+    for k in surf_or:
+        command = "surface "+str(k)+" scheme "+cfg.or_mesh_scheme
+        cubit.cmd(command)
+    for k in list_curve_or:
+        length=cubit.get_curve_length(k)
+        interval=int(2*round(.5*length/cfg.size,0))
+        command = "curve "+str(k)+" interval "+str(interval)
+        cubit.cmd(command)
+        #cubit_error_stop(iproc,command,ner)
+        command = "curve "+str(k)+" scheme equal"
+        cubit.cmd(command)
+        #cubit_error_stop(iproc,command,ner)
+        #
+    for s in surf_vertical:
+        lcurve=cubit.get_relatives("surface",s,"curve")
+        interval_store=[]
+        for k in lcurve:
+            interval_curve=cubit.get_mesh_intervals('curve',k)
+            if k in list_curve_vertical:
+                volume_id = cubit.get_owning_volume("curve", k)
+                for idv in range(0,nvol):
+                    if vol[idv].ID == volume_id:
+                        int_v=vol[idv].intervalv
+                command = "curve "+str(k)+" interval "+str(int_v)
+                cubit.cmd(command)
+                #cubit_error_stop(iproc,command,ner)
+                command = "curve "+str(k)+" scheme equal"
+                cubit.cmd(command)
+                #cubit_error_stop(iproc,command,ner)
+            else:
+                interval_store.append((k,interval_curve))
+            if len(interval_store) != 0:
+                interval_min=min([iv[1] for iv in interval_store])
+                command = "curve "+' '.join(str(iv[0]) for iv in interval_store)+" interval "+str(interval_min)
+                cubit.cmd(command)
+                #cubit_error_stop(iproc,command,ner)
+                command = "curve "+' '.join(str(iv[0]) for iv in interval_store)+" scheme equal"
+                cubit.cmd(command)
+                #cubit_error_stop(iproc,command,ner)
+    #cubit_error_stop(iproc,command,ner)
+    #
+    #meshing
+    if cfg.or_mesh_scheme == 'pave':
+        command='mesh surf '+' '.join(str(t) for t in top)
+        cubit.cmd(command)    
+    elif cfg.or_mesh_scheme == 'map':
+        command='mesh surf '+' '.join(str(t) for t in bottom)
+        cubit.cmd(command)
+    for id_volume in range(nvol-1,-1,-1):
+        command = "mesh vol "+str(vol[id_volume].ID)
+        cubit.cmd(command)        
+    
+    #
+    #smoothing
+    print iproc, 'untangling...'
+    cmd="volume all smooth scheme untangle beta 0.02 cpu 10"
+    cubit.cmd(cmd)
+    cmd="smooth volume all"
+    cubit.cmd(cmd)
+    
+    
+    
+    if  cfg.smoothing:
+        print 'smoothing .... '+str(cfg.smoothing)
+        cubitcommand= 'surf all smooth scheme laplacian '
+        cubit.cmd(cubitcommand)
+        cubitcommand= 'smooth surf all'
+        cubit.cmd(cubitcommand)
+        #
+        cubitcommand= 'vol all smooth scheme laplacian '
+        cubit.cmd(cubitcommand)
+        cubitcommand= 'smooth vol all'
+        cubit.cmd(cubitcommand)
+    #
+    #
+    ##vertical refinement
+    ##for nvol = 3 
+    ##
+    ##___________________________ interface 4
+    ##                 
+    ##vol 2              
+    ##___________________________ interface 3
+    ##
+    ##vol 1
+    ##___________________________ interface 2
+    ##
+    ##vol 0
+    ##___________________________ interface 1
+    ##
+    refinement(nvol,vol,filename=filename)
+    #
+    #top layer vertical coarsening
+    print 'coarsening top layer... ',cfg.coarsening_top_layer
+    if  cfg.coarsening_top_layer:
+        from sets import Set
+        cubitcommand= 'del mesh vol '+str(vol[-1].ID)+ ' propagate'
+        cubit.cmd(cubitcommand)
+        s1=Set(list_curve_vertical)
+        print s1
+        command = "group 'list_curve_tmp' add curve "+"in vol "+str(vol[-1].ID)
+        cubit.cmd(command)
+        group=cubit.get_id_from_name("list_curve_tmp")
+        list_curve_tmp=cubit.get_group_curves(group)
+        command = "delete group "+ str(group)
+        cubit.cmd(command)
+        s2=Set(list_curve_tmp)
+        print s2
+        lc=list(s1 & s2)
+        print lc
+        #
+        cubitcommand= 'curve '+' '.join(str(x) for x in lc)+' interval '+str(cfg.actual_vertical_interval_top_layer)
+        cubit.cmd(cubitcommand)
+        cubitcommand= 'mesh vol '+str(vol[-1].ID)
+        cubit.cmd(cubitcommand)
+    #
+    n=cubit.get_sideset_id_list()
+    if len(n) != 0:
+        command = "del sideset all"
+        cubit.cmd(command)
+    n=cubit.get_block_id_list()
+    if len(n) != 0:    
+        command = "del block all"
+        cubit.cmd(command)
+    #
+    import boundary_definition
+    entities=['face']
+    print iproc, 'hex block definition...'
+    boundary_definition.define_bc(entities,parallel=True,cpux=cfg.cpux,cpuy=cfg.cpuy,cpuxmin=0,cpuymin=0)
+    #save mesh
+    
+    print iproc, 'untangling...'
+    cmd="volume all smooth scheme untangle beta 0.02 cpu 10"
+    cubit.cmd(cmd)
+    cmd="smooth volume all"
+    cubit.cmd(cmd)
+    
+    print iproc, 'saving...'
+    savemesh(mpiflag,iproc=iproc,filename=filename)
+    #
+
+def refinement(nvol,vol,filename=None):
+    import start as start
+    cfg                         = start.start_cfg(filename=filename)
+    #
+    #vertical refinement
+    #for nvol = 3 
+    #
+    #___________________________ interface 4
+    #                 
+    #vol 2              
+    #___________________________ interface 3
+    #
+    #vol 1
+    #___________________________ interface 2
+    #
+    #vol 0
+    #___________________________ interface 1
+    #
+    #
+    if cfg.ntripl != 0:
+        if len(cfg.refinement_depth) != 0:
+            #get the topo surface....
+            surf=cubit.get_relatives('volume',vol[nvol+1-2].ID,'surface')
+            zstore=[-1,-999999999]
+            for s in surf:
+                 c=cubit.get_center_point('surface',s)
+                 z=c[2]
+                 if z > zstore[1]:
+                     zstore=[s,z]
+            tsurf=zstore[0]
+            for idepth in cfg.refinement_depth:
+                 cubitcommand= 'refine node in surf  '+str(tsurf)+' numsplit 1 bias 1.0 depth '+str(idepth)
+                 cubit.cmd(cubitcommand)
+        else:
+            for ir in cfg.tripl:
+                if ir == 1:
+                   command = "comment '"+"interface = 1 means that the refinement interface is at the bottom of the volume"+"'"
+                   cubit.cmd(command)
+                   txt=' all '
+                   idepth = 1
+                   cubitcommand= 'refine hex in vol  '+txt
+                elif ir != nvol+1:
+                   txt=''
+                   for id_vol_ref in range(ir-1,nvol):
+                       txt=txt+str(vol[id_vol_ref].ID)+' '
+                   #txt=txt+'except hex in vol '+str(vol[ir-2].ID)
+                   #idepth = 1
+                   #try:
+                   #     if  cfg.refine_basin:
+                   #         idepth=2
+                   #except:
+                   #     pass
+                   cubitcommand= 'refine hex in vol  '+txt
+                else:
+                   #refinement on the top surface
+                   
+                   surf=cubit.get_relatives('volume',vol[ir-2].ID,'surface')
+                   zstore=[-1,-999999999]
+                   for s in surf:
+                        c=cubit.get_center_point('surface',s)
+                        z=c[2]
+                        if z > zstore[1]:
+                            zstore=[s,z]
+                   idepth=1
+                   cubitcommand= 'refine node in surf '+str(zstore[0])+' numsplit 1 bias 1.0 depth '+str(idepth)
+                cubit.cmd(cubitcommand)
+
+
+
+
+def pinpoly(x,y,polyx,polyy):
+    """point in polygon using ray tracing"""
+    n = len(polyx)
+    inside = False
+    poly=zip(polyx,polyy)
+    px_0,py_0 = poly[0]
+    for i in range(n+1):
+        px_1,py_1 = poly[i % n]
+        if y > min(py_0,py_1):
+            if y <= max(py_1,py_0):
+                if x <= max(px_1,px_0):
+                    if py_0 != py_1:
+                        intersect = (y-py_0)*(px_1-px_0)/(py_1-py_0)+px_0
+                    if px_1 == px_0 or x <= intersect:
+                        inside = not inside
+        px_0,py_0 = px_1,py_1
+    return inside
+
+def curve2poly(line):
+    curve=int(line)
+    cubit.cmd('curve '+str(curve)+' size auto factor 1')
+    cubit.cmd('mesh curve '+str(curve))
+    n=cubit.get_curve_nodes(curve)
+    orientnode=[]
+    vertex_list = cubit.get_relatives("curve", curve, "vertex")
+    if len(vertex_list) != 0:
+        startnode=cubit.get_vertex_node(vertex_list[0])
+        cubit.cmd('del group pgon')
+        cubit.cmd("group 'pgon' add edge in node "+str(startnode))
+        group1 = cubit.get_id_from_name("pgon")
+        edges = list(cubit.get_group_edges(group1))
+        edgestart=edges[0]
+    else:
+        startnode=n[0]
+        cubit.cmd('del group pgon')
+        cubit.cmd("group 'pgon' add edge in node "+str(startnode))
+        group1 = cubit.get_id_from_name("pgon")
+        edges = list(cubit.get_group_edges(group1))
+        edgestart=edges[0]
+    begin=startnode
+    orientnode.append(begin)
+    node_id_list = list(cubit.get_connectivity("edge", edgestart))
+    node_id_list.remove(startnode)
+    startnode=node_id_list[0]
+    orientnode.append(startnode)
+    stopflag=False
+    while startnode != begin and not stopflag:
+        cubit.cmd('del group pgon')
+        cubit.cmd("group 'pgon' add edge in node "+str(startnode))
+        group1 = cubit.get_id_from_name("pgon")
+        edges = list(cubit.get_group_edges(group1))
+        if len(edges) != 1:
+            edges.remove(edgestart)
+            edgestart=edges[0]
+            node_id_list = list(cubit.get_connectivity("edge", edgestart))
+            node_id_list.remove(startnode)
+            orientnode.append(node_id_list[0])
+            startnode=node_id_list[0]
+        else:
+            stopflag=True
+    vx=[]
+    vy=[]
+    for n in orientnode:
+        v=cubit.get_nodal_coordinates(n)
+        vx.append(v[0])
+        vy.append(v[1])    
+    return vx,vy,orientnode
+
+def get_nodes_inside_curve(nodes, curve):
+    vx,vy,n=curve2poly(curve)
+    nodes_inside=[]
+    for n in nodes:
+        vp=cubit.get_nodal_coordinates(n)
+        if pinpoly(vp[0],vp[1],vx,vy): nodes_inside.append(n)
+    return nodes_inside
+
+def refine_inside_curve(curves,ntimes=1,depth=1,block=1,surface=False):
+    if not isinstance(curves,list): 
+       if isinstance(curves,str):
+          curves=map(int,curves.split())
+       else:
+          curves=[curves]
+    for curve in curves:
+        cubit.cmd('del group ntop')
+        if not surface:
+            cubit.cmd("group 'ntop' add node in face in block "+str(block))
+        else:
+            cubit.cmd("group 'ntop' add node in face in surface "+str(surface))
+        group1 = cubit.get_id_from_name("ntop")
+        nodes = list(cubit.get_group_nodes(group1))
+        ni=get_nodes_inside_curve(nodes, curve)
+        if ntimes > 1:
+            cmd='del group hex_refining'
+            cubit.cmd(cmd)
+            command = "group 'hex_refining' add hex propagate face in node "+' '.join(str(x) for x in ni)+"times "+str(ntimes)
+            cubit.cmd(command)
+            id_group=cubit.get_id_from_name('hex_refining')
+            command='refine hex in group "hex_refining" numsplit 1 bias 1.0 depth '+str(depth)+' smooth'
+            cubit.cmd(command)
+        else:
+            command='refine node '+" ".join(str(x) for x in ni)+' numsplit 1 bias 1.0 depth '+str(depth)+' smooth'
+            cubit.cmd(command)
+    #
+    #
+    cmd='group "negativejac" add quality hex all Jacobian high'
+    cubit.cmd(cmd) 
+    group_id_1=cubit.get_id_from_name("negativejac")
+    n1=cubit.get_group_nodes(group_id_1)
+    if len(n1) != 0:
+        print 'error, negative jacobian after the refining'
+        import sys
+        #sys.exit()
+

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/bc.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/bc.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/bc.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,434 @@
+#############################################################################
+# bc.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+def bcheck_regularmap():
+    #
+    import geocubitlib.initializing as initializing
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    from geocubitlib.mpi_geocubit import mpiprint
+    #
+    numpy                       = initializing.initializing_numpy()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    if numproc != cfg.nproc_xi*cfg.nproc_eta:
+        print 'check the number of processor, available '+str(numproc)+' cpus, requested '+str(cfg.nproc_xi*cfg.nproc_eta)+' cpus'
+        import sys
+        sys.exit()
+    #
+    from geocubitlib.utilities import geo2utm,cubit_error_stop
+    ner=cubit.get_error_count()
+    #
+    from math import sqrt
+    #
+    ner=cubit.get_error_count()
+    #
+    x_slice=zeros([numproc],int)
+    y_slice=zeros([numproc],int)
+    for icpuy in range(0,cfg.nproc_eta): 
+        for icpux in range (0,cfg.nproc_xi):
+            iprocnum=icpuy*cfg.nproc_xi+icpux
+            x_slice[iprocnum]=icpux
+            y_slice[iprocnum]=icpuy
+    #
+    icpux=x_slice[iproc]
+    icpuy=y_slice[iproc]
+    #
+    list_vol=cubit.parse_cubit_list("volume","all")
+    nvol=len(list_vol)
+    #
+    #
+    #                              
+    zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
+    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...    
+    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
+    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
+    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
+    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
+    #
+    command = "del sideset all"
+    cubit.cmd(command)
+    #
+    cubitcommand= 'sideset '+str(3)+  ' surface with y_max <= '+str(ymin_box)
+    cubit.cmd(cubitcommand)
+    #
+    cubitcommand= 'sideset '+str(4)+ ' surface with x_max <= '+str(xmin_box)
+    cubit.cmd(cubitcommand)
+    #
+    cubitcommand= 'sideset '+str(5)+  ' surface with y_min >= '+str(ymax_box)
+    cubit.cmd(cubitcommand)
+    #
+    cubitcommand= 'sideset '+str(6)+  ' surface with x_min >= '+str(xmax_box)
+    cubit.cmd(cubitcommand)
+    #
+    cubit.cmd('group "xmin" add node in surface in sideset ' + str(4))
+    cubit.cmd('group "xmax" add node in surface in sideset ' + str(6))
+    cubit.cmd('group "ymin" add node in surface in sideset ' + str(3))
+    cubit.cmd('group "ymax" add node in surface in sideset ' + str(5))
+    # get the group ids
+    group_xmin = cubit.get_id_from_name("xmin")
+    group_xmax = cubit.get_id_from_name("xmax")
+    group_ymin = cubit.get_id_from_name("ymin")
+    group_ymax = cubit.get_id_from_name("ymax")
+    # get the nodes in each group
+    nodes_xmin = cubit.get_group_nodes(group_xmin)
+    nodes_xmax = cubit.get_group_nodes(group_xmax)
+    nodes_ymin = cubit.get_group_nodes(group_ymin)
+    nodes_ymax = cubit.get_group_nodes(group_ymax)
+    #
+    cubit.cmd('group "ed" add edge in surf all')
+    ie= cubit.get_id_from_name("ed")
+    list_edge=cubit.get_group_edges(ie)
+    len_edge=1.e9
+    for edge_id in list_edge:
+        len_edge_tmp=cubit.get_mesh_edge_length(edge_id)    
+        if len_edge_tmp < len_edge: 
+            len_edge = len_edge_tmp
+    min_len=len_edge/2.
+    max_len=len_edge/2.
+    #
+    i=0
+    x_xmin=zeros([len(nodes_xmin)],float)
+    y_xmin=zeros([len(nodes_xmin)],float)
+    z_xmin=zeros([len(nodes_xmin)],float)
+    for node_id in nodes_xmin:
+        v = cubit.get_nodal_coordinates(node_id)
+        x_xmin[i]=v[0]
+        y_xmin[i]=v[1]
+        z_xmin[i]=v[2]
+        i+=1
+    #
+    #
+    i=0
+    x_xmax=zeros([len(nodes_xmax)],float)
+    y_xmax=zeros([len(nodes_xmax)],float)
+    z_xmax=zeros([len(nodes_xmax)],float)
+    for node_id in nodes_xmax:
+        v = cubit.get_nodal_coordinates(node_id)
+        x_xmax[i]=v[0]
+        y_xmax[i]=v[1]
+        z_xmax[i]=v[2]
+        i+=1
+    #
+    i=0
+    x_ymin=zeros([len(nodes_ymin)],float)
+    y_ymin=zeros([len(nodes_ymin)],float)
+    z_ymin=zeros([len(nodes_ymin)],float)
+    for node_id in nodes_ymin:
+        v = cubit.get_nodal_coordinates(node_id)
+        x_ymin[i]=v[0]
+        y_ymin[i]=v[1]
+        z_ymin[i]=v[2]
+        i+=1
+    #
+    i=0
+    x_ymax=zeros([len(nodes_ymax)],float)
+    y_ymax=zeros([len(nodes_ymax)],float)
+    z_ymax=zeros([len(nodes_ymax)],float)
+    for node_id in nodes_ymax:
+        v = cubit.get_nodal_coordinates(node_id)
+        x_ymax[i]=v[0]
+        y_ymax[i]=v[1]
+        z_ymax[i]=v[2]
+        i+=1
+    #
+    #
+    #send rec the boundary nodes
+    if icpux < cfg.nproc_xi-1:
+        mpi.send(x_xmax,iproc+1,1)
+        mpi.send(y_xmax,iproc+1,2)
+        mpi.send(z_xmax,iproc+1,3)
+    else:
+        pass
+    #
+    if icpux > 0:
+        x_xmin_ric,status=mpi.recv(iproc-1,1)
+        y_xmin_ric,status=mpi.recv(iproc-1,2)
+        z_xmin_ric,status=mpi.recv(iproc-1,3)
+    else:
+        x_xmin_ric=x_xmin
+        y_xmin_ric=y_xmin
+        z_xmin_ric=z_xmin
+    #
+    if icpuy < cfg.nproc_eta-1:
+        mpi.send(x_ymax,iproc+cfg.nproc_xi,4)
+        mpi.send(y_ymax,iproc+cfg.nproc_xi,5)
+        mpi.send(z_ymax,iproc+cfg.nproc_xi,6)
+    else:
+        pass
+    #
+    if icpuy > 0:
+        x_ymin_ric,status=mpi.recv(iproc-cfg.nproc_xi,4)
+        y_ymin_ric,status=mpi.recv(iproc-cfg.nproc_xi,5)
+        z_ymin_ric,status=mpi.recv(iproc-cfg.nproc_xi,6)
+    else:
+        x_ymin_ric=x_ymin
+        y_ymin_ric=y_ymin
+        z_ymin_ric=z_ymin
+    #
+    #
+    #if icpux > 0:
+    for node_id in nodes_xmin:
+        n = cubit.get_nodal_coordinates(node_id)
+        min_dist=1.e9 #change here
+        for i in range(0,len(x_xmin_ric)):
+            dx = n[0] - x_xmin_ric[i]
+            dy = n[1] - y_xmin_ric[i]
+            dz = n[2] - z_xmin_ric[i]
+            dist = sqrt(dx*dx + dy*dy + dz*dz)
+            if dist < min_dist:
+               min_dist = dist
+               arch_node = i
+               if min_dist < cfg.precision: break
+        if min_dist < min_len and min_dist > cfg.precision:
+            command = "node " + str(node_id) + " move location position " + str(x_xmin_ric[arch_node]) +" "+ str(y_xmin_ric[arch_node]) + " "+str(z_xmin_ric[arch_node])
+            cubit.cmd(command)
+            command = "comment '"+str(list(n))+" -> "+command+"'"
+            cubit.cmd(command)
+            cubit_error_stop(iproc,command,ner)
+        elif min_dist < cfg.precision and cfg.debug:
+            command = "comment '"+"node "+str(node_id)+"below precision - no move"+"'"
+            cubit.cmd(command)
+        elif min_dist < cfg.precision:
+            pass
+        else:
+            raise NameError, str(iproc)+' check boundaries failed, xmin'
+    #
+    #if icpuy > 0:
+    for node_id in nodes_ymin:
+        n = cubit.get_nodal_coordinates(node_id)
+        min_dist=1.e9
+        for i in range(0,len(x_ymin_ric)):
+            dx = n[0] - x_ymin_ric[i]
+            dy = n[1] - y_ymin_ric[i]
+            dz = n[2] - z_ymin_ric[i]
+            dist = sqrt(dx*dx + dy*dy + dz*dz)
+            if dist < min_dist:
+               min_dist = dist
+               arch_node = i
+               if min_dist < cfg.precision: break
+        if min_dist < min_len and min_dist > cfg.precision:
+            command = "node " + str(node_id) + " move location position " + str(x_ymin_ric[arch_node]) + " "+ str(y_ymin_ric[arch_node]) + " "+ str(z_ymin_ric[arch_node])
+            cubit.cmd(command)
+            cubit_error_stop(iproc,command,ner)
+            command = "comment '"+str(list(n))+" -> "+command+"'"
+            cubit.cmd(command)
+        elif min_dist < cfg.precision and cfg.debug:
+            command = "comment '"+"node "+str(node_id)+"below precision - no move"+"'"
+            cubit.cmd(command)
+        elif min_dist < cfg.precision:
+            pass
+        else:
+            raise NameError, str(iproc)+' check boundaries failed, ymin'
+
+def vert_surf_structure(iproc,surfv):
+    import geocubitlib.initializing as initializing
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    from geocubitlib.mpi_geocubit import mpiprint
+    #
+    numpy                       = initializing.initializing_numpy()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    #
+    from math import sqrt
+    from geocubitlib.utilities import geo2utm,cubit_error_stop
+    #
+    command = "comment '"+"vertical"+"'"
+    cubit.cmd(command)
+    command = "comment '"+str(surfv)+"'"
+    cubit.cmd(command)
+    #
+    mapsurfvertical=[]
+    mapsurfvertical.append(iproc)
+    surf_properties=[]
+    for s in surfv:
+        p=cubit.get_center_point('surface',s)
+        #cubit.cmd('del sideset all')
+        command = 'group "n1" add node in surface '+str(s)
+        cubit.cmd(command)
+        group = cubit.get_id_from_name("n1")
+        nodes = cubit.get_group_nodes(group)
+        cubit.cmd('del group '+str(group))
+        xnode=[]
+        for node_id in nodes:
+              v = cubit.get_nodal_coordinates(node_id)
+              xnode.append([node_id,v])
+        surf_properties=[s,p,xnode]
+        mapsurfvertical.append(surf_properties)
+    return mapsurfvertical
+    #mapsurfvertical is: [ iproc number , [ ...[ surf number, [ xyz surface center point ] , [...[node number, xyz node]...]   ]...] ]
+
+
+def cb(logfile,surf_local,surf_rec):
+    import geocubitlib.initializing as initializing
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    from geocubitlib.mpi_geocubit import mpiprint
+    #
+    numpy                       = initializing.initializing_numpy()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    #
+    from math import sqrt
+    from geocubitlib.utilities import geo2utm,cubit_error_stop
+    #
+    #
+    #
+    number_surf_l=len(surf_local)-1
+    number_surf_r=len(surf_rec)-1
+    #
+    for s_l in surf_local[1:]:
+        #
+        flag=False
+        for s_r in surf_rec[1:]:
+            if abs(s_l[1][0]-s_r[1][0]) < cfg.precision and abs(s_l[1][1]-s_r[1][1]) < cfg.precision and abs(s_l[1][2]-s_r[1][2]) < cfg.precision:
+               s=s_l[0]
+               r=s_r[0]
+               command = "comment ' surf "+str(s_l[0])+ "related to "+str(s_r[0])+"'"
+               cubit.cmd(command)
+               command = "comment '"+str(s_l[1])+"->"+str(s_r[1])+"'"
+               cubit.cmd(command)
+               #
+               #
+               if len(s_l[2]) != len(s_r[2]):
+                    command = "comment 'ERROR: surf "+str(s_l[0])+ "has different number of nodes than surf "+str(s_r[0])+"'"
+                    cubit.cmd(command)
+                    command = "comment '"+str(len(s_l[2]))+"/"+str(len(s_r[2]))+"'"
+                    cubit.cmd(command)
+                    print>>logfile, '***********************************'
+                    print>>logfile, 'surf local'+str(s_l[0])+' <-> '+'surf rec'+str(s_r[0])
+                    print>>logfile, "comment 'ERROR: surf "+str(s_l[0])+ "has different number of nodes than surf "+str(s_r[0])+"'"
+                    print>>logfile, "comment '"+str(len(s_l[2]))+"/"+str(len(s_r[2]))+"'"
+                    print>>logfile, "comment '"+str(s_l[1])+"->"+str(s_r[1])+"'"
+                    print>>logfile, 'local'
+                    print>>logfile, s_l
+                    print>>logfile, 'rec'
+                    print>>logfile, s_r
+               else:
+                    p_l=s_l[2]
+                    p_r=s_r[2]
+                    flag=True
+                    break
+        if flag:
+           cubit.cmd('group "ed" add edge in surf '+str(s_l[0]))
+           ie= cubit.get_id_from_name("ed")
+           list_edge=cubit.get_group_edges(ie)
+           command = "del group "+str(ie)
+           cubit.cmd(command)
+           len_edge=1.e15
+           for edge_id in list_edge:
+               len_edge_tmp=cubit.get_mesh_edge_length(edge_id)    
+               if len_edge_tmp < len_edge: 
+                   len_edge = len_edge_tmp
+           #
+           min_len=len_edge/2.
+           max_len=len_edge/2.
+           #
+           for point_l in p_l[1:]:
+               flag_point=False
+               min_dist=1.e9
+               arch_node=point_l
+               for point_r in p_r[1:]:
+                   dx = point_l[1][0] - point_r[1][0]
+                   dy = point_l[1][1] - point_r[1][1]
+                   dz = point_l[1][2] - point_r[1][2]
+                   dist = sqrt(dx*dx + dy*dy + dz*dz)
+                   if dist < min_dist:
+                      min_dist = dist
+                      arch_node = point_r
+                      if min_dist < cfg.precision: break
+               point_r=arch_node
+               if min_dist < min_len and min_dist > cfg.precision:
+                  command = "node " + str(point_l[0]) + " move location position " + str(.5*(point_l[1][0] + point_r[1][0])) +" "+ str(.5*(point_l[1][1] + point_r[1][1])) + " "+ str(.5*(point_l[1][2] + point_r[1][2]))
+                  cubit.cmd(command)
+                  command = "comment '"+str(list(n))+" -> "+command+"'"
+                  cubit.cmd(command)
+               elif min_dist < cfg.precision and cfg.debug:
+                  command = "comment '"+"node "+str(point_l[0])+" below precision "+str(min_dist)+" < "+str(cfg.precision)+" - no move"+"'"
+                  cubit.cmd(command)
+               else:
+                  command = "comment '"+"node "+str(point_l[0])+" ERROR ["+str(point_l[1][0])+","+str(point_l[1][1])+","+str(point_l[1][2])+"] -> ["+str(point_r[1][0])+","+str(point_r[1][1])+","+str(point_r[1][2])+"] mindist="+str(min_dist)+" - ERROR NO MOVE"+"'"
+                  cubit.cmd(command)
+
+
+
+
+
+def bcheck_basin(surf_vertical,parallel_map):
+    #
+    import geocubitlib.initializing as initializing
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    from geocubitlib.mpi_geocubit import mpiprint
+    #
+    numpy                       = initializing.initializing_numpy()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()    
+    #
+    f=open(cfg.working+'mpi_tracking_'+str(iproc)+'.log','w')
+    command = "comment 'check mpi boundaries proc: "+str(iproc)+"'"
+    cubit.cmd(command)        
+    #
+    #
+    surf_local=vert_surf_structure(iproc,surf_vertical)
+    proc_adj=parallel_map[iproc].p_adj
+    #
+    mpi.barrier()
+    #
+    all_tmp=[]
+    if iproc == 0:
+        all_tmp.append(surf_local)
+        for ip in range(1,numproc):
+            command = "comment '"+"rec proc "+str(ip)+"'"
+            cubit.cmd(command)
+            s_tmp,status=mpi.recv(ip)
+            all_tmp.append(s_tmp)
+    else:
+            mpi.send(surf_local,0)
+    #all_surf_vertical=mpi.allgather(surf_local)
+    
+    mpi.barrier()
+    all_surf_vertical=mpi.bcast(all_tmp)
+    #
+    #if iproc == 0:
+    #    mpi.bcast(all_surf_vertical)
+    #else:
+    #    all_surf_vertical=mpi.bcast()
+    #
+    #print>>f,  all_surf_vertical
+    #
+    command = "comment '"+"checking..."+"'"
+    cubit.cmd(command)
+    for k in proc_adj:
+        #for surf_rec in all_surf_vertical:
+        #    if surf_rec[0] == k:
+        surf_rec=all_surf_vertical[k]
+        if surf_rec[0] != k:
+           command = "comment '"+"ERROR: wrong vertical structure"+"'"
+           cubit.cmd(command)
+        else:
+            command = "comment 'proc"+str(iproc)+"is checking with "+str(k)+"/"+str(proc_adj)+"'"
+            cubit.cmd(command)
+            cb(f,surf_local,surf_rec)
+
+    
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/boundary_check.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/boundary_check.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/boundary_check.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,429 @@
+#############################################################################
+# bc.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+def bcheck_regularmap():
+    #
+    import geocubitlib.initializing as initializing
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    from geocubitlib.mpi_geocubit import mpiprint
+    #
+    numpy                       = initializing.initializing_numpy()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    if numproc != cfg.nproc_xi*cfg.nproc_eta:
+        print 'check the number of processor, available '+str(numproc)+' cpus, requested '+str(cfg.nproc_xi*cfg.nproc_eta)+' cpus'
+        import sys
+        sys.exit()
+    #
+    from geocubitlib.utilities import geo2utm,cubit_error_stop
+    ner=cubit.get_error_count()
+    #
+    from math import sqrt
+    #
+    ner=cubit.get_error_count()
+    #
+    x_slice=zeros([numproc],int)
+    y_slice=zeros([numproc],int)
+    for icpuy in range(0,cfg.nproc_eta): 
+        for icpux in range (0,cfg.nproc_xi):
+            iprocnum=icpuy*cfg.nproc_xi+icpux
+            x_slice[iprocnum]=icpux
+            y_slice[iprocnum]=icpuy
+    #
+    icpux=x_slice[iproc]
+    icpuy=y_slice[iproc]
+    #
+    list_vol=cubit.parse_cubit_list("volume","all")
+    nvol=len(list_vol)
+    #
+    #
+    #                              
+    zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
+    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...    
+    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
+    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
+    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
+    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
+    #
+    command = "del sideset all"
+    cubit.cmd(command)
+    #
+    cubitcommand= 'sideset '+str(3)+  ' surface with y_max <= '+str(ymin_box)
+    cubit.cmd(cubitcommand)
+    #
+    cubitcommand= 'sideset '+str(4)+ ' surface with x_max <= '+str(xmin_box)
+    cubit.cmd(cubitcommand)
+    #
+    cubitcommand= 'sideset '+str(5)+  ' surface with y_min >= '+str(ymax_box)
+    cubit.cmd(cubitcommand)
+    #
+    cubitcommand= 'sideset '+str(6)+  ' surface with x_min >= '+str(xmax_box)
+    cubit.cmd(cubitcommand)
+    #
+    cubit.cmd('group "xmin" add node in surface in sideset ' + str(4))
+    cubit.cmd('group "xmax" add node in surface in sideset ' + str(6))
+    cubit.cmd('group "ymin" add node in surface in sideset ' + str(3))
+    cubit.cmd('group "ymax" add node in surface in sideset ' + str(5))
+    # get the group ids
+    group_xmin = cubit.get_id_from_name("xmin")
+    group_xmax = cubit.get_id_from_name("xmax")
+    group_ymin = cubit.get_id_from_name("ymin")
+    group_ymax = cubit.get_id_from_name("ymax")
+    # get the nodes in each group
+    nodes_xmin = cubit.get_group_nodes(group_xmin)
+    nodes_xmax = cubit.get_group_nodes(group_xmax)
+    nodes_ymin = cubit.get_group_nodes(group_ymin)
+    nodes_ymax = cubit.get_group_nodes(group_ymax)
+    #
+    cubit.cmd('group "ed" add edge in surf all')
+    ie= cubit.get_id_from_name("ed")
+    list_edge=cubit.get_group_edges(ie)
+    len_edge=1.e9
+    for edge_id in list_edge:
+        len_edge_tmp=cubit.get_mesh_edge_length(edge_id)    
+        if len_edge_tmp < len_edge: 
+            len_edge = len_edge_tmp
+    min_len=len_edge/2.
+    max_len=len_edge/2.
+    #
+    i=0
+    x_xmin=zeros([len(nodes_xmin)],float)
+    y_xmin=zeros([len(nodes_xmin)],float)
+    z_xmin=zeros([len(nodes_xmin)],float)
+    for node_id in nodes_xmin:
+        v = cubit.get_nodal_coordinates(node_id)
+        x_xmin[i]=v[0]
+        y_xmin[i]=v[1]
+        z_xmin[i]=v[2]
+        i+=1
+    #
+    #
+    i=0
+    x_xmax=zeros([len(nodes_xmax)],float)
+    y_xmax=zeros([len(nodes_xmax)],float)
+    z_xmax=zeros([len(nodes_xmax)],float)
+    for node_id in nodes_xmax:
+        v = cubit.get_nodal_coordinates(node_id)
+        x_xmax[i]=v[0]
+        y_xmax[i]=v[1]
+        z_xmax[i]=v[2]
+        i+=1
+    #
+    i=0
+    x_ymin=zeros([len(nodes_ymin)],float)
+    y_ymin=zeros([len(nodes_ymin)],float)
+    z_ymin=zeros([len(nodes_ymin)],float)
+    for node_id in nodes_ymin:
+        v = cubit.get_nodal_coordinates(node_id)
+        x_ymin[i]=v[0]
+        y_ymin[i]=v[1]
+        z_ymin[i]=v[2]
+        i+=1
+    #
+    i=0
+    x_ymax=zeros([len(nodes_ymax)],float)
+    y_ymax=zeros([len(nodes_ymax)],float)
+    z_ymax=zeros([len(nodes_ymax)],float)
+    for node_id in nodes_ymax:
+        v = cubit.get_nodal_coordinates(node_id)
+        x_ymax[i]=v[0]
+        y_ymax[i]=v[1]
+        z_ymax[i]=v[2]
+        i+=1
+    #
+    #
+    #send rec the boundary nodes
+    if icpux < cfg.nproc_xi-1:
+        mpi.send(x_xmax,iproc+1,1)
+        mpi.send(y_xmax,iproc+1,2)
+        mpi.send(z_xmax,iproc+1,3)
+    else:
+        pass
+    #
+    if icpux > 0:
+        x_xmin_ric,status=mpi.recv(iproc-1,1)
+        y_xmin_ric,status=mpi.recv(iproc-1,2)
+        z_xmin_ric,status=mpi.recv(iproc-1,3)
+    else:
+        x_xmin_ric=x_xmin
+        y_xmin_ric=y_xmin
+        z_xmin_ric=z_xmin
+    #
+    if icpuy < cfg.nproc_eta-1:
+        mpi.send(x_ymax,iproc+cfg.nproc_xi,4)
+        mpi.send(y_ymax,iproc+cfg.nproc_xi,5)
+        mpi.send(z_ymax,iproc+cfg.nproc_xi,6)
+    else:
+        pass
+    #
+    if icpuy > 0:
+        x_ymin_ric,status=mpi.recv(iproc-cfg.nproc_xi,4)
+        y_ymin_ric,status=mpi.recv(iproc-cfg.nproc_xi,5)
+        z_ymin_ric,status=mpi.recv(iproc-cfg.nproc_xi,6)
+    else:
+        x_ymin_ric=x_ymin
+        y_ymin_ric=y_ymin
+        z_ymin_ric=z_ymin
+    #
+    #
+    #if icpux > 0:
+    for node_id in nodes_xmin:
+        n = cubit.get_nodal_coordinates(node_id)
+        min_dist=1.e9 #change here
+        for i in range(0,len(x_xmin_ric)):
+            dx = n[0] - x_xmin_ric[i]
+            dy = n[1] - y_xmin_ric[i]
+            dz = n[2] - z_xmin_ric[i]
+            dist = sqrt(dx*dx + dy*dy + dz*dz)
+            if dist < min_dist:
+               min_dist = dist
+               arch_node = i
+               if min_dist < cfg.precision: break
+        if min_dist < min_len and min_dist > cfg.precision:
+            command = "node " + str(node_id) + " move location position " + str(x_xmin_ric[arch_node]) +" "+ str(y_xmin_ric[arch_node]) + " "+str(z_xmin_ric[arch_node])
+            cubit.cmd(command)
+            command = "comment '"+str(list(n))+" -> "+command+"'"
+            cubit.cmd(command)
+            cubit_error_stop(iproc,command,ner)
+        elif min_dist < cfg.precision and cfg.debug:
+            command = "comment '"+"node "+str(node_id)+"below precision - no move"+"'"
+            cubit.cmd(command)
+        elif min_dist < cfg.precision:
+            pass
+        else:
+            raise NameError, str(iproc)+' check boundaries failed, xmin'
+    #
+    #if icpuy > 0:
+    for node_id in nodes_ymin:
+        n = cubit.get_nodal_coordinates(node_id)
+        min_dist=1.e9
+        for i in range(0,len(x_ymin_ric)):
+            dx = n[0] - x_ymin_ric[i]
+            dy = n[1] - y_ymin_ric[i]
+            dz = n[2] - z_ymin_ric[i]
+            dist = sqrt(dx*dx + dy*dy + dz*dz)
+            if dist < min_dist:
+               min_dist = dist
+               arch_node = i
+               if min_dist < cfg.precision: break
+        if min_dist < min_len and min_dist > cfg.precision:
+            command = "node " + str(node_id) + " move location position " + str(x_ymin_ric[arch_node]) + " "+ str(y_ymin_ric[arch_node]) + " "+ str(z_ymin_ric[arch_node])
+            cubit.cmd(command)
+            cubit_error_stop(iproc,command,ner)
+            command = "comment '"+str(list(n))+" -> "+command+"'"
+            cubit.cmd(command)
+        elif min_dist < cfg.precision and cfg.debug:
+            command = "comment '"+"node "+str(node_id)+"below precision - no move"+"'"
+            cubit.cmd(command)
+        elif min_dist < cfg.precision:
+            pass
+        else:
+            raise NameError, str(iproc)+' check boundaries failed, ymin'
+
+def vert_surf_structure(iproc,surfv):
+    import geocubitlib.initializing as initializing
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    #
+    numpy                       = initializing.initializing_numpy()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    #
+    from math import sqrt
+    from geocubitlib.utilities import geo2utm
+    #
+    command = "comment '"+"vertical"+"'"
+    cubit.cmd(command)
+    command = "comment '"+str(surfv)+"'"
+    cubit.cmd(command)
+    #
+    mapsurfvertical=[]
+    mapsurfvertical.append(iproc)
+    surf_properties=[]
+    for s in surfv:
+        p=cubit.get_center_point('surface',s)
+        #cubit.cmd('del sideset all')
+        command = 'group "n1" add node in surface '+str(s)
+        cubit.cmd(command)
+        group = cubit.get_id_from_name("n1")
+        nodes = cubit.get_group_nodes(group)
+        cubit.cmd('del group '+str(group))
+        xnode=[]
+        for node_id in nodes:
+              v = cubit.get_nodal_coordinates(node_id)
+              xnode.append([node_id,v])
+        surf_properties=[s,p,xnode]
+        mapsurfvertical.append(surf_properties)
+    return mapsurfvertical
+
+def cb(logfile,surf_local,surf_rec):
+    import geocubitlib.initializing as initializing
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    #
+    numpy                       = initializing.initializing_numpy()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    #
+    from math import sqrt
+    from geocubitlib.utilities import geo2utm
+    #
+    #
+    #
+    number_surf_l=len(surf_local)-1
+    number_surf_r=len(surf_rec)-1
+    #
+    for s_l in surf_local[1:]:
+        #
+        flag=False
+        for s_r in surf_rec[1:]:
+            if abs(s_l[1][0]-s_r[1][0]) < cfg.precision and abs(s_l[1][1]-s_r[1][1]) < cfg.precision and abs(s_l[1][2]-s_r[1][2]) < cfg.precision:
+               s=s_l[0]
+               r=s_r[0]
+               command = "comment ' surf "+str(s_l[0])+ "related to "+str(s_r[0])+"'"
+               cubit.cmd(command)
+               command = "comment '"+str(s_l[1])+"->"+str(s_r[1])+"'"
+               cubit.cmd(command)
+               #
+               #
+               if len(s_l[2]) != len(s_r[2]):
+                    command = "comment 'ERROR: surf "+str(s_l[0])+ "has different number of nodes than surf "+str(s_r[0])+"'"
+                    cubit.cmd(command)
+                    command = "comment '"+str(len(s_l[2]))+"/"+str(len(s_r[2]))+"'"
+                    cubit.cmd(command)
+                    print>>logfile, '***********************************'
+                    print>>logfile, 'surf local'+str(s_l[0])+' <-> '+'surf rec'+str(s_r[0])
+                    print>>logfile, "comment 'ERROR: surf "+str(s_l[0])+ "has different number of nodes than surf "+str(s_r[0])+"'"
+                    print>>logfile, "comment '"+str(len(s_l[2]))+"/"+str(len(s_r[2]))+"'"
+                    print>>logfile, "comment '"+str(s_l[1])+"->"+str(s_r[1])+"'"
+                    print>>logfile, 'local'
+                    print>>logfile, s_l
+                    print>>logfile, 'rec'
+                    print>>logfile, s_r
+               else:
+                    p_l=s_l[2]
+                    p_r=s_r[2]
+                    flag=True
+                    break
+        if flag:
+           cubit.cmd('group "ed" add edge in surf '+str(s_l[0]))
+           ie= cubit.get_id_from_name("ed")
+           list_edge=cubit.get_group_edges(ie)
+           command = "del group "+str(ie)
+           cubit.cmd(command)
+           len_edge=1.e15
+           for edge_id in list_edge:
+               len_edge_tmp=cubit.get_mesh_edge_length(edge_id)    
+               if len_edge_tmp < len_edge: 
+                   len_edge = len_edge_tmp
+           #
+           min_len=len_edge/2.
+           max_len=len_edge/2.
+           #
+           for point_l in p_l[1:]:
+               flag_point=False
+               min_dist=1.e9
+               arch_node=point_l
+               for point_r in p_r[1:]:
+                   dx = point_l[1][0] - point_r[1][0]
+                   dy = point_l[1][1] - point_r[1][1]
+                   dz = point_l[1][2] - point_r[1][2]
+                   dist = sqrt(dx*dx + dy*dy + dz*dz)
+                   if dist < min_dist:
+                      min_dist = dist
+                      arch_node = point_r
+                      if min_dist < cfg.precision: break
+               point_r=arch_node
+               if min_dist < min_len and min_dist > cfg.precision:
+                  command = "node " + str(point_l[0]) + " move location position " + str(.5*(point_l[1][0] + point_r[1][0])) +" "+ str(.5*(point_l[1][1] + point_r[1][1])) + " "+ str(.5*(point_l[1][2] + point_r[1][2]))
+                  cubit.cmd(command)
+                  command = "comment '"+str(list(n))+" -> "+command+"'"
+                  cubit.cmd(command)
+               elif min_dist < cfg.precision and cfg.debug:
+                  command = "comment '"+"node "+str(point_l[0])+" below precision "+str(min_dist)+" < "+str(cfg.precision)+" - no move"+"'"
+                  cubit.cmd(command)
+               else:
+                  command = "comment '"+"node "+str(point_l[0])+" ERROR ["+str(point_l[1][0])+","+str(point_l[1][1])+","+str(point_l[1][2])+"] -> ["+str(point_r[1][0])+","+str(point_r[1][1])+","+str(point_r[1][2])+"] mindist="+str(min_dist)+" - ERROR NO MOVE"+"'"
+                  cubit.cmd(command)
+
+
+
+
+
+def bcheck_basin(surf_vertical,parallel_map):
+    #
+    import geocubitlib.initializing as initializing
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    #
+    numpy                       = initializing.initializing_numpy()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()    
+    #
+    f=open(cfg.working+'mpi_tracking_'+str(iproc)+'.log','w')
+    command = "comment 'check mpi boundaries proc: "+str(iproc)+"'"
+    cubit.cmd(command)        
+    #
+    #
+    surf_local=vert_surf_structure(iproc,surf_vertical)
+    proc_adj=parallel_map[iproc].p_adj
+    #
+    mpi.barrier()
+    #
+    all_tmp=[]
+    if iproc == 0:
+        all_tmp.append(surf_local)
+        for ip in range(1,numproc):
+            command = "comment '"+"rec proc "+str(ip)+"'"
+            cubit.cmd(command)
+            s_tmp,status=mpi.recv(ip)
+            all_tmp.append(s_tmp)
+    else:
+            mpi.send(surf_local,0)
+    #all_surf_vertical=mpi.allgather(surf_local)
+    
+    mpi.barrier()
+    all_surf_vertical=mpi.bcast(all_tmp)
+    #
+    #if iproc == 0:
+    #    mpi.bcast(all_surf_vertical)
+    #else:
+    #    all_surf_vertical=mpi.bcast()
+    #
+    #print>>f,  all_surf_vertical
+    #
+    command = "comment '"+"checking..."+"'"
+    cubit.cmd(command)
+    for k in proc_adj:
+        #for surf_rec in all_surf_vertical:
+        #    if surf_rec[0] == k:
+        surf_rec=all_surf_vertical[k]
+        if surf_rec[0] != k:
+           command = "comment '"+"ERROR: wrong vertical structure"+"'"
+           cubit.cmd(command)
+        else:
+            command = "comment 'proc"+str(iproc)+"is checking with "+str(k)+"/"+str(proc_adj)+"'"
+            cubit.cmd(command)
+            cb(f,surf_local,surf_rec)
+
+    
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/boundary_definition.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/boundary_definition.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/boundary_definition.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,665 @@
+#############################################################################
+# boundary_definition.py                                                    #
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+
+
+def define_absorbing_surf():
+    """
+    define the absorbing surfaces for a layered topological box where boundary are surfaces parallel to the axis.
+    it returns absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,topo_surf
+    where
+    absorbing_surf is the list of all the absorbing boundary surf
+    absorbing_surf_xmin is the list of the absorbing boundary surfaces that correnspond to x=xmin
+    ...
+    absorbing_surf_bottom is the list of the absorbing boundary surfaces that correspond to z=zmin
+    """
+    import initializing as initializing
+    cubit                   = initializing.initializing_cubit()
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    #     
+    absorbing_surf=[]
+    absorbing_surf_xmin=[]
+    absorbing_surf_xmax=[]
+    absorbing_surf_ymin=[]
+    absorbing_surf_ymax=[]
+    absorbing_surf_bottom=[]
+    top_surf=[]
+    list_vol=cubit.parse_cubit_list("volume","all")
+    init_n_vol=len(list_vol)
+    cfg                         = initializing.initializing_cfg()
+    
+    zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
+    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...    
+    #        [                                                  ]
+    #xmin_box=[cubit.get_total_bounding_box("volume",list_vol)[0]]
+    #xmax_box=[cubit.get_total_bounding_box("volume",list_vol)[1]]
+    #ymin_box=[cubit.get_total_bounding_box("volume",list_vol)[3]]
+    #ymax_box=[cubit.get_total_bounding_box("volume",list_vol)[4]]
+    
+    #mpi.barrier()
+    #
+    #total_xmin=mpi.allgather(xmin_box)
+    #xmin_box=min(total_xmin)
+    #
+    #total_xmax=mpi.allgather(xmax_box)
+    #xmax_box=max(total_xmax)       
+    #
+    #total_ymin=mpi.allgather(ymin_box)
+    #ymin_box=min(total_ymin)       
+    #
+    #total_ymax=mpi.allgather(ymax_box)
+    #ymax_box=max(total_ymax)     
+    #
+    #mpi.barrier()                        
+    #
+    def distance(x0,y0,x1,y1,x2,y2):
+        import math
+        d=abs((x2-x1)*(y1-y0)-(x1-x0)*(y2-y1))/math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
+        return d
+    
+    x1=cfg.x1_box
+    x2=cfg.x2_box
+    x3=cfg.x3_box
+    x4=cfg.x4_box
+    y1=cfg.y1_box
+    y2=cfg.y2_box
+    y3=cfg.y3_box
+    y4=cfg.y4_box
+    #tres=cfg.tres_boundarydetection
+    tres=cfg.tres
+    list_surf=cubit.parse_cubit_list("surface","all")
+    surface_hor=[]
+    for k in list_surf:
+        center_point = cubit.get_center_point("surface", k)
+        x0=center_point[0]
+        y0=center_point[1]
+        normal=cubit.get_surface_normal(k)[2]
+        vertical= normal >= -1*tres and normal <= tres
+        if distance(x0,y0,x1,y1,x4,y4) < abs(x4-x1)*.2:
+            absorbing_surf_xmin.append(k)
+            absorbing_surf.append(k)
+        elif distance(x0,y0,x2,y2,x3,y3) < abs(x3-x2)*.2:
+            absorbing_surf_xmax.append(k)
+            absorbing_surf.append(k)
+        elif distance(x0,y0,x1,y1,x2,y2) < abs(y2-y1)*.2:
+            absorbing_surf_ymin.append(k)
+            absorbing_surf.append(k)
+        elif distance(x0,y0,x3,y3,x4,y4) < abs(y3-y4)*.2:
+            absorbing_surf_ymax.append(k)
+            absorbing_surf.append(k)
+        elif not vertical: 
+            surface_hor.append(k)
+    ztop=zmin_box
+    zbottom=zmax_box
+    for k in surface_hor:
+        sbox=cubit.get_bounding_box('surface',k)
+        zsurf_min=sbox[6]
+        zsurf_max=sbox[7]
+        if zsurf_max >= ztop:
+            ktop=k
+            ztop=zsurf_max
+        if zsurf_min <= zbottom:
+            kbottom=k
+            zbottom=zsurf_min
+    absorbing_surf_bottom.append(kbottom)
+    absorbing_surf.append(kbottom)           
+    top_surf.append(ktop)
+                
+    f=open('bc_ok_'+str(iproc),'w')
+    txt=str(absorbing_surf)+str(absorbing_surf_xmin)+str(absorbing_surf_xmax)+str(absorbing_surf_ymin)+str(absorbing_surf_ymax)+str(absorbing_surf_bottom)+str(top_surf)
+    f.write(txt)
+    f.close()
+
+
+
+
+    return absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,top_surf
+
+def define_absorbing_surf_nopar():
+    """
+    define the absorbing surfaces for a layered topological box where boundary surfaces are not parallel to the axis.
+    it returns absorbing_surf,topo_surf
+    where
+    absorbing_surf is the list of all the absorbing boundary surf
+    """
+    #import initializing as initializing
+    #cubit                   = initializing.initializing_cubit()
+    #
+    from sets import Set
+    def product(*args, **kwds):
+        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
+        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
+        pools = map(tuple, args) * kwds.get('repeat', 1)
+        result = [[]]
+        for pool in pools:
+            result = [x+[y] for x in result for y in pool]
+        return result
+    absorbing_surf=[]
+    absorbing_surf_xmin=[]
+    absorbing_surf_xmax=[]
+    absorbing_surf_ymin=[]
+    absorbing_surf_ymax=[]
+    absorbing_surf_bottom=[]
+    top_surf=[]
+    bottom_surf=[]
+    list_vol=cubit.parse_cubit_list("volume","all")
+    init_n_vol=len(list_vol)
+    zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
+    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...    
+    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
+    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
+    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
+    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
+    list_surf=cubit.parse_cubit_list("surface","all")
+    lv=[]
+    for k in list_surf:
+            sbox=cubit.get_bounding_box('surface',k)
+            dzmax=abs((sbox[7] - zmax_box)/zmax_box)
+            dzmin=abs((sbox[6] - zmin_box)/zmin_box)
+            normal=cubit.get_surface_normal(k)
+            zn=normal[2]
+            if dzmax <= 0.1 and zn > 0.4:
+                top_surf.append(k)
+                list_vertex=cubit.get_relatives('surface',k,'vertex')
+                for v in list_vertex:
+                    valence=cubit.get_valence(v)
+                    if valence <= 4: #valence 3 is a corner, 4 is a vertex between 2 volumes, > 4 is a vertex not in the boundaries
+                        lv.append(v)
+            elif dzmin <= 0.001 and zn < -0.7:
+                bottom_surf.append(k)
+                absorbing_surf.append(k)
+    lp=[]
+    combs=product(lv,lv)
+    for comb in combs:
+        v1=comb[0]
+        v2=comb[1]
+        c=Set(cubit.get_relatives("vertex",v1,"curve")) & Set(cubit.get_relatives("vertex",v2,"curve"))
+        if len(c) == 1:
+            p=cubit.get_center_point("curve",list(c)[0])
+            lp.append(p)
+    for k in list_surf: 
+        center_point = cubit.get_center_point("surface", k)
+        for p in lp:
+            if abs((center_point[0] - p[0])/p[0]) <= 0.001 and abs((center_point[1] - p[1])/p[1]) <= 0.001:
+             absorbing_surf.append(k)
+             break
+    return absorbing_surf,top_surf,bottom_surf
+
+def define_absorbing_surf_sphere():
+    import initializing as initializing
+    cubit                   = initializing.initializing_cubit()
+    #
+    surf=[]
+    list_surf=cubit.parse_cubit_list("surface","all")
+    for s in list_surf:
+       v=cubit.get_relatives('surface',s,'volume')
+       if len(v) == 1:
+           surf.append(s)
+    return surf
+
+def define_block():
+    #try:
+    #    import initializing as initializing
+    #    cubit                   = initializing.initializing_cubit()
+    #except:
+    #    pass
+    #
+    list_vol=cubit.parse_cubit_list("volume","all")
+    init_n_vol=len(list_vol)
+    list_name=map(lambda x: 'vol'+x,map(str,list_vol))
+    return list_vol,list_name
+
+def build_block(vol_list,name,id_0):
+    #try:
+    #    import initializing as initializing
+    #    cubit                   = initializing.initializing_cubit()
+    #except:
+    #    pass
+    #
+    from sets import Set
+    #
+    block_list=cubit.get_block_id_list()
+    if len(block_list) > 0:
+         id_block=max(max(block_list),2)+id_0
+    else:
+        id_block=1+id_0
+    for v,n in zip(vol_list,name):
+       id_block+=1
+       v_other=Set(vol_list)-Set([v])
+       #command= 'block '+str(id_block)+' hex in node in vol '+str(v)+' except hex in vol '+str(list(v_other))
+       command= 'block '+str(id_block)+' hex in vol '+str(v)+' except hex in vol '+str(list(v_other))
+       print command
+       command = command.replace("["," ").replace("]"," ")
+       cubit.cmd(command) 
+       command = "block "+str(id_block)+" name '"+n+"'"
+       cubit.cmd(command)
+
+def build_block_side(surf_list,name,obj='surface',id_0=1):
+    #try:
+    #    import initializing as initializing
+    #    cubit                   = initializing.initializing_cubit()
+    #except:
+    #    pass
+    #
+    id_nodeset=cubit.get_next_nodeset_id()
+    #id_block=cubit.get_next_block_id()
+    id_block=id_0
+    if obj == 'hex':
+        txt='hex in node in surface'
+        txt1='block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
+        txt2="block "+str(id_block)+" name '"+name+"'"
+        txt1=txt1.replace("["," ").replace("]"," ")
+        cubit.cmd(txt1)
+        cubit.cmd(txt2)
+    elif obj == 'node':
+         txt=obj+' in surface'
+         txt1= 'nodeset '+str(id_nodeset)+ ' '+ txt +' '+str(list(surf_list))
+         txt1 = txt1.replace("["," ").replace("]"," ")
+         txt2 = "nodeset "+str(id_nodeset)+" name '"+name+"'"
+         cubit.cmd(txt1)
+         cubit.cmd(txt2)
+    elif obj == 'face' or obj == 'edge':
+        txt=obj+' in surface'
+        txt1= 'block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
+        txt1 = txt1.replace("["," ").replace("]"," ")
+        txt2 = "block "+str(id_block)+" name '"+name+"'"
+        cubit.cmd(txt1)
+        cubit.cmd(txt2)
+    else:
+        txt1=''
+        txt2="block "+str(id_block)+" name "+name+"_notsupported (only hex,face,edge,node)"
+        try:
+            cubit.cmd('comment "'+txt1+'"')
+            cubit.cmd('comment "'+txt2+'"')
+        except:
+            pass
+
+def define_bc(*args,**keys):
+    import initializing as initializing
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    cubit                   = initializing.initializing_cubit()
+    
+    parallel=keys.get('parallel',True)
+    closed=keys.get('closed',False)
+    #partitioning_type=keys.get('partitioning_type',None)
+    id_0=1
+    #if partitioning_type:
+    #    if partitioning_type == 't':
+    #        id_0=10
+    #    elif partitioning_type == 'in':
+    #        id_0=100
+    #    elif partitioning_type == 'out':
+    #        id_0=1000
+    #    else:
+    #        print 'check the partitioning definition..', partitioning_type
+    #        return
+    ##
+    cubit.cmd('comment "def bc"')
+    if not closed:
+        if parallel:
+            surf,xmin,xmax,ymin,ymax,bottom,topo=define_absorbing_surf()
+            cubit.cmd('comment "'+str([surf,xmin,xmax,ymin,ymax,bottom,topo])+'"')
+        else:
+            surf,topo,bottom=define_absorbing_surf_nopar()
+        v_list,name_list=define_block()
+        build_block(v_list,name_list,id_0)
+        entities=args[0]
+        id_side=cubit.get_next_block_id()
+        for entity in entities:
+            build_block_side(topo,entity+'_topo',obj=entity,id_0=1) #topo ha block 1
+            id_side=cubit.get_next_block_id()
+            build_block_side(bottom,entity+'_abs_bottom',obj=entity,id_0=id_side)
+            id_side=id_side+1
+            build_block_side(surf,entity+'_abs',obj=entity,id_0=id_side)
+            id_side=id_side+1
+            if parallel: 
+                build_block_side(xmin,entity+'_abs_xmin',obj=entity,id_0=id_side)
+                id_side=id_side+1
+                build_block_side(xmax,entity+'_abs_xmax',obj=entity,id_0=id_side)
+                id_side=id_side+1
+                build_block_side(ymin,entity+'_abs_ymin',obj=entity,id_0=id_side)
+                id_side=id_side+1
+                build_block_side(ymax,entity+'_abs_ymax',obj=entity,id_0=id_side)
+                id_side=id_side+1
+    else:
+        surf=define_absorbing_surf_sphere()
+        v_list,name_list=define_block()
+        build_block(v_list,name_list,id_0)
+        entities=args[0]
+        id_side=1
+        for entity in entities:
+            build_block_side(surf,entity+'_closedvol',obj=entity,id_0=id_side)
+            id_side=id_side+1
+
+
+def list2str(l):
+    if not isinstance(l,list): l=list(l)
+    return ' '.join(str(x) for x in l)
+
+
+
+def get_ordered_node_surf(lsurface,icurve):
+    if not isinstance(lsurface,str): 
+        lsurf=list2str(lsurface)
+    #
+    if not isinstance(icurve,str): 
+        icurvestr=str(icurve)
+    orient_nodes_surf=[]
+    #
+    cubit.cmd('del group sl')
+    cubit.cmd("group 'sl' add node in surf "+lsurf)
+    group1 = cubit.get_id_from_name("sl")
+    nodes_ls =list(cubit.get_group_nodes(group1))
+    cubit.cmd('del group sl')
+    nnode=len(nodes_ls)
+    #
+    orient=[]
+    cubit.cmd('del group n1')
+    cubit.cmd("group 'n1' add node in curve "+icurvestr)
+    x=cubit.get_bounding_box('curve', icurve)
+    if x[2]>x[5]:
+         idx=0
+    else:
+         idx=1
+    group1 = cubit.get_id_from_name("n1")
+    nodes1 = list(cubit.get_group_nodes(group1))
+    for n in nodes1:
+         v = cubit.get_nodal_coordinates(n)
+         orient.append(v[idx])
+    result=zip(orient,nodes1)
+    result.sort()
+    nodes2=[c[1] for c in result]
+    for n in nodes2:
+         try:
+              nodes_ls.remove(n)
+         except:
+              pass             
+    orient_nodes_surf=orient_nodes_surf+nodes2
+    #
+    while len(orient_nodes_surf) < nnode:
+          cubit.cmd('del group n1')
+          cubit.cmd("group 'n1' add node in edge in node "+str(nodes2).replace('[',' ').replace(']',' '))
+          group1 = cubit.get_id_from_name("n1")
+          nodes1 = list(cubit.get_group_nodes(group1))
+          orient=[]
+          nd=[]
+          for n in nodes1:
+              if n in nodes_ls:
+                   v = cubit.get_nodal_coordinates(n)
+                   orient.append(v[idx])
+                   nd.append(n)
+          result=zip(orient,nd)
+          result.sort()
+          nodes2=[c[1] for c in result]
+          for n in nodes2:
+               try:
+                    nodes_ls.remove(n)
+               except:
+                    pass
+          orient_nodes_surf=orient_nodes_surf+nodes2
+    #get the vertical curve
+    curve_vertical=[]
+    for s in lsurface:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for l in lcs:
+            x=cubit.get_bounding_box('curve', l)
+            length=[(x[2],1),(x[5],2),(x[8],3)]
+            length.sort()
+            if length[-1][1] == 3:
+                curve_vertical.append(l)
+    #
+    icurve=list2str(curve_vertical)
+    orientx=[]
+    orienty=[]
+    orientz=[]
+    cubit.cmd('del group curve_vertical')
+    cubit.cmd("group 'curve_vertical' add node in curve "+icurve)
+    group1 = cubit.get_id_from_name('curve_vertical')
+    nodes_curve = list(cubit.get_group_nodes(group1))
+    for n in nodes_curve:
+        try:
+             orient_nodes_surf.remove(n)
+        except:
+             pass
+    #
+    return nodes_curve,orient_nodes_surf
+
+
+
+def select_bottom_curve(lc):
+    z=[]
+    for l in lc:
+        center_point = cubit.get_center_point("curve", l)
+        z.append(center_point[2])
+    result=zip(z,lc)
+    result.sort()
+    print result
+    return result[0][1]
+    
+
+
+def check_bc(iproc,xmin,xmax,ymin,ymax,cpux,cpuy):
+    """
+    set the boundary condition during the collectiong phase and group the nodes of the vertical surface in groups for the merging phase
+    iproc is the value of the processor 
+    xmin,ymin,ymax,ymin are the list of iproc that have at least one absorbing boundary condition
+    """
+    try:
+        import initializing as initializing
+        cubit                   = initializing.initializing_cubit()
+    except:
+        pass
+    list_vol=cubit.parse_cubit_list("volume","all")
+    surf_xmin=[]
+    surf_ymin=[]
+    surf_xmax=[]
+    surf_ymax=[]
+    if  not isinstance(xmin, list): xmin=[xmin]
+    if  not isinstance(ymin, list): ymin=[ymin]
+    if  not isinstance(xmax, list): xmax=[xmax]
+    if  not isinstance(ymax, list): ymax=[ymax]
+    for id_vol in list_vol:
+        surf_vertical=[]
+        xsurf=[]
+        ysurf=[]
+        tres=0.3
+        lsurf=cubit.get_relatives("volume",id_vol,"surface")
+        icheck=0
+        for k in lsurf:
+            normal=cubit.get_surface_normal(k)
+            center_point = cubit.get_center_point("surface", k)
+            if normal[2] >= -1*tres and normal[2] <= tres:
+               surf_vertical.append(k)
+               xsurf.append(center_point[0])
+               ysurf.append(center_point[1])
+        surf_xmin.append(surf_vertical[xsurf.index(min(xsurf))])
+        surf_ymin.append(surf_vertical[ysurf.index(min(ysurf))])
+        surf_xmax.append(surf_vertical[xsurf.index(max(xsurf))])
+        surf_ymax.append(surf_vertical[ysurf.index(max(ysurf))])
+    curve_xmin=[]
+    curve_ymin=[]
+    curve_xmax=[]
+    curve_ymax=[]
+    from sets import Set #UPGRADE.... the sets module is deprecated after python 2.6
+    for s in surf_xmin:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for lc in lcs:
+            curve_xmin.append(lc)
+    for s in surf_xmax:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for lc in lcs:
+            curve_xmax.append(lc)
+    for s in surf_ymin:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for lc in lcs:
+            curve_ymin.append(lc)
+    for s in surf_ymax:
+        lcs=cubit.get_relatives("surface",s,"curve")
+        for lc in lcs:
+            curve_ymax.append(lc)
+    curve_xmin=list(Set(curve_xmin))
+    curve_ymin=list(Set(curve_ymin))
+    curve_xmax=list(Set(curve_xmax))
+    curve_ymax=list(Set(curve_ymax))
+    curve_bottom_xmin=select_bottom_curve(curve_xmin)
+    curve_bottom_ymin=select_bottom_curve(curve_ymin)
+    curve_bottom_xmax=select_bottom_curve(curve_xmax)
+    curve_bottom_ymax=select_bottom_curve(curve_ymax)
+    print curve_bottom_xmin,curve_bottom_ymin,curve_bottom_xmax,curve_bottom_ymax
+    #
+    #
+    nodes_curve_ymax,orient_nodes_surf_ymax=get_ordered_node_surf(surf_ymax,curve_bottom_ymax)
+    nodes_curve_xmax,orient_nodes_surf_xmax=get_ordered_node_surf(surf_xmax,curve_bottom_xmax)
+    nodes_curve_ymin,orient_nodes_surf_ymin=get_ordered_node_surf(surf_ymin,curve_bottom_ymin)
+    nodes_curve_xmin,orient_nodes_surf_xmin=get_ordered_node_surf(surf_xmin,curve_bottom_xmin)
+    c_xminymin=Set(nodes_curve_xmin).intersection(nodes_curve_ymin)
+    c_xminymax=Set(nodes_curve_xmin).intersection(nodes_curve_ymax)
+    c_xmaxymin=Set(nodes_curve_xmax).intersection(nodes_curve_ymin)
+    c_xmaxymax=Set(nodes_curve_xmax).intersection(nodes_curve_ymax)
+    
+    for n in c_xminymin:
+             v = cubit.get_nodal_coordinates(n)
+             orient.append(v[2])
+             nd.append(n)
+    result=zip(orient,nd)
+    result.sort()
+    c_xminymin=[c[1] for c in result]
+    
+    for n in c_xminymax:
+             v = cubit.get_nodal_coordinates(n)
+             orient.append(v[2])
+             nd.append(n)
+    result=zip(orient,nd)
+    result.sort()
+    c_xminymax=[c[1] for c in result]
+    
+    for n in c_xmaxymin:
+             v = cubit.get_nodal_coordinates(n)
+             orient.append(v[2])
+             nd.append(n)
+    result=zip(orient,nd)
+    result.sort()
+    c_xmaxymin=[c[1] for c in result]
+    
+    for n in c_xmaxymax:
+             v = cubit.get_nodal_coordinates(n)
+             orient.append(v[2])
+             nd.append(n)
+    result=zip(orient,nd)
+    result.sort()
+    c_xmaxymax=[c[1] for c in result]
+    #
+    boundary={}
+    boundary['id']=iproc
+    #
+    boundary['nodes_surf_xmin']=orient_nodes_surf_xmin
+    boundary['nodes_surf_xmax']=orient_nodes_surf_xmax
+    boundary['nodes_surf_ymin']=orient_nodes_surf_ymin
+    boundary['nodes_surf_ymax']=orient_nodes_surf_ymax
+    #
+    boundary['node_curve_xminymin']=c_xminymin
+    boundary['node_curve_xminymax']=c_xminymax
+    boundary['node_curve_xmaxymin']=c_xmaxymin
+    boundary['node_curve_xmaxymax']=c_xmaxymax
+    #
+    #
+    block_list=cubit.get_block_id_list()
+    entities=['face']
+    entity='face'
+    
+    if len(block_list) == 0:
+        boundary_definition.define_bc(entities,parallel=False)
+    #
+    if iproc in list(xmin):
+        xminflag=False
+        refname=entity+'_abs_xmin'
+        if block_list != 0:
+           for block in block_list:
+                ty=cubit.get_block_element_type(block)
+                if ty != 'HEX8':
+                    name=cubit.get_exodus_entity_name('block',block)
+                    if name == refname:
+                        build_block_side(surf_xmin,refname,obj=entity,id_0=block)
+                        #build_block_side(surf_xmin,entity+'_abs',obj=entity,id_0=block+1)
+                        xminflag=True
+        if not xminflag:
+            block=cubit.get_next_block_id()
+            build_block_side(surf_xmin,refname,obj=entity,id_0=block)
+            #build_block_side(surf_xmin,entity+'_abs',obj=entity,id_0=block+1)
+    #
+    if iproc in list(xmax):
+        xmaxflag=False
+        refname=entity+'_abs_xmax'
+        if block_list != 0:
+           for block in block_list:
+                ty=cubit.get_block_element_type(block)
+                if ty != 'HEX8':
+                    name=cubit.get_exodus_entity_name('block',block)
+                    if name == refname:
+                        build_block_side(surf_xmax,refname,obj=entity,id_0=block)
+                        #build_block_side(surf_xmax,entity+'_abs',obj=entity,id_0=block+1)
+                        xmaxflag=True
+        if not xmaxflag:
+            block=cubit.get_next_block_id()
+            build_block_side(surf_xmax,refname,obj=entity,id_0=block)
+            #build_block_side(surf_xmax,entity+'_abs',obj=entity,id_0=block)
+            #
+    if iproc in list(ymin):
+        yminflag=False
+        refname=entity+'_abs_ymin'
+        if block_list != 0:
+           for block in block_list:
+                ty=cubit.get_block_element_type(block)
+                if ty != 'HEX8':
+                    name=cubit.get_exodus_entity_name('block',block)
+                    if name == refname:
+                        build_block_side(surf_ymin,refname,obj=entity,id_0=block)
+                        #build_block_side(surf_ymin,entity+'_abs',obj=entity,id_0=block)
+                        yminflag=True
+        if not yminflag:
+            block=cubit.get_next_block_id()
+            build_block_side(surf_ymin,refname,obj=entity,id_0=block)
+            #build_block_side(surf_ymin,entity+'_abs',obj=entity,id_0=block)
+    #
+    if iproc in list(ymax):
+        ymaxflag=False
+        refname=entity+'_abs_ymax'
+        if block_list != 0:
+           for block in block_list:
+                ty=cubit.get_block_element_type(block)
+                if ty != 'HEX8':
+                    name=cubit.get_exodus_entity_name('block',block)
+                    if name == refname:
+                        build_block_side(surf_ymax,refname,obj=entity,id_0=block)
+                        #build_block_side(surf_ymax,entity+'_abs',obj=entity,id_0=block)
+                        ymaxflag=True
+        if not ymaxflag:
+            block=cubit.get_next_block_id()
+            build_block_side(surf_ymax,refname,obj=entity,id_0=block)
+            #build_block_side(surf_ymax,entity+'_abs',obj=entity,id_0=block)
+    
+    return boundary
+    
+
+
+    
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/mpi_geocubit.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/mpi_geocubit.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/mpi_geocubit.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,32 @@
+#############################################################################
+# mpi_geocubit.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+def mpiprint(mpiflag,text):
+    if mpiflag:
+        #import mpi
+        #mpi.synchronizedWrite(text) 
+        #command = "comment '"+text+"'"
+        #cubit.cmd(command)
+        print text
+    else:
+        print text
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/partitioner.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/partitioner.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/partitioner.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,1107 @@
+#############################################################################
+# partitioner.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+
+def partitioner_obsolete():
+    """create the partitioner"""
+    import initializing as initializing
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    
+    import sys, os
+    from sets import Set
+    from utilities import load_curves,project_curve
+    
+    ############
+    #
+    command = "reset"
+    cubit.cmd(command)
+    #
+    if cfg.debug:
+        command = "set info on"
+        cubit.cmd(command)
+        command = "set logging on file '"+cfg.working_dir+"/debug.log'"
+        cubit.cmd(command)
+    #
+    xmin_surf=cfg.xmin
+    xmax_surf=cfg.xmax
+    ymin_surf=cfg.ymin
+    ymax_surf=cfg.ymax
+    #
+    vstart=cubit.get_last_id("vertex")+1
+    command = "create vertex "+str(xmin_surf)+" "+str(ymin_surf)+" "+str(cfg.top_partitioner)
+    cubit.cmd(command)
+    command = "create vertex "+str(xmin_surf)+" "+str(ymax_surf)+" "+str(cfg.top_partitioner)
+    cubit.cmd(command)
+    command = "create vertex "+str(xmax_surf)+" "+str(ymax_surf)+" "+str(cfg.top_partitioner)
+    cubit.cmd(command)
+    command = "create vertex "+str(xmax_surf)+" "+str(ymin_surf)+" "+str(cfg.top_partitioner)
+    cubit.cmd(command)
+    vend=cubit.get_last_id("vertex")
+    #
+    command = "create surface vertex " +str(vstart)+" to "+str(vend)
+    cubit.cmd(command)
+    #
+    top_surface=cubit.get_last_id("surface")
+    top_volume=cubit.get_last_id("volume")
+    #
+    external_curve=cubit.get_relatives("surface", top_surface, "curve")
+    external_curve=str(list(external_curve)).replace("["," ").replace("]"," ")
+    print external_curve
+    print cfg.outline_curve,cfg.transition_curve,cfg.partitioning_curve,cfg.internal_curve
+    #
+    try:
+        outline_curve=load_curves(cfg.outline_curve,top_surface)
+    except:
+        outline_curve=None
+    try:
+        transition_curve=load_curves(cfg.transition_curve,top_surface)
+    except:
+        transition_curve=None
+    try:
+        internal_curve=load_curves(cfg.internal_curve,top_surface)
+    except:
+        internal_curve=None
+    try:
+        partitioning_curve=load_curves(cfg.partitioning_curve,top_surface)
+    except:
+        partitioning_curve=None
+    print outline_curve,transition_curve,partitioning_curve,internal_curve
+    #
+    command = "save as '"+ cfg.working_dir+ "/partitioner_debug.cub' overwrite"
+    cubit.cmd(command)    
+    #
+    #
+    if internal_curve:
+        print 'internal'
+        tmp_curve=cubit.get_last_id("curve")
+        cubit.cmd('imprint volume all with curve '+str(internal_curve))
+        tmp_curve_after=cubit.get_last_id("curve")
+        internal_curve=str(range(tmp_curve+1,tmp_curve_after+1)).replace("["," ").replace("]"," ")
+    #
+    if transition_curve:
+        tmp_curve=cubit.get_last_id("curve")
+        cubit.cmd('imprint volume all with curve '+str(transition_curve))
+        tmp_curve_after=cubit.get_last_id("curve")
+        transition_curve=str(range(tmp_curve+1,tmp_curve_after+1)).replace("["," ").replace("]"," ")
+    #
+    if partitioning_curve:
+        cubit.cmd('imprint volume all with curve '+str(partitioning_curve)) 
+    #
+    cubit.cmd('delete curve all')
+    cubit.cmd('imprint all')
+    cubit.cmd('merge surface all')
+    cubit.cmd('merge curve all')
+    #
+    mer=cubit.get_error_count()
+    command = "save as '"+ cfg.working_dir+ "/partitioner.cub' overwrite"
+    cubit.cmd(command)    
+    #
+    ls=cubit.parse_cubit_list("surface","all")
+    print ls
+    s_out=Set(ls)
+    #
+    s_t=Set()
+    if transition_curve:
+        for s in transition_curve.split(','):
+            s=int(s)
+            #print Set((cubit.get_relatives("curve",s,"surface")))
+            s_t=s_t | Set((cubit.get_relatives("curve",s,"surface")))
+    #
+    print 't',s_t
+    s_inside=Set()
+    if internal_curve:
+        for s in internal_curve.split(','):
+            s=int(s)
+            print s,Set((cubit.get_relatives("curve",s,"surface")))
+            s_inside=s_inside | Set((cubit.get_relatives("curve",s,"surface")))
+    #
+    print 'inside', s_inside
+    if not internal_curve and transition_curve:
+        s_out = s_out - s_t
+        s_t = s_t - s_out
+    else:
+        s_in  = s_inside - s_t
+        s_t   = s_inside - s_in
+        s_out = s_out - s_t
+        s_out = s_out - s_in
+    #
+    surf_out=list(s_out)
+    surf_out_txt=str(surf_out).replace("["," ").replace("]"," ")
+    surf_transition=list(s_t)
+    surf_transition_txt=str(surf_transition).replace("["," ").replace("]"," ")
+    surf_in=list(s_in)
+    surf_in_txt=str(surf_in).replace("["," ").replace("]"," ")
+    print 'in ',surf_in
+    print 'out ',surf_out
+    print 'transition ',surf_transition
+    #
+    cubit.cmd('surface '+surf_in_txt+' size '+str(cfg.size_small))
+    cubit.cmd('surface '+str(surf_in_txt)+' scheme pave')
+    cubit.cmd('mesh surface '+str(surf_in_txt))
+    #
+    #cubit.cmd('curve '+transition_curve+' size '+str(cfg.size_large))
+    cubit.cmd('curve '+transition_curve+' interval 1')
+    command = "mesh curve "+transition_curve
+    cubit.cmd(command)
+    cubit.cmd('surface '+str(surf_out_txt)+' size '+str(cfg.size_large))
+    cubit.cmd('surface '+str(surf_out_txt)+' scheme pave')
+    cubit.cmd('mesh surface '+str(surf_out_txt))
+    #
+    #TODO: make automatic
+    if  cfg.manual_adj:
+        command = "save as '"+cfg.working_dir+'/'+cfg.file_manual_adjustment+"' overwrite"
+        cubit.cmd(command)
+        print '*************************'
+        print command
+        print 'manual node adjustment'
+        q=0
+        for l in ls:
+            q=q+cubit.get_surface_element_count(l)
+        print q, ' quads ---> CPUs'
+        sys.exit()
+    elif cfg.play_adj:
+        print cfg.play_adj
+        for command in cfg.play_adj.split('\n'):
+            cubit.cmd(command)
+            print command
+    elif cfg.no_adj:
+        print 'no adjustements'
+    else:
+        print 'please check the configuration: one of manual_adj,play_adj,no_adjust should be True'
+    
+    
+    #
+    command = "group 'list_edge_out' add edge in face in surf "+str(surf_out_txt)
+    cubit.cmd(command)
+    command = "group 'list_edge_t' add edge in face in surf "+str(surf_transition_txt)
+    cubit.cmd(command)
+    try:
+        group=cubit.get_id_from_name("list_edge_in")
+    except:
+        command = "group 'list_edge_t' add edge in surf "+str(surf_transition_txt)
+        cubit.cmd(command)
+        group=cubit.get_id_from_name("list_edge_in")
+    list_edge_in=cubit.get_group_edges(group)
+    group=cubit.get_id_from_name("list_edge_out")
+    list_edge_out=cubit.get_group_edges(group)
+    group=cubit.get_id_from_name("list_edge_t")
+    list_edge_t=cubit.get_group_edges(group)   
+    edge_in=Set(list_edge_in)
+    edge_out=Set(list_edge_out)
+    edge_transition=Set(list_edge_t)
+    edge_in=edge_in-edge_transition
+    edge_out=edge_out-edge_transition
+    #
+    last_curve_start=cubit.get_last_id("curve")+1
+    for edge in edge_in:
+        nodes=cubit.get_connectivity("Edge",edge)
+        command = "create curve spline node "+str(list(nodes))
+        command = command.replace("["," ").replace("]"," ")
+        cubit.cmd(command)
+        last_curve=cubit.get_last_id("curve")
+        command = "group 'l_curve_in' add curve "+str(last_curve)
+        cubit.cmd(command)
+    #
+    for edge in list_edge_out:
+        nodes=cubit.get_connectivity("Edge",edge)
+        command = "create curve spline node "+str(list(nodes))
+        command = command.replace("["," ").replace("]"," ")
+        cubit.cmd(command)
+        last_curve=cubit.get_last_id("curve")
+        command = "group 'l_curve_out' add curve "+str(last_curve)
+        cubit.cmd(command)
+    #
+    cubit.cmd('reset vol all')
+    #
+    igroup=cubit.get_id_from_name("l_curve_in")
+    l_curve_in=cubit.get_group_curves(igroup)
+    command = "delete group "+ str(igroup)
+    cubit.cmd(command)
+    igroup=cubit.get_id_from_name("l_curve_out")
+    l_curve_out=cubit.get_group_curves(igroup)
+    command = "delete group "+ str(igroup)
+    cubit.cmd(command)
+    #
+    last_surface_before=cubit.get_last_id("surface")
+    command = "imprint vol "+str(top_volume)+" with curve "+str(list(l_curve_in))
+    command = command.replace("["," ").replace("]"," ")
+    cubit.cmd(command)
+    last_surface_after=cubit.get_last_id("surface")
+    command = "group 'list_surface_in' add surface "+surf_in_txt+" "+str(last_surface_before+1)+" to "+str(last_surface_after)
+    cubit.cmd(command)
+    #
+    last_surface_before=cubit.get_last_id("surface")                                                                            
+    command = "imprint vol "+str(top_volume)+" with curve "+str(list(l_curve_out))                                              
+    command = command.replace("["," ").replace("]"," ")
+    cubit.cmd(command)
+    last_surface_after=cubit.get_last_id("surface")
+    command = "group 'list_surface_out' add surface "+surf_out_txt+" "+str(last_surface_before+1)+" to "+str(last_surface_after)
+    cubit.cmd(command)
+    #
+    command = "group 'list_surface_transition' add surface "+surf_transition_txt
+    cubit.cmd(command)
+    #
+    command = "del curve all"
+    cubit.cmd(command)
+    #
+    cubit.cmd('merge surf in volume '+str(top_volume))
+    cubit.cmd('list group all')
+    command = "compress all"
+    cubit.cmd(command)
+    #TODO filename general
+    command = "save as '"+cfg.working_dir+'/'+cfg.file_partitioner_cub+"' overwrite"
+    cubit.cmd(command)
+    print command
+    cubit.print_surface_summary_stats()
+    print 'saved'
+    print
+    ls=cubit.parse_cubit_list("surface","all")
+    print '@@@@@@@@@@@@@@@@@@@@@@ ', ls, ' CORES requested ' 
+    
+
+def partitioner_map_obsolete(partitioner_filename=None):
+    """return the map of the partioner surfaces associated to the cpu, and exclude some surface
+
+    usage: list_surf_all,list_surface_in,list_surface_out,list_surface_transition,list_surface_nomesh,pmap=partitioner_map()
+
+    the map is a dictionary of surfmap class objects:
+
+        obj=surfmap(iproc,list_surface_all)
+
+        obj.iproc = mpi processor
+        obj.idsurf= surface id (the surface is saved in a ACIS (.sat) file called "surf_{idsurf}.sat")                                      
+        obj.s_adj = get the id list of the surfaces adjacent to obj.idsurf
+        obj.p_adj = get the id list of the processor associated to the surface adjacent to obj.idsurf
+        obj.point = get the coordinate of the center_point of the curves shared by the adjacent surfaces
+        obj.all   = list of all the previous obj properties [self.iproc,self.idsurf,self.s_adj,self.p_adj,self.point]
+
+
+    for example:
+
+        iproc processor -> id surf from list_surf_all / [list id surf adjacent] [list id proc adjacent]: 
+        0   -> 4/[5, 1, 15] [1, 22, 11]
+        1   -> 5/[4, 16, 17, 1] [0, 12, 13, 22]
+        2   -> 6/[19, 22, 21] [15, 18, 17]
+        3   -> 7/[8, 14, 9] [4, 10, 5]
+        .....
+
+    """
+    import initializing as initializing
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    from mpi_geocubit import mpiprint
+    #
+    #
+    import sys, os
+    from sets import Set
+    #
+    def get_surf_adj(iproc,list_surf_all):
+          import cubit
+          l=[]
+          l=list(cubit.get_adjacent_surfaces("surface", list_surf_all[iproc]))
+          l.remove( list_surf_all[iproc])
+          return l
+    #
+    def get_proc_adj(iproc,list_surf_all,list_surf_adj):
+          l=[]
+          for s in list_surf_adj:
+                l.append(list_surf_all.index(s))
+          return l
+    #
+    def get_x(idsurf,list_surf_adj):
+          import cubit
+          from sets import Set
+          l=[]
+          for s in list_surf_adj:
+                c=Set(cubit.get_relatives("surface",s,"curve")) & Set(cubit.get_relatives("surface",idsurf,"curve"))
+                p=cubit.get_center_point("curve",list(c)[0])
+                l.append(p)
+          return l
+    #
+    #
+    class surfmap:
+          def __init__(self,iproc,list_surf_all):
+              self.iproc=iproc
+              self.idsurf=list_surf_all[iproc]
+              self.s_adj=get_surf_adj(iproc,list_surf_all)
+              self.p_adj=get_proc_adj(iproc,list_surf_all,self.s_adj)
+              self.point=get_x(self.idsurf,self.s_adj) 
+              self.all=[self.iproc,self.idsurf,self.s_adj,self.p_adj,self.point]     
+          def __repr__(self):
+              msg=str(list(self.all))
+              return msg
+    #
+    command = "reset"
+    cubit.cmd(command)
+    #
+    if cfg.create_partitioner:
+       partitioner()
+    elif os.path.exists(cfg.file_partitioner_cub):
+       command = "import cubit '"+cfg.file_partitioner_cub+"'"
+       cubit.cmd(command)
+    elif os.path.exists(cfg.working_dir+'/'+cfg.file_partitioner_cub):
+       command = "import cubit '"+cfg.working_dir+"/"+cfg.file_partitioner_cub+"'"
+       cubit.cmd(command)
+       
+       
+       
+       
+       
+    #
+    #
+    #command = "imprint curve all"
+    #cubit.cmd(command)
+    #command = "imprint surface all"
+    #cubit.cmd(command)
+    #command = "merge surf all"
+    #cubit.cmd(command)
+    #command = "imprint all"
+    #cubit.cmd(command)
+    #command = "merge all"
+    #cubit.cmd(command)
+    command = "compress all"
+    cubit.cmd(command)
+    #
+    group=cubit.get_id_from_name("list_surface_in")
+    list_surface_in=cubit.get_group_surfaces(group)
+    group=cubit.get_id_from_name("list_surface_out")
+    list_surface_out=cubit.get_group_surfaces(group)
+    group=cubit.get_id_from_name("list_surface_transition")
+    list_surface_transition=cubit.get_group_surfaces(group)
+    group=cubit.get_id_from_name("list_surface_nomesh")
+    list_surface_nomesh=cubit.get_group_surfaces(group)
+    cubit.cmd('list group all')
+    print list_surface_in,list_surface_transition,list_surface_out,list_surface_nomesh
+    
+    #
+    list_surface_all=list(list_surface_out+list_surface_in+list_surface_transition+list_surface_nomesh)
+    list_surface_decomposer=list(list_surface_out+list_surface_in)
+    #
+    if os.path.exists(cfg.working_dir) and (iproc == 0 or cfg.single):
+        command = "export acis '"+cfg.working_dir+"/surf_all.sat' surface all overwrite"
+        cubit.cmd(command)
+        #cubit_error_stop(iproc,command,ner)
+        for i in list_surface_all:
+            command = "export acis '"+cfg.working_dir+"/surf_"+str(i)+".sat' surface "+str(i)+" overwrite"
+            cubit.cmd(command)
+            #cubit_error_stop(iproc,command,ner)
+    #
+    pmap={}
+    for i in range(0,len(list_surface_all)):
+        pmap[i]= surfmap(i,list_surface_all)
+    #
+    #
+    text='***********************\nthe partioner is composed of ***'+str(len(list_surface_all))+ '*** surfaces\nit requires ***'+str(len(list_surface_all))+'*** cpus\n******************'
+    mpiprint(mpiflag,text)
+    #
+    if not mpiflag:
+        print 'ATTENTION***********************************************'
+        print 'id proc = ',iproc,' -> surf ',list_surface_all[iproc]
+        print 'only the volume correspondent to surf_',str(list_surface_all[iproc]),'.sat will be mesh'
+        print 'processor -> list_surf_all / parallel map: '
+        for i in range(0,len(list_surface_all)):
+                flag=''
+                if list_surface_all[i] in list_surface_in:
+                    flag='( in  )'
+                elif list_surface_all[i] in list_surface_out:
+                    flag='( out )'
+                elif list_surface_all[i] in list_surface_transition:
+                    flag='( t   )'
+                elif list_surface_all[i] in list_surface_nomesh:
+                    flag='( no   )'
+                print i,' ',flag,' -> ', list_surface_all[i],'/', surfmap(i,list_surface_all).s_adj, surfmap(i,list_surface_all).p_adj
+        print '********************************************************'
+    else:
+        if iproc == 0:
+            partxt=open(cfg.working_dir+"/partitioner_map.txt","w")
+            partxt.write('processor -> list_surf_all / parallel map: \n')
+            for i in range(0,len(list_surface_all)):
+                flag=''
+                if list_surface_all[i] in list_surface_in:
+                    flag='( in  )'
+                if list_surface_all[i] in list_surface_out:
+                    flag='( out )'
+                if list_surface_all[i] in list_surface_transition:
+                    flag='( t   )'
+                if list_surface_all[i] in list_surface_nomesh:
+                    flag='( no   )'
+                partxt.write(str(i)+' '+flag+' -> '+ str(list_surface_all[i])+'/'+ str(surfmap(i,list_surface_all).s_adj)+' '+str(surfmap(i,list_surface_all).p_adj)+'\n')
+            partxt.close()
+    #
+    #
+    text='***********************\nthe partioner is composed of ***'+str(len(list_surface_all))+ '*** surfaces\nit requires ***'+str(len(list_surface_all))+'*** cpus\n******************'
+    mpiprint(mpiflag,text)
+    #
+    #TODO make recursive so I can mesh with a lower number of cpu
+    if numproc < len(list_surface_all) and mpiflag:
+        text='ATTENTION**********************************************'
+        mpiprint(mpiflag,text)
+        for i in range(numproc+1,len(list_surface_all)):
+            text='the volume correspondent to surf_'+str(list_surface_all[iproc])+'.sat will ***NOT*** be mesh'
+            mpiprint(mpiflag,text)
+        text='********************************************************'
+        mpiprint(mpiflag,text)
+    if numproc > len(list_surface_all):
+        text='number of processors greater than the number of slices....'
+        mpiprint(mpiflag,text)
+        raise NameError, 'error'    
+    #
+    #
+    return list_surface_all,list_surface_in,list_surface_out,list_surface_transition,list_surface_nomesh,pmap
+
+
+
+
+def partitioning_volume_obsolete():
+    import sys,os
+    import menu as menu
+    import initializing as initializing
+    import partitioner as partitioner
+    from sets import Set
+    #
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    from mpi_geocubit import mpiprint
+    #
+    numpy                       = initializing.initializing_numpy()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+
+    def sortf(x,y):
+        return cmp(x[1],y[1])
+    #
+    #
+    list_surface_all,list_surface_in,list_surface_out,list_surface_transition,list_surface_nomesh,pmap=partitioner.partitioner_map(cfg.file_partitioner_cub)
+    #
+    #
+    command = "reset"
+    cubit.cmd(command)
+    #
+    id_partitioner_surf=list_surface_all[iproc]
+    command = "import acis '"+cfg.working_dir+"/surf_"+str(id_partitioner_surf)+".sat'"
+    cubit.cmd(command)
+    last_surface=cubit.get_last_id("surface")
+    #
+    top_box=cubit.get_bounding_box("surface",last_surface)
+    s_xmin=cubit.get_bounding_box("surface",last_surface)[0]
+    s_xmax=cubit.get_bounding_box("surface",last_surface)[1]
+    s_ymin=cubit.get_bounding_box("surface",last_surface)[3]
+    s_ymax=cubit.get_bounding_box("surface",last_surface)[4]
+    command = "del surf "+str(last_surface)
+    cubit.cmd(command)
+    #
+    if cfg.volume_file:
+        command = "import cubit '"+cfg.volume_file+"'"
+        cubit.cmd(command)
+    else:
+        import local_volume
+        if iproc == 0:
+            coordx_0,coordy_0,elev_0,nx_0,ny_0=local_volume.read_grid()
+            coordx=mpi.bcast(coordx_0)
+            coordy=mpi.bcast(coordy_0)
+            elev=mpi.bcast(elev_0)
+            nx=mpi.bcast(nx_0)
+            ny=mpi.bcast(ny_0)
+        else:
+            coordx=mpi.bcast()
+            coordy=mpi.bcast()
+            elev=mpi.bcast()
+            nx=mpi.bcast()
+            ny=mpi.bcast()
+        extract_volume(s_xmin,s_ymin,s_xmax,s_ymax,coordx,coordy,elev,nx,ny)
+    #cubit_error_stop(iproc,command,ner)
+    #
+    list_vol=cubit.parse_cubit_list("volume","all")
+    command = "import acis '"+cfg.working_dir+"/surf_"+str(id_partitioner_surf)+".sat'"
+    cubit.cmd(command)
+    last_surface=cubit.get_last_id("surface")
+    #
+    init_n_vol=len(list_vol)
+    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...    
+    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
+    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
+    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
+    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
+    zmax_box=cubit.get_bounding_box("surface",last_surface)[7]
+    #
+    distance=2.*(zmax_box-zmin_box)
+    #
+    command = "composite create curve in surf "+str(last_surface)
+    cubit.cmd(command)
+    ner=cubit.get_error_count()
+    command = "webcut volume "+str(list(list_vol))+" sweep surface "+str(last_surface)+" vector 0 0 -1 distance "+str(distance)
+    command = command.replace("["," ").replace("]"," ")
+    cubit.cmd(command)
+    #cubit_error_stop(iproc,command,ner)
+    #
+    #
+    #delete the vol 
+    list_vol=cubit.parse_cubit_list("volume","all")
+    set_vol=Set([])
+    dbox=[]
+    for id_vol in list_vol:
+        lsurf=cubit.get_relatives("volume",id_vol,"surface")
+        set_vol.add(len(lsurf))
+        d=cubit.get_bounding_box("volume",id_vol)[1]-cubit.get_bounding_box("volume",id_vol)[0]
+        dbox.append([id_vol,d])
+    dbox.sort(sortf)
+    #TODO explain....
+    if id_partitioner_surf in list_surface_transition:
+        if len(set_vol) != 3: #in the transition there is a hole so there are 3 classes of volume 
+           txt='transition - imprint of partitioner surface not consistent'+str(id_partitioner_surf)
+           command = "comment '"+txt+"'"
+           cubit.cmd(command)
+           raise NameError, txt
+        for obj in dbox[0:init_n_vol]:
+            command = "delete vol "+str(obj[0])
+            cubit.cmd(command)
+        for obj in dbox[3*init_n_vol-init_n_vol:3*init_n_vol]:
+            command = "delete vol "+str(obj[0])
+            cubit.cmd(command)
+    else:
+        if len(set_vol) != 2:
+           txt='in-out-nomesh - imprint of partitioner surface not consistent'+str(id_partitioner_surf)
+           command = "comment '"+txt+"'"
+           cubit.cmd(command)
+           raise NameError, txt 
+        min_surf=min(set_vol)
+        for id_vol in list_vol:
+            lsurf=cubit.get_relatives("volume",id_vol,"surface")
+            if  len(lsurf) != min_surf: 
+                command = "delete vol "+str(id_vol) # I'm deleting the volume which doesn't have the minimum number of surfaces
+                cubit.cmd(command)
+                #cubit_error_stop(iproc,command,ner)
+    #
+    command = "delete surf "+str(last_surface)
+    cubit.cmd(command)
+
+    tol=cfg.size_small/10.
+    command = "merge tolerance "+str(tol)
+    cubit.cmd(command); print command
+    command = "imprint tolerant volume all"
+    cubit.cmd(command)
+    #cubit_error_stop(iproc,command,ner)
+    #command = "imprint all"
+    #cubit.cmd(command)
+    ##cubit_error_stop(iproc,command,ner)
+    #command = "merge all"
+    #cubit.cmd(command)
+    #cubit_error_stop(iproc,command,ner)    
+    command = "merge surf all"
+    cubit.cmd(command)
+    #cubit_error_stop(iproc,command,ner)
+    command = "compress vol all"
+    cubit.cmd(command)
+    #cubit_error_stop(iproc,command,ner)
+    command = "compress surf all"
+    cubit.cmd(command)
+    #cubit_error_stop(iproc,command,ner)
+    if id_partitioner_surf in list_surface_out:
+       command = "save as '"+cfg.working_dir+"/"+"out_vol_"+str(iproc)+".cub' overwrite"
+       cubit.cmd(command)    
+    elif id_partitioner_surf in list_surface_in:
+        command = "save as '"+cfg.working_dir+"/"+"in_vol_"+str(iproc)+".cub' overwrite"
+        cubit.cmd(command)
+        #cubit_error_stop(iproc,command,ner)
+    elif id_partitioner_surf in list_surface_transition:
+        command = "save as '"+cfg.working_dir+"/"+"transition_vol_"+str(iproc)+".cub' overwrite"
+        cubit.cmd(command)             
+    elif id_partitioner_surf in list_surface_transition:
+        command = "save as '"+cfg.working_dir+"/"+"nomesh_vol_"+str(iproc)+".cub' overwrite"
+        cubit.cmd(command)                            
+    else:
+        raise NameError, 'surface not in list'    
+
+
+def refinement_basin_obsolete(iproc,id_partitioner_surf,list_surface_out,list_surface_transition,top_surface,top_surface_add):
+    import initializing as initializing
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    if  id_partitioner_surf not in list_surface_out:
+        from select_in_out import select_in_out
+        cubit.cmd('save as "'+cfg.working_dir+'/view_before_basinrefinement_'+str(iproc)+'.cub" overwrite ')
+        command = "set node constraint off"
+        cubit.cmd(command)
+        vc=cubit.get_volume_element_count(vol[-1].ID)
+        sc=cubit.get_surface_element_count(top_surface)
+        if cfg.cut_outline: 
+            sc2=cubit.get_surface_element_count(top_surface_add)
+        else:
+            sc2=0
+        #
+        ntime=int(vc/(sc+sc2))-2
+        #
+        if not cfg.cut_outline and id_partitioner_surf in list_surface_transition:
+            command = "import acis '"+cfg.outline_curve+"'"
+            cubit.cmd(command)
+            #cubit_error_stop(iproc,command,ner)
+            curve_outline=cubit.get_last_id("curve")
+            node_inside=select_in_out(top_surface,curve_outline)#!!!!!
+            command = "group 'face_selected' add face in node "+str(list(node_inside)).replace("["," ").replace("]"," ")
+            cubit.cmd(command)
+            id_group=cubit.get_id_from_name('face_selected')
+            command = "group "+str(id_group)+"remove face in (surf all except surf "+str(top_surface)+")"
+            cubit.cmd(command)
+        else:
+            command = "group 'face_selected' add face in surf "+str(top_surface)
+            cubit.cmd(command)
+        #
+        id_group=cubit.get_id_from_name('face_selected')
+        if ntime > 0:
+            command = "group 'hex_refining' add hex propagate face in group "+str(list(id_group))+"times "+str(ntime)
+            command = command.replace("["," ").replace("]"," ")
+            cubit.cmd(command)
+            id_group=cubit.get_id_from_name('hex_refining')
+            cubit.cmd('block 1 face in surf all ')
+            cubit.cmd('set large exodus file off')
+            cubit.cmd('save as "'+cfg.working_dir+'/before_basinref_view_side_'+str(iproc)+'.cub" overwrite ')
+            command = "refine hex in group "+str(id_group)+'  numsplit 1 bias 1.0 depth 1 no_smooth'
+            cubit.cmd(command)
+        else:
+            command = "refine face in group "+str(id_group)+'  numsplit 1 bias 1.0 depth 1 no_smooth'
+            cubit.cmd(command)
+
+
+
+def interpolate_basin_obsolete(top_surface,top_surface_add):
+    import initializing as initializing
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    from select_in_out import select_in_out,select_in_out_global
+    #
+    id_group=cubit.get_id_from_name('hex_refining')
+    command = "del group "+str(id_group)
+    cubit.cmd(command)
+    id_group=cubit.get_id_from_name('face_selected')
+    command = "del group "+str(id_group)
+    cubit.cmd(command)
+    #
+    vc=cubit.get_volume_element_count(vol[-1].ID)
+    sc=cubit.get_surface_element_count(top_surface)
+    if cfg.cut_outline: 
+        sc2=cubit.get_surface_element_count(top_surface_add)
+    else:
+        sc2=0
+    #
+    ntime=int(vc/(sc+sc2))-2
+    command = "import acis '"+cfg.outline_curve+"'"
+    cubit.cmd(command)
+    curve_outline=cubit.get_last_id("curve")
+    node_inside=select_in_out(top_surface,curve_outline)
+    command = "group 'face_selected' add face in node "+str(list(node_inside)).replace("["," ").replace("]"," ")
+    cubit.cmd(command)
+    id_group=cubit.get_id_from_name('face_selected')
+    command = "group "+str(id_group)+"remove face in (surf all except surf "+str(top_surface)+")"
+    cubit.cmd(command)
+    if ntime > 0:
+        command = "group 'hex_refining' add hex propagate face in group "+str(list(id_group))+"times "+str(ntime)
+        command = command.replace("["," ").replace("]"," ")
+        cubit.cmd(command)
+    else:
+        command = "group 'hex_refining' add hex in face in group "+str(list(id_group))
+        command = command.replace("["," ").replace("]"," ")
+        cubit.cmd(command)
+    #
+    id_group=cubit.get_id_from_name('hex_refining')
+    list_hex=cubit.get_group_hexes(id_group)
+    #
+    command = "group 'list_node_inbasinhex' add node in hex "+str(list(list_hex))
+    command = command.replace("["," ").replace("]"," ") 
+    cubit.cmd(command)
+    group=cubit.get_id_from_name("list_node_inbasinhex")
+    list_node_inbasinhex=cubit.get_group_nodes(group)
+    command = "delete group "+ str(group)
+    cubit.cmd(command)
+    #
+    command = "import acis '"+cfg.basin_surf_acis_file+"'"
+    cubit.cmd(command)
+    basin_surface=cubit.get_last_id("surface")
+    #
+    nodes_inside_basin=select_in_out_global(list_node_inbasinhex,basin_surface)
+    command = "nodeset 1 "+str(nodes_inside_basin)
+    command = command.replace("["," ").replace("]"," ")
+    cubit.cmd(command)
+
+
+
+
+
+
+
+def mesh_partitioner_obsolete():
+        import sys,os
+        import menu as menu
+        import initializing as initializing
+        import partitioner as partitioner
+        #
+        mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+        from mpi_geocubit import mpiprint
+        #
+        cubit                       = initializing.initializing_cubit()
+        cfg                         = initializing.initializing_cfg()
+        class cubitvolume:
+              def __init__(self,ID,intervalv,centerpoint,dimension):
+                  self.ID=ID
+                  self.intervalv=intervalv
+                  self.centerpoint=centerpoint
+                  self.dim=dimension
+
+              def __repr__(self):
+                  msg="(vol:%3i, vertical interval: %4i, centerpoint: %8.2f)" % (self.ID, self.intervalv,self.centerpoint)
+                  return msg       
+
+        def by_z(x,y):
+            return cmp(x.centerpoint,y.centerpoint)
+        #
+        list_surface_all,list_surface_in,list_surface_out,list_surface_transition,list_surface_nomesh,pmap=partitioner.partitioner_map(cfg.file_partitioner_cub)
+
+        #
+        command = "reset"
+        cubit.cmd(command)
+        #
+        id_partitioner_surf=list_surface_all[iproc]
+        #
+
+        if id_partitioner_surf in list_surface_out:
+           command = "import cubit '"+cfg.working_dir+"/out_vol_"+str(iproc)+".cub' "
+           cubit.cmd(command)    
+        elif id_partitioner_surf in list_surface_in:
+            command = "import cubit '"+cfg.working_dir+"/in_vol_"+str(iproc)+".cub' "
+            cubit.cmd(command)
+        elif id_partitioner_surf in list_surface_transition:
+            command = "import cubit '"+cfg.working_dir+"/transition_vol_"+str(iproc)+".cub' "
+            cubit.cmd(command)
+        elif id_partitioner_surf in list_surface_nomesh:
+            command = "import cubit '"+cfg.working_dir+"/nomesh_vol_"+str(iproc)+".cub' "
+            cubit.cmd(command)                                     
+        else:
+            raise NameError, 'surface not in list'
+        if iproc == 0: print 'import...',command
+        #
+        list_vol=cubit.parse_cubit_list("volume","all")
+        nvol=len(list_vol)                                 
+        vol=[]
+        for id_vol in list_vol:
+            p=cubit.get_center_point("volume",id_vol)
+            vol.append(cubitvolume(id_vol,1,p[2],0))
+        vol.sort(by_z)
+        for id_vol in range(0,nvol):
+            vol[id_vol].intervalv=cfg.iv_interval[id_vol]
+        #
+        #TRANSITION SURF -     
+        if  cfg.cut_outline and id_partitioner_surf in list_surface_transition:
+            text='outline cutting.......'
+            #mpiprint(mpiflag,text)
+            command = "comment '"+"outline cutting......."+"'"
+            cubit.cmd(command)
+            command = "import acis '"+cfg.outline_curve+"'"
+            cubit.cmd(command)
+            #cubit_error_stop(iproc,command,ner)
+            outline_curve=cubit.get_last_id("curve")
+            #
+            #
+            lsurf=cubit.get_relatives("volume",vol[-1].ID,"surface")
+            normal=[]
+            tres=0.2
+            for k in lsurf:
+                normal=cubit.get_surface_normal(k)
+                if abs(normal[2] - 1) <= tres:
+                    top_surf=k
+            #
+            command = "project curve "+str(outline_curve)+ "onto surface " +str(top_surf)
+            cubit.cmd(command)
+            #
+            outline_curve=cubit.get_last_id("curve")
+            #
+            command = "imprint vol "+str(vol[nvol-1].ID)+" with curve "+str(outline_curve)
+            cubit.cmd(command)
+            #
+            command = "delete curve all"
+            cubit.cmd(command)
+            command = "imprint all"
+            cubit.cmd(command)
+            #cubit_error_stop(iproc,command,ner)
+            command = "merge all"
+            cubit.cmd(command)
+        #
+        #
+        surf_vertical=[]
+        surf_or=[]
+        top_surface=0
+        top_surface_add=''
+        bottom_surface=0
+        for l in range(0,nvol):
+            id_vol=vol[l].ID
+            lsurf=cubit.get_relatives("volume",id_vol,"surface")
+            znormal=[]
+            tres=cfg.tres
+            icheck=0
+            list_curve_vertical=[]
+            list_curve_or=[]
+            surf_vertical_tmp=[]
+            source_sweep=0
+            target_sweep=0
+            for k in lsurf:
+                normal=cubit.get_surface_normal(k)
+                center_point = cubit.get_center_point("surface", k)
+                if normal[2] >= -1*tres and normal[2] <= tres:
+                   surf_vertical.append(k)
+                   surf_vertical_tmp.append(k)
+                   lcurve=cubit.get_relatives("surface",k,"curve")
+                   list_curve_vertical=list_curve_vertical+list(lcurve)
+                   command = "surface "+str(k)+" scheme submap"
+                   cubit.cmd(command)
+                   #cubit_error_stop(iproc,command,ner)
+                   center_point = cubit.get_center_point("surface", k)
+                elif normal[2] >= -1-tres and normal[2] <= -1+tres:
+                   target_sweep=k
+                   surf_or.append(k)
+                   lcurve=cubit.get_relatives("surface",k,"curve")
+                   list_curve_or=list_curve_or+list(lcurve)
+                   command = "surface "+str(k)+" scheme pave"
+                   cubit.cmd(command)
+                   #cubit_error_stop(iproc,command,ner)
+                   if id_vol == vol[0].ID:
+                      top_bottom=k
+                elif normal[2] >= 1-tres and normal[2] <= 1+tres:
+                   if source_sweep == 0:
+                      source_sweep = str(k)
+                      source_sweep_add= ''
+                   else:
+                      source_sweep_add = str(k)
+                   surf_or.append(k)
+                   lcurve=cubit.get_relatives("surface",k,"curve")
+                   list_curve_or=list_curve_or+list(lcurve)
+                   if cfg.cut_outline and id_partitioner_surf in list_surface_transition and id_vol == vol[-1].ID :
+                      if top_surface == 0:
+                         top_surface=k
+                      else:
+                         top_surface_add=k
+                         text='top add'+str(k)
+
+                         area1=cubit.get_surface_area(top_surface)
+                         area2=cubit.get_surface_area(top_surface_add)
+                         if area1 > area2:
+                            top_surface_add=top_surface
+                            top_surface=k
+                   elif id_vol == vol[-1].ID:
+                      top_surface=k
+                      top_surface_add=''
+                   command = "surface "+str(k)+" scheme pave"
+                   cubit.cmd(command)
+                   #cubit_error_stop(iproc,command,ner)
+                else:
+                   text='normal = '+str(normal[2])
+                   mpiprint(mpiflag,text)
+                   text='treshold = '+str(tres)
+                   mpiprint(mpiflag,text)
+                   raise NameError, 'error assigning the curve' 
+            for k in list_curve_or:
+                length=cubit.get_curve_length(k)
+                interval=int(2*round(.5*length/cfg.size,0))
+                command = "curve "+str(k)+" interval "+str(interval)
+                cubit.cmd(command)
+                #cubit_error_stop(iproc,command,ner)
+                command = "curve "+str(k)+" scheme equal"
+                cubit.cmd(command)
+                #cubit_error_stop(iproc,command,ner)
+                icheck+=1
+            for s in surf_vertical_tmp:
+                lcurve=cubit.get_relatives("surface",s,"curve")
+                interval_store=[]
+                for k in lcurve:
+                    interval_curve=cubit.get_mesh_intervals('curve',k)
+                    if k not in list_curve_or:
+                        command = "curve "+str(k)+" interval "+str(vol[l].intervalv)
+                        cubit.cmd(command)
+                        #cubit_error_stop(iproc,command,ner)
+                        command = "curve "+str(k)+" scheme equal"
+                        cubit.cmd(command)
+                        #cubit_error_stop(iproc,command,ner)
+                    else:
+                        interval_store.append((k,interval_curve))
+                if interval_store[0][1] == interval_store[1][1]:
+                    pass
+                else:
+                    interval_min=min(interval_store[0][1],interval_store[1][1])
+                    #I am sure that the minimum length is in the curve at the bottom so the min interval will be in vol[0] and the check will propagate correctly
+                    command = "curve "+str(interval_store[0][0])+" "+str(interval_store[1][0])+" interval "+str(interval_min)
+                    cubit.cmd(command)
+                    #cubit_error_stop(iproc,command,ner)
+                    command = "curve "+str(interval_store[0][0])+" "+str(interval_store[1][0])+" scheme equal"
+                    cubit.cmd(command)
+                    #cubit_error_stop(iproc,command,ner)
+            command = "volume "+str(id_vol)+" scheme sweep source surface "+source_sweep+" "+source_sweep_add+" source target "+str(target_sweep)+ " rotate off"
+            cubit.cmd(command)
+            #cubit_error_stop(iproc,command,ner)
+            ner=cubit.get_error_count()
+            command = "volume "+str(id_vol)+" sweep smooth Auto"
+            cubit.cmd(command)
+            #cubit_error_stop(iproc,command,ner)
+            #
+        for id_volume in range(nvol-1,-1,-1):
+            command = "mesh vol "+str(vol[id_volume].ID)
+            cubit.cmd(command)
+            #cubit_error_stop(iproc,command,ner)
+        #
+        #smoothing
+        if  cfg.smoothing:
+            cubitcommand= 'surf all smooth scheme laplacian '
+            cubit.cmd(cubitcommand)
+            #cubit_error_stop(iproc,cubitcommand,ner)
+            cubitcommand= 'smooth surf all'
+            cubit.cmd(cubitcommand)
+            #cubit_error_stop(iproc,cubitcommand,ner)
+            #
+            cubitcommand= 'vol all smooth scheme laplacian '
+            cubit.cmd(cubitcommand)
+            #cubit_error_stop(iproc,cubitcommand,ner)
+            cubitcommand= 'smooth vol all'
+            cubit.cmd(cubitcommand)
+            #cubit_error_stop(iproc,cubitcommand,ner)
+        #
+        #for nvol = 3 
+        #
+        #___________________________ interface 4
+        #                 \*********
+        #vol 2              \*******
+        #_____________________\***** interface 3
+        #
+        #vol 1
+        #___________________________ interface 2
+        #
+        #vol 0
+        #___________________________ interface 1
+        #
+        #
+        refinement(nvol,vol)
+        if  cfg.coarsening_top_layer:
+            from sets import set
+            #
+            cubitcommand= 'del mesh vol '+str(vol[-1].ID)+ ' propagate'
+            cubit.cmd(cubitcommand)
+            #cubit_error_stop(iproc,cubitcommand,ner)
+            s1=set(list_curve_vertical)
+            s2=set(cubit.parse_cubit_list("curve","in vol "+str(vol[-1].ID)))
+            lc=list(s1 & s2).replace("["," ").replace("]"," ")
+            cubitcommand= 'curve '+str(list(lc))+' interval '+str(cfg.actual_vertical_interval_top_layer)
+            cubit.cmd(cubitcommand)
+            #cubit_error_stop(iproc,cubitcommand,ner)
+            cubitcommand= 'mesh vol '+str(vol[-1].ID)
+            cubit.cmd(cubitcommand)
+        #    
+        #    
+        if  cfg.refine_basin and id_partitioner_surf not in list_surface_nomesh:
+            refinement_basin(iproc,id_partitioner_surf,list_surface_out,list_surface_transition,top_surface,top_surface_add)
+        #
+        #
+        #    
+        #save_view_file(iproc)
+        #
+        #
+        n=cubit.get_sideset_id_list()
+        if len(n) != 0:
+            command = "del sideset all"
+            cubit.cmd(command)
+        n=cubit.get_block_id_list()
+        if len(n) != 0:    
+            command = "del block all"
+            cubit.cmd(command)
+        #
+        #
+        if cfg.refine_basin and cfg.interpolatehex and id_partitioner_surf in list_surface_transition:
+                interpolate_basin(top_surface,top_surface_add)
+
+        import boundary_definition
+        entities=['face']
+        if id_partitioner_surf in list_surface_transition:
+            text='t'
+        elif id_partitioner_surf in list_surface_out:
+            text='out'
+        elif id_partitioner_surf in list_surface_in:
+            text='in'
+        else:
+            text=None
+        boundary_definition.define_bc(entities,parallel=True,partitioning_type=text)
+
+        #MPI scheme - checking boundaries
+        if mpiflag and cfg.checkbound and len(list_surface_nomesh) != 0:
+           import boundary_check
+           boundary_check.bcheck_basin(surf_vertical,parallel_map)
+
+        #
+        #   
+        if mpiflag and cfg.checkbound:
+            if id_partitioner_surf not in list_surface_nomesh:
+                command = "save as '"+cfg.output_dir+"/mesh_vol_ck_"+str(iproc)+".cub' overwrite"
+                cubit.cmd(command)
+                ##cubit_error_stop(iproc,command,ner)
+                #cubit.cmd('export Genesis  "'+cfg.output_dir+'/mesh_vol_ck_'+str(iproc)+'.g" dimension 3 block all overwrite ')
+                ##cubit_error_stop(iproc,command,ner)
+            else:
+                command = "save as '"+cfg.output_dir+"/NOmesh_vol_ck_"+str(iproc)+".cub' overwrite"
+                cubit.cmd(command)
+                ##cubit_error_stop(iproc,command,ner)
+                #cubit.cmd('export Genesis  "'+cfg.output_dir+'/NOmesh_vol_ck_'+str(iproc)+'.g" dimension 3 block all overwrite ')
+                ##cubit_error_stop(iproc,command,ner)
+        else:
+            print 'no mpi'
+            command = "save as '"+cfg.output_dir+"/mesh_vol_nock"+str(iproc)+".cub' overwrite"
+            cubit.cmd(command)
+            #cubit.cmd('export Genesis  "'+cfg.output_dir+'mesh_vol_nock'+str(iproc)+'.g" dimension 3 block all overwrite ')
+        #
+
+        import quality_log
+        max_skewness,min_length=quality_log.quality_log()
+        count_hex=[cubit.get_hex_count()]
+        count_node=[cubit.get_node_count()]
+        max_skew=[(iproc,max_skewness)]
+        min_l=[(iproc,min_length)]
+
+        print 'waiting.....'
+        mpi.barrier()
+        total_min_l=mpi.gather(min_l)
+        total_hex=mpi.gather(count_hex)        
+        total_node=mpi.gather(count_node)      
+        total_max_skew=mpi.gather(max_skew)    
+        print iproc, ' ok '
+
+        mpi.barrier()                          
+        if iproc == 0:
+            min_total_min_l=min([ms[1] for ms in total_min_l])
+            max_total_max_skew=max([ms[1] for ms in total_max_skew])
+            sum_total_node=sum(total_node)
+            sum_total_hex=sum(total_hex)
+
+            totstat_file=open(cfg.output_dir+'/totstat.log','w')
+            text='hex total number,node total number,max skew, min length\n'
+            totstat_file.write(text)
+            print text
+            text=str(sum_total_hex)+' , '+str(sum_total_node)+' , '+str(max_total_max_skew)+' , '+str(min_total_min_l)+'\n'
+            totstat_file.write(text)
+            print text
+            totstat_file.write(str(total_max_skew))    
+            totstat_file.close()
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/select_in_out.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/select_in_out.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/obsolete/select_in_out.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,154 @@
+#############################################################################
+# select_in_out.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+
+#####OBSOLETE
+# use different scheme... numpy or cubit firetracing
+
+
+def select_in_out(top_surf,curve_outline):
+    import geocubitlib.menu as menu
+    import geocubitlib.initializing as initializing
+    #
+    #
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    store_node=[]
+    command = "create planar surface with plane zplane offset 0"
+    cubit.cmd(command)
+    tmp_surface=cubit.get_last_id("surface")
+    command = "project curve "+str(curve_outline)+" onto surf "+str(tmp_surface)
+    cubit.cmd(command)
+    outline_projected=cubit.get_last_id("curve")
+    command = "group 'list_node' add node in surf "+str(top_surf)
+    cubit.cmd(command)
+    group=cubit.get_id_from_name("list_node")
+    list_node=cubit.get_group_nodes(group)
+    command = "delete group "+ str(group)
+    cubit.cmd(command)
+    #list_quad=cubit.get_surface_quads(top_surf)
+    box=cubit.get_bounding_box("surface",tmp_surface)
+    xmin=box[0]
+    ymin=box[3]
+    zmin=0
+    for id_node in list_node:
+        center_node=cubit.get_center_point("node",id_node)
+        text='create curve location '+str(xmin)+' '+str(ymin)+' '+str(zmin)+' location '+str(center_node[0])+' '+str(center_node[1])+' 0'
+        cubit.cmd(text)
+        last_curve=cubit.get_last_id("curve")
+        command = "project curve "+str(last_curve)+" on surf "+str(tmp_surface)
+        cubit.cmd(command)
+        command = "del curve "+str(last_curve)
+        cubit.cmd(command)
+        last_curve=cubit.get_last_id("curve")
+        length=cubit.get_curve_length(last_curve)
+        arc_vertex=cubit.get_last_id("vertex")
+        command = "create vertex atintersection curve "+str(last_curve)+' '+str(outline_projected)
+        cubit.cmd(command)
+        last_vertex=cubit.get_last_id("vertex")
+        icount=last_vertex-arc_vertex
+        if icount != 0:
+            for iv in range(arc_vertex+1,last_vertex+1):
+                iv_coord=cubit.get_center_point("vertex",iv)
+                distance=sqrt((xmin-iv_coord[0])**2+(ymin-iv_coord[1])**2)
+                if distance > length:
+                    icount=icount-1
+            if icount%2 != 0:
+                store_node.append(id_node)
+        command = "delete curve "+str(last_curve)
+        cubit.cmd(command)
+        command = "del vertex all"
+        cubit.cmd(command)
+    command = "del surface "+str(tmp_surface)
+    cubit.cmd(command)
+    return store_node
+
+def select_in_out_global(list_node,surf):
+    from math import sqrt
+    import geocubitlib.menu as menu
+    import geocubitlib.initializing as initializing
+    #
+    #
+    mpiflag,iproc,numproc,mpi   = initializing.initializing_mpi()
+    cubit                       = initializing.initializing_cubit()
+    cfg                         = initializing.initializing_cfg()
+    #
+    box=cubit.get_bounding_box("surface",surf)
+    xmin=.5*(box[0]+box[1])
+    ymin=.5*(box[3]+box[4])
+    zmin=box[6]
+    l=[]
+    for id_node in list_node:
+        center_node=cubit.get_center_point("node",id_node)
+        text='create curve location '+str(xmin)+' '+str(ymin)+' '+str(zmin)+' location '+str(center_node[0])+' '+str(center_node[1])+' 0'
+        cubit.cmd(text)
+        last_curve=cubit.get_last_id("curve")
+        last_v=cubit.get_last_id("vertex")
+        last_s=cubit.get_last_id("surface")
+        command='imprint volume in surface '+str(surf)+' with curve '+str(last_curve)
+        cubit.cmd(command)
+        last_s_after=cubit.get_last_id("surface")
+        last_v_after=cubit.get_last_id("vertex")
+        diff=last_v_after-last_v
+        if diff % 2 != 0:
+           l.append(id_node)
+        command='delete curve '+str(last_curve)
+        cubit.cmd(command)
+        command='regularize vol in surf '+str(last_s) + ' to '+ str(last_s_after) 
+        cubit.cmd(command)
+    return l
+
+
+
+
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/quality_log.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/quality_log.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/quality_log.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,282 @@
+#############################################################################
+# quality_log.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+
+
+def quality_log(tqfile=None):
+    """
+    creation of the quality parameter file
+    """
+    import start as start
+    #
+    #
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    #
+    #
+    from hex_metric import SEM_metric_3D
+    #
+    lvol=cubit.parse_cubit_list('volume','all')
+    if len(lvol)!=0:
+        cubit.cmd('quality vol all allmetric                                      ')
+    else:
+        cubit.cmd('quality hex in block all allmetric                                      ')
+    cubit.cmd('list model                                                      ')
+    #
+    toclose=True
+    if isinstance(tqfile,file): 
+        totstat_file=tqfile
+    elif isinstance(tqfile,str):
+        totstat_file=open(tqfile+'_cubitquality_skewness_proc_'+str(iproc)+'.log','w')
+    else:
+        import sys
+        totstat_file=sys.stdout
+        toclose=False
+    
+    mesh=SEM_metric_3D()
+    mesh.check_metric()
+    
+    if mesh.max_skewness is not None:
+        mesh.skew_hystogram=mesh.hyst(0,mesh.max_skewness,mesh.skew_hyst)
+        totstat_file.write('-'*70+'\n')
+        
+        
+        
+        
+        
+        totstat_file.write('='*70+'\n')
+        totstat_file.write('SKEWNESS'+'\n')
+        totstat_file.write('='*70+'\n') 
+        if len(mesh.hex_max_skewness) <= 30:
+            totstat_file.write('max = '+str(mesh.max_skewness)+' in hexes '+str(mesh.hex_max_skewness)+'\n')
+            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+ ' maximun ='+str(mesh.max_angle)+')'+'\n')
+        else:
+            totstat_file.write('max = '+str(mesh.max_skewness)+' in '+str(len(mesh.hex_max_skewness))+' hexes '+'\n')
+            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+' maximun ='+str(mesh.max_angle)+')'+'\n')
+        totstat_file.write('-'*70+'\n')
+        totstat_file.write('skew hystogram')
+        totstat_file.write('-'*70+'\n')
+        tot=0
+        for i in mesh.skew_hystogram.values():
+            tot=tot+len(i)
+        #k=mesh.skew_hystogram.keys()
+        #k.sort()
+        factor=mesh.max_skewness/mesh.nbin
+        for i in range(0,mesh.nbin+1):
+            if mesh.skew_hystogram.has_key(i):
+                if (i+1)*factor <= 1:
+                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : '+str(len(mesh.skew_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.skew_hystogram[i])/float(tot)*100.)+'%)'+'\n')
+            else:
+                if (i+1)*factor <= 1:
+                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
+        totstat_file.write('-'*70+'\n')
+    ###############################################
+    if mesh.min_edge_length is not None:
+        mesh.edgemin_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemin_hyst)
+        mesh.edgemax_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemax_hyst)
+        totstat_file.write('='*70+'\n')
+        totstat_file.write('edge length')
+        totstat_file.write('='*70+'\n')
+        if len(mesh.hex_min_edge_length) <= 30:
+            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in hexes '+str(mesh.hex_min_edge_length)+'\n')
+        else:
+            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in '+str(len(mesh.hex_min_edge_length))+ ' hexes.'+'\n')
+        if len(mesh.hex_max_edge_length) <= 30:
+            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+ ' in hexes '+str(mesh.hex_max_edge_length)+'\n')              
+        else:                                                                                                                        
+            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+' in '+str(len(mesh.hex_max_edge_length))+ ' hexes.'+'\n')    
+        totstat_file.write('-'*70+'\n')
+        totstat_file.write('edge length hystogram')
+        totstat_file.write('-'*70+'\n')
+        factor=(mesh.max_edge_length-mesh.min_edge_length)/mesh.nbin
+        totstat_file.write('minimum edge length'+'\n')
+        tot=0
+        for i in mesh.edgemin_hystogram.values():
+            tot=tot+len(i)
+        #k=mesh.edgemin_hystogram.keys()
+        #k.sort()
+        for i in range(0,mesh.nbin+1):
+            if mesh.edgemin_hystogram.has_key(i):
+                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemin_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemin_hystogram[i])/float(tot)*100.)+'%)'+'\n')
+            else:
+                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
+        totstat_file.write('-'*70+'\n')
+        totstat_file.write('maximum edge length')
+        tot=0
+        for i in mesh.edgemax_hystogram.values():
+            tot=tot+len(i)
+        #k=mesh.edgemax_hystogram.keys()
+        #k.sort()
+        for i in range(0,mesh.nbin+1):
+            if mesh.edgemax_hystogram.has_key(i):
+                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemax_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemax_hystogram[i])/float(tot)*100.)+'%)'+'\n')
+            else:
+                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
+    try:
+        if mesh.dt is not None:
+            totstat_file.write('='*70+'\n')
+            totstat_file.write('STABILITY')
+            totstat_file.write('='*70+'\n')
+            totstat_file.write('time step < '+str(mesh.dt)+'s, for velocity = '+str(mesh.velocity)+'\n')
+    except:
+        pass
+    
+    if toclose: 
+        totstat_file.close()
+    
+    print 'max specfem3d skewness: ',mesh.max_skewness
+    print 'min edge length: ',mesh.min_edge_length
+    return mesh.max_skewness,mesh.min_edge_length
+    
+    
+def quality_log(tqfile=None):
+    """
+    creation of the quality parameter file
+    """
+    import start as start
+    #
+    #
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    #
+    #
+    from hex_metric import SEM_metric_3D
+    #
+    lvol=cubit.parse_cubit_list('volume','all')
+    if len(lvol)!=0:
+        cubit.cmd('quality vol all allmetric                                      ')
+    else:
+        cubit.cmd('quality hex in block all allmetric                                      ')
+    cubit.cmd('list model                                                      ')
+    #
+    toclose=True
+    if isinstance(tqfile,file): 
+        totstat_file=tqfile
+    elif isinstance(tqfile,str):
+        totstat_file=open(tqfile+'_cubitquality_skewness_proc_'+str(iproc)+'.log','w')
+    else:
+        import sys
+        totstat_file=sys.stdout
+        toclose=False
+
+    mesh=SEM_metric_3D()
+    mesh.check_metric()
+
+    if mesh.max_skewness is not None:
+        mesh.skew_hystogram=mesh.hyst(0,mesh.max_skewness,mesh.skew_hyst)
+        totstat_file.write('-'*70+'\n')
+
+
+
+
+
+        totstat_file.write('='*70+'\n')
+        totstat_file.write('SKEWNESS'+'\n')
+        totstat_file.write('='*70+'\n') 
+        if len(mesh.hex_max_skewness) <= 30:
+            totstat_file.write('max = '+str(mesh.max_skewness)+' in hexes '+str(mesh.hex_max_skewness)+'\n')
+            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+ ' maximun ='+str(mesh.max_angle)+')'+'\n')
+        else:
+            totstat_file.write('max = '+str(mesh.max_skewness)+' in '+str(len(mesh.hex_max_skewness))+' hexes '+'\n')
+            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+' maximun ='+str(mesh.max_angle)+')'+'\n')
+        totstat_file.write('-'*70+'\n')
+        totstat_file.write('skew hystogram')
+        totstat_file.write('-'*70+'\n')
+        tot=0
+        for i in mesh.skew_hystogram.values():
+            tot=tot+len(i)
+        #k=mesh.skew_hystogram.keys()
+        #k.sort()
+        factor=mesh.max_skewness/mesh.nbin
+        for i in range(0,mesh.nbin+1):
+            if mesh.skew_hystogram.has_key(i):
+                if (i+1)*factor <= 1:
+                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : '+str(len(mesh.skew_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.skew_hystogram[i])/float(tot)*100.)+'%)'+'\n')
+            else:
+                if (i+1)*factor <= 1:
+                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
+        totstat_file.write('-'*70+'\n')
+    ###############################################
+    if mesh.min_edge_length is not None:
+        mesh.edgemin_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemin_hyst)
+        mesh.edgemax_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemax_hyst)
+        totstat_file.write('='*70+'\n')
+        totstat_file.write('edge length')
+        totstat_file.write('='*70+'\n')
+        if len(mesh.hex_min_edge_length) <= 30:
+            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in hexes '+str(mesh.hex_min_edge_length)+'\n')
+        else:
+            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in '+str(len(mesh.hex_min_edge_length))+ ' hexes.'+'\n')
+        if len(mesh.hex_max_edge_length) <= 30:
+            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+ ' in hexes '+str(mesh.hex_max_edge_length)+'\n')              
+        else:                                                                                                                        
+            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+' in '+str(len(mesh.hex_max_edge_length))+ ' hexes.'+'\n')    
+        totstat_file.write('-'*70+'\n')
+        totstat_file.write('edge length hystogram')
+        totstat_file.write('-'*70+'\n')
+        factor=(mesh.max_edge_length-mesh.min_edge_length)/mesh.nbin
+        totstat_file.write('minimum edge length'+'\n')
+        tot=0
+        for i in mesh.edgemin_hystogram.values():
+            tot=tot+len(i)
+        #k=mesh.edgemin_hystogram.keys()
+        #k.sort()
+        for i in range(0,mesh.nbin+1):
+            if mesh.edgemin_hystogram.has_key(i):
+                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemin_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemin_hystogram[i])/float(tot)*100.)+'%)'+'\n')
+            else:
+                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
+        totstat_file.write('-'*70+'\n')
+        totstat_file.write('maximum edge length')
+        tot=0
+        for i in mesh.edgemax_hystogram.values():
+            tot=tot+len(i)
+        #k=mesh.edgemax_hystogram.keys()
+        #k.sort()
+        for i in range(0,mesh.nbin+1):
+            if mesh.edgemax_hystogram.has_key(i):
+                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemax_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemax_hystogram[i])/float(tot)*100.)+'%)'+'\n')
+            else:
+                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
+    try:
+        if mesh.dt is not None:
+            totstat_file.write('='*70+'\n')
+            totstat_file.write('STABILITY')
+            totstat_file.write('='*70+'\n')
+            totstat_file.write('time step < '+str(mesh.dt)+'s, for velocity = '+str(mesh.velocity)+'\n')
+    except:
+        pass
+
+    if toclose: 
+        totstat_file.close()
+
+    print 'max specfem3d skewness: ',mesh.max_skewness
+    print 'min edge length: ',mesh.min_edge_length
+    return mesh.max_skewness,mesh.min_edge_length
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/read_parameter_cfg.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/read_parameter_cfg.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/read_parameter_cfg.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,330 @@
+#############################################################################
+# read_parameter_cfg.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+import os
+
+def readcfg(filename=None,importmenu=False,mpiflag=False):
+    """
+    read the configuration file, filename is defined in the command line arguments (see menu.py)
+    """
+    if importmenu:
+        import menu as menu
+        cfgname=menu.cfg_name
+        id_proc=menu.id_proc
+        create_plane=menu.create_plane
+        menusurface=menu.surface
+        single=menu.single
+    elif filename:
+        cfgname=filename
+        id_proc=0
+        menu=False
+        create_plane=False
+        menusurface=False
+        single=False
+    else:
+        print 'error: no configuration file'
+        import sys
+        sys.exit()
+    #
+    from utilities import geo2utm #here I can use pyproj but I prefere to include a function in pure python in order to avoid an additional installation
+    #
+    #
+    import ConfigParser
+    config = ConfigParser.ConfigParser()
+    #
+    #
+    def converter(s):
+        if s == 'True':
+            value=True
+        elif s == 'False':
+            value=False
+        elif s == 'None':
+            value= None
+        else:
+            if s.count(',') != 0:
+                value=s.split(',')
+                while value.count(''):                
+                    value.remove('')
+            else:
+                value=s
+            try:
+                if type(value).__name__ == 'str':
+                    if str(value).count('.') != 0:
+                        value=float(value)
+                    else:
+                        value=int(value)
+                else:
+                    if str(value).count('.') != 0:
+                        value=map(float,value)
+                    else:
+                        value=map(int,value)
+            except:
+                pass
+        return value
+    #
+    def section_dict(section):
+        dict_o = {}
+        options = config.options(section)
+        for option in options:
+            try:
+                value=converter(config.get(section, option))
+                dict_o[option] = value
+            except:
+                dict_o[option] = None
+        return dict_o
+    
+    class attrdict(dict):
+        def __init__(self, *args, **kwargs):
+            dict.__init__(self, *args, **kwargs)
+            self.__dict__ = self
+        def __str__(self):
+            names=[]
+            values=[]
+            for name,value in self.items():
+                names.append(name)
+                values.append(value)
+            print names,values
+            a=zip(names,values)
+            a.sort()
+            arc=''
+            for o in a:
+                if o[0][0] != arc: print
+                print o[0],' -> ',o[1]
+                arc=o[0][0]
+            return '____'
+    
+    #
+    dcfg={}
+    #
+    #CONSTANTS
+    dcfg['osystem'] = 'linux'
+    dcfg['debug_cfg']=False
+    dcfg['checkbound']=False
+    dcfg['top_partitioner'] = 10000
+    dcfg['tres']=0.3 #if n is the vertical component of the normal at a surface pointing horizontally, when -tres < n < tres then the surface is vertical
+    dcfg['precision'] =0.02 #precision for the boundary check (0.02 m)
+    #
+    #INIT
+    dcfg['debug']=True 
+    dcfg['cubit_info']="on"
+    dcfg['echo_info']="on"
+    dcfg['jou_info']="on"
+    dcfg['jer_info']="on"
+    dcfg['monitored_cpu']=0
+    dcfg['parallel_import']=True
+    dcfg['save_geometry_cubit']=True
+    dcfg['save_surface_cubit']=False
+    dcfg['save_geometry_paraview'] = False #not implemented 
+    dcfg['save_geometry_ACIS'] = False #not implemented
+    dcfg['export_exodus_mesh']=False
+    dcfg['manual_adj']                  =False
+    dcfg['play_adj']                    =False
+    dcfg['no_adj']                      =False
+    dcfg['nx']=False
+    dcfg['ny']=False
+    dcfg['nstep']=False
+    dcfg['localdir_is_globaldir']=True
+    dcfg['refinement_depth']=[]
+    dcfg['scratchdir']=None
+    dcfg['map_meshing_type']='regularmap'
+    dcfg['4sideparallel']=True
+    dcfg["outlinebasin_curve"]=False
+    dcfg["transition_curve"]=False
+    dcfg["faulttrace_curve"]=False
+    dcfg['geological_imprint']=False
+    dcfg['number_processor_xi']=1
+    dcfg['number_processor_eta']=1
+    dcfg['filename']=None
+    dcfg['actual_vertical_interval_top_layer']=1
+    dcfg['coarsening_top_layer']=False
+    
+    
+    
+    
+    dcfg['nsurf'] = None
+    if cfgname:
+        config.read(cfgname)
+        sections=['cubit.options','simulation.cpu_parameters','geometry.surfaces','geometry.volumes','geometry.volumes.layercake','geometry.volumes.flatcake','geometry.volumes.partitioner','geometry.partitioner','meshing']
+        
+        
+        for section in sections:
+            try:
+                d=section_dict(section)
+                dcfg.update(d)
+            except:
+                pass
+                
+        if dcfg['nsurf']:
+           surface_name=[]
+           num_x=[]
+           num_y=[]
+           xstep=[]
+           ystep=[]
+           step=[]
+           directionx=[]
+           directiony=[]
+           unit2=[]
+           surf_type=[]
+           delimiter=[]
+           nsurf=int(dcfg['nsurf'])
+           for i in range(1,nsurf+1):
+               section='surface'+str(i)+'.parameters'
+               d=section_dict(section)
+               surface_name.append(d['name'])
+               surf_type.append(d['surf_type'])
+               unit2.append(d['unit_surf'])
+               if d['surf_type'] == 'regular_grid':
+                   xstep.append(d['step_along_x'])
+                   ystep.append(d['step_along_y'])
+                   num_x.append(d['number_point_along_x'])
+                   num_y.append(d['number_point_along_y'])
+               elif d['surf_type'] == 'skin':
+                   step.append(d['step'])
+                   try:
+                      delimiter.append(d['delimiter'])
+                   except:
+                      pass
+                   directionx.append(d['directionx'])
+                   directiony.append(d['directiony'])
+           dcfg['surface_name']=surface_name
+           dcfg['num_x']=num_x       
+           dcfg['num_y']=num_y       
+           dcfg['xstep']=xstep       
+           dcfg['ystep']=ystep       
+           dcfg['step']=step        
+           dcfg['directionx']=directionx  
+           dcfg['directiony']=directiony  
+           dcfg['unit2']=unit2       
+           dcfg['surf_type']=surf_type   
+           dcfg['delimiter']=delimiter  
+           
+        try:
+            tres=0
+            xmin,ymin=geo2utm(dcfg['longitude_min'],dcfg['latitude_min'],dcfg['unit'])
+            xmax,ymax=geo2utm(dcfg['longitude_max'],dcfg['latitude_max'],dcfg['unit'])
+            dcfg['xmin']=xmin
+            dcfg['ymin']=ymin
+            dcfg['xmax']=xmax
+            dcfg['ymax']=ymax
+            x1,y1=geo2utm(dcfg['longitude_min'],dcfg['latitude_min'],dcfg['unit'])
+            x2,y2=geo2utm(dcfg['longitude_max'],dcfg['latitude_min'],dcfg['unit'])
+            x3,y3=geo2utm(dcfg['longitude_max'],dcfg['latitude_max'],dcfg['unit'])
+            x4,y4=geo2utm(dcfg['longitude_min'],dcfg['latitude_max'],dcfg['unit'])
+            dcfg['x1_box']=x1
+            dcfg['y1_box']=y1
+            dcfg['x2_box']=x2
+            dcfg['y2_box']=y2
+            dcfg['x3_box']=x3
+            dcfg['y3_box']=y3
+            dcfg['x4_box']=x4
+            dcfg['y4_box']=y4
+            dcfg['tres_boundarydetection']=tres
+        except:
+            pass
+            
+    cfg=attrdict(dcfg)
+    
+    if menu:
+        try:
+            if cfg.working_dir[-1] == '/': cfg.working_dir=cfg.working_dir[:-1]
+            if cfg.working_dir[0] != '/': cfg.working_dir='./'+cfg.working_dir
+        except:
+            cfg.working_dir=os.getcwd()
+        
+        try:
+            if cfg.output_dir[-1] == '/': cfg.output_dir=cfg.output_dir[:-1]
+            if cfg.output_dir[0] != '/': cfg.output_dir='./'+cfg.output_dir
+        except:
+            cfg.output_dir=os.getcwd()
+        
+        try:
+            if cfg.SPECFEM3D_output_dir[-1] == '/': cfg.SPECFEM3D_output_dir=cfg.SPECFEM3D_output_dir[:-1]
+            if cfg.SPECFEM3D_output_dir[0] != '/': cfg.SPECFEM3D_output_dir='./'+cfg.SPECFEM3D_output_dir
+        except:
+            cfg.SPECFEM3D_output_dir=os.getcwd()
+        
+        cfg.single=single
+        
+        if menusurface:
+            cfg.nsurf=1
+            cfg.name=[menu.surface_name]
+            cfg.num_x=[menu.num_x]
+            cfg.num_y=[menu.num_x]
+            cfg.unit=[menu.unit]
+            cfg.surf_type=[menu.surf_type]
+            try:
+                cfg.delimiter=[menu.delimiter]
+            except:
+                cfg.delimiter=[' ']
+            cfg.directionx=[menu.directionx]
+            cfg.directiony=[menu.directiony]
+    else:
+        cfg.SPECFEM3D_output_dir=os.getcwd()
+        
+        
+    if not cfg.number_processor_eta and cfg.nodes:
+        cfg.number_processor_xi,cfg.number_processor_eta=split(cfg.nodes)
+        
+    if isinstance(cfg.filename,str): cfg.filename=[cfg.filename]
+    
+    try:
+        cfg.nproc_eta=cfg.number_processor_eta
+        cfg.nproc_xi=cfg.number_processor_xi
+        cfg.cpuy=cfg.number_processor_eta
+        cfg.cpux=cfg.number_processor_xi
+    except:
+        pass
+    
+    if create_plane:
+        cfg.x1=map(float,menu.x1.split(','))
+        cfg.x2=map(float,menu.x2.split(','))
+        cfg.x3=map(float,menu.x3.split(','))
+        cfg.x4=map(float,menu.x4.split(','))
+        cfg.unit=menu.unit
+    #
+    if menu:
+        cfg.id_proc=menu.id_proc
+    else:
+        cfg.id_proc=id_proc
+    #
+    try:
+        if isinstance(cfg.tripl,int): cfg.tripl=[cfg.tripl]
+    except:
+        pass
+        
+        
+    return cfg
+
+
+class getparameter(dict): 
+    def __init__(self, *args, **kwargs):
+        dict.__init__(self, *args, **kwargs)
+        self.__dict__ = self
+
+
+def split(x):
+    import math
+    c=int(math.sqrt(x))
+    while math.fmod(x,c):
+        c=c+1
+    return c,x/c
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/start.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/start.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/start.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,166 @@
+#############################################################################
+# start.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+#
+#
+#
+#method to call the library
+
+def start_mpi():
+    """ 
+    start mpi, fakempi mimick the mpi function when the run is serial. The object mpi is based upon pyMPI.
+    it returns: mpiflag,iproc,numproc,mpi
+    where 
+        mpiflag is True if parallel mesh is on 
+        iproc is the id of the processor (0 if the run is serial)
+        numproc is the number of the processor (1 if the run is serial)
+        mpi is the mpi object
+    """
+    import sys
+    try:
+        import menu as menu
+        iproc=menu.id_proc
+    except:
+        iproc=0
+    try:
+        import mpi
+        numproc=mpi.size
+        mpiflag=True
+        if numproc == 1:
+            mpiflag=False
+        else:
+            iproc=mpi.rank
+    except:
+        class fakempi(object):
+            def __init__(self):
+                self.size=1
+                self.rank=0
+            def barrier(self):
+                pass
+            def allgather(self,value):
+                return value
+            def gather(self,value):
+                return value
+            def bcast(self,value):
+                return value
+            def scatter(self,value):
+                return value
+            def send(self,value,values):
+                return
+            def recv(self,value):
+                return value,value
+        mpi=fakempi()
+        numproc=1
+        mpiflag=False
+    return mpiflag,iproc,numproc,mpi
+
+def start_cubit(init=False):
+    """ 
+    start cubit, it return the cubit object
+    init argument set the monitotr files
+    """
+    import sys,os
+    try:
+        cubit.silent_cmd('comment')
+    except:
+        try:
+            import cubit
+            cubit.init([""])
+        except:
+            print 'error importing cubit'
+            sys.exit()
+        try:
+            if init:
+                from start import start_cfg,start_mpi
+                cfg=start_cfg()
+                mpiflag,iproc,numproc,mpi   = start_mpi()
+                cubit.cmd('set logging on file "'+cfg.working_dir+'/cubit_proc_'+str(iproc)+'.log"')
+                cubit.cmd("set echo off")
+                cubit.cmd("set info off")
+                if iproc == cfg.monitored_cpu:
+                    cubit.cmd("record '"+cfg.working_dir+"/monitor_"+str(cfg.monitored_cpu)+".jou'")
+                    cubit.cmd("set journal on")
+                    cubit.cmd("journal error on")
+                    d=cfg.__dict__
+                    ks=d.keys()
+                    ks.sort()
+                    for k in ks:
+                        if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
+                            txt=str(k)+' -----> '+str(d[k])
+                            txt=txt.replace("'","").replace('"','')
+                            cubit.cmd('comment "'+txt+'"')
+                else:
+                    cubit.cmd("set journal "+cfg.jou_info)
+                    cubit.cmd("journal error "+cfg.jer_info)
+                    d=cfg.__dict__
+                    ks=d.keys()
+                    ks.sort()
+                    for k in ks:
+                        if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
+                            txt=str(k)+' -----> '+str(d[k])
+                            txt=txt.replace("'","").replace('"','')
+                            cubit.cmd('comment "'+txt+'"')
+                cubit.cmd("set echo "+cfg.echo_info)
+                cubit.cmd("set info "+cfg.cubit_info)
+        except:
+            print 'error start cubit'
+            sys.exit()
+    return cubit
+
+def start_cfg(filename=None,importmenu=True):
+    """
+    return the object cfg with the parameters of the mesh
+    """
+    import read_parameter_cfg
+    mpiflag,iproc,numproc,mpi=start_mpi()
+    if filename: importmenu=False 
+    cfg=read_parameter_cfg.readcfg(filename=filename,importmenu=importmenu,mpiflag=mpiflag)
+    import os
+    try:
+        os.makedirs(cfg.working_dir)
+    except OSError:
+        pass
+    try:
+        os.makedirs(cfg.output_dir)
+    except OSError:
+        pass
+    try:
+         os.makedirs(cfg.SPECFEM3D_output_dir)
+    except OSError:
+         pass
+    
+    return cfg
+
+def start_numpy():
+    """
+    import numpy and check if it is installed
+    """
+    import sys
+    try:
+        import numpy
+    except:
+        print 'error importing numpy, please check if numpy is correctly installed'
+        sys.exit()
+    return numpy
+
+    
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/surfaces.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/surfaces.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/surfaces.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,308 @@
+#############################################################################
+# surfaces.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+
+def surfaces(filename=None):
+    """creating the surfaces defined in the parameter files
+       #
+       nsurf = number of surfaces
+       surf_type = list of stype of method for the creation of the surface
+                   -- regulare_grid (u and v lines)
+                   -- skin (u lines)       
+    """
+    #
+    import start as start
+    cfg                     = start.start_cfg(filename=filename)
+    #
+    #
+    for isurface in range(0,cfg.nsurf):
+        surf_type=cfg.surf_type[isurface]
+        if surf_type == 'regular_grid':
+            surface_regular_grid(isurface,cfgname=filename)
+        elif surf_type == 'skin':
+            surface_skin(isurface,cfgname=filename)
+
+def surface_regular_grid(isurface=0,cfgname=None):
+    """
+    create an acis surface from a regular lon/lat/z grid
+    """
+    import sys,os
+    from math import sqrt
+    from utilities import geo2utm
+    import start as start
+    #
+    #
+    cfg                     = start.start_cfg(cfgname)
+    numpy                   = start.start_numpy()
+    #
+    def create_line_u(ind,n,step,data,unit):
+        last_curve_store=cubit.get_last_id("curve")
+        command='create curve spline '
+        for i in range(0,n):
+            if i%step == 0:
+                lon,lat,z=data[i+ind][0],data[i+ind][1],data[i+ind][2]
+                x,y=geo2utm(lon,lat,unit)
+                txt=' Position ' +   str(x)  +' '+  str(y) +' '+  str(z)
+                command=command+txt
+                #print command
+        cubit.silent_cmd(command)
+        last_curve=cubit.get_last_id("curve")
+        if last_curve != last_curve_store:
+            return last_curve
+        else:
+            return 0
+    
+    def create_line_v(ind,n,n2,step,data,unit):
+        last_curve_store=cubit.get_last_id("curve")
+        command='create curve spline '
+        for i in range(0,n):
+            if i%step == 0:
+                lon,lat,z=data[n2*i+ind][0],data[n2*i+ind][1],data[n2*i+ind][2]
+                x,y=geo2utm(lon,lat,unit)
+                txt=' Position ' +   str(x)  +' '+  str(y) +' '+  str(z)
+                command=command+txt
+                #print command
+        cubit.silent_cmd(command)
+        last_curve=cubit.get_last_id("curve")
+        if last_curve != last_curve_store:
+            return last_curve
+        else:
+            return 0
+    #
+    #
+    cubit.cmd("reset")
+    #
+    position=True
+    #
+    #
+    nu= cfg.num_x[isurface]
+    nv= cfg.num_y[isurface]
+    ustep= cfg.xstep[isurface]
+    vstep= cfg.ystep[isurface]
+    exag=1.
+    unit=cfg.unit2[isurface]
+    #
+    #
+    data=numpy.loadtxt(cfg.surface_name[isurface])
+    if len(data) > 100:
+        command = "set echo off"
+        cubit.cmd(command)
+        command = "set journal off"
+        cubit.cmd(command)
+    #
+    u_curve=[]
+    v_curve=[]
+    #
+    for iv in range(0,nv):
+        if iv%vstep == 0.:
+            u=create_line_u(iv*(nu),nu,ustep,data,unit)
+            u_curve.append(u)
+    for iu in range(0,nu):
+        if iu%ustep == 0.:
+            v=create_line_v(iu,nv,nu,ustep,data,unit)
+            v_curve.append(v)
+    #
+    umax=max(u_curve)
+    umin=min(u_curve)
+    vmax=max(v_curve)
+    vmin=min(v_curve)
+    cubitcommand= 'create surface net u curve '+ str( umin )+' to '+str( umax )+ ' v curve '+ str( vmin )+ ' to '+str( vmax )+' heal'
+    cubit.cmd(cubitcommand)
+    command = "del curve all"
+    cubit.cmd(command)
+    suff=cfg.surface_name[isurface].split('/')
+    command = "save as '"+cfg.working_dir+"/surf_"+suff[-1]+".cub' overwrite"
+    cubit.cmd(command)
+    #
+    #
+    #        
+    cubit.cmd("set info "+cfg.cubit_info)
+    cubit.cmd("set echo "+cfg.echo_info)
+    cubit.cmd("set journal "+cfg.jou_info)
+
+def surface_skin(isurface=0,cfgname=None):
+    """
+    create an acis surface interpolating no-intersecting lines
+    """
+    import sys,os
+    from math import sqrt
+    from utilities import geo2utm
+    import start as start
+    #
+    #
+    cubit                   = start.start_cubit()
+    cfg                     = start.start_cfg(cfgname)
+    #
+    def define_next_line(directionx,directiony,n,data):
+        ndata=len(data)
+        command=''
+        ind=n
+        try:
+            record=data[ind]
+        except:
+            return False,False
+        try:
+            x,y,z=map(float,record.split())
+        except:
+            return False,False
+        txt=' Position ' +   record
+        command=command+txt
+        x_store,y_store,z_store = x,y,z
+        icount=1
+        while True:
+                    ind+=1
+                    if ind >= ndata: return ind,command
+                    record=data[ind]
+                    try:
+                        x,y,z=map(float,record.split())
+                    except:
+                        return ind,command
+                    dx,dy = x-x_store,y-y_store        
+                    if  directionx == 0 and dy/abs(dy) * directiony >= 0:
+                        txt=' Position ' +   record
+                        command=command+txt
+                        icount+=1
+                        x_store,y_store,z_store = x,y,z
+                    elif  directiony == 0 and dx/abs(dx) == directionx :
+                        txt=' Position ' +   record
+                        command=command+txt
+                        icount+=1
+                        x_store,y_store,z_store = x,y,z
+                    else:
+                        if icount==1:
+                           x,y,z=x_store+1e-4*directionx,y_store+1e-4*directiony,z_store
+                           txt=' Position ' +str(x)+ ' '+str(y)+ ' '+str(z)
+                           command=command+txt
+                        return ind,command    
+    def create_line(position):
+        if position:
+            last_curve_store=cubit.get_last_id("curve")
+            command='create curve spline '+position
+            cubit.silent_cmd(command)
+            last_curve=cubit.get_last_id("curve")
+            if last_curve != last_curve_store:
+                return last_curve
+            else:
+                return False
+        else:
+            return False
+                        
+    command = "reset"
+    cubit.cmd(command)
+    #
+    position=True
+    #
+    try:
+         grdfile = open(cfg.surface_name[isurface], 'r')
+    except:
+         raise NameError, 'No such file or directory: '+  str( cfg.surface_name[isurface] )
+    #
+    directionx=cfg.directionx[isurface]
+    directiony=cfg.directiony[isurface]
+    step=cfg.step[isurface]
+    position=True
+    curveskin=[]
+    count_line=0
+    data=grdfile.read().split('\n')
+    ndata=len(data)
+    n=0
+    #
+    #
+    command = "set echo off"
+    cubit.cmd(command)
+    command = "set journal off"
+    cubit.cmd(command)
+    command = "set info off"
+    cubit.cmd(command)         
+    #
+    while position:
+          index,position=define_next_line(directionx,directiony,n,data)
+          if n%step == 0:
+              curve=create_line(position)
+              if curve: curveskin.append(curve)
+          elif n%step != 0 and not position:
+              curve=create_line(position)
+              if curve: curveskin.append(curve)
+          n=index
+    umax=max(curveskin)
+    umin=min(curveskin)
+    print 'create surface skin curve '+ str( umin )+' to '+str( umax )
+    cubitcommand= 'create surface skin curve '+ str( umin )+' to '+str( umax )
+    cubit.cmd(cubitcommand)
+    command = "del curve all"
+    cubit.cmd(command)
+    last_surface=cubit.get_last_id("surface")
+    command = "regularize surf "+str(last_surface)
+    cubit.cmd(command)
+    #
+    suff=cfg.surface_name[isurface].split('/')
+    command = "save as '"+cfg.working_dir+"/surf_"+suff[-1]+".cub' overwrite"
+    cubit.cmd(command)
+    #
+    #
+    #        
+    cubit.cmd("set info "+cfg.cubit_info)
+    cubit.cmd("set echo "+cfg.echo_info)
+    cubit.cmd("set journal "+cfg.jou_info)
+    
+    
+def plane(cfg):
+    import sys,os
+    from math import sqrt
+    from utilities import geo2utm
+    import start as start
+    #
+    #
+    cubit                   = start.start_cubit()
+    #
+    #
+    command = "reset"
+    cubit.cmd(command)
+    #
+    #
+    for p in [cfg.x1,cfg.x2,cfg.x3,cfg.x4]:
+        x_current,y_current=geo2utm(p[0],p[1],cfg.unit)
+        cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( p[2] )
+        cubit.cmd(cubitcommand)
+    #
+    cubitcommand= 'create surface vertex 1 2 3 4'
+    cubit.cmd(cubitcommand)
+    command = "del vertex all"
+    cubit.cmd(command)
+    command = "save as 'plane.cub' overwrite"
+    cubit.cmd(command)
+    #
+    #
+    #        
+    cubit.cmd("set info "+cfg.cubit_info)
+    cubit.cmd("set echo "+cfg.echo_info)
+    cubit.cmd("set journal "+cfg.jou_info)
\ No newline at end of file

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/utilities.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/utilities.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/utilities.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,427 @@
+#############################################################################
+# utilities.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+
+
+
+
+def snapshot(name=None,i=0,viewnumber=1):
+    """
+    it takes a snapshot of the figure, following the predefined view position.
+    view 1: vector 1 1 1 z up
+    """
+    if name is None:
+        name='snapshot_'+str(i)
+    i=i+1
+    if viewnumber == 1:
+        command = "at 0"
+        cubit.cmd(command)
+        command = "from 1 1 1"
+        cubit.cmd(command)
+        command = "up 0 0 1"
+        cubit.cmd(command)
+    cubit.cmd('graphics autocenter on')
+    cubit.cmd("zoom reset")
+    command = "hardcopy '"+name+".png' png"
+    cubit.cmd(command)
+    return i
+
+def cubit_error_stop(iproc,command,ner):
+    er=cubit.get_error_count()
+    if er > ner: 
+       text='"Proc: '+str(iproc)+' ERROR '+str(command)+' number of error '+str(er)+'/'+str(ner)+'"'
+       cubitcommand = 'comment '+text
+       cubit.cmd(cubitcommand)
+       raise NameError, text
+
+def cubit_error_continue(iproc,command,n_er):
+    er=cubit.get_error_count()
+    if  er >= n_er: 
+        text='"Proc: '+str(iproc)+' ERROR continue '+str(command)+' number of error '+str(er)+' '+str(n_er)+'"'
+        cubit.cmd('comment '+ text)
+        print 'error: ',text
+    return er
+    
+def savemesh(mpiflag,iproc=0,filename=None):
+    import start as start
+    cfg                         = start.start_cfg(filename=filename)
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    
+    def runsave(meshfile,iproc,filename=None):
+        import start as start
+        cubit                   = start.start_cubit()
+        cfg                         = start.start_cfg(filename=filename)
+        flag=0
+        ner=cubit.get_error_count()
+        cubitcommand= 'save as "'+ cfg.output_dir+'/'+meshfile+'.cub'+ '" overwrite' 
+        cubit.cmd(cubitcommand)
+        ner2=cubit.get_error_count()
+        if ner == ner2:
+            cubitcommand= 'export mesh "'+ cfg.output_dir+'/'+meshfile+'.e'+ '" dimension 3 block all overwrite' 
+            cubit.cmd(cubitcommand)
+            ner2=cubit.get_error_count()                                                    
+        if ner == ner2:
+            flag=1
+        return flag
+    
+    
+    meshfile='mesh_vol_'+str(iproc)
+    
+    flagsaved=0
+    infosave=(iproc,flagsaved)
+    
+    mpi.barrier()
+    total_saved=mpi.allgather(flagsaved)
+    if isinstance(total_saved,int): total_saved=[total_saved]
+    
+    ind=0
+    saving=True
+    while saving:
+        if len(total_saved) != sum(total_saved):
+            #
+            if not flagsaved: 
+                flagsaved=runsave(meshfile,iproc,filename=filename)
+                if flagsaved:
+                    infosave=(iproc,flagsaved)        
+                    if numproc > 1:
+                        f=open('mesh_saved'+str(iproc),'w')
+                        f.close()
+            mpi.barrier()
+            total_saved=mpi.allgather(flagsaved)
+            if isinstance(total_saved,int): total_saved=[total_saved]
+            ind=ind+1
+        else:
+            saving=False
+        if ind > len(total_saved)+10: saving=False
+        print sum(total_saved),'/',len(total_saved),' saved'
+    
+    info_total_saved=mpi.allgather(infosave)
+    if isinstance(info_total_saved,int): info_total_saved=[info_total_saved]
+    
+    if iproc==0:
+        f=open('mesh_saving.log','w')
+        f.write('\n'.join(str(x) for x in info_total_saved))                
+        f.close()                           
+            
+    f=open(cfg.output_dir+'/'+'blocks_'+str(iproc).zfill(5),'w')
+    blocks=cubit.get_block_id_list()
+    
+    for block in blocks:
+        name=cubit.get_exodus_entity_name('block',block)
+        element_count = cubit.get_exodus_element_count(block, "block")
+        nattrib=cubit.get_block_attribute_count(block)
+        attr=[cubit.get_block_attribute_value(block,x) for x in range(0,nattrib)]
+        ty=cubit.get_block_element_type(block)
+        f.write(str(block)+' ; '+name+' ; nattr '+str(nattrib)+' ; '+' '.join(str(x) for x in attr)+' ; '+ty+' '+str(element_count)+'\n')
+    f.close()
+    
+    import quality_log
+    f=open(cfg.output_dir+'/'+'quality_'+str(iproc).zfill(5),'w')
+    max_skewness,min_length=quality_log.quality_log(f)
+    f.close()
+    
+    
+    count_hex=[cubit.get_hex_count()]
+    count_node=[cubit.get_node_count()]
+    max_skew=[(iproc,max_skewness)]
+    min_l=[(iproc,min_length)]
+    
+    mpi.barrier()
+    total_min_l=mpi.gather(min_l)
+    total_hex=mpi.gather(count_hex)        
+    total_node=mpi.gather(count_node)      
+    total_max_skew=mpi.gather(max_skew)    
+    
+    
+    mpi.barrier()                          
+    if iproc == 0:
+        min_total_min_l=min([ms[1] for ms in total_min_l])
+        max_total_max_skew=max([ms[1] for ms in total_max_skew])
+        sum_total_node=sum(total_node)
+        sum_total_hex=sum(total_hex)
+        
+        totstat_file=open(cfg.output_dir+'/totstat.log','w')
+        text='hex total number,node total number,max skew, min length\n'
+        totstat_file.write(text)
+        
+        text=str(sum_total_hex)+' , '+str(sum_total_node)+' , '+str(max_total_max_skew)+' , '+str(min_total_min_l)+'\n'
+        totstat_file.write(text)
+        
+        totstat_file.write(str(total_max_skew))    
+        totstat_file.close()
+    
+    print 'meshing process end... proc ',iproc 
+
+def importgeometry(geometryfile,iproc=0,filename=None):
+    import start as start
+    cfg                         = start.start_cfg(filename=filename)
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    
+    if iproc == 0: print 'importing geometry....'
+    a=['ok from '+str(iproc)]
+    
+    mpi.barrier()
+    total_a=mpi.allgather(a)
+    if iproc == 0: print total_a
+    
+    def runimport(geometryfile,iproc,filename=None):
+        import start as start
+        cubit                   = start.start_cubit()
+        cfg                         = start.start_cfg(filename=filename)
+        file1=cfg.output_dir+'/'+geometryfile
+        cubitcommand= 'open "'+ file1+ '"  ' 
+        cubit.cmd(cubitcommand)                
+        
+    if cfg.parallel_import:
+        runimport(geometryfile,iproc,filename=filename)
+    else:
+        if iproc == 0:
+            runimport(geometryfile,iproc,filename=filename)
+            for i in range(1,mpi.size):
+                mpi.send('import',i)
+                msg,status=mpi.recv(i)
+        else:
+            msg,status=mpi.recv(0)
+            runimport(geometryfile,iproc,filename=filename)
+            mpi.send('ok'+str(iproc),0)
+
+        
+def savesurf(iproc=0):
+    savegeometry(iproc=iproc,surf=True)
+    
+###################################################################################### BELOW OK
+    
+def load_curves(acis_filename):
+    """
+    load the curves from acis files
+    """
+    import os
+    #
+    #
+    print acis_filename
+    if acis_filename and os.path.exists(acis_filename):
+        tmp_curve=cubit.get_last_id("curve")
+        command = "import acis '"+acis_filename+"'"
+        cubit.cmd(command)
+        tmp_curve_after=cubit.get_last_id("curve")
+        curves=' '.join(str(x) for x in range(tmp_curve+1,tmp_curve_after+1))
+    elif not os.path.exists(acis_filename):
+        print str(acis_filename)+' not found'
+        curves=None
+    return [curves]
+
+def project_curves(curves,top_surface):
+    """
+    project curves on surface
+    """
+    if not isinstance(curves,list): curves=curves.split()
+    tmpc=[]
+    for curve in curves:
+        command = "project curve "+str(curve)+" onto surface "+str(top_surface)
+        cubit.cmd(command)
+        tmp_curve_after=cubit.get_last_id("curve")
+        tmpc.append(tmp_curve_after)
+        command = "del curve "+str(curve)
+        cubit.cmd(command)
+    return tmpc
+    
+def geo2utm(lon,lat,unit,ellipsoid=23):
+    """conversion geocoodinates from geographical to utm
+    
+    usage: x,y=geo2utm(lon,lat,unit,ellipsoid=23)
+    
+    dafault ellipsoid is 23 = WGS-84, 
+        ellipsoid:
+        1, "Airy"
+        2, "Australian National"
+        3, "Bessel 1841"
+        4, "Bessel 1841 (Nambia] "
+        5, "Clarke 1866"
+        6, "Clarke 1880"
+        7, "Everest"
+        8, "Fischer 1960 (Mercury] "
+        9, "Fischer 1968"
+        10, "GRS 1967"
+        11, "GRS 1980"
+        12, "Helmert 1906"
+        13, "Hough"
+        14, "International"
+        15, "Krassovsky"
+        16, "Modified Airy"
+        17, "Modified Everest"
+        18, "Modified Fischer 1960"
+        19, "South American 1969"
+        20, "WGS 60"
+        21, "WGS 66"
+        22, "WGS-72"
+        23, "WGS-84"
+        
+    unit:  'geo' if the coordinates of the model (lon,lat) are geographical
+           'utm' if the coordinates of the model (lon,lat) are utm
+           
+    x,y: the function return the easting, northing utm coordinates 
+    """
+    import LatLongUTMconversion
+    if unit == 'geo' :          
+       (zone, x, y) = LatLongUTMconversion.LLtoUTM(ellipsoid, lat, lon)
+    elif unit == 'utm' : 
+       x=lon
+       y=lat
+    return x,y
+
+
+def savegeometry(iproc=0,surf=False,filename=None):
+    import start as start
+    cfg                         = start.start_cfg(filename=filename)
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    
+    def runsave(geometryfile,iproc,filename=None):
+        import start as start
+        cubit                   = start.start_cubit()
+        cfg                         = start.start_cfg(filename=filename)
+        flag=0
+        ner=cubit.get_error_count()
+        cubitcommand= 'save as "'+ cfg.output_dir+'/'+geometryfile+ '"  overwrite' 
+        cubit.cmd(cubitcommand)                                                    
+        ner2=cubit.get_error_count()                                             
+        if ner == ner2:
+            flag=1
+        return flag
+        
+    if surf:
+        geometryfile='surf_vol_'+str(iproc)+'.cub'
+    else:
+        geometryfile='geometry_vol_'+str(iproc)+'.cub'
+        
+    flagsaved=0
+    infosave=(iproc,flagsaved)
+    
+    mpi.barrier()
+    total_saved=mpi.allgather(flagsaved)
+    if isinstance(total_saved,int): total_saved=[total_saved]
+    
+    ind=0
+    saving=True
+    while saving:
+        if len(total_saved) != sum(total_saved):
+            #
+            if not flagsaved: 
+                flagsaved=runsave(geometryfile,iproc,filename=filename)
+                if flagsaved:
+                    infosave=(iproc,flagsaved)        
+                    if numproc > 1:
+                        f=open('geometry_saved'+str(iproc),'w')
+                        f.close()
+            mpi.barrier()
+            total_saved=mpi.allgather(flagsaved)
+            if isinstance(total_saved,int): total_saved=[total_saved]
+            ind=ind+1
+        else:
+            saving=False
+        if ind > len(total_saved)+10: saving=False
+        print sum(total_saved),'/',len(total_saved),' saved'
+    
+    info_total_saved=mpi.allgather(infosave)
+    if isinstance(info_total_saved,int): info_total_saved=[info_total_saved]
+    
+    if iproc==0:
+        f=open('geometry_saving.log','w')
+        f.write('\n'.join(str(x) for x in info_total_saved))                
+        f.close()
+
+
+def get_v_h_list(vol_id_list):
+    """return the lists of the cubit ID of vertical/horizontal surface and vertical/horizontal curves
+    where v/h is defined by the distance of the z normal component from the axis direction
+    the parameter cfg.tres is the threshold as for example if 
+    normal[2] >= -tres and normal[2] <= tres 
+    then the surface is vertical
+    #
+    usage: surf_or,surf_vertical,list_curve_or,list_curve_vertical,bottom,top = get_v_h_list(list_vol)
+    """
+    #
+    tres=0.3
+    
+    try:
+        nvol=len(vol_id_list)
+    except:
+        nvol=1
+        vol_id_list=[vol_id_list]
+    surf_vertical=[]
+    surf_or=[]
+    list_curve_vertical=[]
+    list_curve_or=[]
+    #
+    #
+    for id_vol in vol_id_list:
+        lsurf=cubit.get_relatives("volume",id_vol,"surface")
+        for k in lsurf:
+            normal=cubit.get_surface_normal(k)
+            center_point = cubit.get_center_point("surface", k)
+            if normal[2] >= -1*tres and normal[2] <= tres:
+               surf_vertical.append(k)
+               lcurve=cubit.get_relatives("surface",k,"curve")
+               list_curve_vertical=list_curve_vertical+list(lcurve)                                                                                                          
+            else:
+                surf_or.append(k)
+                lcurve=cubit.get_relatives("surface",k,"curve")
+                list_curve_or=list_curve_or+list(lcurve)
+    for x in list_curve_or:
+        try:
+            list_curve_vertical.remove(x)
+        except:
+            pass
+    k=surf_or[0]
+    center_point = cubit.get_center_point("surface", k)[2]
+    center_point_top=center_point
+    center_point_bottom=center_point
+    top=k
+    bottom=k 
+    for k in surf_or[1:]:
+        center_point = cubit.get_center_point("surface", k)[2]
+        if center_point > center_point_top:
+            center_point_top=center_point
+            top=k
+        elif center_point < center_point_bottom:
+            center_point_bottom=center_point
+            bottom=k
+    surftop=list(cubit.get_adjacent_surfaces("surface", top))
+    for s in surf_vertical:
+        try:                          
+            surftop.remove(s)    
+        except:                       
+            pass                      
+    top=surftop
+    bottom=[bottom]
+    return surf_or,surf_vertical,list_curve_or,list_curve_vertical,bottom,top
+
+

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/volumes.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/volumes.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/geocubitlib/volumes.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,551 @@
+#############################################################################
+# volumes.py                                                    
+# this file is part of GEOCUBIT                                             #
+#                                                                           #
+# Created by Emanuele Casarotti                                             #
+# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
+#                                                                           #
+#############################################################################
+#                                                                           #
+# GEOCUBIT 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.                                       #
+#                                                                           #
+# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
+#                                                                           #
+#############################################################################
+try:
+    import start as start
+    cubit                   = start.start_cubit()
+except:
+    try:
+        import cubit
+    except:
+        print 'error importing cubit, check if cubit is installed'
+        pass
+
+    
+def volumes(filename=None):
+    """create the volumes"""
+    import start as start
+    print'volume'
+    cfg                     = start.start_cfg(filename=filename)
+    #
+    if cfg.volume_type == 'layercake_volume_ascii_regulargrid_regularmap':
+            layercake_volume_ascii_regulargrid_mpiregularmap(filename=filename)
+    elif cfg.volume_type == 'layercake_volume_fromacis_mpiregularmap':
+            layercake_volume_fromacis_mpiregularmap(filename=filename)
+
+def layercake_volume_ascii_regulargrid_mpiregularmap(filename=None):
+    import sys
+    import start as start
+    #
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    #
+    numpy                       = start.start_numpy()
+    cfg                         = start.start_cfg(filename=filename)                       
+    
+    from utilities import geo2utm, savegeometry,savesurf
+    
+    from math import sqrt
+    #
+    try:
+        mpi.barrier()
+    except:
+        pass
+    #
+    #
+    command = "comment '"+"PROC: "+str(iproc)+"/"+str(numproc)+" '"
+    cubit.cmd(command)
+    #fer=open('ERROR_VOLUME_'+str(iproc),'w')
+    
+    #
+    if mpiflag:
+        x_slice=numpy.zeros([numproc],int)
+        y_slice=numpy.zeros([numproc],int)
+        for icpuy in range(0,cfg.nproc_eta): 
+            for icpux in range (0,cfg.nproc_xi):
+                iprocnum=icpuy*cfg.nproc_xi+icpux
+                #print iprocnum,cfg.nproc_xi,icpux,icpuy,cfg.nproc_xi,cfg.nproc_eta
+                x_slice[iprocnum]=icpux
+                y_slice[iprocnum]=icpuy
+        icpux=x_slice[iproc]
+        icpuy=y_slice[iproc]
+    else:
+        icpuy=int(cfg.id_proc/cfg.nproc_xi)
+        icpux=cfg.id_proc%cfg.nproc_xi
+    
+    #
+    if  cfg.geometry_format == 'ascii':
+        #for the original surfaces
+        #number of points in the files that describe the topography
+        import local_volume
+        if cfg.localdir_is_globaldir:
+            if iproc == 0 or not mpiflag:
+                coordx_0,coordy_0,elev_0,nx_0,ny_0=local_volume.read_grid(filename)
+                print 'end of reading grd files '+str(nx_0*ny_0)+ ' points'
+            else:
+                pass
+            if iproc == 0 or not mpiflag:
+                coordx=mpi.bcast(coordx_0)
+            else:
+                coordx=mpi.bcast()
+            if iproc == 0 or not mpiflag:
+                coordy=mpi.bcast(coordy_0)
+            else:
+                coordy=mpi.bcast()
+            if iproc == 0 or not mpiflag:
+                elev=mpi.bcast(elev_0)
+            else:
+                elev=mpi.bcast()
+            if iproc == 0 or not mpiflag:
+                nx=mpi.bcast(nx_0)
+            else:
+                nx=mpi.bcast()       
+            if iproc == 0 or not mpiflag:
+                ny=mpi.bcast(ny_0)
+            else:
+                ny=mpi.bcast()
+        else:
+            coordx,coordy,elev,nx,ny=local_volume.read_grid(filename)
+        print str(iproc)+ ' end of receving grd files '
+        nx_segment=int(nx/cfg.nproc_xi)+1
+        ny_segment=int(ny/cfg.nproc_eta)+1
+        
+    elif cfg.geometry_format=='regmesh': # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+        
+        if cfg.depth_bottom != cfg.zdepth[0]:
+            if iproc == 0: print 'the bottom of the block is at different depth than depth[0] in the configuration file'
+        nx= cfg.nproc_xi+1
+        ny= cfg.nproc_eta+1
+        nx_segment=2
+        ny_segment=2
+        #if iproc == 0: print nx,ny,cfg.cpux,cfg.cpuy
+        xp=(cfg.xmax-cfg.xmin)/float((nx-1))
+        yp=(cfg.ymax-cfg.ymin)/float((ny-1))
+        #
+        elev=numpy.zeros([nx,ny,cfg.nz],float)
+        coordx=numpy.zeros([nx,ny],float)
+        coordy=numpy.zeros([nx,ny],float)
+        #
+        #
+        xlength=(cfg.xmax-cfg.xmin)/float(cfg.nproc_xi) #length of x slide for chunk
+        ylength=(cfg.ymax-cfg.ymin)/float(cfg.nproc_eta) #length of y slide for chunk
+        nelem_chunk_x=1    
+        nelem_chunk_y=1
+        ivxtot=nelem_chunk_x+1
+        ivytot=nelem_chunk_y+1 
+        xstep=xlength #distance between vertex on x
+        ystep=ylength
+        for i in range(0,cfg.nz):
+            elev[:,:,i] = cfg.zdepth[i]
+        
+        icoord=0
+        for iy in range(0,ny):
+            for ix in range(0,nx):
+                icoord=icoord+1
+                coordx[ix,iy]=cfg.xmin+xlength*(ix)
+                coordy[ix,iy]=cfg.ymin+ylength*(iy)
+        
+        #print coordx,coordy,nx,ny
+    #
+    print 'end of building grid '+str(iproc)
+    print 'number of point: ', len(coordx)
+    #
+    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    #for each processor
+    #
+    nxmin_cpu=(nx_segment-1)*(icpux)
+    nymin_cpu=(ny_segment-1)*(icpuy)
+    nxmax_cpu=min(nx-1,(nx_segment-1)*(icpux+1))
+    nymax_cpu=min(ny-1,(ny_segment-1)*(icpuy+1))
+    #if iproc == 0:
+    #    print nx_segment,ny_segment,nx,ny
+    #    print icpux,icpuy,nxmin_cpu,nxmax_cpu
+    #    print icpux,icpuy,nymin_cpu,nymax_cpu
+    #    print coordx[0,0],coordx[nx-1,ny-1]
+    #    print coordy[0,0],coordy[nx-1,ny-1]
+    #
+    #
+    icurve=0
+    isurf=0
+    ivertex=0
+    #
+    #create vertex
+    for inz in range(0,cfg.nz):
+        if  cfg.bottomflat and inz == 0: #bottom layer
+                #
+                if cfg.geometry_format == 'ascii':
+                    lv=cubit.get_last_id("vertex")     
+                    
+                    x_current,y_current=(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu])
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)
+                    #
+                    x_current,y_current=(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu])
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)                                                                              
+                    #
+                    x_current,y_current=(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu])
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)
+                    #
+                    x_current,y_current=(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu])
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)
+                    #
+                    lv2=cubit.get_last_id("vertex")     
+                    
+                    cubitcommand= 'create surface vertex '+str(lv+1)+' to '+str(lv2)
+                    cubit.cmd(cubitcommand)
+                    #
+                    isurf = isurf + 1
+                else:
+                    lv=cubit.get_last_id("vertex") 
+                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],'utm')
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)
+                    #
+                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],'utm')
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)                                                                              
+                    #
+                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],'utm')
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)
+                    #
+                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
+                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
+                    cubit.cmd(cubitcommand)
+                    #
+                    lv2=cubit.get_last_id("vertex") 
+                    cubitcommand= 'create surface vertex '+str(lv+1)+' to '+str(lv2)
+                    cubit.cmd(cubitcommand)
+                    #
+                    isurf = isurf + 1
+        else:
+            if cfg.geometry_format == 'regmesh':
+                zvertex=cfg.zdepth[inz]
+                lv=cubit.get_last_id("vertex")                        
+                x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],'utm')
+                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
+                cubit.cmd(cubitcommand)
+                #
+                x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],'utm')
+                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
+                cubit.cmd(cubitcommand)                                                                              
+                #
+                x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],'utm')
+                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
+                cubit.cmd(cubitcommand)
+                #
+                x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
+                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
+                cubit.cmd(cubitcommand)
+                #
+                cubitcommand= 'create surface vertex '+str(lv+1)+' '+str(lv+2)+' '+str(lv+3)+' '+str(lv+4)
+                cubit.cmd(cubitcommand)
+                #
+                isurf = isurf + 1
+            elif cfg.geometry_format == 'ascii':
+                
+                vertex=[]
+                
+                for iy in range(nymin_cpu,nymax_cpu+1):
+                    ivx=0
+                    for ix in range(nxmin_cpu,nxmax_cpu+1):
+                        zvertex=elev[ix,iy,inz]
+                        x_current,y_current=(coordx[ix,iy],coordy[ix,iy])
+                        #
+                        vertex.append(' Position '+ str( x_current ) +' '+ str( y_current )+' '+ str( zvertex ) )
+                #
+                print 'proc',iproc, 'vertex list created....',len(vertex)
+                n=max(nx,ny)
+                uline=[]
+                vline=[]
+                iv=0
+                
+                cubit.cmd("set info off")
+                cubit.cmd("set echo off")
+                cubit.cmd("set journal off")
+                
+                for iy in range(0,nymax_cpu-nymin_cpu+1):
+                    positionx=''
+                    for ix in range(0,nxmax_cpu-nxmin_cpu+1):
+                        positionx=positionx+vertex[iv]
+                        iv=iv+1
+                    command='create curve spline '+positionx
+                    cubit.cmd(command)
+                    #print command
+                    uline.append( cubit.get_last_id("curve") )
+                for ix in range(0,nxmax_cpu-nxmin_cpu+1):
+                    positiony=''
+                    for iy in range(0,nymax_cpu-nymin_cpu+1):
+                        positiony=positiony+vertex[ix+iy*(nxmax_cpu-nxmin_cpu+1)]
+                    command='create curve spline '+positiony
+                    cubit.cmd(command)
+                    #print command
+                    vline.append( cubit.get_last_id("curve") )
+                #
+                cubit.cmd("set info "+cfg.cubit_info)
+                cubit.cmd("set echo "+cfg.echo_info)
+                cubit.cmd("set journal "+cfg.jou_info)
+                #
+                #
+                print 'proc',iproc, 'lines created....',len(uline),'*',len(vline)
+                umax=max(uline)
+                umin=min(uline)
+                vmax=max(vline)
+                vmin=min(vline)
+                ner=cubit.get_error_count()
+                cubitcommand= 'create surface net u curve '+ str( umin )+' to '+str( umax )+ ' v curve '+ str( vmin )+ ' to '+str( vmax )+' heal'
+                cubit.cmd(cubitcommand)
+                ner2=cubit.get_error_count()
+                if ner == ner2: 
+                    command = "del curve all"
+                    cubit.cmd(command)
+                    isurf=isurf+1
+                #
+            else:
+                raise NameError, 'error, check geometry_format, it should be ascii or regmesh'   #
+                #
+        cubitcommand= 'del vertex all'
+        cubit.cmd(cubitcommand)
+    if cfg.save_surface_cubit:
+        savegeometry(iproc=iproc,surf=True,filename=filename)
+    #
+    #
+    #!create volume
+    if  cfg.osystem == 'macosx':
+        pass
+    elif cfg.osystem == 'linux':
+        for inz in range(1,cfg.nz):
+            ner=cubit.get_error_count()
+            cubitcommand= 'create volume loft surface '+ str( inz+1 )+' '+str( inz )
+            cubit.cmd(cubitcommand)
+            ner2=cubit.get_error_count()
+            isurf=isurf+6
+    if ner == ner2:
+        cubitcommand= 'del surface 1 to '+ str( cfg.nz )
+        cubit.cmd(cubitcommand)
+        list_vol=cubit.parse_cubit_list("volume","all")
+        if len(list_vol) > 1:     
+            cubitcommand= 'imprint volume all'
+            cubit.cmd(cubitcommand)
+            cubitcommand= 'merge all'
+            cubit.cmd(cubitcommand)
+        ner=cubit.get_error_count()
+        #cubitcommand= 'composite create curve in vol all'
+        #cubit.cmd(cubitcommand)
+    savegeometry(iproc,filename=filename)
+    if cfg.geological_imprint:
+        curvesname=[cfg.outlinebasin_curve,cfg.transition_curve,cfg.faulttrace_curve]
+        outdir=cfg.working_dir
+        imprint_topography_with_geological_outline(curvesname,outdir)
+    #
+    #        
+    cubit.cmd("set info "+cfg.cubit_info)
+    cubit.cmd("set echo "+cfg.echo_info)
+    cubit.cmd("set journal "+cfg.jou_info)
+    
+    
+def layercake_volume_fromacis_mpiregularmap(filename=None):
+    import sys
+    import start as start
+    #
+    mpiflag,iproc,numproc,mpi   = start.start_mpi()
+    #
+    numpy                       = start.start_numpy()
+    cfg                         = start.start_cfg(filename=filename)                       
+    #
+    from utilities import geo2utm, savegeometry
+    #
+    from math import sqrt
+    #
+    try:
+        mpi.barrier()
+    except:
+        pass
+    #
+    #
+    command = "comment '"+"PROC: "+str(iproc)+"/"+str(numproc)+" '"
+    cubit.cmd(command)
+    #
+    #get the limit of the volume considering the cpu
+    def xwebcut(x):
+        command='create planar surface with plane xplane offset '+str(x)
+        cubit.cmd(command)
+        last_surface=cubit.get_last_id("surface")
+        command="webcut volume all tool volume in surf "+str(last_surface)
+        cubit.cmd(command)
+        command="del surf "+str(last_surface)
+        cubit.cmd(command)
+        
+    def ywebcut(x):
+        command='create planar surface with plane yplane offset '+str(x)
+        cubit.cmd(command)
+        last_surface=cubit.get_last_id("surface")
+        command="webcut volume all tool volume in surf "+str(last_surface)
+        cubit.cmd(command)
+        command="del surf "+str(last_surface)
+        cubit.cmd(command)
+        
+    def translate2zero():
+        ss=cubit.parse_cubit_list('surface','all')
+        box = cubit.get_total_bounding_box("surface", ss)
+        xmin=box[0]
+        ymin=box[3]
+        cubit.cmd('move surface all x '+str(-1*xmin)+' y '+str(-1*ymin))
+        return xmin,ymin
+        
+    def translate2original(xmin,ymin):
+        cubit.cmd('move surface all x '+str(xmin)+' y '+str(ymin))
+        
+    if mpiflag:
+        x_slice=numpy.zeros([numproc],int)
+        y_slice=numpy.zeros([numproc],int)
+        for icpuy in range(0,cfg.nproc_eta): 
+            for icpux in range (0,cfg.nproc_xi):
+                iprocnum=icpuy*cfg.nproc_xi+icpux
+                #print iprocnum,cfg.nproc_xi,icpux,icpuy,cfg.nproc_xi,cfg.nproc_eta
+                x_slice[iprocnum]=icpux
+                y_slice[iprocnum]=icpuy
+        icpux=x_slice[iproc]
+        icpuy=y_slice[iproc]
+    else:
+        icpuy=int(cfg.id_proc/cfg.nproc_xi)
+        icpux=cfg.id_proc%cfg.nproc_xi
+    #
+    ner=cubit.get_error_count()
+    #
+    icurve=0
+    isurf=0
+    ivertex=0
+    #
+    xlength=(cfg.xmax-cfg.xmin)/float(cfg.cpux) #length of x slide for chunk
+    ylength=(cfg.ymax-cfg.ymin)/float(cfg.cpuy) #length of y slide for chunk
+    xmin_cpu=cfg.xmin+(xlength*(icpux))
+    ymin_cpu=cfg.ymin+(ylength*(icpuy))
+    xmax_cpu=xmin_cpu+xlength
+    ymax_cpu=ymin_cpu+ylength
+    #
+    #importing the surfaces
+    for inz in range(cfg.nz-2,-2,-1):
+        if cfg.bottomflat and inz==-1:
+            command = "create planar surface with plane zplane offset "+str(cfg.depth_bottom)
+            cubit.cmd(command)
+        else:
+            command = "import cubit '"+cfg.filename[inz]+"'"
+            cubit.cmd(command)
+            
+            
+    #translate
+    xmin,ymin=translate2zero()
+    print 'translate ...', -xmin,-ymin
+    xmin_cpu=xmin_cpu-xmin
+    ymin_cpu=ymin_cpu-ymin
+    xmax_cpu=xmax_cpu-xmin
+    ymax_cpu=ymax_cpu-ymin
+    
+    ss=cubit.parse_cubit_list('surface','all')
+    box = cubit.get_total_bounding_box("surface", ss)
+    print 'dimension... ', box
+    #cutting the surfaces
+    xwebcut(xmin_cpu)
+    xwebcut(xmax_cpu)
+    ywebcut(ymin_cpu)
+    ywebcut(ymax_cpu)
+    #
+    list_surface_all=cubit.parse_cubit_list("surface","all")
+    #condisidering only the surfaces inside the boundaries
+    dict_surf={}
+    for isurf in list_surface_all:
+        p=cubit.get_center_point("surface",isurf)
+        if p[0] < xmin_cpu or p[0] > xmax_cpu or p[1] > ymax_cpu or p[1] < ymin_cpu:
+            command = "del surf "+str(isurf)
+            cubit.cmd(command)
+        else:
+            dict_surf[str(isurf)]=p[2]
+    z=dict_surf.values()
+    z.sort()
+    list_surf=[]
+    for val in z:
+        isurf=[k for k, v in dict_surf.iteritems() if v == val][0]
+        list_surf.append(int(isurf))
+    #
+    
+    #lofting the volume
+    for i,j in zip(list_surf,list_surf[1:]):
+        ner=cubit.get_error_count()
+        cubitcommand= 'create volume loft surface '+ str(i)+' '+str(j)
+        cubit.cmd(cubitcommand)
+        ner2=cubit.get_error_count()
+    #
+    translate2original(xmin,ymin)
+    
+    
+    if ner == ner2:
+        cubitcommand= 'del surface all'
+        cubit.cmd(cubitcommand)
+        #
+        #
+        #cubitcommand= 'composite create curve in vol all'
+        #cubit.cmd(cubitcommand)
+        list_vol=cubit.parse_cubit_list("volume","all")
+        if len(list_vol) > 1:     
+            cubitcommand= 'imprint volume all'
+            cubit.cmd(cubitcommand)
+            #cubit_error_stop(iproc,cubitcommand,ner)
+            #
+            cubitcommand= 'merge all'
+            cubit.cmd(cubitcommand)
+    #
+    savegeometry(iproc,filename=filename)
+    if cfg.geological_imprint:
+        curvesname=[cfg.outlinebasin_curve,cfg.transition_curve,cfg.faulttrace_curve]
+        outdir=cfg.working_dir
+        imprint_topography_with_geological_outline(curvesname,outdir)
+
+
+
+def imprint_topography_with_geological_outline(curvesname,outdir='.'):
+    import sys,os
+    from sets import Set
+    #
+    from utilities import load_curves,project_curves,get_v_h_list
+    
+    list_vol=cubit.parse_cubit_list("volume","all")
+    surf_or,surf_vertical,list_curve_or,list_curve_vertical,bottom,top=get_v_h_list(list_vol)
+    
+    
+    
+    outlinebasin_curve=load_curves(curvesname[0])
+    transition_curve=load_curves(curvesname[1])
+    faulttrace_curve=load_curves(curvesname[2])
+    
+    curves=[]
+    if outlinebasin_curve: curves=curves+outlinebasin_curve
+    if transition_curve: curves=curves+transition_curve
+    if faulttrace_curve: curves=curves+faulttrace_curve
+    
+    if curves:
+            command='imprint tolerant surface '+str(top)+' with curve '+' '.join(str(x) for x in curves)+'  merge'
+            cubit.cmd(command)
+             
+    
+    command = "merge surf all"
+    cubit.cmd(command)
+    command = "compress vol all"
+    cubit.cmd(command)
+    command = "compress surf all"
+    cubit.cmd(command)
+    command = "save as '"+outdirs+"/"+"imprinted_vol_"+str(iproc)+".cub' overwrite"
+    cubit.cmd(command)    
+

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/hex_metric.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/hex_metric.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/hex_metric.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,772 +0,0 @@
-#############################################################################
-# hex_metric.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-##mesh=SEM_metric_3D
-##mesh.check_metric()
-##print mesh
-#
-#
-import math
-
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-
-class SEM_metric_3D(object):
-    def __init__(self,list_hex=None,volume=None):
-        super(SEM_metric_3D, self).__init__()
-        self.list_hex=list_hex
-        self.volume=volume
-        self.skew_hystogram=None
-        self.max_skewness=None
-        self.max_angle=None
-        self.min_angle=None
-        self.min_edge_length=None
-        self.cubit_skew=0
-        self.max_valence=None
-        self.node_with_max_valence=None
-        self.valence_threshold=7
-        self.resolution=.05
-        self.resolution_edge_length=.1
-        self.nbin=10
-        self.spatial_unit=1
-        self.gll=0.17267316464601141
-        self.dt=None
-    def __repr__(self):
-        if self.max_skewness is not None:
-            self.skew_hystogram=self.hyst(0,self.max_skewness,self.skew_hyst)
-            print '-'*70
-            print 'SKEWNESS'
-            print 
-            if len(self.hex_max_skewness) <= 30:
-                print 'max = ',self.max_skewness,' in hexes ',self.hex_max_skewness
-                print '(angle -> minimun =', self.min_angle, ' maximun =', self.max_angle,')'
-            else:
-                print 'max = ',self.max_skewness,' in ', len(self.hex_max_skewness), ' hexes '
-                print '(angle -> minimun =', self.min_angle, ' maximun =', self.max_angle,')'
-            print 
-            print 'skew hystogram'
-            print 
-            tot=0
-            for i in self.skew_hystogram.values():
-                tot=tot+len(i)
-            #k=self.skew_hystogram.keys()
-            #k.sort()
-            factor=self.max_skewness/self.nbin
-            for i in range(0,self.nbin+1):
-                if self.skew_hystogram.has_key(i):
-                    if (i+1)*factor <= 1:
-                        print i,' [',i*factor,'->',(i+1)*factor,'[ : ',len(self.skew_hystogram[i]),'/',tot,' hexes (',len(self.skew_hystogram[i])/float(tot)*100.,'%)'
-                else:
-                    if (i+1)*factor <= 1:
-                        print i,' [',i*factor,'->',(i+1)*factor,'[ : ',0,'/',tot,' hexes (0%)'
-            print
-        ###############################################
-        if self.min_edge_length is not None:
-            self.edgemin_hystogram=self.hyst(self.min_edge_length,self.max_edge_length,self.edgemin_hyst)
-            self.edgemax_hystogram=self.hyst(self.min_edge_length,self.max_edge_length,self.edgemax_hyst)
-            print '-'*70
-            print 'edge length'
-            print 
-            if len(self.hex_min_edge_length) <= 30:
-                print 'minimum edge length: ', self.min_edge_length, ' in hexes ',  self.hex_min_edge_length
-            else:
-                print 'minimum edge length: ', self.min_edge_length, ' in ',  len(self.hex_min_edge_length), ' hexes.'
-            if len(self.hex_max_edge_length) <= 30:
-                print 'maximum edge length: ', self.max_edge_length, ' in hexes ',  self.hex_max_edge_length              
-            else:                                                                                                                        
-                print 'maximum edge length: ', self.max_edge_length, ' in ',  len(self.hex_max_edge_length), ' hexes.'    
-            print
-            print 'edge length hystogram'
-            print 
-            factor=(self.max_edge_length-self.min_edge_length)/self.nbin
-            print 'minimum edge length'
-            tot=0
-            for i in self.edgemin_hystogram.values():
-                tot=tot+len(i)
-            #k=self.edgemin_hystogram.keys()
-            #k.sort()
-            for i in range(0,self.nbin+1):
-                if self.edgemin_hystogram.has_key(i):
-                    print i,' [',i*factor+self.min_edge_length,'->',(i+1)*factor+self.min_edge_length,'[ : ',len(self.edgemin_hystogram[i]),'/',tot,' hexes (',len(self.edgemin_hystogram[i])/float(tot)*100.,'%)'
-                else:
-                    print i,' [',i*factor+self.min_edge_length,'->',(i+1)*factor+self.min_edge_length,'[ : ',0,'/',tot,' hexes (0%)'
-            print 
-            print 'maximum edge length'
-            tot=0
-            for i in self.edgemax_hystogram.values():
-                tot=tot+len(i)
-            #k=self.edgemax_hystogram.keys()
-            #k.sort()
-            for i in range(0,self.nbin+1):
-                if self.edgemax_hystogram.has_key(i):
-                    print i,' [',i*factor+self.min_edge_length,'->',(i+1)*factor+self.min_edge_length,'[ : ',len(self.edgemax_hystogram[i]),'/',tot,' hexes (',len(self.edgemax_hystogram[i])/float(tot)*100.,'%)'
-                else:
-                    print i,' [',i*factor+self.min_edge_length,'->',(i+1)*factor+self.min_edge_length,'[ : ',0,'/',tot,' hexes (0%)'
-        if self.dt is not None:
-            print '-'*70
-            print
-            print 'STABILITY'
-            print
-            print 'time step < ',self.dt,'s, for velocity = ',self.velocity
-            print 
-        try:
-            return str(len(self.list_hex))+' hexes checked'
-        except:
-            return 'please performe a metric check: ex ... object.check_metric()'
-    #
-    #
-    def invert_dict(self,d):
-         inv = {}
-         for k,v in d.iteritems():
-             keys = inv.setdefault(v, [])
-             keys.append(k)
-         return inv
-    def hex_metric(self,h):
-        nodes=cubit.get_connectivity('Hex',h)
-        equiangle_skewness=None
-        min_angle=float('infinity')
-        edge_length_min=float('infinity')
-        max_angle=None
-        edge_length_max=None
-        #loopnode=[(i,j) for i in range(8) for j in range(i+1,8)]
-        if len(nodes) == 4:
-            faces=[[0,1,2,3]]
-        elif len(nodes) == 8:
-            faces=[[0,1,2,3],[4,5,6,7],[1,5,6,2],[0,4,7,3],[2,6,7,3],[1,5,4,0]]
-        else:
-            print 'bad definition of nodes'
-            return None,None,None
-        x=[]
-        y=[]
-        z=[]
-        for i in nodes:
-            n=cubit.get_nodal_coordinates(i)
-            x.append(n[0])
-            y.append(n[1])
-            z.append(n[2])
-        for face in faces:
-            for i in range(-1,3):
-                vx1=x[face[i-1]]-x[face[i]]
-                vy1=y[face[i-1]]-y[face[i]]
-                vz1=z[face[i-1]]-z[face[i]]
-                #
-                vx2=x[face[i+1]]-x[face[i]]
-                vy2=y[face[i+1]]-y[face[i]]
-                vz2=z[face[i+1]]-z[face[i]]
-                #
-                norm1=math.sqrt(vx1*vx1+vy1*vy1+vz1*vz1)
-                norm2=math.sqrt(vx2*vx2+vy2*vy2+vz2*vz2)
-                #
-                if norm1 == 0 or norm2 == 0:
-                    print 'degenerated mesh, 0 length edge'
-                    import sys
-                    sys.exit()
-                angle=math.acos((vx1*vx2+vy1*vy2+vz1*vz2)/(norm1*norm2))
-                #
-                equiangle_skewness=max(equiangle_skewness,math.fabs(2.*angle-math.pi)/math.pi)
-                min_angle=min(min_angle,angle*180./math.pi)
-                max_angle=max(max_angle,angle*180./math.pi)
-                edge_length_min=min(edge_length_min,norm1)
-                edge_length_max=max(edge_length_max,norm1)
-        return round(equiangle_skewness,5),min_angle,max_angle,round(edge_length_min,5),round(edge_length_max,5)
-    def show(self,minvalue,maxvalue,dic):
-        hexlist=[]
-        for k in dic.keys():
-            if minvalue <= dic[k] <= maxvalue: hexlist.extend([k])
-        #command = "draw hex "+str(hexlist)
-        #command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
-        #cubit.cmd(command)
-        return hexlist
-    def hyst(self,minvalue,maxvalue,dic):
-        if maxvalue != minvalue:
-            factor=(maxvalue-minvalue)/self.nbin
-        else:
-            factor=1
-        dic_new={}
-        for k in dic.keys():
-            dic_new[k]=int((dic[k]-minvalue)/factor)
-        inv_dic=self.invert_dict(dic_new)
-        return inv_dic                                                                                          
-    #
-    #
-    #
-    #
-    #
-    ############################################################################################
-    def pick_hex(self,list_hex=None,volume=None):
-        if self.cubit_skew > 0:
-            command = "del group skew_top"
-            cubit.cmd(command)
-            command = "group 'skew_top' add quality volume all skew low "+str(self.cubit_skew)
-            cubit.silent_cmd(command)
-            group=cubit.get_id_from_name("skew_top")
-            self.list_hex=cubit.get_group_hexes(group)
-        elif list_hex is not None:
-            self.list_hex=list_hex
-        elif volume is not None:
-            command = "group 'hextmp' add hex in volume "+str(volume)    
-            cubit.silent_cmd(command)                                           
-            group=cubit.get_id_from_name("hextmp")                       
-            self.list_hex=cubit.get_group_hexes(group)
-            command = "del group hextmp"
-            cubit.silent_cmd(command)   
-        elif self.volume is not None:
-            command = "group 'hextmp' add hex in volume "+str(self.volume) 
-            cubit.silent_cmd(command)                                        
-            group=cubit.get_id_from_name("hextmp")                    
-            self.list_hex=cubit.get_group_hexes(group)
-            command = "del group hextmp"
-            cubit.silent_cmd(command)                 
-        elif list_hex is None and self.list_hex is None:
-            self.list_hex=cubit.parse_cubit_list('hex','all')
-        print 'list_hex: ',len(self.list_hex),' hexes'
-    #
-    #
-    ############################################################################################
-    #SKEWNESS
-    def check_skew(self,list_hex=None,volume=None):
-        self.pick_hex(list_hex=list_hex,volume=volume)
-        global_max_skew=None
-        global_max_angle=None
-        global_min_angle=float('infinity')
-        tmp=int(1./self.resolution)+1
-        skew_hyst={}
-        for i in range(0,tmp):
-            if i*self.resolution < 1:
-                skew_hyst[i]=[]
-        h_global_max_skew=[]
-        h_global_max_angle=[]
-        h_global_min_angle=[]
-        for h in self.list_hex:
-            equiangle_skewness,min_angle,max_angle,tmp,tmp2=self.hex_metric(h)
-            skew_hyst[h]=equiangle_skewness
-            #
-            if equiangle_skewness > global_max_skew: 
-                global_max_skew=equiangle_skewness
-                h_global_max_shew=[]
-                h_global_max_shew.append(h)
-                global_min_angle=min_angle
-                global_max_angle=max_angle
-            elif equiangle_skewness == global_max_skew:
-                h_global_max_shew.append(h)
-            s=h_global_max_shew
-        self.skew_hyst=skew_hyst
-        self.max_skewness=global_max_skew
-        self.max_angle=global_max_angle
-        self.min_angle=global_min_angle
-        self.hex_max_skewness=s
-    def show_skew(self,low=None,high=None):
-        if low is None and high is not None:
-            hexlist=self.show(low,self.max_skewness,self.skew_hyst)
-        elif low is not None and high is None:
-            hexlist=self.show(0,high,self.skew_hyst)
-        if low is not None and high is not None:
-            hexlist=self.show(low,high,self.skew_hyst)
-        else:
-            hexlist=self.hex_min_edge_length
-        command = "draw hex "+str(hexlist)
-        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
-        cubit.silent_cmd(command)
-    def list_skew(self,low=None,high=None):
-        if low is None and high is not None:
-            hexlist=self.show(low,self.max_skewness,self.skew_hyst)
-        elif low is not None and high is None:
-            hexlist=self.show(0,high,self.skew_hyst)
-        if low is not None and high is not None:
-            hexlist=self.show(low,high,self.skew_hyst)
-        else:
-            hexlist=self.hex_min_edge_length
-        return hexlist
-    def highlight_skew(self,low=None,high=None):
-        if low is None and high is not None:
-            hexlist=self.show(low,self.max_skewness,self.skew_hyst)
-        elif low is not None and high is None:
-            hexlist=self.show(0,high,self.skew_hyst)
-        if low is not None and high is not None:
-            hexlist=self.show(low,high,self.skew_hyst)
-        else:
-            hexlist=self.hex_min_edge_length
-        command = "highlight hex "+str(hexlist)
-        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
-        cubit.silent_cmd(command)
-    #
-    #
-    #
-    #############################################################################################
-    #HEX VALENCE
-    def check_valence(self):
-        #usage: hex_valence()
-        #
-        list_hex=cubit.parse_cubit_list('hex','all')
-        list_node=cubit.parse_cubit_list('node','all')
-        lookup=dict(zip(list_node,[0]*len(list_node)))
-        for h in list_hex:
-            n=cubit.get_connectivity('Hex',h)
-            for i in n:
-                if lookup.has_key(i): lookup[i]=lookup[i]+1
-        inv_lookup=self.invert_dict(lookup)
-        #
-        vmax=max(inv_lookup.keys())
-        nmax=inv_lookup[max(inv_lookup.keys())]
-        print 'max hex valence ',vmax,' at node ',nmax
-        print '_____'
-        for v in inv_lookup.keys():
-            print ('valence %2i - %9i hexes '% (v,len(inv_lookup[v])))
-        self.valence_summary=inv_lookup
-        self.max_valence=vmax
-        self.node_with_max_valence=nmax
-    #
-    #
-    ###########################################################################################
-    #EDGE LENGTH
-    def check_edge_length(self,list_hex=None,volume=None):
-        self.pick_hex(list_hex=list_hex,volume=volume)
-        global_min_edge_length=float('infinity')
-        h_global_min_edge_length=[]
-        global_max_edge_length=None
-        h_global_max_edge_length=[]
-        edgemin_hyst={}
-        edgemax_hyst={}     
-        for h in self.list_hex:
-            tmp,tmp2,tmp3,edge_length_min,edge_length_max=self.hex_metric(h)
-            edgemax_hyst[h]=edge_length_max
-            edgemin_hyst[h]=edge_length_min
-            if edge_length_min < global_min_edge_length:
-                global_min_edge_length=edge_length_min
-                h_global_min_edge_length=[]
-                h_global_min_edge_length.append(h)
-            elif edge_length_min == global_min_edge_length:
-                h_global_min_edge_length.append(h)
-            if edge_length_max > global_max_edge_length:
-                global_max_edge_length=edge_length_max
-                h_global_max_edge_length=[]
-                h_global_max_edge_length.append(h)      
-            elif edge_length_max == global_max_edge_length:    
-                h_global_max_edge_length.append(h)
-        self.min_edge_length=global_min_edge_length
-        self.hex_min_edge_length=h_global_min_edge_length
-        self.max_edge_length=global_max_edge_length
-        self.hex_max_edge_length=h_global_max_edge_length
-        self.edgemin_hyst=edgemin_hyst
-        self.edgemax_hyst=edgemax_hyst        
-    def show_edgemin(self,low=None,high=None):
-        if low is None and high is not None:
-            hexlist=self.show(low,self.max_edge_length,self.edgemin_hyst)
-        elif low is not None and high is None:
-            hexlist=self.show(self.min_edge_length,high,self.edgemin_hyst)
-        if low is not None and high is not None:
-            hexlist=self.show(low,high,self.edgemin_hyst)
-        else:
-            hexlist=self.hex_min_edge_length
-        command = "draw hex "+str(hexlist)
-        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
-        cubit.cmd(command)
-    def show_edgemax(self,low=None,high=None):
-        if low is None and high is not None:
-            hexlist=self.show(low,self.max_edge_length,self.edgemax_hyst)
-        elif low is not None and high is None:
-            hexlist=self.show(self.min_edge_length,high,self.edgemax_hyst)
-        if low is not None and high is not None:
-            hexlist=self.show(low,high,self.edgemax_hyst)
-        else:
-            hexlist=self.hex_max_edge_length
-        command = "draw hex "+str(hexlist)
-        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
-        cubit.cmd(command)
-    def list_edgemax(self,low=None,high=None):
-        if low is None and high is not None:
-            hexlist=self.show(low,self.max_edge_length,self.edgemax_hyst)
-        elif low is not None and high is None:
-            hexlist=self.show(self.min_edge_length,high,self.edgemax_hyst)
-        if low is not None and high is not None:
-            hexlist=self.show(low,high,self.edgemax_hyst)
-        else:
-            hexlist=self.hex_max_edge_length        
-        return hexlist
-    def list_edgemin(self,low=None,high=None):
-        if low is None and high is not None:
-            hexlist=self.show(low,self.max_edge_length,self.edgemin_hyst)
-        elif low is not None and high is None:
-            hexlist=self.show(self.min_edge_length,high,self.edgemin_hyst)
-        if low is not None and high is not None:
-            hexlist=self.show(low,high,self.edgemin_hyst)
-        else:
-            hexlist=self.hex_min_edge_length
-        return hexlist
-    def highlight_edgemin(self,low=None,high=None):
-        if low is None and high is not None:
-            hexlist=self.show(low,self.max_edge_length,self.edgemin_hyst)
-        elif low is not None and high is None:
-            hexlist=self.show(self.min_edge_length,high,self.edgemin_hyst)
-        if low is not None and high is not None:
-            hexlist=self.show(low,high,self.edgemin_hyst)
-        else:
-            hexlist=self.hex_min_edge_length
-        command = "highlight hex "+str(hexlist)
-        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
-        cubit.cmd(command)
-    def highlight_edgemax(self,low=None,high=None):
-        if low is None and high is not None:
-            hexlist=self.show(low,self.max_edge_length,self.edgemax_hyst)
-        elif low is not None and high is None:
-            hexlist=self.show(self.min_edge_length,high,self.edgemax_hyst)
-        if low is not None and high is not None:
-            hexlist=self.show(low,high,self.edgemax_hyst)
-        else:
-            hexlist=self.hex_max_edge_length
-        command = "highlight hex "+str(hexlist)
-        command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ")
-        cubit.cmd(command)    #
-    #
-    #
-    #
-    #
-    ############################################################################################
-    def check_metric(self,list_hex=None,volume=None):
-        self.pick_hex(list_hex=list_hex,volume=volume)
-        skew_hyst={}
-        edata={}
-        edgemin_hyst={}
-        edgemax_hyst={}
-        edgemaxdata={}
-        edgemindata={}
-        #
-        global_min_edge_length=float('infinity')
-        h_global_min_edge_length=[]
-        global_max_edge_length=None
-        h_global_max_edge_length=[]
-        #
-        global_max_skew=None
-        global_max_angle=None
-        global_min_angle=float('infinity')
-        h_global_max_skew=[]
-        h_global_max_angle=[]
-        h_global_min_angle=[]
-        #
-        s=0.
-        for h in self.list_hex:
-            equiangle_skewness,min_angle,max_angle,edge_length_min,edge_length_max=self.hex_metric(h)
-            skew_hyst[h]=equiangle_skewness
-            edgemax_hyst[h]=edge_length_max
-            edgemin_hyst[h]=edge_length_min
-            if edge_length_min < global_min_edge_length:
-                global_min_edge_length=edge_length_min
-                h_global_min_edge_length=[]
-                h_global_min_edge_length.append(h)
-            elif edge_length_min == global_min_edge_length:
-                h_global_min_edge_length.append(h)
-            if edge_length_max > global_max_edge_length:
-                global_max_edge_length=edge_length_max
-                h_global_max_edge_length=[]
-                h_global_max_edge_length.append(h)     
-            elif edge_length_max == global_max_edge_length:   
-                h_global_max_edge_length.append(h)
-            if equiangle_skewness > global_max_skew: 
-                global_max_skew=equiangle_skewness
-                h_global_max_shew=[]
-                h_global_max_shew.append(h)
-                global_min_angle=min_angle
-                global_max_angle=max_angle
-            elif equiangle_skewness == global_max_skew:
-                h_global_max_shew.append(h)
-            s=h_global_max_shew
-        #
-        self.max_skewness=global_max_skew    
-        self.max_angle=global_max_angle      
-        self.min_angle=global_min_angle      
-        self.hex_max_skewness=s
-        self.skew_hyst=skew_hyst
-        #                
-        self.min_edge_length=global_min_edge_length
-        self.hex_min_edge_length=h_global_min_edge_length
-        self.max_edge_length=global_max_edge_length
-        self.hex_max_edge_length=h_global_max_edge_length
-        self.edgemin_hyst=edgemin_hyst
-        self.edgemax_hyst=edgemax_hyst
-        #
-        
-class SEM_stability_3D(SEM_metric_3D):
-    def __init__(self,list_hex=None,volume=None):
-        super(SEM_metric_3D, self).__init__()
-        self.list_hex=list_hex
-        self.volume=volume
-        self.Ngll_per_wavelength=5
-        self.gllcoeff=.17
-        self.maxgllcoeff=0.5-.17
-        self.Cmax=.3
-        self.nbin=10
-        self.period_hyst=None
-        self.dt=None
-        self.cubit_skew =0
-        #
-        #
-        #
-    def __repr__(self):
-        print 'check mesh stability'
-        #
-    def check_simulation_parameter(self,list_hex=None,volume=None,tomofile=None,vp_static=None,vs_static=None):
-        self.pick_hex(list_hex=list_hex,volume=volume)
-        timestep_hyst={}
-        stability_hyst={}
-        global_min_timestep=float(1)
-        global_max_periodresolved=None
-        if tomofile: 
-            self.read_tomo(tomofile)
-        #
-        #
-        for ind,h in enumerate(self.list_hex):
-            if ind%10000==0: print 'hex checked: '+str(int(float(ind)/len(self.list_hex)*100))+'%'
-            dt_tmp,pmax_tmp,_,_=self.hex_simulation_parameter(h,vp_static=vp_static,vs_static=vs_static)
-            timestep_hyst[h]=dt_tmp
-            stability_hyst[h]=pmax_tmp
-            if dt_tmp < global_min_timestep:
-                global_min_timestep=dt_tmp
-            if pmax_tmp > global_max_periodresolved:
-                global_max_periodresolved=pmax_tmp   
-        #
-        self.period=global_max_periodresolved    
-        self.dt=global_min_timestep      
-        self.dt_hyst=timestep_hyst
-        self.period_hyst=stability_hyst
-        #                
-    def read_tomo(self,tomofile=None):
-        if tomofile:
-            print 'reading tomography file ',tomofile
-            import numpy
-            #xtomo,ytomo,ztomo,vp,vs,rho=numpy.loadtxt(tomofile,skiprows=4)
-            print 'tomography file loaded'
-            tf=open(tomofile,'r')
-            orig_x, orig_y, orig_z, end_x, end_y, end_z        =map(float,tf.readline().split())
-            spacing_x, spacing_y, spacing_z                    =map(float,tf.readline().split())
-            nx, ny, nz                                         =map(int,tf.readline().split())
-            vp_min, vp_max, vs_min, vs_max, rho_min, rho_max   =map(float,tf.readline().split())
-            #
-            ind=0
-            import sys
-            xtomo,ytomo,ztomo,vp,vs=[],[],[],[],[]
-            while ind<nx*ny*nz:
-                ind=ind+1
-                if ind%100000==0: sys.stdout.write("reading progress: %i/%i   \r" % (ind,(nx*ny*nz)) )
-                x,y,z,v1,v2,_=map(float,tf.readline().split())
-                xtomo.append(x)
-                ytomo.append(y)
-                ztomo.append(z)
-                vp.append(v1)
-                vs.append(v2)
-            tf.close()
-            print 'tomography file loaded'
-            #
-            self.orig_x, self.orig_y, self.orig_z, self.end_x, self.end_y, self.end_z        = orig_x, orig_y, orig_z, end_x, end_y, end_z        
-            self.spacing_x, self.spacing_y, self.spacing_z                    = spacing_x, spacing_y, spacing_z                    
-            self.nx, self.ny, self.nz                                         = nx, ny, nz                                         
-            self.vp_min, self.vp_max, self.vs_min, self.vs_max = vp_min, vp_max, vs_min, vs_max
-            self.xtomo,self.ytomo,self.ztomo,self.vp,self.vs=xtomo,ytomo,ztomo,vp,vs
-        else:
-            print 'no tomofile!!!!'
-            #
-            #
-            #
-    def tomo(self,x,y,z,vp_static=None,vs_static=None):
-        if not vp_static:
-            spac_x = (x - self.orig_x) / self.spacing_x
-            spac_y = (y - self.orig_y) / self.spacing_y
-            spac_z = (z - self.orig_z) / self.spacing_z
-            #
-            ix = int(spac_x)
-            iy = int(spac_y)
-            iz = int(spac_z)
-            #
-            gamma_interp_x = spac_x - float(ix)
-            gamma_interp_y = spac_y - float(iy)
-            #
-            NX=self.nx
-            NY=self.ny
-            NZ=self.nz
-            if(ix < 0):
-                ix = 0
-                gamma_interp_x = 0.
-            if(ix > NX-2):         
-                ix = NX-2          
-                gamma_interp_x = 1.
-            if(iy < 0):            
-                iy = 0             
-                gamma_interp_y = 0.
-            if(iy > NY-2):         
-                iy = NY-2          
-                gamma_interp_y = 1.
-            if(iz < 0):            
-                 iz = 0
-            if(iz > NZ-2):
-                 iz = NZ-2
-            #
-            p0 = ix+iy*NX+iz*(NX*NY)
-            p1 = (ix+1)+iy*NX+iz*(NX*NY)
-            p2 = (ix+1)+(iy+1)*NX+iz*(NX*NY)
-            p3 = ix+(iy+1)*NX+iz*(NX*NY)
-            p4 = ix+iy*NX+(iz+1)*(NX*NY)
-            p5 = (ix+1)+iy*NX+(iz+1)*(NX*NY)
-            p6 = (ix+1)+(iy+1)*NX+(iz+1)*(NX*NY)
-            p7 = ix+(iy+1)*NX+(iz+1)*(NX*NY)
-            #
-            if self.ztomo[p4]==self.ztomo[p0]:
-                gamma_interp_z1 = 1
-            else:
-                gamma_interp_z1 = (z-self.ztomo[p0])/(self.ztomo[p4]-self.ztomo[p0])
-            if(gamma_interp_z1 > 1.): gamma_interp_z1 = 1.
-            if(gamma_interp_z1 < 0.): gamma_interp_z1 = 0.
-            #
-            if self.ztomo[p5]==self.ztomo[p1]:
-                gamma_interp_z2 = 1
-            else:
-                gamma_interp_z2 = (z-self.ztomo[p1])/(self.ztomo[p5]-self.ztomo[p1])
-            if(gamma_interp_z2 > 1.): gamma_interp_z2 = 1.
-            if(gamma_interp_z2 < 0.): gamma_interp_z2 = 0.
-            #
-            if self.ztomo[p6]==self.ztomo[p2]:
-                gamma_interp_z3 = 1
-            else:
-                gamma_interp_z3 = (z-self.ztomo[p2])/(self.ztomo[p6]-self.ztomo[p2])
-            if(gamma_interp_z3 > 1.): gamma_interp_z3 = 1.
-            if(gamma_interp_z3 < 0.): gamma_interp_z3 = 0.
-            #
-            if self.ztomo[p7]==self.ztomo[p3]:
-                gamma_interp_z4 = 1
-            else:
-                gamma_interp_z4 = (z-self.ztomo[p3])/(self.ztomo[p7]-self.ztomo[p3])
-            if(gamma_interp_z4 > 1.): gamma_interp_z4 = 1.
-            if(gamma_interp_z4 < 0.): gamma_interp_z4 = 0.
-            #
-            gamma_interp_z5 = 1. - gamma_interp_z1
-            gamma_interp_z6 = 1. - gamma_interp_z2
-            gamma_interp_z7 = 1. - gamma_interp_z3
-            gamma_interp_z8 = 1. - gamma_interp_z4
-            #
-            vp1 = self.vp[p0]
-            vp2 = self.vp[p1]
-            vp3 = self.vp[p2]
-            vp4 = self.vp[p3]
-            vp5 = self.vp[p4]
-            vp6 = self.vp[p5]
-            vp7 = self.vp[p6]
-            vp8 = self.vp[p7]
-            #       [  ]
-            vs1 = self.vs[p0]
-            vs2 = self.vs[p1]
-            vs3 = self.vs[p2]
-            vs4 = self.vs[p3]
-            vs5 = self.vs[p4]
-            vs6 = self.vs[p5]
-            vs7 = self.vs[p6]
-            vs8 = self.vs[p7]
-            #
-            vp_final = vp1*(1.-gamma_interp_x)*(1.-gamma_interp_y)*(1.-gamma_interp_z1) + \
-               vp2*gamma_interp_x*(1.-gamma_interp_y)*(1.-gamma_interp_z2) + \
-               vp3*gamma_interp_x*gamma_interp_y*(1.-gamma_interp_z3) + \
-               vp4*(1.-gamma_interp_x)*gamma_interp_y*(1.-gamma_interp_z4) + \
-               vp5*(1.-gamma_interp_x)*(1.-gamma_interp_y)*gamma_interp_z1 + \
-               vp6*gamma_interp_x*(1.-gamma_interp_y)*gamma_interp_z2 + \
-               vp7*gamma_interp_x*gamma_interp_y*gamma_interp_z3 + \
-               vp8*(1.-gamma_interp_x)*gamma_interp_y*gamma_interp_z4
-            #
-            vs_final = vs1*(1.-gamma_interp_x)*(1.-gamma_interp_y)*(1.-gamma_interp_z1) + \
-               vs2*gamma_interp_x*(1.-gamma_interp_y)*(1.-gamma_interp_z2) + \
-               vs3*gamma_interp_x*gamma_interp_y*(1.-gamma_interp_z3) + \
-               vs4*(1.-gamma_interp_x)*gamma_interp_y*(1.-gamma_interp_z4) + \
-               vs5*(1.-gamma_interp_x)*(1.-gamma_interp_y)*gamma_interp_z1 + \
-               vs6*gamma_interp_x*(1.-gamma_interp_y)*gamma_interp_z2 + \
-               vs7*gamma_interp_x*gamma_interp_y*gamma_interp_z3 + \
-               vs8*(1.-gamma_interp_x)*gamma_interp_y*gamma_interp_z4
-            #
-            if(vp_final < self.vp_min): vp_final = self.vp_min
-            if(vs_final < self.vs_min): vs_final = self.vs_min
-            if(vp_final > self.vp_max): vp_final = self.vp_max
-            if(vs_final > self.vs_max): vs_final = self.vs_max
-            return vp_final,vs_final
-        else:
-            return vp_static,vs_static
-    #
-    def hex_simulation_parameter(self,h,vp_static=None,vs_static=None):
-        nodes=cubit.get_connectivity('Hex',h)
-        id_nodes=[0,1,2,3,4,5,6,7]
-        id_faces=[[1,3,4],[0,2,5],[1,3,6],[0,2,7],[5,7],[4,6],[5,7],[4,6]]
-        dt=[]
-        pmax=[]
-        vmax=[]
-        vmin=[]
-        for i in id_nodes[:-1]:
-            for j in id_nodes[i+1:]:
-                x1,y1,z1=cubit.get_nodal_coordinates(nodes[i])
-                x2,y2,z2=cubit.get_nodal_coordinates(nodes[j])
-                nvp1,nvs1=self.tomo(x1,y1,z1,vp_static,vs_static)
-                nvp2,nvs2=self.tomo(x2,y2,z2,vp_static,vs_static)
-                d=math.sqrt((x2-x1)**2+(y2-y1)**2+(z2-z1)**2)
-                #pmax_tmp=d*self.gllcoeff/min(nvp1,nvp2,nvs1,nvs2)*self.Ngll_per_wavelength
-                pmax_tmp=d*(.5-self.gllcoeff)/min(nvp1,nvp2,nvs1,nvs2)*self.Ngll_per_wavelength #more conservative.....
-                dt_tmp=self.Cmax*d*self.gllcoeff/max(nvp1,nvp2,nvs1,nvs2)
-                dt.append(dt_tmp)
-                pmax.append(pmax_tmp)
-                vmax.append(max(nvp1,nvp2,nvs1,nvs2))
-                vmin.append(min(nvp1,nvp2,nvs1,nvs2))
-        return min(dt),max(pmax),min(vmin),max(vmax)
-    #
-    def group_period(self):
-        tot=0.
-        if self.period_hyst is not None:
-            pmin=min(self.period_hyst.values())
-            period=self.hyst(pmin,self.period,self.period_hyst)
-            factor=(self.period-pmin)/self.nbin
-            for i in range(0,self.nbin+1):
-                if period.has_key(i):
-                    txt='group "period_%.1e_%.1e" add hex ' %(pmin+factor*i,pmin+factor*(i+1))
-                    txt=txt+' '.join(str(hh) for hh in period[i])
-                    cubit.cmd(txt)
-    def group_timestep(self):
-         tot=0.
-         if self.dt_hyst is not None:
-             dtmax=max(self.dt_hyst.values())
-             dt=self.hyst(self.dt,dtmax,self.dt_hyst)
-             factor=(dtmax-self.dt)/self.nbin
-             for i in range(0,self.nbin+1):
-                 if dt.has_key(i):
-                     txt='group "timestep_%.1e_%.1e" add hex ' %(self.dt+factor*i,self.dt+factor*(i+1))
-                     txt=txt+' '.join(str(hh) for hh in dt[i])
-                     cubit.cmd(txt)
-
-
-#cubit.cmd('brick x 10000')
-#cubit.cmd('mesh vol 1')
-#cubit.cmd('refine hex in node in surf 1')
-#cubit.cmd('refine hex in node in surf 3')
-#vp=1000
-#vs=600
-#mesh=SEM_stability_3D()
-#mesh.check_simulation_parameter(vp_static=vp,vs_static=vs)
-#mesh.group_timestep()
-#mesh.group_period()
\ No newline at end of file

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/local_volume.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/local_volume.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/local_volume.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,242 +0,0 @@
-#############################################################################
-# local_volume.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-
-def read_grid(filename=None):
-    import sys
-    import start as start
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    #
-    numpy                       = start.start_numpy()
-    cfg                         = start.start_cfg(filename=filename)
-    from utilities import geo2utm
-    
-    #     
-    if cfg.nx and cfg.ny:
-        nx=cfg.nx
-        ny=cfg.ny
-        if cfg.nstep:
-            nx=min(cfg.nx,int(cfg.nx/cfg.nstep)+1)
-            ny=min(cfg.ny,int(cfg.ny/cfg.nstep)+1)
-            nstep=cfg.nstep
-        else:
-            nstep=1
-    else:
-        try:
-            xstep=cfg.step
-            ystep=cfg.step
-        except:
-            xstep=cfg.xstep
-            ystep=cfg.ystep
-        nx= int((cfg.longitude_max-cfg.longitude_min)/xstep)+1
-        ny= int((cfg.latitude_max-cfg.latitude_min)/ystep)+1
-        nstep=1
-    #
-    elev=numpy.zeros([nx,ny,cfg.nz],float)
-    coordx=numpy.zeros([nx,ny],float)
-    coordy=numpy.zeros([nx,ny],float)
-    #
-    if  cfg.bottomflat: 
-        elev[:,:,0] = cfg.depth_bottom
-        bottomsurface=1
-    else:
-        bottomsurface=0
-            #
-    for inz in range(bottomsurface,cfg.nz):
-        try:
-             grdfile = open(cfg.filename[inz-bottomsurface], 'r')
-             print 'reading ',cfg.filename[inz-bottomsurface]
-        except:
-             txt='error reading: '+  str( cfg.filename[inz-bottomsurface] )
-             raise NameError, txt
-        #
-        icoord=0
-        for iy in range(0,ny):
-            for ix in range(0,nx):
-                txt=grdfile.readline()
-                try:
-                    if len(txt) != 0:
-                        x,y,z=map(float,txt.split())
-                        if iy%nstep == 0 and ix%nstep == 0:
-                            icoord=icoord+1
-                            x_current,y_current=geo2utm(x,y,cfg.unit)
-                            jx=min(nx-1,ix/nstep)
-                            jy=min(ny-1,iy/nstep)
-                            coordx[jx,jy]=x_current
-                            coordy[jx,jy]=y_current
-                            elev[jx,jy,inz]=z      
-                except:
-                    print 'error reading point ',iy*cfg.nx+ix,txt, cfg.filename[inz-bottomsurface], ' proc ',iproc
-                    raise NameError, 'error reading point'
-                    #
-        if  (nx)*(ny) != icoord: 
-            if iproc == 0: print 'error in the surface file '+cfg.filename[inz-bottomsurface]
-            if iproc == 0: print 'x points ' +str(nx)+ ' y points ' +str(ny)+ ' tot points '+str((nx)*(ny)) 
-            if iproc == 0: print 'points read in '+cfg.filename[inz-bottomsurface]+': '+str(icoord)
-            raise NameError
-            
-        #if iproc == 0: print 'end of reading grd ascii file '+cfg.filename[inz-bottomsurface]+' '+str(icoord)+ ' points'
-        grdfile.close()
-    
-    
-    return coordx,coordy,elev,nx,ny
-    
-
-def extract_volume(xmin,ymin,xmax,ymax,coordx,coordy,elev,nx,ny,filename=None):
-    import sys
-    import start as start
-    #
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    #
-    numpy                       = start.start_numpy()
-    cfg                         = start.start_cfg(filename=filename)             
-    
-    from utilities import geo2utm
-    #
-    rxstep=coordx[1,0]-coordx[0,0]
-    rystep=coordy[0,1]-coordy[0,0]
-    
-    nxmin_cpu=min(0,int((x0-cfg.xmin)/rxstep)+1-10)
-    nymin_cpu=min(0,int((y0-cfg.ymin)/rxstep)+1-10)
-    nxmax_cpu=min(nx,int((x0-cfg.xmin)/rystep)+1+10)
-    nymax_cpu=min(ny,int((y0-cfg.ymin)/rystep)+1+10)
-    #
-    #
-    icurve=0
-    isurf=0
-    ivertex=0
-    #
-    #create vertex
-    last_surface=cubit.get_last_id('surface')
-    for inz in range(0,cfg.nz):
-        if  cfg.bottomflat and inz == 0: #bottom layer
-                    
-                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],cfg.unit)
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)
-                    #
-                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],cfg.unit)
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)                                                                              
-                    #
-                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],cfg.unit)
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)
-                    #
-                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],cfg.unit)
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)
-                    #
-                    cubitcommand= 'create surface vertex 1 2 3 4'
-                    cubit.cmd(cubitcommand)
-                    #
-                    isurf = isurf + 1
-                    
-        else:
-                vertex=[]
-                
-                for iy in range(nymin_cpu,nymax_cpu+1):
-                    ivx=0
-                    for ix in range(nxmin_cpu,nxmax_cpu+1):
-                        zvertex=elev[ix,iy,inz]
-                        x_current,y_current=geo2utm(coordx[ix,iy],coordy[ix,iy],cfg.unit)
-                        #
-                        vertex.append(' Position '+ str( x_current ) +' '+ str( y_current )+' '+ str( zvertex ) )
-                #
-                print iproc, 'vertex created....'
-                n=max(nx,ny)
-                uline=[]
-                vline=[]
-                iv=0
-                
-                cubit.cmd("set info off")
-                cubit.cmd("set echo off")
-                cubit.cmd("set journal off")
-                
-                for iy in range(0,nymax_cpu-nymin_cpu+1):
-                    positionx=''
-                    for ix in range(0,nxmax_cpu-nxmin_cpu+1):
-                        positionx=positionx+vertex[iv]
-                        iv=iv+1
-                    command='create curve spline '+positionx
-                    cubit.cmd(command)
-                    uline.append( cubit.get_last_id("curve") )
-                for ix in range(0,nxmax_cpu-nxmin_cpu+1):
-                    positiony=''
-                    for iy in range(0,nymax_cpu-nymin_cpu+1):
-                        positiony=positiony+vertex[ix+iy*(nxmax_cpu-nxmin_cpu+1)]
-                    command='create curve spline '+positiony
-                    cubit.cmd(command)
-                    vline.append( cubit.get_last_id("curve") )
-                #
-                cubit.cmd("set info "+cfg.cubit_info)
-                cubit.cmd("set echo "+cfg.echo_info)
-                cubit.cmd("set journal "+cfg.jou_info)
-                #
-                #
-                print iproc,'line created....'
-                umax=max(uline)
-                umin=min(uline)
-                vmax=max(vline)
-                vmin=min(vline)
-                cubitcommand= 'create surface net u curve '+ str( umin )+' to '+str( umax )+ ' v curve '+ str( vmin )+ ' to '+str( vmax )+' heal'
-                cubit.cmd(cubitcommand)
-                command = "del curve all"
-                cubit.cmd(command)
-                isurf=isurf+1
-                #
-                #
-        cubitcommand= 'del vertex all'
-        cubit.cmd(cubitcommand)
-        #cubit_error_stop(iproc,cubitcommand,ner)
-    cubitcommand= 'del curve all'
-    cubit.cmd(cubitcommand)
-    #
-    last_surface_2=cubit.get_last_id('surface')
-    #
-    for inz in range(1,cfg.nz):
-        #!cubit cmd
-        cubitcommand= 'create volume loft surface '+ str( inz+1 )+' '+str( inz )
-        cubit.cmd(cubitcommand)
-        #cubit_error_stop(iproc,cubitcommand,ner)
-        isurf=isurf+6
-    cubitcommand= 'del surface '+str(last_surface+1)+' to '+ str( last_surface_2 )
-    cubit.cmd(cubitcommand)
-    #cubit_error_stop(iproc,cubitcommand,ner)
-    #
-    #        
-    cubit.cmd("set info "+cfg.cubit_info)
-    cubit.cmd("set echo "+cfg.echo_info)
-    cubit.cmd("set journal "+cfg.jou_info)
-    command = "compress all"
-    cubit.cmd(command)
-    
\ No newline at end of file

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/menu.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/menu.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/menu.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,315 +0,0 @@
-#############################################################################
-# menu.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-
-import getopt, sys
-
-def usage():
-    print """
-    GEOCUBIT HELP...
-    
-    1) UTILITIES
-    
-         check the configuration of the libraries and dependencies:
-         GEOCUBIT.py --chklib
-         
-         check the parameter file:
-         GEOCUBIT.py --chkcfg --cfg=[filename]
-         
-    2) CREATE GEOMETRY
-    
-         create a surface from regular ascii grid or ascii lines defining a skin:
-         GEOCUBIT.py --surface=[surface file] (--regulargrid=[options]) (--skin=[options])
-         
-         create a plane surface
-         GEOCUBIT.py --plane --x1=[x,y,z] --x2=[x,y,z] --x3=[x,y,z] --x4=[x,y,z] --unit=[utm/geo]
-         
-         create acis surfaces using a parameter file:
-         GEOCUBIT.py --build_surface --cfg=[filename]
-         
-         **SERIAL**: create cubit volumes using a parameter file:
-         GEOCUBIT.py --build_volume --cfg=[filename] (--id_proc=[num_processor, default=0])
-         
-         **PARALLEL**: create a volume from a parameter file
-         mpirun -n [numproc] pyMPI GEOCUBIT.py --build_volume --cfg=[filename
-         
-    3) MESHING
-    
-         **SERIAL**: meshing a volumes
-         GEOCUBIT.py --mesh --cfg=[filename] (--id_proc=[num_processor, default=0])       - note: without the --build_volume flag the script recall an old 'geometry_vol_[id_proc].cub' file
-         
-         build a volume and mesh it....
-         GEOCUBIT.py --build_volume --mesh --cfg=[filename] (--id_proc=[num_processor, default=0])
-         
-         **PARALLEL**: meshing a volume from a parameter file (it is possible to skip the build_volume and use some geometry files already created, but only with a parallel file system and it is risky)
-         mpirun -n [numproc] pyMPI GEOCUBIT.py --build_volume --mesh --cfg=[filename]
-         
-    4) FINALIZING AND EXPORTING
-    
-         collect some cubit files and merge in a single free mesh cubitfile
-         GEOCUBIT.py --collect   --merge --meshfiles=[list of files] --cpux=N --cpuy=N (--rangecpux=[cpuxmin,cpuxmax], --rangecpuy=[cpuymin,cpuymax])
-         
-         collect a single free mesh cubitfile and refine the hex inside some curve (ex. basin)
-         GEOCUBIT.py --collect --meshfiles=[list of files] --curverefining=[list of SAT files]       
-         
-         export a cubit mesh file (with blocks defined following the note)  in a SPECFEM3D_SESAME mesh
-         GEOCUBIT.py --export2SPECFEM3D --meshfiles=[filename] (--listblock=block1,block2,..,blockN --listflag=[list of specfem flag, i.e. --listflag=1,2,3,-1])
-         
-    """
-try:
-    opts, args = getopt.getopt(sys.argv[1:], "sjmohbp1", ["SEMoutput=","qlog","mfast","curverefining=","output=","rangecpux=","rangecpuy=","equivalence","listflag=","listblock=","cpux=","cpuy=","exofiles=","partitioner","plane","x1=","x2=","x3=","x4=","unit=","chkcfg","mat=","merge_tolerance=","export2SPECFEM3D=","mesh","chklib","cfg=","job=","basin","help", "id_proc=", "surface=","script","jou","strat","MPI","regulargrid=",'skin=',"build_surface","build_volume","merge1","merge2","merge","collect","meshfiles="])
-    print opts, args
-except getopt.GetoptError,errmsg:
-    if str(errmsg) == 'option --export2SPECFEM3D requires argument':
-        for i,xop in enumerate(sys.argv[1:]):
-            if 'export2SPECFEM3D' in xop:
-                sys.argv[i+1]=sys.argv[i+1]+'=.'
-        try:
-            opts, args = getopt.getopt(sys.argv[1:], "sjmohbp1", ["SEMoutput=","qlog","mfast","curverefining=","output=","rangecpux=","rangecpuy=","equivalence","listflag=","listblock=","cpux=","cpuy=","exofiles=","partitioner","plane","x1=","x2=","x3=","x4=","unit=","chkcfg","mat=","merge_tolerance=","export2SPECFEM3D=","mesh","chklib","cfg=","job=","basin","help", "id_proc=", "surface=","script","jou","strat","MPI","regulargrid=",'skin=',"build_surface","build_volume","merge1","merge2","merge","collect","meshfiles="])
-            print opts, args
-        except getopt.GetoptError,errmsg:
-            print str(errmsg)
-            usage()
-            sys.exit(2)
-    else:
-        print str(errmsg)
-        usage()
-        sys.exit()
-except AttributeError:
-    opts=None
-    args=None
-    print opts, args
-    
-output='totalmesh_merged'
-SPECFEM3D_output_dir='.'
-verbose = False
-surface = False
-script = False
-mesh = False
-basin = False
-configuration = None
-id_proc=0
-single=False
-nomesh=False
-jobid=0
-build_surface=False
-build_volume=False
-meshing=False
-ckbound_method1=False
-ckbound_method2=False
-collect=False
-export2SPECFEM3D=False
-merge_tolerance=0
-material_file='material_archive.dat'
-material_assignement=[]
-chkcfg=False
-create_plane=False
-create_partitioner=False
-cubfiles=None
-exofiles=None
-listflag=None
-listblock=None
-cpux=0
-cpuy=0
-cpuxmin=0
-cpuymin=0
-cpuxmax=None
-cpuymax=None
-curverefining=False
-
-
-
-
-
-qlog=False
-
-
-if opts: 
-    for o, value in opts:
-        #print o,value
-        if o in ('--partitioner'):
-            create_partitioner=True
-        if o == ('--surface'):
-            surface=True
-            surface_name=value
-        if o == ('--build_surface'):
-            build_surface=True
-        if o == ('--build_volume'):
-            build_volume=True
-        if surface and o == ('--regular_grid'):
-            surface_type='regular_grid'
-            tmp=value.split('/')
-            if len(tmp)==4:
-                num_x,num_y,unit,delimiter=value.split('/')
-            elif len(tmp)==3:
-                num_x,num_y,unit=value.split('/')
-            num_x=int(num_x)
-            num_y=int(num_y)
-            delimiter=' '
-        if surface and o == ('--skin'):
-            surface_type='skin'
-            tmp=value.split('/')
-            if len(tmp)==4:
-                directionx,directiony,unit,delimiter=value.split('/')
-            elif len(tmp)==3:
-                directionx,directiony,unit=value.split('/')
-            directiony=int(directiony)
-            directionx=int(directionx)
-        if o in ('--plane'):
-            create_plane=True
-            cfg_name=False
-        if o in ('--x1'):
-            x1=value
-        if o in ('--x2'):
-            x2=value
-        if o in ('--x3'):         
-            x3=value
-        if o in ('--x4'):         
-            x4=value
-        if o in ('--unit'):
-           unit=value
-        #
-        if o in ('--build_volume'):
-            build_volume=True
-        if o in ("-h", "--help"):
-            usage()
-            sys.exit(2)
-        #chec   k the configuration
-        if o in ("--chklib"):
-            import start as start
-            mpiflag,iproc,numproc,mpi   = start.start_mpi()
-            if mpiflag:
-                print '--------, MPI ON, parallel mesher ready'
-            else:
-                print '--------, MPI OFF, serial mesher ready'
-            numpy                       = start.start_numpy()
-            print '--------, Numpy ON'
-            cubit                  = start.start_cubit()
-            print '--------, CUBIT ON'
-            sys.exit()
-        if o in ("--cfg"):
-            cfg_name=value
-        if o == ('--surface'):
-            surface=True
-            surface_name=value
-        if o == ("--mesh"):
-            meshing=True
-        if o in ("-1"):
-            single=True
-        if o in ("--collect"):
-            collect=True
-        if o in ("--merge2") and o != '--merge':
-            ckbound_method2=True
-        if o in ("--equivalence","--merge1","--merge"):
-            ckbound_method1=True
-        if o in ("--mfast"):
-            ckbound_method1=True
-            ckbound_method2=True
-        if o in ("--meshfiles"):
-            cubfiles=value
-        if o in ("--exofiles"):
-            exofiles=value
-        if o in ("--export2SPECFEM3D"):
-               export2SPECFEM3D=True
-               SPECFEM3D_output_dir=value
-               import os
-               try:
-                   os.makedirs(SPECFEM3D_output_dir)
-               except OSError:
-                   pass
-        if o in ("--merge_tolerance") and o != '--merge' and o != '--merge2' and o != '--merge1':
-             merge_tolerance=map(float,value.split(','))
-        if o in ("--mat"):
-            material_assignement.append([value.split(',')[0],value.split(',')[1]])
-        if o in ("--listblock"):
-            listblock=map(int,value.split(','))
-        if o in ("--listflag"):
-            listflag=map(int,value.split(','))
-        if o in ("--chkcfg"):
-            chkcfg=True
-        if o in ('--id_proc'):
-            id_proc=int(value)
-        if o in ('--rangecpux'):
-            cpuxmin=int(value.split(',')[0])
-            cpuxmax=int(value.split(',')[1])+1
-        if o in ('--rangecpuy'):
-            cpuymin=int(value.split(',')[0])
-            cpuymax=int(value.split(',')[1])+1
-        if o in ('--cpux'):
-            cpux=int(value)
-        if o in ('--cpuy'):
-            cpuy=int(value)
-        if o in ("--qlog"):
-            qlog=True
-        if o in ("--output","-o"):
-            output=value
-        if o in ("--curverefining"):
-            curverefining=value.split(',')
-        if o in ("SEMoutput"):
-            SPECFEM3D_output_dir=value
-    print cpuxmax,cpuymax
-    if cpuymax:
-        pass
-    elif cpuy > 1:
-        cpuymax=cpuy
-    else:
-        cpuymax=1
-    if cpuxmax:
-        pass
-    elif cpux > 1:
-        cpuxmax=cpux
-    else:
-        cpuxmax=1	    
-    print cpuxmax,cpuymax
-    if chkcfg==True:        
-        import start as start
-        cfg=start.start_cfg()
-        d=cfg.__dict__
-        ks=d.keys()                                                              
-        ks.sort()                                                                
-        for k in ks:                                                             
-            if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
-                txt=str(k)+' -----> '+str(d[k])                              #    
-                txt=txt.replace("'","").replace('"','')                      #    
-                print txt                               #
-    else:
-        try:
-            import start as start
-            cfg=start.start_cfg()
-            f=open('cfg.log','w')
-            print>>f, 'CFG FILE: ',cfg_name
-            d=cfg.__dict__
-            ks=d.keys()                                                              
-            ks.sort()                                                                
-            for k in ks:                                                             
-                if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
-                    txt=str(k)+' -----> '+str(d[k])                              #    
-                    txt=txt.replace("'","").replace('"','')                      #    
-                    print>>f, txt
-            f.close()                               #
-        except:
-            pass
-elif opts == []:
-    print __name__
-    usage()
-    raise AttributeError('no options')

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/mesh_volume.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/mesh_volume.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/mesh_volume.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,443 +0,0 @@
-#############################################################################
-# mesh_volume.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-    
-
-def mesh(filename=None):
-    """create the mesh"""
-    import start as start
-    cfg                     = start.start_cfg(filename=filename)
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    #
-    if cfg.map_meshing_type == 'regularmap':
-            mesh_layercake_regularmap(filename=filename)
-            #elif cfg.map_meshing_type == 'partitioner':
-            #        mesh_partitioner()
-    else:
-        print 'error: map_meshing_type ', cfg.map_meshing_type,' not implemented'
-
-
-def mesh_layercake_regularmap(filename=None):
-    import sys,os
-    import start as start
-    #
-    class cubitvolume:
-          def __init__(self,ID,intervalv,centerpoint,dimension):
-              self.ID=ID
-              self.intervalv=intervalv
-              self.centerpoint=centerpoint
-              self.dim=dimension
-          
-          def __repr__(self):
-              msg="(vol:%3i, vertical interval: %4i, centerpoint: %8.2f)" % (self.ID, self.intervalv,self.centerpoint)
-              return msg       
-    #
-    def by_z(x,y):
-        return cmp(x.centerpoint,y.centerpoint)
-    #
-    #
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    from utilities import  importgeometry,savemesh,get_v_h_list
-    #
-    numpy                       = start.start_numpy()
-    cfg                         = start.start_cfg(filename=filename)
-    from math import sqrt
-    from sets import Set
-    #
-    list_vol=cubit.parse_cubit_list("volume","all")
-    if len(list_vol) != 0:
-        pass
-    else:
-        geometryfile='geometry_vol_'+str(iproc)+'.cub'
-        importgeometry(geometryfile,iproc=iproc)
-    #
-    command = 'composite create curve all'
-    cubit.cmd(command)
-    print 'NO CRITICAL ERROR: "No valid composites can be created from the specified curves."  is not critical. \n It means that your model is clean and you don"t need a virtual geometry'
-    #
-    command = "compress all"
-    cubit.cmd(command)
-    list_vol=cubit.parse_cubit_list("volume","all")
-    nvol=len(list_vol)                                 
-    vol=[]
-    for id_vol in list_vol:
-        p=cubit.get_center_point("volume",id_vol)
-        vol.append(cubitvolume(id_vol,1,p[2],0))
-    vol.sort(by_z)
-    #
-    for id_vol in range(0,nvol):
-        vol[id_vol].intervalv=cfg.iv_interval[id_vol]
-    #
-    #
-    surf_vertical=[]
-    surf_or=[]
-    top_surface=0
-    top_surface_add=''
-    bottom_surface=0
-    #
-    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6]
-    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
-    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
-    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
-    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
-    #
-    #
-    #interval assignement
-    surf_or,surf_vertical,list_curve_or,list_curve_vertical,bottom,top = get_v_h_list(list_vol)
-    
-    for k in surf_vertical:
-        command = "surface "+str(k)+" scheme submap"
-        cubit.cmd(command)
-    for k in surf_or:
-        command = "surface "+str(k)+" scheme "+cfg.or_mesh_scheme
-        cubit.cmd(command)
-    for k in list_curve_or:
-        length=cubit.get_curve_length(k)
-        interval=int(2*round(.5*length/cfg.size,0))
-        command = "curve "+str(k)+" interval "+str(interval)
-        cubit.cmd(command)
-        #cubit_error_stop(iproc,command,ner)
-        command = "curve "+str(k)+" scheme equal"
-        cubit.cmd(command)
-        #cubit_error_stop(iproc,command,ner)
-        #
-    for s in surf_vertical:
-        lcurve=cubit.get_relatives("surface",s,"curve")
-        interval_store=[]
-        for k in lcurve:
-            interval_curve=cubit.get_mesh_intervals('curve',k)
-            if k in list_curve_vertical:
-                volume_id = cubit.get_owning_volume("curve", k)
-                for idv in range(0,nvol):
-                    if vol[idv].ID == volume_id:
-                        int_v=vol[idv].intervalv
-                command = "curve "+str(k)+" interval "+str(int_v)
-                cubit.cmd(command)
-                #cubit_error_stop(iproc,command,ner)
-                command = "curve "+str(k)+" scheme equal"
-                cubit.cmd(command)
-                #cubit_error_stop(iproc,command,ner)
-            else:
-                interval_store.append((k,interval_curve))
-            if len(interval_store) != 0:
-                interval_min=min([iv[1] for iv in interval_store])
-                command = "curve "+' '.join(str(iv[0]) for iv in interval_store)+" interval "+str(interval_min)
-                cubit.cmd(command)
-                #cubit_error_stop(iproc,command,ner)
-                command = "curve "+' '.join(str(iv[0]) for iv in interval_store)+" scheme equal"
-                cubit.cmd(command)
-                #cubit_error_stop(iproc,command,ner)
-    #cubit_error_stop(iproc,command,ner)
-    #
-    #meshing
-    if cfg.or_mesh_scheme == 'pave':
-        command='mesh surf '+' '.join(str(t) for t in top)
-        cubit.cmd(command)    
-    elif cfg.or_mesh_scheme == 'map':
-        command='mesh surf '+' '.join(str(t) for t in bottom)
-        cubit.cmd(command)
-    for id_volume in range(nvol-1,-1,-1):
-        command = "mesh vol "+str(vol[id_volume].ID)
-        cubit.cmd(command)        
-    
-    #
-    #smoothing
-    print iproc, 'untangling...'
-    cmd="volume all smooth scheme untangle beta 0.02 cpu 10"
-    cubit.cmd(cmd)
-    cmd="smooth volume all"
-    cubit.cmd(cmd)
-    
-    
-    
-    if  cfg.smoothing:
-        print 'smoothing .... '+str(cfg.smoothing)
-        cubitcommand= 'surf all smooth scheme laplacian '
-        cubit.cmd(cubitcommand)
-        cubitcommand= 'smooth surf all'
-        cubit.cmd(cubitcommand)
-        #
-        cubitcommand= 'vol all smooth scheme laplacian '
-        cubit.cmd(cubitcommand)
-        cubitcommand= 'smooth vol all'
-        cubit.cmd(cubitcommand)
-    #
-    #
-    ##vertical refinement
-    ##for nvol = 3 
-    ##
-    ##___________________________ interface 4
-    ##                 
-    ##vol 2              
-    ##___________________________ interface 3
-    ##
-    ##vol 1
-    ##___________________________ interface 2
-    ##
-    ##vol 0
-    ##___________________________ interface 1
-    ##
-    refinement(nvol,vol,filename=filename)
-    #
-    #top layer vertical coarsening
-    print 'coarsening top layer... ',cfg.coarsening_top_layer
-    if  cfg.coarsening_top_layer:
-        from sets import Set
-        cubitcommand= 'del mesh vol '+str(vol[-1].ID)+ ' propagate'
-        cubit.cmd(cubitcommand)
-        s1=Set(list_curve_vertical)
-        print s1
-        command = "group 'list_curve_tmp' add curve "+"in vol "+str(vol[-1].ID)
-        cubit.cmd(command)
-        group=cubit.get_id_from_name("list_curve_tmp")
-        list_curve_tmp=cubit.get_group_curves(group)
-        command = "delete group "+ str(group)
-        cubit.cmd(command)
-        s2=Set(list_curve_tmp)
-        print s2
-        lc=list(s1 & s2)
-        print lc
-        #
-        cubitcommand= 'curve '+' '.join(str(x) for x in lc)+' interval '+str(cfg.actual_vertical_interval_top_layer)
-        cubit.cmd(cubitcommand)
-        cubitcommand= 'mesh vol '+str(vol[-1].ID)
-        cubit.cmd(cubitcommand)
-    #
-    n=cubit.get_sideset_id_list()
-    if len(n) != 0:
-        command = "del sideset all"
-        cubit.cmd(command)
-    n=cubit.get_block_id_list()
-    if len(n) != 0:    
-        command = "del block all"
-        cubit.cmd(command)
-    #
-    import boundary_definition
-    entities=['face']
-    print iproc, 'hex block definition...'
-    boundary_definition.define_bc(entities,parallel=True,cpux=cfg.cpux,cpuy=cfg.cpuy,cpuxmin=0,cpuymin=0)
-    #save mesh
-    
-    print iproc, 'untangling...'
-    cmd="volume all smooth scheme untangle beta 0.02 cpu 10"
-    cubit.cmd(cmd)
-    cmd="smooth volume all"
-    cubit.cmd(cmd)
-    
-    print iproc, 'saving...'
-    savemesh(mpiflag,iproc=iproc,filename=filename)
-    #
-
-def refinement(nvol,vol,filename=None):
-    import start as start
-    cfg                         = start.start_cfg(filename=filename)
-    #
-    #vertical refinement
-    #for nvol = 3 
-    #
-    #___________________________ interface 4
-    #                 
-    #vol 2              
-    #___________________________ interface 3
-    #
-    #vol 1
-    #___________________________ interface 2
-    #
-    #vol 0
-    #___________________________ interface 1
-    #
-    #
-    if cfg.ntripl != 0:
-        if len(cfg.refinement_depth) != 0:
-            #get the topo surface....
-            surf=cubit.get_relatives('volume',vol[nvol+1-2].ID,'surface')
-            zstore=[-1,-999999999]
-            for s in surf:
-                 c=cubit.get_center_point('surface',s)
-                 z=c[2]
-                 if z > zstore[1]:
-                     zstore=[s,z]
-            tsurf=zstore[0]
-            for idepth in cfg.refinement_depth:
-                 cubitcommand= 'refine node in surf  '+str(tsurf)+' numsplit 1 bias 1.0 depth '+str(idepth)
-                 cubit.cmd(cubitcommand)
-        else:
-            for ir in cfg.tripl:
-                if ir == 1:
-                   command = "comment '"+"interface = 1 means that the refinement interface is at the bottom of the volume"+"'"
-                   cubit.cmd(command)
-                   txt=' all '
-                   idepth = 1
-                   cubitcommand= 'refine hex in vol  '+txt
-                elif ir != nvol+1:
-                   txt=''
-                   for id_vol_ref in range(ir-1,nvol):
-                       txt=txt+str(vol[id_vol_ref].ID)+' '
-                   #txt=txt+'except hex in vol '+str(vol[ir-2].ID)
-                   #idepth = 1
-                   #try:
-                   #     if  cfg.refine_basin:
-                   #         idepth=2
-                   #except:
-                   #     pass
-                   cubitcommand= 'refine hex in vol  '+txt
-                else:
-                   #refinement on the top surface
-                   
-                   surf=cubit.get_relatives('volume',vol[ir-2].ID,'surface')
-                   zstore=[-1,-999999999]
-                   for s in surf:
-                        c=cubit.get_center_point('surface',s)
-                        z=c[2]
-                        if z > zstore[1]:
-                            zstore=[s,z]
-                   idepth=1
-                   cubitcommand= 'refine node in surf '+str(zstore[0])+' numsplit 1 bias 1.0 depth '+str(idepth)
-                cubit.cmd(cubitcommand)
-
-
-
-
-def pinpoly(x,y,polyx,polyy):
-    """point in polygon using ray tracing"""
-    n = len(polyx)
-    inside = False
-    poly=zip(polyx,polyy)
-    px_0,py_0 = poly[0]
-    for i in range(n+1):
-        px_1,py_1 = poly[i % n]
-        if y > min(py_0,py_1):
-            if y <= max(py_1,py_0):
-                if x <= max(px_1,px_0):
-                    if py_0 != py_1:
-                        intersect = (y-py_0)*(px_1-px_0)/(py_1-py_0)+px_0
-                    if px_1 == px_0 or x <= intersect:
-                        inside = not inside
-        px_0,py_0 = px_1,py_1
-    return inside
-
-def curve2poly(line):
-    curve=int(line)
-    cubit.cmd('curve '+str(curve)+' size auto factor 1')
-    cubit.cmd('mesh curve '+str(curve))
-    n=cubit.get_curve_nodes(curve)
-    orientnode=[]
-    vertex_list = cubit.get_relatives("curve", curve, "vertex")
-    if len(vertex_list) != 0:
-        startnode=cubit.get_vertex_node(vertex_list[0])
-        cubit.cmd('del group pgon')
-        cubit.cmd("group 'pgon' add edge in node "+str(startnode))
-        group1 = cubit.get_id_from_name("pgon")
-        edges = list(cubit.get_group_edges(group1))
-        edgestart=edges[0]
-    else:
-        startnode=n[0]
-        cubit.cmd('del group pgon')
-        cubit.cmd("group 'pgon' add edge in node "+str(startnode))
-        group1 = cubit.get_id_from_name("pgon")
-        edges = list(cubit.get_group_edges(group1))
-        edgestart=edges[0]
-    begin=startnode
-    orientnode.append(begin)
-    node_id_list = list(cubit.get_connectivity("edge", edgestart))
-    node_id_list.remove(startnode)
-    startnode=node_id_list[0]
-    orientnode.append(startnode)
-    stopflag=False
-    while startnode != begin and not stopflag:
-        cubit.cmd('del group pgon')
-        cubit.cmd("group 'pgon' add edge in node "+str(startnode))
-        group1 = cubit.get_id_from_name("pgon")
-        edges = list(cubit.get_group_edges(group1))
-        if len(edges) != 1:
-            edges.remove(edgestart)
-            edgestart=edges[0]
-            node_id_list = list(cubit.get_connectivity("edge", edgestart))
-            node_id_list.remove(startnode)
-            orientnode.append(node_id_list[0])
-            startnode=node_id_list[0]
-        else:
-            stopflag=True
-    vx=[]
-    vy=[]
-    for n in orientnode:
-        v=cubit.get_nodal_coordinates(n)
-        vx.append(v[0])
-        vy.append(v[1])    
-    return vx,vy,orientnode
-
-def get_nodes_inside_curve(nodes, curve):
-    vx,vy,n=curve2poly(curve)
-    nodes_inside=[]
-    for n in nodes:
-        vp=cubit.get_nodal_coordinates(n)
-        if pinpoly(vp[0],vp[1],vx,vy): nodes_inside.append(n)
-    return nodes_inside
-
-def refine_inside_curve(curves,ntimes=1,depth=1,block=1,surface=False):
-    if not isinstance(curves,list): 
-       if isinstance(curves,str):
-          curves=map(int,curves.split())
-       else:
-          curves=[curves]
-    for curve in curves:
-        cubit.cmd('del group ntop')
-        if not surface:
-            cubit.cmd("group 'ntop' add node in face in block "+str(block))
-        else:
-            cubit.cmd("group 'ntop' add node in face in surface "+str(surface))
-        group1 = cubit.get_id_from_name("ntop")
-        nodes = list(cubit.get_group_nodes(group1))
-        ni=get_nodes_inside_curve(nodes, curve)
-        if ntimes > 1:
-            cmd='del group hex_refining'
-            cubit.cmd(cmd)
-            command = "group 'hex_refining' add hex propagate face in node "+' '.join(str(x) for x in ni)+"times "+str(ntimes)
-            cubit.cmd(command)
-            id_group=cubit.get_id_from_name('hex_refining')
-            command='refine hex in group "hex_refining" numsplit 1 bias 1.0 depth '+str(depth)+' smooth'
-            cubit.cmd(command)
-        else:
-            command='refine node '+" ".join(str(x) for x in ni)+' numsplit 1 bias 1.0 depth '+str(depth)+' smooth'
-            cubit.cmd(command)
-    #
-    #
-    cmd='group "negativejac" add quality hex all Jacobian high'
-    cubit.cmd(cmd) 
-    group_id_1=cubit.get_id_from_name("negativejac")
-    n1=cubit.get_group_nodes(group_id_1)
-    if len(n1) != 0:
-        print 'error, negative jacobian after the refining'
-        import sys
-        #sys.exit()
-

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/quality_log.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/quality_log.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/quality_log.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,282 +0,0 @@
-#############################################################################
-# quality_log.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-
-
-def quality_log(tqfile=None):
-    """
-    creation of the quality parameter file
-    """
-    import start as start
-    #
-    #
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    #
-    #
-    from hex_metric import SEM_metric_3D
-    #
-    lvol=cubit.parse_cubit_list('volume','all')
-    if len(lvol)!=0:
-        cubit.cmd('quality vol all allmetric                                      ')
-    else:
-        cubit.cmd('quality hex in block all allmetric                                      ')
-    cubit.cmd('list model                                                      ')
-    #
-    toclose=True
-    if isinstance(tqfile,file): 
-        totstat_file=tqfile
-    elif isinstance(tqfile,str):
-        totstat_file=open(tqfile+'_cubitquality_skewness_proc_'+str(iproc)+'.log','w')
-    else:
-        import sys
-        totstat_file=sys.stdout
-        toclose=False
-    
-    mesh=SEM_metric_3D()
-    mesh.check_metric()
-    
-    if mesh.max_skewness is not None:
-        mesh.skew_hystogram=mesh.hyst(0,mesh.max_skewness,mesh.skew_hyst)
-        totstat_file.write('-'*70+'\n')
-        
-        
-        
-        
-        
-        totstat_file.write('='*70+'\n')
-        totstat_file.write('SKEWNESS'+'\n')
-        totstat_file.write('='*70+'\n') 
-        if len(mesh.hex_max_skewness) <= 30:
-            totstat_file.write('max = '+str(mesh.max_skewness)+' in hexes '+str(mesh.hex_max_skewness)+'\n')
-            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+ ' maximun ='+str(mesh.max_angle)+')'+'\n')
-        else:
-            totstat_file.write('max = '+str(mesh.max_skewness)+' in '+str(len(mesh.hex_max_skewness))+' hexes '+'\n')
-            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+' maximun ='+str(mesh.max_angle)+')'+'\n')
-        totstat_file.write('-'*70+'\n')
-        totstat_file.write('skew hystogram')
-        totstat_file.write('-'*70+'\n')
-        tot=0
-        for i in mesh.skew_hystogram.values():
-            tot=tot+len(i)
-        #k=mesh.skew_hystogram.keys()
-        #k.sort()
-        factor=mesh.max_skewness/mesh.nbin
-        for i in range(0,mesh.nbin+1):
-            if mesh.skew_hystogram.has_key(i):
-                if (i+1)*factor <= 1:
-                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : '+str(len(mesh.skew_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.skew_hystogram[i])/float(tot)*100.)+'%)'+'\n')
-            else:
-                if (i+1)*factor <= 1:
-                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
-        totstat_file.write('-'*70+'\n')
-    ###############################################
-    if mesh.min_edge_length is not None:
-        mesh.edgemin_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemin_hyst)
-        mesh.edgemax_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemax_hyst)
-        totstat_file.write('='*70+'\n')
-        totstat_file.write('edge length')
-        totstat_file.write('='*70+'\n')
-        if len(mesh.hex_min_edge_length) <= 30:
-            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in hexes '+str(mesh.hex_min_edge_length)+'\n')
-        else:
-            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in '+str(len(mesh.hex_min_edge_length))+ ' hexes.'+'\n')
-        if len(mesh.hex_max_edge_length) <= 30:
-            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+ ' in hexes '+str(mesh.hex_max_edge_length)+'\n')              
-        else:                                                                                                                        
-            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+' in '+str(len(mesh.hex_max_edge_length))+ ' hexes.'+'\n')    
-        totstat_file.write('-'*70+'\n')
-        totstat_file.write('edge length hystogram')
-        totstat_file.write('-'*70+'\n')
-        factor=(mesh.max_edge_length-mesh.min_edge_length)/mesh.nbin
-        totstat_file.write('minimum edge length'+'\n')
-        tot=0
-        for i in mesh.edgemin_hystogram.values():
-            tot=tot+len(i)
-        #k=mesh.edgemin_hystogram.keys()
-        #k.sort()
-        for i in range(0,mesh.nbin+1):
-            if mesh.edgemin_hystogram.has_key(i):
-                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemin_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemin_hystogram[i])/float(tot)*100.)+'%)'+'\n')
-            else:
-                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
-        totstat_file.write('-'*70+'\n')
-        totstat_file.write('maximum edge length')
-        tot=0
-        for i in mesh.edgemax_hystogram.values():
-            tot=tot+len(i)
-        #k=mesh.edgemax_hystogram.keys()
-        #k.sort()
-        for i in range(0,mesh.nbin+1):
-            if mesh.edgemax_hystogram.has_key(i):
-                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemax_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemax_hystogram[i])/float(tot)*100.)+'%)'+'\n')
-            else:
-                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
-    try:
-        if mesh.dt is not None:
-            totstat_file.write('='*70+'\n')
-            totstat_file.write('STABILITY')
-            totstat_file.write('='*70+'\n')
-            totstat_file.write('time step < '+str(mesh.dt)+'s, for velocity = '+str(mesh.velocity)+'\n')
-    except:
-        pass
-    
-    if toclose: 
-        totstat_file.close()
-    
-    print 'max specfem3d skewness: ',mesh.max_skewness
-    print 'min edge length: ',mesh.min_edge_length
-    return mesh.max_skewness,mesh.min_edge_length
-    
-    
-def quality_log(tqfile=None):
-    """
-    creation of the quality parameter file
-    """
-    import start as start
-    #
-    #
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    #
-    #
-    from hex_metric import SEM_metric_3D
-    #
-    lvol=cubit.parse_cubit_list('volume','all')
-    if len(lvol)!=0:
-        cubit.cmd('quality vol all allmetric                                      ')
-    else:
-        cubit.cmd('quality hex in block all allmetric                                      ')
-    cubit.cmd('list model                                                      ')
-    #
-    toclose=True
-    if isinstance(tqfile,file): 
-        totstat_file=tqfile
-    elif isinstance(tqfile,str):
-        totstat_file=open(tqfile+'_cubitquality_skewness_proc_'+str(iproc)+'.log','w')
-    else:
-        import sys
-        totstat_file=sys.stdout
-        toclose=False
-
-    mesh=SEM_metric_3D()
-    mesh.check_metric()
-
-    if mesh.max_skewness is not None:
-        mesh.skew_hystogram=mesh.hyst(0,mesh.max_skewness,mesh.skew_hyst)
-        totstat_file.write('-'*70+'\n')
-
-
-
-
-
-        totstat_file.write('='*70+'\n')
-        totstat_file.write('SKEWNESS'+'\n')
-        totstat_file.write('='*70+'\n') 
-        if len(mesh.hex_max_skewness) <= 30:
-            totstat_file.write('max = '+str(mesh.max_skewness)+' in hexes '+str(mesh.hex_max_skewness)+'\n')
-            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+ ' maximun ='+str(mesh.max_angle)+')'+'\n')
-        else:
-            totstat_file.write('max = '+str(mesh.max_skewness)+' in '+str(len(mesh.hex_max_skewness))+' hexes '+'\n')
-            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+' maximun ='+str(mesh.max_angle)+')'+'\n')
-        totstat_file.write('-'*70+'\n')
-        totstat_file.write('skew hystogram')
-        totstat_file.write('-'*70+'\n')
-        tot=0
-        for i in mesh.skew_hystogram.values():
-            tot=tot+len(i)
-        #k=mesh.skew_hystogram.keys()
-        #k.sort()
-        factor=mesh.max_skewness/mesh.nbin
-        for i in range(0,mesh.nbin+1):
-            if mesh.skew_hystogram.has_key(i):
-                if (i+1)*factor <= 1:
-                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : '+str(len(mesh.skew_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.skew_hystogram[i])/float(tot)*100.)+'%)'+'\n')
-            else:
-                if (i+1)*factor <= 1:
-                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
-        totstat_file.write('-'*70+'\n')
-    ###############################################
-    if mesh.min_edge_length is not None:
-        mesh.edgemin_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemin_hyst)
-        mesh.edgemax_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemax_hyst)
-        totstat_file.write('='*70+'\n')
-        totstat_file.write('edge length')
-        totstat_file.write('='*70+'\n')
-        if len(mesh.hex_min_edge_length) <= 30:
-            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in hexes '+str(mesh.hex_min_edge_length)+'\n')
-        else:
-            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in '+str(len(mesh.hex_min_edge_length))+ ' hexes.'+'\n')
-        if len(mesh.hex_max_edge_length) <= 30:
-            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+ ' in hexes '+str(mesh.hex_max_edge_length)+'\n')              
-        else:                                                                                                                        
-            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+' in '+str(len(mesh.hex_max_edge_length))+ ' hexes.'+'\n')    
-        totstat_file.write('-'*70+'\n')
-        totstat_file.write('edge length hystogram')
-        totstat_file.write('-'*70+'\n')
-        factor=(mesh.max_edge_length-mesh.min_edge_length)/mesh.nbin
-        totstat_file.write('minimum edge length'+'\n')
-        tot=0
-        for i in mesh.edgemin_hystogram.values():
-            tot=tot+len(i)
-        #k=mesh.edgemin_hystogram.keys()
-        #k.sort()
-        for i in range(0,mesh.nbin+1):
-            if mesh.edgemin_hystogram.has_key(i):
-                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemin_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemin_hystogram[i])/float(tot)*100.)+'%)'+'\n')
-            else:
-                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
-        totstat_file.write('-'*70+'\n')
-        totstat_file.write('maximum edge length')
-        tot=0
-        for i in mesh.edgemax_hystogram.values():
-            tot=tot+len(i)
-        #k=mesh.edgemax_hystogram.keys()
-        #k.sort()
-        for i in range(0,mesh.nbin+1):
-            if mesh.edgemax_hystogram.has_key(i):
-                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemax_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemax_hystogram[i])/float(tot)*100.)+'%)'+'\n')
-            else:
-                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
-    try:
-        if mesh.dt is not None:
-            totstat_file.write('='*70+'\n')
-            totstat_file.write('STABILITY')
-            totstat_file.write('='*70+'\n')
-            totstat_file.write('time step < '+str(mesh.dt)+'s, for velocity = '+str(mesh.velocity)+'\n')
-    except:
-        pass
-
-    if toclose: 
-        totstat_file.close()
-
-    print 'max specfem3d skewness: ',mesh.max_skewness
-    print 'min edge length: ',mesh.min_edge_length
-    return mesh.max_skewness,mesh.min_edge_length
\ No newline at end of file

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/read_parameter_cfg.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/read_parameter_cfg.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/read_parameter_cfg.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,330 +0,0 @@
-#############################################################################
-# read_parameter_cfg.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-import os
-
-def readcfg(filename=None,importmenu=False,mpiflag=False):
-    """
-    read the configuration file, filename is defined in the command line arguments (see menu.py)
-    """
-    if importmenu:
-        import menu as menu
-        cfgname=menu.cfg_name
-        id_proc=menu.id_proc
-        create_plane=menu.create_plane
-        menusurface=menu.surface
-        single=menu.single
-    elif filename:
-        cfgname=filename
-        id_proc=0
-        menu=False
-        create_plane=False
-        menusurface=False
-        single=False
-    else:
-        print 'error: no configuration file'
-        import sys
-        sys.exit()
-    #
-    from utilities import geo2utm #here I can use pyproj but I prefere to include a function in pure python in order to avoid an additional installation
-    #
-    #
-    import ConfigParser
-    config = ConfigParser.ConfigParser()
-    #
-    #
-    def converter(s):
-        if s == 'True':
-            value=True
-        elif s == 'False':
-            value=False
-        elif s == 'None':
-            value= None
-        else:
-            if s.count(',') != 0:
-                value=s.split(',')
-                while value.count(''):                
-                    value.remove('')
-            else:
-                value=s
-            try:
-                if type(value).__name__ == 'str':
-                    if str(value).count('.') != 0:
-                        value=float(value)
-                    else:
-                        value=int(value)
-                else:
-                    if str(value).count('.') != 0:
-                        value=map(float,value)
-                    else:
-                        value=map(int,value)
-            except:
-                pass
-        return value
-    #
-    def section_dict(section):
-        dict_o = {}
-        options = config.options(section)
-        for option in options:
-            try:
-                value=converter(config.get(section, option))
-                dict_o[option] = value
-            except:
-                dict_o[option] = None
-        return dict_o
-    
-    class attrdict(dict):
-        def __init__(self, *args, **kwargs):
-            dict.__init__(self, *args, **kwargs)
-            self.__dict__ = self
-        def __str__(self):
-            names=[]
-            values=[]
-            for name,value in self.items():
-                names.append(name)
-                values.append(value)
-            print names,values
-            a=zip(names,values)
-            a.sort()
-            arc=''
-            for o in a:
-                if o[0][0] != arc: print
-                print o[0],' -> ',o[1]
-                arc=o[0][0]
-            return '____'
-    
-    #
-    dcfg={}
-    #
-    #CONSTANTS
-    dcfg['osystem'] = 'linux'
-    dcfg['debug_cfg']=False
-    dcfg['checkbound']=False
-    dcfg['top_partitioner'] = 10000
-    dcfg['tres']=0.3 #if n is the vertical component of the normal at a surface pointing horizontally, when -tres < n < tres then the surface is vertical
-    dcfg['precision'] =0.02 #precision for the boundary check (0.02 m)
-    #
-    #INIT
-    dcfg['debug']=True 
-    dcfg['cubit_info']="on"
-    dcfg['echo_info']="on"
-    dcfg['jou_info']="on"
-    dcfg['jer_info']="on"
-    dcfg['monitored_cpu']=0
-    dcfg['parallel_import']=True
-    dcfg['save_geometry_cubit']=True
-    dcfg['save_surface_cubit']=False
-    dcfg['save_geometry_paraview'] = False #not implemented 
-    dcfg['save_geometry_ACIS'] = False #not implemented
-    dcfg['export_exodus_mesh']=False
-    dcfg['manual_adj']                  =False
-    dcfg['play_adj']                    =False
-    dcfg['no_adj']                      =False
-    dcfg['nx']=False
-    dcfg['ny']=False
-    dcfg['nstep']=False
-    dcfg['localdir_is_globaldir']=True
-    dcfg['refinement_depth']=[]
-    dcfg['scratchdir']=None
-    dcfg['map_meshing_type']='regularmap'
-    dcfg['4sideparallel']=True
-    dcfg["outlinebasin_curve"]=False
-    dcfg["transition_curve"]=False
-    dcfg["faulttrace_curve"]=False
-    dcfg['geological_imprint']=False
-    dcfg['number_processor_xi']=1
-    dcfg['number_processor_eta']=1
-    dcfg['filename']=None
-    dcfg['actual_vertical_interval_top_layer']=1
-    dcfg['coarsening_top_layer']=False
-    
-    
-    
-    
-    dcfg['nsurf'] = None
-    if cfgname:
-        config.read(cfgname)
-        sections=['cubit.options','simulation.cpu_parameters','geometry.surfaces','geometry.volumes','geometry.volumes.layercake','geometry.volumes.flatcake','geometry.volumes.partitioner','geometry.partitioner','meshing']
-        
-        
-        for section in sections:
-            try:
-                d=section_dict(section)
-                dcfg.update(d)
-            except:
-                pass
-                
-        if dcfg['nsurf']:
-           surface_name=[]
-           num_x=[]
-           num_y=[]
-           xstep=[]
-           ystep=[]
-           step=[]
-           directionx=[]
-           directiony=[]
-           unit2=[]
-           surf_type=[]
-           delimiter=[]
-           nsurf=int(dcfg['nsurf'])
-           for i in range(1,nsurf+1):
-               section='surface'+str(i)+'.parameters'
-               d=section_dict(section)
-               surface_name.append(d['name'])
-               surf_type.append(d['surf_type'])
-               unit2.append(d['unit_surf'])
-               if d['surf_type'] == 'regular_grid':
-                   xstep.append(d['step_along_x'])
-                   ystep.append(d['step_along_y'])
-                   num_x.append(d['number_point_along_x'])
-                   num_y.append(d['number_point_along_y'])
-               elif d['surf_type'] == 'skin':
-                   step.append(d['step'])
-                   try:
-                      delimiter.append(d['delimiter'])
-                   except:
-                      pass
-                   directionx.append(d['directionx'])
-                   directiony.append(d['directiony'])
-           dcfg['surface_name']=surface_name
-           dcfg['num_x']=num_x       
-           dcfg['num_y']=num_y       
-           dcfg['xstep']=xstep       
-           dcfg['ystep']=ystep       
-           dcfg['step']=step        
-           dcfg['directionx']=directionx  
-           dcfg['directiony']=directiony  
-           dcfg['unit2']=unit2       
-           dcfg['surf_type']=surf_type   
-           dcfg['delimiter']=delimiter  
-           
-        try:
-            tres=0
-            xmin,ymin=geo2utm(dcfg['longitude_min'],dcfg['latitude_min'],dcfg['unit'])
-            xmax,ymax=geo2utm(dcfg['longitude_max'],dcfg['latitude_max'],dcfg['unit'])
-            dcfg['xmin']=xmin
-            dcfg['ymin']=ymin
-            dcfg['xmax']=xmax
-            dcfg['ymax']=ymax
-            x1,y1=geo2utm(dcfg['longitude_min'],dcfg['latitude_min'],dcfg['unit'])
-            x2,y2=geo2utm(dcfg['longitude_max'],dcfg['latitude_min'],dcfg['unit'])
-            x3,y3=geo2utm(dcfg['longitude_max'],dcfg['latitude_max'],dcfg['unit'])
-            x4,y4=geo2utm(dcfg['longitude_min'],dcfg['latitude_max'],dcfg['unit'])
-            dcfg['x1_box']=x1
-            dcfg['y1_box']=y1
-            dcfg['x2_box']=x2
-            dcfg['y2_box']=y2
-            dcfg['x3_box']=x3
-            dcfg['y3_box']=y3
-            dcfg['x4_box']=x4
-            dcfg['y4_box']=y4
-            dcfg['tres_boundarydetection']=tres
-        except:
-            pass
-            
-    cfg=attrdict(dcfg)
-    
-    if menu:
-        try:
-            if cfg.working_dir[-1] == '/': cfg.working_dir=cfg.working_dir[:-1]
-            if cfg.working_dir[0] != '/': cfg.working_dir='./'+cfg.working_dir
-        except:
-            cfg.working_dir=os.getcwd()
-        
-        try:
-            if cfg.output_dir[-1] == '/': cfg.output_dir=cfg.output_dir[:-1]
-            if cfg.output_dir[0] != '/': cfg.output_dir='./'+cfg.output_dir
-        except:
-            cfg.output_dir=os.getcwd()
-        
-        try:
-            if cfg.SPECFEM3D_output_dir[-1] == '/': cfg.SPECFEM3D_output_dir=cfg.SPECFEM3D_output_dir[:-1]
-            if cfg.SPECFEM3D_output_dir[0] != '/': cfg.SPECFEM3D_output_dir='./'+cfg.SPECFEM3D_output_dir
-        except:
-            cfg.SPECFEM3D_output_dir=os.getcwd()
-        
-        cfg.single=single
-        
-        if menusurface:
-            cfg.nsurf=1
-            cfg.name=[menu.surface_name]
-            cfg.num_x=[menu.num_x]
-            cfg.num_y=[menu.num_x]
-            cfg.unit=[menu.unit]
-            cfg.surf_type=[menu.surf_type]
-            try:
-                cfg.delimiter=[menu.delimiter]
-            except:
-                cfg.delimiter=[' ']
-            cfg.directionx=[menu.directionx]
-            cfg.directiony=[menu.directiony]
-    else:
-        cfg.SPECFEM3D_output_dir=os.getcwd()
-        
-        
-    if not cfg.number_processor_eta and cfg.nodes:
-        cfg.number_processor_xi,cfg.number_processor_eta=split(cfg.nodes)
-        
-    if isinstance(cfg.filename,str): cfg.filename=[cfg.filename]
-    
-    try:
-        cfg.nproc_eta=cfg.number_processor_eta
-        cfg.nproc_xi=cfg.number_processor_xi
-        cfg.cpuy=cfg.number_processor_eta
-        cfg.cpux=cfg.number_processor_xi
-    except:
-        pass
-    
-    if create_plane:
-        cfg.x1=map(float,menu.x1.split(','))
-        cfg.x2=map(float,menu.x2.split(','))
-        cfg.x3=map(float,menu.x3.split(','))
-        cfg.x4=map(float,menu.x4.split(','))
-        cfg.unit=menu.unit
-    #
-    if menu:
-        cfg.id_proc=menu.id_proc
-    else:
-        cfg.id_proc=id_proc
-    #
-    try:
-        if isinstance(cfg.tripl,int): cfg.tripl=[cfg.tripl]
-    except:
-        pass
-        
-        
-    return cfg
-
-
-class getparameter(dict): 
-    def __init__(self, *args, **kwargs):
-        dict.__init__(self, *args, **kwargs)
-        self.__dict__ = self
-
-
-def split(x):
-    import math
-    c=int(math.sqrt(x))
-    while math.fmod(x,c):
-        c=c+1
-    return c,x/c
\ No newline at end of file

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/save_fault_nodes_elements.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/save_fault_nodes_elements.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/save_fault_nodes_elements.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,84 +0,0 @@
-#!python
-# Opening fault cracks
-# Input : surface up and down.
-import cubit 
-
-class fault_input:
-   def __init__(self,id,surface_u,surface_d): 
-       self.id = id
-       self.surface_u = surface_u
-       self.surface_d = surface_d
-       self.name = 'MESH/fault_file_'+str(id)+'.dat'
-
-       quads_Aup,quads_Adp = save_cracks(self.name,self.surface_u,self.surface_d)
-       #Unpacking list.
-       quads_Au=unpack_list(quads_Aup)
-       quads_Ad=unpack_list(quads_Adp)
-
-       print 'len(Au):',len(quads_Au)
-       print 'len(Ad):',len(quads_Ad)
-
-       if not (len(quads_Au)==len(quads_Ad)):
-           print 'Number of elements for each fauld side up and down do not concide'
-           sys.exit('goodbye')
-           
-       save_elements_nodes(self.name,quads_Au,quads_Ad)
-
-
-def save_cracks(name,list_surface_up,list_surface_down):
-   quads_fault_up = [] 
-   quads_fault_down = []
-   for surface in list_surface_up   :
-       quads_fault = cubit.get_surface_quads(surface)
-       quads_fault_up.append(quads_fault)
-   for surface in list_surface_down :
-       quads_fault = cubit.get_surface_quads(surface)
-       quads_fault_down.append(quads_fault)
-    # TO DO : stop python properly in case fault nodes at both sides
-    #         do not match.
-    #   if len(quads_fault_u) != len(quads_fault_d): stop
-    #
-    # SAVING FAULT ELEMENTS AND NODES
-   return quads_fault_up,quads_fault_down
-
-def unpack_list(fault_list):
-    list_fault = []
-    for i in range(0,len(fault_list)):
-        el=list(fault_list[i])
-        for j in el:
-            list_fault.append(j)
-    return list_fault 
-          
-def save_elements_nodes(name,quads_fault_u,quads_fault_d):
-   fault_file = open(name,'w')
-   txt =''
-   list_hex=cubit.parse_cubit_list('hex','all')
-   txt='%10i %10i\n' % (len(quads_fault_u),len(quads_fault_d))
-   fault_file.write(txt)
-   
-   dic_quads_fault_u = dict(zip(quads_fault_u,quads_fault_u)) 
-   dic_quads_fault_d = dict(zip(quads_fault_d,quads_fault_d)) 
-   
-   # FAULT SIDE DOWN
-   for h in list_hex: 
-       faces = cubit.get_sub_elements('hex',h,2)  
-       for f in faces:
-           if dic_quads_fault_d.has_key(f): 
-              nodes=cubit.get_connectivity('Face',f)
-   #           print 'h,fault nodes side down :',h,nodes[0],nodes[1],nodes[2],nodes[3]
-              txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\
-                                                nodes[1],nodes[2],nodes[3])
-              fault_file.write(txt)
-
-   # FAULT SIDE UP
-   for h in list_hex: 
-       faces = cubit.get_sub_elements('hex',h,2)  
-       for f in faces:
-           if dic_quads_fault_u.has_key(f): 
-              nodes=cubit.get_connectivity('Face',f)
-   #           print 'h,fault nodes side up :',h,nodes[0],nodes[1],nodes[2],nodes[3]
-              txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\
-                                                nodes[1],nodes[2],nodes[3])
-              fault_file.write(txt)
-
-   fault_file.close()

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/setup.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/setup.py	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/setup.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,13 @@
+from distutils.core import setup
+import glob
+
+setup(name='GEOCUBIT',
+      version='3',
+      description='CUBIT plugin',
+      author='emanuele casarotti',
+      author_email='emanuele.casarotti at ingv.it',
+      url='',
+      packages=['','geocubitlib'],
+      scripts=['GEOCUBIT.py']
+)
+

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/start.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/start.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/start.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,166 +0,0 @@
-#############################################################################
-# start.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-#
-#
-#
-#method to call the library
-
-def start_mpi():
-    """ 
-    start mpi, fakempi mimick the mpi function when the run is serial. The object mpi is based upon pyMPI.
-    it returns: mpiflag,iproc,numproc,mpi
-    where 
-        mpiflag is True if parallel mesh is on 
-        iproc is the id of the processor (0 if the run is serial)
-        numproc is the number of the processor (1 if the run is serial)
-        mpi is the mpi object
-    """
-    import sys
-    try:
-        import menu as menu
-        iproc=menu.id_proc
-    except:
-        iproc=0
-    try:
-        import mpi
-        numproc=mpi.size
-        mpiflag=True
-        if numproc == 1:
-            mpiflag=False
-        else:
-            iproc=mpi.rank
-    except:
-        class fakempi(object):
-            def __init__(self):
-                self.size=1
-                self.rank=0
-            def barrier(self):
-                pass
-            def allgather(self,value):
-                return value
-            def gather(self,value):
-                return value
-            def bcast(self,value):
-                return value
-            def scatter(self,value):
-                return value
-            def send(self,value,values):
-                return
-            def recv(self,value):
-                return value,value
-        mpi=fakempi()
-        numproc=1
-        mpiflag=False
-    return mpiflag,iproc,numproc,mpi
-
-def start_cubit(init=False):
-    """ 
-    start cubit, it return the cubit object
-    init argument set the monitotr files
-    """
-    import sys,os
-    try:
-        cubit.silent_cmd('comment')
-    except:
-        try:
-            import cubit
-            cubit.init([""])
-        except:
-            print 'error importing cubit'
-            sys.exit()
-        try:
-            if init:
-                from start import start_cfg,start_mpi
-                cfg=start_cfg()
-                mpiflag,iproc,numproc,mpi   = start_mpi()
-                cubit.cmd('set logging on file "'+cfg.working_dir+'/cubit_proc_'+str(iproc)+'.log"')
-                cubit.cmd("set echo off")
-                cubit.cmd("set info off")
-                if iproc == cfg.monitored_cpu:
-                    cubit.cmd("record '"+cfg.working_dir+"/monitor_"+str(cfg.monitored_cpu)+".jou'")
-                    cubit.cmd("set journal on")
-                    cubit.cmd("journal error on")
-                    d=cfg.__dict__
-                    ks=d.keys()
-                    ks.sort()
-                    for k in ks:
-                        if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
-                            txt=str(k)+' -----> '+str(d[k])
-                            txt=txt.replace("'","").replace('"','')
-                            cubit.cmd('comment "'+txt+'"')
-                else:
-                    cubit.cmd("set journal "+cfg.jou_info)
-                    cubit.cmd("journal error "+cfg.jer_info)
-                    d=cfg.__dict__
-                    ks=d.keys()
-                    ks.sort()
-                    for k in ks:
-                        if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
-                            txt=str(k)+' -----> '+str(d[k])
-                            txt=txt.replace("'","").replace('"','')
-                            cubit.cmd('comment "'+txt+'"')
-                cubit.cmd("set echo "+cfg.echo_info)
-                cubit.cmd("set info "+cfg.cubit_info)
-        except:
-            print 'error start cubit'
-            sys.exit()
-    return cubit
-
-def start_cfg(filename=None,importmenu=True):
-    """
-    return the object cfg with the parameters of the mesh
-    """
-    import read_parameter_cfg
-    mpiflag,iproc,numproc,mpi=start_mpi()
-    if filename: importmenu=False 
-    cfg=read_parameter_cfg.readcfg(filename=filename,importmenu=importmenu,mpiflag=mpiflag)
-    import os
-    try:
-        os.makedirs(cfg.working_dir)
-    except OSError:
-        pass
-    try:
-        os.makedirs(cfg.output_dir)
-    except OSError:
-        pass
-    try:
-         os.makedirs(cfg.SPECFEM3D_output_dir)
-    except OSError:
-         pass
-    
-    return cfg
-
-def start_numpy():
-    """
-    import numpy and check if it is installed
-    """
-    import sys
-    try:
-        import numpy
-    except:
-        print 'error importing numpy, please check if numpy is correctly installed'
-        sys.exit()
-    return numpy
-
-    
\ No newline at end of file

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/surfaces.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/surfaces.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/surfaces.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,308 +0,0 @@
-#############################################################################
-# surfaces.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-
-def surfaces(filename=None):
-    """creating the surfaces defined in the parameter files
-       #
-       nsurf = number of surfaces
-       surf_type = list of stype of method for the creation of the surface
-                   -- regulare_grid (u and v lines)
-                   -- skin (u lines)       
-    """
-    #
-    import start as start
-    cfg                     = start.start_cfg(filename=filename)
-    #
-    #
-    for isurface in range(0,cfg.nsurf):
-        surf_type=cfg.surf_type[isurface]
-        if surf_type == 'regular_grid':
-            surface_regular_grid(isurface,cfgname=filename)
-        elif surf_type == 'skin':
-            surface_skin(isurface,cfgname=filename)
-
-def surface_regular_grid(isurface=0,cfgname=None):
-    """
-    create an acis surface from a regular lon/lat/z grid
-    """
-    import sys,os
-    from math import sqrt
-    from utilities import geo2utm
-    import start as start
-    #
-    #
-    cfg                     = start.start_cfg(cfgname)
-    numpy                   = start.start_numpy()
-    #
-    def create_line_u(ind,n,step,data,unit):
-        last_curve_store=cubit.get_last_id("curve")
-        command='create curve spline '
-        for i in range(0,n):
-            if i%step == 0:
-                lon,lat,z=data[i+ind][0],data[i+ind][1],data[i+ind][2]
-                x,y=geo2utm(lon,lat,unit)
-                txt=' Position ' +   str(x)  +' '+  str(y) +' '+  str(z)
-                command=command+txt
-                #print command
-        cubit.silent_cmd(command)
-        last_curve=cubit.get_last_id("curve")
-        if last_curve != last_curve_store:
-            return last_curve
-        else:
-            return 0
-    
-    def create_line_v(ind,n,n2,step,data,unit):
-        last_curve_store=cubit.get_last_id("curve")
-        command='create curve spline '
-        for i in range(0,n):
-            if i%step == 0:
-                lon,lat,z=data[n2*i+ind][0],data[n2*i+ind][1],data[n2*i+ind][2]
-                x,y=geo2utm(lon,lat,unit)
-                txt=' Position ' +   str(x)  +' '+  str(y) +' '+  str(z)
-                command=command+txt
-                #print command
-        cubit.silent_cmd(command)
-        last_curve=cubit.get_last_id("curve")
-        if last_curve != last_curve_store:
-            return last_curve
-        else:
-            return 0
-    #
-    #
-    cubit.cmd("reset")
-    #
-    position=True
-    #
-    #
-    nu= cfg.num_x[isurface]
-    nv= cfg.num_y[isurface]
-    ustep= cfg.xstep[isurface]
-    vstep= cfg.ystep[isurface]
-    exag=1.
-    unit=cfg.unit2[isurface]
-    #
-    #
-    data=numpy.loadtxt(cfg.surface_name[isurface])
-    if len(data) > 100:
-        command = "set echo off"
-        cubit.cmd(command)
-        command = "set journal off"
-        cubit.cmd(command)
-    #
-    u_curve=[]
-    v_curve=[]
-    #
-    for iv in range(0,nv):
-        if iv%vstep == 0.:
-            u=create_line_u(iv*(nu),nu,ustep,data,unit)
-            u_curve.append(u)
-    for iu in range(0,nu):
-        if iu%ustep == 0.:
-            v=create_line_v(iu,nv,nu,ustep,data,unit)
-            v_curve.append(v)
-    #
-    umax=max(u_curve)
-    umin=min(u_curve)
-    vmax=max(v_curve)
-    vmin=min(v_curve)
-    cubitcommand= 'create surface net u curve '+ str( umin )+' to '+str( umax )+ ' v curve '+ str( vmin )+ ' to '+str( vmax )+' heal'
-    cubit.cmd(cubitcommand)
-    command = "del curve all"
-    cubit.cmd(command)
-    suff=cfg.surface_name[isurface].split('/')
-    command = "save as '"+cfg.working_dir+"/surf_"+suff[-1]+".cub' overwrite"
-    cubit.cmd(command)
-    #
-    #
-    #        
-    cubit.cmd("set info "+cfg.cubit_info)
-    cubit.cmd("set echo "+cfg.echo_info)
-    cubit.cmd("set journal "+cfg.jou_info)
-
-def surface_skin(isurface=0,cfgname=None):
-    """
-    create an acis surface interpolating no-intersecting lines
-    """
-    import sys,os
-    from math import sqrt
-    from utilities import geo2utm
-    import start as start
-    #
-    #
-    cubit                   = start.start_cubit()
-    cfg                     = start.start_cfg(cfgname)
-    #
-    def define_next_line(directionx,directiony,n,data):
-        ndata=len(data)
-        command=''
-        ind=n
-        try:
-            record=data[ind]
-        except:
-            return False,False
-        try:
-            x,y,z=map(float,record.split())
-        except:
-            return False,False
-        txt=' Position ' +   record
-        command=command+txt
-        x_store,y_store,z_store = x,y,z
-        icount=1
-        while True:
-                    ind+=1
-                    if ind >= ndata: return ind,command
-                    record=data[ind]
-                    try:
-                        x,y,z=map(float,record.split())
-                    except:
-                        return ind,command
-                    dx,dy = x-x_store,y-y_store        
-                    if  directionx == 0 and dy/abs(dy) * directiony >= 0:
-                        txt=' Position ' +   record
-                        command=command+txt
-                        icount+=1
-                        x_store,y_store,z_store = x,y,z
-                    elif  directiony == 0 and dx/abs(dx) == directionx :
-                        txt=' Position ' +   record
-                        command=command+txt
-                        icount+=1
-                        x_store,y_store,z_store = x,y,z
-                    else:
-                        if icount==1:
-                           x,y,z=x_store+1e-4*directionx,y_store+1e-4*directiony,z_store
-                           txt=' Position ' +str(x)+ ' '+str(y)+ ' '+str(z)
-                           command=command+txt
-                        return ind,command    
-    def create_line(position):
-        if position:
-            last_curve_store=cubit.get_last_id("curve")
-            command='create curve spline '+position
-            cubit.silent_cmd(command)
-            last_curve=cubit.get_last_id("curve")
-            if last_curve != last_curve_store:
-                return last_curve
-            else:
-                return False
-        else:
-            return False
-                        
-    command = "reset"
-    cubit.cmd(command)
-    #
-    position=True
-    #
-    try:
-         grdfile = open(cfg.surface_name[isurface], 'r')
-    except:
-         raise NameError, 'No such file or directory: '+  str( cfg.surface_name[isurface] )
-    #
-    directionx=cfg.directionx[isurface]
-    directiony=cfg.directiony[isurface]
-    step=cfg.step[isurface]
-    position=True
-    curveskin=[]
-    count_line=0
-    data=grdfile.read().split('\n')
-    ndata=len(data)
-    n=0
-    #
-    #
-    command = "set echo off"
-    cubit.cmd(command)
-    command = "set journal off"
-    cubit.cmd(command)
-    command = "set info off"
-    cubit.cmd(command)         
-    #
-    while position:
-          index,position=define_next_line(directionx,directiony,n,data)
-          if n%step == 0:
-              curve=create_line(position)
-              if curve: curveskin.append(curve)
-          elif n%step != 0 and not position:
-              curve=create_line(position)
-              if curve: curveskin.append(curve)
-          n=index
-    umax=max(curveskin)
-    umin=min(curveskin)
-    print 'create surface skin curve '+ str( umin )+' to '+str( umax )
-    cubitcommand= 'create surface skin curve '+ str( umin )+' to '+str( umax )
-    cubit.cmd(cubitcommand)
-    command = "del curve all"
-    cubit.cmd(command)
-    last_surface=cubit.get_last_id("surface")
-    command = "regularize surf "+str(last_surface)
-    cubit.cmd(command)
-    #
-    suff=cfg.surface_name[isurface].split('/')
-    command = "save as '"+cfg.working_dir+"/surf_"+suff[-1]+".cub' overwrite"
-    cubit.cmd(command)
-    #
-    #
-    #        
-    cubit.cmd("set info "+cfg.cubit_info)
-    cubit.cmd("set echo "+cfg.echo_info)
-    cubit.cmd("set journal "+cfg.jou_info)
-    
-    
-def plane(cfg):
-    import sys,os
-    from math import sqrt
-    from utilities import geo2utm
-    import start as start
-    #
-    #
-    cubit                   = start.start_cubit()
-    #
-    #
-    command = "reset"
-    cubit.cmd(command)
-    #
-    #
-    for p in [cfg.x1,cfg.x2,cfg.x3,cfg.x4]:
-        x_current,y_current=geo2utm(p[0],p[1],cfg.unit)
-        cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( p[2] )
-        cubit.cmd(cubitcommand)
-    #
-    cubitcommand= 'create surface vertex 1 2 3 4'
-    cubit.cmd(cubitcommand)
-    command = "del vertex all"
-    cubit.cmd(command)
-    command = "save as 'plane.cub' overwrite"
-    cubit.cmd(command)
-    #
-    #
-    #        
-    cubit.cmd("set info "+cfg.cubit_info)
-    cubit.cmd("set echo "+cfg.echo_info)
-    cubit.cmd("set journal "+cfg.jou_info)
\ No newline at end of file

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utilities.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utilities.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utilities.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,427 +0,0 @@
-#############################################################################
-# utilities.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-
-
-
-
-def snapshot(name=None,i=0,viewnumber=1):
-    """
-    it takes a snapshot of the figure, following the predefined view position.
-    view 1: vector 1 1 1 z up
-    """
-    if name is None:
-        name='snapshot_'+str(i)
-    i=i+1
-    if viewnumber == 1:
-        command = "at 0"
-        cubit.cmd(command)
-        command = "from 1 1 1"
-        cubit.cmd(command)
-        command = "up 0 0 1"
-        cubit.cmd(command)
-    cubit.cmd('graphics autocenter on')
-    cubit.cmd("zoom reset")
-    command = "hardcopy '"+name+".png' png"
-    cubit.cmd(command)
-    return i
-
-def cubit_error_stop(iproc,command,ner):
-    er=cubit.get_error_count()
-    if er > ner: 
-       text='"Proc: '+str(iproc)+' ERROR '+str(command)+' number of error '+str(er)+'/'+str(ner)+'"'
-       cubitcommand = 'comment '+text
-       cubit.cmd(cubitcommand)
-       raise NameError, text
-
-def cubit_error_continue(iproc,command,n_er):
-    er=cubit.get_error_count()
-    if  er >= n_er: 
-        text='"Proc: '+str(iproc)+' ERROR continue '+str(command)+' number of error '+str(er)+' '+str(n_er)+'"'
-        cubit.cmd('comment '+ text)
-        print 'error: ',text
-    return er
-    
-def savemesh(mpiflag,iproc=0,filename=None):
-    import start as start
-    cfg                         = start.start_cfg(filename=filename)
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    
-    def runsave(meshfile,iproc,filename=None):
-        import start as start
-        cubit                   = start.start_cubit()
-        cfg                         = start.start_cfg(filename=filename)
-        flag=0
-        ner=cubit.get_error_count()
-        cubitcommand= 'save as "'+ cfg.output_dir+'/'+meshfile+'.cub'+ '" overwrite' 
-        cubit.cmd(cubitcommand)
-        ner2=cubit.get_error_count()
-        if ner == ner2:
-            cubitcommand= 'export mesh "'+ cfg.output_dir+'/'+meshfile+'.e'+ '" dimension 3 block all overwrite' 
-            cubit.cmd(cubitcommand)
-            ner2=cubit.get_error_count()                                                    
-        if ner == ner2:
-            flag=1
-        return flag
-    
-    
-    meshfile='mesh_vol_'+str(iproc)
-    
-    flagsaved=0
-    infosave=(iproc,flagsaved)
-    
-    mpi.barrier()
-    total_saved=mpi.allgather(flagsaved)
-    if isinstance(total_saved,int): total_saved=[total_saved]
-    
-    ind=0
-    saving=True
-    while saving:
-        if len(total_saved) != sum(total_saved):
-            #
-            if not flagsaved: 
-                flagsaved=runsave(meshfile,iproc,filename=filename)
-                if flagsaved:
-                    infosave=(iproc,flagsaved)        
-                    if numproc > 1:
-                        f=open('mesh_saved'+str(iproc),'w')
-                        f.close()
-            mpi.barrier()
-            total_saved=mpi.allgather(flagsaved)
-            if isinstance(total_saved,int): total_saved=[total_saved]
-            ind=ind+1
-        else:
-            saving=False
-        if ind > len(total_saved)+10: saving=False
-        print sum(total_saved),'/',len(total_saved),' saved'
-    
-    info_total_saved=mpi.allgather(infosave)
-    if isinstance(info_total_saved,int): info_total_saved=[info_total_saved]
-    
-    if iproc==0:
-        f=open('mesh_saving.log','w')
-        f.write('\n'.join(str(x) for x in info_total_saved))                
-        f.close()                           
-            
-    f=open(cfg.output_dir+'/'+'blocks_'+str(iproc).zfill(5),'w')
-    blocks=cubit.get_block_id_list()
-    
-    for block in blocks:
-        name=cubit.get_exodus_entity_name('block',block)
-        element_count = cubit.get_exodus_element_count(block, "block")
-        nattrib=cubit.get_block_attribute_count(block)
-        attr=[cubit.get_block_attribute_value(block,x) for x in range(0,nattrib)]
-        ty=cubit.get_block_element_type(block)
-        f.write(str(block)+' ; '+name+' ; nattr '+str(nattrib)+' ; '+' '.join(str(x) for x in attr)+' ; '+ty+' '+str(element_count)+'\n')
-    f.close()
-    
-    import quality_log
-    f=open(cfg.output_dir+'/'+'quality_'+str(iproc).zfill(5),'w')
-    max_skewness,min_length=quality_log.quality_log(f)
-    f.close()
-    
-    
-    count_hex=[cubit.get_hex_count()]
-    count_node=[cubit.get_node_count()]
-    max_skew=[(iproc,max_skewness)]
-    min_l=[(iproc,min_length)]
-    
-    mpi.barrier()
-    total_min_l=mpi.gather(min_l)
-    total_hex=mpi.gather(count_hex)        
-    total_node=mpi.gather(count_node)      
-    total_max_skew=mpi.gather(max_skew)    
-    
-    
-    mpi.barrier()                          
-    if iproc == 0:
-        min_total_min_l=min([ms[1] for ms in total_min_l])
-        max_total_max_skew=max([ms[1] for ms in total_max_skew])
-        sum_total_node=sum(total_node)
-        sum_total_hex=sum(total_hex)
-        
-        totstat_file=open(cfg.output_dir+'/totstat.log','w')
-        text='hex total number,node total number,max skew, min length\n'
-        totstat_file.write(text)
-        
-        text=str(sum_total_hex)+' , '+str(sum_total_node)+' , '+str(max_total_max_skew)+' , '+str(min_total_min_l)+'\n'
-        totstat_file.write(text)
-        
-        totstat_file.write(str(total_max_skew))    
-        totstat_file.close()
-    
-    print 'meshing process end... proc ',iproc 
-
-def importgeometry(geometryfile,iproc=0,filename=None):
-    import start as start
-    cfg                         = start.start_cfg(filename=filename)
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    
-    if iproc == 0: print 'importing geometry....'
-    a=['ok from '+str(iproc)]
-    
-    mpi.barrier()
-    total_a=mpi.allgather(a)
-    if iproc == 0: print total_a
-    
-    def runimport(geometryfile,iproc,filename=None):
-        import start as start
-        cubit                   = start.start_cubit()
-        cfg                         = start.start_cfg(filename=filename)
-        file1=cfg.output_dir+'/'+geometryfile
-        cubitcommand= 'open "'+ file1+ '"  ' 
-        cubit.cmd(cubitcommand)                
-        
-    if cfg.parallel_import:
-        runimport(geometryfile,iproc,filename=filename)
-    else:
-        if iproc == 0:
-            runimport(geometryfile,iproc,filename=filename)
-            for i in range(1,mpi.size):
-                mpi.send('import',i)
-                msg,status=mpi.recv(i)
-        else:
-            msg,status=mpi.recv(0)
-            runimport(geometryfile,iproc,filename=filename)
-            mpi.send('ok'+str(iproc),0)
-
-        
-def savesurf(iproc=0):
-    savegeometry(iproc=iproc,surf=True)
-    
-###################################################################################### BELOW OK
-    
-def load_curves(acis_filename):
-    """
-    load the curves from acis files
-    """
-    import os
-    #
-    #
-    print acis_filename
-    if acis_filename and os.path.exists(acis_filename):
-        tmp_curve=cubit.get_last_id("curve")
-        command = "import acis '"+acis_filename+"'"
-        cubit.cmd(command)
-        tmp_curve_after=cubit.get_last_id("curve")
-        curves=' '.join(str(x) for x in range(tmp_curve+1,tmp_curve_after+1))
-    elif not os.path.exists(acis_filename):
-        print str(acis_filename)+' not found'
-        curves=None
-    return [curves]
-
-def project_curves(curves,top_surface):
-    """
-    project curves on surface
-    """
-    if not isinstance(curves,list): curves=curves.split()
-    tmpc=[]
-    for curve in curves:
-        command = "project curve "+str(curve)+" onto surface "+str(top_surface)
-        cubit.cmd(command)
-        tmp_curve_after=cubit.get_last_id("curve")
-        tmpc.append(tmp_curve_after)
-        command = "del curve "+str(curve)
-        cubit.cmd(command)
-    return tmpc
-    
-def geo2utm(lon,lat,unit,ellipsoid=23):
-    """conversion geocoodinates from geographical to utm
-    
-    usage: x,y=geo2utm(lon,lat,unit,ellipsoid=23)
-    
-    dafault ellipsoid is 23 = WGS-84, 
-        ellipsoid:
-        1, "Airy"
-        2, "Australian National"
-        3, "Bessel 1841"
-        4, "Bessel 1841 (Nambia] "
-        5, "Clarke 1866"
-        6, "Clarke 1880"
-        7, "Everest"
-        8, "Fischer 1960 (Mercury] "
-        9, "Fischer 1968"
-        10, "GRS 1967"
-        11, "GRS 1980"
-        12, "Helmert 1906"
-        13, "Hough"
-        14, "International"
-        15, "Krassovsky"
-        16, "Modified Airy"
-        17, "Modified Everest"
-        18, "Modified Fischer 1960"
-        19, "South American 1969"
-        20, "WGS 60"
-        21, "WGS 66"
-        22, "WGS-72"
-        23, "WGS-84"
-        
-    unit:  'geo' if the coordinates of the model (lon,lat) are geographical
-           'utm' if the coordinates of the model (lon,lat) are utm
-           
-    x,y: the function return the easting, northing utm coordinates 
-    """
-    import LatLongUTMconversion
-    if unit == 'geo' :          
-       (zone, x, y) = LatLongUTMconversion.LLtoUTM(ellipsoid, lat, lon)
-    elif unit == 'utm' : 
-       x=lon
-       y=lat
-    return x,y
-
-
-def savegeometry(iproc=0,surf=False,filename=None):
-    import start as start
-    cfg                         = start.start_cfg(filename=filename)
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    
-    def runsave(geometryfile,iproc,filename=None):
-        import start as start
-        cubit                   = start.start_cubit()
-        cfg                         = start.start_cfg(filename=filename)
-        flag=0
-        ner=cubit.get_error_count()
-        cubitcommand= 'save as "'+ cfg.output_dir+'/'+geometryfile+ '"  overwrite' 
-        cubit.cmd(cubitcommand)                                                    
-        ner2=cubit.get_error_count()                                             
-        if ner == ner2:
-            flag=1
-        return flag
-        
-    if surf:
-        geometryfile='surf_vol_'+str(iproc)+'.cub'
-    else:
-        geometryfile='geometry_vol_'+str(iproc)+'.cub'
-        
-    flagsaved=0
-    infosave=(iproc,flagsaved)
-    
-    mpi.barrier()
-    total_saved=mpi.allgather(flagsaved)
-    if isinstance(total_saved,int): total_saved=[total_saved]
-    
-    ind=0
-    saving=True
-    while saving:
-        if len(total_saved) != sum(total_saved):
-            #
-            if not flagsaved: 
-                flagsaved=runsave(geometryfile,iproc,filename=filename)
-                if flagsaved:
-                    infosave=(iproc,flagsaved)        
-                    if numproc > 1:
-                        f=open('geometry_saved'+str(iproc),'w')
-                        f.close()
-            mpi.barrier()
-            total_saved=mpi.allgather(flagsaved)
-            if isinstance(total_saved,int): total_saved=[total_saved]
-            ind=ind+1
-        else:
-            saving=False
-        if ind > len(total_saved)+10: saving=False
-        print sum(total_saved),'/',len(total_saved),' saved'
-    
-    info_total_saved=mpi.allgather(infosave)
-    if isinstance(info_total_saved,int): info_total_saved=[info_total_saved]
-    
-    if iproc==0:
-        f=open('geometry_saving.log','w')
-        f.write('\n'.join(str(x) for x in info_total_saved))                
-        f.close()
-
-
-def get_v_h_list(vol_id_list):
-    """return the lists of the cubit ID of vertical/horizontal surface and vertical/horizontal curves
-    where v/h is defined by the distance of the z normal component from the axis direction
-    the parameter cfg.tres is the threshold as for example if 
-    normal[2] >= -tres and normal[2] <= tres 
-    then the surface is vertical
-    #
-    usage: surf_or,surf_vertical,list_curve_or,list_curve_vertical,bottom,top = get_v_h_list(list_vol)
-    """
-    #
-    tres=0.3
-    
-    try:
-        nvol=len(vol_id_list)
-    except:
-        nvol=1
-        vol_id_list=[vol_id_list]
-    surf_vertical=[]
-    surf_or=[]
-    list_curve_vertical=[]
-    list_curve_or=[]
-    #
-    #
-    for id_vol in vol_id_list:
-        lsurf=cubit.get_relatives("volume",id_vol,"surface")
-        for k in lsurf:
-            normal=cubit.get_surface_normal(k)
-            center_point = cubit.get_center_point("surface", k)
-            if normal[2] >= -1*tres and normal[2] <= tres:
-               surf_vertical.append(k)
-               lcurve=cubit.get_relatives("surface",k,"curve")
-               list_curve_vertical=list_curve_vertical+list(lcurve)                                                                                                          
-            else:
-                surf_or.append(k)
-                lcurve=cubit.get_relatives("surface",k,"curve")
-                list_curve_or=list_curve_or+list(lcurve)
-    for x in list_curve_or:
-        try:
-            list_curve_vertical.remove(x)
-        except:
-            pass
-    k=surf_or[0]
-    center_point = cubit.get_center_point("surface", k)[2]
-    center_point_top=center_point
-    center_point_bottom=center_point
-    top=k
-    bottom=k 
-    for k in surf_or[1:]:
-        center_point = cubit.get_center_point("surface", k)[2]
-        if center_point > center_point_top:
-            center_point_top=center_point
-            top=k
-        elif center_point < center_point_bottom:
-            center_point_bottom=center_point
-            bottom=k
-    surftop=list(cubit.get_adjacent_surfaces("surface", top))
-    for s in surf_vertical:
-        try:                          
-            surftop.remove(s)    
-        except:                       
-            pass                      
-    top=surftop
-    bottom=[bottom]
-    return surf_or,surf_vertical,list_curve_or,list_curve_vertical,bottom,top
-
-

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/jq.sh
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/jq.sh	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/jq.sh	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,8 @@
+#!/bin/sh -f
+#PBS -N GEOCUBIT
+#PBS -o joba.log
+#PBS -l walltime=2:0:0
+#PBS -m abe -M emanuele.casarotti at ingv.it
+#PBS -j oe
+cd /home/casarotti/geocubit4
+python GEOCUBIT.py --mesh --build_volume --cfg='/home/casarotti/geocubit4/example/abruzzo.cfg' --id_proc=${PBS_ARRAY_INDEX} > ${PBS_ARRAY_INDEX}.log

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/jq_single.sh
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/jq_single.sh	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/jq_single.sh	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,8 @@
+#!/bin/sh -f
+#PBS -N GEOCUBIT
+#PBS -o joba.log
+#PBS -l walltime=2:0:0
+#PBS -m abe -M emanuele.casarotti at ingv.it
+#PBS -j oe
+cd /home/casarotti/geocubit4
+python GEOCUBIT.py --mesh --build_volume --cfg='/home/casarotti/geocubit4/example/abruzzo_single.cfg' --id_proc=${PBS_ARRAY_INDEX} > ${PBS_ARRAY_INDEX}.log

Added: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/run.sh
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/run.sh	                        (rev 0)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/run.sh	2013-09-20 17:32:11 UTC (rev 22807)
@@ -0,0 +1,12 @@
+#!/bin/sh -f
+#PBS -N GEOCUBIT
+#PBS -o run.log
+#PBS -l select=1:ncpus=1
+#PBS -l place=free
+#PBS -l walltime=46:0:0
+#PBS -m abe -M emanuele.casarotti at ingv.it
+#PBS -j oe
+
+
+cd $PBS_O_WORKDIR
+python2.5 ./GEOCUBIT.py --collect --merge --meshfiles='/lscratch/users/casarotti/cal/SCAL_LR/mesh*.e' --cpux=15 --cpuy=15


Property changes on: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/utility/run.sh
___________________________________________________________________
Added: svn:executable
   + *

Deleted: seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/volumes.py
===================================================================
--- seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/volumes.py	2013-09-20 17:28:21 UTC (rev 22806)
+++ seismo/3D/SPECFEM3D/trunk/CUBIT_GEOCUBIT/volumes.py	2013-09-20 17:32:11 UTC (rev 22807)
@@ -1,551 +0,0 @@
-#############################################################################
-# volumes.py                                                    
-# this file is part of GEOCUBIT                                             #
-#                                                                           #
-# Created by Emanuele Casarotti                                             #
-# Copyright (c) 2008 Istituto Nazionale di Geofisica e Vulcanologia         #
-#                                                                           #
-#############################################################################
-#                                                                           #
-# GEOCUBIT 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.                                       #
-#                                                                           #
-# GEOCUBIT 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 GEOCUBIT.  If not, see <http://www.gnu.org/licenses/>.         #
-#                                                                           #
-#############################################################################
-try:
-    import start as start
-    cubit                   = start.start_cubit()
-except:
-    try:
-        import cubit
-    except:
-        print 'error importing cubit, check if cubit is installed'
-        pass
-
-    
-def volumes(filename=None):
-    """create the volumes"""
-    import start as start
-    print'volume'
-    cfg                     = start.start_cfg(filename=filename)
-    #
-    if cfg.volume_type == 'layercake_volume_ascii_regulargrid_regularmap':
-            layercake_volume_ascii_regulargrid_mpiregularmap(filename=filename)
-    elif cfg.volume_type == 'layercake_volume_fromacis_mpiregularmap':
-            layercake_volume_fromacis_mpiregularmap(filename=filename)
-
-def layercake_volume_ascii_regulargrid_mpiregularmap(filename=None):
-    import sys
-    import start as start
-    #
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    #
-    numpy                       = start.start_numpy()
-    cfg                         = start.start_cfg(filename=filename)                       
-    
-    from utilities import geo2utm, savegeometry,savesurf
-    
-    from math import sqrt
-    #
-    try:
-        mpi.barrier()
-    except:
-        pass
-    #
-    #
-    command = "comment '"+"PROC: "+str(iproc)+"/"+str(numproc)+" '"
-    cubit.cmd(command)
-    #fer=open('ERROR_VOLUME_'+str(iproc),'w')
-    
-    #
-    if mpiflag:
-        x_slice=numpy.zeros([numproc],int)
-        y_slice=numpy.zeros([numproc],int)
-        for icpuy in range(0,cfg.nproc_eta): 
-            for icpux in range (0,cfg.nproc_xi):
-                iprocnum=icpuy*cfg.nproc_xi+icpux
-                #print iprocnum,cfg.nproc_xi,icpux,icpuy,cfg.nproc_xi,cfg.nproc_eta
-                x_slice[iprocnum]=icpux
-                y_slice[iprocnum]=icpuy
-        icpux=x_slice[iproc]
-        icpuy=y_slice[iproc]
-    else:
-        icpuy=int(cfg.id_proc/cfg.nproc_xi)
-        icpux=cfg.id_proc%cfg.nproc_xi
-    
-    #
-    if  cfg.geometry_format == 'ascii':
-        #for the original surfaces
-        #number of points in the files that describe the topography
-        import local_volume
-        if cfg.localdir_is_globaldir:
-            if iproc == 0 or not mpiflag:
-                coordx_0,coordy_0,elev_0,nx_0,ny_0=local_volume.read_grid(filename)
-                print 'end of reading grd files '+str(nx_0*ny_0)+ ' points'
-            else:
-                pass
-            if iproc == 0 or not mpiflag:
-                coordx=mpi.bcast(coordx_0)
-            else:
-                coordx=mpi.bcast()
-            if iproc == 0 or not mpiflag:
-                coordy=mpi.bcast(coordy_0)
-            else:
-                coordy=mpi.bcast()
-            if iproc == 0 or not mpiflag:
-                elev=mpi.bcast(elev_0)
-            else:
-                elev=mpi.bcast()
-            if iproc == 0 or not mpiflag:
-                nx=mpi.bcast(nx_0)
-            else:
-                nx=mpi.bcast()       
-            if iproc == 0 or not mpiflag:
-                ny=mpi.bcast(ny_0)
-            else:
-                ny=mpi.bcast()
-        else:
-            coordx,coordy,elev,nx,ny=local_volume.read_grid(filename)
-        print str(iproc)+ ' end of receving grd files '
-        nx_segment=int(nx/cfg.nproc_xi)+1
-        ny_segment=int(ny/cfg.nproc_eta)+1
-        
-    elif cfg.geometry_format=='regmesh': # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-        
-        if cfg.depth_bottom != cfg.zdepth[0]:
-            if iproc == 0: print 'the bottom of the block is at different depth than depth[0] in the configuration file'
-        nx= cfg.nproc_xi+1
-        ny= cfg.nproc_eta+1
-        nx_segment=2
-        ny_segment=2
-        #if iproc == 0: print nx,ny,cfg.cpux,cfg.cpuy
-        xp=(cfg.xmax-cfg.xmin)/float((nx-1))
-        yp=(cfg.ymax-cfg.ymin)/float((ny-1))
-        #
-        elev=numpy.zeros([nx,ny,cfg.nz],float)
-        coordx=numpy.zeros([nx,ny],float)
-        coordy=numpy.zeros([nx,ny],float)
-        #
-        #
-        xlength=(cfg.xmax-cfg.xmin)/float(cfg.nproc_xi) #length of x slide for chunk
-        ylength=(cfg.ymax-cfg.ymin)/float(cfg.nproc_eta) #length of y slide for chunk
-        nelem_chunk_x=1    
-        nelem_chunk_y=1
-        ivxtot=nelem_chunk_x+1
-        ivytot=nelem_chunk_y+1 
-        xstep=xlength #distance between vertex on x
-        ystep=ylength
-        for i in range(0,cfg.nz):
-            elev[:,:,i] = cfg.zdepth[i]
-        
-        icoord=0
-        for iy in range(0,ny):
-            for ix in range(0,nx):
-                icoord=icoord+1
-                coordx[ix,iy]=cfg.xmin+xlength*(ix)
-                coordy[ix,iy]=cfg.ymin+ylength*(iy)
-        
-        #print coordx,coordy,nx,ny
-    #
-    print 'end of building grid '+str(iproc)
-    print 'number of point: ', len(coordx)
-    #
-    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-    #for each processor
-    #
-    nxmin_cpu=(nx_segment-1)*(icpux)
-    nymin_cpu=(ny_segment-1)*(icpuy)
-    nxmax_cpu=min(nx-1,(nx_segment-1)*(icpux+1))
-    nymax_cpu=min(ny-1,(ny_segment-1)*(icpuy+1))
-    #if iproc == 0:
-    #    print nx_segment,ny_segment,nx,ny
-    #    print icpux,icpuy,nxmin_cpu,nxmax_cpu
-    #    print icpux,icpuy,nymin_cpu,nymax_cpu
-    #    print coordx[0,0],coordx[nx-1,ny-1]
-    #    print coordy[0,0],coordy[nx-1,ny-1]
-    #
-    #
-    icurve=0
-    isurf=0
-    ivertex=0
-    #
-    #create vertex
-    for inz in range(0,cfg.nz):
-        if  cfg.bottomflat and inz == 0: #bottom layer
-                #
-                if cfg.geometry_format == 'ascii':
-                    lv=cubit.get_last_id("vertex")     
-                    
-                    x_current,y_current=(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu])
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)
-                    #
-                    x_current,y_current=(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu])
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)                                                                              
-                    #
-                    x_current,y_current=(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu])
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)
-                    #
-                    x_current,y_current=(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu])
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)
-                    #
-                    lv2=cubit.get_last_id("vertex")     
-                    
-                    cubitcommand= 'create surface vertex '+str(lv+1)+' to '+str(lv2)
-                    cubit.cmd(cubitcommand)
-                    #
-                    isurf = isurf + 1
-                else:
-                    lv=cubit.get_last_id("vertex") 
-                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],'utm')
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)
-                    #
-                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],'utm')
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)                                                                              
-                    #
-                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],'utm')
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)
-                    #
-                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
-                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
-                    cubit.cmd(cubitcommand)
-                    #
-                    lv2=cubit.get_last_id("vertex") 
-                    cubitcommand= 'create surface vertex '+str(lv+1)+' to '+str(lv2)
-                    cubit.cmd(cubitcommand)
-                    #
-                    isurf = isurf + 1
-        else:
-            if cfg.geometry_format == 'regmesh':
-                zvertex=cfg.zdepth[inz]
-                lv=cubit.get_last_id("vertex")                        
-                x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],'utm')
-                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
-                cubit.cmd(cubitcommand)
-                #
-                x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],'utm')
-                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
-                cubit.cmd(cubitcommand)                                                                              
-                #
-                x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],'utm')
-                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
-                cubit.cmd(cubitcommand)
-                #
-                x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
-                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
-                cubit.cmd(cubitcommand)
-                #
-                cubitcommand= 'create surface vertex '+str(lv+1)+' '+str(lv+2)+' '+str(lv+3)+' '+str(lv+4)
-                cubit.cmd(cubitcommand)
-                #
-                isurf = isurf + 1
-            elif cfg.geometry_format == 'ascii':
-                
-                vertex=[]
-                
-                for iy in range(nymin_cpu,nymax_cpu+1):
-                    ivx=0
-                    for ix in range(nxmin_cpu,nxmax_cpu+1):
-                        zvertex=elev[ix,iy,inz]
-                        x_current,y_current=(coordx[ix,iy],coordy[ix,iy])
-                        #
-                        vertex.append(' Position '+ str( x_current ) +' '+ str( y_current )+' '+ str( zvertex ) )
-                #
-                print 'proc',iproc, 'vertex list created....',len(vertex)
-                n=max(nx,ny)
-                uline=[]
-                vline=[]
-                iv=0
-                
-                cubit.cmd("set info off")
-                cubit.cmd("set echo off")
-                cubit.cmd("set journal off")
-                
-                for iy in range(0,nymax_cpu-nymin_cpu+1):
-                    positionx=''
-                    for ix in range(0,nxmax_cpu-nxmin_cpu+1):
-                        positionx=positionx+vertex[iv]
-                        iv=iv+1
-                    command='create curve spline '+positionx
-                    cubit.cmd(command)
-                    #print command
-                    uline.append( cubit.get_last_id("curve") )
-                for ix in range(0,nxmax_cpu-nxmin_cpu+1):
-                    positiony=''
-                    for iy in range(0,nymax_cpu-nymin_cpu+1):
-                        positiony=positiony+vertex[ix+iy*(nxmax_cpu-nxmin_cpu+1)]
-                    command='create curve spline '+positiony
-                    cubit.cmd(command)
-                    #print command
-                    vline.append( cubit.get_last_id("curve") )
-                #
-                cubit.cmd("set info "+cfg.cubit_info)
-                cubit.cmd("set echo "+cfg.echo_info)
-                cubit.cmd("set journal "+cfg.jou_info)
-                #
-                #
-                print 'proc',iproc, 'lines created....',len(uline),'*',len(vline)
-                umax=max(uline)
-                umin=min(uline)
-                vmax=max(vline)
-                vmin=min(vline)
-                ner=cubit.get_error_count()
-                cubitcommand= 'create surface net u curve '+ str( umin )+' to '+str( umax )+ ' v curve '+ str( vmin )+ ' to '+str( vmax )+' heal'
-                cubit.cmd(cubitcommand)
-                ner2=cubit.get_error_count()
-                if ner == ner2: 
-                    command = "del curve all"
-                    cubit.cmd(command)
-                    isurf=isurf+1
-                #
-            else:
-                raise NameError, 'error, check geometry_format, it should be ascii or regmesh'   #
-                #
-        cubitcommand= 'del vertex all'
-        cubit.cmd(cubitcommand)
-    if cfg.save_surface_cubit:
-        savegeometry(iproc=iproc,surf=True,filename=filename)
-    #
-    #
-    #!create volume
-    if  cfg.osystem == 'macosx':
-        pass
-    elif cfg.osystem == 'linux':
-        for inz in range(1,cfg.nz):
-            ner=cubit.get_error_count()
-            cubitcommand= 'create volume loft surface '+ str( inz+1 )+' '+str( inz )
-            cubit.cmd(cubitcommand)
-            ner2=cubit.get_error_count()
-            isurf=isurf+6
-    if ner == ner2:
-        cubitcommand= 'del surface 1 to '+ str( cfg.nz )
-        cubit.cmd(cubitcommand)
-        list_vol=cubit.parse_cubit_list("volume","all")
-        if len(list_vol) > 1:     
-            cubitcommand= 'imprint volume all'
-            cubit.cmd(cubitcommand)
-            cubitcommand= 'merge all'
-            cubit.cmd(cubitcommand)
-        ner=cubit.get_error_count()
-        #cubitcommand= 'composite create curve in vol all'
-        #cubit.cmd(cubitcommand)
-    savegeometry(iproc,filename=filename)
-    if cfg.geological_imprint:
-        curvesname=[cfg.outlinebasin_curve,cfg.transition_curve,cfg.faulttrace_curve]
-        outdir=cfg.working_dir
-        imprint_topography_with_geological_outline(curvesname,outdir)
-    #
-    #        
-    cubit.cmd("set info "+cfg.cubit_info)
-    cubit.cmd("set echo "+cfg.echo_info)
-    cubit.cmd("set journal "+cfg.jou_info)
-    
-    
-def layercake_volume_fromacis_mpiregularmap(filename=None):
-    import sys
-    import start as start
-    #
-    mpiflag,iproc,numproc,mpi   = start.start_mpi()
-    #
-    numpy                       = start.start_numpy()
-    cfg                         = start.start_cfg(filename=filename)                       
-    #
-    from utilities import geo2utm, savegeometry
-    #
-    from math import sqrt
-    #
-    try:
-        mpi.barrier()
-    except:
-        pass
-    #
-    #
-    command = "comment '"+"PROC: "+str(iproc)+"/"+str(numproc)+" '"
-    cubit.cmd(command)
-    #
-    #get the limit of the volume considering the cpu
-    def xwebcut(x):
-        command='create planar surface with plane xplane offset '+str(x)
-        cubit.cmd(command)
-        last_surface=cubit.get_last_id("surface")
-        command="webcut volume all tool volume in surf "+str(last_surface)
-        cubit.cmd(command)
-        command="del surf "+str(last_surface)
-        cubit.cmd(command)
-        
-    def ywebcut(x):
-        command='create planar surface with plane yplane offset '+str(x)
-        cubit.cmd(command)
-        last_surface=cubit.get_last_id("surface")
-        command="webcut volume all tool volume in surf "+str(last_surface)
-        cubit.cmd(command)
-        command="del surf "+str(last_surface)
-        cubit.cmd(command)
-        
-    def translate2zero():
-        ss=cubit.parse_cubit_list('surface','all')
-        box = cubit.get_total_bounding_box("surface", ss)
-        xmin=box[0]
-        ymin=box[3]
-        cubit.cmd('move surface all x '+str(-1*xmin)+' y '+str(-1*ymin))
-        return xmin,ymin
-        
-    def translate2original(xmin,ymin):
-        cubit.cmd('move surface all x '+str(xmin)+' y '+str(ymin))
-        
-    if mpiflag:
-        x_slice=numpy.zeros([numproc],int)
-        y_slice=numpy.zeros([numproc],int)
-        for icpuy in range(0,cfg.nproc_eta): 
-            for icpux in range (0,cfg.nproc_xi):
-                iprocnum=icpuy*cfg.nproc_xi+icpux
-                #print iprocnum,cfg.nproc_xi,icpux,icpuy,cfg.nproc_xi,cfg.nproc_eta
-                x_slice[iprocnum]=icpux
-                y_slice[iprocnum]=icpuy
-        icpux=x_slice[iproc]
-        icpuy=y_slice[iproc]
-    else:
-        icpuy=int(cfg.id_proc/cfg.nproc_xi)
-        icpux=cfg.id_proc%cfg.nproc_xi
-    #
-    ner=cubit.get_error_count()
-    #
-    icurve=0
-    isurf=0
-    ivertex=0
-    #
-    xlength=(cfg.xmax-cfg.xmin)/float(cfg.cpux) #length of x slide for chunk
-    ylength=(cfg.ymax-cfg.ymin)/float(cfg.cpuy) #length of y slide for chunk
-    xmin_cpu=cfg.xmin+(xlength*(icpux))
-    ymin_cpu=cfg.ymin+(ylength*(icpuy))
-    xmax_cpu=xmin_cpu+xlength
-    ymax_cpu=ymin_cpu+ylength
-    #
-    #importing the surfaces
-    for inz in range(cfg.nz-2,-2,-1):
-        if cfg.bottomflat and inz==-1:
-            command = "create planar surface with plane zplane offset "+str(cfg.depth_bottom)
-            cubit.cmd(command)
-        else:
-            command = "import cubit '"+cfg.filename[inz]+"'"
-            cubit.cmd(command)
-            
-            
-    #translate
-    xmin,ymin=translate2zero()
-    print 'translate ...', -xmin,-ymin
-    xmin_cpu=xmin_cpu-xmin
-    ymin_cpu=ymin_cpu-ymin
-    xmax_cpu=xmax_cpu-xmin
-    ymax_cpu=ymax_cpu-ymin
-    
-    ss=cubit.parse_cubit_list('surface','all')
-    box = cubit.get_total_bounding_box("surface", ss)
-    print 'dimension... ', box
-    #cutting the surfaces
-    xwebcut(xmin_cpu)
-    xwebcut(xmax_cpu)
-    ywebcut(ymin_cpu)
-    ywebcut(ymax_cpu)
-    #
-    list_surface_all=cubit.parse_cubit_list("surface","all")
-    #condisidering only the surfaces inside the boundaries
-    dict_surf={}
-    for isurf in list_surface_all:
-        p=cubit.get_center_point("surface",isurf)
-        if p[0] < xmin_cpu or p[0] > xmax_cpu or p[1] > ymax_cpu or p[1] < ymin_cpu:
-            command = "del surf "+str(isurf)
-            cubit.cmd(command)
-        else:
-            dict_surf[str(isurf)]=p[2]
-    z=dict_surf.values()
-    z.sort()
-    list_surf=[]
-    for val in z:
-        isurf=[k for k, v in dict_surf.iteritems() if v == val][0]
-        list_surf.append(int(isurf))
-    #
-    
-    #lofting the volume
-    for i,j in zip(list_surf,list_surf[1:]):
-        ner=cubit.get_error_count()
-        cubitcommand= 'create volume loft surface '+ str(i)+' '+str(j)
-        cubit.cmd(cubitcommand)
-        ner2=cubit.get_error_count()
-    #
-    translate2original(xmin,ymin)
-    
-    
-    if ner == ner2:
-        cubitcommand= 'del surface all'
-        cubit.cmd(cubitcommand)
-        #
-        #
-        #cubitcommand= 'composite create curve in vol all'
-        #cubit.cmd(cubitcommand)
-        list_vol=cubit.parse_cubit_list("volume","all")
-        if len(list_vol) > 1:     
-            cubitcommand= 'imprint volume all'
-            cubit.cmd(cubitcommand)
-            #cubit_error_stop(iproc,cubitcommand,ner)
-            #
-            cubitcommand= 'merge all'
-            cubit.cmd(cubitcommand)
-    #
-    savegeometry(iproc,filename=filename)
-    if cfg.geological_imprint:
-        curvesname=[cfg.outlinebasin_curve,cfg.transition_curve,cfg.faulttrace_curve]
-        outdir=cfg.working_dir
-        imprint_topography_with_geological_outline(curvesname,outdir)
-
-
-
-def imprint_topography_with_geological_outline(curvesname,outdir='.'):
-    import sys,os
-    from sets import Set
-    #
-    from utilities import load_curves,project_curves,get_v_h_list
-    
-    list_vol=cubit.parse_cubit_list("volume","all")
-    surf_or,surf_vertical,list_curve_or,list_curve_vertical,bottom,top=get_v_h_list(list_vol)
-    
-    
-    
-    outlinebasin_curve=load_curves(curvesname[0])
-    transition_curve=load_curves(curvesname[1])
-    faulttrace_curve=load_curves(curvesname[2])
-    
-    curves=[]
-    if outlinebasin_curve: curves=curves+outlinebasin_curve
-    if transition_curve: curves=curves+transition_curve
-    if faulttrace_curve: curves=curves+faulttrace_curve
-    
-    if curves:
-            command='imprint tolerant surface '+str(top)+' with curve '+' '.join(str(x) for x in curves)+'  merge'
-            cubit.cmd(command)
-             
-    
-    command = "merge surf all"
-    cubit.cmd(command)
-    command = "compress vol all"
-    cubit.cmd(command)
-    command = "compress surf all"
-    cubit.cmd(command)
-    command = "save as '"+outdirs+"/"+"imprinted_vol_"+str(iproc)+".cub' overwrite"
-    cubit.cmd(command)    
-



More information about the CIG-COMMITS mailing list