Actual source code: ex14.c

petsc-3.8.4 2018-03-24
Report Typos and Errors
  1: static const char help[] = "Toy hydrostatic ice flow with multigrid in 3D.\n\
  2: \n\
  3: Solves the hydrostatic (aka Blatter/Pattyn/First Order) equations for ice sheet flow\n\
  4: using multigrid.  The ice uses a power-law rheology with \"Glen\" exponent 3 (corresponds\n\
  5: to p=4/3 in a p-Laplacian).  The focus is on ISMIP-HOM experiments which assume periodic\n\
  6: boundary conditions in the x- and y-directions.\n\
  7: \n\
  8: Equations are rescaled so that the domain size and solution are O(1), details of this scaling\n\
  9: can be controlled by the options -units_meter, -units_second, and -units_kilogram.\n\
 10: \n\
 11: A VTK StructuredGrid output file can be written using the option -o filename.vts\n\
 12: \n\n";

 14: /*
 15: The equations for horizontal velocity (u,v) are

 17:   - [eta (4 u_x + 2 v_y)]_x - [eta (u_y + v_x)]_y - [eta u_z]_z + rho g s_x = 0
 18:   - [eta (4 v_y + 2 u_x)]_y - [eta (u_y + v_x)]_x - [eta v_z]_z + rho g s_y = 0

 20: where

 22:   eta = B/2 (epsilon + gamma)^((p-2)/2)

 24: is the nonlinear effective viscosity with regularization epsilon and hardness parameter B,
 25: written in terms of the second invariant

 27:   gamma = u_x^2 + v_y^2 + u_x v_y + (1/4) (u_y + v_x)^2 + (1/4) u_z^2 + (1/4) v_z^2

 29: The surface boundary conditions are the natural conditions.  The basal boundary conditions
 30: are either no-slip, or Navier (linear) slip with spatially variant friction coefficient beta^2.

 32: In the code, the equations for (u,v) are multiplied through by 1/(rho g) so that residuals are O(1).

 34: The discretization is Q1 finite elements, managed by a DMDA.  The grid is never distorted in the
 35: map (x,y) plane, but the bed and surface may be bumpy.  This is handled as usual in FEM, through
 36: the Jacobian of the coordinate transformation from a reference element to the physical element.

 38: Since ice-flow is tightly coupled in the z-direction (within columns), the DMDA is managed
 39: specially so that columns are never distributed, and are always contiguous in memory.
 40: This amounts to reversing the meaning of X,Y,Z compared to the DMDA's internal interpretation,
 41: and then indexing as vec[i][j][k].  The exotic coarse spaces require 2D DMDAs which are made to
 42: use compatible domain decomposition relative to the 3D DMDAs.

 44: */

 46:  #include <petscts.h>
 47:  #include <petscdm.h>
 48:  #include <petscdmda.h>
 49:  #include <petscdmcomposite.h>
 50: #include <ctype.h>              /* toupper() */

 52: #if defined __SSE2__
 53: #  include <emmintrin.h>
 54: #endif

 56: /* The SSE2 kernels are only for PetscScalar=double on architectures that support it */
 57: #define USE_SSE2_KERNELS (!defined NO_SSE2                              \
 58:                           && !defined PETSC_USE_COMPLEX                 \
 59:                           && !defined PETSC_USE_REAL_SINGLE           \
 60:                           && defined __SSE2__)

 62: #if !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L
 63: #  if defined __cplusplus       /* C++ restrict is nonstandard and compilers have inconsistent rules about where it can be used */
 64: #    define restrict
 65: #  else
 66: #    define restrict PETSC_RESTRICT
 67: #  endif
 68: #endif

 70: static PetscClassId THI_CLASSID;

 72: typedef enum {QUAD_GAUSS,QUAD_LOBATTO} QuadratureType;
 73: static const char *QuadratureTypes[] = {"gauss","lobatto","QuadratureType","QUAD_",0};
 74: static const PetscReal HexQWeights[8] = {1,1,1,1,1,1,1,1};
 75: static const PetscReal HexQNodes[]    = {-0.57735026918962573, 0.57735026918962573};
 76: #define G 0.57735026918962573
 77: #define H (0.5*(1.+G))
 78: #define L (0.5*(1.-G))
 79: #define M (-0.5)
 80: #define P (0.5)
 81: /* Special quadrature: Lobatto in horizontal, Gauss in vertical */
 82: static const PetscReal HexQInterp_Lobatto[8][8] = {{H,0,0,0,L,0,0,0},
 83:                                                    {0,H,0,0,0,L,0,0},
 84:                                                    {0,0,H,0,0,0,L,0},
 85:                                                    {0,0,0,H,0,0,0,L},
 86:                                                    {L,0,0,0,H,0,0,0},
 87:                                                    {0,L,0,0,0,H,0,0},
 88:                                                    {0,0,L,0,0,0,H,0},
 89:                                                    {0,0,0,L,0,0,0,H}};
 90: static const PetscReal HexQDeriv_Lobatto[8][8][3] = {
 91:   {{M*H,M*H,M},{P*H,0,0}  ,{0,0,0}    ,{0,P*H,0}  ,{M*L,M*L,P},{P*L,0,0}  ,{0,0,0}    ,{0,P*L,0}  },
 92:   {{M*H,0,0}  ,{P*H,M*H,M},{0,P*H,0}  ,{0,0,0}    ,{M*L,0,0}  ,{P*L,M*L,P},{0,P*L,0}  ,{0,0,0}    },
 93:   {{0,0,0}    ,{0,M*H,0}  ,{P*H,P*H,M},{M*H,0,0}  ,{0,0,0}    ,{0,M*L,0}  ,{P*L,P*L,P},{M*L,0,0}  },
 94:   {{0,M*H,0}  ,{0,0,0}    ,{P*H,0,0}  ,{M*H,P*H,M},{0,M*L,0}  ,{0,0,0}    ,{P*L,0,0}  ,{M*L,P*L,P}},
 95:   {{M*L,M*L,M},{P*L,0,0}  ,{0,0,0}    ,{0,P*L,0}  ,{M*H,M*H,P},{P*H,0,0}  ,{0,0,0}    ,{0,P*H,0}  },
 96:   {{M*L,0,0}  ,{P*L,M*L,M},{0,P*L,0}  ,{0,0,0}    ,{M*H,0,0}  ,{P*H,M*H,P},{0,P*H,0}  ,{0,0,0}    },
 97:   {{0,0,0}    ,{0,M*L,0}  ,{P*L,P*L,M},{M*L,0,0}  ,{0,0,0}    ,{0,M*H,0}  ,{P*H,P*H,P},{M*H,0,0}  },
 98:   {{0,M*L,0}  ,{0,0,0}    ,{P*L,0,0}  ,{M*L,P*L,M},{0,M*H,0}  ,{0,0,0}    ,{P*H,0,0}  ,{M*H,P*H,P}}};
 99: /* Stanndard Gauss */
100: static const PetscReal HexQInterp_Gauss[8][8] = {{H*H*H,L*H*H,L*L*H,H*L*H, H*H*L,L*H*L,L*L*L,H*L*L},
101:                                                  {L*H*H,H*H*H,H*L*H,L*L*H, L*H*L,H*H*L,H*L*L,L*L*L},
102:                                                  {L*L*H,H*L*H,H*H*H,L*H*H, L*L*L,H*L*L,H*H*L,L*H*L},
103:                                                  {H*L*H,L*L*H,L*H*H,H*H*H, H*L*L,L*L*L,L*H*L,H*H*L},
104:                                                  {H*H*L,L*H*L,L*L*L,H*L*L, H*H*H,L*H*H,L*L*H,H*L*H},
105:                                                  {L*H*L,H*H*L,H*L*L,L*L*L, L*H*H,H*H*H,H*L*H,L*L*H},
106:                                                  {L*L*L,H*L*L,H*H*L,L*H*L, L*L*H,H*L*H,H*H*H,L*H*H},
107:                                                  {H*L*L,L*L*L,L*H*L,H*H*L, H*L*H,L*L*H,L*H*H,H*H*H}};
108: static const PetscReal HexQDeriv_Gauss[8][8][3] = {
109:   {{M*H*H,H*M*H,H*H*M},{P*H*H,L*M*H,L*H*M},{P*L*H,L*P*H,L*L*M},{M*L*H,H*P*H,H*L*M}, {M*H*L,H*M*L,H*H*P},{P*H*L,L*M*L,L*H*P},{P*L*L,L*P*L,L*L*P},{M*L*L,H*P*L,H*L*P}},
110:   {{M*H*H,L*M*H,L*H*M},{P*H*H,H*M*H,H*H*M},{P*L*H,H*P*H,H*L*M},{M*L*H,L*P*H,L*L*M}, {M*H*L,L*M*L,L*H*P},{P*H*L,H*M*L,H*H*P},{P*L*L,H*P*L,H*L*P},{M*L*L,L*P*L,L*L*P}},
111:   {{M*L*H,L*M*H,L*L*M},{P*L*H,H*M*H,H*L*M},{P*H*H,H*P*H,H*H*M},{M*H*H,L*P*H,L*H*M}, {M*L*L,L*M*L,L*L*P},{P*L*L,H*M*L,H*L*P},{P*H*L,H*P*L,H*H*P},{M*H*L,L*P*L,L*H*P}},
112:   {{M*L*H,H*M*H,H*L*M},{P*L*H,L*M*H,L*L*M},{P*H*H,L*P*H,L*H*M},{M*H*H,H*P*H,H*H*M}, {M*L*L,H*M*L,H*L*P},{P*L*L,L*M*L,L*L*P},{P*H*L,L*P*L,L*H*P},{M*H*L,H*P*L,H*H*P}},
113:   {{M*H*L,H*M*L,H*H*M},{P*H*L,L*M*L,L*H*M},{P*L*L,L*P*L,L*L*M},{M*L*L,H*P*L,H*L*M}, {M*H*H,H*M*H,H*H*P},{P*H*H,L*M*H,L*H*P},{P*L*H,L*P*H,L*L*P},{M*L*H,H*P*H,H*L*P}},
114:   {{M*H*L,L*M*L,L*H*M},{P*H*L,H*M*L,H*H*M},{P*L*L,H*P*L,H*L*M},{M*L*L,L*P*L,L*L*M}, {M*H*H,L*M*H,L*H*P},{P*H*H,H*M*H,H*H*P},{P*L*H,H*P*H,H*L*P},{M*L*H,L*P*H,L*L*P}},
115:   {{M*L*L,L*M*L,L*L*M},{P*L*L,H*M*L,H*L*M},{P*H*L,H*P*L,H*H*M},{M*H*L,L*P*L,L*H*M}, {M*L*H,L*M*H,L*L*P},{P*L*H,H*M*H,H*L*P},{P*H*H,H*P*H,H*H*P},{M*H*H,L*P*H,L*H*P}},
116:   {{M*L*L,H*M*L,H*L*M},{P*L*L,L*M*L,L*L*M},{P*H*L,L*P*L,L*H*M},{M*H*L,H*P*L,H*H*M}, {M*L*H,H*M*H,H*L*P},{P*L*H,L*M*H,L*L*P},{P*H*H,L*P*H,L*H*P},{M*H*H,H*P*H,H*H*P}}};
117: static const PetscReal (*HexQInterp)[8],(*HexQDeriv)[8][3];
118: /* Standard 2x2 Gauss quadrature for the bottom layer. */
119: static const PetscReal QuadQInterp[4][4] = {{H*H,L*H,L*L,H*L},
120:                                             {L*H,H*H,H*L,L*L},
121:                                             {L*L,H*L,H*H,L*H},
122:                                             {H*L,L*L,L*H,H*H}};
123: static const PetscReal QuadQDeriv[4][4][2] = {
124:   {{M*H,M*H},{P*H,M*L},{P*L,P*L},{M*L,P*H}},
125:   {{M*H,M*L},{P*H,M*H},{P*L,P*H},{M*L,P*L}},
126:   {{M*L,M*L},{P*L,M*H},{P*H,P*H},{M*H,P*L}},
127:   {{M*L,M*H},{P*L,M*L},{P*H,P*L},{M*H,P*H}}};
128: #undef G
129: #undef H
130: #undef L
131: #undef M
132: #undef P

134: #define HexExtract(x,i,j,k,n) do {              \
135:     (n)[0] = (x)[i][j][k];                      \
136:     (n)[1] = (x)[i+1][j][k];                    \
137:     (n)[2] = (x)[i+1][j+1][k];                  \
138:     (n)[3] = (x)[i][j+1][k];                    \
139:     (n)[4] = (x)[i][j][k+1];                    \
140:     (n)[5] = (x)[i+1][j][k+1];                  \
141:     (n)[6] = (x)[i+1][j+1][k+1];                \
142:     (n)[7] = (x)[i][j+1][k+1];                  \
143:   } while (0)

145: #define HexExtractRef(x,i,j,k,n) do {           \
146:     (n)[0] = &(x)[i][j][k];                     \
147:     (n)[1] = &(x)[i+1][j][k];                   \
148:     (n)[2] = &(x)[i+1][j+1][k];                 \
149:     (n)[3] = &(x)[i][j+1][k];                   \
150:     (n)[4] = &(x)[i][j][k+1];                   \
151:     (n)[5] = &(x)[i+1][j][k+1];                 \
152:     (n)[6] = &(x)[i+1][j+1][k+1];               \
153:     (n)[7] = &(x)[i][j+1][k+1];                 \
154:   } while (0)

