Changeset 23394 for issm/trunk


Ignore:
Timestamp:
10/05/18 10:42:45 (6 years ago)
Author:
Mathieu Morlighem
Message:

merged trunk-jpl and trunk for revision 23392

Location:
issm/trunk
Files:
2 deleted
163 edited
28 copied

Legend:

Unmodified
Added
Removed
  • issm/trunk

  • issm/trunk/configure.ac

    r22822 r23394  
    22
    33#AUTOCONF
    4 AC_INIT([Ice Sheet System Model (ISSM)],[4.14],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
     4AC_INIT([Ice Sheet System Model (ISSM)],[4.15],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
    55AC_CONFIG_AUX_DIR([./aux-config])         #Put config files in aux-config
    66AC_CONFIG_MACRO_DIR([m4])                 #m4 macros are located in m4
  • issm/trunk/etc/environment.sh

    r22758 r23394  
    7575fi
    7676
    77 #legacy mpich2 (To be removed)
    78 MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
    79 if [ -d "$MPI_DIR" ]; then
    80         export MPI_DIR
    81         pathprepend   "$MPI_DIR/bin"
    82         libpathappend "$MPI_DIR/lib"
    83 fi
    84 
    8577MPI_DIR="$ISSM_DIR/externalpackages/mpich/install"
    8678if [ -d "$MPI_DIR" ]; then
    8779        export MPI_DIR
    8880        export MPI_INC_DIR="$MPI_DIR/include"
    89         pathprepend   "$MPI_DIR/bin"
    90         libpathappend "$MPI_DIR/lib"
     81        pathprepend    "$MPI_DIR/bin"
     82        libpathprepend "$MPI_DIR/lib"
    9183fi
    9284
     
    234226pathprepend "$GMAKE_DIR/bin"
    235227
    236 PYTHON_DIR="$ISSM_DIR/externalpackages/python/install"
    237 if [ -d "$PYTHON_DIR" ]; then
    238         export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/lib"
    239         pathprepend    "$PYTHON_DIR/bin"
    240         libpathprepend "$PYTHON_DIR/lib"
    241         libpathprepend "$ISSM_DIR/lib"
    242 fi
    243 
    244228MODELE_DIR="$ISSM_DIR/externalpackages/modelE/install"
    245229pathappend "$MODELE_DIR/src/exec"
  • issm/trunk/jenkins/jenkins.sh

    r23189 r23394  
    324324#concatenate reports
    325325cd $ISSM_DIR/nightlylog/
    326 echo 'CHECKING NIGHTLYLOG DIRECTORY'
    327 echo '-----------------------------'
    328 ls -la
    329 echo '-----------------------------'
     326#echo 'CHECKING NIGHTLYLOG DIRECTORY'
     327#echo '-----------------------------'
     328#ls -la
     329#echo '-----------------------------'
    330330
    331331if [ -f matlab_log.log ]; then
  • issm/trunk/jenkins/linux64_caladan_ad

    r22758 r23394  
    3232                                         mpich install-3.2-linux64.sh
    3333                                         petsc install-3.7-linux64.sh
    34                                          metis install-5.0.1-linux64.sh
    3534                                         triangle install-linux64.sh
    3635                                         gsl install-linux64.sh
  • issm/trunk/jenkins/linux64_caladan_ampi

    r22758 r23394  
    4141                                         mpich install-3.2-linux64.sh
    4242                                         petsc install-3.7-linux64.sh
    43                                          metis install-5.0.1-linux64.sh
    4443                                         triangle install-linux64.sh
    4544                                         gsl install-linux64.sh
  • issm/trunk/jenkins/linux64_ross_ad

    r23189 r23394  
    3737                                         mpich install-3.2-linux64.sh
    3838                                         petsc install-3.7-linux64.sh
    39                                          metis install-5.0.1-linux64.sh
    4039                                         triangle install-linux64.sh
    4140                                         gsl install-linux64.sh
  • issm/trunk/jenkins/linux64_ross_ampi

    r23189 r23394  
    4444                                         mpich install-3.2-linux64.sh
    4545                                         petsc install-3.7-linux64.sh
    46                                          metis install-5.0.1-linux64.sh
    4746                                         triangle install-linux64.sh
    4847                                         gsl install-linux64.sh
  • issm/trunk/jenkins/linux64_ross_dakota

    r23189 r23394  
    1111        --disable-static \
    1212        --with-matlab-dir=$MATLAB_PATH \
     13        --with-python-dir=/usr \
     14        --with-python-numpy-dir=/home/jenkins/.local/lib/python2.7/site-packages/numpy \
    1315        --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
    1416        --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
     
    3032#PYTHON and MATLAB testing
    3133MATLAB_TEST=1
    32 PYTHON_TEST=0
     34PYTHON_TEST=1
    3335
    3436#-----------------------------------#
     
    6365#by Matlab and runme.m
    6466#ex: "'id',[101 102 103]"
    65 PYTHON_NROPTIONS="--exclude 243 701 702 435"
     67PYTHON_NROPTIONS="--exclude 243 701 702 435 --include_name 'Dakota'"
    6668MATLAB_NROPTIONS="'exclude',[243,701,702,435]"
  • issm/trunk/jenkins/linux64_ross_python

    r23189 r23394  
    1010ISSM_CONFIG='--prefix=$ISSM_DIR \
    1111        --disable-static \
     12        --with-matlab-dir=$MATLAB_PATH \
    1213        --with-python-dir=/usr \
    1314        --with-python-numpy-dir=/home/jenkins/.local/lib/python2.7/site-packages/numpy \
    1415        --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
    1516        --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
    16         --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi -lmpifort" \
     17        --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpi -lmpicxx -lmpifort" \
    1718        --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
    1819        --with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
     
    2122        --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
    2223        --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
    23         --with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.9/ -lgfortran" \
     24        --with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.9 -lgfortran" \
    2425        --with-m1qn3-dir=$ISSM_DIR/externalpackages/m1qn3/install \
    2526        --with-numthreads=4 \
     
    5051#number of cpus used in ISSM installation and compilation (one is usually
    5152#safer as some packages are very sensitive to parallel compilation)
    52 NUMCPUS_INSTALL=10
     53NUMCPUS_INSTALL=5
    5354
    5455#number of cpus used in the nightly runs.
    55 NUMCPUS_RUN=5
     56NUMCPUS_RUN=3
    5657
    5758#Nightly run options. The matlab routine runme.m will be called
  • issm/trunk/jenkins/macosx_pine-island

    r23189 r23394  
    55
    66#MATLAB path
    7 MATLAB_PATH="/Applications/MATLAB_R2015b.app/"
     7MATLAB_PATH="/Applications/MATLAB_R2015b.app"
    88
    99#ISSM CONFIGURATION
     
    4848
    4949#number of cpus used in the nightly runs.
    50 NUMCPUS_RUN=2
     50NUMCPUS_RUN=4
    5151
    5252#Nightly run options. The matlab routine runme.m will be called
  • issm/trunk/jenkins/macosx_pine-island_dakota

    r21729 r23394  
    55
    66#MATLAB path
    7 MATLAB_PATH="/Applications/MATLAB_R2015b.app/"
     7MATLAB_PATH="/Applications/MATLAB_R2015b.app"
    88
    9 #ISSM CONFIGURATION 
     9#ISSM CONFIGURATION
    1010ISSM_CONFIG='--prefix=$ISSM_DIR \
    1111        --with-matlab-dir=$MATLAB_PATH \
     12        --with-python-dir=/System/Library/Frameworks/Python.framework/Versions/2.7 \
     13        --with-python-numpy-dir=/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy \
    1214        --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
    1315        --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
     
    2729#PYTHON and MATLAB testing
    2830MATLAB_TEST=1
    29 PYTHON_TEST=0
     31PYTHON_TEST=1
    3032
    3133#-----------------------------------#
     
    5456
    5557#number of cpus used in the nightly runs.
    56 NUMCPUS_RUN=2
     58NUMCPUS_RUN=4
    5759
    5860#Nightly run options. The matlab routine runme.m will be called
    5961#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
    6062#by Matlab and runme.m
    61 #ex: "'id',[101 102 103]"  ERRORS ARE LARGE FOR: 418 420 
    62 PYTHON_NROPTIONS=""
     63#ex: "'id',[101 102 103]"  ERRORS ARE LARGE FOR: 418 420
     64PYTHON_NROPTIONS="--exclude 119 243 514 701 702 703 234 235 418 420 --include_name 'Dakota'"
    6365MATLAB_NROPTIONS="'exclude',[119,243,514,701,702,703,234,235,418,420]"
  • issm/trunk/jenkins/macosx_pine-island_dakota_static

    r23189 r23394  
    44
    55#MATLAB path
    6 MATLAB_PATH="/Applications/MATLAB_R2015b.app/"
     6MATLAB_PATH="/Applications/MATLAB_R2015b.app"
    77
    8 #ISSM CONFIGURATION 
     8#ISSM CONFIGURATION
    99ISSM_CONFIG='--prefix=$ISSM_DIR \
    1010        --disable-static \
     
    5656
    5757#number of cpus used in the nightly runs.
    58 NUMCPUS_RUN=2
     58NUMCPUS_RUN=4
    5959
    6060#Nightly run options. The matlab routine runme.m will be called
     
    6262#by Matlab and runme.m
    6363#ex: "'id',[101 102 103]"
    64 ##                           bamg mesh   FS                     
     64##                           bamg mesh   FS
    6565#PYTHON_NROPTIONS="--exclude_name 'Dakota'"
    6666#MATLAB_NROPTIONS="'exclude',[243,701,702,703,435,IdFromString('Dakota')]"
  • issm/trunk/jenkins/macosx_pine-island_examples

    r21729 r23394  
    55
    66#MATLAB path
    7 MATLAB_PATH="/Applications/MATLAB_R2015b.app/"
     7MATLAB_PATH="/Applications/MATLAB_R2015b.app"
    88
    9 #ISSM CONFIGURATION 
     9#ISSM CONFIGURATION
    1010ISSM_CONFIG='--prefix=$ISSM_DIR \
    1111        --with-matlab-dir=$MATLAB_PATH \
  • issm/trunk/m4/issm_options.m4

    r23189 r23394  
    99        dnl ISSM's internal options
    1010        dnl Build info{{{
    11        
     11
    1212        dnl build date
    1313        AC_PATH_PROGS(DATE, date)
     
    153153        AC_MSG_CHECKING(for wrappers compilation)
    154154        AM_CONDITIONAL([WRAPPERS], [test x$WRAPPERS_VALUE = xyes])
    155         AC_MSG_RESULT($WRAPPERS_VALUE) 
     155        AC_MSG_RESULT($WRAPPERS_VALUE)
    156156        dnl }}}
    157157        dnl Extensions{{{
     
    251251                fi
    252252        fi
    253         AC_SUBST([OSLIBS]) 
     253        AC_SUBST([OSLIBS])
    254254        AC_MSG_RESULT(done)
    255255        dnl }}}
     
    281281
    282282                AC_DEFINE([_HAVE_MATLAB_],[1],[with matlab in ISSM src])
    283                
     283
    284284                dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental) except for windows
    285285                AC_MSG_CHECKING([matlab's mex compilation flags])
    286286                case "${host_os}" in
    287                         *cygwin*) 
     287                        *cygwin*)
    288288                                if  test $VENDOR = intel-win7-32; then
    289                                         MEXLIB="-Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib" 
     289                                        MEXLIB="-Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib"
    290290               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win32/microsoft` -Wl,/link -Wl,/EXPORT:mexFunction -Wl,/DLL"
    291291                                        MEXEXT=`$MATLAB_ROOT/bin/mexext.bat`
    292292                                        MEXEXT=".$MEXEXT"
    293293                                elif test $VENDOR = intel-win7-64; then
    294                                         MEXLIB="-Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib" 
    295                MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win64/microsoft` -Wl,/link -Wl,/EXPORT:mexFunction -Wl,/DLL" 
     294                                        MEXLIB="-Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib"
     295               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win64/microsoft` -Wl,/link -Wl,/EXPORT:mexFunction -Wl,/DLL"
    296296                                        MEXEXT=".mexw64"
    297297                                elif test $VENDOR = MSVC-Win64 || test $VENDOR = MSVC-Win64-par; then
    298                                         MEXLIB="-Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib" 
    299                MEXLINK="-Wl,/link -Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win64/microsoft` -Wl,/link -Wl,/EXPORT:mexFunction -Wl,/DLL" 
     298                                        MEXLIB="-Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib"
     299               MEXLINK="-Wl,/link -Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win64/microsoft` -Wl,/link -Wl,/EXPORT:mexFunction -Wl,/DLL"
    300300                                        MATLABINCL="-I`cygpath -m $MATLAB_ROOT/extern/include/`"
    301301                                        MEXEXT=".mexw64"
     
    311311                                         echo "#include <mex.h>" > conftest.cpp
    312312                                         echo "void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){}" >> conftest.cpp
    313                                          $MATLAB_ROOT/bin/mex -v -lmex conftest.cpp > conftest.tmp 2>&1 
     313                                         $MATLAB_ROOT/bin/mex -v -lmex conftest.cpp > conftest.tmp 2>&1
    314314                                         rm -f conftest.cpp
    315315                                         MEXLINK=$(cat conftest.tmp | grep LDFLAGS  | sed -e "s/LDFLAGS ://g")
     
    333333                MATLABWRAPPEREXT=$MEXEXT
    334334                AC_SUBST([MATLABWRAPPEREXT])
    335            AC_SUBST([MEXLIB]) 
     335           AC_SUBST([MEXLIB])
    336336                AC_SUBST([MEXLINK])
    337337        fi
     
    345345        AC_ARG_WITH([javascript],
    346346          AS_HELP_STRING([--with-javascript], [compile javascript wrappers? default is no.]),
    347           [JAVASCRIPT=$withval],[JAVASCRIPT="no"]) 
     347          [JAVASCRIPT=$withval],[JAVASCRIPT="no"])
    348348
    349349        dnl Check whether javascript wrappers are desired
     
    364364        AC_ARG_WITH([triangle-dir],
    365365                          AS_HELP_STRING([--with-triangle-dir=DIR], [triangle root directory.]),
    366                          [TRIANGLE_ROOT=$withval],[TRIANGLE_ROOT="no"]) 
     366                         [TRIANGLE_ROOT=$withval],[TRIANGLE_ROOT="no"])
    367367
    368368  dnl Check whether triangle is enabled
     
    394394                                if test "x$HAVE_JAVASCRIPT" = "xyes"; then
    395395                                        dnl go to the bit code, not the library.
    396                                         TRIANGLELIB=$TRIANGLE_ROOT/triangle.o 
     396                                        TRIANGLELIB=$TRIANGLE_ROOT/triangle.o
    397397                                else
    398398                                        TRIANGLELIB=$TRIANGLE_ROOT/triangle.a
     
    402402                                if test "x$HAVE_JAVASCRIPT" = "xyes"; then
    403403                                        dnl go to the bit code, not the library.
    404                                         TRIANGLELIB=$TRIANGLE_ROOT/triangle.o 
     404                                        TRIANGLELIB=$TRIANGLE_ROOT/triangle.o
    405405                                else
    406406                                        TRIANGLELIB=$TRIANGLE_ROOT/triangle.a
     
    416416        AC_ARG_WITH([boost-dir],
    417417          AS_HELP_STRING([--with-boost-dir=DIR], [boost root directory.]),
    418           [BOOST_ROOT=$withval],[BOOST_ROOT="no"]) 
     418          [BOOST_ROOT=$withval],[BOOST_ROOT="no"])
    419419
    420420        dnl Check whether boost is enabled
     
    443443        AC_ARG_WITH([dakota-dir],
    444444          AS_HELP_STRING([--with-dakota-dir=DIR], [dakota root directory.]),
    445           [DAKOTA_ROOT=$withval],[DAKOTA_ROOT="no"]) 
    446        
     445          [DAKOTA_ROOT=$withval],[DAKOTA_ROOT="no"])
     446
    447447        dnl Check whether dakota is enabled
    448448        AC_MSG_CHECKING([for dakota])
     
    573573        AC_ARG_WITH([python-dir],
    574574          AS_HELP_STRING([--with-python-dir=DIR], [python root directory.]),
    575           [PYTHON_ROOT=$withval],[PYTHON_ROOT="no"]) 
     575          [PYTHON_ROOT=$withval],[PYTHON_ROOT="no"])
    576576
    577577        dnl Check whether python is enabled
     
    592592        if test "x$HAVE_PYTHON" = "xyes"; then
    593593                AC_MSG_CHECKING([for python version])
    594                 dnl Query Python for its version number.  Getting [:3] seems to be the
     594                dnl Query Python for its version number. Getting [:3] seems to be the
    595595                dnl best way to do this; it's what "site.py" does in the standard library.
    596596                PYTHON_VERSION=$($PYTHON_ROOT/bin/python -c "import sys; print sys.version[[:3]]")
    597597                AC_MSG_RESULT($PYTHON_VERSION)
    598598
    599                 dnl recover major 
     599                dnl recover major
    600600                PYTHON_MAJOR=${PYTHON_VERSION%.*}
    601601                AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
     
    643643        AC_ARG_WITH([python-numpy-dir],
    644644          AS_HELP_STRING([--with-python-numpy-dir=DIR], [python-numpy root directory.]),
    645           [PYTHON_NUMPY_ROOT=$withval],[PYTHON_NUMPY_ROOT="no"])
    646        
     645          [PYTHON_NUMPY_ROOT=$withval],[PYTHON_NUMPY_ROOT="no"])
     646
     647        dnl you can find numpy by typing
     648        dnl >>> import numpy
     649        dnl >>> numpy.__file__
     650        dnl '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/__init__.pyc'
     651
    647652        dnl Check whether numpy is enabled
    648653        AC_MSG_CHECKING(for python-numpy)
     
    667672        AC_ARG_WITH([chaco-dir],
    668673          AS_HELP_STRING([--with-chaco-dir=DIR], [chaco root directory.]),
    669           [CHACO_ROOT=$withval],[CHACO_ROOT="no"]) 
    670        
     674          [CHACO_ROOT=$withval],[CHACO_ROOT="no"])
     675
    671676        dnl Check whether chaco is enabled
    672677        AC_MSG_CHECKING([for chaco])
     
    694699        AC_ARG_WITH([scotch-dir],
    695700          AS_HELP_STRING([--with-scotch-dir=DIR], [scotch root directory.]),
    696           [SCOTCH_ROOT=$withval],[SCOTCH_ROOT="no"]) 
     701          [SCOTCH_ROOT=$withval],[SCOTCH_ROOT="no"])
    697702
    698703  dnl Check whether scotch is enabled
     
    708713        AC_MSG_RESULT($HAVE_SCOTCH)
    709714        AM_CONDITIONAL([SCOTCH],[test x$HAVE_SCOTCH = xyes])
    710        
     715
    711716        dnl scotch libraries
    712717        if test "x$HAVE_SCOTCH" = "xyes"; then
     
    721726        AC_ARG_WITH([esmf-dir],
    722727                AS_HELP_STRING([--with-esmf-dir=DIR], [esmf root directory.]),
    723                 [ESMF_ROOT=$withval],[ESMF_ROOT="no"]) 
     728                [ESMF_ROOT=$withval],[ESMF_ROOT="no"])
    724729
    725730        dnl Check whether esmf is enabled
     
    734739        fi
    735740        AC_MSG_RESULT($HAVE_ESMF)
    736        
     741
    737742        dnl esmf headers and libraries
    738743        if test "x$HAVE_ESMF" == "xyes"; then
     
    745750        AM_CONDITIONAL([ESMF], [test x$HAVE_ESMF = xyes])
    746751        dnl }}}
     752        dnl codipack{{{
     753        AC_ARG_WITH([codipack-dir],
     754                AS_HELP_STRING([--with-codipack-dir=DIR], [CoDiPack root directory.]),
     755                [CODIPACK_ROOT=$withval],[CODIPACK_ROOT="no"])
     756
     757        dnl Check whether codipack is enabled
     758        AC_MSG_CHECKING([for CoDiPack])
     759        if test "x$CODIPACK_ROOT" = "xno" ; then
     760                HAVE_CODIPACK=no
     761        else
     762                HAVE_CODIPACK=yes
     763                if ! test -d "$CODIPACK_ROOT"; then
     764                        AC_MSG_ERROR([codipack directory provided ($CODIPACK_ROOT) does not exist]);
     765                fi
     766        fi
     767        AC_MSG_RESULT($HAVE_CODIPACK)
     768
     769        dnl codipack headers and libraries
     770        if test "x$HAVE_CODIPACK" == "xyes"; then
     771                CODIPACKINCL="-I$CODIPACK_ROOT/include"
     772                AC_DEFINE([_HAVE_CODIPACK_],[1],[with codipack in ISSM src])
     773                AC_DEFINE([_HAVE_AD_],[1],[with AD in ISSM src])
     774                AC_SUBST([CODIPACKINCL])
     775        fi
     776        AM_CONDITIONAL([CODIPACK], [test x$HAVE_CODIPACK = xyes])
     777   AM_COND_IF(CODIPACK,[CXXFLAGS+=" -std=c++11"])
     778        dnl }}}
     779        dnl tapeallocation {{{
     780        AC_ARG_ENABLE([tape-alloc], dnl feature
     781                AS_HELP_STRING([--enable-tape-alloc],[turn tape allocation support on]),
     782                [enable_tape_alloc=$enableval], [enable_tape_alloc=no])
     783
     784        dnl check whether enabled
     785        AC_MSG_CHECKING(for tape memory allocation)
     786        if test "x$enable_tape_alloc" = xyes; then
     787                AC_DEFINE([_AD_TAPE_ALLOC_],[1],[Macro to enable a priori tape allocation for AD])
     788        fi
     789        AC_MSG_RESULT($enable_tape_alloc)
     790        dnl }}}
    747791        dnl adolc{{{
    748792        AC_ARG_WITH([adolc-dir],
    749793                AS_HELP_STRING([--with-adolc-dir=DIR], [adolc root directory.]),
    750                 [ADOLC_ROOT=$withval],[ADOLC_ROOT="no"]) 
     794                [ADOLC_ROOT=$withval],[ADOLC_ROOT="no"])
    751795
    752796        dnl Check whether adolc is enabled
     
    761805        fi
    762806        AC_MSG_RESULT($HAVE_ADOLC)
    763        
     807
    764808        dnl adolc headers and libraries
    765809        if test "x$HAVE_ADOLC" == "xyes"; then
     
    773817        fi
    774818        AM_CONDITIONAL([ADOLC], [test x$HAVE_ADOLC = xyes])
    775         AM_COND_IF(ADOLC,[CXXFLAGS+=" -std=c++11"])
     819   AM_COND_IF(ADOLC,[CXXFLAGS+=" -std=c++11"])
    776820        dnl }}}
    777821        dnl adolc-version{{{
    778822        AC_ARG_WITH([adolc-version],
    779823                AS_HELP_STRING([--with-adolc-version=number], [adolc version.]),
    780                 [ADOLC_VERSION=$withval],[ADOLC_VERSION=2]) 
    781         AC_MSG_CHECKING(for adolc-version) 
     824                [ADOLC_VERSION=$withval],[ADOLC_VERSION=2])
     825        AC_MSG_CHECKING(for adolc-version)
    782826
    783827        AC_DEFINE_UNQUOTED([_ADOLC_VERSION_],$ADOLC_VERSION,[ADOLC version])
     
    787831        AC_ARG_WITH([adic2-dir],
    788832          AS_HELP_STRING([--with-adic2-dir=DIR], [adic2 root directory.]),
    789           [ADIC2_ROOT=$withval],[ADIC2_ROOT="no"]) 
     833          [ADIC2_ROOT=$withval],[ADIC2_ROOT="no"])
    790834
    791835        dnl Check whether adic2 is enabled
     
    815859          AS_HELP_STRING([--with-atlas-dir=DIR],[atlas root directory]),
    816860          [ATLAS_ROOT=$withval],[ATLAS_ROOT="no"])
    817                          
     861
    818862        dnl Check whether atlas is enabled
    819863        AC_MSG_CHECKING(for atlas and cblas libraries)
     
    836880                        ;;
    837881                        *linux*)
    838                         ATLASLIB=-L"$ATLAS_ROOT/lib -lcblas -latlas -lm " 
     882                        ATLASLIB=-L"$ATLAS_ROOT/lib -lcblas -latlas -lm "
    839883                        ;;
    840884                        *darwin*)
    841                         ATLASLIB=-L"$ATLAS_ROOT/lib -lcblas -latlas -lm" 
     885                        ATLASLIB=-L"$ATLAS_ROOT/lib -lcblas -latlas -lm"
    842886                        ;;
    843887                esac
     
    849893        AC_ARG_WITH([gsl-dir],
    850894          AS_HELP_STRING([--with-gsl-dir=DIR], [gsl root directory.]),
    851           [GSL_ROOT=$withval],[GSL_ROOT="no"]) 
     895          [GSL_ROOT=$withval],[GSL_ROOT="no"])
    852896
    853897        dnl Check whether gsl is enabled
     
    862906        fi
    863907        AC_MSG_RESULT($HAVE_GSL)
    864        
     908
    865909        dnl gsl headers and libraries
    866910        if test "x$HAVE_GSL" == "xyes"; then
     
    877921        AM_CONDITIONAL([GSL], [test x$HAVE_GSL = xyes])
    878922        dnl }}}
    879         dnl adjoinable-mpi{{{
     923        dnl ampi (ADOLC){{{
    880924        AC_ARG_WITH([ampi-dir],
    881925          AS_HELP_STRING([--with-ampi-dir=DIR], [adjoinable mpi root directory.]),
    882           [AMPI_ROOT=$withval],[AMPI_ROOT="no"]) 
     926          [AMPI_ROOT=$withval],[AMPI_ROOT="no"])
    883927
    884928        dnl Check whether ampi is enabled
     
    893937        fi
    894938        AC_MSG_RESULT($HAVE_AMPI)
    895        
     939
    896940        dnl ampi headers and libraries
    897941        if test "x$HAVE_AMPI" == "xyes"; then
     
    912956        AM_CONDITIONAL([AMPI], [test x$HAVE_AMPI = xyes])
    913957        dnl }}}
     958        dnl adjointmpi (CoDiPack){{{
     959        AC_ARG_WITH([adjointmpi-dir],
     960          AS_HELP_STRING([--with-adjointmpi-dir=DIR], [adjoinable mpi root directory.]),
     961          [ADJOINTMPI_ROOT=$withval],[ADJOINTMPI_ROOT="no"])
     962
     963        dnl Check whether adjointmpi is enabled
     964        AC_MSG_CHECKING([for adjointmpi])
     965        if test "x$ADJOINTMPI_ROOT" = "xno" ; then
     966                HAVE_ADJOINTMPI=no
     967        else
     968                HAVE_ADJOINTMPI=yes
     969                if ! test -d "$ADJOINTMPI_ROOT"; then
     970                        AC_MSG_ERROR([adjointmpi directory provided ($ADJOINTMPI_ROOT) does not exist]);
     971                fi
     972        fi
     973        AC_MSG_RESULT($HAVE_ADJOINTMPI)
     974
     975        dnl adjointmpi headers and libraries
     976        if test "x$HAVE_ADJOINTMPI" == "xyes"; then
     977                if test "x$CODIPACK_ROOT" == "xno"; then
     978                        AC_MSG_ERROR([cannot run adjoint mpi without CoDiPack]);
     979                fi
     980                ADJOINTMPIINCL="-I$ADJOINTMPI_ROOT/include"
     981                ADJOINTMPILIB="-L$ADJOINTMPI_ROOT/lib  -lAMPI"
     982                dnl Also set _HAVE_AMPI_, because the interface is (almost) the
     983                dnl same as for adjoinable mpi...
     984                AC_DEFINE([_HAVE_AMPI_],[1],[with adjoint mpi in ISSM src])
     985                AC_DEFINE([_HAVE_ADJOINTMPI_],[1],[with adjoint mpi in ISSM src])
     986                AC_SUBST([ADJOINTMPIINCL])
     987                AC_SUBST([ADJOINTMPILIB])
     988        fi
     989        AM_CONDITIONAL([ADJOINTMPI], [test x$HAVE_ADJOINTMPI = xyes])
     990        dnl }}}
     991        dnl medipack (CoDiPack, ADOLC dev){{{
     992        AC_ARG_WITH([medipack-dir],
     993          AS_HELP_STRING([--with-medipack-dir=DIR], [MeDiPack root directory.]),
     994          [MEDIPACK_ROOT=$withval],[MEDIPACK_ROOT="no"])
     995
     996        dnl Check whether medipack is enabled
     997        AC_MSG_CHECKING([for medipack])
     998        if test "x$MEDIPACK_ROOT" = "xno" ; then
     999                HAVE_MEDIPACK=no
     1000        else
     1001                HAVE_MEDIPACK=yes
     1002                if ! test -d "$MEDIPACK_ROOT"; then
     1003                        AC_MSG_ERROR([medipack directory provided ($MEDIPACK_ROOT) does not exist]);
     1004                fi
     1005        fi
     1006        AC_MSG_RESULT($HAVE_MEDIPACK)
     1007
     1008        dnl medipack headers and libraries
     1009        if test "x$HAVE_MEDIPACK" == "xyes"; then
     1010                if test "x$CODIPACK_ROOT" == "xno"; then
     1011                        AC_MSG_ERROR([cannot run MeDiPack without CoDiPack]);
     1012                fi
     1013                MEDIPACKINCL="-I$MEDIPACK_ROOT/include -I$MEDIPACK_ROOT/src"
     1014                dnl Also set _HAVE_AMPI_, because the interface is (almost) the
     1015                dnl same as for adjoinable mpi...
     1016                AC_DEFINE([_HAVE_AMPI_],[1],[with adjoint mpi in ISSM src])
     1017                AC_DEFINE([_HAVE_MEDIPACK_],[1],[with MeDiPack in ISSM src])
     1018                AC_SUBST([MEDIPACKINCL])
     1019        fi
     1020        AM_CONDITIONAL([MEDIPACK], [test x$HAVE_MEDIPACK = xyes])
     1021
     1022        dnl }}}
    9141023        dnl rose{{{
    9151024        AC_ARG_WITH([rose-dir],
    9161025          AS_HELP_STRING([--with-rose-dir=DIR], [rose root directory.]),
    917           [ROSE_ROOT=$withval],[ROSE_ROOT="no"]) 
     1026          [ROSE_ROOT=$withval],[ROSE_ROOT="no"])
    9181027
    9191028        dnl Check whether rose is enabled
     
    9411050        dnl mpi{{{
    9421051        AC_MSG_CHECKING(for mpi)
    943        
     1052
    9441053        AC_ARG_WITH([mpi-include],
    9451054          AS_HELP_STRING([--with-mpi-include=DIR],[mpi include directory, necessary for parallel build]),
     
    9541063          [MPI_LIBFLAGS=$withval],[MPI_LIBFLAGS=""])
    9551064
    956        
     1065
    9571066        if test -z "$MPI_INCLUDE" ; then
    9581067                HAVE_MPI=no
     
    9801089                if  test x$IS_WINDOWS = xyes; then
    9811090                        MPIINCL=/I"$MPI_INCLUDE"
    982                 else 
     1091                else
    9831092                        MPIINCL=-I"$MPI_INCLUDE"
    9841093                fi
     
    9961105          AS_HELP_STRING([--with-petsc-dir=DIR],[PETSc root directory, necessary for parallel build]),
    9971106          [PETSC_ROOT=$withval],[PETSC_ROOT="no"])
    998                
     1107
    9991108        dnl Check whether petsc is enabled
    10001109        AC_MSG_CHECKING([for petsc])
     
    10331142                        AC_MSG_RESULT(no)
    10341143                fi
    1035        
     1144
    10361145                AC_ARG_WITH([petsc-arch],
    10371146                  AS_HELP_STRING([--with-petsc-arch=DIR],[PETSc arch, necessary for PETSc < 3.0]),
     
    10501159                 PETSCINCL+=" $PETSC_ROOT/include/$PETSC_ARCH"
    10511160                fi
    1052                
     1161
    10531162                case "${host_os}" in
    10541163                                *cygwin*)
     
    10691178                                if test "x$host_os_version" = "x3.0.101-0.31.1_1.0502.8394-cray_gem_s" ; then
    10701179                                        PETSCLIB="-L$PETSC_ROOT/lib -lcraypetsc_gnu_real -lmetis"
    1071                                 fi 
     1180                                fi
    10721181                                ;;
    10731182                                *darwin*)
     
    11221231
    11231232                        if test "$METIS_VERSION" = "4" ; then
    1124                                 METISINCL=-I"$METIS_ROOT/Lib" 
     1233                                METISINCL=-I"$METIS_ROOT/Lib"
    11251234                                case "${host_os}" in
    11261235                                        *cygwin*)
    1127                                         METISINCL="/I`cygpath -m $METIS_ROOT/Lib`" 
     1236                                        METISINCL="/I`cygpath -m $METIS_ROOT/Lib`"
    11281237                                        METISLIB="-Wl,/link -Wl,/LIBPATH:`cygpath -m $METIS_ROOT` -Wl,libmetis.lib"
    11291238                                        ;;
     
    11501259                                        ;;
    11511260                                esac
    1152                                 METISINCL=-I"$METIS_ROOT/include" 
     1261                                METISINCL=-I"$METIS_ROOT/include"
    11531262                                AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
    11541263                        fi
     
    11641273        AC_ARG_WITH([tao-dir],
    11651274                AS_HELP_STRING([--with-tao-dir=DIR], [tao root directory.]),
    1166                 [TAO_ROOT=$withval],[TAO_ROOT="no"]) 
     1275                [TAO_ROOT=$withval],[TAO_ROOT="no"])
    11671276
    11681277        dnl Check whether tao is enabled
     
    11991308        AC_ARG_WITH([m1qn3-dir],
    12001309                AS_HELP_STRING([--with-m1qn3-dir=DIR], [m1qn3 root directory.]),
    1201                 [M1QN3_ROOT=$withval],[M1QN3_ROOT="no"]) 
     1310                [M1QN3_ROOT=$withval],[M1QN3_ROOT="no"])
    12021311
    12031312        dnl Check whether m1qn3 is enabled
     
    12121321        fi
    12131322        AC_MSG_RESULT($HAVE_M1QN3)
    1214        
     1323
    12151324        dnl m1qn3 headers and libraries
    12161325        if test "x$HAVE_M1QN3" == "xyes"; then
    1217           M1QN3LIB="$M1QN3_ROOT/libm1qn3.a $M1QN3_ROOT//libddot.a"
     1326          M1QN3LIB="$M1QN3_ROOT/libm1qn3.a $M1QN3_ROOT/libddot.a"
    12181327          AC_DEFINE([_HAVE_M1QN3_],[1],[with M1QN3 in ISSM src])
    12191328          AC_SUBST([M1QN3LIB])
     
    12231332        AC_ARG_WITH([proj4-dir],
    12241333                AS_HELP_STRING([--with-proj4-dir=DIR], [proj4 root directory.]),
    1225                 [PROJ4_ROOT=$withval],[PROJ4_ROOT="no"]) 
     1334                [PROJ4_ROOT=$withval],[PROJ4_ROOT="no"])
    12261335
    12271336        dnl Check whether proj4 is enabled
     
    12361345        fi
    12371346        AC_MSG_RESULT($HAVE_PROJ4)
    1238        
     1347
    12391348        dnl proj4 headers and libraries
    12401349        if test "x$HAVE_PROJ4" == "xyes"; then
     
    12511360          AS_HELP_STRING([--with-slepc-dir=DIR],[slepc root directory]),
    12521361          [SLEPC_ROOT=$withval],[SLEPC_ROOT="no"])
    1253                          
     1362
    12541363        dnl Check whether slepc is enabled
    12551364        AC_MSG_CHECKING([for slepc])
     
    12631372        fi
    12641373        AC_MSG_RESULT($HAVE_SLEPC)
    1265        
     1374
    12661375        dnl slepc headers and libraries
    12671376        if test "x$HAVE_SLEPC" == "xyes"; then
     
    12771386          AS_HELP_STRING([--with-shapelib-dir=DIR], [shapelib root directory]),
    12781387          [SHAPELIB_ROOT=$withval],[SHAPELIB_ROOT="no"])
    1279                          
     1388
    12801389        dnl Check whether shapelib is enabled
    12811390        AC_MSG_CHECKING([for shapelib])
     
    12891398        fi
    12901399        AC_MSG_RESULT($HAVE_SHAPELIB)
    1291        
     1400
    12921401        dnl shapelib headers and libraries
    12931402        if test "x$HAVE_SHAPELIB" == "xyes"; then
     
    13091418          AS_HELP_STRING([--with-scalapack-lib=LIBS],[scalapack libraries to include]),
    13101419          [SCALAPACKLIB=$withval],[SCALAPACKLIB="no"])
    1311                          
     1420
    13121421        dnl Check whether scalapack is enabled
    13131422        AC_MSG_CHECKING([for scalapack])
     
    13291438        fi
    13301439        AC_MSG_RESULT($HAVE_SCALAPACK)
    1331        
     1440
    13321441        dnl scalapack headers and libraries
    13331442        if test "x$HAVE_SCALAPACK" = "xyes"; then
     
    13401449          AS_HELP_STRING([--with-blas-lapack-dir=DIR],[blas-lapack root directory]),
    13411450          [BLASLAPACK_ROOT=$withval],[BLASLAPACK_ROOT="no"])
    1342                          
     1451
    13431452        dnl Check whether blas-lapack is enabled
    13441453        AC_MSG_CHECKING([for blas-lapack])
     
    13521461        fi
    13531462        AC_MSG_RESULT($HAVE_BLASLAPACK)
    1354        
     1463
    13551464        dnl blas-lapack headers and libraries
    13561465        if test "x$HAVE_BLASLAPACK" == "xyes"; then
     
    13621471                  ;;
    13631472                *linux*)
    1364                   BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
     1473                  BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas "
    13651474                  ;;
    13661475                *darwin*)
    1367                   BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
     1476                  BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas "
    13681477                  ;;
    13691478                esac
     
    13931502        dnl plapack{{{
    13941503        AC_MSG_CHECKING(for plapack)
    1395        
     1504
    13961505        AC_ARG_WITH([plapack-lib],
    13971506          AS_HELP_STRING([--with-plapack-lib = lib],[plapack library]),
    13981507          [PLAPACK_LIB=$withval],[PLAPACK_LIB=""])
    1399        
     1508
    14001509        AC_ARG_WITH([plapack-include],
    14011510                          AS_HELP_STRING([--with-plapack-include = include],
    14021511                                                         [plapack include ]),
    14031512                          [PLAPACK_INCLUDE=$withval],[PLAPACK_INCLUDE=""])
    1404          
     1513
    14051514        if test -n "$PLAPACK_LIB"; then
    14061515                if test -n "$PLAPACK_INCLUDE"; then
    1407                
     1516
    14081517                        HAVE_PLAPACK=yes
    14091518                        PLAPACKINCL="$PLAPACK_INCLUDE"
     
    14241533          AS_HELP_STRING([--with-mumps-dir=DIR],[mumps root directory]),
    14251534          [MUMPS_ROOT=$withval],[MUMPS_ROOT="no"])
    1426                          
     1535
    14271536        dnl Check whether mumps is enabled
    14281537        AC_MSG_CHECKING([for mumps])
     
    14361545        fi
    14371546        AC_MSG_RESULT($HAVE_MUMPS)
    1438        
     1547
    14391548        dnl mumps headers and libraries
    14401549        if test "x$HAVE_MUMPS" == "xyes"; then
     
    14551564        if test "x$HAVE_MUMPS" != "xyes"; then
    14561565        AC_MSG_CHECKING(for mumps2 (stand alone))
    1457        
     1566
    14581567        AC_ARG_WITH([mumps2-include],
    14591568          AS_HELP_STRING([--with-mumps2-include=DIR],[mumps2 include directory, necessary for parallel build]),
     
    14641573          [MUMPS_LIBFLAGS=$withval],[MUMPS_LIBFLAGS=""])
    14651574
    1466        
     1575
    14671576        if test -z "$MUMPS_INCLUDE" ; then
    14681577                HAVE_MUMPS=no
     
    14901599                AS_HELP_STRING([--with-blacs-dir=DIR],[blacs root directory]),
    14911600                          [BLACS_ROOT=$withval],[BLACS_ROOT="no"])
    1492                          
     1601
    14931602        dnl Check whether blacs is enabled
    14941603        AC_MSG_CHECKING([for blacs])
     
    15021611        fi
    15031612        AC_MSG_RESULT($HAVE_BLACS)
    1504        
     1613
    15051614        dnl blacs headers and libraries
    15061615        if test "x$HAVE_BLACS" == "xyes"; then
     
    15161625          AS_HELP_STRING([--with-hypre-dir=DIR],[hypre root directory]),
    15171626                          [HYPRE_ROOT=$withval],[HYPRE_ROOT="no"])
    1518                          
     1627
    15191628        dnl Check whether hypre is enabled
    15201629        AC_MSG_CHECKING([for hypre])
     
    15901699                fi
    15911700          dnl }}}
    1592 dnl superlu{{{ 
     1701dnl superlu{{{
    15931702        AC_ARG_WITH([superlu-dir],
    15941703                                AS_HELP_STRING([--with-superlu-dir=DIR],[superlu root directory]),
     
    16061715        fi
    16071716        AC_MSG_RESULT($HAVE_SUPERLU)
    1608        
     1717
    16091718        dnl superlu headers and libraries
    16101719        if test "x$HAVE_SUPERLU" == "xyes"; then
     
    16161725         fi
    16171726         dnl }}}
    1618 dnl spooles{{{ 
     1727dnl spooles{{{
    16191728        AC_ARG_WITH([spooles-dir],
    16201729                                AS_HELP_STRING([--with-spooles-dir=DIR],[spooles root directory]),
     
    16321741        fi
    16331742        AC_MSG_RESULT($HAVE_SPOOLES)
    1634        
     1743
    16351744        dnl spooles headers and libraries
    16361745        if test "x$HAVE_SPOOLES" == "xyes"; then
     
    16421751         fi
    16431752         dnl }}}
    1644 dnl pastix{{{ 
     1753dnl pastix{{{
    16451754        AC_ARG_WITH([pastix-dir],
    16461755                                AS_HELP_STRING([--with-pastix-dir=DIR],[pastix root directory]),
     
    16581767        fi
    16591768        AC_MSG_RESULT($HAVE_PASTIX)
    1660        
     1769
    16611770        dnl pastix headers and libraries
    16621771        if test "x$HAVE_PASTIX" == "xyes"; then
     
    16721781          AS_HELP_STRING([--with-ml-dir=DIR],[ml root directory]),
    16731782                          [ML_ROOT=$withval],[ML_ROOT="no"])
    1674                          
     1783
    16751784        dnl Check whether ml is enabled
    16761785        AC_MSG_CHECKING([for ml])
     
    16841793        fi
    16851794        AC_MSG_RESULT($HAVE_ML)
    1686        
     1795
    16871796        dnl ml headers and libraries
    16881797        if test "x$HAVE_ML" == "xyes"; then
     
    16981807                  AS_HELP_STRING([--with-umfpack-dir=DIR],[UMFPACK root directory]),
    16991808                                        [UMFPACK_ROOT=$withval],[UMFPACK_ROOT="no"])
    1700                          
     1809
    17011810        dnl Check whether umfpack is enabled
    17021811        AC_MSG_CHECKING([for umfpack])
     
    17101819        fi
    17111820        AC_MSG_RESULT($HAVE_UMFPACK)
    1712        
     1821
    17131822        dnl umfpack headers and libraries
    17141823        if test "x$HAVE_UMFPACK" == "xyes"; then
     
    17381847                AC_ARG_WITH([math77-dir],
    17391848                                        AS_HELP_STRING([--with-math77-dir=DIR], [math77 root directory.]),
    1740                                         [MATH77_ROOT=$withval],[MATH77_ROOT="no"]) 
    1741                  
     1849                                        [MATH77_ROOT=$withval],[MATH77_ROOT="no"])
     1850
    17421851        dnl Check whether math77 is enabled
    17431852        AC_MSG_CHECKING([for math77])
     
    17511860        fi
    17521861        AC_MSG_RESULT($HAVE_MATH77)
    1753        
     1862
    17541863        dnl math77 headers and libraries
    17551864        if test "x$HAVE_MATH77" == "xyes"; then
     
    17621871        AC_ARG_WITH([fortran],
    17631872                AS_HELP_STRING([--with-fortran = YES], [do we compile fortran code (default is yes)]),
    1764                 [FORTRAN=$withval],[FORTRAN=yes]) 
     1873                [FORTRAN=$withval],[FORTRAN=yes])
    17651874        AC_MSG_CHECKING(for fortran compilation)
    17661875        if test "x$FORTRAN" = "xyes"; then
     
    18301939        AC_ARG_WITH([meteoio-dir],
    18311940          AS_HELP_STRING([--with-meteoio-dir=DIR], [use meteoio in conjunction with snowpack model.]),
    1832           [METEOIO_ROOT=$withval],[METEOIO_ROOT="no"]) 
     1941          [METEOIO_ROOT=$withval],[METEOIO_ROOT="no"])
    18331942
    18341943        dnl Check whether meteoio is enabled
     
    18431952        fi
    18441953        AC_MSG_RESULT($HAVE_METEOIO)
    1845        
     1954
    18461955        dnl meteoio headers and libraries
    18471956        if test "x$HAVE_METEOIO" == "xyes"; then
     
    18581967        AC_ARG_WITH([snowpack-dir],
    18591968          AS_HELP_STRING([--with-snowpack-dir=DIR], [use snowpack for surface mass balance model.]),
    1860           [SNOWPACK_ROOT=$withval],[SNOWPACK_ROOT="no"]) 
     1969          [SNOWPACK_ROOT=$withval],[SNOWPACK_ROOT="no"])
    18611970
    18621971        dnl Check whether snowpack is enabled
     
    18711980        fi
    18721981        AC_MSG_RESULT($HAVE_SNOWPACK)
    1873        
     1982
    18741983        dnl snowpack headers and libraries
    18751984        if test "x$HAVE_SNOWPACK" == "xyes"; then
     
    18861995        AC_ARG_WITH([neopz-dir],
    18871996                AS_HELP_STRING([--with-neopz-dir=DIR], [neopz root directory.]),
    1888                 [NEOPZ_ROOT=$withval],[NEOPZ_ROOT="no"]) 
     1997                [NEOPZ_ROOT=$withval],[NEOPZ_ROOT="no"])
    18891998
    18901999        dnl Check whether neopz is enabled
     
    18992008        fi
    19002009        AC_MSG_RESULT($HAVE_NEOPZ)
    1901        
     2010
    19022011        dnl neopz headers and libraries
    19032012        if test "x$HAVE_NEOPZ" == "xyes"; then
     
    19382047        AC_ARG_WITH([bamg],
    19392048                AS_HELP_STRING([--with-bamg = YES],[compile with bamg capabilities (default is yes)]),
    1940                 [BAMG=$withval],[BAMG=yes]) 
     2049                [BAMG=$withval],[BAMG=yes])
    19412050        AC_MSG_CHECKING(for bamg capability compilation)
    19422051
     
    19522061        AC_ARG_WITH([ocean],
    19532062                AS_HELP_STRING([--with-ocean = YES],[compile with ice/ocean coupling (default is no)]),
    1954                 [OCEAN=$withval],[OCEAN=no]) 
     2063                [OCEAN=$withval],[OCEAN=no])
    19552064        AC_MSG_CHECKING(for ice/ocean capability compilation)
    19562065
     
    19662075        AC_ARG_WITH([kml],
    19672076                AS_HELP_STRING([--with-kml = YES],[compile with kml capabilities (default is no)]),
    1968                 [KML=$withval],[KML=no]) 
     2077                [KML=$withval],[KML=no])
    19692078        AC_MSG_CHECKING(for kml capability compilation)
    19702079
     
    19802089        AC_ARG_WITH([kriging],
    19812090                AS_HELP_STRING([--with-kriging = YES],[compile with kriging capabilities (default is yes)]),
    1982                 [KRIGING=$withval],[KRIGING=yes]) 
     2091                [KRIGING=$withval],[KRIGING=yes])
    19832092        AC_MSG_CHECKING(for kriging capability compilation)
    19842093
     
    19972106        AC_ARG_WITH([ios],
    19982107                AS_HELP_STRING([--with-ios = YES], [compile with iOS capabilities (default is no, alternatives are yes)]),
    1999                 [IOS=$withval],[IOS=no]) 
     2108                [IOS=$withval],[IOS=no])
    20002109        AC_MSG_CHECKING(for iOS compilation)
    20012110
     
    20162125        AC_ARG_WITH([android],
    20172126                AS_HELP_STRING([--with-android = EXE], [compile with android capabilities (default is no, alternatives are exe and jni)]),
    2018                 [ANDROID=$withval],[ANDROID=no]) 
     2127                [ANDROID=$withval],[ANDROID=no])
    20192128        AC_MSG_CHECKING(for android capability compilation)
    20202129
     
    20432152        AC_ARG_WITH([android-ndk],
    20442153          AS_HELP_STRING([--with-android-ndk=DIR], [android-ndk root directory.]),
    2045           [ANDROID_NDK_ROOT=$withval],[ANDROID_NDK_ROOT=""]) 
     2154          [ANDROID_NDK_ROOT=$withval],[ANDROID_NDK_ROOT=""])
    20462155        AC_MSG_CHECKING(with android ndk)
    2047        
     2156
    20482157        if test -d "$ANDROID_NDK_ROOT"; then
    20492158                dnl defaults
     
    20612170        dnl other options
    20622171        dnl optimization{{{
    2063         dnl bypass standard optimization -g -O2 ? 
     2172        dnl bypass standard optimization -g -O2 ?
    20642173        AC_ARG_WITH([cxxoptflags],
    20652174          AS_HELP_STRING([--with-cxxoptflags = CXXOPTFLAGS], [optimization using CXX flags, ex: --with-cxxoptflags=-march=opteron -O3]),
    2066           [CXXOPTFLAGS=$withval],[CXXOPTFLAGS="-g -O2 -fPIC"]) 
     2175          [CXXOPTFLAGS=$withval],[CXXOPTFLAGS="-g -O2 -fPIC"])
    20672176        AC_MSG_CHECKING(for c++ optimization flags)
    20682177        AC_SUBST([CXXOPTFLAGS])
     
    20792188        MULTITHREADINLIB=""
    20802189        if test "$NUMTHREADS_VALUE" != "1"; then
    2081                
     2190
    20822191                MULTITHREADINGLIB="-lpthread -lrt"
    20832192                case "${host_os}" in
     
    20942203                AC_DEFINE([_MULTITHREADING_],[1],[with numthreads enabled])
    20952204        fi
     2205        dnl check that it is an integer
     2206        if [[ "$NUMTHREADS_VALUE" -eq   "$NUMTHREADS_VALUE" 2> /dev/null ]] ; then
     2207         dnl cool we have an integer
     2208         :
     2209        else
     2210         AC_MSG_ERROR([Number of threads provided ($NUMTHREADS_VALUE) is not an integer]);
     2211        fi
    20962212        AC_DEFINE_UNQUOTED([_NUMTHREADS_],[$NUMTHREADS_VALUE],[number of threads])
    20972213        AC_SUBST([MULTITHREADINGLIB])
    2098         AC_MSG_RESULT($NUMTHREADS_VALUE) 
     2214        AC_MSG_RESULT($NUMTHREADS_VALUE)
    20992215        dnl }}}
    21002216        dnl 64bit {{{
    21012217        AC_ARG_WITH([64bit-indices],
    21022218          AS_HELP_STRING([--with-64bit-indices = bool], [use 64 bit integers, default 0, ex: --with-64bit-indices=1]),
    2103           [USE_64BIT_INDICES=$withval],[USE_64BIT_INDICES=0]) 
     2219          [USE_64BIT_INDICES=$withval],[USE_64BIT_INDICES=0])
    21042220        AC_MSG_CHECKING(for 64 bit indices)
    21052221
     
    21322248                          AC_MSG_ERROR([need fortran compiler to compile GiaIvins (or use --without-GiaIvins )]);
    21332249                 fi
    2134                        
     2250
    21352251       dnl check that fortran is provided if Love is on
    21362252                 if test "$HAVE_LOVE" = "yes" &&  test "$HAVE_FORTRAN" = "no" ; then
     
    21422258                                AC_MSG_ERROR([need mpi if using the metis partitioner!]);
    21432259                  fi
    2144                
     2260
    21452261                dnl check that if we run adolc, we don't compile krigging.exe
    21462262                if test "$HAVE_ADOLC" = "yes"  && test "$HAVE_KRIGING" = "yes" ; then
     
    21512267                        AC_MSG_ERROR([cannot compile ISSM with both PETSc and adolc]);
    21522268                fi
     2269                if test "$HAVE_ADOLC" = "yes"  && test "$HAVE_CODIPACK" = "yes" ; then
     2270                        AC_MSG_ERROR([cannot compile ISSM with both ADOLC and CoDiPack]);
     2271                fi
     2272                if test "$HAVE_ADJOINTMPI" = "yes"  && test "$HAVE_MEDIPACK" = "yes" ; then
     2273                        AC_MSG_ERROR([cannot compile ISSM with both MeDiPack and AdjointMPI]);
     2274                fi
    21532275                dnl check that if we run meteoio, we have snowpack also
    21542276                if test "$HAVE_METEOIO" = "yes"  && test "$HAVE_SNOWPACK" = "no" ; then
  • issm/trunk/src

  • issm/trunk/src/c/Makefile.am

    r23189 r23394  
    1 AM_CPPFLAGS = @NEOPZINCL@ @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @AMPIINCL@ @MPIINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @ANDROID_NDKINCL@ @METEOIOINCL@ @SNOWPACKINCL@ @PROJ4INCL@
     1AM_CPPFLAGS = @NEOPZINCL@ @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @AMPIINCL@ @ADJOINTMPIINCL@ @MEDIPACKINCL@ @MPIINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @CODIPACKINCL@ @GSLINCL@ @BOOSTINCL@ @ANDROID_NDKINCL@ @METEOIOINCL@ @SNOWPACKINCL@ @PROJ4INCL@
    22
    33AUTOMAKE_OPTIONS = subdir-objects
     
    5151                                         ./modules/BamgTriangulatex/BamgTriangulatex.cpp
    5252
    53 #do not include AmrBamg with ADOLC
     53#do not include AmrBamg with AD
    5454if ADOLC
    5555else
     56if CODIPACK
     57else
    5658issm_sources += ./classes/AmrBamg.cpp
     59endif
    5760endif
    5861endif
     
    172175                                        ./shared/Elements/PrintArrays.cpp\
    173176                                        ./shared/Elements/PddSurfaceMassBalance.cpp\
     177                                        ./shared/Elements/PddSurfaceMassBalanceSicopolis.cpp\
    174178                                        ./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp\
    175179                                        ./shared/Elements/ComputeMungsmTemperaturePrecipitation.cpp\
     
    320324                                        ./classes/Inputs/TetraInput.cpp
    321325#}}}
     326#ADJOINTMPI/MeDiPack sources {{{
     327if ADJOINTMPI
     328issm_sources += ./toolkits/codipack/ampi_interface.cpp
     329endif
     330if MEDIPACK
     331issm_sources += ./toolkits/codipack/ampi_interface.cpp
     332endif
     333# }}}
    322334#DAKOTA sources  {{{
    323335if DAKOTA
     
    632644if !WINDOWS
    633645if !STANDALONE_LIBRARIES
    634 libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB)   $(ADOLCLIB) $(AMPILIB) $(METEOIOLIB) $(SNOWPACKLIB)
     646libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB)   $(ADOLCLIB) $(AMPILIB) $(ADJOINTMPILIB) $(METEOIOLIB) $(SNOWPACKLIB)
    635647if FORTRAN
    636648libISSMCore_la_LIBADD += $(FLIBS) $(FORTRANLIB)
     
    714726
    715727#External packages
    716 LDADD +=  $(NEOPZLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(PETSCLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB)  $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(AMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB) $(PROJ4LIB)
     728LDADD +=  $(NEOPZLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(PETSCLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB)  $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(AMPILIB) $(ADJOINTMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB) $(PROJ4LIB)
    717729
    718730if FORTRAN
  • issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp

    r23189 r23394  
    4343                int smb_model;
    4444                iomodel->FindConstant(&smb_model,"md.smb.model");
    45                 if(smb_model==SMBpddEnum)     isdynamic=true;
    46                 if(smb_model==SMBd18opddEnum) isdynamic=true;
     45                if(smb_model==SMBpddEnum)                               isdynamic=true;
     46                if(smb_model==SMBd18opddEnum)                   isdynamic=true;
     47                if(smb_model==SMBpddSicopolisEnum)      isdynamic=true;
    4748        }
    4849
     
    12001201                _assert_((Hc+Ht)>0.);
    12011202                lambda = Hc/(Hc+Ht);
     1203                _assert_(lambda>=0.);
     1204                _assert_(lambda<=1.);
    12021205                kappa  = kappa_c*kappa_t/(lambda*kappa_t+(1.-lambda)*kappa_c); // ==(lambda/kappa_c + (1.-lambda)/kappa_t)^-1
    12031206        }       
  • issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp

    r23189 r23394  
    6565        femmodel->SetCurrentConfiguration(ExtrapolationAnalysisEnum);
    6666
    67         if(VerboseSolution()) _printf0_("extrapolation of " << EnumToStringx(extvar_enum) << ": call computational core:\n");
     67        if(VerboseSolution()) _printf0_("   extrapolation of " << EnumToStringx(extvar_enum) << ":\n");
    6868        solutionsequence_linear(femmodel);
    6969
  • issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp

    r22758 r23394  
    8080        iomodel->FetchDataToInput(elements,"md.mask.ice_levelset",MaskIceLevelsetEnum);
    8181        iomodel->FetchDataToInput(elements,"md.basalforcings.groundedice_melting_rate",BasalforcingsGroundediceMeltingRateEnum,0.);
    82         iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum);
    8382        iomodel->FetchDataToInput(elements,"md.initialization.vx",VxEnum);
    8483        iomodel->FetchDataToInput(elements,"md.initialization.vy",VyEnum);
     
    8988                iomodel->FetchDataToInput(elements,"md.mesh.vertexonbase",MeshVertexonbaseEnum);
    9089                iomodel->FetchDataToInput(elements,"md.mesh.vertexonsurface",MeshVertexonsurfaceEnum);
     90        }
     91
     92        /*Get what we need for ocean-induced basal melting*/
     93        int basalforcing_model;
     94        iomodel->FindConstant(&basalforcing_model,"md.basalforcings.model");
     95        switch(basalforcing_model){
     96                case FloatingMeltRateEnum:
     97                        iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum);
     98                        break;
     99                case LinearFloatingMeltRateEnum:
     100                        break;
     101                case MismipFloatingMeltRateEnum:
     102                        break;
     103                case MantlePlumeGeothermalFluxEnum:
     104                        break;
     105                case SpatialLinearFloatingMeltRateEnum:
     106                        iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum);
     107                        iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum);
     108                        iomodel->FetchDataToInput(elements,"md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum);
     109                        break;
     110                case BasalforcingsPicoEnum:
     111                        iomodel->FetchDataToInput(elements,"md.basalforcings.basin_id",BasalforcingsPicoBasinIdEnum);
     112                        break;
     113                default:
     114                        _error_("Basal forcing model "<<EnumToStringx(basalforcing_model)<<" not supported yet");
    91115        }
    92116}/*}}}*/
  • issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp

    r23189 r23394  
    313313        }
    314314        /*Intermediaries */
     315        int        smb_model;
    315316        IssmDouble dt,scalar,water_head;
    316         IssmDouble water_load,transfer;
     317        IssmDouble water_load,transfer,runoff_value;
    317318        IssmDouble epl_storing,epl_transmitivity;
    318319        IssmDouble Jdet;
    319320        IssmDouble residual,connectivity;
    320321
    321         IssmDouble *xyz_list     = NULL;
    322         Input*      old_wh_input = NULL;
     322        IssmDouble              *xyz_list                                                       = NULL;
     323        Input*                           old_wh_input                                   = NULL;
     324        Input*                           surface_runoff_input = NULL;
    323325
    324326        /*Fetch number of nodes and dof for this finite element*/
     
    334336        //basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
    335337        basalelement ->FindParam(&dt,HydrologydtEnum);
    336 
    337         Input* epl_thick_input = basalelement->GetInput(HydrologydcEplThicknessHydrostepEnum); _assert_(epl_thick_input);
    338         Input* sed_head_input  = basalelement->GetInput(SedimentHeadHydrostepEnum); _assert_(sed_head_input);
    339         Input* epl_head_input    = basalelement->GetInput(EplHeadHydrostepEnum); _assert_(epl_head_input);
    340         Input* water_input               = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(water_input);
    341         Input* residual_input  = basalelement->GetInput(SedimentHeadResidualEnum); _assert_(residual_input);
    342         Input* base_input                        = basalelement->GetInput(BaseEnum); _assert_(base_input);
     338        basalelement ->FindParam(&smb_model,SmbEnum);
     339
     340        Input*  epl_thick_input                  = basalelement->GetInput(HydrologydcEplThicknessHydrostepEnum); _assert_(epl_thick_input);
     341        Input*  sed_head_input                   = basalelement->GetInput(SedimentHeadHydrostepEnum); _assert_(sed_head_input);
     342        Input*  epl_head_input                   = basalelement->GetInput(EplHeadHydrostepEnum); _assert_(epl_head_input);
     343        Input*  basal_melt_input                 = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(basal_melt_input);
     344        Input*  residual_input                   = basalelement->GetInput(SedimentHeadResidualEnum); _assert_(residual_input);
     345        Input*  base_input                                       = basalelement->GetInput(BaseEnum); _assert_(base_input);
    343346
    344347        if(dt!= 0.){
    345348                old_wh_input = basalelement->GetInput(EplHeadOldEnum);            _assert_(old_wh_input);
    346349        }
     350        if(smb_model==SMBgradientscomponentsEnum){
     351                surface_runoff_input = basalelement->GetInput(SmbRunoffEnum); _assert_(surface_runoff_input);
     352        }
     353
    347354        /* Start  looping on the number of gaussian points: */
    348355        Gauss* gauss           = basalelement->NewGauss(2);
     
    355362
    356363                /*Loading term*/
    357                 water_input->GetInputValue(&water_load,gauss);
    358                 scalar = Jdet*gauss->weight*(water_load);
     364                basal_melt_input->GetInputValue(&water_load,gauss);
     365                if(surface_runoff_input) surface_runoff_input->GetInputValue(&runoff_value,gauss);
     366                else                     runoff_value = 0.;
     367                scalar = Jdet*gauss->weight*(water_load+runoff_value);
    359368                //scalar = Jdet*gauss->weight*(water_load)/epl_transmitivity;
    360369                if(dt!=0.) scalar = scalar*dt;
     
    524533        IssmDouble  EPLgrad2;
    525534        IssmDouble  EPL_N;
     535        IssmDouble  opening,closing;
    526536
    527537        femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
     
    589599                                EPLgrad2 = (epl_slopeX[i]*epl_slopeX[i])+(epl_slopeY[i]*epl_slopeY[i]);
    590600                                /*And proceed to the real thing*/
    591                                 thickness[i] = old_thickness[i]/(1.0
    592                                                                                                                                                                  -((rho_water*gravity*epl_conductivity*EPLgrad2*dt)/(rho_ice*latentheat))
    593                                                                                                                                                                  +((2.0*A*dt*pow(EPL_N,n))/(pow(n,n))));
     601                                opening=(rho_water*gravity*epl_conductivity*EPLgrad2*dt)/(rho_ice*latentheat);
     602                                closing=(2.0*A*dt*pow(EPL_N,n))/(pow(n,n));
     603                                /*implicit*/
     604                                thickness[i] = old_thickness[i]/(1.0-opening+closing);
     605                                /*explicit*/
     606                                //thickness[i] = old_thickness[i]*(1.0+opening-closing);
     607                                /*centered*/
     608                                //thickness[i] = old_thickness[i]*(1.0+opening-closing)/(1.0-opening+closing);
    594609                                /*Take care of otherthikening*/
    595610                                if(thickness[i]>max_thick){
     
    688703                if(old_active[i]>0.){
    689704                        vec_mask->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
    690                         /* If epl thickness gets under colapse thickness, close the layer */
    691                         if(epl_thickness[i]<colapse_thick){
     705                        /* If epl thickness gets under colapse thickness, close the layer if there is no residual*/
     706                        if(epl_thickness[i]<colapse_thick && residual[i]<=0.){
    692707                                vec_mask->SetValue(basalelement->nodes[i]->Sid(),0.,INS_VAL);
    693708                                recurence->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
    694709                        }
    695                         /* //If epl head gets under base elevation, close the layer */
    696                         /* else if(eplhead[i]<(base[i]-1.0e-8)){ */
    697                         /*      vec_mask->SetValue(basalelement->nodes[i]->Sid(),0.,INS_VAL); */
    698                         /*      recurence->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL); */
    699                         /* } */
    700                 }
    701                 /*If node is now closed bring its thickness back to initial*/
     710                }
    702711                if (old_active[i]==0.){
    703                         epl_thickness[i]=init_thick;
    704712                        /*Activate if we have a residual from sediment*/
    705713                        if(residual[i]>0.){
    706714                                vec_mask->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
    707                                 if(old_active[i]==0.){
    708                                         recurence->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
    709                                 }
     715                                recurence->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
     716                        }
     717                        else{
     718                                /*If node is now closed bring its thickness back to initial*/
     719                                epl_thickness[i]=init_thick;
     720                                vec_mask->SetValue(basalelement->nodes[i]->Sid(),0.,INS_VAL);
    710721                        }
    711722                }
  • issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp

    r23189 r23394  
    1010        return 1;
    1111}/*}}}*/
    12 
    1312void HydrologyDCInefficientAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
    1413
     
    2928
    3029        /*retrieve some parameters: */
     30        bool   issmb;
     31        iomodel->FindConstant(&issmb,"md.transient.issmb");
    3132        iomodel->FindConstant(&hydrology_model,"md.hydrology.model");
    3233
     
    6364                parameters->AddObject(new DoubleParam(HydrologydcSedimentlimitEnum,sedimentlimit));
    6465        }
     66        if(!issmb){
     67                parameters->AddObject(iomodel->CopyConstantObject("md.smb.model",SmbEnum));
     68        }
     69
    6570  /*Requested outputs*/
    6671  iomodel->FindConstant(&requestedoutputs,&numoutputs,"md.hydrology.requested_outputs");
     
    6974  iomodel->DeleteData(&requestedoutputs,numoutputs,"md.hydrology.requested_outputs");
    7075}/*}}}*/
    71 
    7276void HydrologyDCInefficientAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
    7377
     
    105109                iomodel->FetchDataToInput(elements,"md.mesh.vertexonsurface",MeshVertexonsurfaceEnum);
    106110        }
    107 
    108111        if(isefficientlayer){
    109112                iomodel->FetchDataToInput(elements,"md.hydrology.mask_eplactive_node",HydrologydcMaskEplactiveNodeEnum);
    110113                iomodel->FetchDataToInput(elements,"md.initialization.epl_head",EplHeadHydrostepEnum);
    111114        }
    112 }/*}}}*/
    113 
     115
     116}/*}}}*/
    114117void HydrologyDCInefficientAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
    115118
     
    127130        iomodel->DeleteData(2,"md.mesh.vertexonbase","md.mesh.vertexonsurface");
    128131}/*}}}*/
    129 
    130132void HydrologyDCInefficientAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
    131133
     
    137139        IoModelToConstraintsx(constraints,iomodel,"md.hydrology.spcsediment_head",HydrologyDCInefficientAnalysisEnum,P1Enum);
    138140}/*}}}*/
    139 
    140141void HydrologyDCInefficientAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
    141142
     
    172173        _error_("not implemented");
    173174}/*}}}*/
    174 
    175175ElementVector* HydrologyDCInefficientAnalysis::CreateDVector(Element* element){/*{{{*/
    176176        /*Default, return NULL*/
    177177        return NULL;
    178178}/*}}}*/
    179 
    180179ElementMatrix* HydrologyDCInefficientAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
    181180_error_("Not implemented");
    182181}/*}}}*/
    183 
    184182ElementMatrix* HydrologyDCInefficientAnalysis::CreateKMatrix(Element* element){/*{{{*/
    185183
     
    307305        return Ke;
    308306}/*}}}*/
    309 
    310307ElementVector* HydrologyDCInefficientAnalysis::CreatePVector(Element* element){/*{{{*/
    311308
     
    342339        /*Intermediaries */
    343340        bool       active_element,isefficientlayer;
     341        int        smb_model;
    344342        IssmDouble dt,scalar,sediment_storing;
    345343        IssmDouble water_head,sediment_transmitivity;
    346         IssmDouble water_load,transfer;
     344        IssmDouble water_load,runoff_value,transfer;
    347345        IssmDouble Jdet;
    348346
    349347        IssmDouble *xyz_list             = NULL;
    350348        Input*      active_element_input = NULL;
    351         Input*      old_wh_input = NULL;
     349        Input*      old_wh_input         = NULL;
     350        Input*      surface_runoff_input = NULL;
    352351
    353352        /*Fetch number of nodes and dof for this finite element*/
     
    361360        basalelement->GetVerticesCoordinates(&xyz_list);
    362361        //basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
    363         basalelement ->FindParam(&dt,HydrologydtEnum);
     362        basalelement->FindParam(&dt,HydrologydtEnum);
    364363        basalelement->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
    365 
    366         Input* sed_head_input = basalelement->GetInput(SedimentHeadHydrostepEnum);
    367         Input* epl_head_input = basalelement->GetInput(EplHeadHydrostepEnum);
    368         Input* base_input                 = basalelement->GetInput(BaseEnum);
    369         Input* water_input        = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(water_input);
    370         Input* SedTrans_input = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum); _assert_(SedTrans_input);
     364        basalelement->FindParam(&smb_model,SmbEnum);
     365
     366        Input*  sed_head_input                   = basalelement->GetInput(SedimentHeadHydrostepEnum);
     367        Input*  epl_head_input                   = basalelement->GetInput(EplHeadHydrostepEnum);
     368        Input*  base_input                                       = basalelement->GetInput(BaseEnum);
     369        Input*  basal_melt_input                 = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(basal_melt_input);
     370        Input*  SedTrans_input                   = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum); _assert_(SedTrans_input);
    371371
    372372        if(dt!= 0.){
    373373                old_wh_input = basalelement->GetInput(SedimentHeadOldEnum);                  _assert_(old_wh_input);
    374374        }
     375        if(smb_model==SMBgradientscomponentsEnum){
     376                surface_runoff_input = basalelement->GetInput(SmbRunoffEnum); _assert_(surface_runoff_input);
     377        }
     378
    375379        /*Transfer related Inputs*/
    376380        if(isefficientlayer){
     
    388392                /*Loading term*/
    389393                if(!isefficientlayer){
    390                         water_input->GetInputValue(&water_load,gauss);
    391                         scalar = Jdet*gauss->weight*(water_load);
     394                        basal_melt_input->GetInputValue(&water_load,gauss);
     395                        if(surface_runoff_input) surface_runoff_input->GetInputValue(&runoff_value,gauss);
     396                        else                     runoff_value = 0.;
     397                        scalar = Jdet*gauss->weight*(water_load+runoff_value);
    392398                        //scalar = Jdet*gauss->weight*(water_load)/sediment_transmitivity;
    393399                        if(dt!=0.) scalar = scalar*dt;
     
    400406                        active_element_input->GetInputValue(&active_element);
    401407                        if(!active_element){
    402                                 water_input->GetInputValue(&water_load,gauss);
    403                                 scalar = Jdet*gauss->weight*(water_load);
     408                                basal_melt_input->GetInputValue(&water_load,gauss);
     409                                if(surface_runoff_input) surface_runoff_input->GetInputValue(&runoff_value,gauss);
     410                                else                     runoff_value = 0.;
     411                                scalar = Jdet*gauss->weight*(water_load+runoff_value);
    404412                                //scalar = Jdet*gauss->weight*(water_load)/sediment_transmitivity;
    405413                                if(dt!=0.) scalar = scalar*dt;
     
    444452        return pe;
    445453}/*}}}*/
    446 
    447454void HydrologyDCInefficientAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
    448455        /*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2.
     
    472479        xDelete<IssmDouble>(dbasis);
    473480}/*}}}*/
    474 
    475481void HydrologyDCInefficientAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
    476482        element->GetSolutionFromInputsOneDof(solution,SedimentHeadHydrostepEnum);
    477483}/*}}}*/
    478 
    479484void HydrologyDCInefficientAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
    480485        _error_("Not implemented yet");
    481486}/*}}}*/
    482 
    483487void HydrologyDCInefficientAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
    484488
     
    514518        /*Use the dof list to index into the solution vector: */
    515519
    516         /*need to introduce thawed test herre*/
    517520        for(int i=0;i<numnodes;i++){
    518521                values[i] =solution[doflist[i]];
     
    542545                kappa=kmax*pow(10.,penalty_factor);
    543546
     547
     548                Input* thawed_element_input = basalelement->GetInput(HydrologydcMaskThawedEltEnum); _assert_(thawed_element_input);
     549                thawed_element_input->GetInputValue(&thawed_element);
     550
    544551                for(int i=0;i<numnodes;i++){
     552                        /*frozen elements heads are set to base elevation*/
     553                        if(!thawed_element){
     554                                values[i]=base[i];
     555                        }
    545556                        GetHydrologyDCInefficientHmax(&h_max,basalelement,basalelement->GetNode(i));
    546557                        if(values[i]>h_max) {
     
    551562                                residual[i] = 0.;
    552563                        }
    553                         //adding base in min to take into account heads under bed wich don't change N
    554                         //pressure[i]=(rho_ice*g*thickness[i])-(rho_freshwater*g*(max((min(h_max,values[i])-base[i]),0.0)));
    555564                        pressure[i]=(rho_ice*g*thickness[i])-(rho_freshwater*g*(values[i]-base[i]));
     565
    556566                }
    557567                xDelete<IssmDouble>(thickness);
     
    575585        }
    576586}/*}}}*/
    577 
    578587void HydrologyDCInefficientAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
    579588        /*Default, do nothing*/
    580589        return;
    581590}/*}}}*/
    582 
    583591IssmDouble HydrologyDCInefficientAnalysis::SedimentStoring(Element* element,Gauss* gauss,Input* sed_head_input, Input* base_input){/*{{{*/
    584592        int unconf_scheme;
     
    620628        return sediment_storing;
    621629}/*}}}*/
    622 
    623630IssmDouble HydrologyDCInefficientAnalysis::SedimentTransmitivity(Element* element,Gauss* gauss,Input* sed_head_input, Input* base_input,Input* SedTrans_input){/*{{{*/
    624631        int unconf_scheme;
     
    630637        IssmDouble base_elev,prestep_head,water_sheet;
    631638        IssmDouble sediment_thickness       = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
    632         bool isthermal;
    633 
    634         element->FindParam(&isthermal,TransientIsthermalEnum);
     639
    635640        element->FindParam(&unconf_scheme,HydrologydcUnconfinedFlagEnum);
    636641        SedTrans_input->GetInputValue(&FullLayer_transmitivity,gauss);
     
    657662        return sediment_transmitivity;
    658663}/*}}}*/
    659 
    660664void  HydrologyDCInefficientAnalysis::GetHydrologyDCInefficientHmax(IssmDouble* ph_max,Element* element, Node* innode){/*{{{*/
    661665
     
    693697}
    694698/*}}}*/
    695 
    696699IssmDouble HydrologyDCInefficientAnalysis::GetHydrologyKMatrixTransfer(Element* element){/*{{{*/
    697700
     
    715718        return transfer;
    716719}/*}}}*/
    717 
    718720IssmDouble HydrologyDCInefficientAnalysis::GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* epl_head_input){/*{{{*/
    719721
     
    740742        return transfer;
    741743}/*}}}*/
    742 
    743744void HydrologyDCInefficientAnalysis::ElementizeEplMask(FemModel* femmodel){/*{{{*/
    744745
     
    759760        }
    760761}/*}}}*/
    761 
    762 void  HydrologyDCInefficientAnalysis::HydrologyIDSGetMask(Vector<IssmDouble>* vec_mask, Element* element){
     762void  HydrologyDCInefficientAnalysis::HydrologyIDSGetMask(Vector<IssmDouble>* vec_mask, Element* element){/*{{{*/
    763763        bool        active_element;
    764764        int         domaintype;
     
    801801        xDelete<IssmDouble>(meltingrate);
    802802        xDelete<IssmDouble>(groundedice);
    803 }
     803}/*}}}*/
    804804void HydrologyDCInefficientAnalysis::ElementizeIdsMask(FemModel* femmodel){/*{{{*/
    805805
     
    820820        }
    821821}/*}}}*/
    822 
    823822void HydrologyDCInefficientAnalysis::HydrologyIdsGetActive(Vector<IssmDouble>* active_vec, Element* element){/*{{{*/
    824823        /*Constants*/
  • issm/trunk/src/c/analyses/LevelsetAnalysis.cpp

    r23189 r23394  
    131131        femmodel->SetCurrentConfiguration(LevelsetAnalysisEnum);
    132132
    133         if(VerboseSolution()) _printf0_("call computational core:\n");
     133        if(VerboseSolution()) _printf0_("   call computational core:\n");
    134134        if(stabilization==4){
    135135                solutionsequence_fct(femmodel);
  • issm/trunk/src/c/analyses/MasstransportAnalysis.cpp

    r23189 r23394  
    124124        bool   isoceancoupling;
    125125        bool   issmb;
    126         int    basalforcingsmodel;
    127126
    128127        /*Fetch data needed: */
     
    133132        iomodel->FindConstant(&isoceancoupling,"md.transient.isoceancoupling");
    134133        iomodel->FindConstant(&issmb,"md.transient.issmb");
    135         iomodel->FindConstant(&basalforcingsmodel,"md.basalforcings.model");
    136134
    137135        /*Finite element type*/
     
    158156        iomodel->FetchDataToInput(elements,"md.mask.groundedice_levelset",MaskGroundediceLevelsetEnum);
    159157        iomodel->FetchDataToInput(elements,"md.basalforcings.groundedice_melting_rate",BasalforcingsGroundediceMeltingRateEnum);
    160         if (basalforcingsmodel==SpatialLinearFloatingMeltRateEnum){
    161                 iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum);
    162                 iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum);
    163                 iomodel->FetchDataToInput(elements,"md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum);
    164         }
    165158        iomodel->FetchDataToInput(elements,"md.initialization.vx",VxEnum);
    166159        iomodel->FetchDataToInput(elements,"md.initialization.vy",VyEnum);
     
    181174                        break;
    182175                case MantlePlumeGeothermalFluxEnum:
     176                        break;
     177                case SpatialLinearFloatingMeltRateEnum:
     178                        iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum);
     179                        iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum);
     180                        iomodel->FetchDataToInput(elements,"md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum);
    183181                        break;
    184182                case BasalforcingsPicoEnum:
     
    631629}/*}}}*/
    632630void           MasstransportAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
    633         /*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
     631        /*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2.
    634632         * For node i, Bi can be expressed in the actual coordinate system
    635          * by: 
     633         * by:
    636634         *       Bi=[ N ]
    637635         *          [ N ]
     
    659657}/*}}}*/
    660658void           MasstransportAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
    661         /*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
     659        /*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2.
    662660         * For node i, Bi' can be expressed in the actual coordinate system
    663          * by: 
     661         * by:
    664662         *       Bi_prime=[ dN/dx ]
    665663         *                [ dN/dy ]
  • issm/trunk/src/c/analyses/SmbAnalysis.cpp

    r23189 r23394  
    55#include "../modules/modules.h"
    66
     7// FIX
     8#include "./shared/io/Print/Print.h"
     9
    710/*Model processing*/
    811void SmbAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
     
    2124
    2225        int    smb_model;
    23         bool   isdelta18o,ismungsm,isd18opd,issetpddfac,isprecipscaled,istemperaturescaled;
     26        bool   isdelta18o,ismungsm,isd18opd,issetpddfac,isprecipscaled,istemperaturescaled,isfirnwarming;
    2427
    2528        /*Update elements: */
     
    3538        /*Figure out smb model: */
    3639        iomodel->FindConstant(&smb_model,"md.smb.model");
    37 
    3840        switch(smb_model){
    3941                case SMBforcingEnum:
     
    8890                        }
    8991                        break;
     92                case SMBpddSicopolisEnum:
     93                        iomodel->FetchDataToInput(elements,"md.smb.s0p",SmbS0pEnum);
     94                        iomodel->FetchDataToInput(elements,"md.smb.s0t",SmbS0tEnum);
     95                        iomodel->FindConstant(&isfirnwarming,"md.smb.isfirnwarming");
     96                        iomodel->FetchDataToInput(elements,"md.smb.smb_corr",SmbSmbCorrEnum);
     97                        iomodel->FetchDataToInput(elements,"md.smb.precipitation",SmbPrecipitationEnum);
     98                        iomodel->FetchDataToInput(elements,"md.smb.monthlytemperatures",SmbMonthlytemperaturesEnum);
     99                        iomodel->FetchDataToInput(elements,"md.smb.precipitation_anomaly",SmbPrecipitationsAnomalyEnum);
     100                        iomodel->FetchDataToInput(elements,"md.smb.temperature_anomaly",SmbTemperaturesAnomalyEnum);
     101                        break;
    90102                case SMBd18opddEnum:
    91103                        iomodel->FindConstant(&istemperaturescaled,"md.smb.istemperaturescaled");
     
    139151                        iomodel->FetchDataToInput(elements,"md.smb.refreeze",SmbRefreezeEnum,0.);
    140152                        break;
     153                case SMBgradientscomponentsEnum:
     154                        iomodel->FetchDataToInput(elements,"md.smb.accualti",SmbAccualtiEnum);
     155                        iomodel->FetchDataToInput(elements,"md.smb.accugrad",SmbAccugradEnum);
     156                        iomodel->FetchDataToInput(elements,"md.smb.runoffalti",SmbRunoffaltiEnum);
     157                        iomodel->FetchDataToInput(elements,"md.smb.runoffgrad",SmbRunoffgradEnum);
     158                        break;
    141159                default:
    142160                        _error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
     
    148166        int     numoutputs;
    149167        char**  requestedoutputs = NULL;
    150         bool    isdelta18o,ismungsm,isd18opd,issetpddfac,interp;
     168        bool    isdelta18o,ismungsm,isd18opd,issetpddfac,interp,isfirnwarming;
    151169        int     smb_model;
    152170        IssmDouble *temp = NULL;
     
    215233                        }
    216234                        break;
     235                case SMBpddSicopolisEnum:
     236                        parameters->AddObject(iomodel->CopyConstantObject("md.smb.isfirnwarming",SmbIsfirnwarmingEnum));
     237                        break;
    217238                case SMBd18opddEnum:
    218239                        parameters->AddObject(iomodel->CopyConstantObject("md.smb.ismungsm",SmbIsmungsmEnum));
     
    246267                        /*Nothing to add to parameters*/
    247268                        break;
     269                case SMBgradientscomponentsEnum:
     270                                parameters->AddObject(iomodel->CopyConstantObject("md.smb.accualti",SmbAccualtiEnum));
     271                                parameters->AddObject(iomodel->CopyConstantObject("md.smb.accugrad",SmbAccugradEnum));
     272                                parameters->AddObject(iomodel->CopyConstantObject("md.smb.runoffalti",SmbRunoffaltiEnum));
     273                                parameters->AddObject(iomodel->CopyConstantObject("md.smb.runoffgrad",SmbRunoffgradEnum));
     274
     275                          iomodel->FetchData(&temp,&N,&M,"md.smb.accuref"); _assert_(N==2);
     276                          parameters->AddObject(new TransientParam(SmbAccurefEnum,&temp[0],&temp[M],interp,M));
     277                          iomodel->DeleteData(temp,"md.smb.accuref");
     278
     279                          iomodel->FetchData(&temp,&N,&M,"md.smb.runoffref"); _assert_(N==2);
     280                          parameters->AddObject(new TransientParam(SmbRunoffrefEnum,&temp[0],&temp[M],interp,M));
     281                          iomodel->DeleteData(temp,"md.smb.runoffref");
     282                        break;
    248283                default:
    249284                        _error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
     
    280315                                if(VerboseSolution()) _printf0_("   call Delta18oParameterization module\n");
    281316                                Delta18oParameterizationx(femmodel);
    282                         } 
     317                        }
    283318                        if(ismungsm){
    284319                                if(VerboseSolution()) _printf0_("   call MungsmtpParameterization module\n");
    285320                                MungsmtpParameterizationx(femmodel);
    286                         } 
     321                        }
    287322                        if(VerboseSolution()) _printf0_("   call positive degree day module\n");
    288323                        PositiveDegreeDayx(femmodel);
     324                        break;
     325                case SMBpddSicopolisEnum:
     326                        if(VerboseSolution()) _printf0_("   call SICOPOLIS positive degree day module\n");
     327                        PositiveDegreeDaySicopolisx(femmodel);
    289328                        break;
    290329                case SMBd18opddEnum:
     
    296335                                if(VerboseSolution()) _printf0_("   call positive degree day module\n");
    297336                                PositiveDegreeDayx(femmodel);
    298                         } 
     337                        }
    299338                        break;
    300339                case SMBgradientsEnum:
     
    321360                        /*Nothing to be done*/
    322361                        break;
     362                case SMBgradientscomponentsEnum:
     363                        if(VerboseSolution())_printf0_("        call smb gradients components module\n");
     364                        SmbGradientsComponentsx(femmodel);
     365                        break;
    323366                default:
    324367                        _error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
  • issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp

    r23189 r23394  
    766766        if(isFS){
    767767                iomodel->FetchDataToInput(elements,"md.initialization.pressure",PressureEnum,0.);
    768                 iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum,0.);
     768
     769                /*Add basal forcings to compute melt rate*/
     770                int basalforcing_model;
     771                iomodel->FindConstant(&basalforcing_model,"md.basalforcings.model");
     772                switch(basalforcing_model){
     773                        case FloatingMeltRateEnum:
     774                                iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum);
     775                                break;
     776                        case LinearFloatingMeltRateEnum:
     777                                break;
     778                        case MismipFloatingMeltRateEnum:
     779                                break;
     780                        case MantlePlumeGeothermalFluxEnum:
     781                                break;
     782                        case SpatialLinearFloatingMeltRateEnum:
     783                                iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum);
     784                                iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum);
     785                                iomodel->FetchDataToInput(elements,"md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum);
     786                                break;
     787                        case BasalforcingsPicoEnum:
     788                                iomodel->FetchDataToInput(elements,"md.basalforcings.basin_id",BasalforcingsPicoBasinIdEnum);
     789                                break;
     790                        default:
     791                                _error_("Basal forcing model "<<EnumToStringx(basalforcing_model)<<" not supported yet");
     792                }
    769793        }
    770794        /*LATH parameters*/
     
    844868                        iomodel->FetchDataToInput(elements,"md.friction.till_friction_angle",FrictionTillFrictionAngleEnum);
    845869                        iomodel->FetchDataToInput(elements,"md.friction.sediment_compressibility_coefficient",FrictionSedimentCompressibilityCoefficientEnum);
     870                        iomodel->FetchDataToInput(elements,"md.hydrology.watercolumn_max",HydrologyWatercolumnMaxEnum);
     871                        iomodel->FetchDataToInput(elements,"md.initialization.watercolumn",WatercolumnEnum,0.);
    846872                        break;
    847873                default:
     
    945971                int solver_type;
    946972                PetscOptionsDetermineSolverType(&solver_type);
     973
    947974                if(solver_type==FSSolverEnum) is_schur_cg_solver = true;
    948975                #endif
    949976
     977               
    950978                if(is_schur_cg_solver)
    951979                 solutionsequence_schurcg(femmodel);
     
    32703298                element->NodalFunctionsPressure(pbasis,gauss);
    32713299
    3272                 if(dim==3){
     3300                if(dim==3 || dim==2){
    32733301                        /*Pressure mass matrix*/
    32743302                        for(int k=0;k<pnumnodes;k++){
    32753303                                for(int j=0;j<pnumnodes;j++){
    3276                                         Ke->values[(3*vnumnodes+k)*numdof+3*vnumnodes+j] += gauss->weight*Jdet*(pbasis[j]*pbasis[k]);
     3304                                        Ke->values[(dim*vnumnodes+k)*numdof+dim*vnumnodes+j] += gauss->weight*Jdet*(pbasis[j]*pbasis[k]);
    32773305                                }
    32783306                        }
    3279                 }
    3280                 else{
     3307                }else{
    32813308                        _error_("STOP");
    32823309                }
     
    32893316        return Ke;
    32903317}/*}}}*/
     3318ElementMatrix* StressbalanceAnalysis::CreateSchurPrecondMatrix(Element* element){/*{{{*/
     3319
     3320        /*Intermediaries*/
     3321        int         i,dim;
     3322        IssmDouble  viscosity,FSreconditioning,Jdet;
     3323        IssmDouble *xyz_list = NULL;
     3324
     3325        /*Get problem dimension*/
     3326        element->FindParam(&dim,DomainDimensionEnum);
     3327
     3328        /*Fetch number of nodes and dof for this finite element*/
     3329        int vnumnodes = element->NumberofNodesVelocity();
     3330        int pnumnodes = element->NumberofNodesPressure();
     3331        int numdof    = vnumnodes*dim + pnumnodes;
     3332
     3333        /*Initialize Element matrix and vectors*/
     3334        ElementMatrix* Ke  = element->NewElementMatrix(FSvelocityEnum);
     3335        IssmDouble* pbasis = xNew<IssmDouble>(pnumnodes);
     3336
     3337        /*Retrieve all inputs and parameters*/
     3338        element->GetVerticesCoordinates(&xyz_list);
     3339        //element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
     3340        Input* vx_input=element->GetInput(VxEnum);     _assert_(vx_input);
     3341        Input* vy_input=element->GetInput(VyEnum);     _assert_(vy_input);
     3342        Input* vz_input = NULL;
     3343        if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
     3344
     3345
     3346        /* Start  looping on the number of gaussian points: */
     3347        Gauss* gauss = element->NewGauss(5);
     3348        for(int ig=gauss->begin();ig<gauss->end();ig++){
     3349                gauss->GaussPoint(ig);
     3350
     3351                element->JacobianDeterminant(&Jdet,xyz_list,gauss);
     3352                element->NodalFunctionsPressure(pbasis,gauss);
     3353                element->material->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
     3354
     3355
     3356                if(dim==3 || dim==2){
     3357                        /*Pressure mass matrix*/
     3358                        for(int k=0;k<pnumnodes;k++){
     3359                                for(int j=0;j<pnumnodes;j++){
     3360                                        Ke->values[(dim*vnumnodes+k)*numdof+dim*vnumnodes+j] += gauss->weight*1./viscosity*Jdet*(pbasis[j]*pbasis[k]);
     3361                                }
     3362                        }
     3363                }else{
     3364                        _error_("STOP");
     3365                }
     3366        }
     3367
     3368        /*Clean up and return*/
     3369        delete gauss;
     3370        xDelete<IssmDouble>(xyz_list);
     3371        xDelete<IssmDouble>(pbasis);
     3372        return Ke;
     3373}/*}}}*/
     3374
    32913375ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSViscousLA(Element* element){/*{{{*/
    32923376
  • issm/trunk/src/c/analyses/StressbalanceAnalysis.h

    r23189 r23394  
    7575                ElementMatrix* CreateKMatrixFSViscousXTH(Element* element);
    7676                ElementMatrix* CreatePressureMassMatrix(Element* element);
     77                ElementMatrix* CreateSchurPrecondMatrix(Element* element);
    7778                ElementVector* CreatePVectorFS(Element* element);
    7879                ElementVector* CreatePVectorFSFriction(Element* element);
  • issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp

    r23189 r23394  
    111111        }
    112112        iomodel->FetchDataToInput(elements,"md.basalforcings.groundedice_melting_rate",BasalforcingsGroundediceMeltingRateEnum);
    113         iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum,0.);
    114113        //iomodel->FetchDataToInput(elements,"md.smb.mass_balance",SmbMassBalanceEnum);
     114
     115
     116        /*Add basal forcings to compute melt rate*/
     117        int basalforcing_model;
     118        iomodel->FindConstant(&basalforcing_model,"md.basalforcings.model");
     119        switch(basalforcing_model){
     120                case FloatingMeltRateEnum:
     121                        iomodel->FetchDataToInput(elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum);
     122                        break;
     123                case LinearFloatingMeltRateEnum:
     124                        break;
     125                case MismipFloatingMeltRateEnum:
     126                        break;
     127                case MantlePlumeGeothermalFluxEnum:
     128                        break;
     129                case SpatialLinearFloatingMeltRateEnum:
     130                        iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum);
     131                        iomodel->FetchDataToInput(elements,"md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum);
     132                        iomodel->FetchDataToInput(elements,"md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum);
     133                        break;
     134                case BasalforcingsPicoEnum:
     135                        iomodel->FetchDataToInput(elements,"md.basalforcings.basin_id",BasalforcingsPicoBasinIdEnum);
     136                        break;
     137                default:
     138                        _error_("Basal forcing model "<<EnumToStringx(basalforcing_model)<<" not supported yet");
     139        }
    115140        iomodel->FetchDataToInput(elements,"md.initialization.vx",VxEnum,0.);
    116141        iomodel->FetchDataToInput(elements,"md.initialization.vy",VyEnum,0.);
  • issm/trunk/src/c/analyses/ThermalAnalysis.cpp

    r23189 r23394  
    3333                int smb_model;
    3434                iomodel->FindConstant(&smb_model,"md.smb.model");
    35                 if(smb_model==SMBpddEnum) isdynamic=true;
    36                 if(smb_model==SMBd18opddEnum) isdynamic=true;
     35                if(smb_model==SMBpddEnum)                               isdynamic=true;
     36                if(smb_model==SMBd18opddEnum)                   isdynamic=true;
     37                if(smb_model==SMBpddSicopolisEnum)  isdynamic=true;
    3738        }
    3839        else{
  • issm/trunk/src/c/classes/Elements/Element.cpp

    r23189 r23394  
    653653        xDelete<IssmDouble>(tmp);
    654654
     655}
     656/*}}}*/
     657void       Element::SmbGradCompParameterization(void){/*{{{*/
     658
     659        /*Are we on the base? If not, return*/
     660        if(!IsOnBase()) return;
     661        int        numvertices = this->GetNumberOfVertices();
     662
     663        int        i;
     664        IssmDouble accuref, runoffref; //reference values at given altitude
     665        IssmDouble accualti, runoffalti; //reference altitudes
     666        IssmDouble accugrad, runoffgrad; //gradients from reference altitude
     667        IssmDouble rho_water, rho_ice;
     668        IssmDouble time;
     669
     670        IssmDouble*             smb              = xNew<IssmDouble>(numvertices);
     671        IssmDouble*             surf     = xNew<IssmDouble>(numvertices);
     672        IssmDouble*             accu     = xNew<IssmDouble>(numvertices);
     673        IssmDouble*             runoff = xNew<IssmDouble>(numvertices);
     674
     675        /*Get material parameters :*/
     676        rho_water=this->matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
     677        rho_ice=this->matpar->GetMaterialParameter(MaterialsRhoIceEnum);
     678
     679        /*Recover parameters*/
     680        parameters->FindParam(&time,TimeEnum);
     681        parameters->FindParam(&accualti,SmbAccualtiEnum);
     682        parameters->FindParam(&accugrad,SmbAccugradEnum);
     683        parameters->FindParam(&runoffalti,SmbRunoffaltiEnum);
     684        parameters->FindParam(&runoffgrad,SmbRunoffgradEnum);
     685
     686        /*Recover reference values at current time*/
     687        parameters->FindParam(&accuref,SmbAccurefEnum,time);
     688        parameters->FindParam(&runoffref,SmbRunoffrefEnum,time);
     689
     690        /*Recover surface elevation*/
     691        GetInputListOnVertices(&surf[0],SurfaceEnum);
     692
     693        /*Compute the temperature and precipitation*/
     694        for(int iv=0;iv<numvertices;iv++){
     695                accu[iv]=max(0.,(accuref+(surf[iv]-accualti)*accugrad));
     696                runoff[iv]=max(0.,(runoffref+(surf[iv]-runoffalti)*runoffgrad));
     697                smb[iv]=(accu[iv]-runoff[iv])*rho_ice/rho_water;
     698        }
     699        switch(this->ObjectEnum()){
     700        case TriaEnum:
     701                this->inputs->AddInput(new TriaInput(SmbMassBalanceEnum,&smb[0],P1Enum));
     702                this->inputs->AddInput(new TriaInput(SmbRunoffEnum,&runoff[0],P1Enum));
     703                break;
     704        case PentaEnum:
     705                this->inputs->AddInput(new PentaInput(SmbMassBalanceEnum,&smb[0],P1Enum));
     706                this->inputs->AddInput(new PentaInput(SmbRunoffEnum,&runoff[0],P1Enum));
     707                this->InputExtrude(SmbMassBalanceEnum,-1);
     708                this->InputExtrude(SmbRunoffEnum,-1);
     709                break;
     710        case TetraEnum:
     711                this->inputs->AddInput(new TetraInput(SmbMassBalanceEnum,&smb[0],P1Enum));
     712                this->inputs->AddInput(new TetraInput(SmbRunoffEnum,&runoff[0],P1Enum));
     713                this->InputExtrude(SmbMassBalanceEnum,-1);
     714                this->InputExtrude(SmbRunoffEnum,-1);
     715                break;
     716        default: _error_("Not implemented yet");
     717        }
     718        /* this->AddInput(SmbMassBalanceEnum,smb,P1Enum); */
     719        /* this->AddInput(SmbRunoffEnum,runoff,P1Enum); */
     720        /*clean-up*/
     721        xDelete<IssmDouble>(surf);
     722        xDelete<IssmDouble>(accu);
     723        xDelete<IssmDouble>(runoff);
     724        xDelete<IssmDouble>(smb);
    655725}
    656726/*}}}*/
     
    25612631}
    25622632/*}}}*/
     2633void       Element::PositiveDegreeDaySicopolis(bool isfirnwarming){/*{{{*/
     2634
     2635        /* General FIXMEs: get Tmelting point, pddicefactor, pddsnowfactor, sigma from parameters/user input */
     2636
     2637        int  numvertices = this->GetNumberOfVertices();
     2638
     2639        int        i;
     2640        IssmDouble* smb=xNew<IssmDouble>(numvertices);          // surface mass balance
     2641        IssmDouble* melt=xNew<IssmDouble>(numvertices);         // melting comp. of surface mass balance
     2642        IssmDouble* accu=xNew<IssmDouble>(numvertices);         // accuumulation comp. of surface mass balance
     2643        IssmDouble* melt_star=xNew<IssmDouble>(numvertices);
     2644        IssmDouble* monthlytemperatures=xNew<IssmDouble>(12*numvertices);
     2645        IssmDouble* monthlyprec=xNew<IssmDouble>(12*numvertices);
     2646        IssmDouble* yearlytemperatures=xNew<IssmDouble>(numvertices); memset(yearlytemperatures, 0., numvertices*sizeof(IssmDouble));
     2647        IssmDouble* s=xNew<IssmDouble>(numvertices);                    // actual surface height
     2648        IssmDouble* s0p=xNew<IssmDouble>(numvertices);          // reference elevation for precip.
     2649        IssmDouble* s0t=xNew<IssmDouble>(numvertices);          // reference elevation for temperature
     2650        IssmDouble* smbcorr=xNew<IssmDouble>(numvertices); // surface mass balance correction; will be added after pdd call
     2651        IssmDouble* p_ampl=xNew<IssmDouble>(numvertices);       // precip anomaly
     2652        IssmDouble* t_ampl=xNew<IssmDouble>(numvertices);       // remperature anomaly
     2653        IssmDouble rho_water,rho_ice,desfac,rlaps;
     2654        IssmDouble inv_twelve=1./12.;                                                           //factor for monthly average
     2655        IssmDouble time,yts,time_yr;
     2656
     2657        /*Get material parameters :*/
     2658        rho_water=this->matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
     2659        rho_ice=this->matpar->GetMaterialParameter(MaterialsRhoIceEnum);
     2660
     2661        /*Get parameters for height corrections*/
     2662        desfac=this->matpar->GetMaterialParameter(SmbDesfacEnum);
     2663        rlaps=this->matpar->GetMaterialParameter(SmbRlapsEnum);
     2664
     2665        /*Recover monthly temperatures and precipitation*/
     2666        Input*     input=this->inputs->GetInput(SmbMonthlytemperaturesEnum); _assert_(input);
     2667        Input*     input2=this->inputs->GetInput(SmbPrecipitationEnum); _assert_(input2);
     2668        /*Recover smb correction term */
     2669        Input*     input3=this->inputs->GetInput(SmbSmbCorrEnum); _assert_(input3);
     2670
     2671        /* Get time */
     2672        this->parameters->FindParam(&time,TimeEnum);
     2673        this->parameters->FindParam(&yts,ConstantsYtsEnum);
     2674        time_yr=floor(time/yts)*yts;
     2675
     2676        /* Set parameters for finrnwarming */
     2677        IssmDouble MU_0         = 9.7155; //Firn-warming correction, in (d*deg C)/(mm WE)
     2678        IssmDouble mu           = MU_0*(1000.0*86400.0)*(rho_ice/rho_water);   // (d*deg C)/(mm WE) --> (s*deg C)/(m IE)
     2679
     2680        /*loop over vertices: */
     2681        Gauss* gauss=this->NewGauss();
     2682        for(int month=0;month<12;month++){
     2683                for(int iv=0;iv<numvertices;iv++){
     2684                        gauss->GaussVertex(iv);
     2685                        input->GetInputValue(&monthlytemperatures[iv*12+month],gauss,(month+1)/12.*yts);
     2686                        monthlytemperatures[iv*12+month]=monthlytemperatures[iv*12+month]-273.15; // conversion from Kelvin to celcius for PDD module
     2687                        input2->GetInputValue(&monthlyprec[iv*12+month],gauss,(month+1)/12.*yts);
     2688                        monthlyprec[iv*12+month]=monthlyprec[iv*12+month]*yts;
     2689                }
     2690        }
     2691
     2692        /*Recover info at the vertices: */
     2693        GetInputListOnVertices(&s[0],SurfaceEnum);
     2694        GetInputListOnVertices(&s0p[0],SmbS0pEnum);
     2695        GetInputListOnVertices(&s0t[0],SmbS0tEnum);
     2696        GetInputListOnVertices(&smbcorr[0],SmbSmbCorrEnum);
     2697        GetInputListOnVertices(&t_ampl[0],SmbTemperaturesAnomalyEnum);
     2698        GetInputListOnVertices(&p_ampl[0],SmbPrecipitationsAnomalyEnum);
     2699
     2700        /*measure the surface mass balance*/
     2701        for (int iv = 0; iv<numvertices; iv++){
     2702                smb[iv]=PddSurfaceMassBalanceSicopolis(&monthlytemperatures[iv*12], &monthlyprec[iv*12],
     2703                                        &melt[iv], &accu[iv], &melt_star[iv], &t_ampl[iv], &p_ampl[iv], yts, s[iv],
     2704                                        desfac, s0t[iv], s0p[iv],rlaps,rho_water,rho_ice);
     2705
     2706                /* make correction */
     2707                smb[iv] = smb[iv]+smbcorr[iv];
     2708                /*Get yearlytemperatures */
     2709                for(int month=0;month<12;month++) yearlytemperatures[iv]=yearlytemperatures[iv]+((monthlytemperatures[iv*12+month]+273.15)+t_ampl[iv])*inv_twelve; // Has to be in Kelvin
     2710
     2711                if(isfirnwarming){
     2712                        if(melt_star[iv]>=melt[iv]){
     2713                                yearlytemperatures[iv]= yearlytemperatures[iv]+mu*(melt_star[iv]-melt[iv]);
     2714                        }
     2715                        else{
     2716                                yearlytemperatures[iv]= yearlytemperatures[iv];
     2717                        }
     2718                }
     2719                if (yearlytemperatures[iv]>273.15) yearlytemperatures[iv]=273.15;
     2720        }
     2721
     2722        switch(this->ObjectEnum()){
     2723                case TriaEnum:
     2724                        // this->inputs->AddInput(new TriaInput(TemperatureEnum,&yearlytemperatures[0],P1Enum));
     2725                        this->inputs->AddInput(new TriaInput(TemperaturePDDEnum,&yearlytemperatures[0],P1Enum));
     2726                        this->inputs->AddInput(new TriaInput(SmbMassBalanceEnum,&smb[0],P1Enum));
     2727                        this->inputs->AddInput(new TriaInput(SmbAccumulationEnum,&accu[0],P1Enum));
     2728                        this->inputs->AddInput(new TriaInput(SmbMeltEnum,&melt[0],P1Enum));
     2729                        break;
     2730                case PentaEnum:
     2731                        bool isthermal;
     2732                        this->parameters->FindParam(&isthermal,TransientIsthermalEnum);
     2733                        if(isthermal){
     2734                                bool isenthalpy;
     2735                                this->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
     2736                                if(IsOnSurface()){
     2737                                        /*Here, we want to change the BC of the thermal model, keep
     2738                                         * the temperatures as they are for the base of the penta and
     2739                                         * use yearlytemperatures for the top*/
     2740                                        GetInputListOnVertices(&s[0],TemperatureEnum);
     2741                                        yearlytemperatures[0] = s[0];
     2742                                        yearlytemperatures[1] = s[1];
     2743                                        yearlytemperatures[2] = s[2];
     2744                                        this->inputs->AddInput(new PentaInput(TemperatureEnum,&yearlytemperatures[0],P1Enum));
     2745                                        if(isenthalpy){
     2746                                                /*Convert that to enthalpy for the enthalpy model*/
     2747                                                IssmDouble enthalpy[6];
     2748                                                GetInputListOnVertices(&enthalpy[0],EnthalpyEnum);
     2749                                                ThermalToEnthalpy(&enthalpy[3],yearlytemperatures[3],0.,0.);
     2750                                                ThermalToEnthalpy(&enthalpy[4],yearlytemperatures[4],0.,0.);
     2751                                                ThermalToEnthalpy(&enthalpy[5],yearlytemperatures[5],0.,0.);
     2752                                                this->inputs->AddInput(new PentaInput(EnthalpyEnum,&enthalpy[0],P1Enum));
     2753                                        }
     2754                                }
     2755                        }
     2756                        this->inputs->AddInput(new PentaInput(SmbMassBalanceEnum,&smb[0],P1Enum));
     2757                        this->inputs->AddInput(new PentaInput(TemperaturePDDEnum,&yearlytemperatures[0],P1Enum));
     2758                        this->inputs->AddInput(new PentaInput(SmbAccumulationEnum,&accu[0],P1Enum));
     2759                        this->inputs->AddInput(new PentaInput(SmbMeltEnum,&melt[0],P1Enum));
     2760                        this->InputExtrude(TemperaturePDDEnum,-1);
     2761                        this->InputExtrude(SmbMassBalanceEnum,-1);
     2762                        this->InputExtrude(SmbAccumulationEnum,-1);
     2763                        this->InputExtrude(SmbMeltEnum,-1);
     2764                        break;
     2765                case TetraEnum:
     2766                        if(IsOnSurface()){
     2767                                GetInputListOnVertices(&s[0],TemperatureEnum);
     2768                                yearlytemperatures[0] = s[0];
     2769                                yearlytemperatures[1] = s[1];
     2770                                yearlytemperatures[2] = s[2];
     2771                                this->inputs->AddInput(new TetraInput(TemperatureEnum,&yearlytemperatures[0],P1Enum));
     2772                        }
     2773                        this->inputs->AddInput(new TetraInput(SmbMassBalanceEnum,&smb[0],P1Enum));
     2774                        this->inputs->AddInput(new TetraInput(TemperaturePDDEnum,&yearlytemperatures[0],P1Enum));
     2775                        this->InputExtrude(TemperaturePDDEnum,-1);
     2776                        this->InputExtrude(SmbMassBalanceEnum,-1);
     2777                        break;
     2778                default: _error_("Not implemented yet");
     2779        }
     2780
     2781        /*clean-up*/
     2782        delete gauss;
     2783        xDelete<IssmDouble>(monthlytemperatures);
     2784        xDelete<IssmDouble>(monthlyprec);
     2785        xDelete<IssmDouble>(smb);
     2786        xDelete<IssmDouble>(melt);
     2787        xDelete<IssmDouble>(accu);
     2788        xDelete<IssmDouble>(yearlytemperatures);
     2789        xDelete<IssmDouble>(s);
     2790        xDelete<IssmDouble>(s0t);
     2791        xDelete<IssmDouble>(s0p);
     2792        xDelete<IssmDouble>(t_ampl);
     2793        xDelete<IssmDouble>(p_ampl);
     2794        xDelete<IssmDouble>(smbcorr);
     2795        xDelete<IssmDouble>(melt_star);
     2796}
     2797/*}}}*/
    25632798IssmDouble Element::PureIceEnthalpy(IssmDouble pressure){/*{{{*/
    25642799        return this->matpar->PureIceEnthalpy(pressure);
     
    25682803        /*Some intputs need to be computed, even if they are already in inputs, they might not be up to date!*/
    25692804        switch(output_enum){
    2570                 case ViscousHeatingEnum: this->ViscousHeatingCreateInput(); break;
    2571                 case StressMaxPrincipalEnum: this->StressMaxPrincipalCreateInput(); break;
     2805        case ViscousHeatingEnum: this->ViscousHeatingCreateInput(); break;
     2806        case StressMaxPrincipalEnum: this->StressMaxPrincipalCreateInput(); break;
    25722807                case StressTensorxxEnum:
    25732808                case StressTensorxyEnum:
     
    25822817                case StrainRateyzEnum:
    25832818                case StrainRatezzEnum:
    2584                 case StrainRateeffectiveEnum: this->ComputeStrainRate(); break;
     2819          case StrainRateeffectiveEnum: this->ComputeStrainRate(); break;
    25852820                case DeviatoricStressxxEnum:
    25862821                case DeviatoricStressxyEnum:
     
    31333368                }
    31343369
    3135                 #ifndef _HAVE_ADOLC_ //we want to avoid the round operation at all cost. Not differentiable.
     3370                #if defined(_HAVE_AD_)
     3371                /*we want to avoid the round operation at all cost. Not differentiable.*/
     3372                _error_("not implemented yet");
     3373                #else
    31363374                dMass = sumMass + sumR + sumW - sumP - sumEC - initMass - sumMassAdd;
    31373375                dMass = round(dMass * 100.0)/100.0;
  • issm/trunk/src/c/classes/Elements/Element.h

    r23189 r23394  
    11/*!\file:  Element.h
    22 * \brief abstract class for Element object
    3  * This class is a place holder for the Tria and the Penta elements. 
     3 * This class is a place holder for the Tria and the Penta elements.
    44 * It is derived from Element, so DataSets can contain them.
    5  */ 
     5 */
    66
    77#ifndef _ELEMENT_H_
     
    5050                int  element_type;
    5151
    52         public: 
     52        public:
    5353                /*Constructors/Destructores*/
    5454                Element();
     
    6868                void               Delta18oParameterization(void);
    6969                void               Delta18opdParameterization(void);
     70                void               SmbGradCompParameterization(void);
    7071                IssmDouble         Divergence(void);
    7172                void               dViscositydBFS(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
     
    130131                void               InputUpdateFromConstant(int constant, int name);
    131132                void               InputUpdateFromConstant(bool constant, int name);
    132                 bool               IsFloating(); 
     133                bool               IsFloating();
    133134                bool               IsIceInElement();
    134135                bool               IsLandInElement();
    135136                bool               IsWaterInElement();
    136                 void               LinearFloatingiceMeltingRate(); 
    137                 void               SpatialLinearFloatingiceMeltingRate(); 
    138                 void               MantlePlumeGeothermalFlux(); 
     137                void               LinearFloatingiceMeltingRate();
     138                void               SpatialLinearFloatingiceMeltingRate();
     139                void               MantlePlumeGeothermalFlux();
    139140                void               MarshallElement(char** pmarshalled_data,int* pmarshalled_data_size, int marshall_direction,int numanalyses);
    140141                void               MigrateGroundingLine(IssmDouble* sheet_ungrounding);
    141                 void               MismipFloatingiceMeltingRate(); 
     142                void               MismipFloatingiceMeltingRate();
    142143                void               MungsmtpParameterization(void);
    143144                ElementMatrix*     NewElementMatrix(int approximation_enum=NoneApproximationEnum);
     
    145146                ElementVector*     NewElementVector(int approximation_enum=NoneApproximationEnum);
    146147                void               PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm,bool issetpddfac);
     148                void               PositiveDegreeDaySicopolis(bool isfirnwarming);
    147149                IssmDouble         PureIceEnthalpy(IssmDouble pressure);
    148150                void               ResultInterpolation(int* pinterpolation,int*nodesperelement,int* parray_size, int output_enum);
     
    240242                virtual bool       IsFaceOnBoundary(void)=0;
    241243                virtual bool       IsIcefront(void)=0;
    242                 virtual bool       IsNodeOnShelfFromFlags(IssmDouble* flags)=0; 
     244                virtual bool       IsNodeOnShelfFromFlags(IssmDouble* flags)=0;
    243245                virtual bool       IsOnBase()=0;
    244246                virtual bool       IsOnSurface()=0;
     
    330332                virtual IssmDouble    OceanAverage(IssmDouble* Sg)=0;
    331333                virtual IssmDouble    OceanArea(void)=0;
    332                 virtual void          SealevelriseMomentOfInertia(IssmDouble* dI_list,IssmDouble* Sg_old,IssmDouble eartharea)=0; 
     334                virtual void          SealevelriseMomentOfInertia(IssmDouble* dI_list,IssmDouble* Sg_old,IssmDouble eartharea)=0;
    333335                virtual void          SealevelriseEustatic(Vector<IssmDouble>* pSgi,IssmDouble* peustatic,IssmDouble* latitude,IssmDouble* longitude,IssmDouble* radius,IssmDouble oceanarea,IssmDouble eartharea)=0;
    334336                virtual void          SealevelriseNonEustatic(Vector<IssmDouble>* pSgo,IssmDouble* Sg_old,IssmDouble* latitude,IssmDouble* longitude,IssmDouble* radius,IssmDouble eartharea)=0;
  • issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h

    r23189 r23394  
    622622
    623623        /*Specific instantiations for IssmDouble*: */
    624 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)  //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization.
     624#if defined(_HAVE_AD_) && !defined(_WRAPPERS_)  //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization.
    625625template <> inline GenericExternalResult<IssmDouble*>::~GenericExternalResult(){ /*{{{*/
    626626        xDelete<char>(result_name);
     
    709709                return new GenericExternalResult<Vector<IssmPDouble>*>(this->id,StringToEnumx(this->result_name),this->value,this->step,this->time);
    710710        } /*}}}*/
    711 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)  //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization.
     711#if defined(_HAVE_AD_) && !defined(_WRAPPERS_)  //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization.
    712712        template <> inline void GenericExternalResult<Vector<IssmPDouble>*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
    713713
  • issm/trunk/src/c/classes/FemModel.cpp

    r23189 r23394  
    1717#include "../shared/Enum/Enum.h"
    1818#include "../analyses/analyses.h"
     19
     20#if _HAVE_CODIPACK_
     21#include <sstream> // for output of the CoDiPack tape
     22extern CoDi_global codi_global;
     23#endif
    1924
    2025/*module includes: {{{*/
     
    8489        this->parameters->FindParam(&amr_frequency,TransientAmrFrequencyEnum);
    8590        this->parameters->FindParam(&amr_frequency,TransientAmrFrequencyEnum);
    86         #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
     91        #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_AD_)
    8792        this->amr = NULL;
    8893        #endif
    89         #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     94        #if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    9095        this->amrbamg = NULL;
    9196        #endif
    92         #if !defined(_HAVE_ADOLC_)
     97        #if !defined(_HAVE_AD_)
    9398        if(amr_frequency && solution_type==TransientSolutionEnum){
    9499                /*Verifications. AMR supports SSA, P1 and horizontal 2D domain*/
     
    147152        profiler->Stop(MPROCESSOR);
    148153
    149         #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
     154        #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_AD_)
    150155        this->amr = NULL;
    151156        #endif
    152         #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     157        #if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    153158        this->amrbamg = NULL;
    154159        #endif
     
    184189        if(results)delete results;
    185190
    186         #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
     191        #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_AD_)
    187192        if(amr)delete amr;
    188193        #endif
    189194
    190         #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     195        #if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    191196        if(amrbamg)delete amrbamg;
    192197        #endif
     
    254259        /*Before we delete the profiler, report statistics for this run: */
    255260        profiler->Stop(TOTAL);  //final tagging
     261
    256262        _printf0_("\n");
    257         _printf0_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->TotalTime(MPROCESSOR) << "\n");
    258         _printf0_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->TotalTime(CORE) << "\n");
    259         _printf0_("   "<<setw(40)<<left<<"Solver elapsed time:"<<profiler->TotalTime(SOLVER) << "\n");
     263        _printf0_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<setw(7)<<profiler->TotalTime(MPROCESSOR) << "\n");
     264        /*Total times*/
     265        _printf0_("   "<<setw(40)<<left<<"Total Core solution elapsed time:"<<setw(7)<<profiler->TotalTime(CORE) << "\n");
     266
     267        /*Linear solver only*/
     268        _printf0_("   "<<setw(40)<<left<<"Linear solver elapsed time:"<<setw(7)<<profiler->TotalTime(SOLVER) << " ("<<setprecision(2)<<profiler->TotalTime(SOLVER)/profiler->TotalTime(CORE)*100.<<"%)\n");
    260269        _printf0_("\n");
    261270        _printf0_("   Total elapsed time: "
     
    319328
    320329        /*AMR, no copy for now*/
    321         #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
     330        #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_AD_)
    322331        this->amr = NULL;
    323332        #endif
    324         #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     333        #if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    325334        this->amrbamg = NULL;
    326335        #endif
     
    853862                solution_memory=profiler->Memory(CORE);
    854863
    855                 _printf0_("Core solution elapsed time    : " << solution_time   << " Seconds\n");
    856                 _printf0_("Core solution number of flops : " << solution_flops  << " Flops\n");
    857                 _printf0_("Core solution memory used     : " << solution_memory << " Bytes\n");
    858 
     864                _printf0_("\nCore solution profiling\n");
     865                _printf0_("   elapsed time    : " << solution_time   << " Seconds\n");
     866                _printf0_("   number of flops : " << solution_flops  << " Flops\n");
     867                _printf0_("   memory used     : " << solution_memory << " Bytes\n");
     868
     869                /*Individual cores*/
     870                _printf0_("Individual core profiling\n");
     871                if(profiler->Used(THERMALCORE)) _printf0_("   "<<setw(40)<<left<<"Thermal core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(THERMALCORE) << " sec\n");
     872                if(profiler->Used(HYDROLOGYCORE)) _printf0_("   "<<setw(40)<<left<<"Hydrology core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(HYDROLOGYCORE) << " sec\n");
     873                if(profiler->Used(STRESSBALANCECORE)) _printf0_("   "<<setw(40)<<left<<"Stress balance core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(STRESSBALANCECORE) << " sec\n");
     874                if(profiler->Used(DAMAGECORE)) _printf0_("   "<<setw(40)<<left<<"Damage core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(DAMAGECORE) << " sec\n");
     875                if(profiler->Used(MOVINGFRONTCORE)) _printf0_("   "<<setw(40)<<left<<"Moving front core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(MOVINGFRONTCORE) << " sec\n");
     876                if(profiler->Used(MASSTRANSPORTCORE)) _printf0_("   "<<setw(40)<<left<<"Mass transport core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(MASSTRANSPORTCORE) << " sec\n");
     877                if(profiler->Used(SMBCORE)) _printf0_("   "<<setw(40)<<left<<"SMB core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(SMBCORE) << " sec\n");
     878                if(profiler->Used(GROUNDINGLINECORE)) _printf0_("   "<<setw(40)<<left<<"Groundingline migration core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(GROUNDINGLINECORE) << " sec\n");
     879                if(profiler->Used(GIACORE)) _printf0_("   "<<setw(40)<<left<<"GIA core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(GIACORE) << " sec\n");
     880                if(profiler->Used(ESACORE)) _printf0_("   "<<setw(40)<<left<<"ESA core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(ESACORE) << " sec\n");
     881                if(profiler->Used(SLRCORE)) _printf0_("   "<<setw(40)<<left<<"SLR core elapsed time:"<<setw(7)<<setprecision(6)<<profiler->TotalTime(SLRCORE) << " sec\n");
     882               
    859883                /*Add to results: */
    860884                results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingSolutionTimeEnum,  solution_time));
     
    862886                results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingCurrentFlopsEnum, solution_flops));
    863887
    864                 #ifdef _HAVE_ADOLC_
    865                 solution_time=profiler->TotalTime(ADCORE);
    866                 solution_flops=profiler->TotalFlops(ADCORE);
    867                 solution_memory=profiler->Memory(ADCORE);
    868 
    869                 _printf0_("AD Solution elapsed time    : " << solution_time   << " Seconds\n");
    870                 _printf0_("AD Solution number of flops : " << solution_flops  << " Flops\n");
    871                 _printf0_("AD Solution memory used     : " << solution_memory << " Bytes\n");
     888                #ifdef _HAVE_AD_
     889                solution_time   = profiler->TotalTime(ADCORE);
     890                solution_flops  = profiler->TotalFlops(ADCORE);
     891                solution_memory = profiler->Memory(ADCORE);
     892
     893                _printf0_("AD profiling\n");
     894                _printf0_("   elapsed time    : " << solution_time   << " Seconds\n");
     895                _printf0_("   number of flops : " << solution_flops  << " Flops\n");
     896                _printf0_("   memory used     : " << solution_memory << " Bytes\n");
    872897                #endif
     898                _printf0_("\n");
    873899
    874900        }
     
    18241850
    18251851        if(isautodiff){
    1826                 #ifdef _HAVE_ADOLC_
     1852                #ifdef _HAVE_AD_
    18271853                parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
    18281854                parameters->FindParam(&dependent_objects,AutodiffDependentObjectsEnum);
    18291855                if(num_dependents){
    18301856                        dependents=xNew<IssmPDouble>(num_dependents);
     1857
     1858                        #if defined(_HAVE_CODIPACK_)
     1859                        auto& tape_codi = IssmDouble::getGlobalTape();
     1860                        #endif
    18311861
    18321862                        /*Go through our dependent variables, and compute the response:*/
     
    18351865                                dep->Responsex(&output_value,this);
    18361866                                if (my_rank==0) {
    1837                                         output_value>>=dependents[i];
     1867                                        #if defined(_HAVE_CODIPACK_)
     1868                                                tape_codi.registerOutput(output_value);
     1869                                                dependents[i] = output_value.getValue();
     1870                                                codi_global.output_indices.push_back(output_value.getGradientData());
     1871                                        #else
     1872                                                output_value>>=dependents[i];
     1873                                        #endif
    18381874                                }
    18391875                        }
     
    25092545
    25102546/*AMR*/
    2511 #if !defined(_HAVE_ADOLC_)
     2547#ifndef _HAVE_AD_
    25122548void FemModel::ReMesh(void){/*{{{*/
    25132549
     
    25282564        this->parameters->FindParam(&amrtype,AmrTypeEnum);
    25292565        switch(amrtype){
    2530                 #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
     2566                #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_AD_)
    25312567                case AmrNeopzEnum: this->ReMeshNeopz(&newnumberofvertices,&newnumberofelements,&newx,&newy,&newz,&newelementslist); break;
    25322568                                                                 #endif
    25332569
    2534                 #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     2570                #if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    25352571                case AmrBamgEnum: this->ReMeshBamg(&newnumberofvertices,&newnumberofelements,&newx,&newy,&newz,&newelementslist); break;
    25362572                #endif
     
    48844920#endif
    48854921
    4886 #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     4922#if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    48874923void FemModel::ReMeshBamg(int* pnewnumberofvertices,int* pnewnumberofelements,IssmDouble** pnewx,IssmDouble** pnewy,IssmDouble** pnewz,int** pnewelementslist){/*{{{*/
    48884924
     
    52105246#endif
    52115247
    5212 #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
     5248#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_AD_)
    52135249void FemModel::ReMeshNeopz(int* pnewnumberofvertices,int* pnewnumberofelements,IssmDouble** pnewx,IssmDouble** pnewy,IssmDouble** pnewz,int** pnewelementslist){/*{{{*/
    52145250
  • issm/trunk/src/c/classes/FemModel.h

    r23189 r23394  
    2020class Profiler;
    2121class Elements;
    22 #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
     22#if defined(_HAVE_NEOPZ_) && !defined(_HAVE_AD_)
    2323#include "./AdaptiveMeshRefinement.h"
    2424#endif
    25 #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     25#if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    2626#include "./AmrBamg.h"
    2727#endif
     
    5151
    5252                //FIXME: do we want only one class and have virtual functions? or keep 2 classes, at least rename AdaptiveMeshRefinement -> AmrNeopz
    53                 #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
     53                #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_AD_)
    5454                AdaptiveMeshRefinement *amr;              //adaptive mesh refinement object. It keeps coarse mesh and execute refinement process
    5555                #endif
    5656
    57                 #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     57                #if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    5858                AmrBamg *amrbamg; //adaptive mesh refinement object. It keeps coarse mesh and execute refinement process
    5959                #endif
     
    164164
    165165                /*AMR*/
    166                 #if !defined(_HAVE_ADOLC_)
     166                #if !defined(_HAVE_AD_)
    167167                void ReMesh(void);
    168168                void BedrockFromMismipPlus(void);
     
    191191                #endif
    192192
    193                 #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     193                #if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    194194                void ReMeshBamg(int* pnewnumberofvertices,int* pnewnumberofelements,IssmDouble** pnewx,IssmDouble** pnewy,IssmDouble** pnewz,int** pnewelementslist);
    195195                void InitializeAdaptiveRefinementBamg(void);
     
    199199                #endif
    200200
    201                 #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_ADOLC_)
     201                #if defined(_HAVE_NEOPZ_) && !defined(_HAVE_AD_)
    202202                void ReMeshNeopz(int* pnewnumberofvertices,int* pnewnumberofelements,IssmDouble** pnewx,IssmDouble** pnewy,IssmDouble** pnewz,int** pnewelementslist);
    203203                void InitializeAdaptiveRefinementNeopz(void);
  • issm/trunk/src/c/classes/IoModel.cpp

    r23189 r23394  
    2727#include "../shared/io/io.h"
    2828#include "../shared/shared.h"
     29
     30#ifdef _HAVE_CODIPACK_
     31extern CoDi_global codi_global;
     32#include <sstream> // for output of the CoDiPack tape
     33#endif
    2934
    3035/*IoConstant class and methods*/
     
    431436        if(trace || (autodiff && !iscontrol)){
    432437
    433                 #ifdef _HAVE_ADOLC_
     438                #ifdef _HAVE_AD_
     439                // FIXME codi here we should be able to execute codi version as normal
    434440                this->FetchData(&num_independent_objects,"md.autodiff.num_independent_objects");
    435441                if(num_independent_objects){
     
    460466                #else
    461467                /*if we asked for AD computations, we have a problem!: */
    462                 _error_("Cannot carry out AD mode computations without support of ADOLC compiled in!");
     468                _error_("Cannot carry out AD mode computations without support of ADOLC or CoDiPack compiled in!");
    463469                #endif
    464470        }
     
    17021708        if(X) Xcount=*pXcount;
    17031709
    1704         #ifdef _HAVE_ADOLC_ //cannot come here unless you are running AD mode, from DeclaredIndependents:
     1710        #ifdef _HAVE_AD_ //cannot come here unless you are running AD mode, from DeclaredIndependents:
    17051711
    17061712        /*output: */
     
    17191725                /*Now, before we even broadcast this to other nodes, declare the scalar  as an independent variable!. If we
    17201726                 *have been supplied an X vector, use it instead of what we just read: */
    1721                 if(X){
    1722                         scalar<<=X[Xcount];
    1723                 }
    1724                 else{
    1725                         scalar<<=pscalar;
    1726                 }
     1727                #if defined(_HAVE_CODIPACK_)
     1728                        // FIXME codi here we just assign instead of using "operator <<="
     1729                        if(X){
     1730                                scalar=X[Xcount];
     1731                        } else {
     1732                                scalar=pscalar;
     1733                        }
     1734                        auto& tape_codi = IssmDouble::getGlobalTape();
     1735                        tape_codi.registerInput(scalar);
     1736                        codi_global.input_indices.push_back(scalar.getGradientData());
     1737                #else
     1738                        if(X){
     1739                                scalar<<=X[Xcount];
     1740                        }
     1741                        else{
     1742                                scalar<<=pscalar;
     1743                        }
     1744                #endif
    17271745        }
    17281746
     
    17441762        if(X) Xcount=*pXcount;
    17451763
    1746         #ifdef _HAVE_ADOLC_ //cannot come here unless you are running AD mode, from DeclaredIndependents:
     1764        #ifdef _HAVE_AD_ //cannot come here unless you are running AD mode, from DeclaredIndependents:
    17471765
    17481766        /*Intermediaries*/
     
    17851803                        /*Now, before we even broadcast this to other nodes, declare the whole matrix as a independent variable!
    17861804                          If we have been supplied an X vector, use it instead of what we just read: */
    1787                         if(X){
    1788                                 for(int i=0;i<M*N;i++) matrix[i]<<=X[Xcount+i];  /*<<= ADOLC overloaded operator to declare independent*/
    1789                         }
    1790                         else{
    1791                                 for(int i=0;i<M*N;i++) matrix[i]<<=buffer[i];
    1792                         }
     1805                        #if defined(_HAVE_CODIPACK_)
     1806                                // FIXME codi here we just assign instead of using "operator <<="
     1807                                auto& tape_codi = IssmDouble::getGlobalTape();
     1808                                if(X){
     1809                                        for (int i=0;i<M*N;i++) {
     1810                                                matrix[i]=X[Xcount+i];
     1811                                                tape_codi.registerInput(matrix[i]);
     1812                                                codi_global.input_indices.push_back(matrix[i].getGradientData());
     1813                                        }
     1814                                }
     1815                                else{
     1816                                        for (int i=0;i<M*N;i++) {
     1817                                                matrix[i]=buffer[i];
     1818                                                tape_codi.registerInput(matrix[i]);
     1819                                                codi_global.input_indices.push_back(matrix[i].getGradientData());
     1820                                        }
     1821                                }
     1822                        #else /*ADOLC*/
     1823                                if(X){
     1824                                        for(int i=0;i<M*N;i++) matrix[i]<<=X[Xcount+i];  /*<<= ADOLC overloaded operator to declare independent*/
     1825                                }
     1826                                else{
     1827                                        for(int i=0;i<M*N;i++) matrix[i]<<=buffer[i];
     1828                                }
     1829                        #endif
    17931830                }
    17941831                ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
     
    17981835        else _error_("cannot declare the independent variable \"" << data_name <<  "\" if it's empty!");
    17991836
     1837        // FIXME codi is that at all relevant to CoDiPack or can we simply assume the same?
     1838       
    18001839        /*Add to data as independent*/
    18011840        this->AddDataIndependent(new IoData(matrix,code,layout,M,N,data_name));
     
    24722511        /*recover my_rank:*/
    24732512        my_rank=IssmComm::GetRank();
    2474         _assert_(strncmp(data_name,mddot,3)==0);
     2513        if(strncmp(data_name,mddot,3)!=0){
     2514                _error_("Cannot fetch \""<<data_name<<"\" does not start with \""<<mddot<<"\"");
     2515        }
    24752516
    24762517        /*Go find in the binary file, the position of the data we want to fetch: */
     
    25622603
    25632604        if(trace || (autodiff && !iscontrol)){
    2564                 #ifdef _HAVE_ADOLC_
     2605
     2606                #if defined(_HAVE_ADOLC_)
    25652607                /*Retrieve parameters: */
    25662608                this->FetchData(&keep,"md.autodiff.keep");
     
    25792621                int skipFileDeletion=1;
    25802622                trace_on(my_rank,keepTaylors,reCast<size_t>(obufsize),reCast<size_t>(lbufsize),reCast<size_t>(cbufsize),reCast<size_t>(tbufsize),skipFileDeletion);
     2623
     2624                #elif defined(_HAVE_CODIPACK_)
     2625                //fprintf(stderr, "*** Codipack IoModel::StartTrace\n");
     2626                /*
     2627                 * FIXME codi
     2628                 * - ADOL-C variant uses fine grained tracing with various arguments
     2629                 * - ADOL-C variant sets a garbage collection parameter for its tape
     2630                 * -> These parameters are not read for the CoDiPack ISSM version!
     2631                 */
     2632                auto& tape_codi = IssmDouble::getGlobalTape();
     2633                tape_codi.setActive();
     2634                #if _AD_TAPE_ALLOC_
     2635                //alloc_profiler.Tag(StartInit, true);
     2636                IssmDouble x_t(1.0), y_t(1.0);
     2637                tape_codi.registerInput(y_t);
     2638                int codi_allocn = 0;
     2639                this->FetchData(&codi_allocn,"md.autodiff.tapeAlloc");
     2640                for(int i = 0;i < codi_allocn;++i) {
     2641                        x_t = y_t * y_t;
     2642                }
     2643                /*
     2644                std::stringstream out_s;
     2645                IssmDouble::getGlobalTape().printStatistics(out_s);
     2646                _printf0_("StartTrace::Tape Statistics     : TapeAlloc count=[" << codi_allocn << "]\n" << out_s.str());
     2647                */
     2648                tape_codi.reset();
     2649                //alloc_profiler.Tag(FinishInit, true);
    25812650                #endif
    2582         }
    2583 
    2584 }
    2585 /*}}}*/
     2651                #endif
     2652        }
     2653
     2654}
     2655/*}}}*/
  • issm/trunk/src/c/classes/Materials/Matpar.cpp

    r23189 r23394  
    107107                                        iomodel->FindConstant(&this->rlapslgm,"md.smb.rlapslgm");
    108108                                        break;
     109                                case SMBpddSicopolisEnum:
     110                                        iomodel->FindConstant(&this->desfac,"md.smb.desfac");
     111                                        iomodel->FindConstant(&this->rlaps,"md.smb.rlaps");
     112                                        break;
    109113                                case SMBd18opddEnum:
    110114                                        iomodel->FindConstant(&this->desfac,"md.smb.desfac");
    111115                                        iomodel->FindConstant(&this->rlaps,"md.smb.rlaps");
    112116                                        iomodel->FindConstant(&this->rlapslgm,"md.smb.rlapslgm");
    113                                         iomodel->FindConstant(&this->dpermil,"md.smb.dpermil");                                 
     117                                        iomodel->FindConstant(&this->dpermil,"md.smb.dpermil");
    114118                                case SMBgradientsEnum:
    115119                                        /*Nothing to add*/
     
    125129                                        break;
    126130                                case SMBmeltcomponentsEnum:
     131                                        /*Nothing to add*/
     132                                        break;
     133                                case SMBgradientscomponentsEnum:
    127134                                        /*Nothing to add*/
    128135                                        break;
     
    170177                        break;
    171178                case MaterialsEnum:
    172                         //we have several types of materials. Retrieve this info first: 
     179                        //we have several types of materials. Retrieve this info first:
    173180                        iomodel->FetchData(&nature,&nnat,&dummy,"md.materials.nature");
    174181
    175                         //go through list of materials, and create constant parameters accordingly: 
    176                         for(int i=0;i<nnat;i++){ 
     182                        //go through list of materials, and create constant parameters accordingly:
     183                        for(int i=0;i<nnat;i++){
    177184                                switch(IoCodeToEnumMaterials(nature[i])){ //{{{
    178185                                        case MatlithoEnum:
     
    211218                                                                iomodel->FindConstant(&this->rlapslgm,"md.smb.rlapslgm");
    212219                                                                break;
     220                                                        case SMBpddSicopolisEnum:
     221                                                                iomodel->FindConstant(&this->desfac,"md.smb.desfac");
     222                                                                iomodel->FindConstant(&this->rlaps,"md.smb.rlaps");
     223                                                                break;
    213224                                                        case SMBd18opddEnum:
    214225                                                                iomodel->FindConstant(&this->desfac,"md.smb.desfac");
    215226                                                                iomodel->FindConstant(&this->rlaps,"md.smb.rlaps");
    216227                                                                iomodel->FindConstant(&this->rlapslgm,"md.smb.rlapslgm");
    217                                                                 iomodel->FindConstant(&this->dpermil,"md.smb.dpermil");                                 
     228                                                                iomodel->FindConstant(&this->dpermil,"md.smb.dpermil");
    218229                                                        case SMBgradientsEnum:
    219230                                                                /*Nothing to add*/
     
    233244                                                        default:
    234245                                                                _error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
    235                                                 } 
     246                                                }
    236247                                                if(hydrology_model==HydrologydcEnum){
    237248                                                        iomodel->FindConstant(&this->sediment_compressibility,"md.hydrology.sediment_compressibility");
     
    350361
    351362        this->Echo();
    352 }               
     363}
    353364/*}}}*/
    354365void Matpar::Echo(void){/*{{{*/
     
    381392        _printf_("   sediment_porosity: " << sediment_porosity << "\n");
    382393        _printf_("   sediment_thickness: " << sediment_thickness << "\n");
    383         _printf_("   water_compressibility: " << water_compressibility << "\n");       
    384         _printf_("   epl_compressibility: " << epl_compressibility << "\n");   
    385         _printf_("   epl_porosity: " << epl_porosity << "\n"); 
    386         _printf_("   epl_init_thickness: " << epl_init_thickness << "\n");     
    387         _printf_("   epl_colapse_thickness: " << epl_colapse_thickness << "\n");       
    388         _printf_("   epl_max_thickness: " << epl_max_thickness << "\n");       
    389         _printf_("   epl_conductivity: " << epl_conductivity << "\n"); 
    390         _printf_("   lithosphere_shear_modulus: " << lithosphere_shear_modulus << "\n");       
    391         _printf_("   lithosphere_density: " << lithosphere_density << "\n");   
    392         _printf_("   mantle_shear_modulus: " << mantle_shear_modulus << "\n"); 
    393         _printf_("   mantle_density: " << mantle_density << "\n");     
    394         _printf_("   earth_density: " << earth_density << "\n");       
     394        _printf_("   water_compressibility: " << water_compressibility << "\n");
     395        _printf_("   epl_compressibility: " << epl_compressibility << "\n");
     396        _printf_("   epl_porosity: " << epl_porosity << "\n");
     397        _printf_("   epl_init_thickness: " << epl_init_thickness << "\n");
     398        _printf_("   epl_colapse_thickness: " << epl_colapse_thickness << "\n");
     399        _printf_("   epl_max_thickness: " << epl_max_thickness << "\n");
     400        _printf_("   epl_conductivity: " << epl_conductivity << "\n");
     401        _printf_("   lithosphere_shear_modulus: " << lithosphere_shear_modulus << "\n");
     402        _printf_("   lithosphere_density: " << lithosphere_density << "\n");
     403        _printf_("   mantle_shear_modulus: " << mantle_shear_modulus << "\n");
     404        _printf_("   mantle_density: " << mantle_density << "\n");
     405        _printf_("   earth_density: " << earth_density << "\n");
    395406        return;
    396407}
     
    512523                        this->dpermil=constant;
    513524                        break;
    514                 default: 
     525                default:
    515526                        break;
    516527        }
  • issm/trunk/src/c/classes/Numberedcostfunction.cpp

    r23189 r23394  
    149149                                 _error_("not supported");
    150150                 }
     151                 _printf0_("#"<<i+1<<": "<<value<<" ");
    151152                 value_sum += value;
    152153 }
     154         _printf0_("\n");
    153155
    154156         /*done:*/
  • issm/trunk/src/c/classes/Options/GenericOption.h

    r22758 r23394  
    102102};
    103103
    104 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
     104#if defined(_HAVE_AD_) && !defined(_WRAPPERS_)
    105105/*We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization*/
    106106template <> inline void GenericOption<IssmPDouble*>::Get(IssmPDouble** pvalue){ /*{{{*/
  • issm/trunk/src/c/classes/Params/Parameters.cpp

    r22758 r23394  
    9292}
    9393/*}}}*/
    94 void Parameters::DeepEcho(void){/*{{{*/ 
     94void Parameters::DeepEcho(void){/*{{{*/
    9595        for(int i=0;i<NUMPARAMS;i++) {
    9696                if(this->params[i]) this->params[i]->DeepEcho();
     
    9999}
    100100/*}}}*/
    101 void Parameters::Echo(void){/*{{{*/     
     101void Parameters::Echo(void){/*{{{*/
    102102        for(int i=0;i<NUMPARAMS;i++) {
    103103                if(this->params[i]) this->params[i]->Echo();
     
    139139
    140140                        /*Recover enum of object first: */
    141                         MARSHALLING(obj_enum); 
     141                        MARSHALLING(obj_enum);
    142142
    143143                        if(obj_enum==DoubleParamEnum){
     
    200200                                fileparam->Marshall(pmarshalled_data,pmarshalled_data_size,marshall_direction);
    201201                                delete fileparam;
    202                                 /* No need to add this object, the pointer is not valid             
     202                                /* No need to add this object, the pointer is not valid
    203203                                        The FemModel should reset all FileParams in the restart function */
    204204                        }
     
    426426}
    427427/*}}}*/
     428void Parameters::FindParamAndMakePassive(IssmPDouble* pscalar,int param_enum){ _assert_(this);/*{{{*/
     429        _assert_(param_enum>ParametersSTARTEnum);
     430        _assert_(param_enum<ParametersENDEnum);
     431
     432        /*Get "active" parameter*/
     433        IssmDouble intermediary;
     434        int index = param_enum - ParametersSTARTEnum -1;
     435        if(!this->params[index]) _error_("Parameter " << EnumToStringx(param_enum) <<" not set");
     436        this->params[index]->GetParameterValue(&intermediary);
     437
     438        /*cast to "passive"*/
     439        *pscalar=reCast<IssmPDouble>(intermediary);
     440}
     441/*}}}*/
     442void Parameters::FindParamAndMakePassive(IssmPDouble** pvec,int* pM, int param_enum){ _assert_(this);/*{{{*/
     443
     444        _assert_(param_enum>ParametersSTARTEnum);
     445        _assert_(param_enum<ParametersENDEnum);
     446
     447        int index = param_enum - ParametersSTARTEnum -1;
     448
     449        /*Output*/
     450        int         n;
     451        IssmDouble* vector = NULL;
     452
     453        if(!this->params[index]) _error_("Parameter " << EnumToStringx(param_enum) <<" not set");
     454        this->params[index]->GetParameterValue(&vector,&n);
     455
     456        /*Make output passive*/
     457        IssmPDouble* output = xNew<IssmPDouble>(n);
     458        for(int i=0;i<n;i++) output[i] = reCast<IssmPDouble>(vector[i]);
     459
     460        /*assign output pointers*/
     461        if(pvec) *pvec = output;
     462        if(pM)   *pM   = n;
     463}/*}}}*/
    428464void Parameters::FindParamInDataset(IssmDouble** pIssmDoublearray,int* pM,int* pN,int dataset_type,int enum_type){/*{{{*/
    429465        _assert_(this);
     
    613649char* OptionsFromAnalysis(char** pouttoolkit,Parameters* parameters,int analysis_type){ /*{{{*/
    614650
    615         /* figure out ISSM options for current analysis, return a string. */ 
     651        /* figure out ISSM options for current analysis, return a string. */
    616652
    617653        /*output: */
     
    631667
    632668        parameters->FindParam(&strings,&numanalyses,ToolkitsOptionsStringsEnum);
    633         parameters->FindParam(&toolkits,&dummy,ToolkitsTypesEnum); _assert_(dummy==numanalyses); 
    634         parameters->FindParam(&analyses,&dummy,ToolkitsOptionsAnalysesEnum); _assert_(dummy==numanalyses); 
     669        parameters->FindParam(&toolkits,&dummy,ToolkitsTypesEnum); _assert_(dummy==numanalyses);
     670        parameters->FindParam(&analyses,&dummy,ToolkitsOptionsAnalysesEnum); _assert_(dummy==numanalyses);
    635671
    636672        if(numanalyses==0)return NULL; //we did not find petsc options, don't bother.
     
    674710        xDelete<int>(analyses);
    675711        return outstring;
    676 } 
     712}
    677713/*}}}*/
    678714void ToolkitsOptionsFromAnalysis(Parameters* parameters,int analysis_type){ /*{{{*/
    679715
    680716        /*!\file:  ToolkitsOptionsFromAnalysis.cpp
    681          * \brief: for each analysis, setup the issmoptions string. 
    682          * This is mainly for the case where we run our toolkits using petsc. In this case, we need to 
    683          * plug our toolkits options directly into the petsc options database. This is the case for each analysis type 
     717         * \brief: for each analysis, setup the issmoptions string.
     718         * This is mainly for the case where we run our toolkits using petsc. In this case, we need to
     719         * plug our toolkits options directly into the petsc options database. This is the case for each analysis type
    684720         * and parameters
    685          */ 
     721         */
    686722
    687723        char* options = NULL;
     
    695731
    696732        #ifdef _HAVE_PETSC_
    697                 /*In case we are using PETSC, we do not rely on issmoptions. Instead, we dump issmoptions into the Petsc 
     733                /*In case we are using PETSC, we do not rely on issmoptions. Instead, we dump issmoptions into the Petsc
    698734                 * options database: */
    699735                #if (_PETSC_MINOR_>=7)
     
    717753}
    718754/*}}}*/
    719 
    720 /*Specific case with ADOL-C, we might need to get double params for m1qn3*/
    721 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
    722 void Parameters::FindParamAndMakePassive(double* pscalar,int param_enum){ _assert_(this);/*{{{*/
    723         _assert_(param_enum>ParametersSTARTEnum);
    724         _assert_(param_enum<ParametersENDEnum);
    725 
    726         /*Get "active" parameter*/
    727         IssmDouble intermediary;
    728         int index = param_enum - ParametersSTARTEnum -1;
    729         if(!this->params[index]) _error_("Parameter " << EnumToStringx(param_enum) <<" not set");
    730         this->params[index]->GetParameterValue(&intermediary);
    731 
    732         /*cast to "passive"*/
    733         *pscalar=reCast<double>(intermediary);
    734 }
    735 /*}}}*/
    736 #endif
  • issm/trunk/src/c/classes/Params/Parameters.h

    r22758 r23394  
    5252                void  FindParam(FILE** pfid,int enum_type);
    5353                void  FindParam(DataSet** pdataset, int enum_type);
     54                void  FindParamAndMakePassive(IssmPDouble* pscalar, int enum_type);
     55                void  FindParamAndMakePassive(IssmPDouble** pvec,int* pM,int enum_type);
    5456                void  FindParamInDataset(IssmDouble** pIssmDoublearray,int* pM,int* pN,int dataset_type,int enum_type);
    5557
     
    7072                Param* FindParamObject(int enum_type);
    7173
    72                 /*Specific instantiations for IssmDouble*: */
    73                 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
    74                 void  FindParamAndMakePassive(double* pscalar, int enum_type);
    75                 #endif
    76 
    7774};
    7875
  • issm/trunk/src/c/classes/Profiler.cpp

    r23189 r23394  
    1515/*Profiler constructors and destructors:*/
    1616Profiler::Profiler(){/*{{{*/
    17         for(int i=0;i<MAXIMUMSIZE;i++){
     17        for(int i=0;i<MAXPROFSIZE;i++){
    1818                this->time[i]          = 0.;
    1919                this->time_start[i]    = 0.;
     
    2323                this->memory_start[i]  = 0.;
    2424                this->running[i]       = false;
     25                this->used[i]          = false;
    2526        }
    2627} /*}}}*/
     
    3233        Profiler* output=new Profiler();
    3334
    34         for(int i=0;i<MAXIMUMSIZE;i++){
     35        for(int i=0;i<MAXPROFSIZE;i++){
    3536                output->time[i]  =this->time[i];
    3637                output->flops[i] =this->flops[i];
     
    4950
    5051        _printf_("Profiler:\n");
    51         for(int i=0;i<MAXIMUMSIZE;i++){
     52        for(int i=0;i<MAXPROFSIZE;i++){
    5253                _printf_("    Tag "<<i<<":\n");
    5354                _printf_("       flops:   "<<this->flops[i]<<"\n");
     
    7071        MARSHALLING_ENUM(ProfilerEnum);
    7172        pointer = &this->time[0];
    72         MARSHALLING_DYNAMIC(pointer,IssmPDouble,MAXIMUMSIZE);
     73        MARSHALLING_DYNAMIC(pointer,IssmPDouble,MAXPROFSIZE);
    7374        pointer = &this->flops[0];
    74         MARSHALLING_DYNAMIC(pointer,IssmPDouble,MAXIMUMSIZE);
     75        MARSHALLING_DYNAMIC(pointer,IssmPDouble,MAXPROFSIZE);
    7576        pointer = &this->memory[0];
    76         MARSHALLING_DYNAMIC(pointer,IssmPDouble,MAXIMUMSIZE);
     77        MARSHALLING_DYNAMIC(pointer,IssmPDouble,MAXPROFSIZE);
    7778        bpointer = &this->running[0];
    78         MARSHALLING_DYNAMIC(bpointer,bool,MAXIMUMSIZE);
     79        MARSHALLING_DYNAMIC(bpointer,bool,MAXPROFSIZE);
    7980
    8081} /*}}}*/
     
    8889        /*Get tag*/
    8990        _assert_(tag>=0);
    90         _assert_(tag<MAXIMUMSIZE);
     91        _assert_(tag<MAXPROFSIZE);
    9192        if(this->running[tag]) _error_("Tag "<<tag<<" has not been stopped");
    9293
     
    9798        /*Get tag*/
    9899        _assert_(tag>=0);
    99         _assert_(tag<MAXIMUMSIZE);
     100        _assert_(tag<MAXPROFSIZE);
    100101        if(this->running[tag]) _error_("Tag "<<tag<<" has not been stopped");
    101102
     
    130131        /*Get initial flops*/
    131132        _assert_(tag>=0);
    132         _assert_(tag<MAXIMUMSIZE);
     133        _assert_(tag<MAXPROFSIZE);
    133134        if(this->running[tag]) _error_("Tag "<<tag<<" has not been stopped");
    134135
     
    140141        /*Check tag*/
    141142        _assert_(tag>=0);
    142         _assert_(tag<MAXIMUMSIZE);
     143        _assert_(tag<MAXPROFSIZE);
    143144        if(this->running[tag]) _error_("Tag "<<tag<<" is already running");
    144145
     
    167168        /*Plug into this->time: */
    168169        _assert_(tag>=0);
    169         _assert_(tag<MAXIMUMSIZE);
     170        _assert_(tag<MAXPROFSIZE);
    170171        this->time_start[tag]   = t;
    171172        this->flops_start[tag]  = f;
     
    174175        /*turn on running*/
    175176        this->running[tag] = true;
     177        this->used[tag]    = true;
    176178}/*}}}*/
    177179void  Profiler::Stop(int tag,bool dontmpisync){/*{{{*/
     
    179181        /*Check tag*/
    180182        _assert_(tag>=0);
    181         _assert_(tag<MAXIMUMSIZE);
     183        _assert_(tag<MAXPROFSIZE);
    182184        if(!this->running[tag]) _error_("Tag "<<tag<<" is not running");
    183185
     
    206208        /*Plug into this->time: */
    207209        _assert_(tag>=0);
    208         _assert_(tag<MAXIMUMSIZE);
     210        _assert_(tag<MAXPROFSIZE);
    209211        this->time[tag]   += t - this->time_start[tag];
    210212        this->flops[tag]  += f - this->flops_start[tag];
     
    214216        this->running[tag] = false;
    215217}/*}}}*/
     218bool  Profiler::Used(int tag){/*{{{*/
     219
     220        /*Check tag*/
     221        _assert_(tag>=0);
     222        _assert_(tag<MAXPROFSIZE);
     223        return this->used[tag];
     224}/*}}}*/
  • issm/trunk/src/c/classes/Profiler.h

    r22758 r23394  
    1111
    1212/*Macros*/
    13 #define TOTAL 0      /*Profiling Total time */
    14 #define MPROCESSOR 1 /*Profiling Model processor*/
    15 #define CORE 2       /*Profiling solution */
    16 #define SOLVER 3     /*Profiling solution */
    17 #define ADCORE 4     /*Profiling AD */
    18 #define MAXIMUMSIZE 5
     13#define TOTAL              0 /*Profiling Total time */
     14#define MPROCESSOR         1 /*Profiling Model processor*/
     15#define CORE               2 /*Profiling solution */
     16#define SOLVER             3 /*Profiling solution */
     17#define ADCORE             4 /*Profiling AD */
     18#define THERMALCORE                     5 /*Profiling THERMAL */
     19#define HYDROLOGYCORE           6 /*Profiling HYDROLOGY */
     20#define STRESSBALANCECORE       7 /*Profiling STRESSBALANCE */
     21#define DAMAGECORE                      8 /*Profiling DAMAGE */
     22#define MOVINGFRONTCORE         9 /*Profiling MOVINGFRONT */
     23#define MASSTRANSPORTCORE       10 /*Profiling MASSTRANSPORT */
     24#define SMBCORE                         11 /*Profiling SMB */
     25#define GROUNDINGLINECORE       12 /*Profiling GROUDINGLINE MIGRATION */
     26#define GIACORE                         13 /*Profiling GIA */
     27#define ESACORE                         14 /*Profiling ESA */
     28#define SLRCORE                         15 /*Profiling SLR */
     29#define MAXPROFSIZE                     16 /*Used to initialize static arrays*/
    1930
    2031class Profiler: public Object{
    2132
    2233        public:
    23                 IssmPDouble flops[MAXIMUMSIZE];
    24                 IssmPDouble flops_start[MAXIMUMSIZE];
    25                 IssmPDouble memory[MAXIMUMSIZE];
    26                 IssmPDouble memory_start[MAXIMUMSIZE];
    27                 IssmPDouble time[MAXIMUMSIZE];
    28                 IssmPDouble time_start[MAXIMUMSIZE];
    29                 bool        running[MAXIMUMSIZE];
     34                IssmPDouble flops[MAXPROFSIZE];
     35                IssmPDouble flops_start[MAXPROFSIZE];
     36                IssmPDouble memory[MAXPROFSIZE];
     37                IssmPDouble memory_start[MAXPROFSIZE];
     38                IssmPDouble time[MAXPROFSIZE];
     39                IssmPDouble time_start[MAXPROFSIZE];
     40                bool        running[MAXPROFSIZE];
     41                bool        used[MAXPROFSIZE];
    3042
    3143                /*Profiler constructors, destructors */
     
    4860                int          TotalTimeModSec(int tag);
    4961                IssmPDouble  Memory(int tag);
    50                 void         Start(int tagenum,bool dontmpisync=false);
    51                 void         Stop(int tagenum,bool dontmpisync=false);
     62                void         Start(int tagenum,bool dontmpisync=true); /*Do not call MPI barrier by default to save some ms*/
     63                void         Stop(int tagenum, bool dontmpisync=true); /*Do not call MPI barrier by default to save some ms*/
     64                bool         Used(int tagenum);
    5265};
    5366
  • issm/trunk/src/c/cores/ad_core.cpp

    r23189 r23394  
    1919/*}}}*/
    2020
     21#ifdef _HAVE_CODIPACK_
     22CoDi_global codi_global = {};
     23#endif
    2124void ad_core(FemModel* femmodel){
    2225
     
    4144        if(isautodiff && !iscontrol){
    4245
    43                 #ifdef _HAVE_ADOLC_
     46                #if defined(_HAVE_ADOLC_)
    4447                        if(VerboseAutodiff())_printf0_("   start ad core\n");
    4548
     
    318321                        xDelete(axp);
    319322                        xDelete(driver);
     323
     324                        #elif defined(_HAVE_CODIPACK_)
     325                        if(VerboseAutodiff())_printf0_("   start CoDiPack ad core\n");
     326
     327                        /*First, stop tracing: */
     328                        auto& tape_codi = IssmDouble::getGlobalTape();
     329                        tape_codi.setPassive();
     330
     331                        if(VerboseAutodiff()){ /*{{{*/
     332                                if(my_rank == 0) {
     333                                        // FIXME codi "just because" for now
     334                                        tape_codi.printStatistics(std::cout);
     335                                        codi_global.print(std::cout);
     336                                }
     337                        }
     338
     339                        /*retrieve parameters: */
     340                        femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
     341                        femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
     342
     343                        /*if no dependents, no point in running a driver: */
     344                        if(!(num_dependents*num_independents)) return;
     345
     346                        /*Branch according to AD driver: */
     347                        femmodel->parameters->FindParam(&driver,AutodiffDriverEnum);
     348                        if(VerboseAutodiff())_printf0_("   driver: " << driver << "\n");
     349
     350                        if (strcmp(driver,"fos_reverse")==0) { /*{{{*/
     351                                if(VerboseAutodiff())_printf0_("   CoDiPack fos_reverse\n");
     352                                int     aDepIndex=0;
     353                                double *weightVectorTimesJac=NULL;
     354
     355                                /*retrieve direction index: */
     356                                femmodel->parameters->FindParam(&aDepIndex,AutodiffFosReverseIndexEnum);
     357                                if (my_rank==0) {
     358                                        if (aDepIndex<0 || aDepIndex>=num_dependents
     359                                                        || codi_global.output_indices.size() <= aDepIndex){
     360                                                _error_("index value for AutodiffFosReverseIndexEnum should be in [0,num_dependents-1]");
     361                                        }
     362                                        tape_codi.setGradient(codi_global.output_indices[aDepIndex], 1.0);
     363                                }
     364
     365                                tape_codi.evaluate();
     366
     367                                weightVectorTimesJac=xNew<double>(num_independents);
     368                                /*call driver: */
     369                                auto in_size = codi_global.input_indices.size();
     370                                for(size_t i = 0; i < in_size; ++i) {
     371                                        weightVectorTimesJac[i] = tape_codi.getGradient(codi_global.input_indices[i]);
     372                                }
     373
     374                                /*add to results*/
     375                                femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,weightVectorTimesJac,num_independents,1,0,0.0));
     376
     377                                /*free resources :*/
     378                                xDelete(weightVectorTimesJac);
     379                        } /*}}}*/
     380                        else _error_("driver: " << driver << " not yet supported!");
     381
     382                        if(VerboseAutodiff())_printf0_("   end CoDiPack ad core\n");
     383                        xDelete(driver);
    320384                #else
    321385                        _error_("Should not be requesting AD drivers when an AD library is not available!");
  • issm/trunk/src/c/cores/adgradient_core.cpp

    r23189 r23394  
    4848        if(isautodiff){
    4949
    50                 #ifdef _HAVE_ADOLC_
     50                #if defined(_HAVE_ADOLC_)
    5151                        if(VerboseAutodiff())_printf0_("   start ad core\n");
    5252
     
    182182                        xDelete(totalgradient);
    183183                        xDelete(axp); /*}}}*/
     184
     185                #elif defined(_HAVE_CODIPACK_)
     186                        fprintf(stderr, "*** Codipack adgradient_core()\n");
    184187                #else
    185188                        _error_("Should not be requesting AD drivers when an AD library is not available!");
  • issm/trunk/src/c/cores/adjointstressbalance_core.cpp

    r23189 r23394  
    3131        if(VerboseSolution()) _printf0_("   computing velocities\n");
    3232        femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
     33       
     34        bool is_schur_cg_solver = false;
     35        #ifdef _HAVE_PETSC_
     36        int solver_type;
     37        PetscOptionsDetermineSolverType(&solver_type);
     38
     39        if(solver_type==FSSolverEnum) is_schur_cg_solver = true;
     40        #endif
     41
    3342        if(isFS){
    3443                if (fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum)
    3544                 solutionsequence_la(femmodel);
     45                else if(is_schur_cg_solver)
     46                 solutionsequence_schurcg(femmodel);
    3647                else
    3748                 solutionsequence_nonlinear(femmodel,conserve_loads);
  • issm/trunk/src/c/cores/balancethickness_core.cpp

    r16518 r23394  
    2121        femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
    2222
    23         if(VerboseSolution()) _printf0_("call computational core:\n");
     23        if(VerboseSolution()) _printf0_("   call computational core:\n");
    2424        solutionsequence_linear(femmodel);
    2525
  • issm/trunk/src/c/cores/balancevelocity_core.cpp

    r19105 r23394  
    2727        solutionsequence_linear(femmodel);
    2828
    29         if(VerboseSolution()) _printf0_("call computational core:\n");
     29        if(VerboseSolution()) _printf0_("   call computational core:\n");
    3030        femmodel->SetCurrentConfiguration(BalancevelocityAnalysisEnum);
    3131        solutionsequence_linear(femmodel);
  • issm/trunk/src/c/cores/control_core.cpp

    r22758 r23394  
    8181        IssmDouble  *XL = NULL;
    8282        IssmDouble  *XU = NULL;
    83         GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
    84         GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
     83        GetVectorFromControlInputsx(&XL,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
     84        GetVectorFromControlInputsx(&XU,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
    8585        for(long i=0;i<nsize;i++){
    8686                if(X0[i]>XU[i]) X0[i]=XU[i];
     
    9797                femmodel->OutputControlsx(&femmodel->results);
    9898
    99                 #ifdef _HAVE_ADOLC_
     99                #ifdef _HAVE_AD_
    100100                IssmPDouble* J_passive=xNew<IssmPDouble>(nsteps);
    101101                for(int i=0;i<nsteps;i++) J_passive[i]=reCast<IssmPDouble>(J[i]);
     
    134134        IssmDouble  *XL = NULL;
    135135        IssmDouble  *XU = NULL;
    136         GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
    137         GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
     136        GetVectorFromControlInputsx(&XL,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
     137        GetVectorFromControlInputsx(&XU,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
    138138        for(long i=0;i<nsize;i++){
    139139                if(X[i]>XU[i]) X[i]=XU[i];
     
    143143        /*Update control input*/
    144144        SetControlInputsFromVectorx(femmodel,X);
    145 
     145       
     146       
    146147        /*solve forward: */
    147148        switch(solution_type){
     
    150151                        stressbalance_core(femmodel);   //We need a 3D velocity!! (vz is required for the next thermal run)
    151152                        break;
    152                 case StressbalanceSolutionEnum:
     153                case StressbalanceSolutionEnum:{
    153154                        femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
    154                         solutionsequence_nonlinear(femmodel,conserve_loads);
    155                         break;
     155                       
     156                        bool is_schur_cg_solver = false;
     157                        #ifdef _HAVE_PETSC_
     158                        int solver_type;
     159                        PetscOptionsDetermineSolverType(&solver_type);
     160                        if(solver_type==FSSolverEnum) is_schur_cg_solver = true;
     161                        #endif
     162                       
     163                        if(is_schur_cg_solver){
     164                         solutionsequence_schurcg(femmodel);
     165                        }else{
     166                         solutionsequence_nonlinear(femmodel,conserve_loads);
     167                        }
     168                        }
     169                         break;
    156170                case BalancethicknessSolutionEnum:
    157171                        femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
     
    211225        IssmDouble  *XL = NULL;
    212226        IssmDouble  *XU = NULL;
    213         GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
    214         GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
     227        GetVectorFromControlInputsx(&XL,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
     228        GetVectorFromControlInputsx(&XU,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
    215229        for(long i=0;i<nsize;i++){
    216230                if(X[i]>XU[i]) X[i]=XU[i];
  • issm/trunk/src/c/cores/controlad_core.cpp

    r23189 r23394  
    1111#include "../solutionsequences/solutionsequences.h"
    1212
     13/*This file is probably never used!*/
    1314#if defined (_HAVE_M1QN3_)  & defined (_HAVE_ADOLC_)
    1415/*m1qn3 prototypes {{{*/
  • issm/trunk/src/c/cores/controladm1qn3_core.cpp

    r23189 r23394  
    1111#include "../solutionsequences/solutionsequences.h"
    1212
    13 #if defined (_HAVE_M1QN3_) && defined(_HAVE_ADOLC_)
    14 /*m1qn3 prototypes*/
     13#ifdef _HAVE_CODIPACK_
     14extern CoDi_global codi_global;
     15#include <sstream> // for output of the CoDiPack tape
     16#endif
     17
     18#if defined (_HAVE_M1QN3_) && defined(_HAVE_AD_)
     19/*m1qn3 prototypes {{{*/
    1520extern "C" void *ctonbe_; // DIS mode : Conversion
    1621extern "C" void *ctcabe_; // DIS mode : Conversion
     
    3136        int*         i;
    3237} m1qn3_struct;
     38/*}}}*/
    3339
    3440/*m1qm3 functions*/
    3541void simul_starttrace(FemModel* femmodel){/*{{{*/
    3642
     43        #if defined(_HAVE_ADOLC_)
    3744        /*Retrive ADOLC parameters*/
    3845        IssmDouble gcTriggerRatio;
     
    5764        int my_rank=IssmComm::GetRank();
    5865        trace_on(my_rank,keepTaylors,reCast<size_t>(obufsize),reCast<size_t>(lbufsize),reCast<size_t>(cbufsize),reCast<size_t>(tbufsize),skipFileDeletion);
     66
     67        #elif defined(_HAVE_CODIPACK_)
     68
     69                //fprintf(stderr, "*** Codipack IoModel::StartTrace\n");
     70                /*
     71                 * FIXME codi
     72                 * - ADOL-C variant uses fine grained tracing with various arguments
     73                 * - ADOL-C variant sets a garbage collection parameter for its tape
     74                 * -> These parameters are not read for the CoDiPack ISSM version!
     75                 */
     76                auto& tape_codi = IssmDouble::getGlobalTape();
     77                tape_codi.setActive();
     78                #if _AD_TAPE_ALLOC_
     79                //alloc_profiler.Tag(StartInit, true);
     80                IssmDouble x_t(1.0), y_t(1.0);
     81                tape_codi.registerInput(y_t);
     82                int codi_allocn = 0;
     83                femmodel->parameters->FindParam(&codi_allocn,AutodiffTapeAllocEnum);
     84                for(int i = 0;i < codi_allocn;++i) {
     85                        x_t = y_t * y_t;
     86                }
     87                /*
     88                std::stringstream out_s;
     89                IssmDouble::getGlobalTape().printStatistics(out_s);
     90                _printf0_("StartTrace::Tape Statistics     : TapeAlloc count=[" << codi_allocn << "]\n" << out_s.str());
     91                */
     92                tape_codi.reset();
     93                //alloc_profiler.Tag(FinishInit, true);
     94                #else
     95                tape_codi.reset();
     96                #endif
     97
     98        #else
     99        _error_("not implemented");
     100        #endif
    59101}/*}}}*/
    60 void simul_ad(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs){/*{{{*/
    61 
    62         /*Get rank*/
    63         int my_rank=IssmComm::GetRank();
    64 
    65         /*Recover Arguments*/
    66         m1qn3_struct *input_struct = (m1qn3_struct*)dzs;
    67 
    68         FemModel* femmodel = input_struct->femmodel;
    69         int num_responses,num_controls,numberofvertices,solution_type;
    70         femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
    71         int* N = NULL;
    72         int N_add = 0;
    73         int* control_enum = NULL;
    74 
    75         if (solution_type == TransientSolutionEnum){
    76                 femmodel = input_struct->femmodel->copy();
    77         }
    78 
    79         IssmPDouble*  Jlist        = input_struct->Jlist;
    80         int           JlistM       = input_struct->M;
    81         int           JlistN       = input_struct->N;
    82         int*          Jlisti       = input_struct->i;
    83         int           intn         = (int)*n;
    84 
    85         /*Recover some parameters*/
    86         IssmDouble* scaling_factors = NULL;
    87         femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
    88         femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
    89         femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
    90         femmodel->parameters->FindParam(&N,NULL,ControlInputSizeNEnum);
    91         femmodel->parameters->FindParam(&control_enum,NULL,InversionControlParametersEnum);
    92         numberofvertices=femmodel->vertices->NumberOfVertices();
    93 
    94         /*Constrain input vector and update controls*/
    95         double  *XL = NULL;
    96         double  *XU = NULL;
    97         GetPassiveVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
    98         GetPassiveVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
    99 
    100         N_add = 0;
    101         for (int c=0;c<num_controls;c++){
    102                 for(int i=0;i<numberofvertices*N[c];i++){
    103                         int index = N_add*numberofvertices+i;
    104                         X[index] = X[index]*reCast<double>(scaling_factors[c]);
    105                         if(X[index]>XU[index]) X[index]=XU[index];
    106                         if(X[index]<XL[index]) X[index]=XL[index];
    107                 }
    108                 N_add+=N[c];
    109         }
    110 
    111         /*Start Tracing*/
    112         simul_starttrace(femmodel);
    113         /*Set X as our new control input and as INDEPENDENT*/
    114 #ifdef _HAVE_AD_
    115         IssmDouble* aX=xNew<IssmDouble>(intn,"t");
    116 #else
    117         IssmDouble* aX=xNew<IssmDouble>(intn);
    118 #endif
    119         if(my_rank==0){
    120                 for(int i=0;i<intn;i++){
    121                         aX[i]<<=X[i];
    122                 }
    123         }
    124 
    125         ISSM_MPI_Bcast(aX,intn,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
    126         SetControlInputsFromVectorx(femmodel,aX);
    127         xDelete<IssmDouble>(aX);
    128 
    129         /*Compute solution (forward)*/
    130         void (*solutioncore)(FemModel*)=NULL;
    131         CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
    132         solutioncore(femmodel);
    133 
    134         /*Reset the time to zero for next optimization*/
    135         if(solution_type==TransientSolutionEnum){
    136                 IssmDouble restart_time;
    137                 femmodel->parameters->FindParam(&restart_time,TimesteppingStartTimeEnum);
    138                 femmodel->parameters->SetParam(restart_time,TimeEnum);
    139 
    140         }
    141 
    142         /*Get Dependents*/
    143         IssmDouble  output_value;
    144         int         num_dependents;
    145         IssmPDouble *dependents;
    146         DataSet*    dependent_objects=NULL;
    147         IssmDouble      J=0.;
    148         femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
    149         femmodel->parameters->FindParam(&dependent_objects,AutodiffDependentObjectsEnum);
    150 
    151         /*Go through our dependent variables, and compute the response:*/
    152         dependents=xNew<IssmPDouble>(num_dependents);
    153         for(int i=0;i<dependent_objects->Size();i++){
    154                 DependentObject* dep=(DependentObject*)dependent_objects->GetObjectByOffset(i);
    155                 if(solution_type==TransientSolutionEnum) output_value = dep->GetValue();
    156                 if(solution_type!=TransientSolutionEnum) dep->Responsex(&output_value,femmodel);
    157                 if (my_rank==0) {
    158                         output_value>>=dependents[i];
    159                         J+=output_value;
    160                 }
    161         }
    162 
    163         /*Turning off trace tape*/
     102void simul_stoptrace(){/*{{{*/
     103
     104        #if defined(_HAVE_ADOLC_)
    164105        trace_off();
    165 time_t now = time(NULL);
    166 if(my_rank==0) _printf_("\nTIME: "<<now<<"\n");
    167         /*Print tape statistics so that user can kill this run if something is off already:*/
    168106        if(VerboseAutodiff()){ /*{{{*/
     107
     108                #ifdef _HAVE_ADOLC_
     109                int my_rank=IssmComm::GetRank();
    169110                size_t  tape_stats[15];
    170111                tapestats(my_rank,tape_stats); //reading of tape statistics
     
    207148                }
    208149                delete [] sstats;
     150                #endif
     151
     152                #ifdef _HAVE_CODIPACK_
     153                #ifdef _AD_TAPE_ALLOC_
     154                //_printf_("Allocation time  P(" << my_rank << "): " << alloc_profiler.DeltaTime(StartInit, FinishInit) << "\n");
     155                #endif
     156                std::stringstream out_s;
     157                IssmDouble::getGlobalTape().printStatistics(out_s);
     158                _printf0_("CoDiPack Profiling::Tape Statistics :\n" << out_s.str());
     159                #endif
    209160        } /*}}}*/
    210161
    211         /*diverse: */
    212         int  dummy;
    213         int  num_independents=0;
     162        #elif defined(_HAVE_CODIPACK_)
     163        auto& tape_codi = IssmDouble::getGlobalTape();
     164        tape_codi.setPassive();
     165        if(VerboseAutodiff()){
     166                int my_rank=IssmComm::GetRank();
     167                if(my_rank == 0) {
     168                        // FIXME codi "just because" for now
     169                        tape_codi.printStatistics(std::cout);
     170                        codi_global.print(std::cout);
     171                }
     172        }
     173        #else
     174        _error_("not implemented");
     175        #endif
     176}/*}}}*/
     177void simul_ad(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs){/*{{{*/
     178
     179        /*Get rank*/
     180        int my_rank=IssmComm::GetRank();
     181
     182        /*Recover Arguments*/
     183        m1qn3_struct *input_struct = (m1qn3_struct*)dzs;
     184
     185        FemModel* femmodel = input_struct->femmodel;
     186        int num_responses,num_controls,solution_type;
     187        femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
     188
     189        /*In transient, we need to make sure we do not modify femmodel at each iteration, make a copy*/
     190        if(solution_type == TransientSolutionEnum) femmodel = input_struct->femmodel->copy();
     191
     192        IssmPDouble*  Jlist        = input_struct->Jlist;
     193        int           JlistM       = input_struct->M;
     194        int           JlistN       = input_struct->N;
     195        int*          Jlisti       = input_struct->i;
     196        int           intn         = (int)*n;
     197
     198        /*Recover some parameters*/
     199        IssmDouble *scaling_factors = NULL;
     200        int        *N               = NULL;
     201        int        *control_enum    = NULL;
     202        femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
     203        femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
     204        femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
     205        femmodel->parameters->FindParam(&N,NULL,ControlInputSizeNEnum);
     206        femmodel->parameters->FindParam(&control_enum,NULL,InversionControlParametersEnum);
     207        int numberofvertices=femmodel->vertices->NumberOfVertices();
     208
     209        /*Constrain input vector and update controls*/
     210        double  *XL = NULL;
     211        double  *XU = NULL;
     212        GetPassiveVectorFromControlInputsx(&XL,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
     213        GetPassiveVectorFromControlInputsx(&XU,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
     214
     215        int N_add = 0;
     216        for (int c=0;c<num_controls;c++){
     217                for(int i=0;i<numberofvertices*N[c];i++){
     218                        int index = N_add*numberofvertices+i;
     219                        X[index] = X[index]*reCast<double>(scaling_factors[c]);
     220                        if(X[index]>XU[index]) X[index]=XU[index];
     221                        if(X[index]<XL[index]) X[index]=XL[index];
     222                }
     223                N_add+=N[c];
     224        }
     225
     226        /*Start Tracing*/
     227        simul_starttrace(femmodel);
     228        /*Set X as our new control input and as INDEPENDENT*/
     229#ifdef _HAVE_AD_
     230        IssmDouble* aX=xNew<IssmDouble>(intn,"t");
     231#else
     232        IssmDouble* aX=xNew<IssmDouble>(intn);
     233#endif
     234
     235        #if defined(_HAVE_ADOLC_)
     236        if(my_rank==0){
     237                for(int i=0;i<intn;i++){
     238                        aX[i]<<=X[i];
     239                }
     240        }
     241        #elif defined(_HAVE_CODIPACK_)
     242        auto& tape_codi = IssmDouble::getGlobalTape();
     243        codi_global.input_indices.clear();
     244        if(my_rank==0){
     245                for (int i=0;i<intn;i++) {
     246                        aX[i]=X[i];
     247                        tape_codi.registerInput(aX[i]);
     248                        codi_global.input_indices.push_back(aX[i].getGradientData());
     249                }
     250        }
     251        #else
     252        _error_("not suppoted");
     253        #endif
     254
     255        ISSM_MPI_Bcast(aX,intn,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
     256        SetControlInputsFromVectorx(femmodel,aX);
     257        xDelete<IssmDouble>(aX);
     258
     259        /*Compute solution (forward)*/
     260        void (*solutioncore)(FemModel*)=NULL;
     261        CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
     262        solutioncore(femmodel);
     263
     264        /*Reset the time to zero for next optimization*/
     265        if(solution_type==TransientSolutionEnum){
     266                IssmDouble restart_time;
     267                femmodel->parameters->FindParam(&restart_time,TimesteppingStartTimeEnum);
     268                femmodel->parameters->SetParam(restart_time,TimeEnum);
     269
     270        }
     271
     272        /*Get Dependents*/
     273        IssmDouble  output_value;
     274        int         num_dependents;
     275        IssmPDouble *dependents;
     276        DataSet*    dependent_objects=NULL;
     277        IssmDouble      J=0.;
     278        femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
     279        femmodel->parameters->FindParam(&dependent_objects,AutodiffDependentObjectsEnum);
     280
     281        /*Go through our dependent variables, and compute the response:*/
     282        dependents=xNew<IssmPDouble>(num_dependents);
     283        #if defined(_HAVE_CODIPACK_)
     284        codi_global.output_indices.clear();
     285        #endif
     286        for(int i=0;i<dependent_objects->Size();i++){
     287                DependentObject* dep=(DependentObject*)dependent_objects->GetObjectByOffset(i);
     288                if(solution_type==TransientSolutionEnum) output_value = dep->GetValue();
     289                if(solution_type!=TransientSolutionEnum) dep->Responsex(&output_value,femmodel);
     290                if(my_rank==0) {
     291
     292                        #if defined(_HAVE_CODIPACK_)
     293                        tape_codi.registerOutput(output_value);
     294                        dependents[i] = output_value.getValue();
     295                        codi_global.output_indices.push_back(output_value.getGradientData());
     296
     297                        #elif defined(_HAVE_ADOLC_)
     298                        output_value>>=dependents[i];
     299
     300                        #else
     301                        _error_("not suppoted");
     302                        #endif
     303                        J+=output_value;
     304                }
     305        }
     306
     307        /*Turning off trace tape*/
     308        simul_stoptrace();
     309        //time_t now = time(NULL);
     310        //if(my_rank==0) _printf_("\nTIME: "<<now<<"\n");
    214311
    215312        /*intermediary: */
     313        int          num_independents=intn;
    216314        IssmPDouble *aWeightVector=NULL;
    217315        IssmPDouble *weightVectorTimesJac=NULL;
    218 
    219         /*output: */
    220         IssmPDouble *totalgradient=NULL;
    221 
    222         /*retrieve parameters: */
    223         num_independents = intn;
     316        IssmPDouble *totalgradient=xNewZeroInit<IssmPDouble>(num_independents);
    224317
    225318        /*if no dependents, no point in running a driver: */
     
    229322        int num_dependents_old   = num_dependents;
    230323        int num_independents_old = num_independents;
     324
     325        #if defined(_HAVE_ADOLC_)
     326        /*Get gradient for ADOLC {{{*/
    231327        if(my_rank!=0){
    232328                num_dependents   = 0;
     
    243339        /* Ok, now we are going to call the fos_reverse in a loop on the index, from 0 to num_dependents, so
    244340         * as to generate num_dependents gradients: */
    245         totalgradient=xNewZeroInit<IssmPDouble>(num_independents_old);
    246 
    247341        for(int aDepIndex=0;aDepIndex<num_dependents_old;aDepIndex++){
    248342
     
    277371                xDelete(aWeightVector);
    278372        }
     373        /*}}}*/
     374        #elif defined(_HAVE_CODIPACK_)
     375        /*Get gradient for CoDiPack{{{*/
     376        if(VerboseAutodiff())_printf0_("   CoDiPack fos_reverse\n");
     377
     378        /* call the fos_reverse in a loop on the index, from 0 to num_dependents, so
     379         * as to generate num_dependents gradients: */
     380        for(int aDepIndex=0;aDepIndex<num_dependents_old;aDepIndex++){
     381
     382                /*initialize direction index in the weights vector: */
     383                aWeightVector=xNewZeroInit<IssmPDouble>(num_dependents);
     384                if(my_rank==0){
     385                        if(aDepIndex<0 || aDepIndex>=num_dependents || codi_global.output_indices.size() <= aDepIndex){
     386                                _error_("index value for AutodiffFosReverseIndexEnum should be in [0,num_dependents-1]");
     387                        }
     388                        tape_codi.setGradient(codi_global.output_indices[aDepIndex],1.0);
     389                }
     390                tape_codi.evaluate();
     391
     392                /*Get gradient for this dependent */
     393                weightVectorTimesJac=xNew<IssmPDouble>(num_independents);
     394                auto in_size = codi_global.input_indices.size();
     395                for(size_t i = 0; i < in_size; ++i) {
     396                        _assert_(i<num_independents);
     397                        weightVectorTimesJac[i] = tape_codi.getGradient(codi_global.input_indices[i]);
     398                }
     399                if(my_rank==0) for(int i=0;i<num_independents;i++) {
     400                        totalgradient[i]+=weightVectorTimesJac[i];
     401                }
     402                /*free resources :*/
     403                xDelete(weightVectorTimesJac);
     404                xDelete(aWeightVector);
     405        }
     406        /*}}}*/
     407        #else
     408        _error_("not suppoted");
     409        #endif
    279410
    280411        /*Broadcast gradient to other ranks*/
     
    293424        Jlist[(*Jlisti)*JlistN+num_responses] = reCast<IssmPDouble>(J);
    294425
    295 /*
    296         IssmDouble* test = xNew<IssmDouble>(intn);
    297         femmodel->parameters->FindParam(&test,NULL,InversionXBestEnum);
    298         for(int i=0;i<10;i++)_printf_("X "<<test[i]<<"\n");
    299         xDelete<IssmDouble>(intn);
    300 */
    301426        if(*indic==0){
    302427                /*dry run, no gradient required*/
     
    341466        xDelete<double>(XU);
    342467        xDelete<double>(XL);
     468        xDelete<int>(control_enum);
     469        xDelete<int>(N);
    343470        xDelete<IssmDouble>(scaling_factors);
    344471        xDelete<IssmPDouble>(totalgradient);
     
    394521
    395522        /*Get initial guess*/
    396         Vector<double> *Xpetsc = NULL;
    397 
    398         GetPassiveVectorFromControlInputsx(&Xpetsc,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
    399         X = Xpetsc->ToMPISerial();
    400         Xpetsc->GetSize(&intn);
    401         delete Xpetsc;
     523        GetPassiveVectorFromControlInputsx(&X,&intn,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
    402524        //_assert_(intn==numberofvertices*num_controls);
    403525
     
    458580        double  *XL = NULL;
    459581        double  *XU = NULL;
    460         GetPassiveVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
    461         GetPassiveVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
     582        GetPassiveVectorFromControlInputsx(&XL,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
     583        GetPassiveVectorFromControlInputsx(&XU,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
    462584
    463585        N_add = 0;
     
    479601                aX[i] = reCast<IssmDouble>(X[i]);
    480602                aG[i] = reCast<IssmDouble>(G[i]);
    481                 }
     603        }
    482604
    483605        ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,aG);
     
    538660
    539661#else
    540 void controladm1qn3_core(FemModel* femmodel){_error_("M1QN3 or ADOLC not installed");}
     662void controladm1qn3_core(FemModel* femmodel){_error_("M1QN3 or ADOLC/CoDiPack not installed");}
    541663#endif //_HAVE_M1QN3_
  • issm/trunk/src/c/cores/controlm1qn3_core.cpp

    r23189 r23394  
    1111#include "../solutionsequences/solutionsequences.h"
    1212
    13 #if defined (_HAVE_M1QN3_) && !defined(_HAVE_ADOLC_)
    14 /*m1qn3 prototypes*/
     13#if defined (_HAVE_M1QN3_)
     14/*m1qn3 prototypes {{{*/
    1515extern "C" void *ctonbe_; // DIS mode : Conversion
    1616extern "C" void *ctcabe_; // DIS mode : Conversion
     
    2828/*Use struct to provide arguments*/
    2929typedef struct{
    30         FemModel  * femmodel;
    31         IssmDouble* Jlist;
     30        FemModel   * femmodel;
     31        IssmPDouble* Jlist;
    3232        int         M;
    3333        int         N;
    3434        int*        i;
    3535} m1qn3_struct;
    36 
    37 void controlm1qn3_core(FemModel* femmodel){
     36/*}}}*/
     37
     38void controlm1qn3_core(FemModel* femmodel){/*{{{*/
    3839
    3940        /*Intermediaries*/
    40         long         omode;
    41         double       f,dxmin,gttol;
    42         int          maxsteps,maxiter;
    43         int          intn,numberofvertices,num_controls,num_cost_functions,solution_type;
    44         IssmDouble *scaling_factors = NULL;
    45         IssmDouble *X  = NULL;
    46         IssmDouble *G  = NULL;
     41        long    omode;
     42        double  f,dxmin,gttol;
     43        int     maxsteps,maxiter;
     44        int     intn,numberofvertices,num_controls,num_cost_functions,solution_type;
     45        double *scaling_factors = NULL;
     46        double *X  = NULL;
     47        double *G  = NULL;
    4748
    4849        /*Recover some parameters*/
     
    5253        femmodel->parameters->FindParam(&maxsteps,InversionMaxstepsEnum);
    5354        femmodel->parameters->FindParam(&maxiter,InversionMaxiterEnum);
    54         femmodel->parameters->FindParam(&dxmin,InversionDxminEnum);
    55         femmodel->parameters->FindParam(&gttol,InversionGttolEnum);
    56         femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
     55        femmodel->parameters->FindParamAndMakePassive(&dxmin,InversionDxminEnum);
     56        femmodel->parameters->FindParamAndMakePassive(&gttol,InversionGttolEnum);
     57        femmodel->parameters->FindParamAndMakePassive(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
    5758        femmodel->parameters->SetParam(false,SaveResultsEnum);
    5859        numberofvertices=femmodel->vertices->NumberOfVertices();
     
    7778
    7879        /*Get initial guess*/
    79         Vector<IssmDouble> *Xpetsc = NULL;
    80         GetVectorFromControlInputsx(&Xpetsc,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
    81         X = Xpetsc->ToMPISerial();
    82         Xpetsc->GetSize(&intn);
    83         delete Xpetsc;
     80        GetPassiveVectorFromControlInputsx(&X,&intn,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
    8481        _assert_(intn==numberofvertices*num_controls);
    8582
     
    111108        mystruct.M        = maxiter;
    112109        mystruct.N        = num_cost_functions+1;
    113         mystruct.Jlist    = xNewZeroInit<IssmDouble>(mystruct.M*mystruct.N);
     110        mystruct.Jlist    = xNewZeroInit<IssmPDouble>(mystruct.M*mystruct.N);
    114111        mystruct.i        = xNewZeroInit<int>(1);
    115112
     
    127124                                &reverse,&indic,izs,rzs,(void*)&mystruct);
    128125
     126        /*Print exit flag*/
    129127        switch(int(omode)){
    130128                case 0:  _printf0_("   Stop requested (indic = 0)\n"); break;
     
    140138
    141139        /*Constrain solution vector*/
    142         IssmDouble  *XL = NULL;
    143         IssmDouble  *XU = NULL;
    144         GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
    145         GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
     140        double  *XL = NULL;
     141        double  *XU = NULL;
     142        GetPassiveVectorFromControlInputsx(&XL,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
     143        GetPassiveVectorFromControlInputsx(&XU,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
    146144        for(int c=0;c<num_controls;c++){
    147145                for(int i=0;i<numberofvertices;i++){
     
    152150                }
    153151        }
     152
     153        /*Set X as our new control (need to recast)*/
     154        #ifdef _HAVE_AD_
     155        IssmDouble* aX=xNew<IssmDouble>(intn);
     156        IssmDouble* aG=xNew<IssmDouble>(intn);
     157        for(int i=0;i<intn;i++) {
     158                aX[i] = reCast<IssmDouble>(X[i]);
     159                aG[i] = reCast<IssmDouble>(G[i]);
     160        }
     161        ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,aG);
     162        SetControlInputsFromVectorx(femmodel,aX);
     163        xDelete(aX);
     164        xDelete(aG);
     165        #else
    154166        SetControlInputsFromVectorx(femmodel,X);
    155167        ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
     168        #endif
     169
    156170        femmodel->OutputControlsx(&femmodel->results);
    157171        femmodel->results->AddObject(new GenericExternalResult<double*>(femmodel->results->Size()+1,JEnum,mystruct.Jlist,(*mystruct.i),mystruct.N,0,0));
     
    173187        xDelete<double>(mystruct.Jlist);
    174188        xDelete<int>(mystruct.i);
    175 }
    176 
    177 /*Cost function definition*/
    178 void simul(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs){
     189}/*}}}*/
     190void simul(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs){/*{{{*/
    179191
    180192        /*Recover Arguments*/
    181193        m1qn3_struct *input_struct = (m1qn3_struct*)dzs;
    182194        FemModel     *femmodel     = input_struct->femmodel;
    183         IssmDouble   *Jlist        = input_struct->Jlist;
     195        IssmPDouble  *Jlist        = input_struct->Jlist;
    184196        int           JlistM       = input_struct->M;
    185197        int           JlistN       = input_struct->N;
     
    188200        /*Recover some parameters*/
    189201        int num_responses,num_controls,numberofvertices,solution_type;
    190         IssmDouble* scaling_factors = NULL;
     202        double* scaling_factors = NULL;
    191203        femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
    192204        femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
    193         femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
     205        femmodel->parameters->FindParamAndMakePassive(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
    194206        femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
    195207        numberofvertices=femmodel->vertices->NumberOfVertices();
    196208
    197209        /*Constrain input vector and update controls*/
    198         IssmDouble *XL = NULL;
    199         IssmDouble *XU = NULL;
    200         GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
    201         GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
     210        double *XL = NULL;
     211        double *XU = NULL;
     212        GetPassiveVectorFromControlInputsx(&XL,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
     213        GetPassiveVectorFromControlInputsx(&XU,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
    202214        for(int c=0;c<num_controls;c++){
    203215                for(int i=0;i<numberofvertices;i++){
     
    208220                }
    209221        }
     222        #ifdef _HAVE_AD_
     223        IssmDouble* aX=xNew<IssmDouble>(*n);
     224        for(int i=0;i<*n;i++) aX[i] = reCast<IssmDouble>(X[i]);
     225        SetControlInputsFromVectorx(femmodel,aX);
     226        xDelete(aX);
     227        #else
    210228        SetControlInputsFromVectorx(femmodel,X);
     229        #endif
    211230
    212231        /*Compute solution and adjoint*/
     
    222241        /*Compute objective function*/
    223242        IssmDouble* Jtemp = NULL;
    224         femmodel->CostFunctionx(pf,&Jtemp,NULL);
     243        IssmDouble  J;
     244        femmodel->CostFunctionx(&J,&Jtemp,NULL);
     245        *pf = reCast<double>(J);
    225246        _printf0_("f(x) = "<<setw(12)<<setprecision(7)<<*pf<<"  |  ");
    226247
    227248        /*Record cost function values and delete Jtemp*/
    228         for(int i=0;i<num_responses;i++) Jlist[(*Jlisti)*JlistN+i] = Jtemp[i];
     249        for(int i=0;i<num_responses;i++) Jlist[(*Jlisti)*JlistN+i] = reCast<double>(Jtemp[i]);
    229250        Jlist[(*Jlisti)*JlistN+num_responses] = *pf;
    230251        xDelete<IssmDouble>(Jtemp);
     
    239260
    240261                *Jlisti = (*Jlisti) +1;
    241                 xDelete<IssmDouble>(XU);
    242                 xDelete<IssmDouble>(XL);
     262                xDelete<double>(XU);
     263                xDelete<double>(XL);
    243264                return;
    244265        }
     
    251272        IssmDouble* G2 = NULL;
    252273        Gradjx(&G2,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
    253         for(long i=0;i<*n;i++) G[i] = -G2[i];
     274        for(long i=0;i<*n;i++) G[i] = -reCast<double>(G2[i]);
    254275        xDelete<IssmDouble>(G2);
    255276
     
    275296        /*Clean-up and return*/
    276297        *Jlisti = (*Jlisti) +1;
    277         xDelete<IssmDouble>(XU);
    278         xDelete<IssmDouble>(XL);
    279         xDelete<IssmDouble>(scaling_factors);
    280 }
     298        xDelete<double>(XU);
     299        xDelete<double>(XL);
     300        xDelete<double>(scaling_factors);
     301}/*}}}*/
    281302
    282303#else
    283 void controlm1qn3_core(FemModel* femmodel){
    284         _error_("M1QN3 not installed");
    285 }
     304void controlm1qn3_core(FemModel* femmodel){_error_("M1QN3 not installed");}
    286305#endif //_HAVE_M1QN3_
  • issm/trunk/src/c/cores/controlvalidation_core.cpp

    r22758 r23394  
    99#include "../modules/modules.h"
    1010
     11#ifdef _HAVE_CODIPACK_
     12extern CoDi_global codi_global;
     13#include <sstream> // for output of the CoDiPack tape
     14#endif
     15
     16#ifdef _HAVE_AD_
     17void simul_starttrace2(FemModel* femmodel){/*{{{*/
     18
     19        #if defined(_HAVE_ADOLC_)
     20        /*Retrive ADOLC parameters*/
     21        IssmDouble gcTriggerRatio;
     22        IssmDouble gcTriggerMaxSize;
     23        IssmDouble obufsize;
     24        IssmDouble lbufsize;
     25        IssmDouble cbufsize;
     26        IssmDouble tbufsize;
     27        femmodel->parameters->FindParam(&gcTriggerRatio,AutodiffGcTriggerRatioEnum);
     28        femmodel->parameters->FindParam(&gcTriggerMaxSize,AutodiffGcTriggerMaxSizeEnum);
     29        femmodel->parameters->FindParam(&obufsize,AutodiffObufsizeEnum);
     30        femmodel->parameters->FindParam(&lbufsize,AutodiffLbufsizeEnum);
     31        femmodel->parameters->FindParam(&cbufsize,AutodiffCbufsizeEnum);
     32        femmodel->parameters->FindParam(&tbufsize,AutodiffTbufsizeEnum);
     33
     34        /*Set garbage collection parameters: */
     35        setStoreManagerControl(reCast<IssmPDouble>(gcTriggerRatio),reCast<size_t>(gcTriggerMaxSize));
     36
     37        /*Start trace: */
     38        int skipFileDeletion=1;
     39        int keepTaylors=1;
     40        int my_rank=IssmComm::GetRank();
     41        trace_on(my_rank,keepTaylors,reCast<size_t>(obufsize),reCast<size_t>(lbufsize),reCast<size_t>(cbufsize),reCast<size_t>(tbufsize),skipFileDeletion);
     42
     43        #elif defined(_HAVE_CODIPACK_)
     44
     45                //fprintf(stderr, "*** Codipack IoModel::StartTrace\n");
     46                /*
     47                 * FIXME codi
     48                 * - ADOL-C variant uses fine grained tracing with various arguments
     49                 * - ADOL-C variant sets a garbage collection parameter for its tape
     50                 * -> These parameters are not read for the CoDiPack ISSM version!
     51                 */
     52                auto& tape_codi = IssmDouble::getGlobalTape();
     53                tape_codi.setActive();
     54                #if _AD_TAPE_ALLOC_
     55                //alloc_profiler.Tag(StartInit, true);
     56                IssmDouble x_t(1.0), y_t(1.0);
     57                tape_codi.registerInput(y_t);
     58                int codi_allocn = 0;
     59                femmodel->parameters->FindParam(&codi_allocn,AutodiffTapeAllocEnum);
     60                for(int i = 0;i < codi_allocn;++i) {
     61                        x_t = y_t * y_t;
     62                }
     63                /*
     64                std::stringstream out_s;
     65                IssmDouble::getGlobalTape().printStatistics(out_s);
     66                _printf0_("StartTrace::Tape Statistics     : TapeAlloc count=[" << codi_allocn << "]\n" << out_s.str());
     67                */
     68                tape_codi.reset();
     69                //alloc_profiler.Tag(FinishInit, true);
     70                #else
     71                tape_codi.reset();
     72                #endif
     73
     74        #else
     75        _error_("not implemented");
     76        #endif
     77}/*}}}*/
     78void simul_stoptrace2(){/*{{{*/
     79
     80        #if defined(_HAVE_ADOLC_)
     81        trace_off();
     82        if(VerboseAutodiff()){ /*{{{*/
     83
     84                #ifdef _HAVE_ADOLC_
     85                int my_rank=IssmComm::GetRank();
     86                size_t  tape_stats[15];
     87                tapestats(my_rank,tape_stats); //reading of tape statistics
     88                int commSize=IssmComm::GetSize();
     89                int *sstats=new int[7];
     90                sstats[0]=tape_stats[NUM_OPERATIONS];
     91                sstats[1]=tape_stats[OP_FILE_ACCESS];
     92                sstats[2]=tape_stats[NUM_LOCATIONS];
     93                sstats[3]=tape_stats[LOC_FILE_ACCESS];
     94                sstats[4]=tape_stats[NUM_VALUES];
     95                sstats[5]=tape_stats[VAL_FILE_ACCESS];
     96                sstats[6]=tape_stats[TAY_STACK_SIZE];
     97                int *rstats=NULL;
     98                if (my_rank==0) rstats=new int[commSize*7];
     99                ISSM_MPI_Gather(sstats,7,ISSM_MPI_INT,rstats,7,ISSM_MPI_INT,0,IssmComm::GetComm());
     100                if (my_rank==0) {
     101                        int offset=50;
     102                        int rOffset=(commSize/10)+1;
     103                        _printf_("   ADOLC statistics: \n");
     104                        _printf_("     "<<setw(offset)<<left<<"#independents: " <<setw(12)<<right<<tape_stats[NUM_INDEPENDENTS] << "\n");
     105                        _printf_("     "<<setw(offset)<<left<<"#dependents: " <<setw(12)<<right<<tape_stats[NUM_DEPENDENTS] << "\n");
     106                        _printf_("     "<<setw(offset)<<left<<"max #live active variables: " <<setw(12)<<right<<tape_stats[NUM_MAX_LIVES] << "\n");
     107                        _printf_("     operations: entry size "<< sizeof(unsigned char) << " Bytes \n");
     108                        _printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffObufsizeEnum) " <<setw(12)<<right<<tape_stats[OP_BUFFER_SIZE] << "\n");
     109                        for (int r=0;r<commSize;++r)
     110                         _printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+0] << (rstats[r*7+1]?" ->file":"") << "\n");
     111                        _printf_("     locations: entry size " << sizeof(locint) << " Bytes\n");
     112                        _printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffLbufsizeEnum) " <<setw(12)<<right<<tape_stats[LOC_BUFFER_SIZE] << "\n");
     113                        for (int r=0;r<commSize;++r)
     114                         _printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+2] << (rstats[r*7+3]?" ->file":"") << "\n");
     115                        _printf_("     constant values: entry size " << sizeof(double) << " Bytes\n");
     116                        _printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffCbufsizeEnum) " <<setw(12)<<right<<tape_stats[VAL_BUFFER_SIZE] << "\n");
     117                        for (int r=0;r<commSize;++r)
     118                         _printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+4] << (rstats[r*7+5]?" ->file":"") << "\n");
     119                        _printf_("     Taylor stack: entry size " << sizeof(revreal) << " Bytes\n");
     120                        _printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffTbufsizeEnum) " <<setw(12)<<right<<tape_stats[TAY_BUFFER_SIZE] << "\n");
     121                        for (int r=0;r<commSize;++r)
     122                         _printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+6] << (rstats[r*7+6]>tape_stats[TAY_BUFFER_SIZE]?" ->file":"") << "\n");
     123                        delete []rstats;
     124                }
     125                delete [] sstats;
     126                #endif
     127
     128                #ifdef _HAVE_CODIPACK_
     129                #ifdef _AD_TAPE_ALLOC_
     130                //_printf_("Allocation time  P(" << my_rank << "): " << alloc_profiler.DeltaTime(StartInit, FinishInit) << "\n");
     131                #endif
     132                std::stringstream out_s;
     133                IssmDouble::getGlobalTape().printStatistics(out_s);
     134                _printf0_("CoDiPack Profiling::Tape Statistics :\n" << out_s.str());
     135                #endif
     136        } /*}}}*/
     137
     138        #elif defined(_HAVE_CODIPACK_)
     139        auto& tape_codi = IssmDouble::getGlobalTape();
     140        tape_codi.setPassive();
     141        if(VerboseAutodiff()){
     142                int my_rank=IssmComm::GetRank();
     143                if(my_rank == 0) {
     144                        // FIXME codi "just because" for now
     145                        tape_codi.printStatistics(std::cout);
     146                        codi_global.print(std::cout);
     147                }
     148        }
     149        #else
     150        _error_("not implemented");
     151        #endif
     152}/*}}}*/
     153#endif
     154
    11155void controlvalidation_core(FemModel* femmodel){
    12156
    13157        int         solution_type,n;
    14158        int         num_responses;
    15         IssmDouble  j0,j,yts;
     159        IssmDouble  j0,j;
    16160        IssmDouble  Ialpha,exponent,alpha;
    17161        IssmDouble* scaling_factors = NULL;
    18162        IssmDouble* jlist = NULL;
    19         IssmDouble *G = NULL;
    20         IssmDouble *X = NULL;
    21         IssmDouble *X0= NULL;
    22 
    23         /*Solution and Adjoint core pointer*/
    24         void (*solutioncore)(FemModel*) = NULL;
    25         void (*adjointcore)(FemModel*)  = NULL;
     163        int my_rank=IssmComm::GetRank();
    26164
    27165        /*Recover parameters used throughout the solution*/
     
    29167        femmodel->parameters->SetParam(false,SaveResultsEnum);
    30168        femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
    31         femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
    32169        femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
    33170
    34171        /*Get initial guess*/
    35         Vector<IssmDouble> *Xpetsc = NULL;
    36         GetVectorFromControlInputsx(&Xpetsc,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
    37         Xpetsc->GetSize(&n);
    38         X0 = Xpetsc->ToMPISerial();
    39         delete Xpetsc;
    40 
    41         /*Allocate current vector*/
    42         X = xNew<IssmDouble>(n);
     172        IssmPDouble* X0 = NULL;
     173        GetPassiveVectorFromControlInputsx(&X0,&n,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"value");
     174
     175        /*Allocate vectors*/
     176        IssmDouble*  X = xNew<IssmDouble>(n);
     177        IssmPDouble* G = xNew<IssmPDouble>(n);
    43178
    44179        /*out of solution_type, figure out solution core and adjoint function pointer*/
     180        void (*solutioncore)(FemModel*)=NULL;
    45181        CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
     182
     183        #if defined(_HAVE_ADOLC_)
     184        /*{{{*/
     185        IssmDouble* aX=xNew<IssmDouble>(n);
     186        if(my_rank==0){
     187                for(int i=0;i<n;i++){
     188                        aX[i]<<=X0[i];
     189                }
     190        }
     191        _error_("not implemented yet...");
     192        /*}}}*/
     193        #elif defined(_HAVE_CODIPACK_)
     194        simul_starttrace2(femmodel);
     195        IssmDouble* aX=xNew<IssmDouble>(n);
     196        auto& tape_codi = IssmDouble::getGlobalTape();
     197        codi_global.input_indices.clear();
     198        if(my_rank==0){
     199                for (int i=0;i<n;i++) {
     200                        aX[i]=X0[i];
     201                        tape_codi.registerInput(aX[i]);
     202                        codi_global.input_indices.push_back(aX[i].getGradientData());
     203                }
     204        }
     205        SetControlInputsFromVectorx(femmodel,aX);
     206        xDelete(aX);
     207
     208        if(VerboseControl()) _printf0_("   Compute Initial cost function\n");
     209        solutioncore(femmodel);
     210
     211        /*Get Dependents*/
     212        IssmDouble  output_value;
     213        int         num_dependents;
     214        IssmPDouble *dependents;
     215        DataSet*    dependent_objects=NULL;
     216        IssmDouble      J=0.;
     217        femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
     218        femmodel->parameters->FindParam(&dependent_objects,AutodiffDependentObjectsEnum);
     219
     220        /*Go through our dependent variables, and compute the response:*/
     221        dependents=xNew<IssmPDouble>(num_dependents);
     222        codi_global.output_indices.clear();
     223        for(int i=0;i<dependent_objects->Size();i++){
     224                DependentObject* dep=(DependentObject*)dependent_objects->GetObjectByOffset(i);
     225                if(solution_type==TransientSolutionEnum){
     226                        output_value = dep->GetValue();
     227                }
     228                else{
     229                        dep->Responsex(&output_value,femmodel);
     230                }
     231                _printf0_("=== output ="<<output_value<<" \n");
     232                if(my_rank==0) {
     233                        tape_codi.registerOutput(output_value);
     234                        dependents[i] = output_value.getValue();
     235                        codi_global.output_indices.push_back(output_value.getGradientData());
     236                        J+=output_value;
     237                }
     238        }
     239        j0 = J;
     240        _printf0_("Initial cost function J(x) = "<<setw(12)<<setprecision(7)<<j0<<"\n");
     241        _assert_(j0>0.);
     242        simul_stoptrace2();
     243        /*initialize direction index in the weights vector: */
     244        if(my_rank==0){
     245                tape_codi.setGradient(codi_global.output_indices[0],1.0);
     246        }
     247        tape_codi.evaluate();
     248
     249        /*Get gradient for this dependent */
     250        auto in_size = codi_global.input_indices.size();
     251        for(size_t i = 0; i < in_size; ++i) {
     252                G[i] = tape_codi.getGradient(codi_global.input_indices[i]);
     253        }
     254        #else
     255        /*{{{*/
     256        void (*adjointcore)(FemModel*)  = NULL;
    46257        AdjointCorePointerFromSolutionEnum(&adjointcore,solution_type);
    47258
     
    59270        Gradjx(&G,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
    60271        for(int i=0;i<n;i++) G[i] = -G[i];
     272        /*}}}*/
     273        #endif
    61274
    62275        /*Allocate output*/
     
    76289                SetControlInputsFromVectorx(femmodel,X);
    77290                solutioncore(femmodel);
     291
     292                #if defined(_HAVE_CODIPACK_)
     293                j=0.;
     294                for(int i=0;i<dependent_objects->Size();i++){
     295                        DependentObject* dep=(DependentObject*)dependent_objects->GetObjectByOffset(i);
     296                        if(solution_type==TransientSolutionEnum){
     297                                output_value = dep->GetValue();
     298                        }
     299                        else{
     300                                dep->Responsex(&output_value,femmodel);
     301                        }
     302                        j+=output_value;
     303                }
     304                #else
    78305                femmodel->CostFunctionx(&j,NULL,NULL);
     306                #endif
    79307
    80308                IssmDouble Den = 0.;
    81309                for(int i=0;i<n;i++) Den += alpha* G[i] * scaling_factors[0];
    82310                Ialpha = fabs((j - j0)/Den - 1.);
     311                _assert_(fabs(Den)>0.);
    83312
    84313                _printf0_(" " << setw(11) << setprecision (5)<<alpha<<" " << setw(11) << setprecision (5)<<Ialpha<<"\n");
     
    88317
    89318        /*output*/
    90         #ifdef _HAVE_ADOLC_
     319        #ifdef _HAVE_AD_
    91320        IssmPDouble* J_passive=xNew<IssmPDouble>(2*num);
    92321        for(int i=0;i<2*num;i++) J_passive[i]=reCast<IssmPDouble>(output[i]);
    93322        femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,num,2,0,0));
    94323        xDelete<IssmPDouble>(J_passive);
     324        IssmDouble* aG=xNew<IssmDouble>(n);
     325        for(int i=0;i<n;i++) aG[i] = G[i];
     326        ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,aG);
     327        xDelete<IssmDouble>(aG);
    95328        #else
    96329        femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,output,num,2,0,0));
     330        ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
    97331        #endif
    98         ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
    99332        femmodel->OutputControlsx(&femmodel->results);
    100333
    101334        /*Clean up and return*/
    102335        xDelete<IssmDouble>(output);
    103         xDelete<IssmDouble>(G);
     336        xDelete<IssmPDouble>(G);
    104337        xDelete<IssmDouble>(X);
    105         xDelete<IssmDouble>(X0);
     338        xDelete<double>(X0);
    106339        xDelete<IssmDouble>(scaling_factors);
    107340}
  • issm/trunk/src/c/cores/damage_core.cpp

    r23189 r23394  
    1111
    1212void damage_core(FemModel* femmodel){
    13 
     13       
     14        /*Start profiler*/
     15        femmodel->profiler->Start(DAMAGECORE);
     16       
    1417        /*intermediary*/
    1518        bool   save_results;
     
    4851                xDelete<char*>(requested_outputs);
    4952        }
     53       
     54        /*End profiler*/
     55        femmodel->profiler->Stop(DAMAGECORE);
    5056}
  • issm/trunk/src/c/cores/esa_core.cpp

    r23189 r23394  
    1111
    1212void esa_core(FemModel* femmodel){ /*{{{*/
     13
     14        /*Start profiler*/
     15        femmodel->profiler->Start(ESACORE);
    1316
    1417        Vector<IssmDouble> *U_radial  = NULL;
     
    112115                if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
    113116        }
     117       
     118        /*End profiler*/
     119        femmodel->profiler->Stop(ESACORE);
    114120
    115121}
  • issm/trunk/src/c/cores/gia_core.cpp

    r23189 r23394  
    1010#include "../solutionsequences/solutionsequences.h"
    1111void gia_core(FemModel* femmodel){
     12
     13        /*Start profiler*/
     14        femmodel->profiler->Start(GIACORE);
    1215
    1316        Vector<IssmDouble> *wg    = NULL;
     
    5659        xDelete<IssmDouble>(x);
    5760        xDelete<IssmDouble>(y);
     61       
     62        /*End profiler*/
     63        femmodel->profiler->Stop(GIACORE);
    5864}
  • issm/trunk/src/c/cores/hydrology_core.cpp

    r23189 r23394  
    1111
    1212void hydrology_core(FemModel* femmodel){
     13
     14        /*Start profiler*/
     15        femmodel->profiler->Start(HYDROLOGYCORE);
    1316
    1417        /*intermediary*/
     
    4750                /*intermediary: */
    4851                bool       isefficientlayer;
    49                 bool       isthermal;
    5052                int        step,hydroslices;
    5153                IssmDouble time,init_time,hydrotime,yts;
     
    5961                femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
    6062
    61                 femmodel->parameters->FindParam(&isthermal,TransientIsthermalEnum);
    6263                /*first we exclude frozen nodes of the solved nodes*/
    6364                femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
     
    150151                xDelete<char*>(requested_outputs);
    151152        }
     153
     154        /*End profiler*/
     155        femmodel->profiler->Stop(HYDROLOGYCORE);
    152156}
  • issm/trunk/src/c/cores/masstransport_core.cpp

    r23189 r23394  
    1111
    1212void masstransport_core(FemModel* femmodel){
     13
     14        /*Start profiler*/
     15        femmodel->profiler->Start(MASSTRANSPORTCORE);
    1316
    1417        /*parameters: */
     
    8184        /*Free ressources:*/
    8285        if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
     86
     87        /*profiler*/
     88        femmodel->profiler->Stop(MASSTRANSPORTCORE);
    8389}
  • issm/trunk/src/c/cores/movingfront_core.cpp

    r22758 r23394  
    1111
    1212void movingfront_core(FemModel* femmodel){
     13       
     14        /*Start profiler*/
     15        femmodel->profiler->Start(MOVINGFRONTCORE);
    1316
    1417        /* intermediaries */
     
    98101                femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
    99102        }
     103       
     104        /*End profiler*/
     105        femmodel->profiler->Stop(MOVINGFRONTCORE);
    100106}
  • issm/trunk/src/c/cores/sealevelrise_core.cpp

    r23189 r23394  
    1313void sealevelrise_core(FemModel* femmodel){ /*{{{*/
    1414
     15        /*Start profiler*/
     16        femmodel->profiler->Start(SLRCORE);
     17
    1518        /*Parameters, variables:*/
    1619        bool save_results;
     
    5457        /*requested dependents: */
    5558        if(solution_type==SealevelriseSolutionEnum)femmodel->RequestedDependentsx();
     59       
     60        /*End profiler*/
     61        femmodel->profiler->Stop(SLRCORE);
    5662}
    5763/*}}}*/
  • issm/trunk/src/c/cores/smb_core.cpp

    r23189 r23394  
    1111
    1212void smb_core(FemModel* femmodel){
    13 
     13       
     14        /*Start profiler*/
     15        femmodel->profiler->Start(SMBCORE);
     16       
    1417        /*parameters: */
    1518        Analysis* analysis=NULL;
     
    4548        /*Free ressources:*/
    4649        if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
     50
     51        /*End profiler*/
     52        femmodel->profiler->Stop(SMBCORE);
    4753}
  • issm/trunk/src/c/cores/stressbalance_core.cpp

    r23189 r23394  
    1212
    1313void stressbalance_core(FemModel* femmodel){
     14
     15        /*Start profiler*/
     16        femmodel->profiler->Start(STRESSBALANCECORE);
    1417
    1518        /*parameters: */
     
    3740
    3841        if(VerboseSolution()) _printf0_("   computing new velocity\n");
    39 
    4042        /*Compute slopes if necessary */
    4143        if(isSIA || (isFS && domaintype==Domain2DverticalEnum)) surfaceslope_core(femmodel);
     
    7375        /*Compute vertical velocities*/
    7476        if (domaintype==Domain3DEnum && (isSIA || isSSA || isL1L2 || isHO)){
     77
     78                /*We need basal melt rates for vertical velocity*/
     79                bmb_core(femmodel);
     80
    7581                analysis = new StressbalanceVerticalAnalysis();
    7682                analysis->Core(femmodel);
     
    8793        /*Free ressources:*/   
    8894        if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
     95
     96        /*End profiler*/
     97        femmodel->profiler->Stop(STRESSBALANCECORE);
    8998}
  • issm/trunk/src/c/cores/thermal_core.cpp

    r20500 r23394  
    1212
    1313void thermal_core(FemModel* femmodel){
    14 
     14       
     15        /*Start profiler*/
     16        femmodel->profiler->Start(THERMALCORE);
     17       
    1518        /*intermediary*/
    1619        bool   save_results,isenthalpy;
     
    5255        /*Free ressources:*/   
    5356        if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
    54 
     57       
     58        /*End profiler*/
     59        femmodel->profiler->Stop(THERMALCORE);
    5560}
  • issm/trunk/src/c/cores/transient_core.cpp

    r23189 r23394  
    7070        if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,TransientRequestedOutputsEnum);
    7171
    72         #if defined(_HAVE_BAMG_) && !defined(_HAVE_ADOLC_)
     72        #if defined(_HAVE_BAMG_) && !defined(_HAVE_AD_)
    7373        if(amr_frequency){
    7474                femmodel->parameters->FindParam(&amr_restart,AmrRestartEnum);
     
    7878
    7979        if(isoceancoupling){ /*{{{*/
    80                 #ifndef _HAVE_ADOLC_
     80                #ifndef _HAVE_AD_
    8181                if(VerboseSolution()) _printf0_("   ocean coupling: initialization \n");
    8282                int my_rank;
     
    180180                for(int i=0;i<ngrids_ocean;i++) if(icemask_oceangrid[i]>0.) icebase_oceangrid[i]=+9999.;
    181181                xDelete<IssmDouble>(icemask_oceangrid);
    182                        
     182
    183183                if(my_rank==0){
    184184                        ISSM_MPI_Send(icebase_oceangrid,ngrids_ocean,ISSM_MPI_DOUBLE,0,10001008,tomitgcmcomm);
     
    247247                if(isoceancoupling){ /*{{{*/
    248248
    249                         #ifndef _HAVE_ADOLC_
     249                        #ifndef _HAVE_AD_
    250250                        if(VerboseSolution()) _printf0_("   ocean coupling: exchanging information\n");
    251251                        int my_rank;
     
    371371                                femmodel->parameters->FindParam(&smb_model,SmbEnum);
    372372                                if(isenthalpy){
    373                                         if(smb_model==SMBpddEnum)     ResetBoundaryConditions(femmodel,EnthalpyAnalysisEnum);
    374                                         if(smb_model==SMBd18opddEnum) ResetBoundaryConditions(femmodel,EnthalpyAnalysisEnum);
     373                                        if(smb_model==SMBpddEnum)                               ResetBoundaryConditions(femmodel,EnthalpyAnalysisEnum);
     374                                        if(smb_model==SMBd18opddEnum)                   ResetBoundaryConditions(femmodel,EnthalpyAnalysisEnum);
     375                                        if(smb_model==SMBpddSicopolisEnum)      ResetBoundaryConditions(femmodel,EnthalpyAnalysisEnum);
    375376                                }
    376377                                else{
    377                                         if(smb_model==SMBpddEnum)     ResetBoundaryConditions(femmodel,ThermalAnalysisEnum);
    378                                         if(smb_model==SMBd18opddEnum) ResetBoundaryConditions(femmodel,ThermalAnalysisEnum);
     378                                        if(smb_model==SMBpddEnum)                               ResetBoundaryConditions(femmodel,ThermalAnalysisEnum);
     379                                        if(smb_model==SMBd18opddEnum)                   ResetBoundaryConditions(femmodel,ThermalAnalysisEnum);
     380                                        if(smb_model==SMBpddSicopolisEnum)      ResetBoundaryConditions(femmodel,ThermalAnalysisEnum);
    379381                                }
    380382                        }
     
    382384                }
    383385
     386                /*shifting smb position to have runoff value*/
     387                if(issmb) smb_core(femmodel);
     388
    384389                if(ishydrology) hydrology_core(femmodel);
    385390
     
    391396
    392397                /* from here on, prepare geometry for next time step*/
    393 
    394                 if(issmb) smb_core(femmodel);
     398                //if(issmb) smb_core(femmodel);
    395399
    396400                if(ismasstransport){
     
    401405
    402406                if(isgroundingline){
     407
     408                        /*Start profiler*/
     409                        femmodel->profiler->Start(GROUNDINGLINECORE);
     410
    403411                        if(VerboseSolution()) _printf0_("   computing new grounding line position\n");
    404412                        GroundinglineMigrationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
     
    410418                        femmodel->parameters->SetParam(SurfaceEnum,InputToExtrudeEnum);
    411419                        extrudefrombase_core(femmodel);
     420
     421                        /*Stop profiler*/
     422                        femmodel->profiler->Stop(GROUNDINGLINECORE);
    412423
    413424                        if(save_results){
     
    453464                if(amr_frequency){
    454465
    455                         #if !defined(_HAVE_ADOLC_)
     466                        #if !defined(_HAVE_AD_)
    456467                        if(save_results) femmodel->WriteMeshInResults();
    457468                        if(step%amr_frequency==0 && time<finaltime){
     
    461472
    462473                        #else
    463                         _error_("AMR not suppored with ADOLC");
     474                        _error_("AMR not suppored with AD");
    464475                        #endif
    465476                }
  • issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.cpp

    r22758 r23394  
    99#include <proj_api.h>
    1010
    11 void CoordinateSystemTransformx(IssmDouble** px_dest,IssmDouble** py_dest,IssmDouble* x_src,IssmDouble* y_src,int size,const char* str_src,const char* str_dst){
     11void CoordinateSystemTransformx(double** px_dest,double** py_dest,double* x_src,double* y_src,int size,const char* str_src,const char* str_dst){
    1212
    1313#if !defined(_HAVE_PROJ4_)
     
    1717        /*Allocate output and initialize values as src*/
    1818        _assert_(size>0);
    19         IssmDouble* x_dest = xNew<IssmDouble>(size);
    20         IssmDouble* y_dest = xNew<IssmDouble>(size);
     19        double* x_dest = xNew<double>(size);
     20        double* y_dest = xNew<double>(size);
    2121        for(int i=0;i<size;i++){
    2222                x_dest[i] = x_src[i];
  • issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.h

    r18801 r23394  
    88
    99/* local prototypes: */
    10 void CoordinateSystemTransformx(IssmDouble** px_dest,IssmDouble** py_dest,IssmDouble* x_src,IssmDouble* y_src,int size,const char* str_src,const char* str_dst);
     10void CoordinateSystemTransformx(double** px_dest,double** py_dest,double* x_src,double* y_src,int size,const char* str_src,const char* str_dst);
    1111#endif 
  • issm/trunk/src/c/modules/FloatingiceMeltingRatePicox/FloatingiceMeltingRatePicox.cpp

    r23189 r23394  
    7878                IssmDouble val=sqrt(dmax_basin[i]/dist_max)*(maxbox-1);
    7979
    80                 #ifdef _HAVE_ADOLC_
     80                #ifdef _HAVE_AD_
     81                _error_("Check the implementation of floor below");
    8182                /*Do not use floor when AD is on*/
    8283                int k=0; while(k<val+.5){k++;}
  • issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp

    r23189 r23394  
    7878
    7979}/*}}}*/
    80 void GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){/*{{{*/
     80void GetVectorFromControlInputsx( IssmDouble** pvector,int *pN, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){/*{{{*/
    8181
    8282        /*intermediary: */
     83        int                 N;
    8384        Vector<IssmDouble>* vec_vector=NULL;
    8485
     86        /*Get PETSc vector*/
    8587        GetVectorFromControlInputsx( &vec_vector, elements,nodes, vertices, loads, materials, parameters,data);
     88
     89        /*Serialize*/
     90        vec_vector->GetSize(&N);
    8691        IssmDouble* vector=vec_vector->ToMPISerial();
    87 
    88         /*Free ressources:*/
    8992        delete vec_vector;
    9093
    9194        /*Assign output pointers:*/
    9295        *pvector=vector;
     96        if(pN) *pN=N;
    9397}/*}}}*/
    9498
    9599/*For autodiff, we sometimes need to cast our vectors to passive*/
    96 #ifdef _HAVE_ADOLC_
    97 void GetPassiveVectorFromControlInputsx(Vector<IssmPDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data){/*{{{*/
    98 
    99         /*Get active vector first*/
    100         Vector<IssmDouble>*   activevector=NULL;
    101         Vector<IssmPDouble>*  vector=NULL;
    102         int                   size;
    103 
    104         /*Retrieve some parameters*/
    105         GetVectorFromControlInputsx(&activevector, elements,nodes, vertices, loads, materials, parameters,data);
    106 
    107         /*Serialize vector*/
    108         activevector->GetSize(&size);
    109         IssmDouble* dactivevector=activevector->ToMPISerial();
    110 
    111         /*Cast to passive*/
    112         vector=new Vector<IssmPDouble>(size);
    113         for(int i=0;i<size;i++){
    114                 vector->SetValue(i,reCast<IssmPDouble>(dactivevector[i]),INS_VAL);
    115         }
    116         vector->Assemble();
    117 
    118         /*Assign output pointers:*/
    119         delete activevector;
    120         xDelete<IssmDouble>(dactivevector);
    121         *pvector=vector;
    122 
    123 }/*}}}*/
    124 void GetPassiveVectorFromControlInputsx(IssmPDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){/*{{{*/
     100#ifdef _HAVE_AD_
     101void GetPassiveVectorFromControlInputsx(IssmPDouble** pvector,int* pN, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){/*{{{*/
    125102
    126103        /*Get active vector first*/
     
    144121        xDelete<IssmDouble>(dactivevector);
    145122        *pvector=vector;
     123        if(pN) *pN=size;
    146124
    147125}/*}}}*/
    148126#else
    149 void GetPassiveVectorFromControlInputsx(Vector<IssmPDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data){/*{{{*/
     127void GetPassiveVectorFromControlInputsx(IssmPDouble** pvector,int* pN, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){/*{{{*/
    150128
    151         GetVectorFromControlInputsx(pvector, elements,nodes, vertices, loads, materials, parameters,data);
    152 
    153 }/*}}}*/
    154 void GetPassiveVectorFromControlInputsx(IssmPDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){/*{{{*/
    155 
    156         GetVectorFromControlInputsx(pvector, elements,nodes, vertices, loads, materials, parameters,data);
     129        GetVectorFromControlInputsx(pvector,pN,elements,nodes, vertices, loads, materials, parameters,data);
    157130}/*}}}*/
    158131#endif
  • issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h

    r23189 r23394  
    99/* local prototypes: */
    1010void    GetVectorFromControlInputsx( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
    11 void    GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
     11void    GetVectorFromControlInputsx( IssmDouble** pvector,int* pN, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
    1212
    13 void    GetPassiveVectorFromControlInputsx(Vector<double>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
    14 void    GetPassiveVectorFromControlInputsx(double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
     13void    GetPassiveVectorFromControlInputsx(double** pvector,int* pN, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
    1514
    1615#endif  /* _GETVECTORFROMCONTROLINPUTSXX_H */
  • issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp

    r23189 r23394  
    7373                xDelete<char>(options);
    7474                /*}}}*/
     75                #elif _HAVE_CODIPACK_
     76                //fprintf(stderr, "*** Codipack CreateParametersAutodiff()\n");
     77                /*initialize a placeholder to store solver pointers: {{{*/
     78                /*Solver pointers depend on what type of solver we are implementing: */
     79                options=OptionsFromAnalysis(&toolkit,parameters,DefaultAnalysisEnum);
     80                ToolkitOptions::Init(toolkit,options);
     81                xDelete<char>(toolkit);
     82
     83                switch(IssmSolverTypeFromToolkitOptions()){
     84                        case MumpsEnum:{
     85                                #ifndef _HAVE_MUMPS_
     86                                _error_("CoDiPack: requesting mumps solver without MUMPS being compiled in!");
     87                                #endif
     88                                break;
     89                                }
     90                        case GslEnum: {
     91                                #ifndef _HAVE_GSL_
     92                                _error_("CoDiPack: requesting GSL solver without GSL being compiled in!");
     93                                #endif
     94                                break;
     95                                }
     96                        default:
     97                                                        _error_("solver type not supported yet!");
     98                }
     99                /*Free ressources: */
     100                xDelete<char>(options);
     101                #endif
     102                #if defined(_HAVE_AD_)
    75103
    76104        if(isautodiff){
    77                 /*Copy some parameters from IoModel to parameters dataset: {{{*/
     105                #if defined(_HAVE_ADOLC_)
     106                /*Copy some parameters from IoModel to parameters dataset*/
    78107                parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.obufsize",AutodiffObufsizeEnum));
    79108                parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.cbufsize",AutodiffCbufsizeEnum));
     
    82111                parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.gcTriggerRatio",AutodiffGcTriggerRatioEnum));
    83112                parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.gcTriggerMaxSize",AutodiffGcTriggerMaxSizeEnum));
    84                 /*}}}*/
     113
     114                #elif defined(_HAVE_CODIPACK_)
     115                parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.tapeAlloc",AutodiffTapeAllocEnum));
     116
     117                #else
     118                _error_("not supported yet");
     119                #endif
     120
    85121                /*retrieve driver: {{{*/
    86122                iomodel->FindConstant(&autodiff_driver,"md.autodiff.driver");
     
    88124
    89125                if(strcmp(autodiff_driver,"fos_forward")==0){
     126#if _HAVE_CODIPACK_
     127                        // FIXME codi support Foward Mode (scalar)
     128                        _error_("Foward Mode (scalar) not supported yet!");
     129#endif
    90130                        parameters->AddObject(iomodel->CopyConstantObject("md.autodiff.fos_forward_index",AutodiffFosForwardIndexEnum));
    91131                }
     
    94134                }
    95135                else if(strcmp(autodiff_driver,"fov_forward")==0){
     136#if _HAVE_CODIPACK_
     137                        // FIXME codi support Foward Mode (vector)
     138                        _error_("Foward Mode (vector) not supported yet!");
     139#endif
    96140                        /*Retrieve list of indices: */
    97141                        iomodel->FetchData(&indices,&num_indices,&dummy,"md.autodiff.fov_forward_indices");
  • issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp

    r23189 r23394  
    99#include "../ModelProcessorx.h"
    1010
    11 #if !defined(_HAVE_ADOLC_)
    1211void    UpdateElementsAndMaterialsControl(Elements* elements,Parameters* parameters,Materials* materials, IoModel* iomodel){
    1312        /*Intermediary*/
     
    2019        char     **controls         = NULL;
    2120        char     **cost_functions   = NULL;
     21
     22        /*Fetch parameters: */
     23        bool isautodiff;
     24        iomodel->FindConstant(&isautodiff,"md.autodiff.isautodiff");
     25        if(isautodiff){
     26                UpdateElementsAndMaterialsControlAD(elements,parameters,materials,iomodel);
     27                return;
     28        }
    2229
    2330        /*Fetch parameters: */
     
    126133        xDelete<char*>(controls);
    127134}
    128 #else
    129 void UpdateElementsAndMaterialsControl(Elements* elements,Parameters* parameters,Materials* materials, IoModel* iomodel){
    130 
     135void UpdateElementsAndMaterialsControlAD(Elements* elements,Parameters* parameters,Materials* materials, IoModel* iomodel){
     136
     137        #if defined(_HAVE_AD_)
    131138        /*Intermediaries*/
    132139        int                             num_independent_objects,M,N,M_par,N_par;
     
    222229        xDelete<IssmDouble>(independents_fullmax);
    223230        xDelete<int>(start_point);
     231        xDelete<int>(control_sizes);
    224232        /*Step2: create cost functions (dependents)*/
    225233
    226234        return;
     235#else
     236        _error_("AD not compiled");
     237#endif
    227238}
    228 #endif
  • issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp

    r23189 r23394  
    3232                                for(j=0;j<3;j++){
    3333                                        if(my_nodes[3*i+j]){
    34                                                 nodes->AddObject(new Node(id0+3*i+j+1,id0+3*i+j,lid++,iomodel->elements[+3*i+j]-1,iomodel,analysis,approximation));
     34                                                nodes->AddObject(new Node(id0+3*i+j+1,id0+3*i+j,lid++,iomodel->elements[3*i+j]-1,iomodel,analysis,approximation));
    3535
    3636                                        }
  • issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp

    r23189 r23394  
    374374        ParseToolkitsOptionsx(parameters,toolkitsoptionsfid);
    375375
    376         #ifdef _HAVE_ADOLC_
     376        #ifdef _HAVE_AD_
    377377        if(VerboseMProcessor()) _printf0_("   starting autodiff parameters \n");
    378378        CreateParametersAutodiff(parameters,iomodel);
  • issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h

    r23189 r23394  
    1919void CreateOutputDefinitions(Elements* elements, Parameters* parameters,IoModel* iomodel);
    2020void UpdateElementsAndMaterialsControl(Elements* elements,Parameters* parameters,Materials* materials, IoModel* iomodel);
     21void UpdateElementsAndMaterialsControlAD(Elements* elements,Parameters* parameters,Materials* materials, IoModel* iomodel);
    2122void UpdateElementsAndMaterialsDakota(Elements* elements,Materials* materials, IoModel* iomodel);
    2223void UpdateElementsTransient(Elements* elements,Parameters* parameters,IoModel* iomodel,int analysis_type);
  • issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp

    r23189 r23394  
    3333
    3434                xDelete<int>(control_type);
     35                xDelete<int>(M);
     36                xDelete<int>(N);
    3537        }
    3638        else{
  • issm/trunk/src/c/modules/SurfaceMassBalancex/Gembx.cpp

    r23189 r23394  
    6262        //into specified top structure depth (zTop). Also make sure top grid cell
    6363        //structure length (dzTop) is greater than 5 cm
    64         #ifndef _HAVE_ADOLC_  //avoid the round operation check!
     64        #ifndef _HAVE_AD_  //avoid the round operation check!
    6565        if (dgpTop != round(dgpTop)){
    6666                _error_("top grid cell structure length does not go evenly into specified top structure depth, adjust dzTop or zTop");
     
    425425                        // spectral range:
    426426                        // 0.3 - 0.8um
    427                         IssmDouble a0 = fmin(0.98, 1 - 1.58 *pow(gsz,0.5));
     427                        IssmDouble a0 = min(0.98, 1 - 1.58 *pow(gsz,0.5));
    428428                        // 0.8 - 1.5um
    429                         IssmDouble a1 = fmax(0, 0.95 - 15.4 *pow(gsz,0.5));
     429                        IssmDouble a1 = max(0., 0.95 - 15.4 *pow(gsz,0.5));
    430430                        // 1.5 - 2.8um
    431                         IssmDouble a2 = fmax(0.127, 0.88 + 346.3*gsz - 32.31*pow(gsz,0.5));
     431                        IssmDouble a2 = max(0.127, 0.88 + 346.3*gsz - 32.31*pow(gsz,0.5));
    432432
    433433                        // broadband surface albedo
     
    667667        // NS: 2.16.18 divided dt by scaling factor, default set to 1/11 for stability
    668668        dt=1e12;
    669         for(int i=0;i<m;i++)dt = fmin(dt,CI * pow(dz[i],2) * d[i]  / (3 * K[i]) * thermo_scaling);
     669        for(int i=0;i<m;i++)dt = min(dt,CI * pow(dz[i],2) * d[i]  / (3 * K[i]) * thermo_scaling);
    670670
    671671        // smallest possible even integer of 60 min where diffusion number > 1/2
     
    752752                // less when Ts is taken as the mean of the x top grid cells.
    753753                Ts = (T[0] + T[1])/2.0;
    754                 Ts = fmin(CtoK,Ts);    // don't allow Ts to exceed 273.15 K (0 degC)
     754                Ts = min(CtoK,Ts);    // don't allow Ts to exceed 273.15 K (0 degC)
    755755
    756756                //TURBULENT HEAT FLUX
     
    767767
    768768                // do not allow Ri to exceed 0.19
    769                 Ri = fmin(Ri, 0.19);
     769                Ri = min(Ri, 0.19);
    770770
    771771                // calculate momentum 'coefM' stability factor
     
    947947                        // spectral albedos:
    948948                        // 0.3 - 0.8um
    949                         IssmDouble a0 = fmin(0.98, 1.0 - 1.58 *pow(gsz[0],0.5));
     949                        IssmDouble a0 = min(0.98, 1.0 - 1.58 *pow(gsz[0],0.5));
    950950                        // 0.8 - 1.5um
    951                         IssmDouble a1 = fmax(0.0, 0.95 - 15.4 *pow(gsz[0],0.5));
     951                        IssmDouble a1 = max(0.0, 0.95 - 15.4 *pow(gsz[0],0.5));
    952952                        // 1.5 - 2.8um
    953                         IssmDouble a2 = fmax(0.127, 0.88 + 346.3*gsz[0] - 32.31*pow(gsz[0],0.5));
     953                        IssmDouble a2 = max(0.127, 0.88 + 346.3*gsz[0] - 32.31*pow(gsz[0],0.5));
    954954
    955955                        // separate net shortwave radiative flux into spectral ranges
     
    12041204                mass_diff = mass - massinit - P;
    12051205
    1206                 #ifndef _HAVE_ADOLC_  //avoid round operation. only check in forward mode.
     1206                #ifndef _HAVE_AD_  //avoid round operation. only check in forward mode.
    12071207                mass_diff = round(mass_diff * 100.0)/100.0;
    12081208                if (mass_diff > 0) _error_("mass not conserved in accumulation function");
     
    13231323        // calculate temperature excess above 0 deg C
    13241324        exsT=xNewZeroInit<IssmDouble>(n);
    1325         for(int i=0;i<n;i++) exsT[i]= fmax(0.0, T[i] - CtoK);        // [K] to [degC]
     1325        for(int i=0;i<n;i++) exsT[i]= max(0.0, T[i] - CtoK);        // [K] to [degC]
    13261326
    13271327        // new grid point center temperature, T [K]
    13281328        // for(int i=0;i<n;i++) T[i]-=exsT[i];
    1329         for(int i=0;i<n;i++) T[i]=fmin(T[i],CtoK);
     1329        for(int i=0;i<n;i++) T[i]=min(T[i],CtoK);
    13301330
    13311331        // specify irreducible water content saturation [fraction]
     
    13371337                if(VerboseSmb() && sid==0 && IssmComm::GetRank()==0)_printf0_("      pore water refreeze\n");
    13381338                // calculate maximum freeze amount, maxF [kg]
    1339                 for(int i=0;i<n;i++) maxF[i] = fmax(0.0, -((T[i] - CtoK) * m[i] * CI) / LF);
     1339                for(int i=0;i<n;i++) maxF[i] = max(0.0, -((T[i] - CtoK) * m[i] * CI) / LF);
    13401340
    13411341                // freeze pore water and change snow/ice properties
    1342                 for(int i=0;i<n;i++) dW[i] = fmin(maxF[i], W[i]);    // freeze mass [kg]   
     1342                for(int i=0;i<n;i++) dW[i] = min(maxF[i], W[i]);    // freeze mass [kg]   
    13431343                for(int i=0;i<n;i++) W[i] -= dW[i];                                            // pore water mass [kg]
    13441344                for(int i=0;i<n;i++) m[i] += dW[i];                                            // new mass [kg]
     
    13561356        for(int i=0;i<n;i++){
    13571357                Wi= (dIce - d[i]) * Swi * (m[i] / d[i]);        // irreducible water content [kg]
    1358                 exsW[i] = fmax(0.0, W[i] - Wi);                  // water "squeezed" from snow [kg]
     1358                exsW[i] = max(0.0, W[i] - Wi);                  // water "squeezed" from snow [kg]
    13591359        }
    13601360
     
    13681368                // (maximum T of snow before entire grid cell melts is a constant
    13691369                // LF/CI = 159.1342)
    1370                 surpT=xNew<IssmDouble>(n); for(int i=0;i<n;i++)surpT[i] = fmax(0.0, exsT[i]- LF/CI);
     1370                surpT=xNew<IssmDouble>(n); for(int i=0;i<n;i++)surpT[i] = max(0.0, exsT[i]- LF/CI);
    13711371
    13721372                if (cellsum(surpT,n) > 0.0 + Ttol ){
     
    13801380                                T[i+1] = surpE[i]/m[i+1]/CI + T[i+1];
    13811381
    1382                                 exsT[i+1] = fmax(0.0, T[i+1] - CtoK) + exsT[i+1];
    1383                                 T[i+1] = fmin(CtoK, T[i+1]);
    1384 
    1385                                 surpT[i+1] = fmax(0.0, exsT[i+1] - LF/CI);
     1382                                exsT[i+1] = max(0.0, T[i+1] - CtoK) + exsT[i+1];
     1383                                T[i+1] = min(CtoK, T[i+1]);
     1384
     1385                                surpT[i+1] = max(0.0, exsT[i+1] - LF/CI);
    13861386                                surpE[i+1] = surpT[i+1] * CI * m[i+1];
    13871387
     
    13941394
    13951395                // convert temperature excess to melt [kg]
    1396                 for(int i=0;i<n;i++) M[i] = fmin(exsT[i] * d[i] * dz[i] * CI / LF, m[i]);  // melt
     1396                for(int i=0;i<n;i++) M[i] = min(exsT[i] * d[i] * dz[i] * CI / LF, m[i]);  // melt
    13971397                sumM = cellsum(M,n);                                                       // total melt [kg]
    13981398
    13991399                // calculate maximum refreeze amount, maxF [kg]
    1400                 for(int i=0;i<n;i++)maxF[i] = fmax(0.0, -((T[i] - CtoK) * d[i] * dz[i] * CI)/ LF);
     1400                for(int i=0;i<n;i++)maxF[i] = max(0.0, -((T[i] - CtoK) * d[i] * dz[i] * CI)/ LF);
    14011401
    14021402                // initialize refreeze, runoff, flxDn and dW vectors [kg]
     
    14351435                                m[i] = m[i] - M[i];                     // mass after melt
    14361436                                Wi = (dIce-d[i]) * Swi * (m[i]/d[i]);    // irreducible water
    1437                                 dW[i] = fmax(fmin(inM, Wi - W[i]),-1*W[i]);            // change in pore water
    1438                                 R[i] = fmax(0.0, inM - dW[i]);             // runoff
     1437                                dW[i] = max(min(inM, Wi - W[i]),-1*W[i]);            // change in pore water
     1438                                R[i] = max(0.0, inM - dW[i]);             // runoff
    14391439                                F[i] = 0.0;
    14401440                        }
     
    14471447                                m[i] = m[i] - M[i];                     // mass after melt
    14481448                                Wi = (dIce-d[i]) * Swi * (m[i]/d[i]);    // irreducible water
    1449                                 dW[i] = fmax(fmin(inM, Wi - W[i]),-1*W[i]);              // change in pore water
    1450                                 flxDn[i+1] = fmax(0.0, inM - dW[i]);         // meltwater out
     1449                                dW[i] = max(min(inM, Wi - W[i]),-1*W[i]);              // change in pore water
     1450                                flxDn[i+1] = max(0.0, inM - dW[i]);         // meltwater out
    14511451                                R[i] = 0.0;
    14521452                                F[i] = 0.0;                               // no freeze
     
    14601460                                IssmDouble dz_0 = m[i]/d[i];         
    14611461                                IssmDouble dMax = (dIce - d[i])*dz_0;              // d max = dIce
    1462                                 IssmDouble F1 = fmin(fmin(inM,dMax),maxF[i]);         // maximum refreeze               
     1462                                IssmDouble F1 = min(min(inM,dMax),maxF[i]);         // maximum refreeze               
    14631463                                m[i] = m[i] + F1;                       // mass after refreeze
    14641464                                d[i] = m[i]/dz_0;
     
    14661466                                //-----------------------pore water-----------------------------
    14671467                                Wi = (dIce-d[i])* Swi * dz_0;            // irreducible water
    1468                                 dW[i] = fmin(inM - F1, Wi-W[i]);         // change in pore water
     1468                                dW[i] = min(inM - F1, Wi-W[i]);         // change in pore water
    14691469                                if (dW[i] < 0.0-Wtol && -1*dW[i]>W[i]-Wtol ){
    14701470                                        dW[i]= -1*W[i];
     
    14741474                                if (dW[i] < 0.0-Wtol){                         // excess pore water
    14751475                                        dMax = (dIce - d[i])*dz_0;          // maximum refreeze                                             
    1476                                         IssmDouble maxF2 = fmin(dMax, maxF[i]-F1);      // maximum refreeze
    1477                                         F2 = fmin(-1*dW[i], maxF2);            // pore water refreeze
     1476                                        IssmDouble maxF2 = min(dMax, maxF[i]-F1);      // maximum refreeze
     1477                                        F2 = min(-1*dW[i], maxF2);            // pore water refreeze
    14781478                                        m[i] = m[i] + F2;                   // mass after refreeze
    14791479                                        d[i] = m[i]/dz_0;
     
    17531753
    17541754        /*only in forward mode! avoid round in AD mode as it is not differentiable: */
    1755         #ifndef _HAVE_ADOLC_
     1755        #ifndef _HAVE_AD_
    17561756        dm = round((mSum0 - mSum1 + mAdd)*100.0)/100.0;
    17571757        dE = round(sumE0 - sumE1 - sumER +  addE);
     
    19151915                                c0arth = 0.07 * H;
    19161916                                c1arth = 0.03 * H;
    1917                                 M0 = fmax(1.435 - (0.151 * log(C)),0.25);
    1918                                 M1 = fmax(2.366 - (0.293 * log(C)),0.25);
     1917                                M0 = max(1.435 - (0.151 * log(C)),0.25);
     1918                                M1 = max(2.366 - (0.293 * log(C)),0.25);
    19191919                                c0 = M0*c0arth;
    19201920                                c1 = M1*c1arth;
     
    19261926                                c0arth = 0.07 * H;
    19271927                                c1arth = 0.03 * H;
    1928                                 M0 = fmax(1.042 - (0.0916 * log(C)),0.25);
    1929                                 M1 = fmax(1.734 - (0.2039 * log(C)),0.25);
     1928                                M0 = max(1.042 - (0.0916 * log(C)),0.25);
     1929                                M1 = max(1.734 - (0.2039 * log(C)),0.25);
    19301930                                c0 = M0*c0arth;
    19311931                                c1 = M1*c1arth;
     
    20212021
    20222022        // do not allow Ri to exceed 0.19
    2023         Ri = fmin(Ri, 0.19);
     2023        Ri = min(Ri, 0.19);
    20242024
    20252025        // calculate momentum 'coefM' stability factor
  • issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp

    r23189 r23394  
    11/*!\file SurfaceMassBalancex
    2  * \brief: calculates SMB 
     2 * \brief: calculates SMB
    33 */
    44
     
    105105                for(v=0;v<numvertices;v++){
    106106                        // if surface is above the ELA
    107                         if(s[v]>ela[v]){               
     107                        if(s[v]>ela[v]){
    108108                                smb[v]=b_pos[v]*(s[v]-ela[v]);
    109109                        }
     
    167167        //    INPUT: surface elevation (m): hd(NA)
    168168        //    monthly mean surface sealevel temperature (degrees C): vTempsea(NA
    169         //    ,NTIME) 
     169        //    ,NTIME)
    170170        //    monthly mean precip rate (m/yr water equivalent): vPrec(NA,NTIME)
    171171        //    OUTPUT: mass-balance (m/yr ice): agd(NA)
     
    174174        int    i, it, jj, itm;
    175175        IssmDouble DT = 0.02, sigfac, snormfac;
    176         IssmDouble signorm = 5.5;      // signorm : sigma of the temperature distribution for a normal day 
     176        IssmDouble signorm = 5.5;      // signorm : sigma of the temperature distribution for a normal day
    177177        IssmDouble siglim;       // sigma limit for the integration which is equal to 2.5 sigmanorm
    178178        IssmDouble signormc = signorm - 0.5;     // sigma of the temperature distribution for cloudy day
     
    180180        IssmDouble tstep, tsint, tint, tstepc;
    181181        int    NPDMAX = 1504, NPDCMAX = 1454;
    182         //IssmDouble pdds[NPDMAX]={0}; 
     182        //IssmDouble pdds[NPDMAX]={0};
    183183        //IssmDouble pds[NPDCMAX]={0};
    184184        IssmDouble pddt, pd ; // pd : snow/precip fraction, precipitation falling as snow
     
    193193        Element    *element = NULL;
    194194
    195         pdds=xNew<IssmDouble>(NPDMAX+1); 
    196         pds=xNew<IssmDouble>(NPDCMAX+1); 
     195        pdds=xNew<IssmDouble>(NPDMAX+1);
     196        pds=xNew<IssmDouble>(NPDCMAX+1);
    197197
    198198        // Get ismungsm parameter
     
    216216
    217217        if(itm >= NPDMAX) _error_("increase NPDMAX in massBalance.cpp");
    218         for(it = 0; it < itm; it++){ 
     218        for(it = 0; it < itm; it++){
    219219                //    tstar = REAL(it)*DT-siglim;
    220220                tstar = it*DT-siglim;
     
    262262        xDelete<IssmDouble>(pds);
    263263}/*}}}*/
     264void PositiveDegreeDaySicopolisx(FemModel* femmodel){/*{{{*/
     265
     266        bool isfirnwarming;
     267        femmodel->parameters->FindParam(&isfirnwarming,SmbIsfirnwarmingEnum);
     268
     269        for(int i=0;i<femmodel->elements->Size();i++){
     270                Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
     271                element->PositiveDegreeDaySicopolis(isfirnwarming);
     272        }
     273
     274}/*}}}*/
    264275void SmbHenningx(FemModel* femmodel){/*{{{*/
    265276
     
    346357                /*Allocate all arrays*/
    347358                int         numvertices = element->GetNumberOfVertices();
    348                 IssmDouble* acc         = xNew<IssmDouble>(numvertices); 
     359                IssmDouble* acc         = xNew<IssmDouble>(numvertices);
    349360                IssmDouble* evap        = xNew<IssmDouble>(numvertices);
    350                 IssmDouble* runoff      = xNew<IssmDouble>(numvertices); 
     361                IssmDouble* runoff      = xNew<IssmDouble>(numvertices);
    351362                IssmDouble* smb         = xNew<IssmDouble>(numvertices);
    352363
     
    388399                int         numvertices = element->GetNumberOfVertices();
    389400                IssmDouble* acc         = xNew<IssmDouble>(numvertices);
    390                 IssmDouble* evap        = xNew<IssmDouble>(numvertices); 
     401                IssmDouble* evap        = xNew<IssmDouble>(numvertices);
    391402                IssmDouble* melt        = xNew<IssmDouble>(numvertices);
    392403                IssmDouble* refreeze    = xNew<IssmDouble>(numvertices);
     
    414425
    415426}/*}}}*/
     427void SmbGradientsComponentsx(FemModel* femmodel){/*{{{*/
     428
     429        // void SurfaceMassBalancex(hd,agd,ni){
     430        //    INPUT parameters: ni: working size of arrays
     431        //    INPUT: surface elevation (m): hd(NA)
     432        //    OUTPUT: mass-balance (m/yr ice): agd(NA)
     433
     434        for(int i=0;i<femmodel->elements->Size();i++){
     435                Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
     436                element->SmbGradCompParameterization();
     437        }
     438
     439}/*}}}*/
  • issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h

    r22758 r23394  
    11/*!\file:  SurfaceMassBalancex.h
    22 * \brief header file for SMB
    3  */ 
     3 */
    44
    55#ifndef _SurfaceMassBalancex_H
     
    1616void Delta18opdParameterizationx(FemModel* femmodel);
    1717void PositiveDegreeDayx(FemModel* femmodel);
     18void PositiveDegreeDaySicopolisx(FemModel* femmodel);
    1819void SmbHenningx(FemModel* femmodel);
    1920void SmbComponentsx(FemModel* femmodel);
    20 void SmbMeltComponentsx(FemModel* femmodel); 
    21 
     21void SmbMeltComponentsx(FemModel* femmodel);
     22void SmbGradientsComponentsx(FemModel* femmodel);
    2223/*GEMB: */
    2324void       Gembx(FemModel* femmodel);
    24 void       GembgridInitialize(IssmDouble** pdz, int* psize, IssmDouble zTop, IssmDouble dzTop, IssmDouble zMax, IssmDouble zY); 
     25void       GembgridInitialize(IssmDouble** pdz, int* psize, IssmDouble zTop, IssmDouble dzTop, IssmDouble zMax, IssmDouble zY);
    2526IssmDouble Marbouty(IssmDouble T, IssmDouble d, IssmDouble dT);
    2627void grainGrowth(IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, IssmDouble* T,IssmDouble* dz,IssmDouble* d, IssmDouble* W,IssmDouble smb_dt,int m,int aIdx, int sid);
     
    2829void shortwave(IssmDouble** pswf, int swIdx, int aIdx, IssmDouble dsw, IssmDouble as, IssmDouble* d, IssmDouble* dz, IssmDouble* re, IssmDouble dIce, int m, int sid);
    2930void thermo(IssmDouble* pEC, IssmDouble** T, IssmDouble* dz, IssmDouble* d, IssmDouble* swf, IssmDouble dlw, IssmDouble Ta, IssmDouble V, IssmDouble eAir, IssmDouble pAir, IssmDouble teValue, IssmDouble Ws, IssmDouble dt0, int m, IssmDouble Vz, IssmDouble Tz, IssmDouble thermo_scaling, IssmDouble dIce, int sid);
    30 void accumulation(IssmDouble** pT, IssmDouble** pdz, IssmDouble** pd, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pm, int aIdx,IssmDouble Ta, IssmDouble P, IssmDouble dzMin, IssmDouble aSnow, IssmDouble dIce, int sid); 
     31void accumulation(IssmDouble** pT, IssmDouble** pdz, IssmDouble** pd, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pm, int aIdx,IssmDouble Ta, IssmDouble P, IssmDouble dzMin, IssmDouble aSnow, IssmDouble dIce, int sid);
    3132void melt(IssmDouble* pM, IssmDouble* pR, IssmDouble* pmAdd, IssmDouble* pdz_add, IssmDouble** pT, IssmDouble** pd, IssmDouble** pdz, IssmDouble** pW, IssmDouble** pa, IssmDouble** pre, IssmDouble** pgdn, IssmDouble** pgsp, int* pn, IssmDouble dzMin, IssmDouble zMax, IssmDouble zMin, IssmDouble zTop, IssmDouble dIce, int sid);
    3233void densification(IssmDouble** pd,IssmDouble** pdz, IssmDouble* T, IssmDouble* re, int denIdx, IssmDouble C, IssmDouble dt, IssmDouble Tmean, IssmDouble dIce, int m, int sid);
  • issm/trunk/src/c/shared/Elements/PrintArrays.cpp

    r23189 r23394  
    1212        _printf_("\n");
    1313}
    14 #ifdef _HAVE_ADOLC_
     14#ifdef _HAVE_AD_
    1515void printarray(IssmDouble* array,int lines,int cols){
    1616        _printf_("\n");
  • issm/trunk/src/c/shared/Elements/elements.h

    r23189 r23394  
    2424                                 IssmDouble TdiffTime,IssmDouble sealevTime,IssmDouble pddsnowfac,IssmDouble pddicefac,
    2525                                 IssmDouble rho_water, IssmDouble rho_ice);
     26IssmDouble PddSurfaceMassBalanceSicopolis(IssmDouble* monthlytemperatures,  IssmDouble* monthlyprec,
     27                                 IssmDouble* melt, IssmDouble* accu, IssmDouble* melt_star, IssmDouble* t_ampl, IssmDouble* p_ampl,
     28                                 IssmDouble yts, IssmDouble s, IssmDouble desfac,IssmDouble s0t,
     29                                 IssmDouble s0p, IssmDouble rlaps, IssmDouble rho_water, IssmDouble rho_ice);
    2630void ComputeDelta18oTemperaturePrecipitation(IssmDouble Delta18oSurfacePresent, IssmDouble Delta18oSurfaceLgm, IssmDouble Delta18oSurfaceTime,
    2731                                             IssmDouble Delta18oPresent, IssmDouble Delta18oLgm, IssmDouble Delta18oTime,
     
    4246/*Print arrays*/
    4347void printarray(IssmPDouble* array,int lines,int cols=1);
    44 #if _HAVE_ADOLC_  && !defined(_WRAPPERS_)
     48#if _HAVE_AD_  && !defined(_WRAPPERS_)
    4549void printarray(IssmDouble* array,int lines,int cols=1);
    4650#endif
  • issm/trunk/src/c/shared/Enum/EnumDefinitions.h

    r23189 r23394  
    5353        AutodiffNumIndependentsEnum,
    5454        AutodiffObufsizeEnum,
     55        AutodiffTapeAllocEnum,
    5556        AutodiffTbufsizeEnum,
    5657        AutodiffXpEnum,
     
    272273        SettingsSolverResidueThresholdEnum,
    273274        SettingsWaitonlockEnum,
     275        SmbAccualtiEnum,
     276        SmbAccugradEnum,
     277        SmbAccurefEnum,
    274278        SmbAdThreshEnum,
    275279        SmbAIceEnum,
     
    290294        SmbIsdensificationEnum,
    291295        SmbIsgraingrowthEnum,
     296        SmbIsfirnwarmingEnum,
    292297        SmbIsmeltEnum,
    293298        SmbIsmungsmEnum,
     
    302307        SmbPfacEnum,
    303308        SmbRequestedOutputsEnum,
     309        SmbRunoffaltiEnum,
     310        SmbRunoffgradEnum,
     311        SmbRunoffrefEnum,
    304312        SmbSealevEnum,
    305313        SmbSwIdxEnum,
     
    526534        SealevelNEsaRateEnum,
    527535        SealevelRSLRateEnum,
    528         SealevelUEsaEnum, 
     536        SealevelUEsaEnum,
    529537        SealevelRSLEustaticRateEnum,
    530         SealevelNEsaEnum, 
     538        SealevelNEsaEnum,
    531539        SealevelUGiaEnum,
    532540        SealevelNGiaEnum,
     
    577585        SmbPEnum,
    578586        SmbPrecipitationEnum,
     587        SmbPrecipitationsAnomalyEnum,
    579588        SmbPrecipitationsLgmEnum,
    580589        SmbPrecipitationsPresentdayEnum,
     
    588597        SmbSizeiniEnum,
    589598        SmbSmbrefEnum,
     599        SmbSmbCorrEnum,
    590600        SmbTaEnum,
     601        SmbTemperaturesAnomalyEnum,
    591602        SmbTemperaturesLgmEnum,
    592603        SmbTemperaturesPresentdayEnum,
     
    10951106        SMBmeltcomponentsEnum,
    10961107        SMBpddEnum,
     1108        SMBpddSicopolisEnum,
     1109        SMBgradientscomponentsEnum,
    10971110        SmbRlapsEnum,
    10981111        SmbRlapslgmEnum,
  • issm/trunk/src/c/shared/Enum/EnumToStringx.cpp

    r23189 r23394  
    6161                case AutodiffNumIndependentsEnum : return "AutodiffNumIndependents";
    6262                case AutodiffObufsizeEnum : return "AutodiffObufsize";
     63                case AutodiffTapeAllocEnum : return "AutodiffTapeAlloc";
    6364                case AutodiffTbufsizeEnum : return "AutodiffTbufsize";
    6465                case AutodiffXpEnum : return "AutodiffXp";
     
    280281                case SettingsSolverResidueThresholdEnum : return "SettingsSolverResidueThreshold";
    281282                case SettingsWaitonlockEnum : return "SettingsWaitonlock";
     283                case SmbAccualtiEnum : return "SmbAccualti";
     284                case SmbAccugradEnum : return "SmbAccugrad";
     285                case SmbAccurefEnum : return "SmbAccuref";
    282286                case SmbAdThreshEnum : return "SmbAdThresh";
    283287                case SmbAIceEnum : return "SmbAIce";
     
    298302                case SmbIsdensificationEnum : return "SmbIsdensification";
    299303                case SmbIsgraingrowthEnum : return "SmbIsgraingrowth";
     304                case SmbIsfirnwarmingEnum : return "SmbIsfirnwarming";
    300305                case SmbIsmeltEnum : return "SmbIsmelt";
    301306                case SmbIsmungsmEnum : return "SmbIsmungsm";
     
    310315                case SmbPfacEnum : return "SmbPfac";
    311316                case SmbRequestedOutputsEnum : return "SmbRequestedOutputs";
     317                case SmbRunoffaltiEnum : return "SmbRunoffalti";
     318                case SmbRunoffgradEnum : return "SmbRunoffgrad";
     319                case SmbRunoffrefEnum : return "SmbRunoffref";
    312320                case SmbSealevEnum : return "SmbSealev";
    313321                case SmbSwIdxEnum : return "SmbSwIdx";
     
    583591                case SmbPEnum : return "SmbP";
    584592                case SmbPrecipitationEnum : return "SmbPrecipitation";
     593                case SmbPrecipitationsAnomalyEnum : return "SmbPrecipitationsAnomaly";
    585594                case SmbPrecipitationsLgmEnum : return "SmbPrecipitationsLgm";
    586595                case SmbPrecipitationsPresentdayEnum : return "SmbPrecipitationsPresentday";
     
    594603                case SmbSizeiniEnum : return "SmbSizeini";
    595604                case SmbSmbrefEnum : return "SmbSmbref";
     605                case SmbSmbCorrEnum : return "SmbSmbCorr";
    596606                case SmbTaEnum : return "SmbTa";
     607                case SmbTemperaturesAnomalyEnum : return "SmbTemperaturesAnomaly";
    597608                case SmbTemperaturesLgmEnum : return "SmbTemperaturesLgm";
    598609                case SmbTemperaturesPresentdayEnum : return "SmbTemperaturesPresentday";
     
    10991110                case SMBmeltcomponentsEnum : return "SMBmeltcomponents";
    11001111                case SMBpddEnum : return "SMBpdd";
     1112                case SMBpddSicopolisEnum : return "SMBpddSicopolis";
     1113                case SMBgradientscomponentsEnum : return "SMBgradientscomponents";
    11011114                case SmbRlapsEnum : return "SmbRlaps";
    11021115                case SmbRlapslgmEnum : return "SmbRlapslgm";
  • issm/trunk/src/c/shared/Enum/StringToEnumx.cpp

    r23189 r23394  
    6161              else if (strcmp(name,"AutodiffNumIndependents")==0) return AutodiffNumIndependentsEnum;
    6262              else if (strcmp(name,"AutodiffObufsize")==0) return AutodiffObufsizeEnum;
     63              else if (strcmp(name,"AutodiffTapeAlloc")==0) return AutodiffTapeAllocEnum;
    6364              else if (strcmp(name,"AutodiffTbufsize")==0) return AutodiffTbufsizeEnum;
    6465              else if (strcmp(name,"AutodiffXp")==0) return AutodiffXpEnum;
     
    136137              else if (strcmp(name,"FrictionLaw")==0) return FrictionLawEnum;
    137138              else if (strcmp(name,"FrictionPseudoplasticityExponent")==0) return FrictionPseudoplasticityExponentEnum;
    138               else if (strcmp(name,"FrictionThresholdSpeed")==0) return FrictionThresholdSpeedEnum;
    139139         else stage=2;
    140140   }
    141141   if(stage==2){
    142               if (strcmp(name,"FrictionDelta")==0) return FrictionDeltaEnum;
     142              if (strcmp(name,"FrictionThresholdSpeed")==0) return FrictionThresholdSpeedEnum;
     143              else if (strcmp(name,"FrictionDelta")==0) return FrictionDeltaEnum;
    143144              else if (strcmp(name,"FrictionVoidRatio")==0) return FrictionVoidRatioEnum;
    144145              else if (strcmp(name,"GiaCrossSectionShape")==0) return GiaCrossSectionShapeEnum;
     
    259260              else if (strcmp(name,"SealevelriseFluidLove")==0) return SealevelriseFluidLoveEnum;
    260261              else if (strcmp(name,"SealevelriseGElastic")==0) return SealevelriseGElasticEnum;
    261               else if (strcmp(name,"SealevelriseGeodetic")==0) return SealevelriseGeodeticEnum;
    262262         else stage=3;
    263263   }
    264264   if(stage==3){
    265               if (strcmp(name,"SealevelriseGeodeticRunFrequency")==0) return SealevelriseGeodeticRunFrequencyEnum;
     265              if (strcmp(name,"SealevelriseGeodetic")==0) return SealevelriseGeodeticEnum;
     266              else if (strcmp(name,"SealevelriseGeodeticRunFrequency")==0) return SealevelriseGeodeticRunFrequencyEnum;
    266267              else if (strcmp(name,"SealevelriseHElastic")==0) return SealevelriseHElasticEnum;
    267268              else if (strcmp(name,"SealevelriseHoriz")==0) return SealevelriseHorizEnum;
     
    286287              else if (strcmp(name,"SettingsSolverResidueThreshold")==0) return SettingsSolverResidueThresholdEnum;
    287288              else if (strcmp(name,"SettingsWaitonlock")==0) return SettingsWaitonlockEnum;
     289              else if (strcmp(name,"SmbAccualti")==0) return SmbAccualtiEnum;
     290              else if (strcmp(name,"SmbAccugrad")==0) return SmbAccugradEnum;
     291              else if (strcmp(name,"SmbAccuref")==0) return SmbAccurefEnum;
    288292              else if (strcmp(name,"SmbAdThresh")==0) return SmbAdThreshEnum;
    289293              else if (strcmp(name,"SmbAIce")==0) return SmbAIceEnum;
     
    304308              else if (strcmp(name,"SmbIsdensification")==0) return SmbIsdensificationEnum;
    305309              else if (strcmp(name,"SmbIsgraingrowth")==0) return SmbIsgraingrowthEnum;
     310              else if (strcmp(name,"SmbIsfirnwarming")==0) return SmbIsfirnwarmingEnum;
    306311              else if (strcmp(name,"SmbIsmelt")==0) return SmbIsmeltEnum;
    307312              else if (strcmp(name,"SmbIsmungsm")==0) return SmbIsmungsmEnum;
     
    316321              else if (strcmp(name,"SmbPfac")==0) return SmbPfacEnum;
    317322              else if (strcmp(name,"SmbRequestedOutputs")==0) return SmbRequestedOutputsEnum;
     323              else if (strcmp(name,"SmbRunoffalti")==0) return SmbRunoffaltiEnum;
     324              else if (strcmp(name,"SmbRunoffgrad")==0) return SmbRunoffgradEnum;
     325              else if (strcmp(name,"SmbRunoffref")==0) return SmbRunoffrefEnum;
    318326              else if (strcmp(name,"SmbSealev")==0) return SmbSealevEnum;
    319327              else if (strcmp(name,"SmbSwIdx")==0) return SmbSwIdxEnum;
     
    375383              else if (strcmp(name,"TransientIsmovingfront")==0) return TransientIsmovingfrontEnum;
    376384              else if (strcmp(name,"TransientIsoceancoupling")==0) return TransientIsoceancouplingEnum;
    377               else if (strcmp(name,"TransientIsslr")==0) return TransientIsslrEnum;
     385         else stage=4;
     386   }
     387   if(stage==4){
     388              if (strcmp(name,"TransientIsslr")==0) return TransientIsslrEnum;
    378389              else if (strcmp(name,"TransientIssmb")==0) return TransientIssmbEnum;
    379390              else if (strcmp(name,"TransientIsstressbalance")==0) return TransientIsstressbalanceEnum;
     
    383394              else if (strcmp(name,"Velocity")==0) return VelocityEnum;
    384395              else if (strcmp(name,"WorldComm")==0) return WorldCommEnum;
    385          else stage=4;
    386    }
    387    if(stage==4){
    388               if (strcmp(name,"ParametersEND")==0) return ParametersENDEnum;
     396              else if (strcmp(name,"ParametersEND")==0) return ParametersENDEnum;
    389397              else if (strcmp(name,"InputsSTART")==0) return InputsSTARTEnum;
    390398              else if (strcmp(name,"Adjoint")==0) return AdjointEnum;
     
    498506              else if (strcmp(name,"Ice")==0) return IceEnum;
    499507              else if (strcmp(name,"IceMaskNodeActivation")==0) return IceMaskNodeActivationEnum;
    500               else if (strcmp(name,"Input")==0) return InputEnum;
     508         else stage=5;
     509   }
     510   if(stage==5){
     511              if (strcmp(name,"Input")==0) return InputEnum;
    501512              else if (strcmp(name,"InversionCostFunctionsCoefficients")==0) return InversionCostFunctionsCoefficientsEnum;
    502513              else if (strcmp(name,"InversionSurfaceObs")==0) return InversionSurfaceObsEnum;
     
    506517              else if (strcmp(name,"InversionVyObs")==0) return InversionVyObsEnum;
    507518              else if (strcmp(name,"LevelsetfunctionSlopeX")==0) return LevelsetfunctionSlopeXEnum;
    508          else stage=5;
    509    }
    510    if(stage==5){
    511               if (strcmp(name,"LevelsetfunctionSlopeY")==0) return LevelsetfunctionSlopeYEnum;
     519              else if (strcmp(name,"LevelsetfunctionSlopeY")==0) return LevelsetfunctionSlopeYEnum;
    512520              else if (strcmp(name,"LoadingforceX")==0) return LoadingforceXEnum;
    513521              else if (strcmp(name,"LoadingforceY")==0) return LoadingforceYEnum;
     
    595603              else if (strcmp(name,"SmbP")==0) return SmbPEnum;
    596604              else if (strcmp(name,"SmbPrecipitation")==0) return SmbPrecipitationEnum;
     605              else if (strcmp(name,"SmbPrecipitationsAnomaly")==0) return SmbPrecipitationsAnomalyEnum;
    597606              else if (strcmp(name,"SmbPrecipitationsLgm")==0) return SmbPrecipitationsLgmEnum;
    598607              else if (strcmp(name,"SmbPrecipitationsPresentday")==0) return SmbPrecipitationsPresentdayEnum;
     
    606615              else if (strcmp(name,"SmbSizeini")==0) return SmbSizeiniEnum;
    607616              else if (strcmp(name,"SmbSmbref")==0) return SmbSmbrefEnum;
     617              else if (strcmp(name,"SmbSmbCorr")==0) return SmbSmbCorrEnum;
    608618              else if (strcmp(name,"SmbTa")==0) return SmbTaEnum;
     619              else if (strcmp(name,"SmbTemperaturesAnomaly")==0) return SmbTemperaturesAnomalyEnum;
    609620              else if (strcmp(name,"SmbTemperaturesLgm")==0) return SmbTemperaturesLgmEnum;
    610621              else if (strcmp(name,"SmbTemperaturesPresentday")==0) return SmbTemperaturesPresentdayEnum;
     
    618629              else if (strcmp(name,"SmbVz")==0) return SmbVzEnum;
    619630              else if (strcmp(name,"SmbW")==0) return SmbWEnum;
    620               else if (strcmp(name,"SmbWini")==0) return SmbWiniEnum;
     631         else stage=6;
     632   }
     633   if(stage==6){
     634              if (strcmp(name,"SmbWini")==0) return SmbWiniEnum;
    621635              else if (strcmp(name,"SmbZMax")==0) return SmbZMaxEnum;
    622636              else if (strcmp(name,"SmbZMin")==0) return SmbZMinEnum;
     
    629643              else if (strcmp(name,"StrainRatexy")==0) return StrainRatexyEnum;
    630644              else if (strcmp(name,"StrainRatexz")==0) return StrainRatexzEnum;
    631          else stage=6;
    632    }
    633    if(stage==6){
    634               if (strcmp(name,"StrainRateyy")==0) return StrainRateyyEnum;
     645              else if (strcmp(name,"StrainRateyy")==0) return StrainRateyyEnum;
    635646              else if (strcmp(name,"StrainRateyz")==0) return StrainRateyzEnum;
    636647              else if (strcmp(name,"StrainRatezz")==0) return StrainRatezzEnum;
     
    741752              else if (strcmp(name,"DatasetInput")==0) return DatasetInputEnum;
    742753              else if (strcmp(name,"DataSetParam")==0) return DataSetParamEnum;
    743               else if (strcmp(name,"DefaultAnalysis")==0) return DefaultAnalysisEnum;
     754         else stage=7;
     755   }
     756   if(stage==7){
     757              if (strcmp(name,"DefaultAnalysis")==0) return DefaultAnalysisEnum;
    744758              else if (strcmp(name,"DefaultCalving")==0) return DefaultCalvingEnum;
    745759              else if (strcmp(name,"DegreeOfChannelization")==0) return DegreeOfChannelizationEnum;
     
    752766              else if (strcmp(name,"Domain3Dsurface")==0) return Domain3DsurfaceEnum;
    753767              else if (strcmp(name,"DoubleArrayInput")==0) return DoubleArrayInputEnum;
    754          else stage=7;
    755    }
    756    if(stage==7){
    757               if (strcmp(name,"DoubleExternalResult")==0) return DoubleExternalResultEnum;
     768              else if (strcmp(name,"DoubleExternalResult")==0) return DoubleExternalResultEnum;
    758769              else if (strcmp(name,"DoubleInput")==0) return DoubleInputEnum;
    759770              else if (strcmp(name,"DoubleMatArrayParam")==0) return DoubleMatArrayParamEnum;
     
    864875              else if (strcmp(name,"LambdaS")==0) return LambdaSEnum;
    865876              else if (strcmp(name,"LATaylorHood")==0) return LATaylorHoodEnum;
    866               else if (strcmp(name,"LevelsetAnalysis")==0) return LevelsetAnalysisEnum;
     877         else stage=8;
     878   }
     879   if(stage==8){
     880              if (strcmp(name,"LevelsetAnalysis")==0) return LevelsetAnalysisEnum;
    867881              else if (strcmp(name,"LevelsetfunctionPicard")==0) return LevelsetfunctionPicardEnum;
    868882              else if (strcmp(name,"LinearFloatingMeltRate")==0) return LinearFloatingMeltRateEnum;
     
    875889              else if (strcmp(name,"LoveKernelsImag")==0) return LoveKernelsImagEnum;
    876890              else if (strcmp(name,"LoveKernelsReal")==0) return LoveKernelsRealEnum;
    877          else stage=8;
    878    }
    879    if(stage==8){
    880               if (strcmp(name,"LoveKi")==0) return LoveKiEnum;
     891              else if (strcmp(name,"LoveKi")==0) return LoveKiEnum;
    881892              else if (strcmp(name,"LoveKr")==0) return LoveKrEnum;
    882893              else if (strcmp(name,"LoveLi")==0) return LoveLiEnum;
     
    987998              else if (strcmp(name,"Outputdefinition37")==0) return Outputdefinition37Enum;
    988999              else if (strcmp(name,"Outputdefinition38")==0) return Outputdefinition38Enum;
    989               else if (strcmp(name,"Outputdefinition39")==0) return Outputdefinition39Enum;
     1000         else stage=9;
     1001   }
     1002   if(stage==9){
     1003              if (strcmp(name,"Outputdefinition39")==0) return Outputdefinition39Enum;
    9901004              else if (strcmp(name,"Outputdefinition3")==0) return Outputdefinition3Enum;
    9911005              else if (strcmp(name,"Outputdefinition40")==0) return Outputdefinition40Enum;
     
    9981012              else if (strcmp(name,"Outputdefinition47")==0) return Outputdefinition47Enum;
    9991013              else if (strcmp(name,"Outputdefinition48")==0) return Outputdefinition48Enum;
    1000          else stage=9;
    1001    }
    1002    if(stage==9){
    1003               if (strcmp(name,"Outputdefinition49")==0) return Outputdefinition49Enum;
     1014              else if (strcmp(name,"Outputdefinition49")==0) return Outputdefinition49Enum;
    10041015              else if (strcmp(name,"Outputdefinition4")==0) return Outputdefinition4Enum;
    10051016              else if (strcmp(name,"Outputdefinition50")==0) return Outputdefinition50Enum;
     
    11101121              else if (strcmp(name,"SMBcomponents")==0) return SMBcomponentsEnum;
    11111122              else if (strcmp(name,"SMBd18opdd")==0) return SMBd18opddEnum;
    1112               else if (strcmp(name,"SmbDesfac")==0) return SmbDesfacEnum;
     1123         else stage=10;
     1124   }
     1125   if(stage==10){
     1126              if (strcmp(name,"SmbDesfac")==0) return SmbDesfacEnum;
    11131127              else if (strcmp(name,"SmbDpermil")==0) return SmbDpermilEnum;
    11141128              else if (strcmp(name,"SmbDzAdd")==0) return SmbDzAddEnum;
     
    11211135              else if (strcmp(name,"SMBhenning")==0) return SMBhenningEnum;
    11221136              else if (strcmp(name,"SmbMAdd")==0) return SmbMAddEnum;
    1123          else stage=10;
    1124    }
    1125    if(stage==10){
    1126               if (strcmp(name,"SMBmeltcomponents")==0) return SMBmeltcomponentsEnum;
     1137              else if (strcmp(name,"SMBmeltcomponents")==0) return SMBmeltcomponentsEnum;
    11271138              else if (strcmp(name,"SMBpdd")==0) return SMBpddEnum;
     1139              else if (strcmp(name,"SMBpddSicopolis")==0) return SMBpddSicopolisEnum;
     1140              else if (strcmp(name,"SMBgradientscomponents")==0) return SMBgradientscomponentsEnum;
    11281141              else if (strcmp(name,"SmbRlaps")==0) return SmbRlapsEnum;
    11291142              else if (strcmp(name,"SmbRlapslgm")==0) return SmbRlapslgmEnum;
  • issm/trunk/src/c/shared/MemOps/MemOps.cpp

    r21729 r23394  
    1616#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
    1717template <> adouble*  xNew(unsigned int size, const char* const contig) {
    18         if (*contig == 't')
     18        if (contig[0] == 't' || contig[0] == 'c')
    1919                ensureContiguousLocations(size);
    2020
  • issm/trunk/src/c/shared/Numerics/extrema.cpp

    r15396 r23394  
    1111#include "./types.h"
    1212
     13#ifndef _HAVE_CODIPACK_// already defined in codipack headers
    1314IssmDouble min(IssmDouble a,IssmDouble b){
    1415        if (a<b)return a;
    1516        else return b;
    1617}
     18#endif
    1719int min(int a,int b){
    1820        if (a<b)return a;
    1921        else return b;
    2022}
     23#ifndef _HAVE_CODIPACK_// already defined in codipack headers
    2124IssmDouble max(IssmDouble a,IssmDouble b){
    2225        if (a>b)return a;
    2326        else return b;
    2427}
     28#endif
    2529int max(int a,int b){
    2630        if (a>b)return a;
     
    2832}
    2933
    30 #ifdef _HAVE_ADOLC_
     34#ifdef _HAVE_AD_
    3135IssmPDouble  min(IssmPDouble a,IssmPDouble b){
    3236        if (a<b)return a;
  • issm/trunk/src/c/shared/Numerics/isnan.cpp

    r21341 r23394  
    1313  return std::isnan(X.getValue());
    1414}
    15 #endif
    16 
    17 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
    1815template <> int xIsInf<adouble> (const adouble& X){
    1916  return std::isinf(X.getValue());
    2017}
    2118#endif
     19
     20#if defined(_HAVE_CODIPACK_) && !defined(_WRAPPERS_)
     21template <> int xIsNan<IssmDouble> (const IssmDouble& X){
     22          return std::isnan(X.getValue());
     23}
     24template <> int xIsInf<IssmDouble> (const IssmDouble& X){
     25        return std::isinf(X.getValue());
     26}
     27#endif
  • issm/trunk/src/c/shared/Numerics/isnan.h

    r21341 r23394  
    3333#endif
    3434
     35#if defined(_HAVE_CODIPACK_) && !defined(_WRAPPERS_)
     36#include "./types.h"
     37template <> int xIsNan<IssmDouble> (const IssmDouble& X);
     38template <> int xIsInf<IssmDouble> (const IssmDouble& X);
    3539#endif
     40
     41#endif
  • issm/trunk/src/c/shared/Numerics/numerics.h

    r20500 r23394  
    2020#include "./OptPars.h"
    2121
     22#if !defined(_HAVE_CODIPACK_)
     23// already defined in codipack headers
    2224IssmDouble  min(IssmDouble a,IssmDouble b);
    2325IssmDouble  max(IssmDouble a,IssmDouble b);
     26#endif
    2427
    25 #ifdef _HAVE_ADOLC_
     28#ifdef _HAVE_AD_
    2629IssmPDouble  min(IssmPDouble a,IssmPDouble b);
    2730IssmPDouble  max(IssmPDouble a,IssmPDouble b);
  • issm/trunk/src/c/shared/Numerics/recast.h

    r19105 r23394  
    1515#endif
    1616
    17 #if !defined(_HAVE_ADOLC_) || defined(_WRAPPERS_)
     17#if !defined(_HAVE_AD_) || defined(_WRAPPERS_)
    1818
    1919template<class To, class From> To reCast(const From& from) {
     
    3434 * partial specialization
    3535 */
     36#ifdef _HAVE_ADOLC_
    3637template<class To> struct ForPartialSpecialization<To,adouble> {
    3738    static  To reCast(const adouble& from ) { return (To) (from.getValue());}
    3839};
     40#endif
     41#ifdef _HAVE_CODIPACK_
     42template<class To> struct ForPartialSpecialization<To,IssmDouble> {
     43            static  To reCast(const IssmDouble& from ) { return (To) (from.getValue());}
     44};
     45#endif
    3946
    4047#endif
  • issm/trunk/src/c/shared/Numerics/types.h

    r16137 r23394  
    2222
    2323#if defined(_HAVE_ADOLC_) &&  !defined(_WRAPPERS_)
     24/*ADOLC typedefs*/
    2425#include "adolc/adolc.h"
    25 // for active variables
    26 typedef adouble IssmDouble;
    27 // for passive variables
    28 typedef double IssmPDouble;
     26typedef adouble IssmDouble; /*for active variables*/
     27typedef double  IssmPDouble; /*for passive variables*/
     28
     29#elif defined(_HAVE_CODIPACK_) && !defined(_WRAPPERS_)
     30/*CoDiPack typedefs*/
     31#include <codi.hpp>
     32typedef codi::RealReverse IssmDouble;
     33typedef double            IssmPDouble;
     34
     35/*Non-AD typedefs*/
    2936#else
    30 // see above
    31 typedef double IssmDouble;
    32 // see above
     37typedef double     IssmDouble;
    3338typedef IssmDouble IssmPDouble;
    3439#endif
  • issm/trunk/src/c/shared/io/Marshalling/IoCodeConversions.cpp

    r23189 r23394  
    173173                case 8: return SMBgembEnum;
    174174                case 9: return SMBgradientselaEnum;
     175                case 10: return SMBpddSicopolisEnum;
     176                case 11: return SMBgradientscomponentsEnum;
    175177                default: _error_("Marshalled SMB code \""<<enum_in<<"\" not supported yet");
    176178        }
     
    205207                case 3: return HydrologyshaktiEnum;
    206208                case 4: return HydrologypismEnum;
    207                 default: _error_("Marshalled hydrology code \""<<enum_in<<"\" not supported yet"); 
     209                default: _error_("Marshalled hydrology code \""<<enum_in<<"\" not supported yet");
    208210        }
    209211}/*}}}*/
     
    211213        switch(enum_in){
    212214                case 1: return MatdamageiceEnum;
    213                 case 2: return MatestarEnum; 
     215                case 2: return MatestarEnum;
    214216                case 3: return MaticeEnum;
    215217                case 4: return MatenhancediceEnum;
    216218                case 5: return MatlithoEnum;
    217219                case 6: return MaterialsEnum;
    218                 default: _error_("Marshalled materials code \""<<enum_in<<"\" not supported yet"); 
     220                default: _error_("Marshalled materials code \""<<enum_in<<"\" not supported yet");
    219221        }
    220222}/*}}}*/
     
    222224        switch(enum_in){
    223225                case 1: return FixedTimesteppingEnum;
    224                 case 2: return AdaptiveTimesteppingEnum; 
    225                 default: _error_("Marshalled materials code \""<<enum_in<<"\" not supported yet"); 
     226                case 2: return AdaptiveTimesteppingEnum;
     227                default: _error_("Marshalled materials code \""<<enum_in<<"\" not supported yet");
    226228        }
    227229}/*}}}*/
     
    229231        switch(enum_in){
    230232                case 1: return AmrBamgEnum;
    231                 case 2: return AmrNeopzEnum; 
    232                 default: _error_("Marshalled AMR code \""<<enum_in<<"\" not supported yet"); 
     233                case 2: return AmrNeopzEnum;
     234                default: _error_("Marshalled AMR code \""<<enum_in<<"\" not supported yet");
    233235        }
    234236}/*}}}*/
  • issm/trunk/src/c/solutionsequences/convergence.cpp

    r23189 r23394  
    77#include "../shared/shared.h"
    88
    9 void convergence(bool* pconverged, Matrix<IssmDouble>* Kff,Vector<IssmDouble>* pf,Vector<IssmDouble>* uf,Vector<IssmDouble>* old_uf,IssmDouble eps_res,IssmDouble eps_rel,IssmDouble eps_abs){
     9void convergence(bool* pconverged, Matrix<IssmDouble>* Kff,Vector<IssmDouble>* pf,Vector<IssmDouble>* uf,Vector<IssmDouble>* old_uf,IssmDouble eps_res,IssmDouble eps_rel,IssmDouble eps_abs){/*{{{*/
    1010
    1111        /*output*/
     
    3434        }
    3535
     36
    3637        /*Display solver caracteristics*/
    3738        if (VerboseConvergence()){
     39
     40       
    3841
    3942                /*compute KUF = KU - F = K*U - F*/
     
    136139        /*assign output*/
    137140        *pconverged=converged;
    138 }
     141}/*}}}*/
     142
     143
  • issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp

    r23189 r23394  
    190190                                Reduceloadx(pf,Kfs,ys); delete Kfs;
    191191                                delete uf_epl;
     192
    192193                                femmodel->profiler->Start(SOLVER);
    193194                                Solverx(&uf_epl,Kff,pf,uf_epl_sub_iter,df,femmodel->parameters);
    194195                                femmodel->profiler->Stop(SOLVER);
     196
    195197                                delete Kff; delete pf; delete df;
    196198                                delete uf_epl_sub_iter;
    197                                 uf_epl_sub_iter=uf_epl->Duplicate();
     199                                uf_epl_sub_iter=uf_epl->Duplicate();_assert_(uf_epl_sub_iter);
    198200                                uf_epl->Copy(uf_epl_sub_iter);
    199201                                delete ug_epl;
     
    215217                                        _error_("   maximum number of EPL iterations (" << hydro_maxiter << ") exceeded");
    216218                                }
    217                                 //If there is some colapse go through sediment again
    218                                 /* if(ThickCount<L2Count)eplconverged=true; */
    219219                                eplcount++;
    220220
  • issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp

    r22758 r23394  
    7070                Solverx(&uf, Kff, pf, old_uf, df, femmodel->parameters);
    7171                femmodel->profiler->Stop(SOLVER);
     72       
    7273                Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
    7374
     
    8687                        }
    8788                }
    88 
     89               
    8990                /*Increase count: */
    9091                count++;
  • issm/trunk/src/c/solutionsequences/solutionsequence_schurcg.cpp

    r23189 r23394  
    1010#include "../analyses/analyses.h"
    1111
     12
    1213#ifdef _HAVE_PETSC_
    13 void SchurCGSolver(Vector<IssmDouble>** puf,Mat Kff,Mat Mff,Vec pf, Vec uf0,Vec df,Parameters* parameters){/*{{{*/
     14
     15
     16void SchurCGSolver(Vector<IssmDouble>** puf,Mat Kff,Vec pf, Vec uf0,IS isv,IS isp,Parameters* parameters){/*{{{*/
     17
     18        Mat                  A, B, BT;                          /* Saddle point block matrices */
     19        Mat                                             IP;                                             /* Preconditioner matrix */
     20        Mat                                             IP2;
     21        int                  nu, np;                                    /* No of. free nodes in velocity / pressure space */
     22   Vec                  p,uold,unew;                    /* Solution vectors for pressure / vel. */
     23        Vec                                             tmpu, tmpp, rhsu,rhsp; /* temp. vectors, arbitrary RHS in vel. / pressure space */
     24        Vec                                             gold,gnew,wold,wnew,chi,thetaold,thetanew,eta; /* CG intermediaries */
     25        Vec                                             f1,f2;                                  /* RHS of the global system */
     26        double                                  rho,gamma,tmpScalar; /* Step sizes, arbitrary double */
     27        KSP                                             kspu,kspp;                              /* KSP contexts for vel. / pressure systems*/
     28        KSPConvergedReason      reason;                                 /* Convergence reason for troubleshooting */
     29        int                                             its;                                            /* No. of iterations for troubleshooting */
     30        double                                  initRnorm, rnorm, TOL; /* residual norms, STOP tolerance */
     31        PC                                                      pcu,pcp;                                        /* Preconditioner contexts pertaining the KSP contexts*/
     32        PetscViewer                             viewer;                                 /* Viewer for troubleshooting */
     33        IssmPDouble                             t1,t2;                                  /* Time measurement for bottleneck analysis */
     34
     35        /*STOP tolerance for the rel. residual*/
     36        TOL = 0.4;
    1437
    1538        /*Initialize output*/
    16         Vec uf = NULL;
    17 
    18         _error_("not implemented yet");
     39        Vector<IssmDouble>* out_uf=new Vector<IssmDouble>(uf0);
     40       
     41        /* Extract block matrices from the saddle point matrix */
     42        /* [ A   B ] = Kff
     43    * [ B^T 0 ]
     44         *         */
     45        #if (_PETSC_MAJOR_==3) && (_PETSC_MINOR_>=8)
     46        MatCreateSubMatrix(Kff,isv,isv,MAT_INITIAL_MATRIX,&A);
     47        MatCreateSubMatrix(Kff,isv,isp,MAT_INITIAL_MATRIX,&B);
     48        MatCreateSubMatrix(Kff,isp,isv,MAT_INITIAL_MATRIX,&BT);
     49        #else
     50        MatGetSubMatrix(Kff,isv,isv,MAT_INITIAL_MATRIX,&A);
     51        MatGetSubMatrix(Kff,isv,isp,MAT_INITIAL_MATRIX,&B);
     52        MatGetSubMatrix(Kff,isp,isv,MAT_INITIAL_MATRIX,&BT);
     53        #endif
     54       
     55        /* Extract preconditioner matrix on the pressure space*/
     56        #if (_PETSC_MAJOR_==3) && (_PETSC_MINOR_>=8)
     57        MatCreateSubMatrix(Kff,isp,isp,MAT_INITIAL_MATRIX,&IP);
     58        #else
     59        MatGetSubMatrix(Kff,isp,isp,MAT_INITIAL_MATRIX,&IP);
     60        #endif
     61
     62        /* Get number of velocity / pressure nodes */
     63        MatGetSize(B,&nu,&np);
     64
     65        /* Extract initial guesses for uold and pold */
     66        VecCreate(IssmComm::GetComm(),&p);VecSetSizes(p,PETSC_DECIDE,np);VecSetFromOptions(p);
     67        VecAssemblyBegin(p);VecAssemblyEnd(p);
     68        VecCreate(IssmComm::GetComm(),&uold);VecSetSizes(uold,PETSC_DECIDE,nu);VecSetFromOptions(uold);
     69        VecAssemblyBegin(uold);VecAssemblyEnd(uold);
     70
     71        VecGetSubVector(out_uf->pvector->vector,isv,&uold);
     72        VecGetSubVector(out_uf->pvector->vector,isp,&p);
     73
     74
     75        /* Set up intermediaries */
     76        VecDuplicate(uold,&f1);VecSet(f1,0.0);
     77        VecDuplicate(p,&f2);VecSet(f2,0.0);
     78        VecDuplicate(uold,&tmpu);VecSet(tmpu,0.0);
     79        VecDuplicate(p,&tmpp);VecSet(tmpp,0.0);
     80        VecDuplicate(p,&rhsp);VecSet(rhsp,0.0);
     81        VecDuplicate(uold,&rhsu);VecSet(rhsu,0.0);
     82        VecDuplicate(p,&gold);VecSet(gold,0.0);
     83        VecDuplicate(p,&wnew);VecSet(wnew,0.0);
     84        VecDuplicate(uold,&chi);VecSet(chi,0.0);
     85        VecDuplicate(p,&thetanew);VecSet(thetanew,0.0);
     86        VecDuplicate(p,&thetaold);VecSet(thetaold,0.0);
     87        VecDuplicate(p,&eta);VecSet(eta,0.0);
     88       
     89        /* Get global RHS (for each block sub-problem respectively)*/
     90        VecGetSubVector(pf,isv,&f1);
     91        VecGetSubVector(pf,isp,&f2);
     92
     93   /* ------------------------------------------------------------ */
     94
     95        /* Generate initial value for the velocity from the pressure */
     96        /* a(u0,v) = f1(v)-b(p0,v)  i.e.  Au0 = F1-Bp0 */
     97        /* u0 = u_DIR on \Gamma_DIR */
     98       
     99        /* Create KSP context */
     100        KSPCreate(IssmComm::GetComm(),&kspu);
     101        #if (_PETSC_MAJOR_==3) && (_PETSC_MINOR_>=5)
     102        KSPSetOperators(kspu,A,A);
     103        #else
     104        KSPSetOperators(kspu,A,A,DIFFERENT_NONZERO_PATTERN);
     105        #endif
     106        KSPSetType(kspu,KSPCG);
     107        KSPSetInitialGuessNonzero(kspu,PETSC_TRUE);
     108        //KSPSetTolerances(kspu,1e-12,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
     109        //KSPMonitorSet(kspu,KSPMonitorDefault,NULL,NULL);
     110        KSPGetPC(kspu,&pcu);
     111        PCSetType(pcu,PCSOR);
     112        KSPSetUp(kspu);
     113
     114       
     115        /* Create RHS */
     116        /* RHS = F1-B * pold */
     117        VecScale(p,-1.);MatMultAdd(B,p,f1,rhsu);VecScale(p,-1.);
     118
     119        /* Go solve Au0 = F1-Bp0*/
     120        KSPSolve(kspu,rhsu,uold);
     121       
     122
     123        /* Set up u_new */
     124        VecDuplicate(uold,&unew);VecCopy(uold,unew);
     125        VecAssemblyBegin(unew);VecAssemblyEnd(unew);
     126
     127
     128
     129        /* ------------------------------------------------------------- */
     130
     131        /*Get initial residual*/
     132        /*(1/mu(x) * g0, q) = b(q,u0) - (f2,q)  i.e.  IP * g0 = BT * u0 - F2*/
     133       
     134        /* Create KSP context */
     135        KSPCreate(IssmComm::GetComm(),&kspp);
     136        #if (_PETSC_MAJOR_==3) && (_PETSC_MINOR_>=5)
     137        KSPSetOperators(kspp,IP,IP);
     138        #else
     139        KSPSetOperators(kspp,IP,IP,DIFFERENT_NONZERO_PATTERN);
     140        #endif
     141       
     142        /* Create RHS */
     143        /* RHS = BT * uold - F2 */
     144        VecScale(f2,-1.);MatMultAdd(BT,uold,f2,rhsp);VecScale(f2,-1.);
     145
     146        /* Set KSP & PC options */
     147        KSPSetType(kspp,KSPCG);
     148        KSPSetInitialGuessNonzero(kspp,PETSC_TRUE);
     149        KSPGetPC(kspp,&pcp);
     150        PCSetType(pcp,PCJACOBI);
     151        /* Note: Systems in the pressure space are cheap, so we can afford a better tolerance */
     152        KSPSetTolerances(kspp,1e-10,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
     153        KSPSetUp(kspp);
     154       
     155        /* Go solve */
     156        KSPSolve(kspp,rhsp,gold);
     157       
     158        /*Initial residual*/
     159        VecNorm(gold,NORM_INFINITY,&initRnorm);
     160       
     161        /* Further setup */
     162        VecDuplicate(gold,&gnew);VecCopy(gold,gnew);
     163        VecAssemblyBegin(gnew);VecAssemblyEnd(gnew);
     164
     165
     166        /* ------------------------------------------------------------ */
     167
     168        /*Set initial search direction*/
     169        /*w0 = g0*/
     170        VecDuplicate(gold,&wold);VecCopy(gold,wold);
     171        VecAssemblyBegin(wold);VecAssemblyEnd(wold);
     172
     173        /*Realizing the step size part 1: thetam */
     174        /*IP * theta = BT * uold - F2*/
     175        VecScale(f2,-1.);MatMultAdd(BT,uold,f2,rhsp);VecScale(f2,-1.);
     176        KSPSolve(kspp,rhsp,thetaold);
     177
     178
     179        /* Count number of iterations */
     180        int count = 0;
     181
     182        /* CG iteration*/
     183        for(;;){
     184
     185                /*Realizing the step size part 2: chim */
     186                /*a(chim,v) = -b(wm,v)  i.e.  A * chim = -B * wm */
     187                /*chim_DIR = 0*/
     188                VecScale(wold,-1.);MatMult(B,wold,rhsu);VecScale(wold,-1.);
     189                KSPSolve(kspu,rhsu,chi);
     190
     191                /*Realizing the step size part 3: etam */
     192                MatMult(BT,chi,rhsp);
     193                KSPSolve(kspp,rhsp,eta);
     194       
     195                /* ---------------------------------------------------------- */
     196
     197
     198                /*Set step size*/
     199                /*rhom = [(wm)^T * IP^-1 * (BT * um - F2)]/[(wm)^T * IP^-1 * BT * chim]*/
     200                VecDot(wold,thetaold,&rho);
     201                VecDot(wold,eta,&tmpScalar);
     202                rho = rho/tmpScalar;
     203
     204
     205                /* ---------------------------------------------------------- */
     206
     207
     208                /*Pressure update*/
     209                /*p(m+1) = pm - rhom * wm*/
     210                VecAXPY(p,-1.*rho,wold);
     211
     212
     213                /*Velocity update*/
     214                /*u(m+1) = um - rhom * chim*/
     215                VecWAXPY(unew,-1.*rho,chi,uold);
     216
     217
     218                /* ---------------------------------------------------------- */
     219
     220                /*Theta update*/
     221                /*IP * theta = BT * uold - F2*/
     222                VecScale(f2,-1.);MatMultAdd(BT,unew,f2,rhsp);VecScale(f2,-1.);
     223                KSPSolve(kspp,rhsp,thetanew);
     224
     225
     226                /* ---------------------------------------------------------- */
     227
     228                /*Residual update*/
     229                /*g(m+1) = gm - rhom * BT * chim*/
     230                VecWAXPY(gnew,-1.*rho,eta,gold);
     231
     232                /* ---------------------------------------------------------- */
     233
     234
     235                /*BREAK if norm(g(m+0),2) < TOL or pressure space has been full searched*/
     236                VecNorm(gnew,NORM_INFINITY,&rnorm);
     237                if(rnorm < TOL*initRnorm)
     238                 break;
     239                else if(rnorm > 100*initRnorm)
     240                 _error_("Solver diverged. This shouldn't happen\n");
     241                //else
     242                // PetscPrintf(PETSC_COMM_WORLD,"rel. residual at step %d: %g, at TOL = %g\n",count,rnorm/initRnorm,TOL);
     243       
     244
     245
     246
     247                if(count > np-1) break;
     248       
     249
     250                /* ---------------------------------------------------------- */
     251
     252
     253                /*Directional update*/
     254                /*gamma = [g(m+1)^T * theta(m+1)]/[g(m)^T * thetam]*/
     255                VecDot(gnew,thetanew,&gamma);
     256                VecDot(gold,thetaold,&tmpScalar);
     257                gamma = gamma/tmpScalar;
     258
     259                /*w(m+1) = g(m+1) + gamma * w(m)*/
     260                VecWAXPY(wnew,gamma,wold,gnew);
     261
     262                /* Assign new to old iterates */
     263                VecCopy(wnew,wold);VecCopy(gnew,gold);VecCopy(unew,uold);VecCopy(thetanew,thetaold);
     264               
     265                count++;
     266        }
     267
     268
     269        /* Restore pressure and velocity sol. vectors to its global form */
     270        VecRestoreSubVector(out_uf->pvector->vector,isv,&unew);
     271        VecRestoreSubVector(out_uf->pvector->vector,isp,&p);
    19272
    20273        /*return output pointer*/
    21         Vector<IssmDouble>* out_uf=new Vector<IssmDouble>(uf);
    22         VecFree(&uf);
    23274        *puf=out_uf;
     275
     276
     277        /* Cleanup */
     278        KSPDestroy(&kspu);KSPDestroy(&kspp);
     279
     280        MatDestroy(&A);MatDestroy(&B);MatDestroy(&BT);MatDestroy(&IP);
     281       
     282        VecDestroy(&p);VecDestroy(&uold);VecDestroy(&unew);VecDestroy(&rhsu);VecDestroy(&rhsp);
     283        VecDestroy(&gold);VecDestroy(&gnew);VecDestroy(&wold);VecDestroy(&wnew);VecDestroy(&chi);
     284        VecDestroy(&tmpp);VecDestroy(&tmpu);VecDestroy(&f1);VecDestroy(&f2);VecDestroy(&eta);
     285        VecDestroy(&thetanew);VecDestroy(&thetaold);
     286
     287}/*}}}*/
     288void convergence_schurcg(bool* pconverged, Matrix<IssmDouble>* Kff,Vector<IssmDouble>* pf,Vector<IssmDouble>* uf,Vector<IssmDouble>* old_uf,IssmDouble eps_res,IssmDouble eps_rel,IssmDouble eps_abs,IS isv,IS isp){/*{{{*/
     289
     290        /*output*/
     291        bool converged=false;
     292
     293        /*intermediary*/
     294        //Vector<IssmDouble>* KU=NULL;
     295        //Vector<IssmDouble>* KUF=NULL;
     296        //Vector<IssmDouble>* KUold=NULL;
     297        //Vector<IssmDouble>* KUoldF=NULL;
     298        Vector<IssmDouble>* duf=NULL;
     299        IssmDouble ndu,nduinf,nu;
     300        IssmDouble nKUF;
     301        IssmDouble nKUoldF;
     302        IssmDouble nF;
     303        IssmDouble solver_residue,res;
     304        int analysis_type;
     305
     306        Mat A, B, BT;
     307        Vec u,p,uold,pold,f1,f2,tmp,res1,res2;
     308        int n_u,n_p;
     309        double rnorm1, rnorm2;
     310
     311
     312        if(VerboseModule()) _printf0_("   checking convergence\n");
     313
     314        /*If uf is NULL in input, f-set is nil, model is fully constrained, therefore converged from
     315         * the get go: */
     316        if(uf->IsEmpty()){
     317                *pconverged=true;
     318                return;
     319        }
     320
     321  /* Note: SchurCG also constructs the Schur preconditioner and stores it in the free block of Kff */
     322  /*                    [A    B]
     323        * Kff =  |      |
     324        *                       [B^T IP]
     325   * To calculate the residual, only the necessary blocks need to be extracted */
     326
     327                /*Extract A, B, B^T */
     328                #if (_PETSC_MAJOR_==3) && (_PETSC_MINOR_>=8)
     329                MatCreateSubMatrix(Kff->pmatrix->matrix,isv,isv,MAT_INITIAL_MATRIX,&A);
     330                MatCreateSubMatrix(Kff->pmatrix->matrix,isv,isp,MAT_INITIAL_MATRIX,&B);
     331                MatCreateSubMatrix(Kff->pmatrix->matrix,isp,isv,MAT_INITIAL_MATRIX,&BT);
     332                #else
     333                MatGetSubMatrix(Kff->pmatrix->matrix,isv,isv,MAT_INITIAL_MATRIX,&A);
     334                MatGetSubMatrix(Kff->pmatrix->matrix,isv,isp,MAT_INITIAL_MATRIX,&B);
     335                MatGetSubMatrix(Kff->pmatrix->matrix,isp,isv,MAT_INITIAL_MATRIX,&BT);
     336                #endif
     337       
     338                /*no. of free nodes in velocity/pressure space*/
     339                MatGetSize(B,&n_u,&n_p);
     340
     341                /*Extract values corresponding to the free velocity/pressure nodes*/
     342                VecCreate(IssmComm::GetComm(),&p);VecSetSizes(p,PETSC_DECIDE,n_p);VecSetFromOptions(p);
     343                VecAssemblyBegin(p);VecAssemblyEnd(p);
     344                VecCreate(IssmComm::GetComm(),&u);VecSetSizes(u,PETSC_DECIDE,n_u);VecSetFromOptions(u);
     345                VecAssemblyBegin(u);VecAssemblyEnd(u);
     346
     347                VecGetSubVector(uf->pvector->vector,isv,&u);
     348                VecGetSubVector(uf->pvector->vector,isp,&p);
     349               
     350
     351                /*Extract values of the RHS corresponding to the first/second block*/
     352                VecDuplicate(u,&f1);VecSet(f1,1.0);
     353                VecDuplicate(p,&f2);VecSet(f2,1.0);
     354                VecGetSubVector(pf->pvector->vector,isv,&f1);
     355                VecGetSubVector(pf->pvector->vector,isp,&f2);
     356
     357                /*Allocate intermediaries*/
     358                VecDuplicate(u,&res1);VecSet(res1,1.0);
     359                VecDuplicate(u,&tmp);VecSet(tmp,1.0);
     360                VecDuplicate(p,&res2);VecSet(res2,1.0);
     361
     362
     363        /*Display solver caracteristics*/
     364        if (VerboseConvergence()){
     365               
     366                /*Calculate res1 = A*u + B*p - f1*/
     367                VecScale(f1,-1.);MatMultAdd(A,u,f1,tmp);MatMultAdd(B,p,tmp,res1);VecScale(f1,-1.);
     368                /*Calculate res2 = B^T * u - f2*/
     369                VecScale(f2,-1.);MatMultAdd(BT,u,f2,res2);VecScale(f2,-1.);
     370
     371
     372                /*compute norm(res1), norm(res2), norm(F) and residue*/
     373                VecNorm(res1,NORM_2,&rnorm1);VecNorm(res2,NORM_2,&rnorm2);
     374                nKUF=sqrt(rnorm1*rnorm1 + rnorm2*rnorm2);
     375                nF=pf->Norm(NORM_TWO);
     376                solver_residue=nKUF/nF;
     377                _printf0_("\n" << "   solver residue: norm(KU-F)/norm(F)=" << solver_residue << "\n");
     378                if(xIsNan<IssmDouble>(solver_residue)){
     379                        //Kff->Echo();
     380                }
     381
     382        }
     383        /*clean up*/
     384        VecRestoreSubVector(uf->pvector->vector,isv,&u);
     385        VecRestoreSubVector(uf->pvector->vector,isp,&p);
     386       
     387        /*Extract values corresponding to velocity/pressure on the old solution*/
     388        VecGetSubVector(old_uf->pvector->vector,isv,&uold);
     389        VecGetSubVector(old_uf->pvector->vector,isp,&pold);
     390               
     391
     392        /*Force equilibrium (Mandatory)*/
     393
     394        /*Calculate res1 = A*uold + B*pold - f1*/
     395        VecScale(f1,-1.);MatMultAdd(A,uold,f1,tmp);MatMultAdd(B,pold,tmp,res1);VecScale(f1,-1.);
     396        /*Calculate res2 = B^T * uold - f2*/
     397        VecScale(f2,-1.);MatMultAdd(BT,uold,f2,res2);VecScale(f2,-1.);
     398       
     399        /*compute norm(res1), norm(res2), norm(F) and residue*/
     400        VecNorm(res1,NORM_2,&rnorm1);VecNorm(res2,NORM_2,&rnorm2);
     401        nKUoldF=sqrt(rnorm1*rnorm1 + rnorm2*rnorm2);
     402        nF=pf->Norm(NORM_TWO);
     403        res=nKUoldF/nF;
     404        if (xIsNan<IssmDouble>(res)){
     405                _printf0_("norm nf = " << nF << "f and norm kuold = " << nKUoldF << "f\n");
     406                _error_("mechanical equilibrium convergence criterion is NaN!");
     407        }
     408
     409        MatDestroy(&A);MatDestroy(&B);MatDestroy(&BT);
     410        VecRestoreSubVector(pf->pvector->vector,isv,&f1);
     411        VecRestoreSubVector(pf->pvector->vector,isp,&f2);
     412        VecDestroy(&res1);VecDestroy(&res2);VecDestroy(&tmp);
     413        VecRestoreSubVector(old_uf->pvector->vector,isv,&uold);
     414        VecRestoreSubVector(old_uf->pvector->vector,isp,&pold);
     415       
     416
     417
     418        //print
     419        if(res<eps_res){
     420                if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   mechanical equilibrium convergence criterion"<<res*100<< " < "<<eps_res*100<<" %\n");
     421                converged=true;
     422        }
     423        else{
     424                if(VerboseConvergence()) _printf0_(setw(50)<<left<<"   mechanical equilibrium convergence criterion"<<res*100<<" > "<<eps_res*100<<" %\n");
     425                converged=false;
     426        }
     427
     428        /*Relative criterion (optional)*/
     429        if (!xIsNan<IssmDouble>(eps_rel) || (VerboseConvergence())){
     430
     431                //compute norm(du)/norm(u)
     432                duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
     433                ndu=duf->Norm(NORM_TWO); nu=old_uf->Norm(NORM_TWO);
     434
     435                if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
     436
     437                //clean up
     438                delete duf;
     439
     440                //print
     441                if (!xIsNan<IssmDouble>(eps_rel)){
     442                        if((ndu/nu)<eps_rel){
     443                                if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " < " << eps_rel*100 << " %\n");
     444                        }
     445                        else{
     446                                if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " > " << eps_rel*100 << " %\n");
     447                                converged=false;
     448                        }
     449                }
     450                else _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " %\n");
     451
     452        }
     453
     454        /*Absolute criterion (Optional) = max(du)*/
     455        if (!xIsNan<IssmDouble>(eps_abs) || (VerboseConvergence())){
     456
     457                //compute max(du)
     458                duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
     459                ndu=duf->Norm(NORM_TWO); nduinf=duf->Norm(NORM_INF);
     460                if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
     461
     462                //clean up
     463                delete duf;
     464
     465                //print
     466                if (!xIsNan<IssmDouble>(eps_abs)){
     467                        if ((nduinf)<eps_abs){
     468                                if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf << " < " << eps_abs << "\n");
     469                        }
     470                        else{
     471                                if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf << " > " << eps_abs << "\n");
     472                                converged=false;
     473                        }
     474                }
     475                else  _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf << "\n");
     476
     477        }
     478
     479        /*assign output*/
     480        *pconverged=converged;
    24481}/*}}}*/
    25482void solutionsequence_schurcg(FemModel* femmodel){/*{{{*/
     
    32489        Vector<IssmDouble>* old_uf = NULL;
    33490        Vector<IssmDouble>* pf  = NULL;
    34         Vector<IssmDouble>* pf0 = NULL;
    35491        Vector<IssmDouble>* df  = NULL;
    36492        Vector<IssmDouble>* ys  = NULL;
    37         Matrix<IssmDouble>* Mff = NULL;
     493
    38494
    39495        /*parameters:*/
     
    49505        femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    50506        femmodel->UpdateConstraintsx();
    51 
     507        int size;
    52508        int  count=0;
    53509        bool converged=false;
     
    69525                /*Get stiffness matrix and Load vector*/
    70526                SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
    71                 pf0=pf->Duplicate(); pf->Copy(pf0);
    72527                CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
    73528                Reduceloadx(pf, Kfs, ys); delete Kfs;
    74529
    75530                /*Create mass matrix*/
    76                 int fsize; Kff->GetSize(&fsize,&fsize);
    77                 Mff=new Matrix<IssmDouble>(fsize,fsize,100,4);
    78531                StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
    79532                /*Get complete stiffness matrix without penalties*/
    80533                for(int i=0;i<femmodel->elements->Size();i++){
    81534                        Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
    82                         ElementMatrix* Me = analysis->CreatePressureMassMatrix(element);
    83                         if(Me) Me->AddToGlobal(Mff,NULL);
    84                         delete Me;
     535                        ElementMatrix* Ie = analysis->CreateSchurPrecondMatrix(element);
     536                        if(Ie) Ie->AddToGlobal(Kff,NULL);
     537                        delete Ie;
    85538                }
    86                 Mff->Assemble();
     539                Kff->Assemble();
    87540                delete analysis;
     541
     542                /*Obtain index sets for velocity and pressure components */
     543                IS isv = NULL;
     544                IS isp = NULL;
     545                #if _PETSC_MAJOR_==3
     546                        /*Make indices out of doftypes: */
     547                        if(!(df->pvector->vector))_error_("need doftypes for FS solver!\n");
     548                        DofTypesToIndexSet(&isv,&isp,df->pvector->vector,FSSolverEnum);
     549                #else
     550                        _error_("Petsc 3.X required");
     551                #endif
     552
    88553
    89554                /*Solve*/
    90555                femmodel->profiler->Start(SOLVER);
    91556                _assert_(Kff->type==PetscMatType);
     557               
    92558                SchurCGSolver(&uf,
    93559                                        Kff->pmatrix->matrix,
    94                                         Mff->pmatrix->matrix,
    95560                                        pf->pvector->vector,
    96561                                        old_uf->pvector->vector,
    97                                         df->pvector->vector,
     562                                        isv,
     563                                        isp,
    98564                                        femmodel->parameters);
    99565                femmodel->profiler->Stop(SOLVER);
    100                 delete pf0; delete Mff;
     566       
    101567
    102568                /*Merge solution from f set to g set*/
     
    104570
    105571                /*Check for convergence and update inputs accordingly*/
    106                 convergence(&converged,Kff,pf,uf,old_uf,eps_res,eps_rel,eps_abs); delete Kff; delete pf; delete df;
     572                convergence_schurcg(&converged,Kff,pf,uf,old_uf,eps_res,eps_rel,eps_abs,isv,isp); delete Kff; delete pf; delete df;
    107573                count++;
     574
    108575                if(count>=max_nonlinear_iterations){
    109576                        _printf0_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded\n");
     
    128595
    129596}/*}}}*/
     597
    130598#else
    131599void solutionsequence_schurcg(FemModel* femmodel){_error_("PETSc needs to be installed");}
  • issm/trunk/src/c/toolkits/gsl/DenseGslSolve.cpp

    r21729 r23394  
    1414#include "../../classes/Params/Parameters.h"
    1515#include "../adolc/adolcincludes.h"
     16#include "../codipack/codipackincludes.h"
    1617#include "./gslincludes.h"
    1718
     
    251252/*}}}*/
    252253#endif
     254
     255#ifdef _HAVE_CODIPACK_
     256void SolverxSeq_codi_b(void* tape_in,void* data_in,void* ra) {/*{{{*/
     257
     258        /*recast data_in and tape*/
     259        codi::DataStore* data = (codi::DataStore*)data_in;
     260        //IssmDouble::TapeType& tape = (IssmDouble::TapeType&)tape_in;
     261        IssmDouble::TapeType& tape = IssmDouble::getGlobalTape();
     262
     263  IssmDouble::Real* valueATrans;
     264  IssmDouble::GradientData* indexATrans;
     265  IssmDouble::GradientData* indexB;
     266  IssmDouble::Real* valueX;
     267  IssmDouble::GradientData* indexX;
     268  int n;
     269
     270  data->getData(valueATrans);
     271  data->getData(indexATrans);
     272  data->getData(indexB);
     273  data->getData(valueX);
     274  data->getData(indexX);
     275  data->getData(n);
     276
     277
     278  // create the adjoint vector for x and reset the adjoint values on the tape
     279  IssmDouble::GradientValue* adjX = xNew<IssmDouble::GradientValue>(n);
     280  getVectorAdjoint(tape, indexX, adjX, n);
     281
     282  IssmDouble::GradientValue* sol  = xNew<IssmDouble::GradientValue>(n);
     283  SolverxSeq(sol, valueATrans, adjX, n);
     284
     285  updateVectorAdjoint(tape, indexB, sol, n);
     286  for(int i=0; i<n; ++i) {
     287    for (int j=0; j<n; ++j) {
     288      // we access the transposed matrix here because we stored the indices in a transposed way
     289      updateAdjoint(tape, indexATrans[i*n+j], -sol[j]*valueX[i]);
     290    }
     291  }
     292
     293  xDelete(sol);
     294  xDelete(adjX);
     295}
     296/*}}}*/
     297void SolverxSeq_codi_delete(void* tape_in,void* data_in) {/*{{{*/
     298
     299        /*recast data_in*/
     300        codi::DataStore* data = (codi::DataStore*)data_in;
     301
     302  IssmDouble::Real* valueATrans;
     303  IssmDouble::GradientData* indexATrans;
     304  IssmDouble::GradientData* indexB;
     305  IssmDouble::Real* valueX;
     306  IssmDouble::GradientData* indexX;
     307  int n;
     308
     309  data->getData(valueATrans);
     310  data->getData(indexATrans);
     311  data->getData(indexB);
     312  data->getData(valueX);
     313  data->getData(indexX);
     314  data->getData(n);
     315
     316  xDelete(valueATrans);
     317  xDelete(indexATrans);
     318  xDelete(indexB);
     319  xDelete(valueX);
     320  xDelete(indexX);
     321}
     322/*}}}*/
     323void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters){/*{{{*/
     324  IssmDouble::TapeType& tape = IssmDouble::getGlobalTape();
     325  codi::DataStore* dataHandler = NULL;
     326
     327  if(tape.isActive()) {
     328    dataHandler = new codi::DataStore();
     329
     330    // create the index vector and the double data for A and B
     331    IssmDouble::Real* valueATrans = xNew<IssmDouble::Real>(n*n);
     332    IssmDouble::GradientData* indexATrans = xNew<IssmDouble::GradientData>(n*n);
     333
     334    // read the data for matrix in a transposed fashion
     335          for (int i=0; i<n; ++i) {
     336      for (int j=0; j<n; ++j) {
     337        getPrimalAndGradData(A[i*n+j], valueATrans[j*n+i], indexATrans[j*n+i]);
     338      }
     339    }
     340
     341    // read the data from B (primal values are not required vor B
     342    IssmDouble::GradientData* indexB = xNew<IssmDouble::GradientData>(n);
     343    getVectorGradData(B, indexB, n);
     344
     345    dataHandler->addData(valueATrans);
     346    dataHandler->addData(indexATrans);
     347    dataHandler->addData(indexB);
     348  }
     349
     350  // unpack the primal values from the matrix and the vector
     351  IssmDouble::Real* valueA = xNew<IssmDouble::Real>(n*n);
     352  IssmDouble::Real* valueB = xNew<IssmDouble::Real>(n);
     353  // read the data from A and B
     354  getVectorPrimal(A, valueA, n*n);
     355  getVectorPrimal(B, valueB, n);
     356
     357  // create the placeholder for X and solve the system
     358  IssmDouble::Real* valueX = xNew<IssmDouble::Real>(n);
     359  SolverxSeq(valueX, valueA, valueB, n);
     360
     361  // pack the values into x
     362  setVectorPrimal(X, valueX, n);
     363
     364  if(tape.isActive()) {
     365    // create the index vector X and register x as active variables
     366    IssmDouble::GradientData* indexX = xNew<IssmDouble::GradientData>(n);
     367    registerVector(X, indexX, n);
     368
     369    dataHandler->addData(valueX);
     370    dataHandler->addData(indexX);
     371
     372    // store other arguments
     373    dataHandler->addData(n);
     374
     375    tape.pushExternalFunctionHandle(&SolverxSeq_codi_b, dataHandler, &SolverxSeq_codi_delete);
     376  } else {
     377    // if the tape is active valueX is stored in the dataHandler and deleted in the reverse sweep
     378    xDelete(valueX);
     379  }
     380
     381  xDelete(valueB);
     382  xDelete(valueA);
     383}
     384/*}}}*/
     385void DenseGslSolve(/*output*/ IssmDouble** px,/*stiffness matrix:*/ IssmDouble* Kff, int Kff_M, int Kff_N, /*right hand side load vector: */ IssmDouble* pf, int pf_M, Parameters* parameters){ /*{{{*/
     386
     387        /*Intermediary: */
     388
     389        if(Kff_N!=pf_M)_error_("Right hand side vector of size " << pf_M << ", when matrix is of size " << Kff_M << "-" << Kff_N << " !");
     390        if(Kff_M!=Kff_N)_error_("Stiffness matrix should be square!");
     391
     392        IssmDouble *x  = xNew<IssmDouble>(Kff_N,"t");
     393
     394        SolverxSeq(x,Kff,pf,Kff_N,parameters);
     395
     396        /*allocate output pointers: */
     397        *px=x;
     398}
     399/*}}}*/
     400#endif
  • issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp

    r16560 r23394  
    8686int IssmSolverTypeFromToolkitOptions(void){ /*{{{*/
    8787
    88         char* solver_type=NULL;
    8988        int   solver_type_enum;
    90         int   num_procs=0;
    9189        bool  isparallel=false;
    9290
    9391        /*first, figure out if we are running in parallel: */
    94         num_procs=IssmComm::GetSize();
     92        int num_procs=IssmComm::GetSize();
    9593        if(num_procs>1)isparallel=true;
    9694
    9795        /*retrieve solver type as a string, from the Toolkits Options database, similar to what Petsc does. Actually,
    9896         *we try and stick with the Petsc vector types: */
    99         solver_type=ToolkitOptions::GetToolkitOptionValue("solver_type");
     97        char* solver_type=ToolkitOptions::GetToolkitOptionValue("solver_type");
     98        if(!solver_type) _error_("Solver not set");
    10099
    101100        if (strcmp(solver_type,"mumps")==0){
  • issm/trunk/src/c/toolkits/mpi/issmmpi.cpp

    r20500 r23394  
    4242  assert(sendcount==recvcount || sendtype==recvtype); // we handle only identical representations
    4343#ifdef _HAVE_MPI_
    44 # ifdef _HAVE_AMPI_
     44#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    4545  rc=AMPI_Allgather(sendbuf,
    4646                    sendcount,
     
    6060# endif
    6161#else
    62 # ifdef _HAVE_ADOLC_
     62# ifdef _HAVE_AD_
    6363  if (sendtype==ISSM_MPI_DOUBLE) {
    6464    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
     
    7676  assert(sendtype==recvtype); // we handle only identical representations
    7777#ifdef _HAVE_MPI_
    78 # ifdef _HAVE_AMPI_
     78#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    7979  rc=AMPI_Allgatherv(sendbuf,
    8080                     sendcount,
     
    9797#else
    9898  assert(sendcount==recvcounts[0]); // we handle only identical representations
    99 # ifdef _HAVE_ADOLC_
     99# ifdef _HAVE_AD_
    100100  if (sendtype==ISSM_MPI_DOUBLE) {
    101101    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
     
    113113  int rc=0;
    114114#ifdef _HAVE_MPI_
    115 # ifdef _HAVE_AMPI_
     115#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    116116  rc=AMPI_Allreduce(sendbuf,
    117117                    recvbuf,
     
    129129# endif
    130130#else
    131 # ifdef _HAVE_ADOLC_
     131#ifdef _HAVE_AD_
    132132  if (datatype==ISSM_MPI_DOUBLE) {
    133133    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
     
    145145  int rc=0;
    146146#ifdef _HAVE_MPI_
    147 # ifdef _HAVE_AMPI_
     147#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    148148  rc=AMPI_Barrier(comm);
    149149# else
     
    159159  int rc=0;
    160160#ifdef _HAVE_MPI_
    161 # ifdef _HAVE_AMPI_
     161#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    162162  rc=AMPI_Bcast(buffer,
    163163                count,
     
    181181  int rc=0;
    182182#ifdef _HAVE_MPI_
    183 # ifdef _HAVE_AMPI_
     183#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    184184  assert(0); // to be implemented
    185185# else
     
    215215int ISSM_MPI_Finalize(void){  /*{{{*/
    216216
    217   int rc=0;
    218 #ifdef _HAVE_MPI_
    219 # ifdef _HAVE_AMPI_
    220   rc=AMPI_Finalize_NT();
    221 # else
    222   rc=MPI_Finalize();
    223 # endif
    224 #endif
     217        int rc=0;
     218        #ifdef _HAVE_MPI_
     219                #if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
     220                        #if defined(_HAVE_ADJOINTMPI_)
     221                                rc=AMPI_Finalize();
     222                        #elif defined(_HAVE_MEDIPACK_)
     223                                TOOL::finalize();
     224                                rc=AMPI_Finalize();
     225                        #else
     226                                rc=AMPI_Finalize_NT();
     227                        #endif
     228                #else
     229                  rc=MPI_Finalize();
     230                #endif
     231        #endif
    225232  return rc;
    226233}/*}}}*/
     
    230237  assert(sendtype==recvtype && sendcnt==recvcnt); // we handle only identical representations
    231238#ifdef _HAVE_MPI_
    232 # ifdef _HAVE_AMPI_
     239#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    233240  rc=AMPI_Gather(sendbuf,
    234241                 sendcnt,
     
    250257# endif
    251258#else
    252 # ifdef _HAVE_ADOLC_
     259# ifdef _HAVE_AD_
    253260  if (sendtype==ISSM_MPI_DOUBLE) {
    254261    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
     
    267274  assert(sendtype==recvtype); // we handle only identical representations
    268275#ifdef _HAVE_MPI_
    269 # ifdef _HAVE_AMPI_
     276#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    270277  rc=AMPI_Gatherv(sendbuf,
    271278                  sendcnt,
     
    290297#else
    291298  assert(sendcnt==recvcnts[0]); // we handle only identical representations
    292 # ifdef _HAVE_ADOLC_
     299#ifdef _HAVE_AD_
    293300  if (sendtype==ISSM_MPI_DOUBLE) {
    294301    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
     
    304311int ISSM_MPI_Init(int *argc, char ***argv){  /*{{{*/
    305312
    306   int rc=0;
    307 #ifdef _HAVE_MPI_
    308 # ifdef _HAVE_AMPI_
    309   rc=AMPI_Init_NT(argc,argv);
    310 # else
    311   rc=MPI_Init(argc,argv);
    312 # endif
    313 #endif
     313        int rc=0;
     314        #ifdef _HAVE_MPI_
     315                #if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
     316                        #if defined(_HAVE_ADJOINTMPI_)
     317                                rc=AMPI_Init(argc,argv);
     318                        #elif defined(_HAVE_MEDIPACK_)
     319                                rc=AMPI_Init(argc,argv);
     320                                TOOL::init();
     321                        #else
     322                                rc=AMPI_Init_NT(argc,argv);
     323                        #endif
     324                #else
     325                        rc=MPI_Init(argc,argv);
     326                #endif
     327        #endif
    314328  return rc;
    315329}/*}}}*/
     
    318332  int rc=0;
    319333#ifdef _HAVE_MPI_
    320 # ifdef _HAVE_AMPI_
     334#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    321335  rc=AMPI_Recv(buf,
    322336               count,
     
    324338               source,
    325339               tag,
     340                         #if !defined(_HAVE_ADJOINTMPI_) && !defined(_HAVE_MEDIPACK_)
    326341               AMPI_FROM_SEND, // as long as there are no other variants
     342                         #endif
    327343               comm,
    328344               status);
     
    347363  int rc=0;
    348364#ifdef _HAVE_MPI_
    349 # ifdef _HAVE_AMPI_
     365#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    350366  rc=AMPI_Reduce(sendbuf,
    351367                 recvbuf,
     
    365381# endif
    366382#else
    367 # ifdef _HAVE_ADOLC_
     383# ifdef _HAVE_AD_
    368384  if (datatype==ISSM_MPI_DOUBLE) {
    369385    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
     
    382398  assert(sendtype==recvtype && sendcnt==recvcnt); // we handle only identical representations
    383399#ifdef _HAVE_MPI_
    384 # ifdef _HAVE_AMPI_
     400#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    385401  rc=AMPI_Scatter(sendbuf,
    386402                  sendcnt,
     
    402418# endif
    403419#else
    404 # ifdef _HAVE_ADOLC_
     420# ifdef _HAVE_AD_
    405421  if (sendtype==ISSM_MPI_DOUBLE) {
    406422    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
     
    419435  assert(sendtype==recvtype); // we handle only identical representations
    420436#ifdef _HAVE_MPI_
    421 # ifdef _HAVE_AMPI_
     437#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    422438  rc=AMPI_Scatterv(sendbuf,
    423439                   sendcnts,
     
    442458#else
    443459  assert(sendcnts[0]==recvcnt); // we handle only identical representations
    444 # ifdef _HAVE_ADOLC_
     460# ifdef _HAVE_AD_
    445461  if (sendtype==ISSM_MPI_DOUBLE) {
    446462    IssmDouble* activeSendBuf=(IssmDouble*)(sendbuf)+displs[0];
     
    458474  int rc=0;
    459475#ifdef _HAVE_MPI_
    460 # ifdef _HAVE_AMPI_
     476#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    461477  rc=AMPI_Send(buf,
    462478               count,
     
    464480               dest,
    465481               tag,
     482                         #if !defined(_HAVE_ADJOINTMPI_) && !defined(_HAVE_MEDIPACK_)
    466483               AMPI_TO_RECV, // as long as there are no other variants
     484                         #endif
    467485               comm);
    468486# else
     
    492510#ifdef _HAVE_ADOLC_
    493511  ensureContiguousLocations(aSize);
     512#else
     513  fprintf(stderr, "*** Codipack ISSM_MPI_ContiguousInAdolc()\n");
    494514#endif
    495515}/*}}}*/
     
    498518int rc=0;
    499519#ifdef _HAVE_MPI_
    500 #ifdef _HAVE_AMPI_
     520#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    501521rc=MPI_Comm_split(comm, color, key, newcomm);
    502522#else
     
    512532        int rc=0;
    513533#ifdef _HAVE_MPI_
    514 #ifdef _HAVE_AMPI_
     534#if defined(_HAVE_AMPI_) &&  !defined(_WRAPPERS_)
    515535        rc=MPI_Intercomm_create(comm,local_leader,peer_comm,remote_leader,tag,newintercomm);
    516536#else
  • issm/trunk/src/c/toolkits/mpi/issmmpi.h

    r22758 r23394  
    1616#include "../../shared/Numerics/types.h"
    1717
    18 #ifdef _HAVE_MPI_
     18#if defined(_HAVE_MPI_)
    1919        /*Include header files: {{{*/
    20         #ifdef _HAVE_AMPI_
    21                 #include <ampi/ampi.h>
     20        #if defined(_HAVE_AMPI_) && !defined(_WRAPPERS_)
     21                #if defined(_HAVE_ADJOINTMPI_)
     22                        #include <ampi_tape.hpp>
     23
     24                #elif defined(_HAVE_MEDIPACK_)
     25                        #include "medi/medi.hpp"
     26                        using namespace medi;
     27                        #include "medi/codiMediPackTypes.hpp"
     28                        #if defined(_HAVE_CODIPACK_)
     29                        #define TOOL CoDiPackTool<IssmDouble>
     30                        #define AMPI_ADOUBLE TOOL::MPI_TYPE
     31                        #elif defined(_HAVE_ADOLC_)
     32                        #include "adolc/medipacksupport.h"
     33                        #define TOOL AdolcTool
     34                        #else
     35                        #error "don't know about AD tool"
     36                        #endif
     37
     38                #else
     39                        #include <ampi/ampi.h>
     40                #endif
    2241        #elif  _HAVE_PETSC_MPI_ // Petsc now hides there MPI header. It can be reached through Petsc.
    2342                #include <petsc.h>
     
    2746        /*}}}*/
    2847        /*MPI defines: *{{{*/
     48
    2949        // types
     50        #if defined(_HAVE_MEDIPACK_) && !defined(_WRAPPERS_)
     51        typedef AMPI_Comm             ISSM_MPI_Comm;
     52        typedef AMPI_Datatype         ISSM_MPI_Datatype;
     53        typedef AMPI_Op               ISSM_MPI_Op;
     54        typedef AMPI_Status           ISSM_MPI_Status;
     55        #else
    3056        typedef MPI_Comm             ISSM_MPI_Comm;
    3157        typedef MPI_Datatype         ISSM_MPI_Datatype;
    3258        typedef MPI_Op               ISSM_MPI_Op;
    3359        typedef MPI_Status           ISSM_MPI_Status;
     60        #endif
    3461
    35         // data types
    36         #define ISSM_MPI_CHAR       MPI_CHAR
    37         #ifdef _HAVE_AMPI_
    38                 #define ISSM_MPI_DOUBLE    AMPI_ADOUBLE // corresponds to IssmDouble
    39         #else
    40                 #define ISSM_MPI_DOUBLE    MPI_DOUBLE  // corresponds to IssmDouble
     62        #if defined(_HAVE_MEDIPACK_) && !defined(_WRAPPERS_)
     63        #define ISSM_MPI_CHAR       AMPI_CHAR
     64        #define ISSM_MPI_DOUBLE     AMPI_ADOUBLE // corresponds to IssmDouble
     65        #define ISSM_MPI_PDOUBLE    AMPI_DOUBLE  // corresponds to IssmPDouble
     66        #define ISSM_MPI_INT        AMPI_INT
     67       
     68        // operations
     69        #define ISSM_MPI_MAX        AMPI_MAX
     70        #define ISSM_MPI_MIN        AMPI_MIN
     71        #define ISSM_MPI_PROD       AMPI_PROD
     72        #define ISSM_MPI_SUM        AMPI_SUM
     73       
     74        // others
     75        #define ISSM_MPI_COMM_WORLD    AMPI_COMM_WORLD
     76        #define ISSM_MPI_STATUS_IGNORE AMPI_STATUS_IGNORE
     77        #define ISSM_MPI_ANY_TAG       AMPI_ANY_TAG
     78        #define ISSM_MPI_ANY_SOURCE    AMPI_ANY_SOURCE
     79
     80        #else
     81                #if defined(_HAVE_AMPI_) && !defined(_WRAPPERS_)
     82                        #define ISSM_MPI_DOUBLE    AMPI_ADOUBLE
     83                #else
     84                        #define ISSM_MPI_DOUBLE    MPI_DOUBLE
     85                #endif
     86                #define ISSM_MPI_PDOUBLE    MPI_DOUBLE
     87                #define ISSM_MPI_INT        MPI_INT
     88                #define ISSM_MPI_CHAR       MPI_CHAR
     89
     90                // operations
     91                #define ISSM_MPI_MAX        MPI_MAX
     92                #define ISSM_MPI_MIN        MPI_MIN
     93                #define ISSM_MPI_PROD       MPI_PROD
     94                #define ISSM_MPI_SUM        MPI_SUM
     95
     96                // others
     97                #define ISSM_MPI_COMM_WORLD    MPI_COMM_WORLD
     98                #define ISSM_MPI_STATUS_IGNORE MPI_STATUS_IGNORE
     99                #define ISSM_MPI_ANY_TAG       MPI_ANY_TAG
     100                #define ISSM_MPI_ANY_SOURCE    MPI_ANY_SOURCE
    41101        #endif
    42         #define ISSM_MPI_PDOUBLE    MPI_DOUBLE  // corresponds to IssmPDouble
    43         #define ISSM_MPI_INT        MPI_INT
    44 
    45         // operations
    46         #define ISSM_MPI_MAX        MPI_MAX
    47         #define ISSM_MPI_MIN        MPI_MIN
    48         #define ISSM_MPI_PROD       MPI_PROD
    49         #define ISSM_MPI_SUM        MPI_SUM
    50 
    51         // others
    52         #define ISSM_MPI_COMM_WORLD    MPI_COMM_WORLD
    53         #define ISSM_MPI_STATUS_IGNORE MPI_STATUS_IGNORE
    54         #define ISSM_MPI_ANY_TAG       MPI_ANY_TAG
    55         #define ISSM_MPI_ANY_SOURCE    MPI_ANY_SOURCE
    56102
    57103    /*other include files: */
     
    90136template <class T> ISSM_MPI_Datatype TypeToMPIType(){assert(false);};
    91137template <> inline ISSM_MPI_Datatype TypeToMPIType<IssmDouble>(){return ISSM_MPI_DOUBLE;};
    92 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
     138#if defined(_HAVE_AD_) && !defined(_WRAPPERS_)
    93139template <> inline ISSM_MPI_Datatype TypeToMPIType<IssmPDouble>(){return ISSM_MPI_PDOUBLE;};
    94140#endif
  • issm/trunk/src/c/toolkits/mumps/MumpsSolve.cpp

    r23189 r23394  
    1818#include "../mpi/issmmpi.h"
    1919#include "../adolc/adolcincludes.h"
     20#include "../codipack/codipackincludes.h"
    2021#include "../issm/SparseRow.h"
    2122#include "./mumpsincludes.h"
     
    2526
    2627void MumpsInit(DMUMPS_STRUC_C &theMumpsStruc){
     28        theMumpsStruc.n = 0;
     29        theMumpsStruc.nz = 0;
     30        theMumpsStruc.a = NULL;
     31        theMumpsStruc.jcn = NULL;
     32        theMumpsStruc.irn = NULL;
    2733        theMumpsStruc.par          = 1; 
    2834        theMumpsStruc.sym          = 0;
     
    98104}
    99105
    100 #ifdef _HAVE_ADOLC_
     106#ifdef _HAVE_AD_
    101107// prototype for active variant
    102108void MumpsSolve(int n,
     
    354360
    355361#ifdef _HAVE_ADOLC_
    356 
    357 int mumpsSolveEDF(int iArrLength, int* iArr, int /* ignored */, IssmPDouble* dp_x, int /* ignored */, IssmPDouble* dp_y) {
     362int mumpsSolveEDF(int iArrLength, int* iArr, int /* ignored */, IssmPDouble* dp_x, int /* ignored */, IssmPDouble* dp_y){/*{{{*/
    358363  // unpack parameters
    359364  int n=iArr[0];
     
    381386  xDelete(local_irn);
    382387  return 0;
    383 }
    384 
    385 void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc,IssmDouble *a_loc,IssmDouble *rhs,Parameters* parameters){
     388}/*}}}*/
     389void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc,IssmDouble *a_loc,IssmDouble *rhs,Parameters* parameters){/*{{{*/
    386390  int packedDimsSparseArrLength=1+1+1+local_nnz+local_nnz;
    387391  int *packedDimsSparseArr=xNew<int>(packedDimsSparseArrLength);
     
    425429  xDelete(pack_A_rhs);
    426430  xDelete(packedDimsSparseArr);
    427 }
    428 
    429 int fos_reverse_mumpsSolveEDF(int iArrLength, int* iArr,
    430                               int m, IssmPDouble *dp_U,
    431                               int nPlusNz, IssmPDouble *dp_Z,
    432                               IssmPDouble *dp_x, IssmPDouble *dp_y) {
     431}/*}}}*/
     432int fos_reverse_mumpsSolveEDF(int iArrLength, int* iArr, int m, IssmPDouble *dp_U, int nPlusNz, IssmPDouble *dp_Z, IssmPDouble *dp_x, IssmPDouble *dp_y) {/*{{{*/
    433433  // unpack parameters
    434434  int n=iArr[0];
     
    481481  xDelete(local_irn);
    482482  return 3;
    483 }
    484 
    485 #endif
     483}/*}}}*/
     484#endif
     485
     486#ifdef _HAVE_CODIPACK_
     487void MumpsSolve_codi_b(void* tape_in,void* data_in,void* ra) {/*{{{*/
     488
     489        /*recast data_in and tape*/
     490  codi::DataStore* data = (codi::DataStore*)data_in;
     491  //IssmDouble::TapeType& tape = (IssmDouble::TapeType&)tape_in;
     492  IssmDouble::TapeType& tape = IssmDouble::getGlobalTape();
     493
     494
     495  IssmDouble::Real* valueATrans;
     496  IssmDouble::GradientData* indexATrans;
     497  int* irnATrans;
     498  int* jcnATrans;
     499  IssmDouble::GradientData* indexB;
     500  IssmDouble::Real* valueX;
     501  IssmDouble::GradientData* indexX;
     502  int n;
     503  int nnz;
     504  int local_nnz;
     505  Parameters* parameters;
     506
     507  data->getData(valueATrans);
     508  data->getData(indexATrans);
     509  data->getData(irnATrans);
     510  data->getData(jcnATrans);
     511  data->getData(indexB);
     512  data->getData(valueX);
     513  data->getData(indexX);
     514  data->getData(n);
     515  data->getData(nnz);
     516  data->getData(local_nnz);
     517  data->getData(parameters);
     518
     519  // create the adjoint vector for x and reset the adjoint values on the tape
     520  IssmDouble::GradientValue* adjX = xNew<IssmDouble::GradientValue>(n);
     521  getVectorAdjoint(tape, indexX, adjX, n);
     522
     523  MumpsSolve(n, nnz, local_nnz, irnATrans, jcnATrans, valueATrans, adjX, parameters);
     524  // adjX contains now the solution
     525
     526  updateVectorAdjoint(tape, indexB, adjX, n);
     527
     528  // bcast dp_y (the solution of the forward system)
     529  ISSM_MPI_Bcast(valueX,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
     530  // bcast the adjoint of the right-hand-side, i.e. this solution
     531  ISSM_MPI_Bcast(adjX,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
     532
     533  for(int i=0; i<local_nnz; ++i) {
     534    // we access the transposed matrix here because we stored the indices in a transposed way
     535    // -1 is substracted because jcn and irn are stored with fortran indexing
     536    updateAdjoint(tape, indexATrans[i], -adjX[jcnATrans[i]-1]*valueX[irnATrans[i]-1]);
     537  }
     538
     539  xDelete(adjX);
     540}
     541/*}}}*/
     542void MumpsSolve_codi_delete(void* tape_in,void* data_in) {/*{{{*/
     543
     544        /*recast data_in*/
     545        codi::DataStore* data = (codi::DataStore*)data_in;
     546
     547  IssmDouble::Real* valueATrans;
     548  IssmDouble::GradientData* indexATrans;
     549  int* irnATrans;
     550  int* jcnATrans;
     551  IssmDouble::GradientData* indexB;
     552  IssmDouble::Real* valueX;
     553  IssmDouble::GradientData* indexX;
     554  int n;
     555  int nnz;
     556  int local_nnz;
     557  Parameters* parameters;
     558
     559  data->getData(valueATrans);
     560  data->getData(indexATrans);
     561  data->getData(irnATrans);
     562  data->getData(jcnATrans);
     563  data->getData(indexB);
     564  data->getData(valueX);
     565  data->getData(indexX);
     566  data->getData(n);
     567  data->getData(nnz);
     568  data->getData(local_nnz);
     569  data->getData(parameters);
     570
     571  xDelete(valueATrans);
     572  xDelete(indexATrans);
     573  xDelete(irnATrans);
     574  xDelete(jcnATrans);
     575  xDelete(indexB);
     576  xDelete(valueX);
     577  xDelete(indexX);
     578}
     579/*}}}*/
     580void MumpsSolve(int n,int nnz,int local_nnz,int* irn_loc,int* jcn_loc,IssmDouble *a_loc,IssmDouble *rhs,Parameters* parameters){/*{{{*/
     581  IssmDouble::TapeType& tape = IssmDouble::getGlobalTape();
     582  codi::DataStore* dataHandler = NULL;
     583
     584  if(tape.isActive()) {
     585    dataHandler = new codi::DataStore();
     586
     587    // create the index and double vector for the matrix
     588    IssmDouble::Real* valueATrans = xNew<IssmDouble::Real>(local_nnz);
     589    IssmDouble::GradientData* indexATrans = xNew<IssmDouble::GradientData>(local_nnz);
     590    int* irnATrans = xNew<int>(local_nnz);
     591    int* jcnATrans = xNew<int>(local_nnz);
     592
     593    // read the data for the matrix A in a transposed fashion
     594          for (int i=0; i<local_nnz; ++i) {
     595        getPrimalAndGradData(a_loc[i], valueATrans[i], indexATrans[i]);
     596        irnATrans[i]=jcn_loc[i];  // transposed store
     597        jcnATrans[i]=irn_loc[i];  // transposed store
     598    }
     599
     600    // create the index vector for a (primal values are not needed for a)
     601    IssmDouble::GradientData* indexB = xNew<IssmDouble::GradientData>(n);
     602    getVectorGradData(rhs, indexB, n);
     603
     604    dataHandler->addData(valueATrans);
     605    dataHandler->addData(indexATrans);
     606    dataHandler->addData(irnATrans);
     607    dataHandler->addData(jcnATrans);
     608    dataHandler->addData(indexB);
     609  }
     610
     611  // unpack the primal values from the matrix and the vector
     612  IssmDouble::Real* valueA = xNew<IssmDouble::Real>(local_nnz);
     613  IssmDouble::Real* valueB = xNew<IssmDouble::Real>(n);
     614  // read the data from A and B
     615  getVectorPrimal(a_loc, valueA, local_nnz);
     616  getVectorPrimal(rhs, valueB, n);
     617
     618  MumpsSolve(n, nnz, local_nnz, irn_loc, jcn_loc, valueA, valueB, parameters);
     619  // valueB contains now the solution
     620
     621  // pack the values into rhs
     622  setVectorPrimal(rhs, valueB, n);
     623
     624  if(tape.isActive()) {
     625    // create the index vector X and register x as active variables
     626    IssmDouble::GradientData* indexX = xNew<IssmDouble::GradientData>(n);
     627    registerVector(rhs, indexX, n);
     628
     629    dataHandler->addData(valueB); // contains the values from x
     630    dataHandler->addData(indexX);
     631
     632    // store other arguments
     633    dataHandler->addData(n);
     634    dataHandler->addData(nnz);
     635    dataHandler->addData(local_nnz);
     636    dataHandler->addData(parameters); // we assume here that parameters is still intact when the reverse run is called
     637
     638         //tape.pushExternalFunction(&MumpsSolve_codi_b, dataHandler, &MumpsSolve_codi_delete);
     639    tape.pushExternalFunctionHandle(&MumpsSolve_codi_b,(void*)dataHandler, &MumpsSolve_codi_delete);
     640  } else {
     641    // if the tape is active valueB is stored in the dataHandler and deleted in the reverse sweep
     642    xDelete(valueB);
     643  }
     644
     645  xDelete(valueA);
     646}
     647/*}}}*/
     648#endif
  • issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp

    r20500 r23394  
    2121PetscMat::PetscMat(){/*{{{*/
    2222        this->matrix=NULL;
    23         #ifdef _HAVE_ADOLC_
     23        #ifdef _HAVE_AD_
    2424        this->amatrix=NULL;
    2525        #endif
  • issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h

    r15396 r23394  
    2727                Mat matrix;
    2828
    29                 #ifdef _HAVE_ADOLC_
     29                #ifdef _HAVE_AD_
    3030                IssmDouble* amatrix;
    3131                #endif
  • issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp

    r23189 r23394  
    1515#include "../../../shared/io/Comm/IssmComm.h"
    1616#include "../../../shared/Enum/Enum.h"
     17#include "../../../shared/io/Print/Print.h"
    1718
    1819void    PetscSolve(PetscVec** puf, PetscMat* Kff, PetscVec* pf, PetscVec* uf0,PetscVec* df, Parameters* parameters){ /*{{{*/
     
    156157        KSPGetIterationNumber(ksp,&iteration_number);
    157158        if (iteration_number<0) _error_("Solver diverged at iteration number: " << -iteration_number);
     159        if (VerboseSolver())  _printf0_("Petsc: "<< iteration_number << " KSP iterations\n");
    158160
    159161        /*Free resources:*/
  • issm/trunk/src/c/toolkits/petsc/objects/PetscVec.cpp

    r20500 r23394  
    2121PetscVec::PetscVec(){/*{{{*/
    2222        this->vector=NULL;
    23         #ifdef _HAVE_ADOLC_
     23        #ifdef _HAVE_AD_
    2424        this->avector=NULL;
    2525        #endif
  • issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h

    r20500 r23394  
    2525                Vec vector;
    2626
    27                 #ifdef _HAVE_ADOLC_
     27                #ifdef _HAVE_AD_
    2828                IssmDouble* avector;
    2929                #endif
  • issm/trunk/src/c/toolkits/toolkits.h

    r16137 r23394  
    3030#endif
    3131
     32#ifdef _HAVE_CODIPACK_
     33#include "./codipack/codipackincludes.h"
     34#endif
     35
    3236#ifdef _HAVE_TRIANGLE_
    3337#include "./triangle/triangleincludes.h"
  • issm/trunk/src/m/classes/autodiff.js

    r21341 r23394  
    1414                this.gcTriggerRatio=2.0;
    1515                this.gcTriggerMaxSize=65536;
     16                this.tapeAlloc    = 15000000;
    1617
    1718        }// }}}
     
    2930                fielddisplay(this,'gcTriggerRatio','free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio');
    3031                fielddisplay(this,'gcTriggerMaxSize','free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize');
     32                fielddisplay(this,'tapeAlloc','Iteration count of a priori memory allocation of the AD tape');
    3133
    3234        }// }}}
     
    4951                        checkfield(md,'fieldname','autodiff.gcTriggerRatio','>=',0);
    5052                        checkfield(md,'fieldname','autodiff.gcTriggerMaxSize','>=',65536);
     53                        checkfield(md,'fieldname','autodiff.tapeAlloc','>=',0);
    5154
    5255                        //go through our dependents and independents and check consistency:
     
    7982                        WriteData(fid,prefix,'object',this,'fieldname','gcTriggerRatio','format','Double');
    8083                        WriteData(fid,prefix,'object',this,'fieldname','gcTriggerMaxSize','format','Double');
     84                        WriteData(fid,prefix,'object',this,'fieldname','tapeAlloc','format','Integer');
    8185                        //}}}
    8286                        //process dependent variables {{{
     
    216220                        this.gcTriggerRatio=NullFix(this.gcTriggerRatio,NaN);
    217221                        this.gcTriggerMaxSize=NullFix(this.gcTriggerMaxSize,NaN);
     222                        this.tapeAlloc=NullFix(this.tapeAlloc,NaN);
    218223                }//}}}
    219224        //properties
     
    229234        this.gcTriggerRatio = NaN;
    230235        this.gcTriggerMaxSize = NaN;
     236        this.tapeAlloc = NaN;
    231237
    232238        this.setdefaultparameters();
  • issm/trunk/src/m/classes/autodiff.m

    r23189 r23394  
    1717                gcTriggerRatio = NaN;
    1818                gcTriggerMaxSize = NaN;
     19                tapeAlloc = NaN;
    1920                end
    2021                %}}}
     
    3536                self.gcTriggerRatio=2.0;
    3637                self.gcTriggerMaxSize=65536;
     38                self.tapeAlloc    = 15000000;
    3739                end % }}}
    3840                function md = checkconsistency(self,md,solution,analyses) % {{{
     
    5153                        md = checkfield(md,'fieldname','autodiff.gcTriggerRatio','>=',0);
    5254                        md = checkfield(md,'fieldname','autodiff.gcTriggerMaxSize','>=',65536);
     55                        md = checkfield(md,'fieldname','autodiff.tapeAlloc','>=',0);
    5356
    5457                        %go through our dependents and independents and check consistency:
     
    7578                        fielddisplay(self,'gcTriggerRatio','free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio');
    7679                        fielddisplay(self,'gcTriggerMaxSize','free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize');
     80                        fielddisplay(self,'tapeAlloc','Iteration count of a priori memory allocation of the AD tape');
    7781                end % }}}
    7882                function marshall(self,prefix,md,fid) % {{{
     
    9599                        WriteData(fid,prefix,'object',self,'fieldname','gcTriggerRatio','format','Double');
    96100                        WriteData(fid,prefix,'object',self,'fieldname','gcTriggerMaxSize','format','Double');
     101                        WriteData(fid,prefix,'object',self,'fieldname','tapeAlloc','format','Integer');
    97102                        %}}}
    98103                        %process dependent variables {{{
  • issm/trunk/src/m/classes/autodiff.py

    r21341 r23394  
    2525                self.gcTriggerMaxSize     = float('NaN')
    2626                self.gcTriggerRatio     = float('NaN')
     27                self.tapeAlloc = float('NaN')
    2728                if not len(args):
    2829                        self.setdefaultparameters()
     
    4344                s+="%s\n" % fielddisplay(self,'gcTriggerRatio',"free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio")
    4445                s+="%s\n" % fielddisplay(self,'gcTriggerMaxSize',"free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize)")
     46                s+="%s\n" % fielddisplay(self,'tapeAlloc','Iteration count of a priori memory allocation of the AD tape');
    4547
    4648                return s
     
    5456                self.gcTriggerRatio=2.0
    5557                self.gcTriggerMaxSize=65536
     58                self.tapeAlloc    = 15000000;
    5659                return self
    5760        # }}}
     
    6871                md = checkfield(md,'fieldname','autodiff.gcTriggerRatio','>=',2.0)
    6972                md = checkfield(md,'fieldname','autodiff.gcTriggerMaxSize','>=',65536)
     73                md = checkfield(md,'fieldname','autodiff.tapeAlloc','>=',0);
    7074
    7175                #Driver value:
     
    97101                WriteData(fid,prefix,'object',self,'fieldname','gcTriggerRatio','format','Double');
    98102                WriteData(fid,prefix,'object',self,'fieldname','gcTriggerMaxSize','format','Double');
    99                 #}}}
     103                WriteData(fid,prefix,'object',self,'fieldname','tapeAlloc','format','Integer');
     104                #}}}
    100105                #process dependent variables {{{
    101106                num_dependent_objects=len(self.dependents)
  • issm/trunk/src/m/classes/clusters/stallo.py

    r22758 r23394  
    1212except ImportError:
    1313        print 'You need stallo_settings.py to proceed, check presence and sys.path'
    14        
     14
    1515class stallo(object):
    1616        """
    1717        Stallo cluster class definition
    1818        This is a SLURM queue
    19         The priorities are given to: 
     19        The priorities are given to:
    2020           - Large jobs
    2121           - Short jobs
     
    2323
    2424        There are some 20cpu nodes and 16cpu nodes, with 32GB (a few with 128GB) mem per node, you can ask for part of a node if you need more memory.(1 node, 2 CPUS and 10GB per cpu for example)
    25        
     25
    2626
    2727           Usage:
     
    5151                #OK get other fields
    5252                self=options.AssignObjectFields(self)
    53                 self.np=self.numnodes*self.cpuspernode         
     53                self.np=self.numnodes*self.cpuspernode
    5454        # }}}
    55        
     55
    5656        def __repr__(self):
    5757        # {{{
     
    6161                s = "%s\n%s"%(s,fielddisplay(self,'login','login'))
    6262                s = "%s\n%s"%(s,fielddisplay(self,'numnodes','number of nodes'))
    63                 s = "%s\n%s"%(s,fielddisplay(self,'cpuspernode','number of nodes per CPUs'))
     63                s = "%s\n%s"%(s,fielddisplay(self,'cpuspernode','number of CPUs per nodes'))
    6464                s = "%s\n%s"%(s,fielddisplay(self,'mem','memory per CPU'))
    6565                s = "%s\n%s"%(s,fielddisplay(self,'queue','name of the queue (normal (D), short,singlenode,multinode,devel)'))
     
    104104                if isoceancoupling:
    105105                        executable='issm_ocean.exe'
    106                 #write queuing script 
     106                #write queuing script
    107107                shortname=modelname[0:min(12,len(modelname))]
     108                timeobj=datetime.timedelta(minutes=self.time)
     109                m,s=divmod(timeobj.total_seconds(), 60)
     110                h,m=divmod(m, 60)
     111                d,h=divmod(h, 60)
     112                timestring="%02d-%02d:%02d:%02d" % (d, h, m, s)
     113
    108114                fid=open(modelname+'.queue','w')
    109                                                                        
    110115                fid.write('#!/bin/bash -l\n')
    111116                fid.write('#SBATCH --job-name=%s \n' % shortname)
    112                 fid.write('#SBATCH --partition %s \n' % self.queue)
    113                 fid.write('#SBATCH --nodes=%i' % self.numnodes)
    114                 fid.write('#SBATCH --ntasks-per-nodes==%i \n' % self.cpuspernode)                                                                       
    115                 fid.write('#SBATCH --time=%s\n' % self.time) #walltime is minutes
    116                 fid.write('#SBATCH --mem-per-cpu=%iGB\n' % self.mem)# mem is in GB
     117                fid.write('#SBATCH --qos=%s \n' % self.queue)
     118                fid.write('#SBATCH --nodes=%i \n' % self.numnodes)
     119                fid.write('#SBATCH --ntasks-per-node=%i \n' % self.cpuspernode)
     120                fid.write('#SBATCH --time={}\n'.format(timestring)) #walltime is minutes
     121                fid.write('#SBATCH --mem-per-cpu={}MB\n'.format(int(1000*self.mem)))# mem is in MB
    117122                if (np.mod(self.np,16)+np.mod(self.np,20))==0:
    118123                        fid.write('#SBATCH --ntask=%i\n' % self.np)
    119                 fid.write('#SBATCH --account=%s\n' % self.accountname) 
     124                fid.write('#SBATCH --account=%s\n' % self.accountname)
    120125                fid.write('#SBATCH --output %s/%s/%s.outlog \n' % (self.executionpath,dirname,modelname))
    121126                fid.write('#SBATCH --error %s/%s/%s.errlog \n\n' % (self.executionpath,dirname,modelname))
  • issm/trunk/src/m/classes/geometry.py

    r22758 r23394  
    1313
    1414        def __init__(self): # {{{
    15                 self.surface           = float('NaN')
    16                 self.thickness         = float('NaN')
     15                self.surface            = float('NaN')
     16                self.thickness          = float('NaN')
    1717                self.base               = float('NaN')
    18                 self.bed        = float('NaN')
    19                 self.hydrostatic_ratio = float('NaN')
     18                self.bed                = float('NaN')
     19                self.hydrostatic_ratio  = float('NaN')
    2020
    2121                #set defaults
  • issm/trunk/src/m/classes/groundingline.js

    r23189 r23394  
    2929                        checkfield(md,'fieldname','groundingline.melt_interpolation','values',['NoMeltOnPartiallyFloating', 'SubelementMelt1', 'SubelementMelt2', 'FullMeltOnPartiallyFloating']);
    3030
    31                         if (this.migration !='None'){
     31                        if(this.migration !='None' & md.trans.isgroundingline==1 & solution == 'TransientSolution'){
    3232                                if (isNaN(md.geometry.bed)){
    3333                                        md.checkmessage('requesting grounding line migration, but bathymetry is absent!');
  • issm/trunk/src/m/classes/groundingline.m

    r23189 r23394  
    3333                        md = checkfield(md,'fieldname','groundingline.melt_interpolation','values',{'NoMeltOnPartiallyFloating' 'SubelementMelt1' 'SubelementMelt2' 'FullMeltOnPartiallyFloating'});
    3434
    35                         if ~strcmp(self.migration,'None'),
     35                        if ~strcmp(self.migration,'None') & strcmp(solution,'TransientSolution') & md.transient.isgroundingline==1,
    3636                                if isnan(md.geometry.bed),
    3737                                        md = checkmessage(md,['requesting grounding line migration, but bathymetry is absent!']);
  • issm/trunk/src/m/classes/groundingline.py

    r23189 r23394  
    4545                md = checkfield(md,'fieldname','groundingline.melt_interpolation','values',['SubelementMelt1','SubelementMelt2','NoMeltOnPartiallyFloating','FullMeltOnPartiallyFloating'])
    4646
    47                 if not m.strcmp(self.migration,'None'):
     47                if(not m.strcmp(self.migration,'None') and md.transient.isgroundingline and solution=='TransientSolution'):
    4848                        if np.any(np.isnan(md.geometry.bed)):
    4949                                md.checkmessage("requesting grounding line migration, but bathymetry is absent!")
  • issm/trunk/src/m/classes/numberedcostfunction.m

    r22758 r23394  
    1 %M1QN3INVERSION class definition
     1%NUMBEREDCOSTFUNCTION class definition
    22%
    33%   Usage:
     
    4444                function md = checkconsistency(self,md,solution,analyses) % {{{
    4545
    46                         num_costfunc=size(md.inversion.cost_functions,2);
     46                        num_costfunc=size(self.cost_functions,2);
    4747
    48                         md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',supportedcostfunctions());
    49                         md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
    50 
     48                        md = checkfield(md,'fieldname','md.outputdefinition.definition{X}.dependent{X}.cost_functions','field',self.cost_functions,'size',[1 num_costfunc],'values',supportedcostfunctions());
     49                        md = checkfield(md,'fieldname','md.outputdefinition.definition{X}.cost_functions_coefficients','field',self.cost_functions_coefficients,'size',[md.mesh.numberofvertices numel(self.cost_functions)],'>=',0);
     50                       
    5151                        if strcmp(solution,'BalancethicknessSolution')
    52                                 md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
    53                                 md = checkfield(md,'fieldname','inversion.surface_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
     52                                md = checkfield(md,'fieldname','md.outputdefinition.definition{X}.thickness_obs','field',self.thickness_obs,'size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
     53                                md = checkfield(md,'fieldname','md.outputdefinition.definition{X}.surface_obs','field',self.surface_obs,'size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
    5454                        elseif strcmp(solution,'BalancethicknessSoftSolution')
    55                                 md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
     55                                md = checkfield(md,'fieldname','md.outputdefinition.definition{X}.thickness_obs','field',self.thickness_obs,'size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
    5656                        else
    57                                 md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
     57                                md = checkfield(md,'fieldname','md.outputdefinition.definition{X}.vx_obs','field',self.vx_obs,'size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
    5858                                if ~strcmp(domaintype(md.mesh),'2Dvertical'),
    59                                         md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
     59                                        md = checkfield(md,'fieldname','md.outputdefinition.definition{X}.vy_obs','field',self.vy_obs,'size',[md.mesh.numberofvertices 1],'NaN',1,'Inf',1);
    6060                                end
    6161                        end
  • issm/trunk/src/m/classes/taoinversion.py

    r22758 r23394  
    9797                else:
    9898                        self.algorithm = 'tao_blmvm';
    99                
     99
    100100                #several responses can be used:
    101101                self.cost_functions=101;
     
    110110                if numel(self.cost_functions_coefficients) > 1:
    111111                        self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node')
    112                
     112
    113113                if numel(self.min_parameters) > 1:
    114114                        self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node')
    115                
     115
    116116                if numel(self.max_parameters)>1:
    117117                        self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node')
     
    123123                        return md
    124124                if not IssmConfig('_HAVE_TAO_')[0]:
    125                         md = checkmessage(md,['TAO has not been installed, ISSM needs to be reconfigured and recompiled with TAO'])
     125                        md = md.checkmessage('TAO has not been installed, ISSM needs to be reconfigured and recompiled with TAO')
    126126
    127127
  • issm/trunk/src/m/contrib/defleurian/netCDF/export_netCDF.py

    r21729 r23394  
    1818                        print ('New file name is {}'.format(newname))
    1919                        filename=newname
    20                        
     20
    2121        NCData=Dataset(filename, 'w', format='NETCDF4')
    2222        NCData.description = 'Results for run' + md.miscellaneous.name
     
    100100                                Subgroup.__setattr__('classtype',md.__dict__[group].__class__.__name__)
    101101                                subfields=dict.keys(md.__dict__[group].__dict__[field].__dict__)
    102                                
     102
    103103                                for subfield in subfields:
    104104                                        if str(subfield)!='outlog':
    105105                                                Var=md.__dict__[group].__dict__[field].__dict__[subfield]
    106106                                                DimDict=CreateVar(NCData,Var,subfield,Subgroup,DimDict)
    107                                
     107
    108108        NCData.close()
    109109
     
    130130                                                        str:str,
    131131                                                        dict:str}
    132                
     132
    133133        val_dim=np.shape(val_shape)[0]
     134
    134135        #Now define and fill up variable
    135136        #treating scalar string or bool as atribute
    136         if val_type==str or val_type==unicode or val_type==bool:
     137        if val_type in [str,unicode,bool]:
    137138                Group.__setattr__(str(field).swapcase(), str(var))
    138139        #treating list as string table
     
    147148                if val_shape==0:
    148149                        ncvar= []
    149                 else:                   
     150                else:
    150151                        for elt in range(0,val_shape[0]):
    151152                                ncvar[elt] = var[elt]
     
    164165                        ncvar[elt,1]=str(dict.values(var)[elt]) #converting to str to avoid potential problems
    165166        #Now dealing with numeric variables
    166         else:
     167        elif val_type in [float,'float64',np.float64,int,'int64']:
    167168                dimensions,DimDict=GetDim(NCData,var,val_shape,DimDict,val_dim)
    168169                ncvar = Group.createVariable(str(field),TypeDict[val_type],dimensions,zlib=True)
     
    175176                except TypeError: #type does not accept nan, get vallue of the variable
    176177                        ncvar[:] = var
     178        else:
     179                print('WARNING type "{}" is unknown for "{}.{}"'.format(val_type,Group.name,field))
    177180        return DimDict
    178181
  • issm/trunk/src/m/contrib/defleurian/paraview/enveloppeVTK.py

    r21341 r23394  
    99        creates a directory with the vtk files for displays in paraview
    1010        (only work for triangle and wedges based on their number of nodes)
    11        
    12         Give only the results for nw but could be extended to geometry, mask... 
    13        
    14         input: filename   destination 
     11
     12        Give only the results for nw but could be extended to geometry, mask...
     13
     14        input: filename   destination
    1515        (string)
    1616        ------------------------------------------------------------------
    17 model      this is md 
     17model      this is md
    1818        ------------------------------------------------------------------
    1919        By default only the results are exported, you can add whichever
     
    4040                os.mkdir(filename)
    4141
    42         IsEnveloppe=np.where(model.mesh.vertexonbase | model.mesh.vertexonsurface)
    43         #get the element related variables
     42        # {{{get the element related variables
    4443        if 'z' in dict.keys(model.mesh.__dict__):
    45                 points=np.column_stack((model.mesh.x,model.mesh.y,model.mesh.z))
    46                 num_of_elt=np.size(np.isnan(model.mesh.lowerelements))+np.size(np.isnan(model.mesh.upperelements))
    47                 low_elt_num=np.size(np.isnan(model.mesh.lowerelements))
    48                 top_elt_num=np.size(np.isnan(model.mesh.upperelements))
     44                is_enveloppe=np.logical_or(model.mesh.vertexonbase,model.mesh.vertexonsurface)
     45                enveloppe_index=np.where(is_enveloppe)[0]
     46                convert_index=np.nan*np.ones(np.shape(model.mesh.x))
     47                convert_index=np.asarray([[i,np.where(enveloppe_index==i)[0][0]] for i,val in enumerate(convert_index) if any(enveloppe_index==i)])
     48                points=np.column_stack((model.mesh.x[enveloppe_index],
     49                                                                                                                model.mesh.y[enveloppe_index],
     50                                                                                                                model.mesh.z[enveloppe_index]))
     51                low_elt_num=np.size(np.where(np.isnan(model.mesh.lowerelements)))
     52                top_elt_num=np.size(np.where(np.isnan(model.mesh.upperelements)))
     53                num_of_elt=low_elt_num+top_elt_num
     54                connect=model.mesh.elements[np.where(is_enveloppe[model.mesh.elements-1])].reshape(int(num_of_elt),3)-1
     55                for elt in range(0, num_of_elt):
     56                        connect[elt,0]=convert_index[np.where(convert_index==connect[elt,0])[0],1][0]
     57                        connect[elt,1]=convert_index[np.where(convert_index==connect[elt,1])[0],1][0]
     58                        connect[elt,2]=convert_index[np.where(convert_index==connect[elt,2])[0],1][0]
     59
    4960        else:
    50                 points=np.column_stack((model.mesh.x,model.mesh.y,np.zeros(np.shape(model.mesh.x))))
     61                points=np.column_stack((model.mesh.x,
     62                                                                                                                model.mesh.y,
     63                                                                                                                np.zeros(np.shape(model.mesh.x))))
    5164                num_of_elt=np.shape(model.mesh.elements)[0]
    52                
    53         num_of_points=np.size(points)[0]
    54         dim=np.size(points)[1]
    55         point_per_elt=np.shape(model.mesh.elements)[1]
    56                
     65                connect=model.mesh.elements-1
     66                enveloppe_index=np.arange(0,np.size(model.mesh.x))
     67
     68        every_nodes=np.size(model.mesh.x)
     69        num_of_points=np.size(enveloppe_index)
     70        dim=3
     71        point_per_elt=3
    5772        celltype=5 #triangles
    58        
    59         #this is the result structure
     73
     74        # }}}
     75        # {{{this is the result structure
    6076        res_struct=model.results
    6177        if (len(res_struct.__dict__)>0):
     
    6480                num_of_sols=len(solnames)
    6581                num_of_timesteps=1
    66                 #%building solutionstructure 
     82                #%building solutionstructure
    6783                for solution in solnames:
    6884                        #looking for multiple time steps
    6985                        if (np.size(res_struct.__dict__[solution])>num_of_timesteps):
    7086                                num_of_timesteps=np.size(res_struct.__dict__[solution])
    71                                 num_of_timesteps=int(num_of_timesteps)+1
     87                                num_of_timesteps=int(num_of_timesteps)
    7288        else:
    7389                num_of_timesteps=1
    74 
     90        # }}}
     91        # {{{write header and mesh
    7592        for step in range(0,num_of_timesteps):
    7693                timestep=step
     
    83100                for point in points:
    84101                        fid.write('%f %f %f \n'%(point[0], point[1], point[2]))
    85                        
     102
    86103                fid.write('CELLS %d %d\n' %(num_of_elt, num_of_elt*(point_per_elt+1)))
    87104
    88                 #       if exist('low_elt_num')
    89                 # triaconnect=zeros(num_of_elt,3);
    90                 # triaconnect(1:low_elt_num,:)=model.mesh.elements(find(isnan(model.mesh.lowerelements)),1:3);
    91                 # upshift=-min(min(model.mesh.elements(find(isnan(model.mesh.upperelements)),4:6)))+1+max(max(model.mesh.elements(find(isnan(model.mesh.lowerelements)),1:3)));
    92                 # triaconnect(1+low_elt_num:num_of_elt,:)=model.mesh.elements(find(isnan(model.mesh.upperelements)),4:6)+upshift;
    93                 # fprintf(fid,s,[(3)*ones(num_of_elt,1) triaconnect-1]');
    94105                for elt in range(0, num_of_elt):
    95                
    96                         fid.write('3 %d %d %d\n' %(model.mesh.elements[elt,0]-1,model.mesh.elements[elt,1]-1,model.mesh.elements[elt,2]-1))
    97                
     106                        fid.write('3 %d %d %d\n' %(connect[elt,0],
     107                                                                                                                                 connect[elt,1],
     108                                                                                                                                 connect[elt,2]))
     109
    98110                fid.write('CELL_TYPES %d\n' %num_of_elt)
    99111                for elt in range(0, num_of_elt):
     
    101113
    102114                fid.write('POINT_DATA %s \n' %str(num_of_points))
    103        
    104                 #loop over the different solution structures
     115                # }}}
     116                # {{{loop over the different solution structures
    105117                if 'solnames' in locals():
    106118                        for sol in solnames:
     
    110122                                else:
    111123                                        timestep = np.size(res_struct.__dict__[sol])
    112                                
     124
    113125                                #getting the  fields in the solution
    114126                                if(np.size(res_struct.__dict__[sol])>1):
    115                                         fieldnames=dict.keys(res_struct.__dict__[sol].__getitem__(timestep-1).__dict__)
     127                                        fieldnames=dict.keys(res_struct.__dict__[sol].__getitem__(timestep).__dict__)
    116128                                else:
    117129                                        fieldnames=dict.keys(res_struct.__dict__[sol].__dict__)
     
    119131                                for field in fieldnames:
    120132                                        if(np.size(res_struct.__dict__[sol])>1):
    121                                                 fieldstruct=res_struct.__dict__[sol].__getitem__(timestep-1).__dict__[field]
     133                                                fieldstruct=res_struct.__dict__[sol].__getitem__(timestep).__dict__[field]
    122134                                        else:
    123135                                                fieldstruct=res_struct.__dict__[sol].__dict__[field]
    124136
    125                                         if ((np.size(fieldstruct))==num_of_points):
     137                                        if ((np.size(fieldstruct))==every_nodes):
    126138                                                fid.write('SCALARS %s float 1 \n' % field)
    127139                                                fid.write('LOOKUP_TABLE default\n')
    128140                                                for node in range(0,num_of_points):
    129141                                                        #paraview does not like NaN, replacing
    130                                                         if np.isnan(fieldstruct[node]):
     142                                                        if np.isnan(fieldstruct[enveloppe_index[node]]):
    131143                                                                fid.write('%e\n' % -9999.9999)
    132144                                                        #also checking for verry small value that mess up
    133                                                         elif (abs(fieldstruct[node])<1.0e-20):
     145                                                        elif (abs(fieldstruct[enveloppe_index[node]])<1.0e-20):
    134146                                                                fid.write('%e\n' % 0.0)
    135147                                                        else:
    136                                                                 fid.write('%e\n' % fieldstruct[node])
    137                                        
    138                 #loop on arguments, if something other than result is asked, do
    139                 #it now
     148                                                                fid.write('%e\n' % fieldstruct[enveloppe_index[node]])
     149                # }}}
     150                # {{{loop on arguments, if something other than result is asked, do it now
     151
    140152                for other in args:
    141153                        other_struct=model.__dict__[other]
    142154                        othernames=(dict.keys(other_struct.__dict__))
    143155                        for field in othernames:
    144 #                               fprintf(fid,s,res_struct.(fieldnames{k})(IsEnveloppe));
    145                                 if ((np.size(other_struct.__dict__[field]))==num_of_points):
     156                                if ((np.size(other_struct.__dict__[field]))==every_nodes):
    146157                                        fid.write('SCALARS %s float 1 \n' % field)
    147158                                        fid.write('LOOKUP_TABLE default\n')
    148159                                        for node in range(0,num_of_points):
    149160                                                #paraview does not like NaN, replacing
    150                                                 if np.isnan(other_struct.__dict__[field][node]):
     161                                                if np.isnan(other_struct.__dict__[field][enveloppe_index[node]]):
    151162                                                        fid.write('%e\n' % -9999.9999)
    152163                                                #also checking for verry small value that mess up
    153                                                 elif (abs(other_struct.__dict__[field][node])<1.0e-20):
     164                                                elif (abs(other_struct.__dict__[field][enveloppe_index[node]])<1.0e-20):
    154165                                                        fid.write('%e\n' % 0.0)
    155166                                                else:
    156                                                         fid.write('%e\n' % other_struct.__dict__[field][node])
     167                                                        fid.write('%e\n' % other_struct.__dict__[field][enveloppe_index[node]])
     168
     169                        # }}}
    157170        fid.close();
  • issm/trunk/src/m/contrib/defleurian/paraview/exportVTK.py

    r21729 r23394  
    99        creates a directory with the vtk files for displays in paraview
    1010        (only work for triangle and wedges based on their number of nodes)
    11        
    12         Give only the results for nw but could be extended to geometry, mask... 
    13        
    14         input: filename   destination 
     11
     12        Give only the results for nw but could be extended to geometry, mask...
     13
     14        input: filename   destination
    1515        (string)
    1616        ------------------------------------------------------------------
    17 model      this is md 
     17model      this is md
    1818        ------------------------------------------------------------------
    1919        By default only the results are exported, you can add whichever
     
    6767                num_of_sols=len(solnames)
    6868                num_of_timesteps=1
    69                 #%building solutionstructure 
     69                #%building solutionstructure
    7070                for solution in solnames:
    7171                        #looking for multiple time steps
     
    9191                        for point in points:
    9292                                fid.write('%f %f %f \n'%(point[0], point[1], point[2]))
    93                        
     93
    9494                fid.write('CELLS %d %d\n' %(num_of_elt, num_of_elt*(point_per_elt+1)))
    95                
     95
    9696                if point_per_elt==3:
    9797                        for elt in range(0, num_of_elt):
     
    117117                                else:
    118118                                        timestep = np.size(res_struct.__dict__[sol])
    119                                
     119
    120120                                #getting the  fields in the solution
    121121                                if(np.size(res_struct.__dict__[sol])>1):
     
    187187                                        # reloaded variable are generally of dim 2
    188188                                        elif np.shape(other_struct.__dict__[field])[0]==num_of_points:
     189                                                # we want only vector
     190                                                if np.shape(other_struct.__dict__[field])[1]==1:
    189191                                                        fid.write('SCALARS %s float 1 \n' % field)
    190192                                                        fid.write('LOOKUP_TABLE default\n')
    191193                                                        for node in range(0,num_of_points):
    192194                                                                #paraview does not like NaN, replacing
     195                                                                print other_struct.__dict__[field][node]
    193196                                                                if np.isnan(other_struct.__dict__[field][node]):
    194197                                                                        fid.write('%e\n' % -9999.9999)
    195                                                                 #also checking for verry small value that mess up
     198                                                                        #also checking for verry small value that mess up
    196199                                                                elif (abs(other_struct.__dict__[field][node])<1.0e-20):
    197200                                                                        fid.write('%e\n' % 0.0)
  • issm/trunk/src/m/mesh/planet/gmsh/gmshplanet.m

    r22822 r23394  
    2323        resolution=getfieldvalue(options,'resolution')*1000;
    2424
    25         %initialize mesh: 
     25        %initialize mesh:
    2626        mesh=mesh3dsurface;
    2727
     
    9797                end
    9898                fprintf(fid,'};\n');
    99                
     99
    100100                fclose(fid);
    101101                % }}}
     
    111111        end
    112112        if isempty(gmshpath),
    113                 error('gmt not found, make sure it is properly installed');
     113                error('gmsh not found, make sure it is properly installed');
    114114        end
    115115
     
    160160        mesh.numberofelements=fscanf(fid,'%i',1);
    161161        A=fscanf(fid,'%i %i %i %i %i %i %i %i',[8 mesh.numberofelements]);
    162         mesh.elements=A(6:8,:)'; 
     162        mesh.elements=A(6:8,:)';
    163163        A=fscanf(fid,'%s',1);
    164164        if ~strcmp(A,'$EndElements'),
    165165                error(['Expecting $EndElements (' A ')']);
    166166        end
    167         fclose(fid); 
     167        fclose(fid);
    168168        %}}}
    169169
    170         %figure out other fields in mesh3dsurface: 
     170        %figure out other fields in mesh3dsurface:
    171171        mesh.r=sqrt(mesh.x.^2+mesh.y.^2+mesh.z.^2);
    172172        mesh.lat = asin(mesh.z./mesh.r)/pi*180;
    173173        mesh.long = atan2(mesh.y,mesh.x)/pi*180;
    174174
    175         %erase files: 
     175        %erase files:
    176176        system('rm -rf sphere.geo sphere.msh sphere.pos');
    177177
    178         %return mesh: 
     178        %return mesh:
    179179        return;
  • issm/trunk/src/m/mesh/triangle.py

    r22758 r23394  
    22import numpy as np
    33from mesh2d import mesh2d
    4 from Triangle import Triangle
    54from NodeConnectivity import NodeConnectivity
    65from ElementConnectivity import ElementConnectivity
     6from Triangle_python import Triangle_python
    77import MatlabFuncs as m
    88
     
    5050        #Mesh using Triangle
    5151        md.mesh=mesh2d()
    52         md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers=Triangle(domainname,riftname,area)
     52        md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers=Triangle_python(domainname,riftname,area)
    5353        md.mesh.elements=md.mesh.elements.astype(int)
    5454        md.mesh.segments=md.mesh.segments.astype(int)
  • issm/trunk/src/m/mesh/triangle2dvertical.m

    r22758 r23394  
    2525
    2626%Mesh using Triangle
    27 [elements,x,z,segments,segmentmarkers]=Triangle(domainname,'',area);
     27[elements,x,z,segments,segmentmarkers]=Triangle_matlab(domainname,'',area);
    2828
    2929%check that all the created nodes belong to at least one element
  • issm/trunk/src/m/modules/Chaco.py

    r23189 r23394  
    55
    66   Usage:
    7       [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);
     7      assgn = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);
    88
    99   A:                   Input adjacency matrix
  • issm/trunk/src/m/modules/MeshPartition.m

    r22758 r23394  
    33%
    44%          Usage:
    5 %                       [element_partitioning,node_partitioning]=MeshPartition(md,numpartitions)");
     5%                       [element_partitioning,node_partitioning]=MeshPartition(md,numpartitions);
    66%
    77%          element_partitioning: Vector of partitioning area numbers, for every element.
     
    3535
    3636% Call mex module
    37 [element_partitioning, node_partitioning] = MeshPartition_matlab(numberofvertices,elements,numberofvertices2d,elements2d,numberoflayers,meshelementtype,numpartitions);
     37[element_partitioning, node_partitioning] = MeshPartition_matlab(numberofvertices,elements,numberofvertices2d,elements2d,numberoflayers,elementtype,numpartitions);
  • issm/trunk/src/m/modules/MeshPartition.py

    r23189 r23394  
    99
    1010           Usage:
    11                         [element_partitioning,node_partitioning]=MeshPartition(md.mesh,numpartitions)")
     11                        [element_partitioning,node_partitioning]=MeshPartition(md.mesh,numpartitions)
    1212
    1313           element_partitioning: Vector of partitioning area numbers, for every element.
     
    3838
    3939        #Call module
    40         [element_partitioning, node_partitioning] = MeshPartition_python(numberofvertices, elements, numberofvertices2d, elements2d, numberoflayers, meshelementtype, numpartitions)
     40        [element_partitioning, node_partitioning] = MeshPartition_python(numberofvertices, elements, numberofvertices2d, elements2d, numberoflayers,elementtype, numpartitions)
    4141
    4242        return [element_partitioning, node_partitioning]
  • issm/trunk/src/m/modules/Scotch.py

    r23189 r23394  
    22
    33def Scotch(*varargin):
    4 '''SCOTCH - Scotch partitioner
     4        '''SCOTCH - Scotch partitioner
    55
    66   Usage:
  • issm/trunk/src/m/partition/partitioner.py

    r23189 r23394  
    33import MatlabFuncs as m
    44from adjacency import *
    5 #from Chaco import *
     5from Chaco import *
    66#from Scotch import *
    7 #from MeshPartition import *
     7from MeshPartition import *
    88from project3d import *
     9from mesh2d import *
    910
    1011def partitioner(md,*varargin):
     
    6061
    6162        if m.strcmpi(package,'chaco'):
    62                 raise RuntimeError('Chaco is not currently supported for this function')
     63                #raise RuntimeError('Chaco is not currently supported for this function')
    6364
    6465                #  default method (from chaco.m)
    65                 #method=np.array([1,1,0,0,1,1,50,0,.001,7654321]).reshape(-1,1)
    66                 #method[0]=3    #  global method (3=inertial (geometric))
    67                 #method[2]=0    #  vertex weights (0=off, 1=on)
     66                method=np.array([1,1,0,0,1,1,50,0,.001,7654321])
     67                method[0]=3    #  global method (3=inertial (geometric))
     68                method[2]=0    #  vertex weights (0=off, 1=on)
    6869
    6970                #specify bisection
    70                 #method[5]=options.getfieldvalue('section')#  ndims (1=bisection, 2=quadrisection, 3=octasection)
     71                method[5]=options.getfieldvalue('section')#  ndims (1=bisection, 2=quadrisection, 3=octasection)
    7172
    7273                #are we using weights?
    73                 #if m.strcmpi(options.getfieldvalue('weighting'),'on'):
    74                         #weights=np.floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight))
    75                         #method[2]=1
    76                 #else:
    77                         #weights=[]
     74                if m.strcmpi(options.getfieldvalue('weighting'),'on'):
     75                        weights=np.floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight))
     76                        method[2]=1
     77                else:
     78                        weights=[]
    7879       
     80                method = method.reshape(-1,1)   # transpose to 1x10 instead of 10
     81
    7982                #  partition into nparts
    80                 #if isinstance(md.mesh,mesh2d):
    81                         #part=Chaco(md.qmu.adjacency,weights,[],md.mesh.x, md.mesh.y,np.zeros((md.mesh.numberofvertices,)),method,npart,[]).T+1 #index partitions from 1 up. like metis.
    82                 #else:
    83                         #part=Chaco(md.qmu.adjacency,weights,[],md.mesh.x, md.mesh.y,md.mesh.z,method,npart,[]).T+1 #index partitions from 1 up. like metis.
    84        
     83                if isinstance(md.mesh,mesh2d):
     84                        part=np.array(Chaco(md.qmu.adjacency,weights,np.array([]),md.mesh.x, md.mesh.y,np.zeros((md.mesh.numberofvertices,)),method,npart,np.array([]))).T+1 #index partitions from 1 up. like metis.
     85                else:
     86                        part=np.array(Chaco(md.qmu.adjacency,weights,np.array([]),md.mesh.x, md.mesh.y,md.mesh.z,method,npart,np.array([]))).T+1 #index partitions from 1 up. like metis.
    8587       
    8688        elif m.strcmpi(package,'scotch'):
  • issm/trunk/src/m/plot/applyoptions.m

    r23189 r23394  
    142142        if exist(options,'colorbarcornerposition'),
    143143                c=colorbar(getfieldvalue(options,'colorbarcornerposition'),'peer',gca);
     144        elseif exist(options,'colorbarpos') & ischar(getfieldvalue(options,'colorbarpos')),
     145                c=colorbar(getfieldvalue(options,'colorbarpos'));
    144146        else
    145147                c=colorbar('peer',gca);
     
    151153                set(c,'Ylim',lim);
    152154        end
    153         if exist(options,'colorbarpos'),
     155        if exist(options,'colorbarpos') & isnumeric(getfieldvalue(options,'colorbarpos')),
    154156                set(c,'Position',getfieldvalue(options,'colorbarpos'));
    155157        end
  • issm/trunk/src/m/plot/googlemaps.m

    r22758 r23394  
    123123                        '&scale=' num2str(scale)];
    124124                url = ['http://maps.google.com/maps/api/staticmap?' params];
    125                 [X, map]=imread(url,'png');
     125                count = 0;
     126                countmax = 10;
     127                while(true)
     128                        try,
     129                                [X, map]=imread(url,'png');
     130                                break;
     131                        catch me,
     132                                count = count+1;
     133                                disp(['Failed, trying again... (' num2str(countmax-count) ' more attempts)']);
     134                                pause(.3);
     135                                if count>countmax,
     136                                        disp('Giving up...');
     137                                        rethrow(me);
     138                                end
     139                        end
     140                end
    126141                X=ind2rgb(X,map);
    127142                indx1 = floor(x*width)+1;
  • issm/trunk/src/m/qmu/dakota_in_write.py

    r23189 r23394  
    6262        filei2=fullfile(pathstr,name+ext)
    6363
    64         print 'Opening Dakota input file \''+filei2 + '\''
     64        print 'Opening Dakota input file \''+filei2 + '\'.'
    6565        try:
    6666                with open(filei2,'w+') as fidi:
  • issm/trunk/src/m/qmu/dakota_out_parse.py

    r23189 r23394  
    241241        dmax95 =prctile_issm(data,95,0)
    242242
     243        # Note: the following line may cause the following warning
     244        #       (should not crash or invalidate results) when one of
     245        #       the inputs does not change with respect to the
     246        #       other/s causing an internal divide-by-zero error
     247
     248        #/usr/local/lib/python2.7/dist-packages/numpy/lib/function_base.py:3163:
     249        #       RuntimeWarning: invalid value encountered in true_divide
     250        #       c /= stddev[:,None]
     251
     252        #       (and/or the same but with "c /= stddev[None, :]")
     253
    243254        dcorrel=np.corrcoef(data.T)
    244255
  • issm/trunk/src/m/qmu/helpers.py

    r23189 r23394  
    250250                pass
    251251
    252         # if all of that fails, then if is not empty
     252        # if all of that fails, then it is not empty
    253253        return False
    254254
  • issm/trunk/src/m/qmu/preqmu.py

    r23189 r23394  
    4545                        raise RuntimeError('Existing '+str(options.qmudir)+' directory, cannot overwrite. Specify "overwrite","y" option in solve arguments.')
    4646       
    47 
    48         os.makedirs(qmudir)
     47        # os.makedirs() raises error when dir exists, matlab's mkdir() does not
     48        if not os.path.isdir(qmudir):
     49                os.makedirs(qmudir)
    4950        os.chdir(qmudir)
    5051
  • issm/trunk/src/m/qmu/process_qmu_response_data.m

    r23189 r23394  
    4343        %ok, process the domains named in qmu_mass_flux_profiles,  to build a list of segments (MatArray)
    4444        md.qmu.mass_flux_segments=cell(num_mass_flux,1);
    45         md.qmu.mass_flux_segments
    4645        for i=1:num_mass_flux,
    4746                md.qmu.mass_flux_segments{i}=MeshProfileIntersection(md.mesh.elements,md.mesh.x,md.mesh.y,[md.qmu.mass_flux_profile_directory '/' md.qmu.mass_flux_profiles{i}]);
    4847        end
    49         md.qmu.mass_flux_segments
    5048end
  • issm/trunk/src/m/solve/WriteData.py

    r23189 r23394  
    77        """
    88        WRITEDATA - write model field in binary file
    9  
     9
    1010           Usage:
    1111              WriteData(fid,varargin)
     
    5757        #Step 1: write the enum to identify this record uniquely
    5858        fid.write(struct.pack('i',len(name)))
    59         fid.write(struct.pack('%ds' % len(name),name)) 
     59        fid.write(struct.pack('%ds' % len(name),name))
    6060
    6161        #Step 2: write the data itself.
     
    6767                fid.write(struct.pack('i',4+4))  #1 bool (disguised as an int)+code
    6868
    69                 #write data code: 
    70                 fid.write(struct.pack('i',FormatToCode(format))) 
     69                #write data code:
     70                fid.write(struct.pack('i',FormatToCode(format)))
    7171
    7272                #now write integer
     
    8181                fid.write(struct.pack('i',4+4))  #1 integer + code
    8282
    83                 #write data code: 
    84                 fid.write(struct.pack('i',FormatToCode(format))) 
     83                #write data code:
     84                fid.write(struct.pack('i',FormatToCode(format)))
    8585
    8686                #now write integer
    87                 fid.write(struct.pack('i',data)) 
     87                fid.write(struct.pack('i',data))
    8888                # }}}
    8989
     
    9595                fid.write(struct.pack('i',8+4))  #1 double+code
    9696
    97                 #write data code: 
    98                 fid.write(struct.pack('i',FormatToCode(format))) 
     97                #write data code:
     98                fid.write(struct.pack('i',FormatToCode(format)))
    9999
    100100                #now write double
    101                 fid.write(struct.pack('d',data)) 
     101                fid.write(struct.pack('d',data))
    102102                # }}}
    103103
     
    106106                fid.write(struct.pack('i',len(data)+4+4))  #string + string size + code
    107107
    108                 #write data code: 
    109                 fid.write(struct.pack('i',FormatToCode(format))) 
     108                #write data code:
     109                fid.write(struct.pack('i',FormatToCode(format)))
    110110
    111111                #now write string
    112                 fid.write(struct.pack('i',len(data))) 
    113                 fid.write(struct.pack('%ds' % len(data),data)) 
     112                fid.write(struct.pack('i',len(data)))
     113                fid.write(struct.pack('%ds' % len(data),data))
    114114                # }}}
    115115
     
    135135                fid.write(struct.pack('i',4+4+8*np.product(s)+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
    136136
    137                 #write data code and matrix type: 
    138                 fid.write(struct.pack('i',FormatToCode(format))) 
     137                #write data code and matrix type:
     138                fid.write(struct.pack('i',FormatToCode(format)))
    139139                fid.write(struct.pack('i',mattype))
    140140
    141141                #now write matrix
    142142                if np.ndim(data)==1:
    143                         fid.write(struct.pack('i',s[0])) 
    144                         fid.write(struct.pack('i',1)) 
     143                        fid.write(struct.pack('i',s[0]))
     144                        fid.write(struct.pack('i',1))
    145145                        for i in xrange(s[0]):
    146146                                fid.write(struct.pack('d',float(data[i])))    #get to the "c" convention, hence the transpose
    147147                else:
    148                         fid.write(struct.pack('i',s[0])) 
    149                         fid.write(struct.pack('i',s[1])) 
     148                        fid.write(struct.pack('i',s[0]))
     149                        fid.write(struct.pack('i',s[1]))
    150150                        for i in xrange(s[0]):
    151151                                for j in xrange(s[1]):
     
    174174                fid.write(struct.pack('i',4+4+8*np.product(s)+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
    175175
    176                 #write data code and matrix type: 
    177                 fid.write(struct.pack('i',FormatToCode(format))) 
     176                #write data code and matrix type:
     177                fid.write(struct.pack('i',FormatToCode(format)))
    178178                fid.write(struct.pack('i',mattype))
    179179
    180180                #now write matrix
    181181                if np.ndim(data) == 1:
    182                         fid.write(struct.pack('i',s[0])) 
    183                         fid.write(struct.pack('i',1)) 
     182                        fid.write(struct.pack('i',s[0]))
     183                        fid.write(struct.pack('i',1))
    184184                        for i in xrange(s[0]):
    185185                                fid.write(struct.pack('d',float(data[i])))    #get to the "c" convention, hence the transpose
    186186                else:
    187                         fid.write(struct.pack('i',s[0])) 
    188                         fid.write(struct.pack('i',s[1])) 
     187                        fid.write(struct.pack('i',s[0]))
     188                        fid.write(struct.pack('i',s[1]))
    189189                        for i in xrange(s[0]):
    190190                                for j in xrange(s[1]):
     
    217217                fid.write(struct.pack('i',recordlength))  #2 integers (32 bits) + the double matrix + code + matrix type
    218218
    219                 #write data code and matrix type: 
    220                 fid.write(struct.pack('i',FormatToCode(format))) 
     219                #write data code and matrix type:
     220                fid.write(struct.pack('i',FormatToCode(format)))
    221221                fid.write(struct.pack('i',mattype))
    222222
    223223                #now write matrix
    224224                if np.ndim(data) == 1:
    225                         fid.write(struct.pack('i',s[0])) 
    226                         fid.write(struct.pack('i',1)) 
     225                        fid.write(struct.pack('i',s[0]))
     226                        fid.write(struct.pack('i',1))
    227227                        for i in xrange(s[0]):
    228228                                fid.write(struct.pack('d',float(data[i])))    #get to the "c" convention, hence the transpose
    229229                else:
    230                         fid.write(struct.pack('i',s[0])) 
    231                         fid.write(struct.pack('i',s[1])) 
     230                        fid.write(struct.pack('i',s[0]))
     231                        fid.write(struct.pack('i',s[1]))
    232232                        for i in xrange(s[0]):
    233233                                for j in xrange(s[1]):
     
    266266                fid.write(struct.pack('i',recordlength))  #2 integers (32 bits) + the matrix + code + matrix type
    267267
    268                 #write data code and matrix type: 
    269                 fid.write(struct.pack('i',FormatToCode(format))) 
     268                #write data code and matrix type:
     269                fid.write(struct.pack('i',FormatToCode(format)))
    270270                fid.write(struct.pack('i',mattype))
    271271
     
    276276
    277277                if rangeA == 0:
    278                         A = A*0 
    279                 else:
    280                         A = (A-offsetA)/rangeA*255. 
    281                
     278                        A = A*0
     279                else:
     280                        A = (A-offsetA)/rangeA*255.
     281
    282282                #now write matrix
    283283                if np.ndim(data) == 1:
    284                         fid.write(struct.pack('i',s[0])) 
    285                         fid.write(struct.pack('i',1)) 
     284                        fid.write(struct.pack('i',s[0]))
     285                        fid.write(struct.pack('i',1))
    286286                        fid.write(struct.pack('d',float(offsetA)))
    287287                        fid.write(struct.pack('d',float(rangeA)))
     
    292292
    293293                elif np.product(s) > 0:
    294                         fid.write(struct.pack('i',s[0])) 
    295                         fid.write(struct.pack('i',s[1])) 
     294                        fid.write(struct.pack('i',s[0]))
     295                        fid.write(struct.pack('i',s[1]))
    296296                        fid.write(struct.pack('d',float(offsetA)))
    297297                        fid.write(struct.pack('d',float(rangeA)))
     
    324324
    325325                #write length of record
    326                 fid.write(struct.pack('i',recordlength)) 
    327 
    328                 #write data code: 
    329                 fid.write(struct.pack('i',FormatToCode(format))) 
     326                fid.write(struct.pack('i',recordlength))
     327
     328                #write data code:
     329                fid.write(struct.pack('i',FormatToCode(format)))
    330330
    331331                #write data, first number of records
    332                 fid.write(struct.pack('i',len(data))) 
     332                fid.write(struct.pack('i',len(data)))
    333333
    334334                for matrix in data:
     
    343343
    344344                        if np.ndim(matrix) == 1:
    345                                 fid.write(struct.pack('i',s[0])) 
    346                                 fid.write(struct.pack('i',1)) 
     345                                fid.write(struct.pack('i',s[0]))
     346                                fid.write(struct.pack('i',1))
    347347                                for i in xrange(s[0]):
    348348                                        fid.write(struct.pack('d',float(matrix[i])))    #get to the "c" convention, hence the transpose
    349349                        else:
    350                                 fid.write(struct.pack('i',s[0])) 
    351                                 fid.write(struct.pack('i',s[1])) 
     350                                fid.write(struct.pack('i',s[0]))
     351                                fid.write(struct.pack('i',s[1]))
    352352                                for i in xrange(s[0]):
    353353                                        for j in xrange(s[1]):
     
    363363
    364364                #write length of record
    365                 fid.write(struct.pack('i',recordlength)) 
    366 
    367                 #write data code: 
    368                 fid.write(struct.pack('i',FormatToCode(format))) 
     365                fid.write(struct.pack('i',recordlength))
     366
     367                #write data code:
     368                fid.write(struct.pack('i',FormatToCode(format)))
    369369
    370370                #now write length of string array
    371                 fid.write(struct.pack('i',len(data))) 
     371                fid.write(struct.pack('i',len(data)))
    372372
    373373                #now write the strings
    374374                for string in data:
    375                         fid.write(struct.pack('i',len(string))) 
    376                         fid.write(struct.pack('%ds' % len(string),string)) 
     375                        fid.write(struct.pack('i',len(string)))
     376                        fid.write(struct.pack('%ds' % len(string),string))
    377377                # }}}
    378378
     
    383383def FormatToCode(format): # {{{
    384384        """
    385         This routine takes the format string, and hardcodes it into an integer, which 
    386         is passed along the record, in order to identify the nature of the dataset being 
     385        This routine takes the format string, and hardcodes it into an integer, which
     386        is passed along the record, in order to identify the nature of the dataset being
    387387        sent.
    388388        """
  • issm/trunk/src/wrappers/Chaco/Chaco.cpp

    r22758 r23394  
    4747        /*Fetch Data*/
    4848        FetchChacoData(&nvtxs,&adjacency,&start,&ewgts,A_IN,EWGTS_IN);
    49         FetchData(&vwgts,&nterms,VWGTS_IN); 
    50         FetchData(&x,&nterms,X_IN); 
    51         FetchData(&y,&nterms,Y_IN); 
    52         FetchData(&z,&nterms,Z_IN); 
    53         FetchData(&in_options,&nterms,OPTNS_IN); 
     49        FetchData(&vwgts,&nterms,VWGTS_IN);
     50        FetchData(&x,&nterms,X_IN);
     51        FetchData(&y,&nterms,Y_IN);
     52        FetchData(&z,&nterms,Z_IN);
     53        FetchData(&in_options,&nterms,OPTNS_IN);
    5454        for (i=0;i<(nterms<10?nterms:10);i++) options[i]=in_options[i]; //copy in_options into default options
    55         FetchData(&npart,NPARTS_IN); 
     55        FetchData(&npart,NPARTS_IN);
    5656        //int * nparts=xNew<int>(1); nparts[0]=npart; //weird Chacox interface ain't it?
    57         FetchData(&goal,&nterms,GOAL_IN); 
     57        FetchData(&goal,&nterms,GOAL_IN);
    5858
    5959        /*Allocate output: */
  • issm/trunk/src/wrappers/DistanceToMaskBoundary/DistanceToMaskBoundary.cpp

    r21341 r23394  
    4343
    4444        /*Call core of computation: */
    45         DistanceToMaskBoundaryx(&distance,x,y,mask,nods);
     45        _error_("messing up with AD, is this fonction really used??");
     46        //DistanceToMaskBoundaryx(&distance,x,y,mask,nods);
    4647
    4748        /*Write results: */
  • issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp

    r21341 r23394  
    6666        else if(strcmp(name,"_HAVE_M1QN3_")==0){
    6767                #ifdef _HAVE_M1QN3_
     68                value = 1.;
     69                #endif
     70        }
     71        else if(strcmp(name,"_HAVE_ADOLC_")==0){
     72                #ifdef _HAVE_ADOLC_
     73                value = 1.;
     74                #endif
     75        }
     76        else if(strcmp(name,"_HAVE_CODIPACK_")==0){
     77                #ifdef _HAVE_CODIPACK_
    6878                value = 1.;
    6979                #endif
  • issm/trunk/src/wrappers/javascript/Makefile.am

    r23189 r23394  
    1 AM_CPPFLAGS = @DAKOTAINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @AMPIINCL@
     1AM_CPPFLAGS = @DAKOTAINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @AMPIINCL@ @ADJOINTMPIINCL@ @CODIPACKINCL@
    22AUTOMAKE_OPTIONS = subdir-objects
    33
  • issm/trunk/src/wrappers/matlab/Makefile.am

    r22758 r23394  
    1 AM_CPPFLAGS = @NEOPZINCL@ @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @AMPIINCL@
     1AM_CPPFLAGS = @NEOPZINCL@ @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @AMPIINCL@ @ADJOINTMPIINCL@ @MEDIPACKINCL@ @CODIPACKINCL@
    22AUTOMAKE_OPTIONS = subdir-objects
    33
  • issm/trunk/src/wrappers/python/Makefile.am

    r22758 r23394  
    1 AM_CPPFLAGS = @DAKOTAINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@ @AMPIINCL@
     1AM_CPPFLAGS = @DAKOTAINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@ @AMPIINCL@ @ADJOINTMPIINCL@ @MEDIPACKINCL@ @CODIPACKINCL@
    22AUTOMAKE_OPTIONS = subdir-objects
    33
  • issm/trunk/src/wrappers/python/io/FetchPythonData.cpp

    r22758 r23394  
    3232        }
    3333        else if (PyInt_Check(py_float))
    34          dscalar=(double)PyInt_AsLong(py_float);
     34                dscalar=(double)PyInt_AsLong(py_float);
    3535        else if (PyBool_Check(py_float))
    3636                dscalar=(double)PyLong_AsLong(py_float);
     
    132132        double* dmatrix=NULL;
    133133        double* matrix=NULL;
    134         int M,N;
     134        int M=0;
     135        int N=0;
    135136        int ndim;
    136137        npy_intp*  dims=NULL;
     
    236237        /*output: */
    237238        int* matrix=NULL;
    238         int M,N;
     239        int M=0;
     240        int N=0;
    239241        int ndim;
    240242        npy_intp*  dims=NULL;
     
    325327        bool* bmatrix=NULL;
    326328        bool* matrix=NULL;
    327         int M,N;
     329        int M=0;
     330        int N=0;
    328331        int ndim;
    329332        npy_intp*  dims=NULL;
     
    411414        double* dvector=NULL;
    412415        double* vector=NULL;
    413         int M;
     416        int M=0;
    414417        int ndim;
    415418        npy_intp*  dims=NULL;
     
    499502        /*output: */
    500503        float* vector=NULL;
    501         int M;
     504        int M=0;
    502505        int ndim;
    503506        npy_intp*  dims=NULL;
     
    539542                                /*transform into int vector: */
    540543                                vector=xNew<float>(M);
    541                                 for(i=0;i<M;i++)vector[i]=(float)lvector[i];
     544                                for(i=0;i<M;i++)vector[i]=(float)dvector[i];
    542545                        }
    543546
     
    566569                }
    567570                else
    568                  vector=NULL;
     571                        vector=NULL;
    569572        }
    570573        else{
     
    584587        /*output: */
    585588        int* vector=NULL;
    586         int M;
     589        int M=0;
    587590        int ndim;
    588591        npy_intp*  dims=NULL;
     
    624627                                /*transform into int vector: */
    625628                                vector=xNew<int>(M);
    626                                 for(i=0;i<M;i++)vector[i]=(int)lvector[i];
     629                                for(i=0;i<M;i++)vector[i]=(int)dvector[i];
    627630                        }
    628631
     
    672675        bool* bvector=NULL;
    673676        bool* vector=NULL;
    674         int M;
     677        int M=0;
    675678        int ndim;
    676679        npy_intp*  dims=NULL;
     
    923926        *pcontours=contours;
    924927}
    925 /*}}}*/
    926 void FetchChacoData(int* pnvtxs,int** padjacency,int** pstart,float** pewgts,PyObject* A_IN,PyObject* EWGTS_IN){
    927         _error_("Nathan... I need your help here");
    928 }
     928
     929void FetchChacoData(int* pnvtxs,int** padjacency,int** pstart,float** pewgts,PyObject* A_IN, PyObject* EWGTS_IN){/*{{{*/
     930
     931        double* a = ((double*)PyArray_DATA((PyArrayObject*)A_IN));
     932        int ndim  = PyArray_NDIM((PyArrayObject*)A_IN);
     933        int nzmax = PyArray_CountNonzero((PyArrayObject*)A_IN);
     934
     935        /*Fetch adjacency matrix:*/
     936        int      nvtxs       = PyArray_DIMS((PyArrayObject*)A_IN)[1];
     937
     938        int* mwstart = xNewZeroInit<int>(nvtxs+1);
     939        pyGetJc(a,nvtxs,mwstart);
     940
     941        int* mwadjacency = xNewZeroInit<int>(nzmax);
     942        pyGetIr(a,nvtxs,nzmax,mwadjacency);
     943       
     944        int* start = xNew<int>(nvtxs+1);
     945        for(int i=0;i<nvtxs+1;i++) start[i]=(int)mwstart[i];
     946        int* adjacency = xNew<int>(nzmax);
     947        for(int i=0; i<nzmax; i++) adjacency[i]=(int)mwadjacency[i];
     948
     949        /*Get edges weights*/
     950        int nedges = start[nvtxs];
     951        float* ewgts = NULL;
     952        int size = PyArray_SIZE((PyArrayObject*)EWGTS_IN);
     953        //size may be 1 and still be empty;
     954        //presumably size of edge_weights input will never be exactly 1
     955        if(size != 1 && size != 0){
     956                ewgts = xNewZeroInit<float>(nedges);
     957                for(int i = 0; i<nedges;i++){
     958                        ewgts[i] = (float)a[i];
     959                }
     960        }
     961
     962        /*Assign output pointers*/
     963        *pnvtxs     = nvtxs;
     964        *padjacency = adjacency;
     965        *pstart     = start;
     966        *pewgts     = ewgts;
     967}
     968/*}}}*/
     969
     970void pyGetJc(double* a, int nvtxs, int* Jc){
     971/*{{{*/
     972        //get the number of non-zero elements in each row, adding to the prior number;
     973        //always starts with 0 and has length: number_of_rows_in(a)+1 == nvtxs+1
     974        // eg: 0, 1, 3, 6, 8, 13, ...
     975        // for: 1 in the first row, 2 in the second, 3 in the third, etc.
     976        int c = 0;
     977        Jc[c++] = 0;
     978
     979        for(int i=0;i<nvtxs;i++){
     980                for(int j=0;j<nvtxs;j++){
     981                        if ((int)a[i+(j*nvtxs)] != 0){
     982                                Jc[c] += 1;
     983                        }
     984                }
     985                c++;
     986                Jc[c] = Jc[c-1];
     987        }
     988        return;
     989}
     990/*}}}*/
     991
     992void pyGetIr(double* a, int nvtxs, int nzmax, int* Ir){
     993/*{{{*/
     994        //get the row-wise position of each non-zero element;
     995        //has length: number_of_non_zero_elements_in(a) == nzmax
     996        // eg: 10, 24, 25, 4, ...
     997        // the 10th, 24th, and 25th elements in the first row, the 4th in the second row
     998        // using pyGetJc to determine which indices correspond to which row
     999        int r = 0;
     1000
     1001        for(int i=0;i<nvtxs;i++){
     1002                for(int j=0;j<nvtxs;j++){
     1003                        if ((int)a[i+(j*nvtxs)] != 0){
     1004                                Ir[r] = j;
     1005                                r++;
     1006                        }
     1007                }
     1008        }
     1009        return;
     1010}
     1011/*}}}*/
    9291012
    9301013/*Python version dependent: */
  • issm/trunk/src/wrappers/python/io/pythonio.h

    r22758 r23394  
    5151void FetchChacoData(int* pnvtxs,int** padjacency,int** pstart,float** pewgts,PyObject* A_IN,PyObject* EWGTS_IN);
    5252
     53void pyGetJc(double* a, int nvtxs, int* Jc);
     54void pyGetIr(double* a, int nvtxs, int nzmax, int* Ir);
     55
    5356int CheckNumPythonArguments(PyObject* inputs,int NRHS, void (*function)( void ));
    5457
  • issm/trunk/test

  • issm/trunk/test/NightlyRun/runme.py

    r23189 r23394  
    1111        """
    1212        RUNME - test deck for ISSM nightly runs
    13  
     13
    1414            In a test deck directory (tests/Vertification/NightlyRun for example)
    1515            The following command will launch all the existing tests:
     
    1818            >> runme(id=[101,102])
    1919            etc...
    20  
     20
    2121            Available options:
    2222               'id'            followed by the list of ids or (parts of) test names requested
     
    3737               'procedure'     'check' : run the test (default)
    3838                               'update': update the archive
    39  
     39
    4040            Usage:
    4141               runme(varargin)
    42  
     42
    4343            Examples:
    4444               runme()
     
    4949               runme(id=[[101,102],['Dakota','Slr']])
    5050        """
    51 
    5251        from parallelrange import parallelrange
    5352        from IdToName import IdToName
     
    8281        flist=glob('test*.py')    #File name must start with 'test' and must end by '.py' and must be different than 'test.py'
    8382        list_ids=[int(file[4:-3]) for file in flist if not file == 'test.py']    #Keep test id only (skip 'test' and '.py')
    84         #print 'list_ids =',list_ids
    8583
    8684        i1,i2=parallelrange(rank,numprocs,len(list_ids))    #Get tests for this cpu only
    8785        list_ids=list_ids[i1:i2+1]
    88         #print 'list_ids after parallelrange =',list_ids
    89        
    90         if id:
     86
     87        if np.size(id) > 0 and not id==None:
    9188                test_ids = set(GetIds(id)).intersection(set(list_ids))
    9289        else:
    9390                # if no tests are specifically provided, do them all
    9491                test_ids = set(list_ids)
    95                
    96         #print 'test_ids after list =',test_ids
     92
    9793        # }}}
    9894        #GET exclude {{{
     
    10096
    10197        test_ids=test_ids.difference(exclude_ids)
    102         #print 'test_ids after exclude =',sorted(test_ids)
    103         #return
    10498        # }}}
    10599        #Process Ids according to benchmarks {{{
     
    124118        elif benchmark=='adolc':
    125119                test_ids=test_ids.intersection(set(range(3001,3200)))
    126         #print 'test_ids after benchmark =',test_ids
    127120        test_ids=list(test_ids)
    128121        test_ids.sort()
    129         #print 'test_ids after sort =',test_ids
    130122        # }}}
    131123
     
    190182                                                        if np.shape(field) != np.shape(archive):
    191183                                                                raise RuntimeError("Field '"+archive_name+"' from test is malformed; shape is "+str(np.shape(field.T))+", should be "+str(np.shape(archive))+" (or "+str(np.shape(archive.T))+").")
    192                                                
     184
    193185                                                error_diff=np.amax(np.abs(archive-field),axis=0)/(np.amax(np.abs(archive),axis=0)+float_info.epsilon)
    194186
  • issm/trunk/test/NightlyRun/test2084.m

    r23189 r23394  
    1 
    2 %Test Name: GiaCaron.
     1%Test Name: GiaCaron
    32%Forward Love number solution for a viscoelastic earth, model M3-L70-V01 from
    43%Spada, G., Barletta, V. R., Klemann, V., Riva, R. E. M., Martinec, Z.,
     
    3938%loading love numbers
    4039field_names     ={'LoveH_loading_elastic','LoveK_loading_elastic','LoveL_loading_elastic'};
    41 field_tolerances={7.0e-10,7.0e-10,7.0e-10};
     40field_tolerances={4.3e-9,4.3e-9,4.3e-9};
    4241field_values={...
    4342        (md.results.LoveSolution.LoveHr(:,1)),...
     
    5756%Fields and tolerances to track changes
    5857field_names     ={field_names{:},'LoveH_loading_realpart','LoveK_loading_realpart','LoveL_loading_realpart','LoveH_loading_imagpart','LoveK_loading_imagpart','LoveL_loading_imagpart'};
    59 field_tolerances={field_tolerances{:},7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10};
     58field_tolerances={field_tolerances{:},5e-7,5e-7,5e-7,5e-7,5e-7,5e-7};
    6059field_values={field_values{:},...
    6160        (md.results.LoveSolution.LoveHr(:,:)),...
     
    7574%tidal love numbers
    7675field_names     ={field_names{:},'LoveH_tidal_elastic','LoveK_tidal_elastic','LoveL_tidal_elastic','LoveH_tidal_realpart','LoveK_tidal_realpart','LoveL_tidal_realpart','LoveH_tidal_imagpart','LoveK_tidal_imagpart','LoveL_tidal_imagpart'};
    77 field_tolerances={field_tolerances{:},7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10};
     76field_tolerances={field_tolerances{:},8e-6,8e-6,8e-6,8e-6,8e-6,8e-6,8e-6,8e-6,8e-6};
    7877field_values={field_values{:},...
    7978        (md.results.LoveSolution.LoveHr(:,1)),...
     
    115114%
    116115%field_names     ={field_names{:},'LoveH_loadingVSS96_elastic','LoveK_loadingVSS96_elastic','LoveL_loadingVSS96_elastic','LoveH_loadingVSS96_realpart','LoveK_loadingVSS96_realpart','LoveL_loadingVSS96_realpart','LoveH_loadingVSS96_imagpart','LoveK_loadingVSS96_imagpart','LoveL_loadingVSS96_imagpart'};
    117 %field_tolerances={field_tolerances{:},7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10};
     116%field_tolerances={field_tolerances{:},2e-6,2e-6,2e-6,2e-6,2e-6,2e-6,2e-6,2e-6,2e-6};
    118117%field_values={field_values{:},...
    119118%       (md.results.LoveSolution.LoveHr(:,1)),...
     
    147146
    148147field_names     ={field_names{:},'LoveH_loadingVSS96_elastic','LoveK_loadingVSS96_elastic','LoveL_loadingVSS96_elastic','LoveH_loadingVSS96_realpart','LoveK_loadingVSS96_realpart','LoveL_loadingVSS96_realpart','LoveH_loadingVSS96_imagpart','LoveK_loadingVSS96_imagpart','LoveL_loadingVSS96_imagpart'};
    149 field_tolerances={field_tolerances{:},7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10,7.0e-10};
     148field_tolerances={field_tolerances{:},2e-6,2e-6,2e-6,2e-6,2e-6,2e-6,2e-6,2e-6,2e-6};
    150149field_values={field_values{:},...
    151150        (md.results.LoveSolution.LoveHr(:,1)),...
  • issm/trunk/test/NightlyRun/test2084.py

    r23189 r23394  
    1 #Test Name: GiaCaron. Forward Love number solution for a viscoelastic earth,
    2 #       model M3-L70-V01 from Spada, G., Barletta, V. R., Klemann, V., Riva, R. E. M.,
    3 #       Martinec, Z., Gasperini, P., Lund, B., Wolf, D., Vermeersen, L. L. A.
    4 #       and King, M. A. (2011), A benchmark study for glacial isostatic
    5 #       adjustment codes. Geophysical Journal International,
    6 #       185: 106-132. doi:10.1111/j.1365-246X.2011.04952.x
     1#Test Name: GiaCaron
     2#Forward Love number solution for a viscoelastic earth,
     3#model M3-L70-V01 from Spada, G., Barletta, V. R., Klemann, V., Riva, R. E. M.,
     4#Martinec, Z., Gasperini, P., Lund, B., Wolf, D., Vermeersen, L. L. A.
     5#and King, M. A. (2011), A benchmark study for glacial isostatic
     6#adjustment codes. Geophysical Journal International,
     7#185: 106-132. doi:10.1111/j.1365-246X.2011.04952.x
    78
    89from model import *
     
    4849#Fields and tolerances to track changes
    4950#loading love numbers
    50 field_names=['LoveHe','LoveKe','LoveLe']
    51 field_tolerances=[3.7e-9,3.7e-9,3.7e-9]
     51field_names=['LoveH_loading_elastic','LoveK_loading_elastic','LoveL_loading_elastic']
     52field_tolerances=[4.3e-9,4.3e-9,4.3e-9]
    5253field_values=[
    5354np.array(md.results.LoveSolution.LoveHr)[:,0],
     
    6768#Fields and tolerances to track changes
    6869#loading love numbers
    69 field_names+=['LoveHlr','LoveKlr','LoveLlr','LoveHli','LoveKli','LoveLli']
    70 field_tolerances+=[3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9]
     70field_names+=['LoveH_loading_realpart','LoveK_loading_realpart','LoveL_loading_realpart','LoveH_loading_imagpart','LoveK_loading_imagpart','LoveL_loading_imagpart']
     71field_tolerances+=[5e-7,5e-7,5e-7,5e-7,5e-7,5e-7]
    7172field_values+=[
    7273np.array(md.results.LoveSolution.LoveHr),
     
    8788
    8889#tidal love numbers, check
    89 field_names+=['LoveHtr','LoveKtr','LoveLtr','LoveHti','LoveKti','LoveLti']
    90 field_tolerances+=[3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9]
     90field_names+=['LoveH_tidal_elastic','LoveK_tidal_elastic','LoveL_tidal_elastic','LoveH_tidal_realpart','LoveK_tidal_realpart','LoveL_tidal_realpart','LoveH_tidal_imagpart','LoveK_tidal_imagpart','LoveL_tidal_imagpart']
     91field_tolerances+=[8e-6,8e-6,8e-6,8e-6,8e-6,8e-6,8e-6,8e-6,8e-6]
    9192field_values+=[
    9293np.array(md.results.LoveSolution.LoveHr)[:,0],
     
    127128#md=solve(md,'lv')
    128129#
    129 #field_names=[field_names,'LoveHmr','LoveKmr','LoveLmr','LoveHmi','LoveKmi','LoveLmi']
    130 #field_tolerances=[field_tolerances,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
     130#field_names=[field_names,'LoveH_loadingVSS96_elastic','LoveK_loadingVSS96_elastic','LoveL_loadingVSS96_elastic','LoveH_loadingVSS96_realpart','LoveK_loadingVSS96_realpart','LoveL_loadingVSS96_realpart','LoveH_loadingVSS96_imagpart','LoveK_loadingVSS96_imagpart','LoveL_loadingVSS96_imagpart']
     131#field_tolerances=[field_tolerances,4.3e-9,4.3e-9,4.3e-9,4.3e-9,4.3e-9,4.3e-9,4.3e-9,4.3e-9,4.3e-9]
    131132#field_values=[field_values,\
    132133#       (md.results.LoveSolution.LoveHr[:][0]),\
     
    186187md.love.nfreq=len(md.love.frequencies)
    187188
    188 field_names+=['LoveHmr','LoveKmr','LoveLmr','LoveHmi','LoveKmi','LoveLmi']
    189 field_tolerances+=[3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9,3.7e-9]
     189field_names+=['LoveH_loadingVSS96_elastic','LoveK_loadingVSS96_elastic','LoveL_loadingVSS96_elastic','LoveH_loadingVSS96_realpart','LoveK_loadingVSS96_realpart','LoveL_loadingVSS96_realpart','LoveH_loadingVSS96_imagpart','LoveK_loadingVSS96_imagpart','LoveL_loadingVSS96_imagpart']
     190field_tolerances+=[2e-6,2e-6,2e-6,2e-6,2e-6,2e-6,2e-6,2e-6,2e-6]
    190191field_values+=[
    191192np.array(md.results.LoveSolution.LoveHr)[:,0],
  • issm/trunk/test/NightlyRun/test211.js

    r21341 r23394  
    1212//Fields and tolerances to track changes
    1313field_names=[
    14         'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1', 
    15         'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2', 
     14        'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsGroundediceMeltingRate1',
     15        'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsGroundediceMeltingRate2',
    1616        'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3'];
    1717field_tolerances=[
    1818        2e-08,2e-08,5e-05,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,
    19         5e-06,5e-06,8e-05,5e-06,1e-07,5e-07,5e-07,5e-07,3e-06,5e-05,
     19        5e-06,5e-06,8e-05,5e-06,5e-07,5e-07,5e-07,5e-07,3e-06,5e-05,
    2020        8e-06,8e-06,8e-05,8e-06,5e-07,8e-07,8e-07,8e-07,5e-06,8e-05];
    2121field_values=[
  • issm/trunk/test/NightlyRun/test211.m

    r21341 r23394  
    1616field_tolerances={...
    1717        2e-08,2e-08,5e-05,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,...
    18         5e-06,5e-06,8e-05,5e-06,1e-07,5e-07,5e-07,5e-07,3e-06,5e-05,...
     18        5e-06,5e-06,8e-05,5e-06,5e-07,5e-07,5e-07,5e-07,3e-06,5e-05,...
    1919        8e-06,8e-06,8e-05,8e-06,5e-07,8e-07,8e-07,8e-07,5e-06,8e-05};
    2020field_values={...
  • issm/trunk/test/NightlyRun/test211.py

    r21729 r23394  
    2626                                                 'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsGroundediceMeltingRate3']
    2727field_tolerances=[2e-08,2e-08,5e-05,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,
    28                                                                         5e-06,5e-06,8e-05,5e-06,1e-07,5e-07,5e-07,5e-07,3e-06,5e-05,
    29                                                                         8e-06,8e-06,8e-05,8e-06,5e-07,8e-07,8e-07,8e-07,5e-06,8e-05]
     28        5e-06,5e-06,8e-05,5e-06,5e-07,5e-07,5e-07,5e-07,3e-06,5e-05,
     29        8e-06,8e-06,8e-05,8e-06,5e-07,8e-07,8e-07,8e-07,5e-06,8e-05]
    3030field_values=[md.results.TransientSolution[0].Vx,
    3131                                                        md.results.TransientSolution[0].Vy,
  • issm/trunk/test/NightlyRun/test215.m

    r23189 r23394  
    2424%Fields and tolerances to track changes
    2525field_names     ={'Gradient','Misfits','MaterialsRheologyBbar','Pressure','Vel','Vx','Vy'};
    26 field_tolerances={4.6e-08,1e-08,2e-08,1e-09,2e-09,2e-08,2e-08};
     26field_tolerances={4.6e-08,1e-08,2e-08,2e-09,3e-09,2e-08,2e-08};
    2727field_values={...
    2828        (md.results.StressbalanceSolution.Gradient1),...
  • issm/trunk/test/NightlyRun/test215.py

    r23189 r23394  
    3737# Fields and tolerances to track changes
    3838field_names     =['Gradient','Misfits','MaterialsRheologyBbar','Pressure','Vel','Vx','Vy']
    39 field_tolerances=[4.6e-08,1e-08,2e-09,1e-08,2e-09,2e-08,2e-08]
     39field_tolerances=[4.6e-08,1e-08,2e-08,2e-09,3e-09,2e-08,2e-08]
    4040field_values=[md.results.StressbalanceSolution.Gradient1,
    4141        md.results.StressbalanceSolution.J,
  • issm/trunk/test/NightlyRun/test290.m

    r21341 r23394  
    1111%Fields and tolerances to track changes
    1212field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
    13 field_tolerances={5e-5,5e-5,8e-5,5e-5,1e-7};
     13field_tolerances={5e-5,5e-5,8e-4,5e-4,2e-7};
    1414field_values={...
    1515        (md.results.StressbalanceSolution.Vx),...
  • issm/trunk/test/NightlyRun/test290.py

    r21729 r23394  
    2121#Fields and tolerances to track changes
    2222field_names     =['Vx', 'Vy', 'Vz', 'Vel','Pressure']
    23 field_tolerances=[5e-5,5e-5,8e-5,5e-5,1e-7]
     23field_tolerances=[5e-5,5e-5,8e-4,5e-4,2e-7]
    2424field_values=[\
    2525        md.results.StressbalanceSolution.Vx,\
  • issm/trunk/test/NightlyRun/test3015.m

    r22758 r23394  
    1515%setup autodiff parameters
    1616index=1; %this is the scalar component we are checking against
    17 md.autodiff.independents={...
    18         independent('name','md.geometry.thickness','type','vertex','nods',md.mesh.numberofvertices,'fos_forward_index',index)
     17
     18if IssmConfig('_HAVE_CODIPACK_')
     19        md.autodiff.independents={...
     20                independent('name','md.geometry.thickness','type','vertex','nods',md.mesh.numberofvertices)
     21        };
     22        md.autodiff.dependents={...
     23                dependent('name','IceVolume','type','scalar','fos_reverse_index',index)...
     24                };
     25        md.autodiff.driver='fos_reverse';
     26else
     27        md.autodiff.independents={...
     28                independent('name','md.geometry.thickness','type','vertex','nods',md.mesh.numberofvertices,'fos_forward_index',index)
    1929        };
    2030
    21 md.autodiff.dependents={...
    22         dependent('name','IceVolume','type','scalar')...
    23         };
    24 md.autodiff.driver='fos_forward';
     31        md.autodiff.dependents={...
     32                dependent('name','IceVolume','type','scalar')...
     33                };
     34        md.autodiff.driver='fos_forward';
     35end
    2536
    2637%parameters for the step-wise derivative
     
    7081md=solve(md,'Masstransport');
    7182%retrieve directly
    72 dVdh_ad=md.results.MasstransportSolution.AutodiffJacobian;
     83if IssmConfig('_HAVE_CODIPACK_')
     84        dVdh_ad=md.results.MasstransportSolution.AutodiffJacobian(index);
     85else
     86        dVdh_ad=md.results.MasstransportSolution.AutodiffJacobian;
     87end
    7388
    74 disp(sprintf('dV/dh: analytical:  %16.16g\n       using adolc:  %16.16g\n',dVdh_an,dVdh_ad));
     89disp(sprintf('dV/dh: analytical:  %16.16g\n       using ad  %16.16g\n',dVdh_an,dVdh_ad));
    7590
    7691%Fields and tolerances to track changes
  • issm/trunk/test/NightlyRun/test3480.m

    r22758 r23394  
    1818md.inversion.iscontrol=1;
    1919md.autodiff.isautodiff=1;
     20md.autodiff.driver='fos_reverse';
    2021
    2122md.friction.coefficient(1:md.mesh.numberofvertices,1)=50;
  • issm/trunk/test/NightlyRun/test3481.m

    r22758 r23394  
    1818md.inversion.iscontrol=1;
    1919md.autodiff.isautodiff=1;
     20md.autodiff.driver='fos_reverse';
    2021
    2122md.friction.coefficient(1:md.mesh.numberofvertices,1)=50;
  • issm/trunk/test/NightlyRun/test421.m

    r23189 r23394  
    1010%Fields and tolerances to track changes
    1111field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
    12 field_tolerances={1e-06,9e-07,2e-05,2e-06,2e-06};
     12field_tolerances={2e-06,9e-07,2e-05,2e-06,2e-06};
    1313field_values={...
    1414        (md.results.StressbalanceSolution.Vx),...
  • issm/trunk/test/NightlyRun/test421.py

    r23189 r23394  
    2020#Fields and tolerances to track changes
    2121field_names     =['Vx','Vy','Vz','Vel','Pressure']
    22 field_tolerances=[1e-06,9e-07,2e-05,2e-06,2e-06]
     22field_tolerances=[2e-06,9e-07,2e-05,2e-06,2e-06]
    2323field_values=[\
    2424        md.results.StressbalanceSolution.Vx,\
  • issm/trunk/test/NightlyRun/test455.m

    r21341 r23394  
    1414        md=solve(md,'Stressbalance');
    1515        field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vz' i{1}],['Vel' i{1}],['Pressure' i{1}]};
    16         field_tolerances={field_tolerances{:},6e-08,6e-08,6e-08,6e-08,3e-13};
     16        field_tolerances={field_tolerances{:},7e-08,6e-08,6e-08,6e-08,3e-13};
    1717        field_values={field_values{:},...
    1818        (md.results.StressbalanceSolution.Vx),...
  • issm/trunk/test/NightlyRun/test455.py

    r21729 r23394  
    2424        md=solve(md,'Stressbalance')
    2525        field_names     =field_names+['Vx'+i,'Vy'+i,'Vz'+i,'Vel'+i,'Pressure'+i]
    26         field_tolerances=field_tolerances+[6e-08,6e-08,6e-08,6e-08,3e-13]
     26        field_tolerances=field_tolerances+[7e-08,6e-08,6e-08,6e-08,3e-13]
    2727        field_values=field_values+[\
    2828                        md.results.StressbalanceSolution.Vx,\
  • issm/trunk/test/NightlyRun/test701.m

    r23189 r23394  
    3535md.stressbalance.spcvx(find(vertexflags(md.mesh,4)))=0;
    3636md.stressbalance.spcvy(find(vertexflags(md.mesh,4)))=0;
     37md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
    3738
    3839%Misc
  • issm/trunk/test/NightlyRun/test701.py

    r23189 r23394  
    4242md.stressbalance.spcvx[np.where(md.mesh.vertexflags(4))] = 0.
    4343md.stressbalance.spcvy[np.where(md.mesh.vertexflags(4))] = 0.
     44md.basalforcings.floatingice_melting_rate=np.zeros((md.mesh.numberofvertices,))
    4445
    4546#Misc
  • issm/trunk/test/NightlyRun/test702.m

    r23189 r23394  
    3434md.stressbalance.spcvx(find(vertexflags(md.mesh,4)))=800;
    3535md.stressbalance.spcvy(find(vertexflags(md.mesh,4)))=0;
     36md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
    3637
    3738%Misc
Note: See TracChangeset for help on using the changeset viewer.