diff --git a/ChangeLog b/ChangeLog
index e7be9648..432d3ab9 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,6 +1,11 @@
CISM Changelog
-Changes in CISM tag cism_main_2.01.002
+Changes in CISM tag cism_main_2.01.013
+======================================
+
+Updates to support building and running on Derecho. Removing redundant use statements that slowed the Intel build. Changes to Python tests to make them python3 compatible and bit for bit. Changes to update old SLAP code and make it slightly nicer for modern compilers.
+
+Changes in CISM tag cism_main_2.01.003
======================================
ESCOMP/cism/main 792e43f and 410b384
diff --git a/builds/cheyenne-intel/cheyenne-intel-cmake.sh b/builds/cheyenne-intel/cheyenne-intel-cmake.sh
index b6fcf777..c94d55df 100644
--- a/builds/cheyenne-intel/cheyenne-intel-cmake.sh
+++ b/builds/cheyenne-intel/cheyenne-intel-cmake.sh
@@ -16,7 +16,7 @@ else
fi
echo CISM: "${cism_top}"
-
+source /etc/profile.d/modules.sh
module purge
module load ncarenv/1.2
diff --git a/builds/derecho-intel/README b/builds/derecho-intel/README
new file mode 100644
index 00000000..bc2a13fb
--- /dev/null
+++ b/builds/derecho-intel/README
@@ -0,0 +1,30 @@
+This directory contains posix-compliant CMake build scripts (*-cmake.sh) and
+shell agnostic build scripts (*-cmake), which are mostly intended for csh/tcsh
+users.
+
+The posix scripts are recommended because they support out of source builds by
+using the first command-line argument to set the (top-level) CISM source
+directory. For example, to build in this directory, you may run the command:
+
+source PLATFORM-COMPILER-cmake.sh
+
+Likewise, if your CISM source is located in $CISM, you may build in a $BUILD
+subdirectory by:
+
+mkdir -p $BUILD && cd $BUILD source
+$CISM/builds/PLATFORM-COMPILER/PLATFORM-COMPILER-cmake.sh $CISM
+
+This functionality is necessary for using the build and test structure (BATS,
+located in $CISM/tests/regression/), will allow you to build multiple versions
+of CISM for testing, and make cleaning up the build directory easier.
+
+Because there isn't a reasonable way to make out-of-source capable build
+scripts work across both posix-compliant shells (sh, bash, zsh, etc.) and
+non-compliant shells (csh, tcsh), a shell agnostic build script is also
+available for csh/tcsh users.
+
+NOTE: If you edit one of these script, please reflect your changes in the other
+script!
+
+WARNING: It is possible these scripts will have diverged, so if you're having
+build problems, first check the differences between the two scripts.
diff --git a/builds/derecho-intel/derecho-intel-cmake b/builds/derecho-intel/derecho-intel-cmake
new file mode 100755
index 00000000..416d5d57
--- /dev/null
+++ b/builds/derecho-intel/derecho-intel-cmake
@@ -0,0 +1,60 @@
+# Run this script by typing: source cheyenne-intel-cmake
+# After this script completes, type: make -j 8
+# If rebuilding, type 'make clean' before running 'make -j 8'
+
+# This cmake configuration script is set up to perform a parallel build with Trilinos
+
+module purge
+module load ncarenv/23.06
+module load intel/2023.0.0
+module load intel-mpi/2021.8.0
+module load mkl/2023.0.0
+#module load mpt/2.19
+module load netcdf/4.9.2
+module load ncarcompilers/1.0.0
+#module load pnetcdf/1.11.0
+module load cmake/3.26.3
+#module load python/2.7.13
+#module load numpy/1.12.0
+#module load netcdf4-python/1.2.7
+
+# remove old build data:
+rm -f ./CMakeCache.txt
+rm -rf ./CMakeFiles
+
+echo
+echo "Doing CMake Configuration step"
+
+# Note: the compilation flags were taken from the defaults for a CESM build on
+# cheyenne-intel (using cime at 84aafd5). Some of these options are probably
+# unnecessary for a standalone cism build, but I am keeping things consistent
+# with the CESM build for simplicity.
+
+cmake \
+ -D CISM_BUILD_CISM_DRIVER:BOOL=ON \
+ -D CISM_ENABLE_BISICLES=OFF \
+ -D CISM_ENABLE_FELIX=OFF \
+\
+ -D CISM_USE_TRILINOS:BOOL=OFF \
+ -D CISM_MPI_MODE:BOOL=ON \
+ -D CISM_SERIAL_MODE:BOOL=OFF \
+\
+ -D CISM_USE_GPTL_INSTRUMENTATION:BOOL=OFF \
+ -D CISM_COUPLED:BOOL=OFF \
+ -D CISM_USE_CISM_FRONT_END:BOOL=OFF \
+\
+ -D CISM_NETCDF_DIR=$NETCDF \
+ -D CMAKE_VERBOSE_MAKEFILE:BOOL=OFF \
+\
+ -D CMAKE_CXX_COMPILER=mpiicpc \
+ -D CMAKE_C_COMPILER=mpicc \
+ -D CMAKE_Fortran_COMPILER=mpif90 \
+\
+ -D CMAKE_EXE_LINKER_FLAGS="-mkl=cluster" \
+\
+ -D CMAKE_Fortran_FLAGS:STRING="-qno-opt-dynamic-align -convert big_endian -assume byterecl -ftz -traceback -assume realloc_lhs -fp-model source -qopt-report -O2 -debug minimal " \
+ -D CMAKE_C_FLAGS:STRING="-qno-opt-dynamic-align -fp-model precise -std=gnu99 -qopt-report -O2 -debug minimal " \
+ -D CMAKE_CXX_FLAGS:STRING="-qno-opt-dynamic-align -fp-model precise -std=gnu99 -qopt-report -O2 -debug minimal " \
+ ../..
+
+# Note: last argument above "../.." is path to top-level cism directory
diff --git a/builds/derecho-intel/derecho-intel-cmake.sh b/builds/derecho-intel/derecho-intel-cmake.sh
new file mode 100644
index 00000000..db0475b5
--- /dev/null
+++ b/builds/derecho-intel/derecho-intel-cmake.sh
@@ -0,0 +1,73 @@
+#!/bin/sh
+
+# After this script completes, type: make -j 8
+# If rebuilding, type 'make clean' before running 'make -j 8'
+
+# Set path to top cism directory
+# Note, this is an easy way to build out of source.
+# In directory you want to build in, run:
+# $ source $CISM/builds/linux-gnu-cism/linux-gnu-cism-cmake $CISM
+# where $CISM is the path to the top level cism directory.
+if [ $# -eq 0 ]
+then
+ cism_top="../.."
+else
+ cism_top=${1%/}
+fi
+
+echo CISM: "${cism_top}"
+
+
+module purge
+module load ncarenv/23.06
+module load intel/2023.0.0
+module load mkl/2023.0.0
+#module load mpt/2.15f
+module load netcdf/4.9.2
+module load ncarcompilers/1.0.0
+#module load pnetcdf/1.8.0
+module load cmake/3.26.3
+#module load python/2.7.13
+#module load numpy/1.12.0
+#module load netcdf4-python/1.2.7
+
+# remove old build data:
+rm -f ./CMakeCache.txt
+rm -rf ./CMakeFiles
+
+echo
+echo "Doing CMake Configuration step"
+
+# Note: the compilation flags were taken from the defaults for a CESM build on
+# cheyenne-intel (using cime at 84aafd5). Some of these options are probably
+# unnecessary for a standalone cism build, but I am keeping things consistent
+# with the CESM build for simplicity.
+
+# CISM_USE_GPTL_INSTRUMENTATION -- ON by default, set to OFF to not use GPTL instrumentation.
+
+cmake \
+ -D CISM_BUILD_CISM_DRIVER:BOOL=ON \
+ -D CISM_ENABLE_BISICLES=OFF \
+ -D CISM_ENABLE_FELIX=OFF \
+\
+ -D CISM_USE_TRILINOS:BOOL=OFF \
+ -D CISM_MPI_MODE:BOOL=ON \
+ -D CISM_SERIAL_MODE:BOOL=OFF \
+\
+ -D CISM_USE_GPTL_INSTRUMENTATION:BOOL="${CISM_USE_GPTL_INSTRUMENTATION:=ON}" \
+ -D CISM_COUPLED:BOOL=OFF \
+ -D CISM_USE_CISM_FRONT_END:BOOL=OFF \
+\
+ -D CISM_NETCDF_DIR="$NETCDF" \
+ -D CISM_GPTL_DIR= "utils/libgptl" \
+ -D CMAKE_VERBOSE_MAKEFILE:BOOL=OFF \
+\
+ -D CMAKE_CXX_COMPILER=mpiicpc \
+ -D CMAKE_C_COMPILER=mpicc \
+ -D CMAKE_Fortran_COMPILER=mpif90 \
+\
+ -D CMAKE_Fortran_FLAGS:STRING="-qno-opt-dynamic-align -convert big_endian -assume byterecl -ftz -traceback -assume realloc_lhs -fp-model source -qopt-report -O2 -debug minimal " \
+ -D CMAKE_C_FLAGS:STRING="-qno-opt-dynamic-align -fp-model precise -std=gnu99 -qopt-report -O2 -debug minimal " \
+ -D CMAKE_CXX_FLAGS:STRING="-qno-opt-dynamic-align -fp-model precise -std=gnu99 -qopt-report -O2 -debug minimal " \
+ "${cism_top}"
+
diff --git a/libglimmer-solve/SLAP/dlapqc.f b/libglimmer-solve/SLAP/dlapqc.f
index b7200ec8..c97b366f 100644
--- a/libglimmer-solve/SLAP/dlapqc.f
+++ b/libglimmer-solve/SLAP/dlapqc.f
@@ -574,7 +574,7 @@ SUBROUTINE DRMGEN( NELTMX, FACTOR, IERR, N, NELT, ISYM,
DOUBLE PRECISION FACTOR, A(NELTMX)
DOUBLE PRECISION F(N), SOLN(N), DSUM(N)
INTEGER DUMMY
- REAL, EXTERNAL :: RAND
+ REAL, EXTERNAL :: SLRAND
C
C Start by setting the random number generator seed.
C This is done for reproducablility in debuggin. Remove
@@ -582,7 +582,7 @@ SUBROUTINE DRMGEN( NELTMX, FACTOR, IERR, N, NELT, ISYM,
C
C***FIRST EXECUTABLE STATEMENT DRMGEN
DUMMY = 16381
- ISEED = RAND( DUMMY )
+ ISEED = SLRAND( DUMMY )
IERR = 0
DO 10 I = 1, N
IDIAG(I) = 0
@@ -599,7 +599,7 @@ SUBROUTINE DRMGEN( NELTMX, FACTOR, IERR, N, NELT, ISYM,
C
C To keep things sparse divide by two, three or four or ...
C
- INUM = (IFIX( RAND(DUMMY)*NL ) + 1)/3
+ INUM = (IFIX( SLRAND(DUMMY)*NL ) + 1)/3
CALL DMPL( NL, INUM, ITMP )
C
C Set up this column (and row, if non-sym structure).
@@ -616,7 +616,7 @@ SUBROUTINE DRMGEN( NELTMX, FACTOR, IERR, N, NELT, ISYM,
IF( IA(NELT).EQ.ICOL ) THEN
IDIAG(ICOL) = NELT
ELSE
- A(NELT) = -RAND(DUMMY)
+ A(NELT) = -SLRAND(DUMMY)
DSUM(ICOL) = DSUM(ICOL) + A(NELT)
IF( ISYM.EQ.0 ) THEN
C
@@ -666,7 +666,7 @@ SUBROUTINE DRMGEN( NELTMX, FACTOR, IERR, N, NELT, ISYM,
CVD$ NOVECTOR
CVD$ NOCONCUR
DO 50 I = 1, N
- SOLN(I) = RAND(DUMMY)
+ SOLN(I) = SLRAND(DUMMY)
F(I) = 0.0D0
50 CONTINUE
C
@@ -702,7 +702,7 @@ SUBROUTINE DMPL( N, M, INDX )
C***ROUTINES CALLED RAND
C***END PROLOGUE
IMPLICIT DOUBLE PRECISION(A-H,O-Z)
- REAL, EXTERNAL :: RAND
+ REAL, EXTERNAL :: SLRAND
INTEGER DUMMY
INTEGER N, M, INDX(M)
C
@@ -712,10 +712,10 @@ SUBROUTINE DMPL( N, M, INDX )
IF( N*M.LT.0 .OR. M.GT.N ) RETURN
C
C.. Set the indeicies.
- INDX(1) = IFIX( RAND(DUMMY)*N ) + 1
+ INDX(1) = IFIX( SLRAND(DUMMY)*N ) + 1
CVD$ NOCONCUR
DO 30 I = 2, M
- 10 ID = IFIX( RAND(DUMMY)*N ) + 1
+ 10 ID = IFIX( SLRAND(DUMMY)*N ) + 1
C
C.. Check to see if id has already been chosen.
CVD$ NOVECTOR
diff --git a/libglimmer-solve/SLAP/xersla.f b/libglimmer-solve/SLAP/xersla.f
index 78e8049a..c9062eb4 100644
--- a/libglimmer-solve/SLAP/xersla.f
+++ b/libglimmer-solve/SLAP/xersla.f
@@ -29,7 +29,7 @@ subroutine xerabt(messg,nmessg)
c 1982.
c***routines called (none)
c***end prologue xerabt
- dimension messg(nmessg)
+ character*(*) messg
c***first executable statement xerabt
stop 1
end
@@ -300,7 +300,7 @@ subroutine xerrwv(messg,nmessg,nerr,level,ni,i1,i2,nr,r1,r2)
if (lkntrl.le.0) go to 40
c error number
write (iunit,30) lerr
- 30 format (15h error number =,i10)
+ 30 format ('15h error number =',i10)
40 continue
50 continue
c trace-back
@@ -380,8 +380,8 @@ subroutine xersav(messg,nmessg,nerr,level,icount)
if (iunit.eq.0) iunit = i1mach(4)
c print table header
write (iunit,10)
- 10 format (32h0 error message summary/
- 1 51h message start nerr level count)
+ 10 format ('32h0 error message summary'/
+ 1 '51h message start , nerr, level, count')
c print body of table
do 20 i=1,10
if (kount(i).eq.0) go to 30
@@ -391,7 +391,7 @@ subroutine xersav(messg,nmessg,nerr,level,icount)
30 continue
c print number of other errors
if (kountx.ne.0) write (iunit,40) kountx
- 40 format (41h0other errors not individually tabulated=,i10)
+ 40 format ('41h0other errors not individually tabulated=',i10)
write (iunit,50)
50 format (1x)
60 continue
@@ -811,8 +811,8 @@ subroutine xsetun(iunit)
junk = j4save(5,1,.true.)
return
end
- FUNCTION RAND(R)
-C***BEGIN PROLOGUE RAND
+ FUNCTION SLRAND(R)
+C***BEGIN PROLOGUE SLRAND
C***DATE WRITTEN 770401 (YYMMDD)
C***REVISION DATE 861211 (YYMMDD)
C***CATEGORY NO. L6A21
@@ -823,7 +823,7 @@ FUNCTION RAND(R)
C***DESCRIPTION
C
C This pseudo-random number generator is portable among a wide
-C variety of computers. RAND(R) undoubtedly is not as good as many
+C variety of computers. SLRAND(R) undoubtedly is not as good as many
C readily available installation dependent versions, and so this
C routine is not recommended for widespread usage. Its redeeming
C feature is that the exact same random numbers (to within final round-
@@ -887,18 +887,18 @@ FUNCTION RAND(R)
C possible use in a restart procedure.
C If R .GT. 0., the sequence of random numbers will start with
C the seed R mod 1. This seed is also returned as the value of
-C RAND provided the arithmetic is done exactly.
+C SLRAND provided the arithmetic is done exactly.
C
C Output Value --
-C RAND a pseudo-random number between 0. and 1.
+C SLRAND a pseudo-random number between 0. and 1.
C***REFERENCES (NONE)
C***ROUTINES CALLED (NONE)
-C***END PROLOGUE RAND
+C***END PROLOGUE SLRAND
SAVE IA1, IA0, IA1MA0, IC, IX1, IX0
DATA IA1, IA0, IA1MA0 /1536, 1029, 507/
DATA IC /1731/
DATA IX1, IX0 /0, 0/
-C***FIRST EXECUTABLE STATEMENT RAND
+C***FIRST EXECUTABLE STATEMENT SLRAND
IF (R.LT.0.) GO TO 10
IF (R.GT.0.) GO TO 20
C
@@ -912,8 +912,8 @@ FUNCTION RAND(R)
IY1 = IY1 + (IY0-IX0)/2048
IX1 = MOD (IY1, 2048)
C
- 10 RAND = IX1*2048 + IX0
- RAND = RAND / 4194304.
+ 10 SLRAND = IX1*2048 + IX0
+ SLRAND = SLRAND / 4194304.
RETURN
C
20 IX1 = AMOD(R,1.)*4194304. + 0.5
diff --git a/libglimmer/ncdf_template.F90.in b/libglimmer/ncdf_template.F90.in
index b33770a0..c0b336db 100644
--- a/libglimmer/ncdf_template.F90.in
+++ b/libglimmer/ncdf_template.F90.in
@@ -39,8 +39,15 @@ module NAME_io
! template for creating subsystem specific I/O routines
! written by Magnus Hagdorn, 2004
+ !WHL, Sept. 2023
+ ! Moved some 'use' statements to the top to avoid redundant statements that slow the build,
+ ! particularly on the Intel compiler
+
use DATAMOD
use glimmer_ncdf
+ use glimmer_paramets
+ use glimmer_physcon
+ use glimmer_scales
implicit none
@@ -69,8 +76,6 @@ contains
!*****************************************************************************
subroutine NAME_io_createall(model,data,outfiles)
! open all netCDF files for output
- use DATAMOD
- use glide_types
use glimmer_ncio
implicit none
type(glide_global_type) :: model
@@ -94,8 +99,6 @@ contains
subroutine NAME_io_writeall(data,model,atend,outfiles,time)
! if necessary write to netCDF files
- use DATAMOD
- use glide_types
use glimmer_ncio
implicit none
type(DATATYPE) :: data
@@ -142,14 +145,9 @@ contains
use cism_parallel, only: parallel_type, &
parallel_def_dim, parallel_inq_dimid, parallel_def_var, parallel_inq_varid, parallel_put_att
- use glide_types
- use DATAMOD
use glimmer_ncio
use glimmer_map_types
use glimmer_log
- use glimmer_paramets
- use glimmer_physcon
- use glimmer_scales
implicit none
type(glimmer_nc_output), pointer :: outfile
type(glide_global_type) :: model
@@ -238,10 +236,6 @@ contains
subroutine NAME_io_write(outfile,data)
use cism_parallel, only: parallel_type, parallel_inq_varid, distributed_put_var, parallel_put_var
- use DATAMOD
- use glimmer_paramets
- use glimmer_physcon
- use glimmer_scales
implicit none
type(glimmer_nc_output), pointer :: outfile
! structure containg output netCDF descriptor
@@ -387,8 +381,6 @@ contains
!*****************************************************************************
subroutine NAME_io_readall(data, model, filetype)
! read from netCDF file
- use DATAMOD
- use glide_types
use glimmer_ncio
implicit none
type(DATATYPE) :: data
@@ -425,7 +417,6 @@ contains
! Read data from forcing files
use glimmer_log
- use glide_types
use cism_parallel, only: main_task
implicit none
@@ -520,9 +511,6 @@ contains
use cism_parallel, only: parallel_type, &
parallel_inq_varid, parallel_get_att, distributed_get_var, parallel_get_var
use glimmer_log
- use DATAMOD
- use glimmer_paramets
- use glimmer_scales
implicit none
type(glimmer_nc_input), pointer :: infile
! structure containg output netCDF descriptor
@@ -547,8 +535,6 @@ contains
! check if dimension sizes in file match dims of model
use cism_parallel, only: parallel_type, parallel_inq_dimid, parallel_inquire_dimension
use glimmer_log
- use glide_types
- use DATAMOD
implicit none
type(glimmer_nc_input), pointer :: infile
! structure containg output netCDF descriptor
@@ -575,8 +561,6 @@ contains
! TODO: Write code to check for doubly listed tavg variables and throw a fatal error.
use cism_parallel, only: parallel_inq_varid
- use glide_types
- use DATAMOD
implicit none
type(glimmer_nc_output), pointer :: outfile
! structure containg output netCDF descriptor
@@ -597,7 +581,6 @@ contains
subroutine NAME_avg_reset(outfile,data)
use cism_parallel, only: parallel_inq_varid
- use DATAMOD
implicit none
type(glimmer_nc_output), pointer :: outfile
! structure containg output netCDF descriptor
diff --git a/libglint/glint_initialise.F90 b/libglint/glint_initialise.F90
index 73ffdeea..868b7fb4 100644
--- a/libglint/glint_initialise.F90
+++ b/libglint/glint_initialise.F90
@@ -557,6 +557,7 @@ subroutine glint_i_end(instance)
!> Tidy up
use glide
+ use glide_stop, only : glide_finalise
use glimmer_ncio
implicit none
type(glint_instance), intent(inout) :: instance !> The instance being initialised.
diff --git a/tests/MISMIP/mismip.code/README.mismip b/tests/MISMIP/mismip.code/README.mismip
index e837fa4b..680ea718 100644
--- a/tests/MISMIP/mismip.code/README.mismip
+++ b/tests/MISMIP/mismip.code/README.mismip
@@ -1,12 +1,14 @@
Instructions for setting up and running the MISMIP experiments with CISM.
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
Note: These instructions assume that you have access to the NCAR HPC Cheyenne,
with an LIWG HPC account. If you do not have an account and would like one,
please contact Gunter Leguy (gunterl@ucar.edu).
See this paper for details on MISMIP:
-Pattyn,F., et al., Results of the Marine Ice Sheet Model Intercomparison Project, MISMIP,
-The Cryosphere, 6, 573-588, doi:10.5194/tc-6-573-2012, 2012.
+"Pattyn,F., et al., Results of the Marine Ice Sheet Model Intercomparison Project, MISMIP,
+The Cryosphere, 6, 573-588, doi:10.5194/tc-6-573-2012, 2012."
The MISMIP experiments consist of a set of advance and retreat experiments of the
grounding line. This is achieved by modifying the flow rate factor A.
diff --git a/tests/MISMIP/mismip.code/mismipPlotGL.py b/tests/MISMIP/mismip.code/mismipPlotGL.py
index 90bb1c36..894a1e8b 100755
--- a/tests/MISMIP/mismip.code/mismipPlotGL.py
+++ b/tests/MISMIP/mismip.code/mismipPlotGL.py
@@ -5,7 +5,7 @@
from netCDF4 import Dataset
-from optparse import OptionParser
+from argparse import ArgumentParser
import numpy as np
import matplotlib.pyplot as plt
import sys, os
@@ -194,17 +194,14 @@ def xgSemianalytic(bedType):
# Parse options.
-optparser = OptionParser()
+parser = ArgumentParser()
-optparser.add_option('-x', '--expt', dest='experiment', type='string', default = 'all', help='MISMIP experiment set to run', metavar="EXPT")
-optparser.add_option('-s', '--stat', dest='StatChoice',type='string',default='advance', help='MISMIP experiment set to run', metavar="EXPT")
-optparser.add_option('--bed', dest='bedtopo', type='string', default ='linear',help='bed topography, linear or poly', metavar='BEDTOPO')
+parser.add_argument('-x', '--expt', dest='experiment', type=str, default = 'all', help='MISMIP experiment set to run', metavar="EXPT")
+parser.add_argument('-s', '--stat', dest='StatChoice',type=str,default='advance', help='MISMIP experiment set to run', metavar="EXPT")
+parser.add_argument('--bed', dest='bedtopo', type=str, default ='linear',help='bed topography, linear or poly', metavar='BEDTOPO')
-for option in optparser.option_list:
- if option.default != ("NO", "DEFAULT"):
- option.help += (" " if option.help else "") + "[default: %default]"
-options, args = optparser.parse_args()
+options = parser.parse_args()
if options.bedtopo == 'linear':
As = AsLinear
diff --git a/tests/MISMIP/mismip.code/mismipRun.py b/tests/MISMIP/mismip.code/mismipRun.py
old mode 100644
new mode 100755
index 6fdf96fb..92ba2e7f
--- a/tests/MISMIP/mismip.code/mismipRun.py
+++ b/tests/MISMIP/mismip.code/mismipRun.py
@@ -11,9 +11,9 @@
import fileinput
import numpy as np
-from optparse import OptionParser
+from argparse import ArgumentParser
from netCDF4 import Dataset
-from ConfigParser import ConfigParser
+import configparser
@@ -107,7 +107,7 @@
def launchCism(executable, configfile, parallel):
# Run CISM (only if no job script is being created and/or run).
- print 'parallel =', parallel
+ print( 'parallel =', parallel)
if parallel == None:
# Perform a serial run.
@@ -131,7 +131,7 @@ def launchCism(executable, configfile, parallel):
sys.exit('Unable to execute parallel run. Please edit the script to use your MPI run command, or run manually with something like: mpirun -np 4 ./cism_driver mismip3dInit.config')
runstring = mpiexec + ' ' + executable + ' ' + configfile
- print 'Executing parallel run with: ' + runstring + '\n\n'
+ print( 'Executing parallel run with: ' + runstring + '\n\n')
# Here is where the parallel run is actually executed!
os.system(runstring)
@@ -144,19 +144,16 @@ def launchCism(executable, configfile, parallel):
########
# Parse options.
-optparser = OptionParser()
+parser = ArgumentParser()
-optparser.add_option('-e', '--exec', dest='executable',type = 'string',default='./cism_driver', help='Path to the CISM executable')
-optparser.add_option('-n', '--parallel',dest='parallel', type='int',help='Number of processors: if specified then run in parallel', metavar="NUMPROCS")
-optparser.add_option('-x', '--expt', dest='experiment',type='string',default='all', help='MISMIP experiment set to run', metavar="EXPT")
-optparser.add_option('-s', '--stat', dest='StatChoice',type='string',default='advance', help='Experiment status set to run', metavar='STATUS')
-optparser.add_option('--bed', dest='bedtopo', type='string', default ='linear',help='bed topography, linear or poly', metavar='BEDTOPO')
+parser.add_argument('-e', '--exec', dest='executable',type =str,default='./cism_driver', help='Path to the CISM executable')
+parser.add_argument('-n', '--parallel',dest='parallel', type=int,help='Number of processors: if specified then run in parallel', metavar="NUMPROCS")
+parser.add_argument('-x', '--expt', dest='experiment',type=str,default='all', help='MISMIP experiment set to run', metavar="EXPT")
+parser.add_argument('-s', '--stat', dest='StatChoice',type=str,default='advance', help='Experiment status set to run', metavar='STATUS')
+parser.add_argument('--bed', dest='bedtopo', type=str, default ='linear',help='bed topography, linear or poly', metavar='BEDTOPO')
-for option in optparser.option_list:
- if option.default != ("NO", "DEFAULT"):
- option.help += (" " if option.help else "") + "[default: %default]"
-options, args = optparser.parse_args()
+options = parser.parse_args()
if options.bedtopo == 'linear':
@@ -180,15 +177,15 @@ def launchCism(executable, configfile, parallel):
if options.experiment == 'all':
experiments = As
Astat = Astatus
- print 'Running all the MISMIP experiments'
+ print( 'Running all the MISMIP experiments')
elif options.experiment == 'advance':
experiments = AsAdvance
Astat = AstatusAdvance
- print 'Running advance experiments'
+ print( 'Running advance experiments')
elif options.experiment == 'retreat':
experiments = AsRetreat
Astat = AstatusRetreat
- print 'Running retreat experiments'
+ print( 'Running retreat experiments')
elif options.experiment in As:
# In this case there might be 2 possibilities, advance or retreat.
experiments = [options.experiment]
@@ -197,7 +194,7 @@ def launchCism(executable, configfile, parallel):
else:
Astat = ['advance']
- print 'Running experiment ', options.experiment
+ print( 'Running experiment ', options.experiment)
else:
sys.exit('Please specify experiment(s) from this list: all, advance, retreat or a single value from Pattyn et al.2012.')
@@ -219,14 +216,17 @@ def launchCism(executable, configfile, parallel):
# Change to A value directory.
os.chdir(expt)
- print 'changed directory to ', stat+'/'+expt
+ print( 'changed directory to ', stat+'/'+expt)
# Name of the restart pointer file.
restartPointer = 'mismip_' + expt + '.pointer'
# Read information from config file.
configfile = 'mismip_' + expt + '.config'
- config = ConfigParser()
+ config = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config.read(configfile)
inputFile = config.get('CF input', 'name')
@@ -257,10 +257,10 @@ def launchCism(executable, configfile, parallel):
pass
elif (lastTimeEntry < endTime) and (sizeTimeOutput > 1):
# The run for this A value is not done and needs to continue.
- print 'Continuing experiment from restart.'
+ print( 'Continuing experiment from restart.')
# Make sure restart is set to 1 in config file.
- config.set('options', 'restart', 1)
+ config.set('options', 'restart', '1')
# Write to config file.
with open(configfile, 'w') as newconfigfile:
@@ -274,29 +274,29 @@ def launchCism(executable, configfile, parallel):
lastTimeEntry = outputData['time'][-1]
outputData.close()
if (lastTimeEntry >= (endTime - buffer)):
- print 'Finished experiment', expt
+ print( 'Finished experiment', expt)
else:
- print 'Experiment interrupted.'
+ print( 'Experiment interrupted.')
sys.exit('Terminating the run.')
else:
# Start the experiment from time = 0.
if (expt == As[0]) and (stat=='advance'):
- print 'First A-value, beginning from initial setup.'
+ print( 'First A-value, beginning from initial setup.')
else:
- print 'Restarting from previous A-value restart file.'
+ print( 'Restarting from previous A-value restart file.')
inputData = Dataset(inputFile,'r+')
lastEntryInternal = inputData['internal_time'][-1]
inputslice = 1
- if lastentry != 0:
+ if lastEntryInternal != 0:
inputData['internal_time'][:] = inputData['internal_time'][:] - lastEntryInternal
- print 'the new internal_time array is ', inputData['internal_time'][:]
+ print( 'the new internal_time array is ', inputData['internal_time'][:])
inputData.close()
# Set config file.
- config.set('CF input', 'time', inputslice)
+ config.set('CF input', 'time', str(inputslice))
# launch CISM.
@@ -307,9 +307,9 @@ def launchCism(executable, configfile, parallel):
lastTimeEntry = outputData['time'][-1]
outputData.close()
if (lastTimeEntry >= (endTime - buffer)):
- print 'Finished experiment', expt
+ print( 'Finished experiment', expt)
else:
- print 'Experiment interrupted.'
+ print( 'Experiment interrupted.')
sys.exit('Terminating the run.')
diff --git a/tests/MISMIP/mismip.code/mismipSetup.py b/tests/MISMIP/mismip.code/mismipSetup.py
index 44bdc2d0..fb1dfd57 100755
--- a/tests/MISMIP/mismip.code/mismipSetup.py
+++ b/tests/MISMIP/mismip.code/mismipSetup.py
@@ -14,8 +14,8 @@
import fileinput
import numpy as np
from netCDF4 import Dataset
-from ConfigParser import ConfigParser
-from optparse import OptionParser
+import configparser
+from argparse import ArgumentParser
###############################
@@ -258,27 +258,22 @@ def computeHGuess(xH, xu, bedType, HInitType):
# Parse options.
-optparser = OptionParser()
+parser = ArgumentParser()
-optparser.add_option('-c', '--config',dest='configfile', type='string',default='mismip.config.template', help='config file name for setting up the MISMIP experiment', metavar='FILE')
-optparser.add_option('-e', '--exec', dest='executable',default='cism_driver',help='Set path to the CISM executable', metavar='EXECUTABLE')
-optparser.add_option('-x', '--expt', dest='experiment', type='string',default = 'all', help='MISMIP experiment(s) to set up', metavar='EXPT')
-optparser.add_option('-t', '--tstep', dest='timestep', type='float', default = 1, help='time step (yr)', metavar='TSTEP')
-optparser.add_option('-r', '--res', dest='resolution', type='int', default = 2000, help='grid resolution (m)', metavar='RES')
-optparser.add_option('-v', '--vlevel',dest='vertlevels', type='int', default = 3, help='no. of vertical levels', metavar='VLEVEL')
-optparser.add_option('-a', '--approx',dest='approximation',type='string',default = 'DIVA',help='Stokes approximation (SSA, DIVA, BP)', metavar='APPROXIMATION')
-optparser.add_option('-b', '--basal', dest='basalFriction', type='string', default='powerlaw', help='Basal friction law (powerlaw, schoof)', metavar='BASALFRICTION')
-optparser.add_option('-y', '--year', dest='yearsSpinup', type='int', default = 30000, help='Length of Spinup run (yr)', metavar='YEARSPINUP')
-optparser.add_option('--bed', dest='bedtopo', type='string',default ='linear',help='bed topography, linear or poly', metavar='BEDTOPO')
-optparser.add_option('--yrun', dest='yearsRun', type='int', default ='20000', help='run length between 2 experiments', metavar='YEARSRUN')
-optparser.add_option('--hinit',dest='initThick',type='string',default ='slab', help='experiment initial thickness profile', metavar='INITTHICK')
+parser.add_argument('-c', '--config',dest='configfile', type=str,default='mismip.config.template', help='config file name for setting up the MISMIP experiment', metavar='FILE')
+parser.add_argument('-e', '--exec', dest='executable',default='cism_driver',help='Set path to the CISM executable', metavar='EXECUTABLE')
+parser.add_argument('-x', '--expt', dest='experiment', type=str,default = 'all', help='MISMIP experiment(s) to set up', metavar='EXPT')
+parser.add_argument('-t', '--tstep', dest='timestep', type=float, default = 1, help='time step (yr)', metavar='TSTEP')
+parser.add_argument('-r', '--res', dest='resolution', type=int, default = 2000, help='grid resolution (m)', metavar='RES')
+parser.add_argument('-v', '--vlevel',dest='vertlevels', type=int, default = 3, help='no. of vertical levels', metavar='VLEVEL')
+parser.add_argument('-a', '--approx',dest='approximation',type=str,default = 'DIVA',help='Stokes approximation (SSA, DIVA, BP)', metavar='APPROXIMATION')
+parser.add_argument('-b', '--basal', dest='basalFriction', type=str, default='powerlaw', help='Basal friction law (powerlaw, schoof)', metavar='BASALFRICTION')
+parser.add_argument('-y', '--year', dest='yearsSpinup', type=int, default = 30000, help='Length of Spinup run (yr)', metavar='YEARSPINUP')
+parser.add_argument('--bed', dest='bedtopo', type=str,default ='linear',help='bed topography, linear or poly', metavar='BEDTOPO')
+parser.add_argument('--yrun', dest='yearsRun', type=int, default ='20000', help='run length between 2 experiments', metavar='YEARSRUN')
+parser.add_argument('--hinit',dest='initThick',type=str,default ='slab', help='experiment initial thickness profile', metavar='INITTHICK')
-optparser.add_option
-
-for option in optparser.option_list:
- if option.default != ('NO', 'DEFAULT'):
- option.help += (' ' if option.help else '') + '[default: %default]'
-options, args = optparser.parse_args()
+options = parser.parse_args()
if options.bedtopo == 'linear':
@@ -309,17 +304,17 @@ def computeHGuess(xH, xu, bedType, HInitType):
experiments = As
AsTime = AsTimePoly
Astat = Astatus
- print 'Setting up all the experiments'
+ print( 'Setting up all the experiments')
elif options.experiment == 'advance':
experiments = AsAdvance
AsTime = AsTimeAdvancePoly
Astat = AstatusAdvance
- print 'Setting up advance experiments'
+ print( 'Setting up advance experiments')
elif options.experiment == 'retreat':
experiments = AsRetreat
AsTime = AsTimeRetreatPoly
Astat = AstatusRetreat
- print 'Setting up retreat experiments'
+ print( 'Setting up retreat experiments')
else:
sys.exit('Please specify experiment(s) from this list: all, advance, retreat.')
@@ -360,8 +355,8 @@ def computeHGuess(xH, xu, bedType, HInitType):
else:
sys.exit('Error: must have at least 2 vertical levels')
-print 'MISMIP grid resolution (m) =', options.resolution
-print 'Number of vertical levels =', nz
+print( 'MISMIP grid resolution (m) =', options.resolution)
+print( 'Number of vertical levels =', nz)
# Note: This is a streamline experiment with no y-direction variation in bed or forces.
# For this reason we can limit the domain in y-direction by a fixed amount of grid cells.
@@ -380,85 +375,91 @@ def computeHGuess(xH, xu, bedType, HInitType):
except OSError:
sys.exit('Could not copy', options.configfile)
-print 'Creating master config file', masterConfigFile
+print( 'Creating master config file', masterConfigFile)
# Read the master config file.
-config = ConfigParser()
+config = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config.read(masterConfigFile)
# Set the grid variables in the master config file.
-config.set('grid', 'ewn', nx)
-config.set('grid', 'nsn', ny)
-config.set('grid', 'upn', nz)
-config.set('grid', 'dew', dx)
-config.set('grid', 'dns', dy)
+config.set('grid', 'ewn', str(nx))
+config.set('grid', 'nsn', str(ny))
+config.set('grid', 'upn', str(nz))
+config.set('grid', 'dew', str(dx))
+config.set('grid', 'dns', str(dy))
# Set the time step in the msster config file.
# Set the diagnostic interval to the same value (not necessary, but helpful for debugging).
-config.set('time', 'dt', options.timestep)
-config.set('time', 'dt_diag', options.timestep)
+config.set('time', 'dt', str(options.timestep))
+config.set('time', 'dt_diag', str(options.timestep))
# Set Stokes approximation in config file.
if options.approximation == 'SSA':
which_ho_approx = 1
- print 'Using SSA velocity solver'
+ print( 'Using SSA velocity solver')
elif options.approximation == 'DIVA':
which_ho_approx = 4
- print 'Using DIVA velocity solver'
+ print( 'Using DIVA velocity solver')
elif options.approximation == 'BP':
which_ho_approx = 2
- print 'Using Blatter-Pattyn velocity solver'
+ print( 'Using Blatter-Pattyn velocity solver')
else:
which_ho_approx = 4
- print 'Defaulting to DIVA velocity solver'
+ print( 'Defaulting to DIVA velocity solver')
-config.set('ho_options', 'which_ho_approx', which_ho_approx)
+config.set('ho_options', 'which_ho_approx', str(which_ho_approx))
# Config settings related to basal friction law.
# Note: Each of these friction laws is associate with certain basal parameters.
# The desired parameters should be set in the config template.
if options.basalFriction == 'Schoof':
which_ho_babc = 11
- print 'Using Schoof basal friction law'
+ print( 'Using Schoof basal friction law')
elif options.basalFriction == 'Tsai':
which_ho_babc = 12
- print 'Using Tsai basal friction law'
+ print( 'Using Tsai basal friction law')
elif options.basalFriction == 'powerlaw':
which_ho_babc = 9
- print 'Using basal friction power law'
+ print( 'Using basal friction power law')
else:
which_ho_babc = 9 # powerlaw is default
- print 'Defaulting to powerlaw basal friction law'
+ print( 'Defaulting to powerlaw basal friction law')
-config.set('ho_options', 'which_ho_babc', which_ho_babc)
+config.set('ho_options', 'which_ho_babc', str(which_ho_babc))
# Config setting related to spin up time.
yearsSpinup = float(options.yearsSpinup)
-config.set('time', 'tend', yearsSpinup)
+config.set('time', 'tend', str(yearsSpinup))
# Config setting related to presence of ice.
-config.set('parameters','marine_limit',marine_limit)
+config.set('parameters','marine_limit', str(marine_limit))
# Write to the master config file.
with open(masterConfigFile, 'w') as configfile:
config.write(configfile)
-print 'years of Spinup experiment =', yearsSpinup
+print( 'years of Spinup experiment =', yearsSpinup)
restartfreqSpinup = min(1000.0, options.yearsSpinup) # can be changed by the user if needed
-print 'Spinup restart frequency =', restartfreqSpinup
+print( 'Spinup restart frequency =', restartfreqSpinup)
# Create the netCDF input file according to the information in the config file.
try:
- parser = ConfigParser()
+ parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
parser.read(options.configfile)
initfile = parser.get('CF input', 'name')
except OSError:
sys.exit('Error parsing ' + options.configfile)
-print 'Creating input file', initfile
+print( 'Creating input file', initfile)
ncfile = Dataset(initfile, 'w')
@@ -510,7 +511,7 @@ def computeHGuess(xH, xu, bedType, HInitType):
# Set bed topography.
bedType = options.bedtopo
-print 'Computing ' + bedType + ' bed'
+print( 'Computing ' + bedType + ' bed')
for i in range(nx):
topg[:,:,i] = computeBed(x1[i]/1.e3, bedType) # x1 is in [m] and we need input in [km]
@@ -518,9 +519,9 @@ def computeHGuess(xH, xu, bedType, HInitType):
# Creating 'linear' or 'poly' bedtype directory.
try:
os.mkdir(bedType)
- print 'Created subdirectory', bedType
+ print( 'Created subdirectory', bedType)
except OSError:
- print 'Subdirectory', bedType, 'already exists'
+ print( 'Subdirectory', bedType, 'already exists')
# Set initial ice thickness.
@@ -565,26 +566,29 @@ def computeHGuess(xH, xu, bedType, HInitType):
# Create advance and/or retreat directory if needed.
try:
os.mkdir(stat)
- print 'Created subdirectory', expt
+ print( 'Created subdirectory', expt)
except OSError:
- print 'Subdirectory', expt, 'already exists'
+ print( 'Subdirectory', expt, 'already exists')
# Change to advance or retreat directory.
os.chdir(stat)
# For each experiment, make a suitable config file and set up a subdirectory.
- print 'Creating config file for experiment A value', expt
+ print( 'Creating config file for experiment A value', expt)
# Make a copy of the mismip config file.
# Below, this copy will be tailored for the chosen MISMIP experiment,
# without changing the settings used for the Spinup experiment.
newConfigFile = 'mismip_' + expt + '.config'
- print 'Config file for this experiment:', newConfigFile
+ print( 'Config file for this experiment:', newConfigFile)
shutil.copy('../../' + masterConfigFile, newConfigFile)
# Read the new config file.
- config = ConfigParser()
+ config = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config.read(newConfigFile)
# Experiment-specific settings.
@@ -643,11 +647,11 @@ def computeHGuess(xH, xu, bedType, HInitType):
sys.exit('Exiting the run.')
# Set the start and end times.
- config.set('time', 'tstart', tstart)
- config.set('time', 'tend', tend)
+ config.set('time', 'tstart', str(tstart))
+ config.set('time', 'tend', str(tend))
# Set the default flwa value.
- config.set('parameters', 'default_flwa', float(expt))
+ config.set('parameters', 'default_flwa', str(float(expt)))
# Change the default comment.
comment = 'MISMIP experiment ' + expt
@@ -655,22 +659,22 @@ def computeHGuess(xH, xu, bedType, HInitType):
# Set input file and time slice.
config.set('CF input', 'name', inputfile)
- config.set('CF input', 'time', inputslice)
+ config.set('CF input', 'time', str(inputslice))
# Set the output filename in the section [CF output].
outfilename = 'mismip_' + expt + '.out.nc'
- print 'Output file:', outfilename
+ print( 'Output file:', outfilename)
config.set('CF output', 'name', outfilename)
- config.set('CF output', 'frequency', outputfreq)
+ config.set('CF output', 'frequency', str(outputfreq))
# Set restart info. This should be in the section called '[CF output]'.
# Note: Each experiment (except Stnd) writes out only one time slice to a restart file.
restartfilename = 'mismip_' + expt + '.restart.nc'
- print 'Restart file:', restartfilename
+ print( 'Restart file:', restartfilename)
config.set('CF restart', 'name', restartfilename)
config.set('CF restart', 'variables', 'restart')
- config.set('CF restart', 'frequency', restartfreq)
- config.set('CF restart', 'start', tstart + restartfreq)
+ config.set('CF restart', 'frequency', str(restartfreq))
+ config.set('CF restart', 'start', str(tstart + restartfreq))
config.set('CF restart', 'xtype', 'double')
# Write to the new config file.
@@ -680,15 +684,15 @@ def computeHGuess(xH, xu, bedType, HInitType):
# Create a subdirectory named for the experiment, and stage the run there.
try:
os.mkdir(expt)
- print 'Created subdirectory', expt
+ print( 'Created subdirectory', expt)
except OSError:
- print 'Subdirectory', expt, 'already exists'
+ print( 'Subdirectory', expt, 'already exists')
os.chdir(expt)
# Move the config file from the parent directory to the subdirectory.
shutil.move('../' + newConfigFile, newConfigFile)
- print 'Created config file', newConfigFile
+ print( 'Created config file', newConfigFile)
# Link to the cism_driver executable in the parent directory.
try:
diff --git a/tests/MISMIP/mismip.code/mismipWriteGL.py b/tests/MISMIP/mismip.code/mismipWriteGL.py
index 3b3fbdba..885b65f7 100755
--- a/tests/MISMIP/mismip.code/mismipWriteGL.py
+++ b/tests/MISMIP/mismip.code/mismipWriteGL.py
@@ -13,7 +13,7 @@
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
-from optparse import OptionParser
+from argparse import ArgumentParser
###############################
@@ -108,19 +108,15 @@
# Parse options.
-parser = OptionParser()
+parser = ArgumentParser()
-parser.add_option('-x', '--expt',dest='experiment',type='string', default='all', help='MISMIP experiment(s) to run', metavar="EXPT")
-parser.add_option('-f', '--file',dest='filename', type='string', help='CISM output file from MISMIP3d run', metavar="FILE")
-parser.add_option('-s', '--stat',dest='StatChoice',type='string',default='advance',help='MISMIP experiment set to run', metavar="EXPT")
-parser.add_option('--bed', dest='bedtopo', type='string', default ='linear',help='bed topography, linear or poly', metavar='BEDTOPO')
+parser.add_argument('-x', '--expt',dest='experiment',type=str, default='all', help='MISMIP experiment(s) to run', metavar="EXPT")
+parser.add_argument('-f', '--file',dest='filename', type=str, help='CISM output file from MISMIP3d run', metavar="FILE")
+parser.add_argument('-s', '--stat',dest='StatChoice',type=str,default='advance',help='MISMIP experiment set to run', metavar="EXPT")
+parser.add_argument('--bed', dest='bedtopo', type=str, default ='linear',help='bed topography, linear or poly', metavar='BEDTOPO')
-for option in parser.option_list:
- if option.default != ("NO", "DEFAULT"):
- option.help += (" " if option.help else "") + "[default: %default]"
-
-options, args = parser.parse_args()
+options = parser.parse_args()
if options.bedtopo == 'linear':
As = AsLinear
diff --git a/tests/MISMIP3d/mismip3d.code/README.mismip3d b/tests/MISMIP3d/mismip3d.code/README.mismip3d
index b7f38a36..a1425337 100644
--- a/tests/MISMIP3d/mismip3d.code/README.mismip3d
+++ b/tests/MISMIP3d/mismip3d.code/README.mismip3d
@@ -1,5 +1,7 @@
Instructions for setting up and running the MISMIP3d experiments with CISM.
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
Note: part of the instruction assumes that you have access to the NCAR HPC
Cheyenne and have access to the LIWG HPC spending account.
diff --git a/tests/MISMIP3d/mismip3d.code/mismip3dRun.py b/tests/MISMIP3d/mismip3d.code/mismip3dRun.py
index d14bb14e..66f5b71f 100755
--- a/tests/MISMIP3d/mismip3d.code/mismip3dRun.py
+++ b/tests/MISMIP3d/mismip3d.code/mismip3dRun.py
@@ -8,8 +8,8 @@
import shutil
import fileinput
import numpy as np
-from optparse import OptionParser
-from ConfigParser import ConfigParser
+from argparse import ArgumentParser
+import configparser
from netCDF4 import Dataset
@@ -48,9 +48,9 @@ def replace_string(file, oldString, newString):
if (not stringFound) and (oldString in line):
line = line.replace(oldString, newString)
stringFound = True
- print line,
+ print( line,)
else:
- print line,
+ print( line,)
@@ -60,38 +60,34 @@ def replace_string(file, oldString, newString):
# Parse options.
-optparser = OptionParser()
+parser = ArgumentParser()
-optparser.add_option('-e', '--exec', dest='executable', type = 'string', default='./cism_driver', help='Path to the CISM executable')
-optparser.add_option('-x', '--expt', dest='experiment', type='string', default='all', help='MISMIP3d experiment(s) to run', metavar='EXPT')
-optparser.add_option('-n', '--parallel', dest='parallel', type='int', help='Number of processors: if specified then run in parallel', metavar='NUMPROCS')
-optparser.add_option('--job', action="store_true", dest='jobscript', help='option to set up a script to run on HPC')
-optparser.add_option('--submit', action="store_true", dest='jobsubmit', help='option to submit the run script directly after executing this script')
+parser.add_argument('-e', '--exec', dest='executable', type =str, default='./cism_driver', help='Path to the CISM executable')
+parser.add_argument('-x', '--expt', dest='experiment', type=str, default='all', help='MISMIP3d experiment(s) to run', metavar='EXPT')
+parser.add_argument('-n', '--parallel', dest='parallel', type=int, help='Number of processors: if specified then run in parallel', metavar='NUMPROCS')
+parser.add_argument('--job', action="store_true", dest='jobscript', help='option to set up a script to run on HPC')
+parser.add_argument('--submit', action="store_true", dest='jobsubmit', help='option to submit the run script directly after executing this script')
-
-for option in optparser.option_list:
- if option.default != ('NO', 'DEFAULT'):
- option.help += (' ' if option.help else '') + '[default: %default]'
-options, args = optparser.parse_args()
+options = parser.parse_args()
if options.experiment == 'all':
experiments = ['Stnd', 'P75S', 'P75R']
- print 'Run all the MISMIP3d experiments'
+ print( 'Run all the MISMIP3d experiments')
elif options.experiment == 'allP75':
experiments = ['P75S', 'P75R']
- print 'Run all the MISMIP3d P75 (S) and (R) experiments'
+ print( 'Run all the MISMIP3d P75 (S) and (R) experiments')
elif options.experiment in ['Stnd', 'P75S', 'P75R']:
experiments = [options.experiment]
- print 'Run experiment', options.experiment
+ print( 'Run experiment', options.experiment)
else:
sys.exit('Please specify experiment(s) from this list: Stnd, P75S, P75R')
if (options.jobsubmit) and (not options.jobscript):
- print 'You are trying to submit a batch job without the job option. No job will be submitted.'
+ print( 'You are trying to submit a batch job without the job option. No job will be submitted.')
if (options.parallel is not None) and (options.jobscript):
- print 'The number of processors will not be taken into account as you will be submitting a batch job script.'
+ print( 'The number of processors will not be taken into account as you will be submitting a batch job script.')
restart = 0 # constant meant to keep track of restart status.
@@ -100,11 +96,14 @@ def replace_string(file, oldString, newString):
# Change to directory for this experiment.
os.chdir(expt)
- print 'Changed directory to ', expt
+ print( 'Changed directory to ', expt)
# Set and open config file for reading.
configfile = 'mismip3d' + expt + '.config'
- config = ConfigParser()
+ config = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config.read(configfile)
inputFile = config.get('CF input', 'name')
@@ -136,14 +135,14 @@ def replace_string(file, oldString, newString):
# The run for this A value is not done and needs to continue.
# Make sure restart is set to 1 in config file.
- config.set('options', 'restart', 1)
+ config.set('options', 'restart', '1')
# Write to config file.
with open(configfile, 'w') as newconfigfile:
config.write(newconfigfile)
else:
- print 'there is nothing to restart from, executing from the beginning'
+ print( 'there is nothing to restart from, executing from the beginning')
# Make sure we are starting from the final time slice of the input file,
@@ -162,9 +161,9 @@ def replace_string(file, oldString, newString):
infile = Dataset(inputfile,'r')
ntime = len(infile.dimensions['time']) # reading the last time slice of the previous experiment
- config.set('CF input', 'time', ntime)
- print 'input file =', inputfile
- print 'time slice =', ntime
+ config.set('CF input', 'time', str(ntime))
+ print( 'input file =', inputfile)
+ print( 'time slice =', str(ntime))
infile.close()
@@ -178,7 +177,7 @@ def replace_string(file, oldString, newString):
f_ground = infileOut.variables['f_ground'][:,:,:]
infileOut.close()
- print 'opening inputfile ',inputfile
+ print( 'opening inputfile ',inputfile)
infile = Dataset(inputfile,'r+')
nx = len(infile.dimensions['x0'])
ny = len(infile.dimensions['y0'])
@@ -186,15 +185,15 @@ def replace_string(file, oldString, newString):
y0 = infile.variables['y0'][:]
ycenter = int(ny/2)
- print 'ycenter=',ycenter
+ print( 'ycenter=',ycenter)
for i in range(1,nx-1):
if (f_ground[ntimeout-1,ycenter,i] > 0) and (f_ground[ntimeout-1,ycenter,i+1] == 0):
xGL = x0[i]
- print 'grounding line at ycenter =', xGL
+ print( 'grounding line at ycenter =', xGL)
# We now write C_space factor to the file.
- print 'writing peturbation to C_space_factor'
+ print( 'writing peturbation to C_space_factor')
for i in range(nx):
for j in range(ny):
infile.variables['C_space_factor'][-1,j,i] = computeBasalPerturbation(x0[i]/1000,y0[j]/1000,xGL/1000)
@@ -203,7 +202,7 @@ def replace_string(file, oldString, newString):
lastentry = infile['internal_time'][-1]
if lastentry != 0:
infile['internal_time'][:] = infile['internal_time'][:] - lastentry
- print 'the new internal_time array is ', infile['internal_time'][:]
+ print( 'the new internal_time array is ', infile['internal_time'][:])
infile.close()
@@ -211,13 +210,13 @@ def replace_string(file, oldString, newString):
# We need to reset C_space_factor to 1 and internal_time to 0.
if (expt == 'P75R') and (restart==0):
infile = Dataset(inputfile,'r+')
- print 'opening inputfile ',inputfile
+ print( 'opening inputfile ',inputfile)
infile.variables['C_space_factor'][:,:,:] = 1
lastentry = infile['internal_time'][-1]
if lastentry != 0:
infile['internal_time'][:] = infile['internal_time'][:] - lastentry
- print 'the new internal_time array is ', infile['internal_time'][:]
+ print( 'the new internal_time array is ', infile['internal_time'][:])
infile.close()
@@ -240,7 +239,7 @@ def replace_string(file, oldString, newString):
except:
sys.exit('Could not copy ' + templateJobScriptFile)
- print 'Created master job submission script ', newJobScriptFile, ' for experiment ', expt
+ print( 'Created master job submission script ', newJobScriptFile, ' for experiment ', expt)
# Modifying the walltime and computing power based on resolution (and Bill's experience).
@@ -309,7 +308,7 @@ def replace_string(file, oldString, newString):
linecheck = HPCpowerLook
replace_string(newJobScriptFile, HPCpowerLook, HPCpowerReplace)
except:
- print 'this line does not exist: ', linecheck
+ print( 'this line does not exist: ', linecheck)
# Modifying the executable line based on config file name.
execlineLook = 'mpiexec_mpt ./cism_driver mismip3d.config'
@@ -317,13 +316,13 @@ def replace_string(file, oldString, newString):
try:
replace_string(newJobScriptFile, execlineLook, execlineReplace)
except:
- print 'this line does not exist: ', execlineLook
+ print( 'this line does not exist: ', execlineLook)
if options.jobsubmit:
# Submitting the job.
try:
submitscriptstring = 'qsub' + ' ' + newJobScriptFile
- print 'submitting the batch job script '
+ print( 'submitting the batch job script ')
os.system(submitscriptstring)
except:
sys.exit('Could not submit job. Check if you are running this script on HPC Cheyenne.')
@@ -337,7 +336,7 @@ def replace_string(file, oldString, newString):
# Run CISM (only if no job script is being created and/or run).
- print 'parallel =', options.parallel
+ print( 'parallel =', options.parallel)
if options.parallel == None:
# Perform a serial run.
@@ -361,12 +360,12 @@ def replace_string(file, oldString, newString):
sys.exit('Unable to execute parallel run. Please edit the script to use your MPI run command, or run manually with something like: mpirun -np 4 ./cism_driver mismip3dInit.config')
runstring = mpiexec + ' ' + options.executable + ' ' + configfile
- print 'Executing parallel run with: ' + runstring + '\n\n'
+ print( 'Executing parallel run with: ' + runstring + '\n\n')
# Here is where the parallel run is actually executed.
os.system(runstring)
- print 'Finished experiment', expt
+ print( 'Finished experiment', expt)
# Change to parent directory and continue.
os.chdir('..')
diff --git a/tests/MISMIP3d/mismip3d.code/mismip3dSetup.py b/tests/MISMIP3d/mismip3d.code/mismip3dSetup.py
index e860a000..232c0645 100755
--- a/tests/MISMIP3d/mismip3d.code/mismip3dSetup.py
+++ b/tests/MISMIP3d/mismip3d.code/mismip3dSetup.py
@@ -9,9 +9,8 @@
import fileinput
import numpy as np
from netCDF4 import Dataset
-from ConfigParser import ConfigParser
-from optparse import OptionParser
-
+import configparser
+from argparse import ArgumentParser
#############
# Constants #
@@ -48,34 +47,30 @@ def computeBed(x):
# Parse options
-optparser = OptionParser()
+parser = ArgumentParser()
-optparser.add_option('-c', '--config', dest='configfile', type='string', default='mismip3d.config.template', help='config file name for setting up the MISMIP3d experiment', metavar='FILE')
-optparser.add_option('-e', '--exec', dest='executable', default='cism_driver',help='Set path to the CISM executable', metavar='EXECUTABLE')
-optparser.add_option('-x', '--expt', dest='experiment', type='string', default = 'all', help='MISMIP3d experiment to set up', metavar='EXPT')
-optparser.add_option('-t', '--tstep', dest='timestep', type='float', default = 1, help='time step (yr)', metavar='TSTEP')
-optparser.add_option('-r', '--res', dest='resolution', type='int', default = 2000, help='grid resolution (m)', metavar='RES')
-optparser.add_option('-v', '--vlevel', dest='vertlevels', type='int', default = 3, help='no. of vertical levels', metavar='VLEVEL')
-optparser.add_option('-a', '--approx', dest='approximation', type='string', default = 'DIVA', help='Stokes approximation (SSA, DIVA, BP)', metavar='APPROXIMATION')
-optparser.add_option('-b', '--basal', dest='basalFriction', type='string', default='powerlaw', help='Basal friction law (powerlaw, schoof)', metavar='BASALFRICTION')
-optparser.add_option('-y', '--year', dest='yearsStnd', type='int', default = 20000, help='Length of Stnd run (yr)', metavar='YEARSPINUP')
+parser.add_argument('-c', '--config', dest='configfile', type=str, default='mismip3d.config.template', help='config file name for setting up the MISMIP3d experiment', metavar='FILE')
+parser.add_argument('-e', '--exec', dest='executable', default='cism_driver',help='Set path to the CISM executable', metavar='EXECUTABLE')
+parser.add_argument('-x', '--expt', dest='experiment', type=str, default = 'all', help='MISMIP3d experiment to set up', metavar='EXPT')
+parser.add_argument('-t', '--tstep', dest='timestep', type=float, default = 1, help='time step (yr)', metavar='TSTEP')
+parser.add_argument('-r', '--res', dest='resolution', type=int, default = 2000, help='grid resolution (m)', metavar='RES')
+parser.add_argument('-v', '--vlevel', dest='vertlevels', type=int, default = 3, help='no. of vertical levels', metavar='VLEVEL')
+parser.add_argument('-a', '--approx', dest='approximation', type=str, default = 'DIVA', help='Stokes approximation (SSA, DIVA, BP)', metavar='APPROXIMATION')
+parser.add_argument('-b', '--basal', dest='basalFriction', type=str, default='powerlaw', help='Basal friction law (powerlaw, schoof)', metavar='BASALFRICTION')
+parser.add_argument('-y', '--year', dest='yearsStnd', type=int, default = 20000, help='Length of Stnd run (yr)', metavar='YEARSPINUP')
-optparser.add_option
-for option in optparser.option_list:
- if option.default != ('NO', 'DEFAULT'):
- option.help += (' ' if option.help else '') + '[default: %default]'
-options, args = optparser.parse_args()
+options = parser.parse_args()
if options.experiment == 'all':
experiments = ['Stnd','P75S','P75R']
- print 'Setting up all the MISMIP3d experiments'
+ print( 'Setting up all the MISMIP3d experiments')
elif options.experiment == 'allP75':
experiments = ['P75S','P75R']
- print 'Setting up P75S and P75R experiments'
+ print( 'Setting up P75S and P75R experiments')
elif options.experiment in ['Stnd','P75S','P75R']:
experiments = [options.experiment]
- print 'Setting up experiment', options.experiment
+ print( 'Setting up experiment', options.experiment)
else:
sys.exit('Please specify experiment(s) from this list: Stnd, P75S, P75R')
@@ -116,8 +111,8 @@ def computeBed(x):
else:
sys.exit('Error: must have at least 2 vertical levels')
-print 'MISMIP3d grid resolution (m) =', options.resolution
-print 'Number of vertical levels =', nz
+print( 'MISMIP3d grid resolution (m) =', options.resolution)
+print( 'Number of vertical levels =', nz)
# Set number of grid cells in each direction.
# Include a few extra cells in the x direction to handle boundary conditions.
@@ -132,79 +127,85 @@ def computeBed(x):
except OSError:
sys.exit('Could not copy', options.configfile)
-print 'Creating master config file', masterConfigFile
+print( 'Creating master config file', masterConfigFile)
# Read the master config file.
-config = ConfigParser()
+config = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config.read(masterConfigFile)
# Set the grid variables in the master config file.
-config.set('grid', 'ewn', nx)
-config.set('grid', 'nsn', ny)
-config.set('grid', 'upn', nz)
-config.set('grid', 'dew', dx)
-config.set('grid', 'dns', dy)
+config.set('grid', 'ewn', str(nx))
+config.set('grid', 'nsn', str(ny))
+config.set('grid', 'upn', str(nz))
+config.set('grid', 'dew', str(dx))
+config.set('grid', 'dns', str(dy))
# Set the time step in the msster config file.
# Set the diagnostic interval to the same value (not necessary, but helpful for debugging).
-config.set('time', 'dt', options.timestep)
-config.set('time', 'dt_diag', options.timestep)
+config.set('time', 'dt', str(options.timestep))
+config.set('time', 'dt_diag', str(options.timestep))
# Set Stokes approximation in config file.
if options.approximation == 'SSA':
which_ho_approx = 1
- print 'Using SSA velocity solver'
+ print( 'Using SSA velocity solver')
elif options.approximation == 'DIVA':
which_ho_approx = 4
- print 'Using DIVA velocity solver'
+ print( 'Using DIVA velocity solver')
elif options.approximation == 'BP':
which_ho_approx = 2
- print 'Using Blatter-Pattyn velocity solver'
+ print( 'Using Blatter-Pattyn velocity solver')
else:
which_ho_approx = 4
- print 'Defaulting to DIVA velocity solver'
+ print( 'Defaulting to DIVA velocity solver')
-config.set('ho_options', 'which_ho_approx', which_ho_approx)
+config.set('ho_options', 'which_ho_approx', str(which_ho_approx))
# Config settings related to basal friction law.
# Note: Each of these friction laws is associate with certain basal parameters.
# The desired parameters should be set in the config template.
if options.basalFriction == 'powerlaw':
p_ocean_penetration = 0
- print 'Using basal friction power law (Schoof2007)'
+ print( 'Using basal friction power law (Schoof2007)')
elif options.basalFriction == 'schoof':
p_ocean_penetration = 1
- print 'Using Schoof 2005 basal friction law'
+ print( 'Using Schoof 2005 basal friction law')
else:
p_ocean_penetration = 0 # is default
- print 'Defaulting to Powerlaw basal friction law'
+ print( 'Defaulting to Powerlaw basal friction law')
-config.set('parameters', 'p_ocean_penetration', p_ocean_penetration)
+config.set('parameters', 'p_ocean_penetration', str(p_ocean_penetration))
# Config setting related to spin up time.
yearsStnd = float(options.yearsStnd)
-config.set('time', 'tend', yearsStnd)
+config.set('time', 'tend', str(yearsStnd))
# Write to the master config file.
with open(masterConfigFile, 'w') as configfile:
config.write(configfile)
-print 'years of Stnd experiment =', yearsStnd
+print( 'years of Stnd experiment =', yearsStnd)
restartfreqStnd = min(1000.0, options.yearsStnd) # can be changed by the user if needed
-print 'Stnd restart frequency =', restartfreqStnd
+print( 'Stnd restart frequency =', restartfreqStnd)
# Create the netCDF input file according to the information in the config file.
try:
- parser = ConfigParser()
+ parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
parser.read(options.configfile)
initfile = parser.get('CF input', 'name')
except OSError:
sys.exit('Error parsing ' + options.configfile)
-print 'Creating input file', initfile
+print( 'Creating input file', initfile)
ncfile = Dataset(initfile, 'w')
@@ -282,24 +283,27 @@ def computeBed(x):
ncfile.close()
-print 'Experiments:', experiments
+print( 'Experiments:', experiments)
# Loop through experiments.
for expt in experiments:
# For each experiment, make a suitable config file and set up a subdirectory.
- print 'Creating config file for experiment', expt
+ print( 'Creating config file for experiment', expt)
# Make a copy of the mismip3dInit config file.
# Below, this copy will be tailored for the chosen MISMIP3d experiment,
# without changing the settings used for the Stnd experiment.
newConfigFile = 'mismip3d' + expt + '.config'
- print 'Config file for this experiment:', newConfigFile
+ print( 'Config file for this experiment:', newConfigFile)
shutil.copy(masterConfigFile, newConfigFile)
# Read the new config file.
- config = ConfigParser()
+ config = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config.read(newConfigFile)
# Experiment-specific settings.
@@ -331,8 +335,8 @@ def computeBed(x):
restartfreq = 1000.0
# Set the start and end times
- config.set('time', 'tstart', tstart)
- config.set('time', 'tend', tend)
+ config.set('time', 'tstart', str(tstart))
+ config.set('time', 'tend', str(tend))
# Change the default comment
comment = 'MISMIP3d experiment ' + expt
@@ -342,27 +346,27 @@ def computeBed(x):
# Note: This method may not be robust for Stnd and P75R runs that start and restart.
# For this reason, the script mismip3dRun.py makes sure the 'time' entry
# in [CF input] corresponds to the final time slice.
- print 'Input file:', inputfile
+ print( 'Input file:', inputfile)
if expt=='P75S':
config.set('CF input', 'nameOut', inputfileOut)
config.set('CF input', 'name', inputfile)
- config.set('CF input', 'time', inputslice)
+ config.set('CF input', 'time', str(inputslice))
# Set the output filename in the section [CF output1].
outfilename = 'mismip3d' + expt + '.out.nc'
- print 'Output file:', outfilename
+ print( 'Output file:', outfilename)
config.set('CF output', 'name', outfilename)
- config.set('CF output', 'frequency', outputfreq)
+ config.set('CF output', 'frequency', str(outputfreq))
# Set restart info. This should be in the section called '[CF output]'.
# Note: Each experiment (except Stnd) writes out only one time slice to a restart file.
restartfilename = 'mismip3d' + expt + '.restart.nc'
- print 'Restart file:', restartfilename
+ print( 'Restart file:', restartfilename)
config.set('CF restart', 'name', restartfilename)
config.set('CF restart', 'variables', 'restart')
- config.set('CF restart', 'frequency', restartfreq)
- config.set('CF restart', 'start', tstart + restartfreq)
+ config.set('CF restart', 'frequency', str(restartfreq))
+ config.set('CF restart', 'start', str(tstart + restartfreq))
config.set('CF restart', 'xtype', 'double')
# Write to the new config file.
@@ -372,15 +376,15 @@ def computeBed(x):
# Create a subdirectory named for the experiment, and stage the run there.
try:
os.mkdir(expt)
- print 'Created subdirectory', expt
+ print( 'Created subdirectory', expt)
except OSError:
- print 'Subdirectory', expt, 'already exists'
+ print( 'Subdirectory', expt, 'already exists')
os.chdir(expt)
# Move the config file from the parent directory to the subdirectory.
shutil.move('../' + newConfigFile, newConfigFile)
- print 'Created config file', newConfigFile
+ print( 'Created config file', newConfigFile)
# Link to the cism_driver executable in the parent directory.
try:
diff --git a/tests/MISMIP3d/mismip3d.code/mismip3dWriteGL.py b/tests/MISMIP3d/mismip3d.code/mismip3dWriteGL.py
index c76b7d57..2b8deaf0 100755
--- a/tests/MISMIP3d/mismip3d.code/mismip3dWriteGL.py
+++ b/tests/MISMIP3d/mismip3d.code/mismip3dWriteGL.py
@@ -28,17 +28,14 @@
model = '_cism'
# Parse options
-from optparse import OptionParser
-parser = OptionParser()
+from argparse import ArgumentParser
+parser = ArgumentParser()
-parser.add_option("-x", "--expt", dest="experiment", type='string', default='all', help="Name of MISMIP3d experiment(s)", metavar="EXPT")
-parser.add_option("-f", "--file", dest="filename", type='string', help="CISM output file from MISMIP3d run", metavar="FILE")
+parser.add_argument("-x", "--expt", dest="experiment", type=str, default='all', help="Name of MISMIP3d experiment(s)", metavar="EXPT")
+parser.add_argument("-f", "--file", dest="filename", type=str, help="CISM output file from MISMIP3d run", metavar="FILE")
-for option in parser.option_list:
- if option.default != ("NO", "DEFAULT"):
- option.help += (" " if option.help else "") + "[default: %default]"
-options, args = parser.parse_args()
+options = parser.parse_args()
if options.experiment:
if options.experiment == 'all':
@@ -62,8 +59,8 @@
else:
file = 'mismip3d' + expt + '.out.nc'
- print 'Creating a MISMIP3d grounding-line file for experiment', expt
- print 'Attempting to read CISM file', file
+ print( 'Creating a MISMIP3d grounding-line file for experiment', expt)
+ print( 'Attempting to read CISM file', file)
# Open the CISM output file, get needed dimensions.
# Note: (x0,y0) are dimensions of the staggered (velocity) grid.
@@ -84,7 +81,7 @@
# Initialize some variables and arrays.
# Read in some fields needed to compute diagnostics similar to the one of the MISMIP+ experiment.
- print 'Reading in CISM variables...'
+ print( 'Reading in CISM variables...')
try:
# These array names are somewhat arbitrary. Sometime I have used CISM names;
@@ -121,7 +118,7 @@
outfilename = expt + model + '.nc'
ncfile = Dataset(outfilename, 'w')
- print 'Created output file', outfilename
+ print( 'Created output file', outfilename)
# Set dimensions.
glptdim = ncfile.createDimension('nPointGL', size = None)
@@ -145,11 +142,11 @@
vMeanGL = ncfile.createVariable('vMeanGL', 'f4', ('nPointGL', 'nTime'))
# Loop over time slices and fill variables.
- print 'Adding grounding-line variables to output file...'
+ print( 'Adding grounding-line variables to output file...')
for iTime in range(nTime):
- print ' Time slice:', iTime
+ print( ' Time slice:', iTime)
# Add the scalar data for this time slice.
time[iTime] = t[iTime]
diff --git a/tests/MISMIP3d/mismip3d.code/runCISM.cheyenne.template b/tests/MISMIP3d/mismip3d.code/runCISM.cheyenne.template
index 2b8a4847..47a74e1f 100755
--- a/tests/MISMIP3d/mismip3d.code/runCISM.cheyenne.template
+++ b/tests/MISMIP3d/mismip3d.code/runCISM.cheyenne.template
@@ -3,9 +3,9 @@
#PBS -N MISMIP3d
#PBS -A P93300601
#PBS -l walltime=00:01:00
-#PBS -q economy
+#PBS -q main
#PBS -j oe
#PBS -m abe
#PBS -l select=1:ncpus=1:mpiprocs=1
-mpiexec_mpt ./cism_driver mismip3d.config
+mpiexec ./cism_driver mismip3d.config
diff --git a/tests/MISOMIP/mismip+/README.mismip+ b/tests/MISOMIP/mismip+/README.mismip+
index 7f890e97..a8736a81 100644
--- a/tests/MISOMIP/mismip+/README.mismip+
+++ b/tests/MISOMIP/mismip+/README.mismip+
@@ -1,11 +1,13 @@
Instructions for setting up and running the MISMIP+ experiments with CISM.
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
See this paper for details on MISMIP+:
-X. S. Asay-Davis et al. (2016), Experimental design for three interrelated
+"X. S. Asay-Davis et al. (2016), Experimental design for three interrelated
marine ice sheet and ocean model intercomparison projects:
MISMIP v. 3 (MISMIP+), ISOMIP v. 2 (ISOMIP+) and MISOMIP v. 1 (MISOMIP1),
-Geosci. Model Devel., 9, 2471-2497, doi: 10.5194/gmd-9-2471-2016.
+Geosci. Model Devel., 9, 2471-2497, doi: 10.5194/gmd-9-2471-2016."
The following experiments are included in MISMIP+:
@@ -72,6 +74,10 @@ This script has the following optional arguments:
Notes on optional arguments:
- If setting up all the experiments at once, the -x argument is not needed.
- The following resolutions (m) are supported: 8000, 4000, 2000, 1000, 500, 250.
+- For the timestep argument, the code takes the minimum between the parsed option and 2
+ except for the spinup experiment for which it writes the parsed argument. The reason being
+ the non spinup experiment lead to CFL violation at the first few time steps due to the
+ change in the forcing is the time step is too large.
- Some of the sensitivity experiments (e.g., Ice1r) might require a shorter time step
than the Spinup experiment. For instance, a spin-up using DIVA at 2 km is typically stable with dt = 1.0 yr.
With identical config settings, Ice1r is unstable and requires a shorter time step, e.g. dt = 0.5 yr.
diff --git a/tests/MISOMIP/mismip+/mismip+Run.py b/tests/MISOMIP/mismip+/mismip+Run.py
index 3a512b5e..7679b677 100755
--- a/tests/MISOMIP/mismip+/mismip+Run.py
+++ b/tests/MISOMIP/mismip+/mismip+Run.py
@@ -9,48 +9,44 @@
import sys, os
import fileinput
-from optparse import OptionParser
-from ConfigParser import ConfigParser
+from argparse import ArgumentParser
+import configparser
from netCDF4 import Dataset
# Parse options.
-optparser = OptionParser()
+parser = ArgumentParser()
-optparser.add_option('-e', '--exec', dest='executable', type = 'string', default ='./cism_driver', help="Path to the CISM executable")
-optparser.add_option('-x', '--expt', dest='experiment', type ='string', default = 'all', help="MISMIP+ experiment(s) to run", metavar="EXPT")
-optparser.add_option('-n', '--parallel', dest='parallel', type ='int', help="Number of processors: if specified then run in parallel", metavar="NUMPROCS")
+parser.add_argument('-e', '--exec', dest='executable', type = str, default ='./cism_driver', help="Path to the CISM executable")
+parser.add_argument('-x', '--expt', dest='experiment', type =str, default = 'all', help="MISMIP+ experiment(s) to run", metavar="EXPT")
+parser.add_argument('-n', '--parallel', dest='parallel', type =int, help="Number of processors: if specified then run in parallel", metavar="NUMPROCS")
-
-for option in optparser.option_list:
- if option.default != ("NO", "DEFAULT"):
- option.help += (" " if option.help else "") + "[default: %default]"
-options, args = optparser.parse_args()
+options = parser.parse_args()
if options.experiment == 'Spinup':
experiments = ['Spinup']
- print 'Run the MISMIP+ Spinup experiment'
+ print( 'Run the MISMIP+ Spinup experiment')
elif options.experiment == 'all':
experiments = ['Spinup', 'Ice0', 'Ice1r', 'Ice1ra', 'Ice1rr', 'Ice2r', 'Ice2ra', 'Ice2rr', 'Ice1rax', 'Ice1rrx', 'Ice2rax', 'Ice2rrx']
- print 'Run all the MISMIP+ experiments, including Spinup'
+ print( 'Run all the MISMIP+ experiments, including Spinup')
elif options.experiment == 'allIce':
experiments = ['Ice0', 'Ice1r', 'Ice1ra', 'Ice1rr', 'Ice2r', 'Ice2ra', 'Ice2rr', 'Ice1rax', 'Ice1rrx', 'Ice2rax', 'Ice2rrx']
- print 'Run all the MISMIP+ experiments, excluding Spinup'
+ print( 'Run all the MISMIP+ experiments, excluding Spinup')
elif options.experiment == 'Ice1':
experiments = ['Ice1r', 'Ice1ra', 'Ice1rr', 'Ice1rax', 'Ice1rrx']
- print 'Run the MISMIP+ Ice1 experiments'
+ print( 'Run the MISMIP+ Ice1 experiments')
elif options.experiment == 'Ice2':
experiments = ['Ice2r', 'Ice2ra', 'Ice2rr', 'Ice2rax', 'Ice2rrx']
- print 'Run the MISMIP+ Ice2 experiments'
+ print( 'Run the MISMIP+ Ice2 experiments')
elif options.experiment in ['Ice0', 'Ice1r', 'Ice1ra', 'Ice1rr', 'Ice1rax', 'Ice1rrx', 'Ice2r', 'Ice2ra', 'Ice2rr', 'Ice2rax', 'Ice2rrx']:
experiments = [options.experiment]
- print 'Run experiment', options.experiment
+ print( 'Run experiment', options.experiment)
else:
sys.exit('Please specify experiment(s) from this list: Spinup, allIce, Ice1, Ice2, Spinup, Ice0, Ice1r, Ice1ra, Ice1rr, Ice1rax, Ice1rrx, Ice2r, Ice2ra, Ice2rr, Ice2rax, Ice2rrx')
# Loop through experiments.
for expt in experiments:
- print 'Running experiment', expt
+ print( 'Running experiment', expt)
# Change to directory for this experiment.
os.chdir(expt)
@@ -62,7 +58,10 @@
# (Except for Spinup, the input file is a restart file from a previous run.)
# Read the config file.
- config = ConfigParser()
+ config = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config.read(configfile)
if expt != 'Spinup':
@@ -71,9 +70,9 @@
inputfile = config.get('CF input', 'name')
infile = Dataset(inputfile,'r+')
ntime = len(infile.dimensions['time'])
- config.set('CF input', 'time', ntime)
- print 'input file =', inputfile
- print 'time slice =', ntime
+ config.set('CF input', 'time', str(ntime))
+ print( 'input file =', inputfile)
+ print( 'time slice =', ntime)
# Before starting each test suite experiment, we need to make sure
# the Spinup restart file internal_time last entry is shifted to 0.
@@ -81,7 +80,7 @@
lastentry = infile['internal_time'][-1]
if lastentry != 0:
infile['internal_time'][:] = infile['internal_time'][:] - lastentry
- print 'the new internal_time array is ', infile['internal_time'][:]
+ print( 'the new internal_time array is ', infile['internal_time'][:])
infile.close()
@@ -114,23 +113,23 @@
pass
elif (lastTimeEntry < endTime) and (sizeTimeOutput > 1):
# The run for this A value is not done and needs to continue.
- print 'Continuing experiment from restart.'
+ print( 'Continuing experiment from restart.')
# Make sure restart is set to 1 in config file.
- config.set('options', 'restart', 1)
+ config.set('options', 'restart', '1')
# Write to config file.
with open(configfile, 'w') as newconfigfile:
config.write(newconfigfile)
else:
- print 'There is nothing to restart from, executing from the beginning.'
+ print( 'There is nothing to restart from, executing from the beginning.')
# Run CISM.
- print 'parallel =', options.parallel
+ print( 'parallel =', options.parallel)
if options.parallel == None:
# Perform a serial run.
@@ -143,6 +142,8 @@
# These calls to os.system will return the exit status: 0 for success (the command exists), some other integer for failure.
if os.system('which openmpirun > /dev/null') == 0:
mpiexec = 'openmpirun -np ' + str(options.parallel)
+ elif os.system('which mpiexec > /dev/null') == 0:
+ mpiexec = 'mpiexec -np ' + str(options.parallel)
elif os.system('which mpirun > /dev/null') == 0:
mpiexec = 'mpirun -np ' + str(options.parallel)
elif os.system('which aprun > /dev/null') == 0:
@@ -154,12 +155,12 @@
sys.exit('Unable to execute parallel run. Please edit the script to use your MPI run command, or run manually with something like: mpirun -np 4 ./cism_driver mismip+Init.config')
runstring = mpiexec + ' ' + options.executable + ' ' + configfile
- print 'Executing parallel run with: ' + runstring + '\n\n'
+ print( 'Executing parallel run with: ' + runstring + '\n\n')
# Here is where the parallel run is actually executed!
os.system(runstring)
- print 'Finished experiment', expt
+ print( 'Finished experiment', expt)
# Change to parent directory and continue.
os.chdir('..')
diff --git a/tests/MISOMIP/mismip+/mismip+Setup.py b/tests/MISOMIP/mismip+/mismip+Setup.py
index a33c85be..e84571d8 100755
--- a/tests/MISOMIP/mismip+/mismip+Setup.py
+++ b/tests/MISOMIP/mismip+/mismip+Setup.py
@@ -12,8 +12,8 @@
import fileinput
import numpy as np
from netCDF4 import Dataset
-from ConfigParser import ConfigParser
-from optparse import OptionParser
+import configparser
+from argparse import ArgumentParser
@@ -69,40 +69,35 @@ def computeBed(x,y):
########
# Parse options.
-optparser = OptionParser()
+parser = ArgumentParser()
-optparser.add_option('-c', '--config', dest='configfile', type='string', default='mismip+.config.template', help="config file template", metavar="FILE")
-optparser.add_option('-e', '--exec', dest='executable', type='string', default='cism_driver', help="path to the CISM executable")
-optparser.add_option('-x', '--expt', dest='experiment', type='string', default= 'all', help="MISMIP+ experiment(s) to set up", metavar="EXPT")
-optparser.add_option('-t', '--tstep', dest='timestep', type='float', default= 0.5, help="time step (yr)", metavar="TSTEP")
-optparser.add_option('-r', '--res', dest='resolution', type='int', default= 2000, help="grid resolution (m)", metavar="RES")
-optparser.add_option('-v', '--vlevel', dest='vertlevels', type='int', default= 3, help="no. of vertical levels", metavar="VLEVEL")
-optparser.add_option('-a', '--approx', dest='approximation', type='string', default= 'DIVA', help="Stokes approximation (SSA, DIVA, BP)")
-optparser.add_option('-b', '--basal', dest='basalFriction', type='string', default='Schoof', help="basal friction law (Schoof, Tsai, powerlaw)")
-optparser.add_option('-y', '--year', dest='yearsSpinup', type='int', default= 20000, help="length of spinup run (yr)")
+parser.add_argument('-c', '--config', dest='configfile', type=str, default='mismip+.config.template', help="config file template", metavar="FILE")
+parser.add_argument('-e', '--exec', dest='executable', type=str, default='cism_driver', help="path to the CISM executable")
+parser.add_argument('-x', '--expt', dest='experiment', type=str, default= 'all', help="MISMIP+ experiment(s) to set up", metavar="EXPT")
+parser.add_argument('-t', '--tstep', dest='timestep', type=float, default= 0.5, help="time step (yr)", metavar="TSTEP")
+parser.add_argument('-r', '--res', dest='resolution', type=int, default= 2000, help="grid resolution (m)", metavar="RES")
+parser.add_argument('-v', '--vlevel', dest='vertlevels', type=int, default= 3, help="no. of vertical levels", metavar="VLEVEL")
+parser.add_argument('-a', '--approx', dest='approximation', type=str, default= 'DIVA', help="Stokes approximation (SSA, DIVA, BP)")
+parser.add_argument('-b', '--basal', dest='basalFriction', type=str, default='Schoof', help="basal friction law (Schoof, Tsai, powerlaw)")
+parser.add_argument('-y', '--year', dest='yearsSpinup', type=int, default= 20000, help="length of spinup run (yr)")
-optparser.add_option
-
-for option in optparser.option_list:
- if option.default != ("NO", "DEFAULT"):
- option.help += (" " if option.help else "") + "[default: %default]"
-options, args = optparser.parse_args()
+options = parser.parse_args()
if options.experiment == 'all':
experiments = ['Spinup', 'Ice0', 'Ice1r', 'Ice1ra', 'Ice1rr', 'Ice1rax', 'Ice1rrx', 'Ice2r', 'Ice2ra', 'Ice2rr', 'Ice2rax', 'Ice2rrx']
- print 'Setting up all the MISMIP+ experiments'
+ print( 'Setting up all the MISMIP+ experiments')
elif options.experiment == 'allIce':
experiments = ['Ice0', 'Ice1r', 'Ice1ra', 'Ice1rr', 'Ice2r', 'Ice2ra', 'Ice2rr', 'Ice1rax', 'Ice1rrx', 'Ice2rax', 'Ice2rrx']
- print 'Run all the MISMIP+ experiments, excluding Spinup'
+ print( 'Run all the MISMIP+ experiments, excluding Spinup')
elif options.experiment == 'Ice1':
experiments = ['Ice1r', 'Ice1ra', 'Ice1rr', 'Ice1rax', 'Ice1rrx']
- print 'Run the MISMIP+ Ice1 experiments'
+ print( 'Run the MISMIP+ Ice1 experiments')
elif options.experiment == 'Ice2':
experiments = ['Ice2r', 'Ice2ra', 'Ice2rr', 'Ice2rax', 'Ice2rrx']
- print 'Run the MISMIP+ Ice2 experiments'
+ print( 'Run the MISMIP+ Ice2 experiments')
elif options.experiment in ['Spinup', 'Ice0', 'Ice1r', 'Ice1ra', 'Ice1rr', 'Ice1rax', 'Ice1rrx', 'Ice2r', 'Ice2ra', 'Ice2rr', 'Ice2rax', 'Ice2rrx']:
experiments = [options.experiment]
- print 'Setting up experiment', options.experiment
+ print( 'Setting up experiment', options.experiment)
else:
sys.exit('Please specify experiment(s) from this list: all, Spinup, Ice0, Ice1r, Ice1ra, Ice1rr, Ice1rax, Ice1rrx, Ice2r, Ice2ra, Ice2rr, Ice2rax, Ice2rrx')
@@ -141,8 +136,8 @@ def computeBed(x,y):
else:
sys.exit('Error: must have at least 2 vertical levels')
-print 'MISMIP+ grid resolution (m) =', options.resolution
-print 'Number of vertical levels =', nz
+print( 'MISMIP+ grid resolution (m) =', options.resolution)
+print( 'Number of vertical levels =', nz)
# Set number of grid cells in each direction.
# Include a few extra cells in the x direction to handle boundary conditions.
@@ -157,72 +152,78 @@ def computeBed(x,y):
except:
sys.exit('Could not copy', options.configfile)
-print 'Creating master config file', masterConfigFile
+print( 'Creating master config file', masterConfigFile)
# Read the master config file.
-config = ConfigParser()
+config = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config.read(masterConfigFile)
# Set the grid variables in the master config file.
-config.set('grid', 'ewn', nx)
-config.set('grid', 'nsn', ny)
-config.set('grid', 'upn', nz)
-config.set('grid', 'dew', dx)
-config.set('grid', 'dns', dy)
+config.set('grid', 'ewn', str(nx))
+config.set('grid', 'nsn', str(ny))
+config.set('grid', 'upn', str(nz))
+config.set('grid', 'dew', str(dx))
+config.set('grid', 'dns', str(dy))
# Set Stokes approximation in config file.
if options.approximation == 'SSA':
which_ho_approx = 1
- print 'Using SSA velocity solver'
+ print( 'Using SSA velocity solver')
elif options.approximation == 'DIVA':
which_ho_approx = 4
- print 'Using DIVA velocity solver'
+ print( 'Using DIVA velocity solver')
elif options.approximation == 'BP':
which_ho_approx = 2
- print 'Using Blatter-Pattyn velocity solver'
+ print( 'Using Blatter-Pattyn velocity solver')
else:
which_ho_approx = 4
- print 'Defaulting to DIVA velocity solver'
+ print( 'Defaulting to DIVA velocity solver')
-config.set('ho_options', 'which_ho_approx', which_ho_approx)
+config.set('ho_options', 'which_ho_approx', str(which_ho_approx))
# Config settings related to basal friction law.
# Note: Each of these friction laws is associate with certain basal parameters.
# The desired parameters should be set in the config template.
if options.basalFriction == 'Schoof':
which_ho_babc = 11
- print 'Using Schoof basal friction law'
+ print( 'Using Schoof basal friction law')
elif options.basalFriction == 'Tsai':
which_ho_babc = 12
- print 'Using Tsai basal friction law'
+ print( 'Using Tsai basal friction law')
elif options.basalFriction == 'powerlaw':
which_ho_babc = 9
- print 'Using basal friction power law'
+ print( 'Using basal friction power law')
else:
which_ho_babc = 11 # Schoof is default
- print 'Defaulting to Schoof basal friction law'
+ print( 'Defaulting to Schoof basal friction law')
-config.set('ho_options', 'which_ho_babc', which_ho_babc)
+config.set('ho_options', 'which_ho_babc', str(which_ho_babc))
yearsSpinup = float(options.yearsSpinup)
-config.set('time', 'tend', yearsSpinup)
+config.set('time', 'tend', str(yearsSpinup))
# Write to the master config file.
with open(masterConfigFile, 'w') as configfile:
config.write(configfile)
-print 'years of spinup =', yearsSpinup
-print 'spinup restart frequency =', restartfreqSpinup
+print( 'years of spinup =', yearsSpinup)
+print( 'spinup restart frequency =', restartfreqSpinup)
# Create the netCDF input file.
try:
- parser = ConfigParser()
+ parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
parser.read(options.configfile)
initfile = parser.get('CF input', 'name')
except:
sys.exit('Error parsing ' + options.configfile)
-print 'Creating input file', initfile
+print( 'Creating input file', initfile)
ncfile = Dataset(initfile, 'w')
# Create dimensions.
@@ -306,24 +307,27 @@ def computeBed(x,y):
ncfile.close()
-print 'Experiments:', experiments
+print( 'Experiments:', experiments)
# Loop through experiments.
for expt in experiments:
# For each experiment, make a suitable config file and set up a subdirectory.
- print 'Creating config file for experiment', expt
+ print( 'Creating config file for experiment', expt)
# Make a copy of the mismip+Init config file.
# Below, this copy will be tailored for the chosen MISMIP+ experiment,
# without changing the settings used for spin-up.
newConfigFile = 'mismip+' + expt + '.config'
- print 'Config file for this experiment:', newConfigFile
+ print( 'Config file for this experiment:', newConfigFile)
shutil.copy(masterConfigFile, newConfigFile)
# Read the new config file.
- config = ConfigParser()
+ config = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config.read(newConfigFile)
# Experiment-specific settings.
@@ -352,7 +356,7 @@ def computeBed(x,y):
outputfreq = 10.0
restartfreq = 100.0
elif expt == 'Ice1r':
- config.set('options', 'bmlt_float', 1)
+ config.set('options', 'bmlt_float', '1')
tstart = 0.0
tend = 100.0
inputdir = '../Spinup/'
@@ -377,7 +381,7 @@ def computeBed(x,y):
outputfreq = 100.0
restartfreq = 800.0
elif expt == 'Ice1rr':
- config.set('options', 'bmlt_float', 1)
+ config.set('options', 'bmlt_float', '1')
tstart = 100.0
tend = 200.0
inputdir = '../Ice1r/'
@@ -386,7 +390,7 @@ def computeBed(x,y):
outputfreq = 10.0
restartfreq = 100.0
elif expt == 'Ice1rrx':
- config.set('options', 'bmlt_float', 1)
+ config.set('options', 'bmlt_float', '1')
tstart = 200.0
tend = 1000.0
inputdir = '../Ice1rr/'
@@ -395,7 +399,7 @@ def computeBed(x,y):
outputfreq = 100.0
restartfreq = 800.0
elif expt == 'Ice2r':
- config.set('options', 'bmlt_float', 2)
+ config.set('options', 'bmlt_float', '2')
tstart = 0.0
tend = 100.0
inputdir = '../Spinup/'
@@ -420,7 +424,7 @@ def computeBed(x,y):
outputfreq = 100.0
restartfreq = 800.0
elif expt == 'Ice2rr':
- config.set('options', 'bmlt_float', 2)
+ config.set('options', 'bmlt_float', '2')
tstart = 100.0
tend = 200.0
inputdir = '../Ice2r/'
@@ -429,7 +433,7 @@ def computeBed(x,y):
outputfreq = 10.0
restartfreq = 100.0
elif expt == 'Ice2rrx':
- config.set('options', 'bmlt_float', 2)
+ config.set('options', 'bmlt_float', '2')
tstart = 200.0
tend = 1000.0
inputdir = '../Ice2rr/'
@@ -441,22 +445,22 @@ def computeBed(x,y):
# The Spinup run is initialized to the surface air temperature (temp_init = 1).
# For all other experiments, the initial temperature is read from the input/restart file.
if expt != 'Spinup':
- config.set('options', 'temp_init', 4)
+ config.set('options', 'temp_init', '4')
# Set the time step in the master config file.
# Set the diagnostic interval to the same value (not necessary, but helpful for debugging).
# Note: this step is necessary when running at resolution coarser that 4 km as the output files
# needs to be written every 10 years to satisfy plotting criteria.
if expt != 'Spinup':
- config.set('time', 'dt', min(options.timestep, 2.))
- config.set('time', 'dt_diag', min(options.timestep, 2.))
+ config.set('time', 'dt', str(min(options.timestep, 2.)))
+ config.set('time', 'dt_diag', str(min(options.timestep, 2.)))
else:
- config.set('time', 'dt', options.timestep)
- config.set('time', 'dt_diag', options.timestep)
+ config.set('time', 'dt', str(options.timestep))
+ config.set('time', 'dt_diag', str(options.timestep))
# Set the start and end times.
- config.set('time', 'tstart', tstart)
- config.set('time', 'tend', tend)
+ config.set('time', 'tstart', str(tstart))
+ config.set('time', 'tend', str(tend))
# Change the default comment.
comment = 'MISMIP+ experiment ' + expt
@@ -466,25 +470,25 @@ def computeBed(x,y):
# Note: This method may not be robust for Spinup runs that start and restart.
# For this reason, the script mismip+Run.py makes sure the 'time' entry
# in [CF input] corresponds to the final time slice.
- print 'Input file:', inputfile
+ print( 'Input file:', inputfile)
config.set('CF input', 'name', inputfile)
- config.set('CF input', 'time', inputslice)
+ config.set('CF input', 'time', str(inputslice))
# Set the output filename in the section '[CF output]'.
outputfile = 'mismip+' + expt + '.out.nc'
- print 'Output file:', outputfile
+ print( 'Output file:', outputfile)
config.set('CF output', 'name', outputfile)
- config.set('CF output', 'frequency', outputfreq)
+ config.set('CF output', 'frequency', str(outputfreq))
# Set restart info in the section '[CF restart]'.
# Note: Each experiment (except Spinup) writes only one time slice to a restart file.
restartfile = 'mismip+' + expt + '.restart.nc'
- print 'Restart file:', restartfile
+ print( 'Restart file:', restartfile)
config.set('CF restart', 'name', restartfile)
config.set('CF restart', 'variables', 'restart')
- config.set('CF restart', 'frequency', restartfreq)
+ config.set('CF restart', 'frequency', str(restartfreq))
config.set('CF restart', 'xtype', 'double')
- config.set('CF restart', 'write_init', False)
+ config.set('CF restart', 'write_init', 'False')
# Write to the new config file.
with open(newConfigFile, 'w') as configfile:
@@ -493,15 +497,15 @@ def computeBed(x,y):
# Create a subdirectory named for the experiment, and stage the run there.
try:
os.mkdir(expt)
- print 'Created subdirectory', expt
+ print( 'Created subdirectory', expt)
except:
- print 'Subdirectory', expt, 'already exists'
+ print( 'Subdirectory', expt, 'already exists')
os.chdir(expt)
# Move the config file from the parent directory to the subdirectory.
shutil.move('../' + newConfigFile, newConfigFile)
- print 'Created config file', newConfigFile
+ print( 'Created config file', newConfigFile)
# Link to the cism_driver executable in the parent directory.
try:
diff --git a/tests/MISOMIP/mismip+/mismip+WriteGL.py b/tests/MISOMIP/mismip+/mismip+WriteGL.py
index 267a3df0..1fc2dad8 100755
--- a/tests/MISOMIP/mismip+/mismip+WriteGL.py
+++ b/tests/MISOMIP/mismip+/mismip+WriteGL.py
@@ -25,19 +25,18 @@
model = '_cism'
# Parse options
-from optparse import OptionParser
-parser = OptionParser()
+from argparse import ArgumentParser
+
+parser = ArgumentParser()
+
#TODO - Loop over all experiments here
-parser.add_option("-x", "--expt", dest="experiment", type='string', default='all', help="Name of MISMIP+ experiment(s)", metavar="EXPT")
-parser.add_option("-f", "--file", dest="filename", type='string', help="CISM output file from MISMIP+ run, e.g. mismip+Ice0.out.nc", metavar="FILE")
+parser.add_argument("-x", "--expt", dest="experiment", type=str, default='all', help="Name of MISMIP+ experiment(s)", metavar="EXPT")
+parser.add_argument("-f", "--file", dest="filename", type=str, help="CISM output file from MISMIP+ run, e.g. mismip+Ice0.out.nc", metavar="FILE")
-for option in parser.option_list:
- if option.default != ("NO", "DEFAULT"):
- option.help += (" " if option.help else "") + "[default: %default]"
-options, args = parser.parse_args()
+options = parser.parse_args()
if options.experiment:
if options.experiment == 'all':
@@ -56,7 +55,7 @@ def glplot(ncfile, times, colora, label):
"""
ncid = Dataset(ncfile, 'r')
ltime = ncid.variables["time"][:]
- print 'ltime:', ltime[:]
+ print( 'ltime:', ltime[:])
lxmax = 0.0
lxmin = 800.0
for i in range(0, len(times)):
@@ -80,8 +79,8 @@ def glplot(ncfile, times, colora, label):
else:
file = 'mismip+' + expt + '.out.nc'
- print 'Creating a MISMIP+ grounding-line file for experiment', expt
- print 'Attempting to read CISM file', file
+ print( 'Creating a MISMIP+ grounding-line file for experiment', expt)
+ print( 'Attempting to read CISM file', file)
# Open the CISM output file, get needed dimensions
# Note: (x0,y0) are dimensions of the staggered (velocity) grid
@@ -102,7 +101,7 @@ def glplot(ncfile, times, colora, label):
# Initialize some variables and arrays
# Read in some fields needed to compute MISMIP+ diagnostics
- print 'Reading in CISM variables...'
+ print( 'Reading in CISM variables...')
try:
# These array names are somewhat arbitrary. Sometime I have used CISM names;
@@ -135,7 +134,7 @@ def glplot(ncfile, times, colora, label):
except:
sys.exit('Error: The output file is missing needed fields.')
- print 'Shape of 2D fields:', f_ground.shape
+ print( 'Shape of 2D fields:', f_ground.shape)
# Create the GL output file
#WHL: Change to [expt]_cism.nc
@@ -143,7 +142,7 @@ def glplot(ncfile, times, colora, label):
#outfilename = 'mismip+_example.cism.nc'
outfilename = expt + model + '.nc'
ncfile = Dataset(outfilename, 'w')
- print 'Created output file', outfilename
+ print( 'Created output file', outfilename)
# Set dimensions
glptdim = ncfile.createDimension('nPointGL', size = None)
@@ -167,11 +166,11 @@ def glplot(ncfile, times, colora, label):
vMeanGL = ncfile.createVariable('vMeanGL', 'f4', ('nPointGL', 'nTime'))
# Loop over time slices and fill variables
- print 'Adding grounding-line variables to output file...'
+ print( 'Adding grounding-line variables to output file...')
for iTime in range(nTime):
- print ' Time slice:', iTime
+ print( ' Time slice:', iTime)
# Add the scalar data for this time slice
time[iTime] = t[iTime]
@@ -222,7 +221,7 @@ def glplot(ncfile, times, colora, label):
plt.savefig(plotfilename)
plt.clf()
- print 'Created test plot', plotfilename, '\n'
+ print( 'Created test plot', plotfilename, '\n')
# Change to the parent directory
os.chdir('..')
diff --git a/tests/dome/README.md b/tests/dome/README.md
index f8f93c15..f18f5084 100644
--- a/tests/dome/README.md
+++ b/tests/dome/README.md
@@ -1,6 +1,8 @@
Dome test case
==============
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
This directory contains a python script for running an experiment involving an
ice sheet with an parabolic "dome" shape on a flat base.
diff --git a/tests/dome/netCDF.py b/tests/dome/netCDF.py
index 2640e87b..09e31828 100644
--- a/tests/dome/netCDF.py
+++ b/tests/dome/netCDF.py
@@ -20,9 +20,9 @@
import pycdf
netCDF_module = 'pycdf'
except ImportError:
- print 'Unable to import any of the following python modules:'
- print ' Scientific.IO.NetCDF \n netcdf4 \n pycdf'
- print 'One of them must be installed.'
+ print('Unable to import any of the following python modules:')
+ print(' Scientific.IO.NetCDF \n netcdf4 \n pycdf')
+ print('One of them must be installed.')
raise ImportError('No netCDF module found')
def NCtype(value):
diff --git a/tests/dome/runDome.py b/tests/dome/runDome.py
index 31e67c30..f573db60 100755
--- a/tests/dome/runDome.py
+++ b/tests/dome/runDome.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
#FIXME: More detailed description of this test case!!!
"""
@@ -15,7 +15,7 @@
import sys
import errno
import subprocess
-import ConfigParser
+import configparser
import numpy
import netCDF
@@ -125,7 +125,7 @@ def main():
scale_factor = 2 ** args.scale
try:
- config_parser = ConfigParser.SafeConfigParser()
+ config_parser = configparser.ConfigParser()
config_parser.read( args.config )
nz = int(config_parser.get('grid','upn'))
@@ -141,10 +141,10 @@ def main():
try:
forcing_name = config_parser.get('CF forcing','name')
forcing_root, forcing_ext = os.path.splitext(forcing_name)
- except ConfigParser.NoSectionError as noForce:
+ except configparser.NoSectionError as noForce:
forcing_name = ''
- except ConfigParser.Error as error:
+ except configparser.Error as error:
print("Error parsing " + args.config )
print(" "),
print(error)
@@ -179,7 +179,7 @@ def main():
forcing_name = forcing_root+mod+forcing_ext
config_parser.set('CF forcing', 'name', forcing_name)
- with open(config_name, 'wb') as config_file:
+ with open(config_name, 'w') as config_file:
config_parser.write(config_file)
@@ -220,9 +220,9 @@ def main():
# Calculate the thickness of the (ellipsoidal) dome of ice
for i in range(nx):
- x = float(i-nx/2)/nx
+ x = float(i-nx//2)/nx
for j in range(ny):
- y = float(j-ny/2)/ny
+ y = float(j-ny//2)/ny
r_squared = x*x+y*y
if r_squared < 0.125:
thk[0,j,i] = 2000.0 * sqrt(0.125 - r_squared)
@@ -247,7 +247,6 @@ def main():
subprocess.check_call("cp *rilinosOptions.xml "+args.output_dir, shell=True)
subprocess.check_call("mv "+file_name+" "+args.output_dir, shell=True)
subprocess.check_call("mv "+config_name+" "+args.output_dir, shell=True)
-
# create the forcing netCDF file
@@ -314,7 +313,7 @@ def main():
command_list = prep_commands(args, config_name)
commands_all = ["# DOME"+mod+" test"]
commands_all.extend(command_list)
-
+
result_mv = "mv results "+root+mod+".results 2>/dev/null"
timing_mv = "for file in cism_timing*; do mv $file "+root+mod+".$file 2>/dev/null; done"
commands_all.append(result_mv)
@@ -325,14 +324,19 @@ def main():
if not args.quiet:
print("\nRunning CISM dome test")
print( "======================\n")
+ #process = subprocess.check_call('source /etc/profile.d/modules.sh', shell=True, stderr=subprocess.STDOUT)
+ #process = subprocess.check_call('module list', shell=True, stderr=subprocess.STDOUT)
- process = subprocess.check_call(str.join("; ",command_list), shell=True)
-
+
+ process = subprocess.check_call(str.join("; ",command_list), shell=True, stderr=subprocess.STDOUT)
+
+
try:
subprocess.check_call("cd "+args.output_dir+"; "+result_mv, shell=True)
except subprocess.CalledProcessError:
pass
+
try:
subprocess.check_call("cd "+args.output_dir+"; "+timing_mv, shell=True)
except subprocess.CalledProcessError:
diff --git a/tests/halfar/README.md b/tests/halfar/README.md
index 09429c87..f22932f5 100644
--- a/tests/halfar/README.md
+++ b/tests/halfar/README.md
@@ -2,6 +2,8 @@
Halfar Test Case
================
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
This directory contains Python scripts for running an experiment involving an
ice sheet with a "dome" shape on a flat base. The time evolution of this dome
shape using the shallow-ice approximation has an analytic solution. For
@@ -78,10 +80,10 @@ Higher order
As mentioned above, the analytic solution is only valid for the shallow-ice
approximation. However, if desired the test may be run with the first-order
-Glissade dycore. To do so, use the `halfar.HO.config` file:
+Glissade dycore. To do so, use the `halfar-HO.config` file:
```sh
-./runHalfar.py -c halfar.HO.config
+./runHalfar.py -c halfar-HO.config
```
In this case, the model output should not be expected to match the analytic
diff --git a/tests/halfar/halfar.config b/tests/halfar/halfar.config
index 66118798..0ab109bd 100644
--- a/tests/halfar/halfar.config
+++ b/tests/halfar/halfar.config
@@ -28,8 +28,8 @@ which_ho_sparse = 1 ;# 1 = SLAP GMRES, 4 = Trilinos for linear solver
which_ho_nonlinear = 1 ;# 0 = Picard, 1 = accelerated Picard
[parameters]
-ice_limit = 10. ;# min thickness (m) for dynamics
-default_flwa = 1.0e-16 ;# NOTE: The Halfar testing script requires that flwa is supplied here!
+ice_limit = 10. ;# min thickness (m) for dynamics
+default_flwa = 1.0e-16 ;# NOTE: The Halfar testing script requires that flwa is supplied here!
[CF default]
comment = created with halfar.py
diff --git a/tests/halfar/halfar_results.py b/tests/halfar/halfar_results.py
index 95fbebe6..57b29047 100755
--- a/tests/halfar/halfar_results.py
+++ b/tests/halfar/halfar_results.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
# A script to compare CISM model output to the Halfar analytic solution of SIA evolution of a dome.
# Matt Hoffman, LANL, October 2013
@@ -17,7 +17,7 @@
from math import tan, pi, sin, cos
from netCDF import *
-from ConfigParser import ConfigParser
+import configparser
from runHalfar import halfarDome # located in current directory
@@ -97,7 +97,10 @@ def main():
filein = get_in_file()
# Open config file for reading
- config_parser = ConfigParser()
+ config_parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config_file = os.path.join(args.output_dir, args.output_file.replace('out.nc','config'))
config_parser.read(config_file)
@@ -105,7 +108,7 @@ def main():
# This is the only way this test case supports specifying flwa.
try:
flwa = float(config_parser.get('parameters','default_flwa'))
- print 'Parameter used: ' + config_file + ' has specified a flwa value of ' + str(flwa)
+ print('Parameter used: ' + config_file + ' has specified a flwa value of ' + str(flwa))
flow_law = int(config_parser.get('options','flow_law'))
if flow_law != 0:
sys.exit('Error: The option "flow_law" must be set to 0 for the test case to work properly.')
@@ -116,9 +119,9 @@ def main():
# Try to get ice density used by the model
try:
rhoi = float( subprocess.check_output( 'grep "real(dp),parameter :: rhoi =" ../../libglimmer/glimmer_physcon.F90 | cut -d " " -f 7 | cut -d "." -f 1', shell='/bin/bash' ) )
- print 'Parameter used: ../../libglimmer/glimmer_physcon.F90 has specified a rhoi value of ' + str(rhoi)
+ print('Parameter used: ../../libglimmer/glimmer_physcon.F90 has specified a rhoi value of ' + str(rhoi))
except:
- print 'Warning: problem getting ice density value from ../../../libglimmer/glimmer_physcon.F90 Assuming 910.0 kg/m^3 as a default value.'
+ print('Warning: problem getting ice density value from ../../../libglimmer/glimmer_physcon.F90 Assuming 910.0 kg/m^3 as a default value.')
rhoi = 910.0
@@ -141,15 +144,15 @@ def main():
RMS = ( (thkDiffIce**2).sum() / float(len(thkDiffIce)) )**0.5
# Print some stats about the error
- print '\nError statistics for cells modeled to have ice (in m):'
- print '* RMS error = ' + str( RMS )
- print '* Maximum error is ' + str( thkDiffIce.max() )
- print '* Minimum error is ' + str( thkDiffIce.min() )
- print '* Mean error is ' + str( thkDiffIce.mean() )
- print '* Median error is ' + str( np.median(thkDiffIce) )
- print '* Mean absolute error = ' + str( np.absolute(thkDiffIce).mean() )
- print '* Median absolute error = ' + str( np.median(np.absolute(thkDiffIce)) )
- print ''
+ print('\nError statistics for cells modeled to have ice (in m):')
+ print('* RMS error = ' + str( RMS ))
+ print('* Maximum error is ' + str( thkDiffIce.max() ))
+ print('* Minimum error is ' + str( thkDiffIce.min() ))
+ print('* Mean error is ' + str( thkDiffIce.mean() ))
+ print('* Median error is ' + str( np.median(thkDiffIce) ))
+ print('* Mean absolute error = ' + str( np.absolute(thkDiffIce).mean() ))
+ print('* Median absolute error = ' + str( np.median(np.absolute(thkDiffIce)) ))
+ print('')
# ================
diff --git a/tests/halfar/netCDF.py b/tests/halfar/netCDF.py
index 2640e87b..09e31828 100644
--- a/tests/halfar/netCDF.py
+++ b/tests/halfar/netCDF.py
@@ -20,9 +20,9 @@
import pycdf
netCDF_module = 'pycdf'
except ImportError:
- print 'Unable to import any of the following python modules:'
- print ' Scientific.IO.NetCDF \n netcdf4 \n pycdf'
- print 'One of them must be installed.'
+ print('Unable to import any of the following python modules:')
+ print(' Scientific.IO.NetCDF \n netcdf4 \n pycdf')
+ print('One of them must be installed.')
raise ImportError('No netCDF module found')
def NCtype(value):
diff --git a/tests/halfar/runHalfar.py b/tests/halfar/runHalfar.py
index 440803f2..3eb93bfd 100755
--- a/tests/halfar/runHalfar.py
+++ b/tests/halfar/runHalfar.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
"""
This script runs an experiment for an ice sheet with a "dome" shape on a flat
@@ -18,7 +18,7 @@
import sys
import errno
import subprocess
-import ConfigParser
+import configparser
import numpy
import netCDF
@@ -91,6 +91,8 @@ def prep_commands(args, config_name):
# These calls to os.system will return the exit status: 0 for success (the command exists), some other integer for failure
if os.system('which openmpirun > /dev/null') == 0:
mpiexec = 'openmpirun -np ' + str(args.parallel)+" "
+ elif os.system('which mpiexec > /dev/null') == 0:
+ mpiexec = 'mpiexec -np ' + str(args.parallel)+" "
elif os.system('which mpirun > /dev/null') == 0:
mpiexec = 'mpirun -np ' + str(args.parallel)+" "
elif os.system('which aprun > /dev/null') == 0:
@@ -162,7 +164,10 @@ def main():
# get the configuration
# ---------------------
try:
- config_parser = ConfigParser.SafeConfigParser()
+ config_parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config_parser.read( args.config )
nz = int(config_parser.get('grid','upn'))
@@ -181,7 +186,7 @@ def main():
file_name = config_parser.get('CF input', 'name')
root, ext = os.path.splitext(file_name)
- except ConfigParser.Error as error:
+ except configparser.Error as error:
print("Error parsing " + args.config )
print(" "),
print(error)
@@ -217,7 +222,7 @@ def main():
config_parser.set('CF output', 'name', out_name)
config_parser.set('CF output', 'xtype', 'double')
- with open(config_name, 'wb') as config_file:
+ with open(config_name, 'w') as config_file:
config_parser.write(config_file)
diff --git a/tests/ismip-hom/README.md b/tests/ismip-hom/README.md
index 661c2f97..9688e037 100644
--- a/tests/ismip-hom/README.md
+++ b/tests/ismip-hom/README.md
@@ -1,10 +1,14 @@
ISMIP-HOM Experiments
=====================
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
Ice Sheet Model Intercomparison Project for Higher-Order Models (ISMIP-HOM)
prescribes a set of experiments meant to test the implementation of higher-order
physics. For more information, see
.
+If the previous link does not work, try
+
The python scripts provided here (`runISMIP_HOM.py` and `plotISMIP_HOM.py`,
referred to in the following as the ISMIP-HOM scripts) were created to run the
@@ -27,6 +31,8 @@ For comparison you need to download the ISMIP-HOM results from
and
unzip to a directory named `ismip_all`. (Make `ismip_all` a subdirectory of the
directory containing the ISMIP-HOM scripts.)
+If the previous link does not work, try
+
You will need to either copy your executable into this directory, have the
executable in your path, or create a symbolic link to your executable, using:
diff --git a/tests/ismip-hom/netCDF.py b/tests/ismip-hom/netCDF.py
index 2640e87b..09e31828 100644
--- a/tests/ismip-hom/netCDF.py
+++ b/tests/ismip-hom/netCDF.py
@@ -20,9 +20,9 @@
import pycdf
netCDF_module = 'pycdf'
except ImportError:
- print 'Unable to import any of the following python modules:'
- print ' Scientific.IO.NetCDF \n netcdf4 \n pycdf'
- print 'One of them must be installed.'
+ print('Unable to import any of the following python modules:')
+ print(' Scientific.IO.NetCDF \n netcdf4 \n pycdf')
+ print('One of them must be installed.')
raise ImportError('No netCDF module found')
def NCtype(value):
diff --git a/tests/ismip-hom/plotISMIP_HOM.py b/tests/ismip-hom/plotISMIP_HOM.py
index 9e98c919..e616f8f3 100755
--- a/tests/ismip-hom/plotISMIP_HOM.py
+++ b/tests/ismip-hom/plotISMIP_HOM.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
"""
This script plots the results of running ISMIP-HOM experiments using CISM.
@@ -19,6 +19,9 @@
# NOTE: Did not adjust inner workings except where needed. This could
# seriously use a clean-up (probably an entire rewrite).
+# This script was modified on 04-18-22 by GRL to make it python3 compatible.
+
+
import os
import sys
import glob
@@ -27,7 +30,8 @@
from math import sqrt, sin, cos, pi
from netCDF import *
-from optparse import OptionParser
+
+from functools import reduce
import matplotlib.figure
from matplotlib import pyplot
@@ -168,15 +172,18 @@ def get_experiments_and_sizes(pattern):
# Lists of model classifications
# Note: 'aas1' is skipped below -- see line ~165
+
fullStokesModels = ['aas1','aas2','cma1','fpa2','ghg1','jvj1','mmr1','oga1','rhi1','rhi3','spr1','ssu1','yko1']
lmlaModels = ['ahu1','ahu2','bds1','fpa1','mbr1','rhi2','tpa1']
+
# Classification used in Pattyn et al. 2008 paper, but not used by this script. Listed here for reference only.
#nonFSModels = ['ahu1','ahu2','bds1','cma2','dpo1','fpa1','lpe1','mbr1','mtk1','oso1','rhi2','rhi4','rhi5','tpa1']
# Function to read data files
# Returns a list of tuples [(x0,|v0|),(x1,|v1|),...,(xm,|vm|)]
def read(filename,experiment):
+ print('experiment=',experiment)
if experiment in ['b','d','e']:
# Read two numbers, x and vx, from each line in the file
n = 2
@@ -204,14 +211,20 @@ def read(filename,experiment):
target = 0.25 # desired dimensionless y-position to use for the profile
with open(filename) as inputfile:
+ print('inputfile=',filename)
data = list()
for line in inputfile:
- row = map(float,line.strip().split()[:n])
- if reduce(lambda a,b: a or b,[x != x for x in row]):
- if printNaNwarnings:
- print 'WARNING: NaN in file', filename, line,
+ # This if statement was necessary with the update to python3 to avoid the code
+ # to crash because it would read empty lines in the text files.
+ if line == "\n":
+ continue
else:
- data.append(tuple(row))
+ row = [float(x) for x in line.strip().split()[:n]]
+ if reduce(lambda a,b: a or b,[x != x for x in row]):
+ if printNaNwarnings:
+ print( 'WARNING: NaN in file', filename, line,)
+ else:
+ data.append(tuple(row))
if experiment in ['b','d','e']:
return [( row[X], abs(row[VX]) ) for row in data] # use the absolute value of the x-velocity
@@ -244,7 +257,7 @@ def read(filename,experiment):
# print 'WARNING: unequal number of x values in file', filename
for (a,b) in zip(dataA,dataB):
if a[0]!=b[0]:
- print 'WARNING: the x values are not the same in file', filename
+ print( 'WARNING: the x values are not the same in file', filename)
# Return the interpolated values
alpha = (target-below)/(above-below)
return [(a[0],alpha*a[1]+(1-alpha)*b[1]) for (a,b) in zip(dataA,dataB)]
@@ -263,8 +276,8 @@ def main():
nonFSmodelType='All Partial Stokes'
else:
nonFSmodelType='First Order'
- print 'NOTE: The category being used for models approximating Full Stokes is: '+nonFSmodelType
- print 'For more information, see details of option -a by invoking: python plotISMIP_HOM.py --help \n'
+ print( 'NOTE: The category being used for models approximating Full Stokes is: '+nonFSmodelType)
+ print( 'For more information, see details of option -a by invoking: python plotISMIP_HOM.py --help \n')
# =========================================================
@@ -277,7 +290,6 @@ def main():
# =========================================================
pattern = get_file_pattern()
-
experiments, sizes = get_experiments_and_sizes(pattern)
if args.sizes and (set(args.sizes) <= set(map(int,sizes))):
@@ -324,16 +336,14 @@ def main():
else:
res = size
-
-
out_file = pattern.replace('-?','-'+experiment).replace('????',str(res).zfill(4))
+
netCDFfile = NetCDFFile(out_file,'r')
if netCDF_module == 'Scientific.IO.NetCDF':
velscale = netCDFfile.variables['uvel_extend'].scale_factor
else:
velscale = 1.0
-
if experiment in ['f',]:
# Convert CISM output data to the rotated coord system used by the problem setup
alpha = -3.0 * pi/180 # defined in run script
@@ -429,17 +439,20 @@ def main():
# Write a "standard" ISMIP-HOM file (example file name: "cis1a020.txt") in the "output" subdirectory
ISMIP_HOMfilename = out_file.replace('.out.nc','.txt')
+
ISMIP_HOMfile = open(ISMIP_HOMfilename,'w')
for i, x in enumerate(xx):
for j, y in enumerate(yy):
+
if experiment in ('a','c','f'): # include x and y positions
ISMIP_HOMfile.write('\t'.join(map(str,[x,y]+[v[j,i] for (v) in data]))+'\n')
else: # only include x position
ISMIP_HOMfile.write('\t'.join(map(str,[x]+[v[j,i] for (v) in data]))+'\n')
+
ISMIP_HOMfile.close()
netCDFfile.close()
except:
- print 'Warning: The CISM output file for experiment '+experiment+' at size '+str(size)+' could NOT be read successfully!'
+ print( 'Warning: The CISM output file for experiment '+experiment+' at size '+str(size)+' could NOT be read successfully!')
raise
# =========================================================
@@ -448,7 +461,7 @@ def main():
# Loop over the experiments requested on the command line
for experiment in experiments:
- print 'ISMIP-HOM', experiment.upper()
+ print( 'ISMIP-HOM', experiment.upper())
# Create the figure on which the plot axes will be placed
figure = pyplot.figure(subplotpars=matplotlib.figure.SubplotParams(top=.85,bottom=.15))
@@ -470,12 +483,12 @@ def main():
figure.legend([Line2D,Patch],[nonFSmodelType+' Mean',nonFSmodelType+' Std. Dev.'],loc=(0.55,0.02),prop=prop).draw_frame(False)
# Loop over the sizes requested on the command line
- for i, size in enumerate(map(int,sizes)):
+ for i, size in enumerate(list(map(int,sizes))):
try:
res = size
if experiment == 'f':
if size != 100 or len(sizes) > 1:
- print 'NOTE: Experiment f uses a domain size of 100 km only'
+ print( 'NOTE: Experiment f uses a domain size of 100 km only')
size = 100
res = 0
@@ -494,6 +507,7 @@ def main():
# Get the Glimmer output data
glimmerData = read(out_file.replace('.out.nc','.txt'),experiment)
+
# The Glimmer data is on a staggered grid;
# Interpolate to obtain the value at x=0 and x=1
# using periodic boundary conditions
@@ -527,7 +541,7 @@ def main():
continue # ignore the sliding version for now
if modelName == 'cma1':
continue # the cma1 'f' experiments made the x,y coords dimensionless instead of dimensional - ignore for convenience
- print 'Using data from file:',os.path.join(path,filename)
+ print( 'Using data from file:',os.path.join(path,filename))
data = read(os.path.join(path,filename),experiment)
if modelName in fullStokesModels:
index = fullStokes
@@ -560,7 +574,7 @@ def main():
xAbove,vAbove = data[a]
if xAbove == xBelow:
- print 'Surprise!',above,below,xAbove,xBelow,vAbove,vBelow
+ print( 'Surprise!',above,below,xAbove,xBelow,vAbove,vBelow)
v = (vAbove+vBelow)/2
else:
alpha = (target-xBelow)/(xAbove-xBelow)
@@ -570,7 +584,7 @@ def main():
# Calculate statistics of the other model results
if sum(count) == 0:
- print 'To compare with other models you need to download the ISMIP-HOM results from: http://www.the-cryosphere.net/2/95/2008/tc-2-95-2008-supplement.zip and unzip the contained file tc-2007-0019-sp2.zip into a directory named ismip_all. The ismip_all directory must be in the directory from which you are running this script.'
+ print( 'To compare with other models you need to download the ISMIP-HOM results from: http://www.the-cryosphere.net/2/95/2008/tc-2-95-2008-supplement.zip and unzip the contained file tc-2007-0019-sp2.zip into a directory named ismip_all. The ismip_all directory must be in the directory from which you are running this script.')
else:
# Find the mean and standard deviation of the velocities at each x
for index in (firstOrder,fullStokes):
@@ -604,18 +618,18 @@ def main():
compare = sum([(s/m) for (s,m) in zip(standardDeviation,mean)])
n = len(glimmerData)
#print '\t'.join([str(size)+' km',str(total/n),str(compare/n),str(position)])
- print 'Size='+str(size)+' km'
- print ' Mean percent error along flowline of CISM relative to mean of first-order models='+str(total/float(n))+'%'
- print ' Mean COD (stdev/mean) along flowline of mean of first-order models (excluding CISM)='+str(compare/float(n)*100.0)+'%'
- print ' Max. CISM percent error='+str(maximum)+'% at x-position '+str(position)
- print ' Max. CISM absolute error='+str(max(abserror))+' m/yr at x-position '+str(glimmerData[abserror.index(max(abserror))][0])
+ print( 'Size='+str(size)+' km' )
+ print( ' Mean percent error along flowline of CISM relative to mean of first-order models='+str(total/float(n))+'%')
+ print( ' Mean COD (stdev/mean) along flowline of mean of first-order models (excluding CISM)='+str(compare/float(n)*100.0)+'%')
+ print( ' Max. CISM percent error='+str(maximum)+'% at x-position '+str(position))
+ print( ' Max. CISM absolute error='+str(max(abserror))+' m/yr at x-position '+str(glimmerData[abserror.index(max(abserror))][0]))
except:
- print "Error in analyzing/plotting experiment ",experiment," at size ",size," km"
+ print( "Error in analyzing/plotting experiment ",experiment," at size ",size," km")
if savePlotInFile:
plot_file = pattern.replace('-?','-'+experiment).replace('.????','').replace('.out.nc',plotType)
- print 'Writing:', plot_file
+ print( 'Writing:', plot_file)
pyplot.savefig(plot_file)
# Experiment f can also have a surface profile plotted
@@ -697,7 +711,7 @@ def main():
continue # ignore the sliding version for now
if modelName == 'cma1':
continue # the cma1 'f' experiments made the x,y coords dimensionless instead of dimensional - ignore for convenience
- print 'Using data from file:',os.path.join(path,filename)
+ print( 'Using data from file:',os.path.join(path,filename))
data = read(os.path.join(path,filename), experiment='f-elevation')
if modelName in fullStokesModels:
index = fullStokes
@@ -728,7 +742,7 @@ def main():
else:
xAbove,vAbove = data[a]
if xAbove == xBelow:
- print 'Surprise!',above,below,xAbove,xBelow,vAbove,vBelow
+ print( 'Surprise!',above,below,xAbove,xBelow,vAbove,vBelow)
v = (vAbove+vBelow)/2
else:
alpha = (target-xBelow)/(xAbove-xBelow)
@@ -738,7 +752,7 @@ def main():
# Calculate statistics of the other model results
if sum(count) == 0:
- print 'To compare with other models you need to download the ISMIP-HOM results from: http://www.the-cryosphere.net/2/95/2008/tc-2-95-2008-supplement.zip and unzip the contained file tc-2007-0019-sp2.zip into a directory named ismip_all. The ismip_all directory must be in the directory from which you are running this script.'
+ print( 'To compare with other models you need to download the ISMIP-HOM results from: http://www.the-cryosphere.net/2/95/2008/tc-2-95-2008-supplement.zip and unzip the contained file tc-2007-0019-sp2.zip into a directory named ismip_all. The ismip_all directory must be in the directory from which you are running this script.')
else:
# Find the mean and standard deviation of the velocities at each x
for index in (firstOrder,fullStokes):
@@ -764,7 +778,7 @@ def main():
if savePlotInFile:
plot_file = pattern.replace('-?','-'+experiment+'-SurfaceElevation').replace('.????','').replace('.out.nc',plotType)
- print 'Writing:', plot_file
+ print( 'Writing:', plot_file)
pyplot.savefig(plot_file)
# Experiment f should be run for one size (100 km) only
diff --git a/tests/ismip-hom/runISMIP_HOM.py b/tests/ismip-hom/runISMIP_HOM.py
index 2667f738..52fb6c50 100755
--- a/tests/ismip-hom/runISMIP_HOM.py
+++ b/tests/ismip-hom/runISMIP_HOM.py
@@ -15,7 +15,7 @@
import sys
import errno
import subprocess
-import ConfigParser
+import configparser
import numpy
import netCDF
@@ -116,6 +116,8 @@ def prep_commands(args, config_name):
# These calls to os.system will return the exit status: 0 for success (the command exists), some other integer for failure
if os.system('which openmpirun > /dev/null') == 0:
mpiexec = 'openmpirun -np ' + str(args.parallel)+" "
+ elif os.system('which mpiexec > /dev/null') == 0:
+ mpiexec = 'mpiexec -np ' + str(args.parallel)+" "
elif os.system('which mpirun > /dev/null') == 0:
mpiexec = 'mpirun -np ' + str(args.parallel)+" "
elif os.system('which aprun > /dev/null') == 0:
@@ -163,7 +165,10 @@ def main():
ran_f = True
try:
- config_parser = ConfigParser.SafeConfigParser()
+ config_parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config_parser.read( args.config )
if args.vertical:
@@ -177,7 +182,7 @@ def main():
file_name = config_parser.get('CF input', 'name')
root, ext = os.path.splitext(file_name)
- except ConfigParser.Error as error:
+ except configparser.Error as error:
print("Error parsing " + args.config )
print(" "),
print(error)
@@ -224,6 +229,7 @@ def main():
offset = float(size)*1000.0 * tan(0.1 * pi/180.0)
elif experiment in ('f'):
offset = float(size)*1000.0 * tan(3.0 * pi/180.0)
+
config_parser.set('parameters', 'periodic_offset_ew', str(offset))
# if experiment in ('c' 'd'):
@@ -254,7 +260,7 @@ def main():
# write the config file
- with open(config_name, 'wb') as config_file:
+ with open(config_name, 'w') as config_file:
config_parser.write(config_file)
diff --git a/tests/new/README.md b/tests/new/README.md
index b96da93a..d756ab42 100644
--- a/tests/new/README.md
+++ b/tests/new/README.md
@@ -1,6 +1,8 @@
-How to create a new CISM test
+Hw to create a new CISM test
=============================
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
This directory contains a new test template called `runTest.py` which
should be used to create a new test in CISM. This template is based off of the
`tests/higher-order/dome` test, and you should start by playing around with that test
diff --git a/tests/new/netCDF.py b/tests/new/netCDF.py
index 2640e87b..09e31828 100644
--- a/tests/new/netCDF.py
+++ b/tests/new/netCDF.py
@@ -20,9 +20,9 @@
import pycdf
netCDF_module = 'pycdf'
except ImportError:
- print 'Unable to import any of the following python modules:'
- print ' Scientific.IO.NetCDF \n netcdf4 \n pycdf'
- print 'One of them must be installed.'
+ print('Unable to import any of the following python modules:')
+ print(' Scientific.IO.NetCDF \n netcdf4 \n pycdf')
+ print('One of them must be installed.')
raise ImportError('No netCDF module found')
def NCtype(value):
diff --git a/tests/new/runTest.py b/tests/new/runTest.py
index 846c26bd..0e826f34 100755
--- a/tests/new/runTest.py
+++ b/tests/new/runTest.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
#NOTE: This is an annotated copy of the tests/higher-order/dome/runDome.py
# script. You should play around with the dome test case first so that you
@@ -20,7 +20,7 @@
import sys
import errno
import subprocess
-import ConfigParser
+import configparser
import numpy
import netCDF
@@ -143,7 +143,10 @@ def main():
scale_factor = 2 ** args.scale
try:
- config_parser = ConfigParser.SafeConfigParser()
+ config_parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config_parser.read( args.config )
nz = int(config_parser.get('grid','upn'))
@@ -161,10 +164,10 @@ def main():
try:
forcing_name = config_parser.get('CF forcing','name')
forcing_root, forcing_ext = os.path.splitext(forcing_name)
- except ConfigParser.NoSectionError as noForce:
+ except configparser.NoSectionError as noForce:
forcing_name = ''
- except ConfigParser.Error as error:
+ except configparser.Error as error:
print("Error parsing " + args.config )
print(" "),
print(error)
@@ -202,7 +205,7 @@ def main():
forcing_name = forcing_root+mod+forcing_ext
config_parser.set('CF forcing', 'name', forcing_name)
- with open(os.path.join(args.output_dir, config_name), 'wb') as config_file:
+ with open(os.path.join(args.output_dir, config_name), 'w') as config_file:
config_parser.write(config_file)
diff --git a/tests/regression/build_and_test.py b/tests/regression/build_and_test.py
index a187dbe4..dd630029 100755
--- a/tests/regression/build_and_test.py
+++ b/tests/regression/build_and_test.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
"""
The build and test structure (BATS) module. BATS is primarily intended to allow
diff --git a/tests/regression/setup_derecho b/tests/regression/setup_derecho
new file mode 100755
index 00000000..4c964d93
--- /dev/null
+++ b/tests/regression/setup_derecho
@@ -0,0 +1,19 @@
+module load intel
+##module load git
+module load conda
+conda activate npl
+
+##module load jupyter
+
+##module load wrapt
+##module load pylint
+
+##module load numpy
+
+##module load numexpr
+##module load bottleneck
+##module load pandas
+
+##module load netcdf4-python
+
+module list
diff --git a/tests/ross/README.md b/tests/ross/README.md
index 6fb2aecf..76fe735e 100644
--- a/tests/ross/README.md
+++ b/tests/ross/README.md
@@ -1,6 +1,8 @@
Ross Ice Shelf Experiment
=========================
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
This experiment was designed to model the Ross Ice Shelf off Antarctica. For
information about the experiment and its results see:
diff --git a/tests/ross/netCDF.py b/tests/ross/netCDF.py
index 2640e87b..09e31828 100644
--- a/tests/ross/netCDF.py
+++ b/tests/ross/netCDF.py
@@ -20,9 +20,9 @@
import pycdf
netCDF_module = 'pycdf'
except ImportError:
- print 'Unable to import any of the following python modules:'
- print ' Scientific.IO.NetCDF \n netcdf4 \n pycdf'
- print 'One of them must be installed.'
+ print('Unable to import any of the following python modules:')
+ print(' Scientific.IO.NetCDF \n netcdf4 \n pycdf')
+ print('One of them must be installed.')
raise ImportError('No netCDF module found')
def NCtype(value):
diff --git a/tests/ross/plotRoss.py b/tests/ross/plotRoss.py
index 49274030..6a0de459 100755
--- a/tests/ross/plotRoss.py
+++ b/tests/ross/plotRoss.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
"""
This script plots the results of the Ross Ice Shelf Experiments.
@@ -170,23 +170,23 @@ def main():
riggs_velocity.append(tokens[10])
glimmer_velocity.append(v)
else:
- print 'Glimmer velocity is zero at (%g, %g); RIGGS velocity is %g' % (lon,lat,tokens[10])
+ print( 'Glimmer velocity is zero at (%g, %g); RIGGS velocity is %g' % (lon,lat,tokens[10]))
lat0.append(lat)
lon0.append(lon)
vel0.append(tokens[10])
else:
- print 'RIGGS data is off the grid at (%g, %g); RIGGS velocity is %g' % (lon,lat,tokens[10])
- print 'These points are not included in Chi-squared.'
+ print( 'RIGGS data is off the grid at (%g, %g); RIGGS velocity is %g' % (lon,lat,tokens[10]))
+ print( 'These points are not included in Chi-squared.')
riggs_file.close()
# Present the output
# ------------------
sigma = 30
X2 = sum([((v1-v2)/sigma)**2 for v1,v2 in zip(riggs_velocity,glimmer_velocity)])
- print
- print 'Chi-squared for',len(riggs_velocity),'points is', X2
- print 'The maximum velocity from Glimmer/CISM is', numpy.max(velnorm)
- print 'The maximum velocity from the RIGGS data is', max(riggs_velocity)
+ print('\n')
+ print( 'Chi-squared for',len(riggs_velocity),'points is', X2)
+ print( 'The maximum velocity from Glimmer/CISM is', numpy.max(velnorm))
+ print( 'The maximum velocity from the RIGGS data is', max(riggs_velocity))
# Create a scatter plot
pyplot.figure(1)
@@ -232,14 +232,14 @@ def main():
pyplot.axes().set_aspect('equal')
pyplot.colorbar(orientation='vertical',fraction=0.05,pad=0.01,shrink=0.93,ticks=ticks)
pyplot.title('Ross Ice Shelf Experiment - Velocity (meters/year)')
- print
- print 'FIGURE 2:'
- print 'If Glimmer/CISM perfectly predicted the velocities measured by the Ross'
- print 'Ice Shelf Geophysical and Glaciological Survey (RIGGS), the colors in'
- print 'the circles (which represent the RIGGS velocities) would be the same as'
- print 'the color of the background (which represents the velocities calculated'
- print 'by Glimmer/CISM).'
- print
+ print('\n')
+ print( 'FIGURE 2:')
+ print( 'If Glimmer/CISM perfectly predicted the velocities measured by the Ross')
+ print( 'Ice Shelf Geophysical and Glaciological Survey (RIGGS), the colors in')
+ print( 'the circles (which represent the RIGGS velocities) would be the same as')
+ print( 'the color of the background (which represents the velocities calculated')
+ print( 'by Glimmer/CISM).')
+ print('\n')
# Create a contour plot of Glimmer to compare to paper Figure 3.
@@ -255,12 +255,11 @@ def main():
pyplot.xlim((110,147))
pyplot.ylim((1,58))
- print
- print 'FIGURE 3:'
- print 'Compare this plot to Figure 3 in the EISMINT paper: '
- print 'MacAyeal, et al.: An ice-shelf model test based on the Ross Ice Shelf, Antarctica, Ann. Glaciol., 23, 46-51, 1996'
- print 'Try URL: http://www.igsoc.org/annals.old/23/igs_annals_vol23_year1996_pg46-51.pdf'
- print
+ print( 'FIGURE 3:')
+ print( 'Compare this plot to Figure 3 in the EISMINT paper: ')
+ print( 'MacAyeal, et al.: An ice-shelf model test based on the Ross Ice Shelf, Antarctica, Ann. Glaciol., 23, 46-51, 1996')
+ print( 'Try URL: http://www.igsoc.org/annals.old/23/igs_annals_vol23_year1996_pg46-51.pdf')
+ print('\n')
pyplot.show()
diff --git a/tests/ross/runRoss.py b/tests/ross/runRoss.py
index 61a95ffb..3911d172 100755
--- a/tests/ross/runRoss.py
+++ b/tests/ross/runRoss.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
#FIXME: More detailed description of this test case!!!
"""
@@ -14,7 +14,7 @@
import sys
import errno
import subprocess
-import ConfigParser
+import configparser
import numpy
import netCDF
@@ -52,10 +52,6 @@ def unsigned_int(x):
parser.add_argument('-s','--setup-only', action='store_true',
help="Set up the test, but don't actually run it.")
-# Additional test specific options:
-
-#optparser.add_option("-r", "--run", dest="doRun", default=False, action="store_true", help="Including this flag will run CISM. Excluding it will cause the script to only setup the initial condition file")
-
# Some useful functions
# ---------------------
@@ -87,6 +83,8 @@ def prep_commands(args, config_name):
# These calls to os.system will return the exit status: 0 for success (the command exists), some other integer for failure
if os.system('which openmpirun > /dev/null') == 0:
mpiexec = 'openmpirun -np ' + str(args.parallel)+" "
+ elif os.system('which mpiexec > /dev/null') == 0:
+ mpiexec = 'mpiexec -np ' + str(args.parallel)+" "
elif os.system('which mpirun > /dev/null') == 0:
mpiexec = 'mpirun -np ' + str(args.parallel)+" "
elif os.system('which aprun > /dev/null') == 0:
@@ -152,7 +150,10 @@ def main():
#scale_factor = 2 ** args.scale
try:
- config_parser = ConfigParser.SafeConfigParser()
+ config_parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';')
+ # interpolation=None)
config_parser.read( args.config )
nz = int(config_parser.get('grid','upn'))
@@ -166,18 +167,18 @@ def main():
# because we are choosing to use the raw data on the velocity grid.
if nx != 148:
print("WARNING: ewn should be set to 148 in ross.config")
- raise ConfigParser.Error
+ raise configparser.Error
if ny != 112:
print("WARNING: nsn should be set to 112 in ross.config")
- raise ConfigParser.Error
+ raise configparser.Error
if dx != 6822 or dy !=6822:
print("WARNING: dew and dns should be set to 6822 in ross.config")
- raise ConfigParser.Error
+ raise configparser.Error
file_name = config_parser.get('CF input', 'name')
root, ext = os.path.splitext(file_name)
- except ConfigParser.Error as error:
+ except configparser.Error as error:
print("Error parsing " + args.config )
print(" "),
print(error)
@@ -209,7 +210,7 @@ def main():
config_parser.set('CF output', 'name', out_name)
config_parser.set('CF output', 'xtype', 'double')
- with open(config_name, 'wb') as config_file:
+ with open(config_name, 'w') as config_file:
config_parser.write(config_file)
@@ -331,6 +332,7 @@ def main():
# Get the components of the velocity vector
#NOTE: velocity1 is vvel, velocity 2 is uvel
azimuth *= numpy.pi/180.0
+
velocity1 = velocity * numpy.cos(azimuth)
velocity2 = velocity * numpy.sin(azimuth)
@@ -414,7 +416,7 @@ def main():
beta = numpy.zeros((ny-1,nx-1),dtype='float32')
uvel = numpy.array(nz*[velocity2])
vvel = numpy.array(nz*[velocity1])
-
+
mask = numpy.logical_and(velocity==0,numpy.logical_or(mask1==1,mask3==1))
kinbcmask = numpy.int32(numpy.where(mask, 0, 1))
diff --git a/tests/shelf/README.md b/tests/shelf/README.md
index 8c929e29..f5594cd3 100644
--- a/tests/shelf/README.md
+++ b/tests/shelf/README.md
@@ -2,6 +2,8 @@
Shelf
=====
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
This directory contains Python scripts for running idealized ice shelf
experiments.
diff --git a/tests/shelf/netCDF.py b/tests/shelf/netCDF.py
index 2640e87b..18f05dfe 100644
--- a/tests/shelf/netCDF.py
+++ b/tests/shelf/netCDF.py
@@ -20,9 +20,9 @@
import pycdf
netCDF_module = 'pycdf'
except ImportError:
- print 'Unable to import any of the following python modules:'
- print ' Scientific.IO.NetCDF \n netcdf4 \n pycdf'
- print 'One of them must be installed.'
+ print( 'Unable to import any of the following python modules:')
+ print( ' Scientific.IO.NetCDF \n netcdf4 \n pycdf')
+ print( 'One of them must be installed.')
raise ImportError('No netCDF module found')
def NCtype(value):
diff --git a/tests/shelf/runShelfCircular.py b/tests/shelf/runShelfCircular.py
index 07303495..837c32ce 100755
--- a/tests/shelf/runShelfCircular.py
+++ b/tests/shelf/runShelfCircular.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
#FIXME: More detailed description of this test case!!!
"""
@@ -15,7 +15,7 @@
import sys
import errno
import subprocess
-import ConfigParser
+import configparser
import numpy
import netCDF
@@ -98,6 +98,8 @@ def prep_commands(args, config_name):
# These calls to os.system will return the exit status: 0 for success (the command exists), some other integer for failure
if os.system('which openmpirun > /dev/null') == 0:
mpiexec = 'openmpirun -np ' + str(args.parallel)+" "
+ elif os.system('which mpiexec > /dev/null') == 0:
+ mpiexec = 'mpiexec -np ' + str(args.parallel)+" "
elif os.system('which mpirun > /dev/null') == 0:
mpiexec = 'mpirun -np ' + str(args.parallel)+" "
elif os.system('which aprun > /dev/null') == 0:
@@ -134,7 +136,10 @@ def main():
#scale_factor = 2 ** args.scale
try:
- config_parser = ConfigParser.SafeConfigParser()
+ config_parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config_parser.read( args.config )
nz = int(config_parser.get('grid','upn'))
@@ -147,7 +152,7 @@ def main():
file_name = config_parser.get('CF input', 'name')
root, ext = os.path.splitext(file_name)
- except ConfigParser.Error as error:
+ except configparser.Error as error:
print("Error parsing " + args.config )
print(" "),
print(error)
@@ -177,7 +182,7 @@ def main():
config_parser.set('CF output', 'name', out_name)
config_parser.set('CF output', 'xtype', 'double')
- with open(config_name, 'wb') as config_file:
+ with open(config_name, 'w') as config_file:
config_parser.write(config_file)
@@ -243,11 +248,11 @@ def main():
if not args.beta: # Don't use a Gaussian
beta[0,:,:] = 0 # beta is 0 almost everywhere
- beta[0,ny/2-1:ny/2+1,nx/2-1:nx/2+1] = 1.0e8 # but large in the center
+ beta[0,ny//2-1:ny//2+1,nx//2-1:nx//2+1] = 1.0e8 # but large in the center
# Add a single bedrock spike in the domain center, to "ground" shelf for
# bisicles dycore
- topg[0,(ny-1)/2-1:(ny-1)/2+2,(nx-1)/2-1:(nx-1)/2+2] = -880.
+ topg[0,(ny-1)//2-1:(ny-1)//2+2,(nx-1)//2-1:(nx-1)//2+2] = -880.
# Create the required variables in the netCDF file.
nc_file.createVariable('thk', 'f',('time','y1','x1'))[:] = thk
diff --git a/tests/shelf/runShelfConfined.py b/tests/shelf/runShelfConfined.py
index b4280857..59e8dc05 100755
--- a/tests/shelf/runShelfConfined.py
+++ b/tests/shelf/runShelfConfined.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
#FIXME: More detailed description of this test case!!!
"""
@@ -16,7 +16,7 @@
import sys
import errno
import subprocess
-import ConfigParser
+import configparser
import numpy
import netCDF
@@ -91,6 +91,8 @@ def prep_commands(args, config_name):
# These calls to os.system will return the exit status: 0 for success (the command exists), some other integer for failure
if os.system('which openmpirun > /dev/null') == 0:
mpiexec = 'openmpirun -np ' + str(args.parallel)+" "
+ elif os.system('which mpiexec > /dev/null') == 0:
+ mpiexec = 'mpiexec -np ' + str(args.parallel)+" "
elif os.system('which mpirun > /dev/null') == 0:
mpiexec = 'mpirun -np ' + str(args.parallel)+" "
elif os.system('which aprun > /dev/null') == 0:
@@ -127,7 +129,10 @@ def main():
#scale_factor = 2 ** args.scale
try:
- config_parser = ConfigParser.SafeConfigParser()
+ config_parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config_parser.read( args.config )
nz = int(config_parser.get('grid','upn'))
@@ -140,7 +145,7 @@ def main():
file_name = config_parser.get('CF input', 'name')
root, ext = os.path.splitext(file_name)
- except ConfigParser.Error as error:
+ except configparser.Error as error:
print("Error parsing " + args.config )
print(" "),
print(error)
@@ -170,7 +175,7 @@ def main():
config_parser.set('CF output', 'name', out_name)
config_parser.set('CF output', 'xtype', 'double')
- with open(config_name, 'wb') as config_file:
+ with open(config_name, 'w') as config_file:
config_parser.write(config_file)
diff --git a/tests/slab/netCDF.py b/tests/slab/netCDF.py
index 2640e87b..09e31828 100644
--- a/tests/slab/netCDF.py
+++ b/tests/slab/netCDF.py
@@ -20,9 +20,9 @@
import pycdf
netCDF_module = 'pycdf'
except ImportError:
- print 'Unable to import any of the following python modules:'
- print ' Scientific.IO.NetCDF \n netcdf4 \n pycdf'
- print 'One of them must be installed.'
+ print('Unable to import any of the following python modules:')
+ print(' Scientific.IO.NetCDF \n netcdf4 \n pycdf')
+ print('One of them must be installed.')
raise ImportError('No netCDF module found')
def NCtype(value):
diff --git a/tests/slab/plotSlab.py b/tests/slab/plotSlab.py
index 214c6531..b00a8c29 100755
--- a/tests/slab/plotSlab.py
+++ b/tests/slab/plotSlab.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
"""
@@ -123,8 +123,8 @@ def main():
#yp = 15
#xp = 15
# =====================================================================
- print 'Using x index of '+str(xp)+'='+str(x0[xp])
- print 'Using y index of '+str(yp)+'='+str(y0[yp])
+ print('Using x index of '+str(xp)+'='+str(x0[xp]))
+ print('Using y index of '+str(yp)+'='+str(y0[yp]))
thk = filein.variables['thk'][:]
if netCDF_module == 'Scientific.IO.NetCDF':
diff --git a/tests/slab/runSlab.py b/tests/slab/runSlab.py
index 2fc0217a..2d81977d 100755
--- a/tests/slab/runSlab.py
+++ b/tests/slab/runSlab.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
#FIXME: More detailed description of this test case!!!
"""
@@ -17,7 +17,7 @@
import sys
import errno
import subprocess
-import ConfigParser
+import configparser
import numpy
import netCDF
@@ -151,7 +151,7 @@ def main():
# get the configuration
# ---------------------
try:
- config_parser = ConfigParser.SafeConfigParser()
+ config_parser = configparser.ConfigParser()
config_parser.read( args.config )
nz = int(config_parser.get('grid','upn'))
@@ -202,7 +202,7 @@ def main():
config_parser.set('CF output', 'name', out_name)
config_parser.set('CF output', 'xtype', 'double')
- with open(config_name, 'wb') as config_file:
+ with open(config_name, 'w') as config_file:
config_parser.write(config_file)
diff --git a/tests/stream/README.md b/tests/stream/README.md
index b48405ce..c876410d 100644
--- a/tests/stream/README.md
+++ b/tests/stream/README.md
@@ -1,6 +1,8 @@
======
stream
======
+Note: For setting up the experiments on an NCAR computing environment, follow the steps in the README.NCAR_HPC file in the tests directory.
+
This directory contains Python scripts for running idealized ice stream
experiments.
diff --git a/tests/stream/netCDF.py b/tests/stream/netCDF.py
index 2640e87b..18f05dfe 100644
--- a/tests/stream/netCDF.py
+++ b/tests/stream/netCDF.py
@@ -20,9 +20,9 @@
import pycdf
netCDF_module = 'pycdf'
except ImportError:
- print 'Unable to import any of the following python modules:'
- print ' Scientific.IO.NetCDF \n netcdf4 \n pycdf'
- print 'One of them must be installed.'
+ print( 'Unable to import any of the following python modules:')
+ print( ' Scientific.IO.NetCDF \n netcdf4 \n pycdf')
+ print( 'One of them must be installed.')
raise ImportError('No netCDF module found')
def NCtype(value):
diff --git a/tests/stream/plotStream.py b/tests/stream/plotStream.py
index 1e6c5a86..e976cc8d 100755
--- a/tests/stream/plotStream.py
+++ b/tests/stream/plotStream.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
"""
This script plots the results of an experiment with an ice stream.
@@ -109,9 +109,9 @@ def main():
#btract = (btractx**2 + btracty**2)**0.5
x0 = filein.variables['x0'][:]
- xpos = x0.shape[0]/2 # integer division on x-length to get the middle column of the domain
+ xpos = x0.shape[0]//2 # integer division on x-length to get the middle column of the domain
- ypos = y0.shape[0]/2 # integer division on y-length to get the middle row of the domain
+ ypos = y0.shape[0]//2 # integer division on y-length to get the middle row of the domain
# Calculate analytic velocity profile - the analytic functions are in runStream.py
if analytic_solution == 'raymond':
diff --git a/tests/stream/runStream.py b/tests/stream/runStream.py
index 86d4dc8c..469aa6b4 100755
--- a/tests/stream/runStream.py
+++ b/tests/stream/runStream.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
#FIXME: More detailed description of this test case!!!
"""
@@ -14,7 +14,7 @@
import sys
import errno
import subprocess
-import ConfigParser
+import configparser
import numpy
import netCDF
@@ -61,11 +61,9 @@ def unsigned_int(x):
parser.add_argument('-z','--stream-size', type=unsigned_int, default=25,
help=") The number of grid cells used to model the ice stream portion of the domain."
+"Note: values <19 may not work properly for all problems.")
-#optparser.add_option('-s','--stream-size',dest='stream_grid_size',default=25,type='int',help='Number of cells to use to model the ice stream portion of the domain (values <19 may not work properly for all problems).')
parser.add_argument('--vertical', type=unsigned_int,
help="Override the vertical grid size (upn) in the config file.")
-#optparser.add_option('-v','--vert-grid-size',dest='vertical_grid_size',default=2,type='int',help='Number of vertical layers to use (upn); minimum value = 2')
# Some useful functions
# ---------------------
@@ -97,6 +95,8 @@ def prep_commands(args, config_name):
# These calls to os.system will return the exit status: 0 for success (the command exists), some other integer for failure
if os.system('which openmpirun > /dev/null') == 0:
mpiexec = 'openmpirun -np ' + str(args.parallel)+" "
+ elif os.system('which mpiexec > /dev/null') == 0:
+ mpiexec = 'mpiexec -np ' + str(args.parallel)+" "
elif os.system('which mpirun > /dev/null') == 0:
mpiexec = 'mpirun -np ' + str(args.parallel)+" "
elif os.system('which aprun > /dev/null') == 0:
@@ -125,6 +125,8 @@ def prep_commands(args, config_name):
kinflag = 1 # 1=apply kinematic bc (analytic soln) at points in the domain (discussed further below); 0=the run will be doubly periodic (preferred)
fillInitialGuess = 0 # 1=use the analytic solution as the initial guess for the velocity solver to speed convergence; 0=use the default 0-velocity initial guess
+eps = 1.e-10 # a small number
+
# Domain parameters
streamHalfWidth = 25000.0 # ice stream half-width, in m - used for both raymond & schoof formulations
alongFlowLength = 30000.0 # the desired along-flow length of the domain, in m; set to -1 to get a square domain
@@ -199,7 +201,10 @@ def main():
# get the configuration
# ---------------------
try:
- config_parser = ConfigParser.SafeConfigParser()
+ config_parser = configparser.ConfigParser(delimiters=('=', ':'),
+ comment_prefixes=('#', ';'),
+ inline_comment_prefixes=';',
+ interpolation=None)
config_parser.read( args.config )
if args.vertical:
@@ -210,7 +215,7 @@ def main():
file_name = config_parser.get('CF input', 'name')
root, ext = os.path.splitext(file_name)
- except ConfigParser.Error as error:
+ except configparser.Error as error:
print("Error parsing " + args.config )
print(" "),
print(error)
@@ -229,7 +234,7 @@ def main():
# Figure out the number of cells we need to add to get as close t0 the
# desired width of the strong region as possible (note: may want to use
# ceil() instead of round() here)
- nStrongStrip = int(round(strongWidth / dy))
+ nStrongStrip = int(round(strongWidth / dy + eps))
# a +1 is needed to convert from y0 to y1 but we leaving it off lets the
#stream boundaries fall on the y0 grid, which is needed to best match the
@@ -279,7 +284,7 @@ def main():
config_parser.set('CF output', 'name', out_name)
config_parser.set('CF output', 'xtype', 'double')
- with open(config_name, 'wb') as config_file:
+ with open(config_name, 'w') as config_file:
config_parser.write(config_file)
@@ -306,6 +311,7 @@ def main():
x0 = dx/2.0 + x1[:-1] # staggered grid
y0 = dy/2.0 + y1[:-1]
+
# Make sure the edge of the stream lands on the grid cells on the y0 grid.
# This should always happen with the logic above, so this check should never be activated.
if (analytic_solution == 'raymond') and (not True in (numpy.absolute(streamHalfWidth-y0) < 0.0001)):
diff --git a/tests/unsupported/exact-isothermal/scripts/create_test.py b/tests/unsupported/exact-isothermal/scripts/create_test.py
index 376831f5..a9806a8f 100755
--- a/tests/unsupported/exact-isothermal/scripts/create_test.py
+++ b/tests/unsupported/exact-isothermal/scripts/create_test.py
@@ -5,25 +5,25 @@
# Create test configuration based on Ed Bueler's exact solutions
import sys,string, Numeric, PyCF, datetime
-from optparse import OptionParser
+from argparse import ArgumentParser
import exact_is
if __name__ == '__main__':
# setup options
- parser = OptionParser(usage = "usage: %prog [options] name")
- parser.add_option("-m","--massbalance",metavar="MB",default=0.3,type="float",help="set accumulation [m/a] (default = 0.3)")
- parser.add_option("-n","--flow-law-exponent",metavar="N",default=3.,type="float",help="set Glen's flow law exponent (default = 3)")
- parser.add_option("-l","--margin-radius",metavar="L",default=750.,type="float",help="set radius of margin [km] (default = 750)")
- parser.add_option("-d","--delta",metavar="D",default=25.,type="float",help="set grid spacing [km] (default = 25)")
+ parser = ArgumentParser(usage = "usage: %prog [options] name")
+ parser.add_argument("-m","--massbalance", metavar="MB",default=0.3, type=float,help="set accumulation [m/a] (default = 0.3)")
+ parser.add_argument("-n","--flow-law-exponent",metavar="N", default=3., type=float,help="set Glen's flow law exponent (default = 3)")
+ parser.add_argument("-l","--margin-radius", metavar="L", default=750.,type=float,help="set radius of margin [km] (default = 750)")
+ parser.add_argument("-d","--delta", metavar="D", default=25., type=float,help="set grid spacing [km] (default = 25)")
- (options, args) = parser.parse_args()
+ options = parser.parse_args()
if len(args)!=1:
parser.error("no output file name given")
# ice sheet
- print options.massbalance,options.flow_law_exponent,options.margin_radius
+ print( options.massbalance,options.flow_law_exponent,options.margin_radius)
ism = exact_is.ModelAE(options.massbalance,options.flow_law_exponent,options.margin_radius)
# creating output netCDF file
diff --git a/tests/unsupported/exact-isothermal/scripts/plot_diff.py b/tests/unsupported/exact-isothermal/scripts/plot_diff.py
index 909d2448..ecedae45 100755
--- a/tests/unsupported/exact-isothermal/scripts/plot_diff.py
+++ b/tests/unsupported/exact-isothermal/scripts/plot_diff.py
@@ -8,7 +8,7 @@
import pylab, matplotlib
import Scientific.IO.NetCDF
import numpy.ma
-from optparse import OptionParser
+from argparse import ArgumentParser
if __name__ == '__main__':
@@ -17,10 +17,10 @@
plot difference between exact and simulated solution at specified time"""
- parser = OptionParser(usage=usage)
- parser.add_option("-o","--output",metavar="FILE",help="write image to file. image type is determined by file suffix")
- parser.add_option("-T","--time-slice",metavar="T",default=-1,type='int',help="extract data for time slice T")
- (options, args) = parser.parse_args()
+ parser = ArgumentParser(usage=usage)
+ parser.add_argument("-o","--output",metavar="FILE",help="write image to file. image type is determined by file suffix")
+ parser.add_argument("-T","--time-slice",metavar="T",default=-1,type=int,help="extract data for time slice T")
+ options = parser.parse_args()
if len(args)!=1:
parser.error('Expecting one input file')
diff --git a/tests/unsupported/exact-isothermal/scripts/plot_errors.py b/tests/unsupported/exact-isothermal/scripts/plot_errors.py
index b7755ddf..408d2674 100755
--- a/tests/unsupported/exact-isothermal/scripts/plot_errors.py
+++ b/tests/unsupported/exact-isothermal/scripts/plot_errors.py
@@ -7,7 +7,8 @@
import numpy, Scientific.IO.NetCDF
import pylab
-from optparse import OptionParser
+from argparse import ArgumentParser
+
def parse_title(title):
"""Parse title string."""
@@ -27,9 +28,9 @@ def parse_title(title):
plot model errors as function of grid spacing"""
- parser = OptionParser(usage=usage)
- parser.add_option("-o","--output",metavar="FILE",help="write image to file. image type is determined by file suffix")
- (options, args) = parser.parse_args()
+ parser = ArgumentParser(usage=usage)
+ parser.add_argument("-o","--output",metavar="FILE",help="write image to file. image type is determined by file suffix")
+ options = parser.parse_args()
if len(args)<1:
parser.error('Expecting at least one file')
diff --git a/tests/unsupported/exact-isothermal/scripts/plot_time.py b/tests/unsupported/exact-isothermal/scripts/plot_time.py
index 03661733..b5dc2da0 100755
--- a/tests/unsupported/exact-isothermal/scripts/plot_time.py
+++ b/tests/unsupported/exact-isothermal/scripts/plot_time.py
@@ -7,7 +7,7 @@
import os.path
import pylab
-from optparse import OptionParser
+from argparse import ArgumentParser
def parse_title(title):
"""Parse title string."""
@@ -26,9 +26,9 @@ def parse_title(title):
parse RESULTS file and plot model runtimes"""
- parser = OptionParser(usage=usage)
- parser.add_option("-o","--output",metavar="FILE",help="write image to file. image type is determined by file suffix")
- (options, args) = parser.parse_args()
+ parser = ArgumentParser(usage=usage)
+ parser.add_argument("-o","--output",metavar="FILE",help="write image to file. image type is determined by file suffix")
+ options = parser.parse_args()
if len(args)>1:
parser.error('Expecting at most one results file')
diff --git a/tests/unsupported/exact-isothermal/scripts/plot_verif.py b/tests/unsupported/exact-isothermal/scripts/plot_verif.py
index 74037271..0db83f8e 100755
--- a/tests/unsupported/exact-isothermal/scripts/plot_verif.py
+++ b/tests/unsupported/exact-isothermal/scripts/plot_verif.py
@@ -85,7 +85,7 @@ def munch_verif(fname, verif):
if g not in grids:
grids[g] = gn
gn = gn+1
- print grids
+ print( grids)
key_y=2.5
ysize = 7.
dy = 1.
diff --git a/tests/unsupported/exact-isothermal/scripts/plot_vol.py b/tests/unsupported/exact-isothermal/scripts/plot_vol.py
index 7d1ac9ab..337ea881 100755
--- a/tests/unsupported/exact-isothermal/scripts/plot_vol.py
+++ b/tests/unsupported/exact-isothermal/scripts/plot_vol.py
@@ -7,7 +7,7 @@
import Scientific.IO.NetCDF
import pylab
-from optparse import OptionParser
+from argparse import ArgumentParser
def parse_title(title):
"""Parse title string."""
diff --git a/tests/unsupported/exact-isothermal/scripts/run_verif.py b/tests/unsupported/exact-isothermal/scripts/run_verif.py
index 3406cd14..57ea7e0f 100755
--- a/tests/unsupported/exact-isothermal/scripts/run_verif.py
+++ b/tests/unsupported/exact-isothermal/scripts/run_verif.py
@@ -4,7 +4,8 @@
#
# Create test configuration and run test
-import time, sys, optparse, os.path, os,fcntl
+import time, sys, os.path, os,fcntl
+from argparse import ArgumentParser
# test setups
EXCLUDE = ['name']
@@ -113,24 +114,24 @@ def create_config(experiment, solver, gridsize, timestep, tname):
if __name__ == '__main__':
# setup options
- parser = optparse.OptionParser(usage = "usage: %prog [options] template_file")
- parser.add_option('--experiment',default='B',metavar='TEST',type='choice',choices=TEST_CONFIGURATION.keys(),help='select test scenario (default: B)')
- parser.add_option('--solver',default='lin',metavar='SOLVER',type='choice',choices=SOLVERS.keys(),help='select solver (default: lin)')
- parser.add_option('--gridsize',default=20,metavar='DELTAX',type='int',help='grid spacing in km (default: 20)')
- parser.add_option('--timestep',default=10.,metavar='DELTAT',type='float',help='time step in a (default: 10)')
- parser.add_option('-f','--file',metavar='SPEC',help='an alternative way of setting up the model. The SPEC string takes the following format: test_EXP_SOLVER_Xkm_Ta where EXP is the experiment (see -e), SOLVER the solver (see -s), X the gridspacing in km (see -g) and T the time step in years (see -t)')
- group = optparse.OptionGroup(parser,"Options used for running the model.")
- group.add_option('--only-configure',action="store_true",default=False,help="only produce model configuration file.")
- group.add_option("-m", "--model", help="name of model binary to be launched", metavar="BINARY")
- group.add_option("-r", "--results", help="name of file where timing info is stored (default: results)", metavar="RESULTS", default="results")
- group.add_option("-s", "--submit-sge",action="store_true",default=False,help="submit job to Sun Grid Engine")
- group.add_option("-o", "--submit-options",default="",help="set additional options for cluster submission")
+ parser = ArgumentParser(usage = "usage: %prog [options] template_file")
+ parser.add_argument('--experiment',default='B',metavar='TEST',type='choice',choices=TEST_CONFIGURATION.keys(),help='select test scenario (default: B)')
+ parser.add_argument('--solver',default='lin',metavar='SOLVER',type='choice',choices=SOLVERS.keys(),help='select solver (default: lin)')
+ parser.add_argument('--gridsize',default=20,metavar='DELTAX',type='int',help='grid spacing in km (default: 20)')
+ parser.add_argument('--timestep',default=10.,metavar='DELTAT',type='float',help='time step in a (default: 10)')
+ parser.add_argument('-f','--file',metavar='SPEC',help='an alternative way of setting up the model. The SPEC string takes the following format: test_EXP_SOLVER_Xkm_Ta where EXP is the experiment (see -e), SOLVER the solver (see -s), X the gridspacing in km (see -g) and T the time step in years (see -t)')
+ group = parser.add_argument_group(parser,"Options used for running the model.")
+ group.add_argument('--only-configure',action="store_true",default=False,help="only produce model configuration file.")
+ group.add_argument("-m", "--model", help="name of model binary to be launched", metavar="BINARY")
+ group.add_argument("-r", "--results", help="name of file where timing info is stored (default: results)", metavar="RESULTS", default="results")
+ group.add_argument("-s", "--submit-sge",action="store_true",default=False,help="submit job to Sun Grid Engine")
+ group.add_argument("-o", "--submit-options",default="",help="set additional options for cluster submission")
parser.add_option_group(group)
- (options, args) = parser.parse_args()
+ options = parser.parse_args()
- if len(args)!=1:
- parser.error("no template file name given")
+# if len(args)!=1:
+# parser.error("no template file name given")
# create configuration file
if options.file == None:
@@ -151,7 +152,7 @@ def create_config(experiment, solver, gridsize, timestep, tname):
configname = create_config(exp,solver,dx,dt,args[0])
if options.only_configure:
- print 'Create configuration file %s.config'%base_name
+ print( 'Create configuration file %s.config'%base_name)
sys.exit(0)
prefix = os.path.abspath(os.path.dirname(sys.argv[0]))
@@ -182,6 +183,6 @@ def create_config(experiment, solver, gridsize, timestep, tname):
# sys.stderr.write("glide model %s was terminated by signal %d\n"%(model,-retcode))
# except OSError, e:
# sys.stderr.write("Execution failed: %s\n"%e)
- print os.popen(prog,'r').read()
+ print( os.popen(prog,'r').read())
diff --git a/utils/build/autogen-for-glint-and-glad-in-build-dir b/utils/build/autogen-for-glint-and-glad-in-build-dir
index f46d51cb..2b57f17e 100755
--- a/utils/build/autogen-for-glint-and-glad-in-build-dir
+++ b/utils/build/autogen-for-glint-and-glad-in-build-dir
@@ -36,11 +36,11 @@ export GLAD_VARS_PATH=$CISM_SOURCE_DIR/libglad/glad_vars.def
export GLAD_MBAL_PATH=$CISM_SOURCE_DIR/libglad/glad_mbal_vars.def
# Call python script with source file arguments
-python -V
-python $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLINT_VARS_PATH $NCDF_TEMPL_PATH
-python $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLINT_MBAL_PATH $NCDF_TEMPL_PATH
-python $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLAD_VARS_PATH $NCDF_TEMPL_PATH
-python $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLAD_MBAL_PATH $NCDF_TEMPL_PATH
+python3 -V
+python3 $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLINT_VARS_PATH $NCDF_TEMPL_PATH
+python3 $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLINT_MBAL_PATH $NCDF_TEMPL_PATH
+python3 $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLAD_VARS_PATH $NCDF_TEMPL_PATH
+python3 $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLAD_MBAL_PATH $NCDF_TEMPL_PATH
popd
diff --git a/utils/build/autogenerate-in-build-dir b/utils/build/autogenerate-in-build-dir
index 64f2f570..8af2a531 100755
--- a/utils/build/autogenerate-in-build-dir
+++ b/utils/build/autogenerate-in-build-dir
@@ -32,8 +32,8 @@ export GLIDE_VARS_PATH=$CISM_SOURCE_DIR/libglide/glide_vars.def
export NCDF_TEMPL_PATH=$CISM_SOURCE_DIR/libglimmer/ncdf_template.F90.in
# Call python script with source file arguments
-python -V
-python $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLIDE_VARS_PATH $NCDF_TEMPL_PATH
+python3 -V
+python3 $CISM_SOURCE_DIR/utils/build/generate_ncvars.py $GLIDE_VARS_PATH $NCDF_TEMPL_PATH
popd
diff --git a/utils/build/generate_ncvars.py b/utils/build/generate_ncvars.py
index 4a3bd42e..f50a702c 100755
--- a/utils/build/generate_ncvars.py
+++ b/utils/build/generate_ncvars.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
# Copyright (C) 2005-2018
# Glimmer-CISM contributors - see AUTHORS file for list of contributors
@@ -614,10 +614,6 @@ def print_var_accessor(self,var):
if not is_dimvar(var) and dimlen<3 and AVERAGE_SUFFIX not in var['name']:
# get
self.stream.write(" subroutine %s_get_%s(data,outarray)\n"%(module['name'],var['name']))
- self.stream.write(" use glimmer_scales\n")
- self.stream.write(" use glimmer_paramets\n")
- self.stream.write(" use glimmer_physcon\n")
- self.stream.write(" use %s\n"%module['datamod'])
self.stream.write(" implicit none\n")
self.stream.write(" type(%s) :: data\n"%module['datatype'])
if var['type'] == 'int':
@@ -639,10 +635,6 @@ def print_var_accessor(self,var):
# only creating set routine if the variable is not derived
if len(var['data'].split('data'))<3:
self.stream.write(" subroutine %s_set_%s(data,inarray)\n"%(module['name'],var['name']))
- self.stream.write(" use glimmer_scales\n")
- self.stream.write(" use glimmer_paramets\n")
- self.stream.write(" use glimmer_physcon\n")
- self.stream.write(" use %s\n"%module['datamod'])
self.stream.write(" implicit none\n")
self.stream.write(" type(%s) :: data\n"%module['datatype'])
if var['type'] == 'int':