156: #define QuadExtract(x,i,j,n) do {               \
157:     (n)[0] = (x)[i][j];                         \
158:     (n)[1] = (x)[i+1][j];                       \
159:     (n)[2] = (x)[i+1][j+1];                     \
160:     (n)[3] = (x)[i][j+1];                       \
161:   } while (0)

163: static PetscScalar Sqr(PetscScalar a) {return a*a;}

165: static void HexGrad(const PetscReal dphi[][3],const PetscReal zn[],PetscReal dz[])
166: {
167:   PetscInt i;
168:   dz[0] = dz[1] = dz[2] = 0;
169:   for (i=0; i<8; i++) {
170:     dz[0] += dphi[i][0] * zn[i];
171:     dz[1] += dphi[i][1] * zn[i];
172:     dz[2] += dphi[i][2] * zn[i];
173:   }
174: }

176: static void HexComputeGeometry(PetscInt q,PetscReal hx,PetscReal hy,const PetscReal dz[restrict],PetscReal phi[restrict],PetscReal dphi[restrict][3],PetscReal *restrict jw)
177: {
178:   const PetscReal
179:     jac[3][3] = {{hx/2,0,0}, {0,hy/2,0}, {dz[0],dz[1],dz[2]}}
180:   ,ijac[3][3] = {{1/jac[0][0],0,0}, {0,1/jac[1][1],0}, {-jac[2][0]/(jac[0][0]*jac[2][2]),-jac[2][1]/(jac[1][1]*jac[2][2]),1/jac[2][2]}}
181:   ,jdet = jac[0][0]*jac[1][1]*jac[2][2];
182:   PetscInt i;

184:   for (i=0; i<8; i++) {
185:     const PetscReal *dphir = HexQDeriv[q][i];
186:     phi[i] = HexQInterp[q][i];
187:     dphi[i][0] = dphir[0]*ijac[0][0] + dphir[1]*ijac[1][0] + dphir[2]*ijac[2][0];
188:     dphi[i][1] = dphir[0]*ijac[0][1] + dphir[1]*ijac[1][1] + dphir[2]*ijac[2][1];
189:     dphi[i][2] = dphir[0]*ijac[0][2] + dphir[1]*ijac[1][2] + dphir[2]*ijac[2][2];
190:   }
191:   *jw = 1.0 * jdet;
192: }

194: typedef struct _p_THI   *THI;
195: typedef struct _n_Units *Units;

197: typedef struct {
198:   PetscScalar u,v;
199: } Node;

201: typedef struct {
202:   PetscScalar b;                /* bed */
203:   PetscScalar h;                /* thickness */
204:   PetscScalar beta2;            /* friction */
205: } PrmNode;

207: #define FieldSize(ntype) ((PetscInt)(sizeof(ntype)/sizeof(PetscScalar)))
208: #define FieldOffset(ntype,member) ((PetscInt)(offsetof(ntype,member)/sizeof(PetscScalar)))
209: #define FieldIndex(ntype,i,member) ((PetscInt)((i)*FieldSize(ntype) + FieldOffset(ntype,member)))
210: #define NODE_SIZE FieldSize(Node)
211: #define PRMNODE_SIZE FieldSize(PrmNode)

213: typedef struct {
214:   PetscReal min,max,cmin,cmax;
215: } PRange;

217: struct _p_THI {
218:   PETSCHEADER(int);
219:   void      (*initialize)(THI,PetscReal x,PetscReal y,PrmNode *p);
220:   PetscInt  nlevels;
221:   PetscInt  zlevels;
222:   PetscReal Lx,Ly,Lz;           /* Model domain */
223:   PetscReal alpha;              /* Bed angle */
224:   Units     units;
225:   PetscReal dirichlet_scale;
226:   PetscReal ssa_friction_scale;
227:   PetscReal inertia;
228:   PRange    eta;
229:   PRange    beta2;
230:   struct {
231:     PetscReal Bd2,eps,exponent,glen_n;
232:   } viscosity;
233:   struct {
234:     PetscReal irefgam,eps2,exponent;
235:   } friction;
236:   struct {
237:     PetscReal rate,exponent,refvel;
238:   } erosion;
239:   PetscReal rhog;
240:   PetscBool no_slip;
241:   PetscBool verbose;
242:   MatType   mattype;
243:   char      *monitor_basename;
244:   PetscInt  monitor_interval;
245: };

247: struct _n_Units {
248:   /* fundamental */
249:   PetscReal meter;
250:   PetscReal kilogram;
251:   PetscReal second;
252:   /* derived */
253:   PetscReal Pascal;
254:   PetscReal year;
255: };

257: static void PrmHexGetZ(const PrmNode pn[],PetscInt k,PetscInt zm,PetscReal zn[])
258: {
259:   const PetscScalar zm1 = zm-1,
260:     znl[8] = {pn[0].b + pn[0].h*(PetscScalar)k/zm1,
261:               pn[1].b + pn[1].h*(PetscScalar)k/zm1,
262:               pn[2].b + pn[2].h*(PetscScalar)k/zm1,
263:               pn[3].b + pn[3].h*(PetscScalar)k/zm1,
264:               pn[0].b + pn[0].h*(PetscScalar)(k+1)/zm1,
265:               pn[1].b + pn[1].h*(PetscScalar)(k+1)/zm1,
266:               pn[2].b + pn[2].h*(PetscScalar)(k+1)/zm1,
267:               pn[3].b + pn[3].h*(PetscScalar)(k+1)/zm1};
268:   PetscInt i;
269:   for (i=0; i<8; i++) zn[i] = PetscRealPart(znl[i]);
270: }

272: /* Compute a gradient of all the 2D fields at four quadrature points.  Output for [quadrature_point][direction].field_name */
273: static PetscErrorCode QuadComputeGrad4(const PetscReal dphi[][4][2],PetscReal hx,PetscReal hy,const PrmNode pn[4],PrmNode dp[4][2])
274: {
276:   PetscInt       q,i,f;
277:   const PetscScalar (*restrict pg)[PRMNODE_SIZE] = (const PetscScalar(*)[PRMNODE_SIZE])pn; /* Get generic array pointers to the node */
278:   PetscScalar (*restrict dpg)[2][PRMNODE_SIZE]   = (PetscScalar(*)[2][PRMNODE_SIZE])dp;

281:   PetscMemzero(dpg,4*sizeof(dpg[0]));
282:   for (q=0; q<4; q++) {
283:     for (i=0; i<4; i++) {
284:       for (f=0; f<PRMNODE_SIZE; f++) {
285:         dpg[q][0][f] += dphi[q][i][0]/hx * pg[i][f];
286:         dpg[q][1][f] += dphi[q][i][1]/hy * pg[i][f];
287:       }
288:     }
289:   }
290:   return(0);
291: }

293: static inline PetscReal StaggeredMidpoint2D(PetscScalar a,PetscScalar b,PetscScalar c,PetscScalar d)
294: {return 0.5*PetscRealPart(0.75*a + 0.75*b + 0.25*c + 0.25*d);}
295: static inline PetscReal UpwindFlux1D(PetscReal u,PetscReal hL,PetscReal hR)
296: {return (u > 0) ? hL*u : hR*u;}

298: #define UpwindFluxXW(x3,x2,h,i,j,k,dj) UpwindFlux1D(StaggeredMidpoint2D(x3[i][j][k].u,x3[i-1][j][k].u, x3[i-1][j+dj][k].u,x3[i][k+dj][k].u), \
299:                                                     PetscRealPart(0.75*x2[i-1][j  ].h+0.25*x2[i-1][j+dj].h), PetscRealPart(0.75*x2[i  ][j  ].h+0.25*x2[i  ][j+dj].h))
300: #define UpwindFluxXE(x3,x2,h,i,j,k,dj) UpwindFlux1D(StaggeredMidpoint2D(x3[i][j][k].u,x3[i+1][j][k].u, x3[i+1][j+dj][k].u,x3[i][k+dj][k].u), \
301:                                                     PetscRealPart(0.75*x2[i  ][j  ].h+0.25*x2[i  ][j+dj].h), PetscRealPart(0.75*x2[i+1][j  ].h+0.25*x2[i+1][j+dj].h))
302: #define UpwindFluxYS(x3,x2,h,i,j,k,di) UpwindFlux1D(StaggeredMidpoint2D(x3[i][j][k].v,x3[i][j-1][k].v, x3[i+di][j-1][k].v,x3[i+di][j][k].v), \
303:                                                     PetscRealPart(0.75*x2[i  ][j-1].h+0.25*x2[i+di][j-1].h), PetscRealPart(0.75*x2[i  ][j  ].h+0.25*x2[i+di][j  ].h))
304: #define UpwindFluxYN(x3,x2,h,i,j,k,di) UpwindFlux1D(StaggeredMidpoint2D(x3[i][j][k].v,x3[i][j+1][k].v, x3[i+di][j+1][k].v,x3[i+di][j][k].v), \
305:                                                     PetscRealPart(0.75*x2[i  ][j  ].h+0.25*x2[i+di][j  ].h), PetscRealPart(0.75*x2[i  ][j+1].h+0.25*x2[i+di][j+1].h))

307: static void PrmNodeGetFaceMeasure(const PrmNode **p,PetscInt i,PetscInt j,PetscScalar h[])
308: {
309:   /* West */
310:   h[0] = StaggeredMidpoint2D(p[i][j].h,p[i-1][j].h,p[i-1][j-1].h,p[i][j-1].h);
311:   h[1] = StaggeredMidpoint2D(p[i][j].h,p[i-1][j].h,p[i-1][j+1].h,p[i][j+1].h);
312:   /* East */
313:   h[2] = StaggeredMidpoint2D(p[i][j].h,p[i+1][j].h,p[i+1][j+1].h,p[i][j+1].h);
314:   h[3] = StaggeredMidpoint2D(p[i][j].h,p[i+1][j].h,p[i+1][j-1].h,p[i][j-1].h);
315:   /* South */
316:   h[4] = StaggeredMidpoint2D(p[i][j].h,p[i][j-1].h,p[i+1][j-1].h,p[i+1][j].h);
317:   h[5] = StaggeredMidpoint2D(p[i][j].h,p[i][j-1].h,p[i-1][j-1].h,p[i-1][j].h);
318:   /* North */
319:   h[6] = StaggeredMidpoint2D(p[i][j].h,p[i][j+1].h,p[i-1][j+1].h,p[i-1][j].h);
320:   h[7] = StaggeredMidpoint2D(p[i][j].h,p[i][j+1].h,p[i+1][j+1].h,p[i+1][j].h);
321: }

323: /* Tests A and C are from the ISMIP-HOM paper (Pattyn et al. 2008) */
324: static void THIInitialize_HOM_A(THI thi,PetscReal x,PetscReal y,PrmNode *p)
325: {
326:   Units units = thi->units;
327:   PetscReal s = -x*PetscSinReal(thi->alpha);
328:   p->b = s - 1000*units->meter + 500*units->meter * PetscSinReal(x*2*PETSC_PI/thi->Lx) * PetscSinReal(y*2*PETSC_PI/thi->Ly);
329:   p->h = s - p->b;
330:   p->beta2 = -1e-10;             /* This value is not used, but it should not be huge because that would change the finite difference step size  */
331: }

333: static void THIInitialize_HOM_C(THI thi,PetscReal x,PetscReal y,PrmNode *p)
334: {
335:   Units units = thi->units;
336:   PetscReal s = -x*PetscSinReal(thi->alpha);
337:   p->b = s - 1000*units->meter;
338:   p->h = s - p->b;
339:   /* tau_b = beta2 v   is a stress (Pa).
340:    * This is a big number in our units (it needs to balance the driving force from the surface), so we scale it by 1/rhog, just like the residual. */
341:   p->beta2 = 1000 * (1 + PetscSinReal(x*2*PETSC_PI/thi->Lx)*PetscSinReal(y*2*PETSC_PI/thi->Ly)) * units->Pascal * units->year / units->meter / thi->rhog;
342: }

344: /* These are just toys */

346: /* From Fred Herman */
347: static void THIInitialize_HOM_F(THI thi,PetscReal x,PetscReal y,PrmNode *p)
348: {
349:   Units units = thi->units;
350:   PetscReal s = -x*PetscSinReal(thi->alpha);
351:   p->b = s - 1000*units->meter + 100*units->meter * PetscSinReal(x*2*PETSC_PI/thi->Lx);/* * sin(y*2*PETSC_PI/thi->Ly); */
352:   p->h = s - p->b;
353:   p->h = (1-(atan((x-thi->Lx/2)/1.)+PETSC_PI/2.)/PETSC_PI)*500*units->meter+1*units->meter;
354:   s = PetscRealPart(p->b + p->h);
355:   p->beta2 = -1e-10;
356:   /*  p->beta2 = 1000 * units->Pascal * units->year / units->meter; */
357: }

359: /* Same bed as test A, free slip everywhere except for a discontinuous jump to a circular sticky region in the middle. */
360: static void THIInitialize_HOM_X(THI thi,PetscReal xx,PetscReal yy,PrmNode *p)
361: {
362:   Units units = thi->units;
363:   PetscReal x = xx*2*PETSC_PI/thi->Lx - PETSC_PI,y = yy*2*PETSC_PI/thi->Ly - PETSC_PI; /* [-pi,pi] */
364:   PetscReal r = PetscSqrtReal(x*x + y*y),s = -x*PetscSinReal(thi->alpha);
365:   p->b = s - 1000*units->meter + 500*units->meter * PetscSinReal(x + PETSC_PI) * PetscSinReal(y + PETSC_PI);
366:   p->h = s - p->b;
367:   p->beta2 = 1000 * (r < 1 ? 2 : 0) * units->Pascal * units->year / units->meter / thi->rhog;
368: }

370: /* Like Z, but with 200 meter cliffs */
371: static void THIInitialize_HOM_Y(THI thi,PetscReal xx,PetscReal yy,PrmNode *p)
372: {
373:   Units units = thi->units;
374:   PetscReal x = xx*2*PETSC_PI/thi->Lx - PETSC_PI,y = yy*2*PETSC_PI/thi->Ly - PETSC_PI; /* [-pi,pi] */
375:   PetscReal r = PetscSqrtReal(x*x + y*y),s = -x*PetscSinReal(thi->alpha);
376:   p->b = s - 1000*units->meter + 500*units->meter * PetscSinReal(x + PETSC_PI) * PetscSinReal(y + PETSC_PI);
377:   if (PetscRealPart(p->b) > -700*units->meter) p->b += 200*units->meter;
378:   p->h = s - p->b;
379:   p->beta2 = 1000 * (1. + PetscSinReal(PetscSqrtReal(16*r))/PetscSqrtReal(1e-2 + 16*r)*PetscCosReal(x*3/2)*PetscCosReal(y*3/2)) * units->Pascal * units->year / units->meter / thi->rhog;
380: }

382: /* Same bed as A, smoothly varying slipperiness, similar to MATLAB's "sombrero" (uncorrelated with bathymetry) */
383: static void THIInitialize_HOM_Z(THI thi,PetscReal xx,PetscReal yy,PrmNode *p)
384: {
385:   Units units = thi->units;
386:   PetscReal x = xx*2*PETSC_PI/thi->Lx - PETSC_PI,y = yy*2*PETSC_PI/thi->Ly - PETSC_PI; /* [-pi,pi] */
387:   PetscReal r = PetscSqrtReal(x*x + y*y),s = -x*PetscSinReal(thi->alpha);
388:   p->b = s - 1000*units->meter + 500*units->meter * PetscSinReal(x + PETSC_PI) * PetscSinReal(y + PETSC_PI);
389:   p->h = s - p->b;
390:   p->beta2 = 1000 * (1. + PetscSinReal(PetscSqrtReal(16*r))/PetscSqrtReal(1e-2 + 16*r)*PetscCosReal(x*3/2)*PetscCosReal(y*3/2)) * units->Pascal * units->year / units->meter / thi->rhog;
391: }

393: static void THIFriction(THI thi,PetscReal rbeta2,PetscReal gam,PetscReal *beta2,PetscReal *dbeta2)
394: {
395:   if (thi->friction.irefgam == 0) {
396:     Units units = thi->units;
397:     thi->friction.irefgam = 1./(0.5*PetscSqr(100 * units->meter / units->year));
398:     thi->friction.eps2 = 0.5*PetscSqr(1.e-4 / thi->friction.irefgam);
399:   }
400:   if (thi->friction.exponent == 0) {
401:     *beta2  = rbeta2;
402:     *dbeta2 = 0;
403:   } else {
404:     *beta2  = rbeta2 * PetscPowReal(thi->friction.eps2 + gam*thi->friction.irefgam,thi->friction.exponent);
405:     *dbeta2 = thi->friction.exponent * *beta2 / (thi->friction.eps2 + gam*thi->friction.irefgam) * thi->friction.irefgam;
406:   }
407: }

409: static void THIViscosity(THI thi,PetscReal gam,PetscReal *eta,PetscReal *deta)
410: {
411:   PetscReal Bd2,eps,exponent;
412:   if (thi->viscosity.Bd2 == 0) {
413:     Units units = thi->units;
414:     const PetscReal
415:       n = thi->viscosity.glen_n,                        /* Glen exponent */
416:       p = 1. + 1./n,                                    /* for Stokes */
417:       A = 1.e-16 * PetscPowReal(units->Pascal,-n) / units->year, /* softness parameter (Pa^{-n}/s) */
418:       B = PetscPowReal(A,-1./n);                                 /* hardness parameter */
419:     thi->viscosity.Bd2      = B/2;
420:     thi->viscosity.exponent = (p-2)/2;
421:     thi->viscosity.eps      = 0.5*PetscSqr(1e-5 / units->year);
422:   }
423:   Bd2      = thi->viscosity.Bd2;
424:   exponent = thi->viscosity.exponent;
425:   eps      = thi->viscosity.eps;
426:   *eta     = Bd2 * PetscPowReal(eps + gam,exponent);
427:   *deta    = exponent * (*eta) / (eps + gam);
428: }

430: static void THIErosion(THI thi,const Node *vel,PetscScalar *erate,Node *derate)
431: {
432:   const PetscScalar magref2 = 1.e-10 + (PetscSqr(vel->u) + PetscSqr(vel->v)) / PetscSqr(thi->erosion.refvel),
433:                     rate    = -thi->erosion.rate*PetscPowScalar(magref2, 0.5*thi->erosion.exponent);
434:   if (erate) *erate = rate;
435:   if (derate) {
436:     if (thi->erosion.exponent == 1) {
437:       derate->u = 0;
438:       derate->v = 0;
439:     } else {
440:       derate->u = 0.5*thi->erosion.exponent * rate / magref2 * 2. * vel->u / PetscSqr(thi->erosion.refvel);
441:       derate->v = 0.5*thi->erosion.exponent * rate / magref2 * 2. * vel->v / PetscSqr(thi->erosion.refvel);
442:     }
443:   }
444: }

446: static void RangeUpdate(PetscReal *min,PetscReal *max,PetscReal x)
447: {
448:   if (x < *min) *min = x;
449:   if (x > *max) *max = x;
450: }

452: static void PRangeClear(PRange *p)
453: {
454:   p->cmin = p->min = 1e100;
455:   p->cmax = p->max = -1e100;
456: }

458: static PetscErrorCode PRangeMinMax(PRange *p,PetscReal min,PetscReal max)
459: {

462:   p->cmin = min;
463:   p->cmax = max;
464:   if (min < p->min) p->min = min;
465:   if (max > p->max) p->max = max;
466:   return(0);
467: }

469: static PetscErrorCode THIDestroy(THI *thi)
470: {

474:   if (--((PetscObject)(*thi))->refct > 0) return(0);
475:   PetscFree((*thi)->units);
476:   PetscFree((*thi)->mattype);
477:   PetscFree((*thi)->monitor_basename);
478:   PetscHeaderDestroy(thi);
479:   return(0);
480: }

482: static PetscErrorCode THICreate(MPI_Comm comm,THI *inthi)
483: {
484:   static PetscBool registered = PETSC_FALSE;
485:   THI              thi;
486:   Units            units;
487:   char             monitor_basename[PETSC_MAX_PATH_LEN] = "thi-";
488:   PetscErrorCode   ierr;

491:   *inthi = 0;
492:   if (!registered) {
493:     PetscClassIdRegister("Toy Hydrostatic Ice",&THI_CLASSID);
494:     registered = PETSC_TRUE;
495:   }
496:   PetscHeaderCreate(thi,THI_CLASSID,"THI","Toy Hydrostatic Ice","THI",comm,THIDestroy,0);

498:   PetscNew(&thi->units);

500:   units           = thi->units;
501:   units->meter    = 1e-2;
502:   units->second   = 1e-7;
503:   units->kilogram = 1e-12;

505:   PetscOptionsBegin(comm,NULL,"Scaled units options","");
506:   {
507:     PetscOptionsReal("-units_meter","1 meter in scaled length units","",units->meter,&units->meter,NULL);
508:     PetscOptionsReal("-units_second","1 second in scaled time units","",units->second,&units->second,NULL);
509:     PetscOptionsReal("-units_kilogram","1 kilogram in scaled mass units","",units->kilogram,&units->kilogram,NULL);
510:   }
511:   PetscOptionsEnd();
512:   units->Pascal = units->kilogram / (units->meter * PetscSqr(units->second));
513:   units->year   = 31556926. * units->second, /* seconds per year */

515:   thi->Lx              = 10.e3;
516:   thi->Ly              = 10.e3;
517:   thi->Lz              = 1000;
518:   thi->nlevels         = 1;
519:   thi->dirichlet_scale = 1;
520:   thi->verbose         = PETSC_FALSE;

522:   thi->viscosity.glen_n = 3.;
523:   thi->erosion.rate     = 1e-3; /* m/a */
524:   thi->erosion.exponent = 1.;
525:   thi->erosion.refvel   = 1.;   /* m/a */

527:   PetscOptionsBegin(comm,NULL,"Toy Hydrostatic Ice options","");
528:   {
529:     QuadratureType quad       = QUAD_GAUSS;
530:     char           homexp[]   = "A";
531:     char           mtype[256] = MATSBAIJ;
532:     PetscReal      L,m = 1.0;
533:     PetscBool      flg;
534:     L    = thi->Lx;
535:     PetscOptionsReal("-thi_L","Domain size (m)","",L,&L,&flg);
536:     if (flg) thi->Lx = thi->Ly = L;
537:     PetscOptionsReal("-thi_Lx","X Domain size (m)","",thi->Lx,&thi->Lx,NULL);
538:     PetscOptionsReal("-thi_Ly","Y Domain size (m)","",thi->Ly,&thi->Ly,NULL);
539:     PetscOptionsReal("-thi_Lz","Z Domain size (m)","",thi->Lz,&thi->Lz,NULL);
540:     PetscOptionsString("-thi_hom","ISMIP-HOM experiment (A or C)","",homexp,homexp,sizeof(homexp),NULL);
541:     switch (homexp[0] = toupper(homexp[0])) {
542:     case 'A':
543:       thi->initialize = THIInitialize_HOM_A;
544:       thi->no_slip    = PETSC_TRUE;
545:       thi->alpha      = 0.5;
546:       break;
547:     case 'C':
548:       thi->initialize = THIInitialize_HOM_C;
549:       thi->no_slip    = PETSC_FALSE;
550:       thi->alpha      = 0.1;
551:       break;
552:     case 'F':
553:       thi->initialize = THIInitialize_HOM_F;
554:       thi->no_slip    = PETSC_FALSE;
555:       thi->alpha      = 0.5;
556:       break;
557:     case 'X':
558:       thi->initialize = THIInitialize_HOM_X;
559:       thi->no_slip    = PETSC_FALSE;
560:       thi->alpha      = 0.3;
561:       break;
562:     case 'Y':
563:       thi->initialize = THIInitialize_HOM_Y;
564:       thi->no_slip    = PETSC_FALSE;
565:       thi->alpha      = 0.5;
566:       break;
567:     case 'Z':
568:       thi->initialize = THIInitialize_HOM_Z;
569:       thi->no_slip    = PETSC_FALSE;
570:       thi->alpha      = 0.5;
571:       break;
572:     default:
573:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"HOM experiment '%c' not implemented",homexp[0]);
574:     }
575:     PetscOptionsEnum("-thi_quadrature","Quadrature to use for 3D elements","",QuadratureTypes,(PetscEnum)quad,(PetscEnum*)&quad,NULL);
576:     switch (quad) {
577:     case QUAD_GAUSS:
578:       HexQInterp = HexQInterp_Gauss;
579:       HexQDeriv  = HexQDeriv_Gauss;
580:       break;
581:     case QUAD_LOBATTO:
582:       HexQInterp = HexQInterp_Lobatto;
583:       HexQDeriv  = HexQDeriv_Lobatto;
584:       break;
585:     }
586:     PetscOptionsReal("-thi_alpha","Bed angle (degrees)","",thi->alpha,&thi->alpha,NULL);
587:     PetscOptionsReal("-thi_viscosity_glen_n","Exponent in Glen flow law, 1=linear, infty=ideal plastic",NULL,thi->viscosity.glen_n,&thi->viscosity.glen_n,NULL);
588:     PetscOptionsReal("-thi_friction_m","Friction exponent, 0=Coulomb, 1=Navier","",m,&m,NULL);
589:     thi->friction.exponent = (m-1)/2;
590:     PetscOptionsReal("-thi_erosion_rate","Rate of erosion relative to sliding velocity at reference velocity (m/a)",NULL,thi->erosion.rate,&thi->erosion.rate,NULL);
591:     PetscOptionsReal("-thi_erosion_exponent","Power of sliding velocity appearing in erosion relation",NULL,thi->erosion.exponent,&thi->erosion.exponent,NULL);
592:     PetscOptionsReal("-thi_erosion_refvel","Reference sliding velocity for erosion (m/a)",NULL,thi->erosion.refvel,&thi->erosion.refvel,NULL);
593:     thi->erosion.rate   *= units->meter / units->year;
594:     thi->erosion.refvel *= units->meter / units->year;
595:     PetscOptionsReal("-thi_dirichlet_scale","Scale Dirichlet boundary conditions by this factor","",thi->dirichlet_scale,&thi->dirichlet_scale,NULL);
596:     PetscOptionsReal("-thi_ssa_friction_scale","Scale slip boundary conditions by this factor in SSA (2D) assembly","",thi->ssa_friction_scale,&thi->ssa_friction_scale,NULL);
597:     PetscOptionsReal("-thi_inertia","Coefficient of accelaration term in velocity system, physical is almost zero",NULL,thi->inertia,&thi->inertia,NULL);
598:     PetscOptionsInt("-thi_nlevels","Number of levels of refinement","",thi->nlevels,&thi->nlevels,NULL);
599:     PetscOptionsFList("-thi_mat_type","Matrix type","MatSetType",MatList,mtype,(char*)mtype,sizeof(mtype),NULL);
600:     PetscStrallocpy(mtype,&thi->mattype);
601:     PetscOptionsBool("-thi_verbose","Enable verbose output (like matrix sizes and statistics)","",thi->verbose,&thi->verbose,NULL);
602:     PetscOptionsString("-thi_monitor","Basename to write state files to",NULL,monitor_basename,monitor_basename,sizeof(monitor_basename),&flg);
603:     if (flg) {
604:       PetscStrallocpy(monitor_basename,&thi->monitor_basename);
605:       thi->monitor_interval = 1;
606:       PetscOptionsInt("-thi_monitor_interval","Frequency at which to write state files",NULL,thi->monitor_interval,&thi->monitor_interval,NULL);
607:     }
608:   }
609:   PetscOptionsEnd();

611:   /* dimensionalize */
612:   thi->Lx    *= units->meter;
613:   thi->Ly    *= units->meter;
614:   thi->Lz    *= units->meter;
615:   thi->alpha *= PETSC_PI / 180;

617:   PRangeClear(&thi->eta);
618:   PRangeClear(&thi->beta2);

620:   {
621:     PetscReal u       = 1000*units->meter/(3e7*units->second),
622:               gradu   = u / (100*units->meter),eta,deta,
623:               rho     = 910 * units->kilogram/PetscPowRealInt(units->meter,3),
624:               grav    = 9.81 * units->meter/PetscSqr(units->second),
625:               driving = rho * grav * PetscSinReal(thi->alpha) * 1000*units->meter;
626:     THIViscosity(thi,0.5*gradu*gradu,&eta,&deta);
627:     thi->rhog = rho * grav;
628:     if (thi->verbose) {
629:       PetscPrintf(PetscObjectComm((PetscObject)thi),"Units: meter %8.2g  second %8.2g  kg %8.2g  Pa %8.2g\n",units->meter,units->second,units->kilogram,units->Pascal);
630:       PetscPrintf(PetscObjectComm((PetscObject)thi),"Domain (%6.2g,%6.2g,%6.2g), pressure %8.2g, driving stress %8.2g\n",thi->Lx,thi->Ly,thi->Lz,rho*grav*1e3*units->meter,driving);
631:       PetscPrintf(PetscObjectComm((PetscObject)thi),"Large velocity 1km/a %8.2g, velocity gradient %8.2g, eta %8.2g, stress %8.2g, ratio %8.2g\n",u,gradu,eta,2*eta*gradu,2*eta*gradu/driving);
632:       THIViscosity(thi,0.5*PetscSqr(1e-3*gradu),&eta,&deta);
633:       PetscPrintf(PetscObjectComm((PetscObject)thi),"Small velocity 1m/a  %8.2g, velocity gradient %8.2g, eta %8.2g, stress %8.2g, ratio %8.2g\n",1e-3*u,1e-3*gradu,eta,2*eta*1e-3*gradu,2*eta*1e-3*gradu/driving);
634:     }
635:   }

637:   *inthi = thi;
638:   return(0);
639: }

641: /* Our problem is periodic, but the domain has a mean slope of alpha so the bed does not line up between the upstream
642:  * and downstream ends of the domain.  This function fixes the ghost values so that the domain appears truly periodic in
643:  * the horizontal. */
644: static PetscErrorCode THIFixGhosts(THI thi,DM da3,DM da2,Vec X3,Vec X2)
645: {
647:   DMDALocalInfo  info;
648:   PrmNode        **x2;
649:   PetscInt       i,j;

652:   DMDAGetLocalInfo(da3,&info);
653:   /* VecView(X2,PETSC_VIEWER_STDOUT_WORLD); */
654:   DMDAVecGetArray(da2,X2,&x2);
655:   for (i=info.gzs; i<info.gzs+info.gzm; i++) {
656:     if (i > -1 && i < info.mz) continue;
657:     for (j=info.gys; j<info.gys+info.gym; j++) {
658:       x2[i][j].b += PetscSinReal(thi->alpha) * thi->Lx * (i<0 ? 1.0 : -1.0);
659:     }
660:   }
661:   DMDAVecRestoreArray(da2,X2,&x2);
662:   /* VecView(X2,PETSC_VIEWER_STDOUT_WORLD); */
663:   return(0);
664: }

666: static PetscErrorCode THIInitializePrm(THI thi,DM da2prm,PrmNode **p)
667: {
668:   PetscInt       i,j,xs,xm,ys,ym,mx,my;

672:   DMDAGetGhostCorners(da2prm,&ys,&xs,0,&ym,&xm,0);
673:   DMDAGetInfo(da2prm,0, &my,&mx,0, 0,0,0, 0,0,0,0,0,0);
674:   for (i=xs; i<xs+xm; i++) {
675:     for (j=ys; j<ys+ym; j++) {
676:       PetscReal xx = thi->Lx*i/mx,yy = thi->Ly*j/my;
677:       thi->initialize(thi,xx,yy,&p[i][j]);
678:     }
679:   }
680:   return(0);
681: }

683: static PetscErrorCode THIInitial(THI thi,DM pack,Vec X)
684: {
685:   DM             da3,da2;
686:   PetscInt       i,j,k,xs,xm,ys,ym,zs,zm,mx,my;
687:   PetscReal      hx,hy;
688:   PrmNode        **prm;
689:   Node           ***x;
690:   Vec            X3g,X2g,X2;

694:   DMCompositeGetEntries(pack,&da3,&da2);
695:   DMCompositeGetAccess(pack,X,&X3g,&X2g);
696:   DMGetLocalVector(da2,&X2);

698:   DMDAGetInfo(da3,0, 0,&my,&mx, 0,0,0, 0,0,0,0,0,0);
699:   DMDAGetCorners(da3,&zs,&ys,&xs,&zm,&ym,&xm);
700:   DMDAVecGetArray(da3,X3g,&x);
701:   DMDAVecGetArray(da2,X2,&prm);

703:   THIInitializePrm(thi,da2,prm);

705:   hx = thi->Lx / mx;
706:   hy = thi->Ly / my;
707:   for (i=xs; i<xs+xm; i++) {
708:     for (j=ys; j<ys+ym; j++) {
709:       for (k=zs; k<zs+zm; k++) {
710:         const PetscScalar zm1      = zm-1,
711:                           drivingx = thi->rhog * (prm[i+1][j].b+prm[i+1][j].h - prm[i-1][j].b-prm[i-1][j].h) / (2*hx),
712:                           drivingy = thi->rhog * (prm[i][j+1].b+prm[i][j+1].h - prm[i][j-1].b-prm[i][j-1].h) / (2*hy);
713:         x[i][j][k].u = 0. * drivingx * prm[i][j].h*(PetscScalar)k/zm1;
714:         x[i][j][k].v = 0. * drivingy * prm[i][j].h*(PetscScalar)k/zm1;
715:       }
716:     }
717:   }

719:   DMDAVecRestoreArray(da3,X3g,&x);
720:   DMDAVecRestoreArray(da2,X2,&prm);

722:   DMLocalToGlobalBegin(da2,X2,INSERT_VALUES,X2g);
723:   DMLocalToGlobalEnd  (da2,X2,INSERT_VALUES,X2g);
724:   DMRestoreLocalVector(da2,&X2);

726:   DMCompositeRestoreAccess(pack,X,&X3g,&X2g);
727:   return(0);
728: }

730: static void PointwiseNonlinearity(THI thi,const Node n[restrict 8],const PetscReal phi[restrict 3],PetscReal dphi[restrict 8][3],PetscScalar *restrict u,PetscScalar *restrict v,PetscScalar du[restrict 3],PetscScalar dv[restrict 3],PetscReal *eta,PetscReal *deta)
731: {
732:   PetscInt    l,ll;
733:   PetscScalar gam;

735:   du[0] = du[1] = du[2] = 0;
736:   dv[0] = dv[1] = dv[2] = 0;
737:   *u    = 0;
738:   *v    = 0;
739:   for (l=0; l<8; l++) {
740:     *u += phi[l] * n[l].u;
741:     *v += phi[l] * n[l].v;
742:     for (ll=0; ll<3; ll++) {
743:       du[ll] += dphi[l][ll] * n[l].u;
744:       dv[ll] += dphi[l][ll] * n[l].v;
745:     }
746:   }
747:   gam = Sqr(du[0]) + Sqr(dv[1]) + du[0]*dv[1] + 0.25*Sqr(du[1]+dv[0]) + 0.25*Sqr(du[2]) + 0.25*Sqr(dv[2]);
748:   THIViscosity(thi,PetscRealPart(gam),eta,deta);
749: }

751: static PetscErrorCode THIFunctionLocal_3D(DMDALocalInfo *info,const Node ***x,const PrmNode **prm,const Node ***xdot,Node ***f,THI thi)
752: {
753:   PetscInt       xs,ys,xm,ym,zm,i,j,k,q,l;
754:   PetscReal      hx,hy,etamin,etamax,beta2min,beta2max;

758:   xs = info->zs;
759:   ys = info->ys;
760:   xm = info->zm;
761:   ym = info->ym;
762:   zm = info->xm;
763:   hx = thi->Lx / info->mz;
764:   hy = thi->Ly / info->my;

766:   etamin   = 1e100;
767:   etamax   = 0;
768:   beta2min = 1e100;
769:   beta2max = 0;

771:   for (i=xs; i<xs+xm; i++) {
772:     for (j=ys; j<ys+ym; j++) {
773:       PrmNode pn[4],dpn[4][2];
774:       QuadExtract(prm,i,j,pn);
775:       QuadComputeGrad4(QuadQDeriv,hx,hy,pn,dpn);
776:       for (k=0; k<zm-1; k++) {
777:         PetscInt  ls = 0;
778:         Node      n[8],ndot[8],*fn[8];
779:         PetscReal zn[8],etabase = 0;
780:         PrmHexGetZ(pn,k,zm,zn);
781:         HexExtract(x,i,j,k,n);
782:         HexExtract(xdot,i,j,k,ndot);
783:         HexExtractRef(f,i,j,k,fn);
784:         if (thi->no_slip && k == 0) {
785:           for (l=0; l<4; l++) n[l].u = n[l].v = 0;
786:           /* The first 4 basis functions lie on the bottom layer, so their contribution is exactly 0, hence we can skip them */
787:           ls = 4;
788:         }
789:         for (q=0; q<8; q++) {
790:           PetscReal   dz[3],phi[8],dphi[8][3],jw,eta,deta;
791:           PetscScalar du[3],dv[3],u,v,udot=0,vdot=0;
792:           for (l=ls; l<8; l++) {
793:             udot += HexQInterp[q][l]*ndot[l].u;
794:             vdot += HexQInterp[q][l]*ndot[l].v;
795:           }
796:           HexGrad(HexQDeriv[q],zn,dz);
797:           HexComputeGeometry(q,hx,hy,dz,phi,dphi,&jw);
798:           PointwiseNonlinearity(thi,n,phi,dphi,&u,&v,du,dv,&eta,&deta);
799:           jw /= thi->rhog;      /* scales residuals to be O(1) */
800:           if (q == 0) etabase = eta;
801:           RangeUpdate(&etamin,&etamax,eta);
802:           for (l=ls; l<8; l++) { /* test functions */
803:             const PetscScalar ds[2] = {dpn[q%4][0].h+dpn[q%4][0].b, dpn[q%4][1].h+dpn[q%4][1].b};
804:             const PetscReal   pp    = phi[l],*dp = dphi[l];
805:             fn[l]->u += dp[0]*jw*eta*(4.*du[0]+2.*dv[1]) + dp[1]*jw*eta*(du[1]+dv[0]) + dp[2]*jw*eta*du[2] + pp*jw*thi->rhog*ds[0];
806:             fn[l]->v += dp[1]*jw*eta*(2.*du[0]+4.*dv[1]) + dp[0]*jw*eta*(du[1]+dv[0]) + dp[2]*jw*eta*dv[2] + pp*jw*thi->rhog*ds[1];
807:             fn[l]->u += pp*jw*udot*thi->inertia*pp;
808:             fn[l]->v += pp*jw*vdot*thi->inertia*pp;
809:           }
810:         }
811:         if (k == 0) { /* we are on a bottom face */
812:           if (thi->no_slip) {
813:             /* Note: Non-Galerkin coarse grid operators are very sensitive to the scaling of Dirichlet boundary
814:             * conditions.  After shenanigans above, etabase contains the effective viscosity at the closest quadrature
815:             * point to the bed.  We want the diagonal entry in the Dirichlet condition to have similar magnitude to the
816:             * diagonal entry corresponding to the adjacent node.  The fundamental scaling of the viscous part is in
817:             * diagu, diagv below.  This scaling is easy to recognize by considering the finite difference operator after
818:             * scaling by element size.  The no-slip Dirichlet condition is scaled by this factor, and also in the
819:             * assembled matrix (see the similar block in THIJacobianLocal).
820:             *
821:             * Note that the residual at this Dirichlet node is linear in the state at this node, but also depends
822:             * (nonlinearly in general) on the neighboring interior nodes through the local viscosity.  This will make
823:             * a matrix-free Jacobian have extra entries in the corresponding row.  We assemble only the diagonal part,
824:             * so the solution will exactly satisfy the boundary condition after the first linear iteration.
825:             */
826:             const PetscReal   hz    = PetscRealPart(pn[0].h)/(zm-1.);
827:             const PetscScalar diagu = 2*etabase/thi->rhog*(hx*hy/hz + hx*hz/hy + 4*hy*hz/hx),diagv = 2*etabase/thi->rhog*(hx*hy/hz + 4*hx*hz/hy + hy*hz/hx);
828:             fn[0]->u = thi->dirichlet_scale*diagu*x[i][j][k].u;
829:             fn[0]->v = thi->dirichlet_scale*diagv*x[i][j][k].v;
830:           } else {              /* Integrate over bottom face to apply boundary condition */
831:             for (q=0; q<4; q++) { /* We remove the explicit scaling of the residual by 1/rhog because beta2 already has that scaling to be O(1) */
832:               const PetscReal jw = 0.25*hx*hy,*phi = QuadQInterp[q];
833:               PetscScalar     u  =0,v=0,rbeta2=0;
834:               PetscReal       beta2,dbeta2;
835:               for (l=0; l<4; l++) {
836:                 u     += phi[l]*n[l].u;
837:                 v     += phi[l]*n[l].v;
838:                 rbeta2 += phi[l]*pn[l].beta2;
839:               }
840:               THIFriction(thi,PetscRealPart(rbeta2),PetscRealPart(u*u+v*v)/2,&beta2,&dbeta2);
841:               RangeUpdate(&beta2min,&beta2max,beta2);
842:               for (l=0; l<4; l++) {
843:                 const PetscReal pp = phi[l];
844:                 fn[ls+l]->u += pp*jw*beta2*u;
845:                 fn[ls+l]->v += pp*jw*beta2*v;
846:               }
847:             }
848:           }
849:         }
850:       }
851:     }
852:   }

854:   PRangeMinMax(&thi->eta,etamin,etamax);
855:   PRangeMinMax(&thi->beta2,beta2min,beta2max);
856:   return(0);
857: }

859: static PetscErrorCode THIFunctionLocal_2D(DMDALocalInfo *info,const Node ***x,const PrmNode **prm,const PrmNode **prmdot,PrmNode **f,THI thi)
860: {
861:   PetscInt xs,ys,xm,ym,zm,i,j,k;

864:   xs = info->zs;
865:   ys = info->ys;
866:   xm = info->zm;
867:   ym = info->ym;
868:   zm = info->xm;

870:   for (i=xs; i<xs+xm; i++) {
871:     for (j=ys; j<ys+ym; j++) {
872:       PetscScalar div = 0,erate,h[8];
873:       PrmNodeGetFaceMeasure(prm,i,j,h);
874:       for (k=0; k<zm; k++) {
875:         PetscScalar weight = (k==0 || k == zm-1) ? 0.5/(zm-1) : 1.0/(zm-1);
876:         if (0) {                /* centered flux */
877:           div += (- weight*h[0] * StaggeredMidpoint2D(x[i][j][k].u,x[i-1][j][k].u, x[i-1][j-1][k].u,x[i][j-1][k].u)
878:                   - weight*h[1] * StaggeredMidpoint2D(x[i][j][k].u,x[i-1][j][k].u, x[i-1][j+1][k].u,x[i][j+1][k].u)
879:                   + weight*h[2] * StaggeredMidpoint2D(x[i][j][k].u,x[i+1][j][k].u, x[i+1][j+1][k].u,x[i][j+1][k].u)
880:                   + weight*h[3] * StaggeredMidpoint2D(x[i][j][k].u,x[i+1][j][k].u, x[i+1][j-1][k].u,x[i][j-1][k].u)
881:                   - weight*h[4] * StaggeredMidpoint2D(x[i][j][k].v,x[i][j-1][k].v, x[i+1][j-1][k].v,x[i+1][j][k].v)
882:                   - weight*h[5] * StaggeredMidpoint2D(x[i][j][k].v,x[i][j-1][k].v, x[i-1][j-1][k].v,x[i-1][j][k].v)
883:                   + weight*h[6] * StaggeredMidpoint2D(x[i][j][k].v,x[i][j+1][k].v, x[i-1][j+1][k].v,x[i-1][j][k].v)
884:                   + weight*h[7] * StaggeredMidpoint2D(x[i][j][k].v,x[i][j+1][k].v, x[i+1][j+1][k].v,x[i+1][j][k].v));
885:         } else {                /* Upwind flux */
886:           div += weight*(-UpwindFluxXW(x,prm,h,i,j,k, 1)
887:                          -UpwindFluxXW(x,prm,h,i,j,k,-1)
888:                          +UpwindFluxXE(x,prm,h,i,j,k, 1)
889:                          +UpwindFluxXE(x,prm,h,i,j,k,-1)
890:                          -UpwindFluxYS(x,prm,h,i,j,k, 1)
891:                          -UpwindFluxYS(x,prm,h,i,j,k,-1)
892:                          +UpwindFluxYN(x,prm,h,i,j,k, 1)
893:                          +UpwindFluxYN(x,prm,h,i,j,k,-1));
894:         }
895:       }
896:       /* printf("div[%d][%d] %g\n",i,j,div); */
897:       THIErosion(thi,&x[i][j][0],&erate,NULL);
898:       f[i][j].b     = prmdot[i][j].b - erate;
899:       f[i][j].h     = prmdot[i][j].h + div;
900:       f[i][j].beta2 = prmdot[i][j].beta2;
901:     }
902:   }
903:   return(0);
904: }

906: static PetscErrorCode THIFunction(TS ts,PetscReal t,Vec X,Vec Xdot,Vec F,void *ctx)
907: {
909:   THI            thi = (THI)ctx;
910:   DM             pack,da3,da2;
911:   Vec            X3,X2,Xdot3,Xdot2,F3,F2,F3g,F2g;
912:   const Node     ***x3,***xdot3;
913:   const PrmNode  **x2,**xdot2;
914:   Node           ***f3;
915:   PrmNode        **f2;
916:   DMDALocalInfo  info3;

919:   TSGetDM(ts,&pack);
920:   DMCompositeGetEntries(pack,&da3,&da2);
921:   DMDAGetLocalInfo(da3,&info3);
922:   DMCompositeGetLocalVectors(pack,&X3,&X2);
923:   DMCompositeGetLocalVectors(pack,&Xdot3,&Xdot2);
924:   DMCompositeScatter(pack,X,X3,X2);
925:   THIFixGhosts(thi,da3,da2,X3,X2);
926:   DMCompositeScatter(pack,Xdot,Xdot3,Xdot2);

928:   DMGetLocalVector(da3,&F3);
929:   DMGetLocalVector(da2,&F2);
930:   VecZeroEntries(F3);

932:   DMDAVecGetArray(da3,X3,&x3);
933:   DMDAVecGetArray(da2,X2,&x2);
934:   DMDAVecGetArray(da3,Xdot3,&xdot3);
935:   DMDAVecGetArray(da2,Xdot2,&xdot2);
936:   DMDAVecGetArray(da3,F3,&f3);
937:   DMDAVecGetArray(da2,F2,&f2);

939:   THIFunctionLocal_3D(&info3,x3,x2,xdot3,f3,thi);
940:   THIFunctionLocal_2D(&info3,x3,x2,xdot2,f2,thi);

942:   DMDAVecRestoreArray(da3,X3,&x3);
943:   DMDAVecRestoreArray(da2,X2,&x2);
944:   DMDAVecRestoreArray(da3,Xdot3,&xdot3);
945:   DMDAVecRestoreArray(da2,Xdot2,&xdot2);
946:   DMDAVecRestoreArray(da3,F3,&f3);
947:   DMDAVecRestoreArray(da2,F2,&f2);

949:   DMCompositeRestoreLocalVectors(pack,&X3,&X2);
950:   DMCompositeRestoreLocalVectors(pack,&Xdot3,&Xdot2);

952:   VecZeroEntries(F);
953:   DMCompositeGetAccess(pack,F,&F3g,&F2g);
954:   DMLocalToGlobalBegin(da3,F3,ADD_VALUES,F3g);
955:   DMLocalToGlobalEnd  (da3,F3,ADD_VALUES,F3g);
956:   DMLocalToGlobalBegin(da2,F2,INSERT_VALUES,F2g);
957:   DMLocalToGlobalEnd  (da2,F2,INSERT_VALUES,F2g);

959:   if (thi->verbose) {
960:     PetscViewer viewer;
961:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)thi),&viewer);
962:     PetscViewerASCIIPrintf(viewer,"3D_Velocity residual (bs=2):\n");
963:     PetscViewerASCIIPushTab(viewer);
964:     VecView(F3,viewer);
965:     PetscViewerASCIIPopTab(viewer);
966:     PetscViewerASCIIPrintf(viewer,"2D_Fields residual (bs=3):\n");
967:     PetscViewerASCIIPushTab(viewer);
968:     VecView(F2,viewer);
969:     PetscViewerASCIIPopTab(viewer);
970:   }

972:   DMCompositeRestoreAccess(pack,F,&F3g,&F2g);

974:   DMRestoreLocalVector(da3,&F3);
975:   DMRestoreLocalVector(da2,&F2);
976:   return(0);
977: }

979: static PetscErrorCode THIMatrixStatistics(THI thi,Mat B,PetscViewer viewer)
980: {
982:   PetscReal      nrm;
983:   PetscInt       m;
984:   PetscMPIInt    rank;

987:   MatNorm(B,NORM_FROBENIUS,&nrm);
988:   MatGetSize(B,&m,0);
989:   MPI_Comm_rank(PetscObjectComm((PetscObject)B),&rank);
990:   if (!rank) {
991:     PetscScalar val0,val2;
992:     MatGetValue(B,0,0,&val0);
993:     MatGetValue(B,2,2,&val2);
994:     PetscViewerASCIIPrintf(viewer,"Matrix dim %8d  norm %8.2e, (0,0) %8.2e  (2,2) %8.2e, eta [%8.2e,%8.2e] beta2 [%8.2e,%8.2e]\n",m,nrm,PetscRealPart(val0),PetscRealPart(val2),thi->eta.cmin,thi->eta.cmax,thi->beta2.cmin,thi->beta2.cmax);
995:   }
996:   return(0);
997: }

999: static PetscErrorCode THISurfaceStatistics(DM pack,Vec X,PetscReal *min,PetscReal *max,PetscReal *mean)
1000: {
1002:   DM             da3,da2;
1003:   Vec            X3,X2;
1004:   Node           ***x;
1005:   PetscInt       i,j,xs,ys,zs,xm,ym,zm,mx,my,mz;
1006:   PetscReal      umin = 1e100,umax=-1e100;
1007:   PetscScalar    usum =0.0,gusum;

1010:   DMCompositeGetEntries(pack,&da3,&da2);
1011:   DMCompositeGetAccess(pack,X,&X3,&X2);
1012:   *min = *max = *mean = 0;
1013:   DMDAGetInfo(da3,0, &mz,&my,&mx, 0,0,0, 0,0,0,0,0,0);
1014:   DMDAGetCorners(da3,&zs,&ys,&xs,&zm,&ym,&xm);
1015:   if (zs != 0 || zm != mz) SETERRQ(PETSC_COMM_SELF,1,"Unexpected decomposition");
1016:   DMDAVecGetArray(da3,X3,&x);
1017:   for (i=xs; i<xs+xm; i++) {
1018:     for (j=ys; j<ys+ym; j++) {
1019:       PetscReal u = PetscRealPart(x[i][j][zm-1].u);
1020:       RangeUpdate(&umin,&umax,u);
1021:       usum += u;
1022:     }
1023:   }
1024:   DMDAVecRestoreArray(da3,X3,&x);
1025:   DMCompositeRestoreAccess(pack,X,&X3,&X2);

1027:   MPI_Allreduce(&umin,min,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)da3));
1028:   MPI_Allreduce(&umax,max,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)da3));
1029:   MPI_Allreduce(&usum,&gusum,1,MPIU_SCALAR,MPIU_SUM,PetscObjectComm((PetscObject)da3));
1030:   *mean = PetscRealPart(gusum) / (mx*my);
1031:   return(0);
1032: }

1034: static PetscErrorCode THISolveStatistics(THI thi,TS ts,PetscInt coarsened,const char name[])
1035: {
1036:   MPI_Comm       comm;
1037:   DM             pack;
1038:   Vec            X,X3,X2;

1042:   PetscObjectGetComm((PetscObject)thi,&comm);
1043:   TSGetDM(ts,&pack);
1044:   TSGetSolution(ts,&X);
1045:   DMCompositeGetAccess(pack,X,&X3,&X2);
1046:   PetscPrintf(comm,"Solution statistics after solve: %s\n",name);
1047:   {
1048:     PetscInt            its,lits;
1049:     SNESConvergedReason reason;
1050:     SNES                snes;
1051:     TSGetSNES(ts,&snes);
1052:     SNESGetIterationNumber(snes,&its);
1053:     SNESGetConvergedReason(snes,&reason);
1054:     SNESGetLinearSolveIterations(snes,&lits);
1055:     PetscPrintf(comm,"%s: Number of SNES iterations = %d, total linear iterations = %d\n",SNESConvergedReasons[reason],its,lits);
1056:   }
1057:   {
1058:     PetscReal   nrm2,tmin[3]={1e100,1e100,1e100},tmax[3]={-1e100,-1e100,-1e100},min[3],max[3];
1059:     PetscInt    i,j,m;
1060:     PetscScalar *x;
1061:     VecNorm(X3,NORM_2,&nrm2);
1062:     VecGetLocalSize(X3,&m);
1063:     VecGetArray(X3,&x);
1064:     for (i=0; i<m; i+=2) {
1065:       PetscReal u = PetscRealPart(x[i]),v = PetscRealPart(x[i+1]),c = PetscSqrtReal(u*u+v*v);
1066:       tmin[0] = PetscMin(u,tmin[0]);
1067:       tmin[1] = PetscMin(v,tmin[1]);
1068:       tmin[2] = PetscMin(c,tmin[2]);
1069:       tmax[0] = PetscMax(u,tmax[0]);
1070:       tmax[1] = PetscMax(v,tmax[1]);
1071:       tmax[2] = PetscMax(c,tmax[2]);
1072:     }
1073:     VecRestoreArray(X,&x);
1074:     MPI_Allreduce(tmin,min,3,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)thi));
1075:     MPI_Allreduce(tmax,max,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)thi));
1076:     /* Dimensionalize to meters/year */
1077:     nrm2 *= thi->units->year / thi->units->meter;
1078:     for (j=0; j<3; j++) {
1079:       min[j] *= thi->units->year / thi->units->meter;
1080:       max[j] *= thi->units->year / thi->units->meter;
1081:     }
1082:     PetscPrintf(comm,"|X|_2 %g   u in [%g, %g]   v in [%g, %g]   c in [%g, %g] \n",nrm2,min[0],max[0],min[1],max[1],min[2],max[2]);
1083:     {
1084:       PetscReal umin,umax,umean;
1085:       THISurfaceStatistics(pack,X,&umin,&umax,&umean);
1086:       umin  *= thi->units->year / thi->units->meter;
1087:       umax  *= thi->units->year / thi->units->meter;
1088:       umean *= thi->units->year / thi->units->meter;
1089:       PetscPrintf(comm,"Surface statistics: u in [%12.6e, %12.6e] mean %12.6e\n",umin,umax,umean);
1090:     }
1091:     /* These values stay nondimensional */
1092:     PetscPrintf(comm,"Global eta range   [%g, %g], converged range [%g, %g]\n",thi->eta.min,thi->eta.max,thi->eta.cmin,thi->eta.cmax);
1093:     PetscPrintf(comm,"Global beta2 range [%g, %g], converged range [%g, %g]\n",thi->beta2.min,thi->beta2.max,thi->beta2.cmin,thi->beta2.cmax);
1094:   }
1095:   PetscPrintf(comm,"\n");
1096:   DMCompositeRestoreAccess(pack,X,&X3,&X2);
1097:   return(0);
1098: }

1100: static inline PetscInt DMDALocalIndex3D(DMDALocalInfo *info,PetscInt i,PetscInt j,PetscInt k)
1101: {return ((i-info->gzs)*info->gym + (j-info->gys))*info->gxm + (k-info->gxs);}
1102: static inline PetscInt DMDALocalIndex2D(DMDALocalInfo *info,PetscInt i,PetscInt j)
1103: {return (i-info->gzs)*info->gym + (j-info->gys);}

1105: static PetscErrorCode THIJacobianLocal_Momentum(DMDALocalInfo *info,const Node ***x,const PrmNode **prm,Mat B,Mat Bcpl,THI thi)
1106: {
1107:   PetscInt       xs,ys,xm,ym,zm,i,j,k,q,l,ll;
1108:   PetscReal      hx,hy;

1112:   xs = info->zs;
1113:   ys = info->ys;
1114:   xm = info->zm;
1115:   ym = info->ym;
1116:   zm = info->xm;
1117:   hx = thi->Lx / info->mz;
1118:   hy = thi->Ly / info->my;

1120:   for (i=xs; i<xs+xm; i++) {
1121:     for (j=ys; j<ys+ym; j++) {
1122:       PrmNode pn[4],dpn[4][2];
1123:       QuadExtract(prm,i,j,pn);
1124:       QuadComputeGrad4(QuadQDeriv,hx,hy,pn,dpn);
1125:       for (k=0; k<zm-1; k++) {
1126:         Node        n[8];
1127:         PetscReal   zn[8],etabase = 0;
1128:         PetscScalar Ke[8*NODE_SIZE][8*NODE_SIZE],Kcpl[8*NODE_SIZE][4*PRMNODE_SIZE];
1129:         PetscInt    ls = 0;

1131:         PrmHexGetZ(pn,k,zm,zn);
1132:         HexExtract(x,i,j,k,n);
1133:         PetscMemzero(Ke,sizeof(Ke));
1134:         PetscMemzero(Kcpl,sizeof(Kcpl));
1135:         if (thi->no_slip && k == 0) {
1136:           for (l=0; l<4; l++) n[l].u = n[l].v = 0;
1137:           ls = 4;
1138:         }
1139:         for (q=0; q<8; q++) {
1140:           PetscReal   dz[3],phi[8],dphi[8][3],jw,eta,deta;
1141:           PetscScalar du[3],dv[3],u,v;
1142:           HexGrad(HexQDeriv[q],zn,dz);
1143:           HexComputeGeometry(q,hx,hy,dz,phi,dphi,&jw);
1144:           PointwiseNonlinearity(thi,n,phi,dphi,&u,&v,du,dv,&eta,&deta);
1145:           jw /= thi->rhog;      /* residuals are scaled by this factor */
1146:           if (q == 0) etabase = eta;
1147:           for (l=ls; l<8; l++) { /* test functions */
1148:             const PetscReal pp=phi[l],*restrict dp = dphi[l];
1149:             for (ll=ls; ll<8; ll++) { /* trial functions */
1150:               const PetscReal *restrict dpl = dphi[ll];
1151:               PetscScalar dgdu,dgdv;
1152:               dgdu = 2.*du[0]*dpl[0] + dv[1]*dpl[0] + 0.5*(du[1]+dv[0])*dpl[1] + 0.5*du[2]*dpl[2];
1153:               dgdv = 2.*dv[1]*dpl[1] + du[0]*dpl[1] + 0.5*(du[1]+dv[0])*dpl[0] + 0.5*dv[2]*dpl[2];
1154:               /* Picard part */
1155:               Ke[l*2+0][ll*2+0] += dp[0]*jw*eta*4.*dpl[0] + dp[1]*jw*eta*dpl[1] + dp[2]*jw*eta*dpl[2];
1156:               Ke[l*2+0][ll*2+1] += dp[0]*jw*eta*2.*dpl[1] + dp[1]*jw*eta*dpl[0];
1157:               Ke[l*2+1][ll*2+0] += dp[1]*jw*eta*2.*dpl[0] + dp[0]*jw*eta*dpl[1];
1158:               Ke[l*2+1][ll*2+1] += dp[1]*jw*eta*4.*dpl[1] + dp[0]*jw*eta*dpl[0] + dp[2]*jw*eta*dpl[2];
1159:               /* extra Newton terms */
1160:               Ke[l*2+0][ll*2+0] += dp[0]*jw*deta*dgdu*(4.*du[0]+2.*dv[1]) + dp[1]*jw*deta*dgdu*(du[1]+dv[0]) + dp[2]*jw*deta*dgdu*du[2];
1161:               Ke[l*2+0][ll*2+1] += dp[0]*jw*deta*dgdv*(4.*du[0]+2.*dv[1]) + dp[1]*jw*deta*dgdv*(du[1]+dv[0]) + dp[2]*jw*deta*dgdv*du[2];
1162:               Ke[l*2+1][ll*2+0] += dp[1]*jw*deta*dgdu*(4.*dv[1]+2.*du[0]) + dp[0]*jw*deta*dgdu*(du[1]+dv[0]) + dp[2]*jw*deta*dgdu*dv[2];
1163:               Ke[l*2+1][ll*2+1] += dp[1]*jw*deta*dgdv*(4.*dv[1]+2.*du[0]) + dp[0]*jw*deta*dgdv*(du[1]+dv[0]) + dp[2]*jw*deta*dgdv*dv[2];
1164:               /* inertial part */
1165:               Ke[l*2+0][ll*2+0] += pp*jw*thi->inertia*pp;
1166:               Ke[l*2+1][ll*2+1] += pp*jw*thi->inertia*pp;
1167:             }
1168:             for (ll=0; ll<4; ll++) { /* Trial functions for surface/bed */
1169:               const PetscReal dpl[] = {QuadQDeriv[q%4][ll][0]/hx, QuadQDeriv[q%4][ll][1]/hy}; /* surface = h + b */
1170:               Kcpl[FieldIndex(Node,l,u)][FieldIndex(PrmNode,ll,h)] += pp*jw*thi->rhog*dpl[0];
1171:               Kcpl[FieldIndex(Node,l,u)][FieldIndex(PrmNode,ll,b)] += pp*jw*thi->rhog*dpl[0];
1172:               Kcpl[FieldIndex(Node,l,v)][FieldIndex(PrmNode,ll,h)] += pp*jw*thi->rhog*dpl[1];
1173:               Kcpl[FieldIndex(Node,l,v)][FieldIndex(PrmNode,ll,b)] += pp*jw*thi->rhog*dpl[1];
1174:             }
1175:           }
1176:         }
1177:         if (k == 0) { /* on a bottom face */
1178:           if (thi->no_slip) {
1179:             const PetscReal   hz    = PetscRealPart(pn[0].h)/(zm-1);
1180:             const PetscScalar diagu = 2*etabase/thi->rhog*(hx*hy/hz + hx*hz/hy + 4*hy*hz/hx),diagv = 2*etabase/thi->rhog*(hx*hy/hz + 4*hx*hz/hy + hy*hz/hx);
1181:             Ke[0][0] = thi->dirichlet_scale*diagu;
1182:             Ke[0][1] = 0;
1183:             Ke[1][0] = 0;
1184:             Ke[1][1] = thi->dirichlet_scale*diagv;
1185:           } else {
1186:             for (q=0; q<4; q++) { /* We remove the explicit scaling by 1/rhog because beta2 already has that scaling to be O(1) */
1187:               const PetscReal jw = 0.25*hx*hy,*phi = QuadQInterp[q];
1188:               PetscScalar     u  =0,v=0,rbeta2=0;
1189:               PetscReal       beta2,dbeta2;
1190:               for (l=0; l<4; l++) {
1191:                 u      += phi[l]*n[l].u;
1192:                 v      += phi[l]*n[l].v;
1193:                 rbeta2 += phi[l]*pn[l].beta2;
1194:               }
1195:               THIFriction(thi,PetscRealPart(rbeta2),PetscRealPart(u*u+v*v)/2,&beta2,&dbeta2);
1196:               for (l=0; l<4; l++) {
1197:                 const PetscReal pp = phi[l];
1198:                 for (ll=0; ll<4; ll++) {
1199:                   const PetscReal ppl = phi[ll];
1200:                   Ke[l*2+0][ll*2+0] += pp*jw*beta2*ppl + pp*jw*dbeta2*u*u*ppl;
1201:                   Ke[l*2+0][ll*2+1] +=                   pp*jw*dbeta2*u*v*ppl;
1202:                   Ke[l*2+1][ll*2+0] +=                   pp*jw*dbeta2*v*u*ppl;
1203:                   Ke[l*2+1][ll*2+1] += pp*jw*beta2*ppl + pp*jw*dbeta2*v*v*ppl;
1204:                 }
1205:               }
1206:             }
1207:           }
1208:         }
1209:         {
1210:           const PetscInt rc3blocked[8] = {
1211:             DMDALocalIndex3D(info,i+0,j+0,k+0),
1212:             DMDALocalIndex3D(info,i+1,j+0,k+0),
1213:             DMDALocalIndex3D(info,i+1,j+1,k+0),
1214:             DMDALocalIndex3D(info,i+0,j+1,k+0),
1215:             DMDALocalIndex3D(info,i+0,j+0,k+1),
1216:             DMDALocalIndex3D(info,i+1,j+0,k+1),
1217:             DMDALocalIndex3D(info,i+1,j+1,k+1),
1218:             DMDALocalIndex3D(info,i+0,j+1,k+1)
1219:           },col2blocked[PRMNODE_SIZE*4] = {
1220:             DMDALocalIndex2D(info,i+0,j+0),
1221:             DMDALocalIndex2D(info,i+1,j+0),
1222:             DMDALocalIndex2D(info,i+1,j+1),
1223:             DMDALocalIndex2D(info,i+0,j+1)
1224:           };
1225: #if !defined COMPUTE_LOWER_TRIANGULAR /* fill in lower-triangular part, this is really cheap compared to computing the entries */
1226:           for (l=0; l<8; l++) {
1227:             for (ll=l+1; ll<8; ll++) {
1228:               Ke[ll*2+0][l*2+0] = Ke[l*2+0][ll*2+0];
1229:               Ke[ll*2+1][l*2+0] = Ke[l*2+0][ll*2+1];
1230:               Ke[ll*2+0][l*2+1] = Ke[l*2+1][ll*2+0];
1231:               Ke[ll*2+1][l*2+1] = Ke[l*2+1][ll*2+1];
1232:             }
1233:           }
1234: #endif
1235:           MatSetValuesBlockedLocal(B,8,rc3blocked,8,rc3blocked,&Ke[0][0],ADD_VALUES); /* velocity-velocity coupling can use blocked insertion */
1236:           {                     /* The off-diagonal part cannot (yet) */
1237:             PetscInt row3scalar[NODE_SIZE*8],col2scalar[PRMNODE_SIZE*4];
1238:             for (l=0; l<8; l++) for (ll=0; ll<NODE_SIZE; ll++) row3scalar[l*NODE_SIZE+ll] = rc3blocked[l]*NODE_SIZE+ll;
1239:             for (l=0; l<4; l++) for (ll=0; ll<PRMNODE_SIZE; ll++) col2scalar[l*PRMNODE_SIZE+ll] = col2blocked[l]*PRMNODE_SIZE+ll;
1240:             MatSetValuesLocal(Bcpl,8*NODE_SIZE,row3scalar,4*PRMNODE_SIZE,col2scalar,&Kcpl[0][0],ADD_VALUES);
1241:           }
1242:         }
1243:       }
1244:     }
1245:   }
1246:   return(0);
1247: }

1249: static PetscErrorCode THIJacobianLocal_2D(DMDALocalInfo *info,const Node ***x3,const PrmNode **x2,const PrmNode **xdot2,PetscReal a,Mat B22,Mat B21,THI thi)
1250: {
1252:   PetscInt       xs,ys,xm,ym,zm,i,j,k;

1255:   xs = info->zs;
1256:   ys = info->ys;
1257:   xm = info->zm;
1258:   ym = info->ym;
1259:   zm = info->xm;

1261:   if (zm > 1024) SETERRQ(((PetscObject)info->da)->comm,PETSC_ERR_SUP,"Need to allocate more space");
1262:   for (i=xs; i<xs+xm; i++) {
1263:     for (j=ys; j<ys+ym; j++) {
1264:       {                         /* Self-coupling */
1265:         const PetscInt    row[]  = {DMDALocalIndex2D(info,i,j)};
1266:         const PetscInt    col[]  = {DMDALocalIndex2D(info,i,j)};
1267:         const PetscScalar vals[] = {
1268:           a,0,0,
1269:           0,a,0,
1270:           0,0,a
1271:         };
1272:         MatSetValuesBlockedLocal(B22,1,row,1,col,vals,INSERT_VALUES);
1273:       }
1274:       for (k=0; k<zm; k++) {    /* Coupling to velocity problem */
1275:         /* Use a cheaper quadrature than for residual evaluation, because it is much sparser */
1276:         const PetscInt row[]  = {FieldIndex(PrmNode,DMDALocalIndex2D(info,i,j),h)};
1277:         const PetscInt cols[] = {
1278:           FieldIndex(Node,DMDALocalIndex3D(info,i-1,j,k),u),
1279:           FieldIndex(Node,DMDALocalIndex3D(info,i  ,j,k),u),
1280:           FieldIndex(Node,DMDALocalIndex3D(info,i+1,j,k),u),
1281:           FieldIndex(Node,DMDALocalIndex3D(info,i,j-1,k),v),
1282:           FieldIndex(Node,DMDALocalIndex3D(info,i,j  ,k),v),
1283:           FieldIndex(Node,DMDALocalIndex3D(info,i,j+1,k),v)
1284:         };
1285:         const PetscScalar
1286:           w  = (k && k<zm-1) ? 0.5 : 0.25,
1287:           hW = w*(x2[i-1][j  ].h+x2[i  ][j  ].h)/(zm-1.),
1288:           hE = w*(x2[i  ][j  ].h+x2[i+1][j  ].h)/(zm-1.),
1289:           hS = w*(x2[i  ][j-1].h+x2[i  ][j  ].h)/(zm-1.),
1290:           hN = w*(x2[i  ][j  ].h+x2[i  ][j+1].h)/(zm-1.);
1291:         PetscScalar *vals,
1292:                      vals_upwind[] = {((PetscRealPart(x3[i][j][k].u) > 0) ? -hW : 0),
1293:                                       ((PetscRealPart(x3[i][j][k].u) > 0) ? +hE : -hW),
1294:                                       ((PetscRealPart(x3[i][j][k].u) > 0) ?  0  : +hE),
1295:                                       ((PetscRealPart(x3[i][j][k].v) > 0) ? -hS : 0),
1296:                                       ((PetscRealPart(x3[i][j][k].v) > 0) ? +hN : -hS),
1297:                                       ((PetscRealPart(x3[i][j][k].v) > 0) ?  0  : +hN)},
1298:                      vals_centered[] = {-0.5*hW, 0.5*(-hW+hE), 0.5*hE,
1299:                                         -0.5*hS, 0.5*(-hS+hN), 0.5*hN};
1300:         vals = 1 ? vals_upwind : vals_centered;
1301:         if (k == 0) {
1302:           Node derate;
1303:           THIErosion(thi,&x3[i][j][0],NULL,&derate);
1304:           vals[1] -= derate.u;
1305:           vals[4] -= derate.v;
1306:         }
1307:         MatSetValuesLocal(B21,1,row,6,cols,vals,INSERT_VALUES);
1308:       }
1309:     }
1310:   }
1311:   return(0);
1312: }

1314: static PetscErrorCode THIJacobian(TS ts,PetscReal t,Vec X,Vec Xdot,PetscReal a,Mat A,Mat B,void *ctx)
1315: {
1317:   THI            thi = (THI)ctx;
1318:   DM             pack,da3,da2;
1319:   Vec            X3,X2,Xdot2;
1320:   Mat            B11,B12,B21,B22;
1321:   DMDALocalInfo  info3;
1322:   IS             *isloc;
1323:   const Node     ***x3;
1324:   const PrmNode  **x2,**xdot2;

1327:   TSGetDM(ts,&pack);
1328:   DMCompositeGetEntries(pack,&da3,&da2);
1329:   DMDAGetLocalInfo(da3,&info3);
1330:   DMCompositeGetLocalVectors(pack,&X3,&X2);
1331:   DMCompositeGetLocalVectors(pack,NULL,&Xdot2);
1332:   DMCompositeScatter(pack,X,X3,X2);
1333:   THIFixGhosts(thi,da3,da2,X3,X2);
1334:   DMCompositeScatter(pack,Xdot,NULL,Xdot2);

1336:   MatZeroEntries(B);

1338:   DMCompositeGetLocalISs(pack,&isloc);
1339:   MatGetLocalSubMatrix(B,isloc[0],isloc[0],&B11);
1340:   MatGetLocalSubMatrix(B,isloc[0],isloc[1],&B12);
1341:   MatGetLocalSubMatrix(B,isloc[1],isloc[0],&B21);
1342:   MatGetLocalSubMatrix(B,isloc[1],isloc[1],&B22);

1344:   DMDAVecGetArray(da3,X3,&x3);
1345:   DMDAVecGetArray(da2,X2,&x2);
1346:   DMDAVecGetArray(da2,Xdot2,&xdot2);

1348:   THIJacobianLocal_Momentum(&info3,x3,x2,B11,B12,thi);

1350:   /* Need to switch from ADD_VALUES to INSERT_VALUES */
1351:   MatAssemblyBegin(*B,MAT_FLUSH_ASSEMBLY);
1352:   MatAssemblyEnd(*B,MAT_FLUSH_ASSEMBLY);

1354:   THIJacobianLocal_2D(&info3,x3,x2,xdot2,a,B22,B21,thi);

1356:   DMDAVecRestoreArray(da3,X3,&x3);
1357:   DMDAVecRestoreArray(da2,X2,&x2);
1358:   DMDAVecRestoreArray(da2,Xdot2,&xdot2);

1360:   MatRestoreLocalSubMatrix(B,isloc[0],isloc[0],&B11);
1361:   MatRestoreLocalSubMatrix(B,isloc[0],isloc[1],&B12);
1362:   MatRestoreLocalSubMatrix(B,isloc[1],isloc[0],&B21);
1363:   MatRestoreLocalSubMatrix(B,isloc[1],isloc[1],&B22);
1364:   ISDestroy(&isloc[0]);
1365:   ISDestroy(&isloc[1]);
1366:   PetscFree(isloc);

1368:   DMCompositeRestoreLocalVectors(pack,&X3,&X2);
1369:   DMCompositeRestoreLocalVectors(pack,0,&Xdot2);

1371:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1372:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1373:   if (A != B) {
1374:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1375:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1376:   }
1377:   if (thi->verbose) {THIMatrixStatistics(thi,*B,PETSC_VIEWER_STDOUT_WORLD);}
1378:   return(0);
1379: }

1381: /* VTK's XML formats are so brain-dead that they can't handle multiple grids in the same file.  Since the communication
1382:  * can be shared between the two grids, we write two files at once, one for velocity (living on a 3D grid defined by
1383:  * h=thickness and b=bed) and another for all properties living on the 2D grid.
1384:  */
1385: static PetscErrorCode THIDAVecView_VTK_XML(THI thi,DM pack,Vec X,const char filename[],const char filename2[])
1386: {
1387:   const PetscInt dof   = NODE_SIZE,dof2 = PRMNODE_SIZE;
1388:   Units          units = thi->units;
1389:   MPI_Comm       comm;
1391:   PetscViewer    viewer3,viewer2;
1392:   PetscMPIInt    rank,size,tag,nn,nmax,nn2,nmax2;
1393:   PetscInt       mx,my,mz,r,range[6];
1394:   PetscScalar    *x,*x2;
1395:   DM             da3,da2;
1396:   Vec            X3,X2;

1399:   PetscObjectGetComm((PetscObject)thi,&comm);
1400:   DMCompositeGetEntries(pack,&da3,&da2);
1401:   DMCompositeGetAccess(pack,X,&X3,&X2);
1402:   DMDAGetInfo(da3,0, &mz,&my,&mx, 0,0,0, 0,0,0,0,0,0);
1403:   MPI_Comm_size(comm,&size);
1404:   MPI_Comm_rank(comm,&rank);
1405:   PetscViewerASCIIOpen(comm,filename,&viewer3);
1406:   PetscViewerASCIIOpen(comm,filename2,&viewer2);
1407:   PetscViewerASCIIPrintf(viewer3,"<VTKFile type=\"StructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n");
1408:   PetscViewerASCIIPrintf(viewer2,"<VTKFile type=\"StructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n");
1409:   PetscViewerASCIIPrintf(viewer3,"  <StructuredGrid WholeExtent=\"%d %d %d %d %d %d\">\n",0,mz-1,0,my-1,0,mx-1);
1410:   PetscViewerASCIIPrintf(viewer2,"  <StructuredGrid WholeExtent=\"%d %d %d %d %d %d\">\n",0,0,0,my-1,0,mx-1);

1412:   DMDAGetCorners(da3,range,range+1,range+2,range+3,range+4,range+5);
1413:   PetscMPIIntCast(range[3]*range[4]*range[5]*dof,&nn);
1414:   MPI_Reduce(&nn,&nmax,1,MPI_INT,MPI_MAX,0,comm);
1415:   PetscMPIIntCast(range[4]*range[5]*dof2,&nn2);
1416:   MPI_Reduce(&nn2,&nmax2,1,MPI_INT,MPI_MAX,0,comm);
1417:   tag  = ((PetscObject)viewer3)->tag;
1418:   VecGetArray(X3,&x);
1419:   VecGetArray(X2,&x2);
1420:   if (!rank) {
1421:     PetscScalar *array,*array2;
1422:     PetscMalloc2(nmax,&array,nmax2,&array2);
1423:     for (r=0; r<size; r++) {
1424:       PetscInt i,j,k,f,xs,xm,ys,ym,zs,zm;
1425:       Node     *y3;
1426:       PetscScalar (*y2)[PRMNODE_SIZE];
1427:       MPI_Status status;
1428:       if (r) {
1429:         MPI_Recv(range,6,MPIU_INT,r,tag,comm,MPI_STATUS_IGNORE);
1430:       }
1431:       zs = range[0];ys = range[1];xs = range[2];zm = range[3];ym = range[4];xm = range[5];
1432:       if (xm*ym*zm*dof > nmax) SETERRQ(PETSC_COMM_SELF,1,"should not happen");
1433:       if (r) {
1434:         MPI_Recv(array,nmax,MPIU_SCALAR,r,tag,comm,&status);
1435:         MPI_Get_count(&status,MPIU_SCALAR,&nn);
1436:         if (nn != xm*ym*zm*dof) SETERRQ(PETSC_COMM_SELF,1,"corrupt da3 send");
1437:         y3   = (Node*)array;
1438:         MPI_Recv(array2,nmax2,MPIU_SCALAR,r,tag,comm,&status);
1439:         MPI_Get_count(&status,MPIU_SCALAR,&nn2);
1440:         if (nn2 != xm*ym*dof2) SETERRQ(PETSC_COMM_SELF,1,"corrupt da2 send");
1441:         y2 = (PetscScalar(*)[PRMNODE_SIZE])array2;
1442:       } else {
1443:         y3 = (Node*)x;
1444:         y2 = (PetscScalar(*)[PRMNODE_SIZE])x2;
1445:       }
1446:       PetscViewerASCIIPrintf(viewer3,"    <Piece Extent=\"%d %d %d %d %d %d\">\n",zs,zs+zm-1,ys,ys+ym-1,xs,xs+xm-1);
1447:       PetscViewerASCIIPrintf(viewer2,"    <Piece Extent=\"%d %d %d %d %d %d\">\n",0,0,ys,ys+ym-1,xs,xs+xm-1);

1449:       PetscViewerASCIIPrintf(viewer3,"      <Points>\n");
1450:       PetscViewerASCIIPrintf(viewer2,"      <Points>\n");
1451:       PetscViewerASCIIPrintf(viewer3,"        <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n");
1452:       PetscViewerASCIIPrintf(viewer2,"        <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n");
1453:       for (i=xs; i<xs+xm; i++) {
1454:         for (j=ys; j<ys+ym; j++) {
1455:           PetscReal
1456:             xx = thi->Lx*i/mx,
1457:             yy = thi->Ly*j/my,
1458:             b  = PetscRealPart(y2[i*ym+j][FieldOffset(PrmNode,b)]),
1459:             h  = PetscRealPart(y2[i*ym+j][FieldOffset(PrmNode,h)]);
1460:           for (k=zs; k<zs+zm; k++) {
1461:             PetscReal zz = b + h*k/(mz-1.);
1462:             PetscViewerASCIIPrintf(viewer3,"%f %f %f\n",xx,yy,zz);
1463:           }
1464:           PetscViewerASCIIPrintf(viewer2,"%f %f %f\n",xx,yy,(double)0.0);
1465:         }
1466:       }
1467:       PetscViewerASCIIPrintf(viewer3,"        </DataArray>\n");
1468:       PetscViewerASCIIPrintf(viewer2,"        </DataArray>\n");
1469:       PetscViewerASCIIPrintf(viewer3,"      </Points>\n");
1470:       PetscViewerASCIIPrintf(viewer2,"      </Points>\n");

1472:       {                         /* Velocity and rank (3D) */
1473:         PetscViewerASCIIPrintf(viewer3,"      <PointData>\n");
1474:         PetscViewerASCIIPrintf(viewer3,"        <DataArray type=\"Float32\" Name=\"velocity\" NumberOfComponents=\"3\" format=\"ascii\">\n");
1475:         for (i=0; i<nn/dof; i++) {
1476:           PetscViewerASCIIPrintf(viewer3,"%f %f %f\n",PetscRealPart(y3[i].u)*units->year/units->meter,PetscRealPart(y3[i].v)*units->year/units->meter,0.0);
1477:         }
1478:         PetscViewerASCIIPrintf(viewer3,"        </DataArray>\n");

1480:         PetscViewerASCIIPrintf(viewer3,"        <DataArray type=\"Int32\" Name=\"rank\" NumberOfComponents=\"1\" format=\"ascii\">\n");
1481:         for (i=0; i<nn; i+=dof) {
1482:           PetscViewerASCIIPrintf(viewer3,"%d\n",r);
1483:         }
1484:         PetscViewerASCIIPrintf(viewer3,"        </DataArray>\n");
1485:         PetscViewerASCIIPrintf(viewer3,"      </PointData>\n");
1486:       }

1488:       {                         /* 2D */
1489:         PetscViewerASCIIPrintf(viewer2,"      <PointData>\n");
1490:         for (f=0; f<PRMNODE_SIZE; f++) {
1491:           const char *fieldname;
1492:           DMDAGetFieldName(da2,f,&fieldname);
1493:           PetscViewerASCIIPrintf(viewer2,"        <DataArray type=\"Float32\" Name=\"%s\" format=\"ascii\">\n",fieldname);
1494:           for (i=0; i<nn2/PRMNODE_SIZE; i++) {
1495:             PetscViewerASCIIPrintf(viewer2,"%g\n",y2[i][f]);
1496:           }
1497:           PetscViewerASCIIPrintf(viewer2,"        </DataArray>\n");
1498:         }
1499:         PetscViewerASCIIPrintf(viewer2,"      </PointData>\n");
1500:       }

1502:       PetscViewerASCIIPrintf(viewer3,"    </Piece>\n");
1503:       PetscViewerASCIIPrintf(viewer2,"    </Piece>\n");
1504:     }
1505:     PetscFree2(array,array2);
1506:   } else {
1507:     MPI_Send(range,6,MPIU_INT,0,tag,comm);
1508:     MPI_Send(x,nn,MPIU_SCALAR,0,tag,comm);
1509:     MPI_Send(x2,nn2,MPIU_SCALAR,0,tag,comm);
1510:   }
1511:   VecRestoreArray(X3,&x);
1512:   VecRestoreArray(X2,&x2);
1513:   PetscViewerASCIIPrintf(viewer3,"  </StructuredGrid>\n");
1514:   PetscViewerASCIIPrintf(viewer2,"  </StructuredGrid>\n");

1516:   DMCompositeRestoreAccess(pack,X,&X3,&X2);
1517:   PetscViewerASCIIPrintf(viewer3,"</VTKFile>\n");
1518:   PetscViewerASCIIPrintf(viewer2,"</VTKFile>\n");
1519:   PetscViewerDestroy(&viewer3);
1520:   PetscViewerDestroy(&viewer2);
1521:   return(0);
1522: }

1524: static PetscErrorCode THITSMonitor(TS ts,PetscInt step,PetscReal t,Vec X,void *ctx)
1525: {
1527:   THI            thi = (THI)ctx;
1528:   DM             pack;
1529:   char           filename3[PETSC_MAX_PATH_LEN],filename2[PETSC_MAX_PATH_LEN];

1532:   if (step < 0) return(0); /* negative one is used to indicate an interpolated solution */
1533:   PetscPrintf(PetscObjectComm((PetscObject)ts),"%3D: t=%g\n",step,(double)t);
1534:   if (thi->monitor_interval && step % thi->monitor_interval) return(0);
1535:   TSGetDM(ts,&pack);
1536:   PetscSNPrintf(filename3,sizeof(filename3),"%s-3d-%03d.vts",thi->monitor_basename,step);
1537:   PetscSNPrintf(filename2,sizeof(filename2),"%s-2d-%03d.vts",thi->monitor_basename,step);
1538:   THIDAVecView_VTK_XML(thi,pack,X,filename3,filename2);
1539:   return(0);
1540: }


1543: static PetscErrorCode THICreateDM3d(THI thi,DM *dm3d)
1544: {
1545:   MPI_Comm       comm;
1546:   PetscInt       M    = 3,N = 3,P = 2;
1547:   DM             da;

1551:   PetscObjectGetComm((PetscObject)thi,&comm);
1552:   PetscOptionsBegin(comm,NULL,"Grid resolution options","");
1553:   {
1554:     PetscOptionsInt("-M","Number of elements in x-direction on coarse level","",M,&M,NULL);
1555:     N    = M;
1556:     PetscOptionsInt("-N","Number of elements in y-direction on coarse level (if different from M)","",N,&N,NULL);
1557:     PetscOptionsInt("-P","Number of elements in z-direction on coarse level","",P,&P,NULL);
1558:   }
1559:   PetscOptionsEnd();
1560:   DMDACreate3d(comm,DM_BOUNDARY_NONE,DM_BOUNDARY_PERIODIC,DM_BOUNDARY_PERIODIC,DMDA_STENCIL_BOX,P,N,M,1,PETSC_DETERMINE,PETSC_DETERMINE,sizeof(Node)/sizeof(PetscScalar),1,0,0,0,&da);
1561:   DMSetFromOptions(da);
1562:   DMSetUp(da);
1563:   DMDASetFieldName(da,0,"x-velocity");
1564:   DMDASetFieldName(da,1,"y-velocity");
1565:   *dm3d = da;
1566:   return(0);
1567: }

1569: int main(int argc,char *argv[])
1570: {
1571:   MPI_Comm       comm;
1572:   DM             pack,da3,da2;
1573:   TS             ts;
1574:   THI            thi;
1575:   Vec            X;
1576:   Mat            B;
1577:   PetscInt       i,steps;
1578:   PetscReal      ftime;

1581:   PetscInitialize(&argc,&argv,0,help);
1582:   comm = PETSC_COMM_WORLD;

1584:   THICreate(comm,&thi);
1585:   THICreateDM3d(thi,&da3);
1586:   {
1587:     PetscInt        Mx,My,mx,my,s;
1588:     DMDAStencilType st;
1589:     DMDAGetInfo(da3,0, 0,&My,&Mx, 0,&my,&mx, 0,&s,0,0,0,&st);
1590:     DMDACreate2d(PetscObjectComm((PetscObject)thi),DM_BOUNDARY_PERIODIC,DM_BOUNDARY_PERIODIC,st,My,Mx,my,mx,sizeof(PrmNode)/sizeof(PetscScalar),s,0,0,&da2);
1591:     DMSetUp(da2);
1592:   }

1594:   PetscObjectSetName((PetscObject)da3,"3D_Velocity");
1595:   DMSetOptionsPrefix(da3,"f3d_");
1596:   DMDASetFieldName(da3,0,"u");
1597:   DMDASetFieldName(da3,1,"v");
1598:   PetscObjectSetName((PetscObject)da2,"2D_Fields");
1599:   DMSetOptionsPrefix(da2,"f2d_");
1600:   DMDASetFieldName(da2,0,"b");
1601:   DMDASetFieldName(da2,1,"h");
1602:   DMDASetFieldName(da2,2,"beta2");
1603:   DMCompositeCreate(comm,&pack);
1604:   DMCompositeAddDM(pack,da3);
1605:   DMCompositeAddDM(pack,da2);
1606:   DMDestroy(&da3);
1607:   DMDestroy(&da2);
1608:   DMSetUp(pack);
1609:   DMCreateMatrix(pack,&B);
1610:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);
1611:   MatSetOptionsPrefix(B,"thi_");

1613:   for (i=0; i<thi->nlevels; i++) {
1614:     PetscReal Lx = thi->Lx / thi->units->meter,Ly = thi->Ly / thi->units->meter,Lz = thi->Lz / thi->units->meter;
1615:     PetscInt  Mx,My,Mz;
1616:     DMCompositeGetEntries(pack,&da3,&da2);
1617:     DMDAGetInfo(da3,0, &Mz,&My,&Mx, 0,0,0, 0,0,0,0,0,0);
1618:     PetscPrintf(PetscObjectComm((PetscObject)thi),"Level %d domain size (m) %8.2g x %8.2g x %8.2g, num elements %3d x %3d x %3d (%8d), size (m) %g x %g x %g\n",i,Lx,Ly,Lz,Mx,My,Mz,Mx*My*Mz,Lx/Mx,Ly/My,1000./(Mz-1));
1619:   }

1621:   DMCreateGlobalVector(pack,&X);
1622:   THIInitial(thi,pack,X);

1624:   TSCreate(comm,&ts);
1625:   TSSetDM(ts,pack);
1626:   TSSetProblemType(ts,TS_NONLINEAR);
1627:   TSMonitorSet(ts,THITSMonitor,thi,NULL);
1628:   TSSetType(ts,TSTHETA);
1629:   TSSetIFunction(ts,NULL,THIFunction,thi);
1630:   TSSetIJacobian(ts,B,B,THIJacobian,thi);
1631:   TSSetMaxTime(ts,10.0);
1632:   TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER);
1633:   TSSetSolution(ts,X);
1634:   TSSetTimeStep(ts,1e-3);
1635:   TSSetFromOptions(ts);

1637:   TSSolve(ts,X);
1638:   TSGetSolveTime(ts,&ftime);
1639:   TSGetStepNumber(ts,&steps);
1640:   PetscPrintf(PETSC_COMM_WORLD,"Steps %D  final time %g\n",steps,(double)ftime);

1642:   if (0) {THISolveStatistics(thi,ts,0,"Full");}

1644:   {
1645:     PetscBool flg;
1646:     char      filename[PETSC_MAX_PATH_LEN] = "";
1647:     PetscOptionsGetString(NULL,NULL,"-o",filename,sizeof(filename),&flg);
1648:     if (flg) {
1649:       THIDAVecView_VTK_XML(thi,pack,X,filename,NULL);
1650:     }
1651:   }

1653:   VecDestroy(&X);
1654:   MatDestroy(&B);
1655:   DMDestroy(&pack);
1656:   TSDestroy(&ts);
1657:   THIDestroy(&thi);
1658:   PetscFinalize();
1659:   return ierr;
1660: }