File: cahnhill.c

package info (click to toggle)
illuminator 0.8.9-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,076 kB
  • ctags: 352
  • sloc: sh: 8,535; ansic: 4,589; makefile: 241
file content (1659 lines) | stat: -rw-r--r-- 63,108 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
/***************************************
  $Header: /cvsroot/petscgraphics/cahnhill.c,v 1.8 2003/05/21 22:52:29 hazelsct Exp $

  This file contains the heart of the Cahn-Hilliard formulation, in particular
  the functions which build the finite difference residuals and Jacobian.
***************************************/


/* Including cahnhill.h includes the necessary PETSc header files */
#include "cahnhill.h"


/*++++++++++++++++++++++++++++++++++++++
  This calculates the derivative of homogeneous free energy with respect to
  concentration, which is a component of the chemical potential.  It currently
  uses
  +latex+$$\Psi' = C(1-C)\left(\frac{1}{2}+m-C\right)$$
  +html+ <center>Psi' = <i>C</i> (1-<i>C</i>) (0.5+<i>m</i>+<i>C</i>)</center>
  which gives (meta)stable equilibria at
  +latex+$C=0$ and 1 and an unstable equilibrium at $C=\frac{1}{2}+m$; if $m>0$
  +html+ <i>C</i>=0 and 1 and an unstable equilibrium at <i>C</i> = 1/2 +
  +html+ <i>m</i>; if <i>m</i>&gt;0
  then the 0 phase is stable and vice versa.

  PetscScalar ch_psiprime It returns the derivative itself.

  PetscScalar C The concentration.

  PetscScalar mparam The model parameter
  +latex+$m$.
  +html+ <i>m</i>.
  ++++++++++++++++++++++++++++++++++++++*/

static inline PetscScalar ch_psiprime (PetscScalar C, PetscScalar mparam)
{ return C*(1-C)*(0.5+mparam-C); }

#define PSIPRIME_FLOPS 5


/*++++++++++++++++++++++++++++++++++++++
  This calculates the second derivative of homogeneous free energy with respect
  to concentration, for insertion into the Jacobian matrix.  See the
  +latex+{\tt ch\_psiprime()} function for the definition of $\Psi$.
  +html+ <tt>ch_psiprime()</tt> function for the definition of Psi.

  PetscScalar ch_psidoubleprime It returns the second derivative
  +latex+$\Psi''(C)$.
  -latex-Psi''(C).

  PetscScalar C The concentration.

  PetscScalar mparam The model parameter
  +latex+$m$.
  +html+ <i>m</i>.
  ++++++++++++++++++++++++++++++++++++++*/

static inline PetscScalar ch_psidoubleprime (PetscScalar C, PetscScalar mparam)
{ return 3*C*C - (3+2*mparam)*C + 0.5+mparam; }

#define PSIDOUBLEPRIME_FLOPS 8


/*++++++++++++++++++++++++++++++++++++++
  This function computes the residual from indices to points in the
  concentration array.  ``Up'' refers to the positive
  +latex+$y$-direction, ``down'' to negative $y$, ``left'' to negative $x$ and
  +latex+``right'' to positive $x$.
  +html+ <i>y</i>-direction, ``down'' to negative <i>y</i>, ``left'' to
  +html+ negative <i>x</i> and ``right'' to positive <i>x</i>.

  PetscScalar ch_residual_2d Returns the residual itself

  PetscScalar *conc Array of concentrations

  PetscScalar alpha Model parameter
  +latex+$\kappa\alpha$
  -latex-kappa alpha

  PetscScalar beta Model parameter
  +latex+$\kappa\beta$
  -latex-kappa beta

  PetscScalar mparam Model parameter
  +latex+$m$
  -latex-m

  PetscScalar hx Inverse square
  +latex+$x$-spacing $h_x^{-2}$
  +html+ <i>x</i>-spacing <i>h<sub>x</sub></i><sup>-2</sup>

  PetscScalar hy Inverse square
  +latex+$y$-spacing $h_y^{-2}$
  +html+ <i>y</i>-spacing <i>h<sub>y</sub></i><sup>-2</sup>

  int upup Index to array position two cells up from current

  int upleft Index to array position one cell up and one left from current

  int up Index to array position one cell up from current

  int upright Index to array position one cell up and one right from current

  int leftleft Index to array position two cells left of current

  int left Index to array position one cell left of current

  int current Index to current cell array position

  int right Index to array position one cell right of current

  int rightright Index to array position two cells right of current

  int downleft Index to array position one cell down and one left from current

  int down Index to array position one cell down from current

  int downright Index to array position one cell down and one right from current

  int downdown Index to array position two cells down from current
  ++++++++++++++++++++++++++++++++++++++*/

static inline PetscScalar ch_residual_2d
(PetscScalar *conc, PetscScalar alpha, PetscScalar beta, PetscScalar mparam,
 PetscScalar hx, PetscScalar hy, int upup, int upleft, int up, int upright, int
 leftleft, int left, int current, int right, int rightright, int downleft, int
 down, int downright, int downdown)
{
  PetscScalar retval, hx2, hy2, hxhy;

  hx2 = hx*hx;  hy2 = hy*hy;  hxhy = hx*hy;

  /*+ This calculates the
    +latex+$\beta$-term, $\kappa\beta$ times the Laplacian of $\Psi'(C)$,
    -latex-beta term, kappa*beta times the laplacian of Psi prime(C),
    +*/
  retval = beta *
    (hx * (ch_psiprime(conc[left], mparam) + ch_psiprime(conc[right], mparam))
     + hy * (ch_psiprime(conc[up], mparam) + ch_psiprime(conc[down], mparam))
     - 2*(hx+hy) * ch_psiprime(conc[current], mparam));

  /*+ then subtracts the
    +latex+$\alpha$-term, $\kappa\alpha\nabla^2\nabla^2C$.
    -latex-alpha term, kappa*alpha times the Laplacian of the Laplacian of C.
    +*/
  retval -= alpha *
    (hx2 * (conc[leftleft] + conc[rightright])
     + hy2 * (conc[upup] + conc[downdown])
     + 2*hxhy * (conc[upleft]+conc[upright]+conc[downleft]+conc[downright])
     - (4*hx2 + 4*hxhy) * (conc[left] + conc[right])
     - (4*hy2 + 4*hxhy) * (conc[up] + conc[down])
     + (6*hx2 + 6*hy2 + 8*hxhy) * conc[current]);

  return retval;
}

#define RESIDUAL_FLOPS_2D (5*PSIPRIME_FLOPS + 10 + 32)


/*++++++++++++++++++++++++++++++++++++++
  This function computes the residual from indices to points in the
  concentration array.  ``Front refers to the positive
  +latex+$z$-direction, ``back'' to negative $z$, ``up'' to positive
  +latex+$y$, ``down'' to negative $y$, ``left'' to
  +latex+negative $x$ and ``right'' to positive $x$.
  +html+ <i>z</i>-direction, ``back'' to negative <i>z</i>, ``up'' to positive
  +html+ <i>y</i>, ``down'' to negative <i>y</i>, ``left'' to
  +html+ negative <i>x</i> and ``right'' to positive <i>x</i>.

  PetscScalar ch_residual_3d Returns the residual itself

  PetscScalar *conc Array of concentrations

  PetscScalar alpha Model parameter
  +latex+$\kappa\alpha$
  -latex-kappa alpha

  PetscScalar beta Model parameter
  +latex+$\kappa\beta$
  -latex-kappa beta

  PetscScalar mparam Model parameter
  +latex+$m$
  -latex-m

  PetscScalar hx Inverse square
  +latex+$x$-spacing $h_x^{-2}$
  +html+ <i>x</i>-spacing <i>h<sub>x</sub></i><sup>-2</sup>

  PetscScalar hy Inverse square
  +latex+$y$-spacing $h_y^{-2}$
  +html+ <i>y</i>-spacing <i>h<sub>y</sub></i><sup>-2</sup>

  PetscScalar hz Inverse square
  +latex+$z$-spacing $h_z^{-2}$
  +html+ <i>z</i>-spacing <i>h<sub>z</sub></i><sup>-2</sup>

  int frontfront Index to array position two cells in front of current

  int frontup Index to array position one cell front and one up from current

  int frontleft Index to array position one cell front and one left from current

  int front Index to array position one cell in front of current

  int frontright Index to array position one cell front and one right from current

  int frontdown Index to array position one cell front and one down from current

  int upup Index to array position two cells up from current

  int upleft Index to array position one cell up and one left from current

  int up Index to array position one cell up from current

  int upright Index to array position one cell up and one right from current

  int leftleft Index to array position two cells left of current

  int left Index to array position one cell left of current

  int current Index to current cell array position

  int right Index to array position one cell right of current

  int rightright Index to array position two cells right of current

  int downleft Index to array position one cell down and one left from current

  int down Index to array position one cell down from current

  int downright Index to array position one cell down and one right from current

  int downdown Index to array position two cells down from current

  int backup Index to array position one cell back and one up from current

  int backleft Index to array position one cell back and one left from current

  int back Index to array position one cell in back of current

  int backright Index to array position one cell back and one right from current

  int backdown Index to array position one cell back and one down from current

  int backback Index to array position two cells in back of current
  ++++++++++++++++++++++++++++++++++++++*/

static inline PetscScalar ch_residual_3d
(PetscScalar *conc, PetscScalar alpha, PetscScalar beta, PetscScalar mparam,
 PetscScalar hx, PetscScalar hy, PetscScalar hz, int frontfront,
 int frontup, int frontleft, int front, int frontright, int frontdown,
 int upup, int upleft, int up, int upright, int leftleft, int left,
 int current, int right, int rightright, int downleft, int down, int downright,
 int downdown,
 int backup, int backleft, int back, int backright, int backdown,
 int backback)
{
  PetscScalar retval, hx2, hy2, hz2, hxhy, hxhz, hyhz;

  hx2 = hx*hx;  hy2 = hy*hy;  hz2 = hz*hz;
  hxhy = hx*hy; hxhz = hx*hz; hyhz = hy*hz;

  /*+ This calculates the
    +latex+$\beta$-term, $\kappa\beta$ times the Laplacian of $\Psi'(C)$,
    -latex-beta term, kappa*beta times the laplacian of Psi prime(C),
    +*/
  retval = beta *
    (hx * (ch_psiprime(conc[left], mparam) + ch_psiprime(conc[right], mparam))
     + hy * (ch_psiprime(conc[up], mparam) + ch_psiprime(conc[down], mparam))
     + hz * (ch_psiprime(conc[front], mparam)+ ch_psiprime(conc[back], mparam))
     - 2*(hx+hy+hz) * ch_psiprime(conc[current], mparam));

  /*+ then subtracts the
    +latex+$\alpha$-term, $\kappa\alpha\nabla^2\nabla^2C$.
    -latex-alpha term, kappa*alpha times the Laplacian of the Laplacian of C.
    +*/
  retval -= alpha *
    (hx2 * (conc[leftleft] + conc[rightright])
     + hy2 * (conc[upup] + conc[downdown])
     + hz2 * (conc[frontfront] + conc[backback])
     + 2*hxhy * (conc[upleft]+conc[upright]+conc[downleft]+conc[downright])
     + 2*hxhz*(conc[frontleft]+conc[frontright]+conc[backleft]+conc[backright])
     + 2*hyhz * (conc[frontup]+conc[frontdown]+conc[backup]+conc[backdown])
     - (4*hx2 + 4*hxhy + 4*hxhz) * (conc[left] + conc[right])
     - (4*hy2 + 4*hxhy + 4*hyhz) * (conc[up] + conc[down])
     - (4*hz2 + 4*hxhz + 4*hyhz) * (conc[front] + conc[back])
     + (6*hx2 + 6*hy2 + 6*hz2 + 8*hxhy + 8*hxhz + 8*hyhz) * conc[current]);

  return retval;
}

#define RESIDUAL_FLOPS_3D (7*PSIPRIME_FLOPS + 14 + 65)


/*++++++++++++++++++++++++++++++++++++++
  This evaluates the nonlinear finite difference approximation to the residuals
  +latex+$R_i$.
  +html+ <i>R<sub>i</sub></i>.
  Note that it loops on the interior points and the boundary separately, to
  avoid conditional statements within the double loop over the local grid
  indices.

  int ch_residual_vector_2d It returns zero or an error value.

  Vec X The pre-allocated local vector of unknowns.

  Vec F The pre-allocated local vector of residuals, filled by this function.

  void *ptr Data passed in the application context.
  ++++++++++++++++++++++++++++++++++++++*/

int ch_residual_vector_2d (Vec X, Vec F, void *ptr)
{
  AppCtx  *user = (AppCtx*)ptr;
  int     ierr,i,j, mc,chvar, mx,my,xs,ys,xm,ym,gxs,gys,gxm,gym;
  int     xints,xinte,yints,yinte;
  PetscScalar  hx,hy,dhx,dhy,hxm2,hym2;
  PetscScalar  alpha, beta, mparam;
  PetscScalar  *x,*f;
  Vec     localX = user->localX,localF = user->localF; 

  /* Scatter ghost points to local vector, using the 2-step process
        DAGlobalToLocalBegin(), DAGlobalToLocalEnd().
     By placing code between these two statements, computations can be
     done while messages are in transition. */
  ierr = DAGlobalToLocalBegin (user->da, X, INSERT_VALUES, localX);
  CHKERRQ (ierr);

  /* Define mesh intervals ratios for uniform grid.
     [Note: FD formulae below may someday be normalized by multiplying through
     by local volume element to obtain coefficients O(1) in two dimensions.] */

  mc = user->mc;
  chvar = user->chvar;
  mx = user->mx;
  my = user->my;
  mparam = user->mparam;
  alpha = user->kappa * user->gamma * user->epsilon;
  beta = user->kappa * user->gamma / user->epsilon;
  dhx = (PetscScalar)(mx-1);
  dhy = (PetscScalar)(my-1);
  /* These next two lines hard-code the 1x1 square */
  hx = 1./dhx;
  hy = 1./dhy;
  hxm2 = 1./hx/hx;
  hym2 = 1./hy/hy;

  ierr = DAGlobalToLocalEnd (user->da, X, INSERT_VALUES, localX);
  CHKERRQ (ierr);

  /* Get pointers to vector data */
  ierr = VecGetArray (localX, &x); CHKERRQ (ierr);
  ierr = VecGetArray (localF, &f); CHKERRQ (ierr);

  /* Get local grid boundaries */
  ierr = DAGetCorners (user->da, &xs, &ys, PETSC_NULL, &xm, &ym, PETSC_NULL);
  CHKERRQ (ierr);
  ierr = DAGetGhostCorners (user->da, &gxs, &gys, PETSC_NULL, &gxm, &gym,
			    PETSC_NULL); CHKERRQ (ierr);

  /* Determine the interior of the locally owned part of the grid. */
  if (user->period == DA_XPERIODIC || user->period == DA_XYPERIODIC) {
    xints = xs; xinte = xs+xm; }
  else {
    xints = (xs==0) ? 2:xs; xinte = (xs+xm==mx) ? xs+xm-2 : xs+xm; }
  if (user->period == DA_YPERIODIC || user->period == DA_XYPERIODIC) {
    yints = ys; yinte = ys+ym; }
  else {
    yints = (ys==0) ? 2:ys; yinte = (ys+ym==my) ? ys+ym-2 : ys+ym; }

  /* Loop over the interior points */
  for (j=yints-gys; j<yinte-gys; j++)
    for (i=j*gxm + xints-gxs; i<j*gxm + xinte-gxs; i++)
      f[C(i)] = ch_residual_2d
	(x, alpha, beta, mparam, hxm2, hym2,
	 C(i+2*gxm), C(i+gxm-1), C(i+gxm), C(i+gxm+1),
	 C(i-2), C(i-1), C(i), C(i+1), C(i+2),
	 C(i-gxm-1), C(i-gxm), C(i-gxm+1), C(i-2*gxm));

  /* Okay, that was the easy part.  Now for the fun part.
     The following conditionals implement symmetry boundary conditions. */

  /* Test whether we are on the bottom edge of the global array */
  if (yints == 2) /* Not ys==0 because that would be true for periodic too */
    {
      printf ("This must only be reached if we are NOT y-periodic\n");
      /* Bottom two edge lines */
      for (i=xints-gxs; i<xinte-gxs; i++)
	{
	  f[C(i)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+2*gxm), C(i+gxm-1), C(i+gxm), C(i+gxm+1),
	     C(i-2), C(i-1), C(i), C(i+1), C(i+2),
	     C(i+gxm-1), C(i+gxm), C(i+gxm+1), C(i+2*gxm));
	  f[C(i+gxm)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+3*gxm), C(i+2*gxm-1), C(i+2*gxm), C(i+2*gxm+1),
	     C(i+gxm-2), C(i+gxm-1), C(i+gxm), C(i+gxm+1), C(i+gxm+2),
	     C(i-1), C(i), C(i+1), C(i+gxm));
	}

      /* Bottom left corner */
      if (xints == 2)
	{
	  f[C(0)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(2*gxm), C(gxm+1), C(gxm), C(gxm+1),
	     C(2), C(1), C(0), C(1), C(2),
	     C(gxm+1), C(gxm), C(gxm+1), C(2*gxm));
	  f[C(1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(2*gxm+1), C(gxm), C(gxm+1), C(gxm+2),
	     C(1), C(0), C(1), C(2), C(3),
	     C(gxm), C(gxm+1), C(gxm+2), C(2*gxm+1));
	  f[C(gxm)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(3*gxm), C(2*gxm+1), C(2*gxm), C(2*gxm+1),
	     C(gxm+2), C(gxm+1), C(gxm+0), C(gxm+1), C(gxm+2),
	     C(1), C(0), C(1), C(gxm));
	  f[C(gxm+1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(3*gxm+1), C(2*gxm), C(2*gxm+1), C(2*gxm+2),
	     C(gxm+1), C(gxm), C(gxm+1), C(gxm+2), C(gxm+3),
	     C(0), C(1), C(2), C(gxm+1));
	}

      /* Bottom right corner */
      if (xinte == mx-2)
	{
	  i = mx-gxs-1; /* Array index of the bottom right corner point */
	  f[C(i)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+2*gxm), C(i+gxm-1), C(i+gxm), C(i+gxm-1),
	     C(i-2), C(i-1), C(i), C(i-1), C(i-2),
	     C(i+gxm-1), C(i+gxm), C(i+gxm-1), C(i+2*gxm));
	  f[C(i-1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+2*gxm-1), C(i+gxm-2), C(i+gxm-1), C(i+gxm),
	     C(i-3), C(i-2), C(i-1), C(i), C(i-1),
	     C(i+gxm-2), C(i+gxm-1), C(i+gxm), C(i+2*gxm-1));
	  f[C(i+gxm)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+3*gxm), C(i+2*gxm-1), C(i+2*gxm), C(i+2*gxm-1),
	     C(i+gxm-2), C(i+gxm-1), C(i+gxm), C(i+gxm-1), C(i+gxm-2),
	     C(i-1), C(i), C(i-1), C(i+gxm));
	  f[C(i+gxm-1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+3*gxm-1), C(i+2*gxm-2), C(i+2*gxm-1), C(i+2*gxm),
	     C(i+gxm-3), C(i+gxm-2), C(i+gxm-1), C(i+gxm), C(i+gxm-1),
	     C(i-2), C(i-1), C(i), C(i+gxm-1));
	}
    }

  /* Test whether we are on the top edge of the global array */
  if (yinte == my-2)
    {
      printf ("This must only be reached if we are NOT y-periodic\n");
      /* Top two edge lines */
      for (i=(my-gys-1)*gxm + xints-gxs; i<(my-gys-1)*gxm + xinte-gxs; i++)
	{
	  f[C(i)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-2*gxm), C(i-gxm-1), C(i-gxm), C(i-gxm+1),
	     C(i-2), C(i-1), C(i), C(i+1), C(i+2),
	     C(i-gxm-1), C(i-gxm), C(i-gxm+1), C(i-2*gxm));
	  f[C(i-gxm)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-gxm), C(i-1), C(i), C(i+1),
	     C(i-gxm-2), C(i-gxm-1), C(i-gxm), C(i-gxm+1), C(i-gxm+2),
	     C(i-2*gxm-1), C(i-2*gxm), C(i-2*gxm+1), C(i-3*gxm));
	}

      /* Top left corner */
      if (xints == 2)
	{
	  i = (my-gys-1)*gxm; /* Array index of the top left corner point */
	  f[C(i)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-2*gxm), C(i-gxm+1), C(i-gxm), C(i-gxm+1),
	     C(i+2), C(i+1), C(i), C(i+1), C(i+2),
	     C(i-gxm+1), C(i-gxm), C(i-gxm+1), C(i-2*gxm));
	  f[C(i+1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-2*gxm+1), C(i-gxm), C(i-gxm+1), C(i-gxm+2),
	     C(i+1), C(i), C(i+1), C(i+2), C(i+3),
	     C(i-gxm), C(i-gxm+1), C(i-gxm+2), C(i-2*gxm+1));
	  f[C(i-gxm)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-gxm), C(i+1), C(i), C(i+1),
	     C(i-gxm+2), C(i-gxm+1), C(i-gxm), C(i-gxm+1), C(i-gxm+2),
	     C(i-2*gxm+1), C(i-2*gxm), C(i-2*gxm+1), C(i-3*gxm));
	  f[C(i-gxm+1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-gxm+1), C(i), C(i+1), C(i+2),
	     C(i-gxm+1), C(i-gxm), C(i-gxm+1), C(i-gxm+2), C(i-gxm+3),
	     C(i-2*gxm), C(i-2*gxm+1), C(i-2*gxm+2), C(i-3*gxm+1));
	}

      /* Top right corner */
      if (xinte == mx-2)
	{ /* Array index of top right corner point */
	  i = (my-gys-1)*gxm + mx-gxs-1;
	  f[C(i)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-2*gxm), C(i-gxm-1), C(i-gxm), C(i-gxm-1),
	     C(i-2), C(i-1), C(i), C(i-1), C(i-2),
	     C(i-gxm-1), C(i-gxm), C(i-gxm-1), C(i-2*gxm));
	  f[C(i-1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-2*gxm-1), C(i-gxm-2), C(i-gxm-1), C(i-gxm),
	     C(i-3), C(i-2), C(i-1), C(i), C(i-1),
	     C(i-gxm-2), C(i-gxm-1), C(i-gxm), C(i-2*gxm-1));
	  f[C(i-gxm)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-gxm), C(i-1), C(i), C(i-1),
	     C(i-gxm-2), C(i-gxm-1), C(i-gxm), C(i-gxm-1), C(i-gxm-2),
	     C(i-2*gxm-1), C(i-2*gxm), C(i-2*gxm-1), C(i-3*gxm));
	  f[C(i-gxm-1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i-gxm-1), C(i-2), C(i-1), C(i),
	     C(i-gxm-3), C(i-gxm-2), C(i-gxm-1), C(i-gxm), C(i-gxm-1),
	     C(i-2*gxm-2), C(i-2*gxm-1), C(i-2*gxm), C(i-3*gxm-1));
	}
    }

  /* Test whether we are on the left edge of the global array */
  if (xints == 2)
    {
      printf ("This must only be reached if we are NOT x-periodic\n");
      /* Left 2 edge lines */
      for (j=yints-gys; j<yinte-gys; j++)
	{
	  i = j*gxm;
	  f[C(i)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+2*gxm), C(i+gxm+1), C(i+gxm), C(i+gxm+1),
	     C(i+2), C(i+1), C(i), C(i+1), C(i+2),
	     C(i-gxm+1), C(i-gxm), C(i-gxm+1), C(i-2*gxm));
	  f[C(i+1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+2*gxm+1), C(i+gxm), C(i+gxm+1), C(i+gxm+2),
	     C(i+1), C(i), C(i+1), C(i+2), C(i+3),
	     C(i-gxm), C(i-gxm+1), C(i-gxm+2), C(i-2*gxm+1));
	}
    }

  /* Test whether we are on the right edge of the global array */
  if (xinte == mx-2)
    {
      printf ("This must only be reached if we are NOT x-periodic\n");
      /* Right 2 edge lines */ 
      for (j=yints-gys; j<yinte-gys; j++)
	{
	  i = j*gxm + mx-gxs-1;
	  f[C(i)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+2*gxm), C(i+gxm-1), C(i+gxm), C(i+gxm-1),
	     C(i-2), C(i-1), C(i), C(i-1), C(i-2),
	     C(i-gxm-1), C(i-gxm), C(i-gxm-1), C(i-2*gxm));
	  f[C(i-1)] = ch_residual_2d
	    (x, alpha, beta, mparam, hxm2, hym2,
	     C(i+2*gxm-1), C(i+gxm-2), C(i+gxm-1), C(i+gxm),
	     C(i-3), C(i-2), C(i-1), C(i), C(i-1),
	     C(i-gxm-2), C(i-gxm-1), C(i-gxm), C(i-2*gxm-1));
	}
    }

  /* Restore vectors */
  ierr = VecRestoreArray (localX, &x); CHKERRQ (ierr);
  ierr = VecRestoreArray (localF, &f); CHKERRQ (ierr);

  /* Insert values into global vector */
  ierr = DALocalToGlobal(user->da,localF,INSERT_VALUES,F); CHKERRQ (ierr);

  /* Flop count (multiply-adds are counted as 2 operations) */
  ierr = PetscLogFlops(RESIDUAL_FLOPS_2D*ym*xm); CHKERRQ (ierr);

  return 0; 
}


/*++++++++++++++++++++++++++++++++++++++
  This evaluates the nonlinear finite difference approximation to the residuals
  +latex+$R_i$.
  +html+ <i>R<sub>i</sub></i>.
  Note that it loops on the interior points and the boundary separately, to
  avoid conditional statements within the double loop over the local grid
  indices.
  +latex+\par
  +html+ <p>
  Thus far, only periodic boundary conditions work.

  int ch_residual_vector_3d It returns zero or an error value.

  Vec X The pre-allocated local vector of unknowns.

  Vec F The pre-allocated local vector of residuals, filled by this function.

  void *ptr Data passed in the application context.
  ++++++++++++++++++++++++++++++++++++++*/

int ch_residual_vector_3d (Vec X, Vec F, void *ptr)
{
  AppCtx  *user = (AppCtx*)ptr;
  int     ierr,i,j,k, mc,chvar, mx,my,mz,xs,ys,zs,xm,ym,zm;
  int     gxs,gys,gzs,gxm,gym,gzm, xints,xinte,yints,yinte,zints,zinte;
  PetscScalar  hx,hy,hz,dhx,dhy,dhz,hxm2,hym2,hzm2;
  PetscScalar  alpha, beta, mparam;
  PetscScalar  *x,*f;
  Vec     localX = user->localX,localF = user->localF; 

  /* Scatter ghost points to local vector, using the 2-step process
        DAGlobalToLocalBegin(), DAGlobalToLocalEnd().
     By placing code between these two statements, computations can be
     done while messages are in transition. */
  ierr = DAGlobalToLocalBegin (user->da, X, INSERT_VALUES, localX);
  CHKERRQ (ierr);

  /* Define mesh intervals ratios for uniform grid.
     [Note: FD formulae below may someday be normalized by multiplying through
     by local volume element to obtain coefficients O(1) in two dimensions.] */

  mc = user->mc;
  chvar = user->chvar;
  mx = user->mx; my = user->my; mz = user->mz;
  mparam = user->mparam;
  alpha = user->kappa * user->gamma * user->epsilon;
  beta = user->kappa * user->gamma / user->epsilon;
  dhx = (PetscScalar)(mx-1); dhy = (PetscScalar)(my-1);
  dhz = (PetscScalar)(mz-1);
  /* This next line hard-codes the 1x1x1 cube */
  hx = 1./dhx;     hy = 1./dhy;     hz = 1./dhz;
  hxm2 = 1./hx/hx; hym2 = 1./hy/hy; hzm2 = 1./hz/hz;

  ierr = DAGlobalToLocalEnd (user->da, X, INSERT_VALUES, localX);
  CHKERRQ (ierr);

  /* Get pointers to vector data */
  ierr = VecGetArray (localX, &x); CHKERRQ (ierr);
  ierr = VecGetArray (localF, &f); CHKERRQ (ierr);

  /* Get local grid boundaries */
  ierr = DAGetCorners (user->da, &xs, &ys, &zs, &xm, &ym, &zm); CHKERRQ (ierr);
  ierr = DAGetGhostCorners (user->da, &gxs, &gys, &gzs, &gxm, &gym, &gzm);
  CHKERRQ (ierr);

  /* Determine the interior of the locally owned part of the grid. */
  if (user->period == DA_XYZPERIODIC) {
    xints = xs; xinte = xs+xm;
    yints = ys; yinte = ys+ym;
    zints = zs; zinte = zs+zm; }
  else {
    SETERRQ(PETSC_ERR_ARG_WRONGSTATE,
	    "Only periodic boundary conditions in 3-D Cahn-Hilliard"); }

  /* Loop over the interior points (no boundaries yet) */
  for (k=zints-gzs; k<zinte-gzs; k++)
    for (j=k*gym + yints-gys; j<k*gym + yinte-gys; j++)
      for (i=j*gxm + xints-gxs; i<j*gxm + xinte-gxs; i++)
	f[C(i)] = ch_residual_3d
	  (x, alpha, beta, mparam, hxm2, hym2, hzm2,
	   C(i+2*gxm*gym), C(i+gxm*gym+gxm), C(i+gxm*gym-1), C(i+gxm*gym),
	   C(i+gxm*gym+1), C(i+gxm*gym-gxm),
	   C(i+2*gxm), C(i+gxm-1), C(i+gxm), C(i+gxm+1),
	   C(i-2), C(i-1), C(i), C(i+1), C(i+2),
	   C(i-gxm-1), C(i-gxm), C(i-gxm+1), C(i-2*gxm),
	   C(i-gxm*gym+gxm), C(i-gxm*gym-1), C(i-gxm*gym), C(i-gxm*gym+1),
	   C(i-gxm*gym-gxm), C(i-2*gxm*gym));

  /* Restore vectors */
  ierr = VecRestoreArray (localX, &x); CHKERRQ (ierr);
  ierr = VecRestoreArray (localF, &f); CHKERRQ (ierr);

  /* Insert values into global vector */
  ierr = DALocalToGlobal(user->da,localF,INSERT_VALUES,F); CHKERRQ (ierr);

  /* Flop count (multiply-adds are counted as 2 operations) */
  ierr = PetscLogFlops(RESIDUAL_FLOPS_3D*ym*xm*zm); CHKERRQ (ierr);

  /* ierr = VecView (F, VIEWER_STDOUT_SELF); CHKERRQ (ierr); */

  return 0;
}


/*++++++++++++++++++++++++++++++++++++++
  This computes the Jacobian matrix at each iteration, starting with the alpha
  term which is pre-computed at the beginning by
  +latex+{\tt ch\_jacobian\_alpha\_2d()}.
  +html+ <tt>ch_jacobian_alpha_2d()</tt>.

  int ch_jacobian_2d It returns 0 or an error code.

  Vec X The vector of unknowns.

  Mat *A The Jacobian matrix returned to PETSc.

  Mat *B The matrix preconditioner, in this case the same matrix.

  MatStructure *flag Flag saying the nonzeroes are the same each time.

  void *ptr Application context structure.
  ++++++++++++++++++++++++++++++++++++++*/

int ch_jacobian_2d (Vec X, Mat *A, Mat *B, MatStructure *flag, void *ptr)
{
  AppCtx  *user = (AppCtx*)ptr;
  int     ierr,node,i,j, mc,chvar, mx,my,xs,ys,xm,ym,gxs,gys,gxm,gym;
  int     xints,xinte,yints,yinte;
  int     columns [5];
  PetscScalar  hx,hy,dhx,dhy,hxm2,hym2;
  PetscScalar  alpha,beta,mparam;
  PetscScalar  *x, bvalue[5];
  Vec     localX = user->localX;

  /* Set the MatStructure flag right, Mats to return */
  *flag = SAME_NONZERO_PATTERN;
  A = &(user->J);
  B = &(user->J);

  /* Copy the alpha term Jacobian into the main Jacobian space */
  ierr = MatCopy (user->alpha, user->J, SAME_NONZERO_PATTERN);

  /* Scatter ghost points to local vector, using 2-step async I/O with (a
     couple of trivial) computations in between. */

  ierr = DAGlobalToLocalBegin(user->da,X,INSERT_VALUES,localX); CHKERRQ (ierr);
  mc = user->mc;  chvar = user->chvar;
  mx = user->mx;  my = user->my;  mparam = user->mparam;
  alpha = user->kappa * user->gamma * user->epsilon;
  beta = user->kappa * user->gamma / user->epsilon;

  /* Define mesh intervals ratios for uniform grid.
     [Note: FD formulae below may someday be normalized by multiplying through
     by local volume element to obtain coefficients O(1) in two dimensions.] */
  dhx = (PetscScalar)(mx-1);  dhy = (PetscScalar)(my-1);
  hx = 1./dhx;           hy = 1./dhy; /* This line hard-codes the 1x1 square */
  hxm2 = 1./hx/hx;       hym2 = 1./hy/hy;

  ierr = DAGlobalToLocalEnd(user->da,X,INSERT_VALUES,localX); CHKERRQ (ierr);

  /* Get pointer to vector data */
  ierr = VecGetArray(localX,&x); CHKERRQ (ierr);

  /*
     Get local grid boundaries
  */
  ierr = DAGetCorners(user->da,&xs,&ys,PETSC_NULL,&xm,&ym,PETSC_NULL); CHKERRQ (ierr);
  ierr = DAGetGhostCorners(user->da,&gxs,&gys,PETSC_NULL,&gxm,&gym,PETSC_NULL); CHKERRQ (ierr);

  /* Determine the interior of the locally owned part of the grid. */
  if (user->period == DA_XPERIODIC || user->period == DA_XYPERIODIC) {
    xints = xs; xinte = xs+xm; }
  else {
    xints = (xs==0) ? 1:xs; xinte = (xs+xm==mx) ? xs+xm-1 : xs+xm; }
  if (user->period == DA_YPERIODIC || user->period == DA_XYPERIODIC) {
    yints = ys; yinte = ys+ym; }
  else {
    yints = (ys==0) ? 1:ys; yinte = (ys+ym==my) ? ys+ym-1 : ys+ym; }

  /* Loop over the interior points... */
  for (j=yints-gys; j<yinte-gys; j++)
    for (i=j*gxm + xints-gxs; i<j*gxm + xinte-gxs; i++) {

      /* Form the column indices */
      columns[0]=C(i+gxm);
      columns[1]=C(i-1); columns[2]=C(i); columns[3]=C(i+1);
      columns[4]=C(i-gxm);

      bvalue[0] = beta * hym2 * ch_psidoubleprime (x[columns[0]], mparam);
      bvalue[1] = beta * hxm2 * ch_psidoubleprime (x[columns[1]], mparam);
      bvalue[2] = -2.*beta * (hxm2+hym2) *
	ch_psidoubleprime (x[columns[2]], mparam);
      bvalue[3] = beta * hxm2 * ch_psidoubleprime (x[columns[3]], mparam);
      bvalue[4] = beta * hym2 * ch_psidoubleprime (x[columns[4]], mparam);

      node = C(i);
      MatSetValuesLocal (user->J, 1,&node, 5,columns, bvalue, ADD_VALUES);
    }

  /* Now the boundary conditions... */

  /* Test whether we're on the bottom row and non-y-periodic */
  if (yints == 1) {
    printf ("This must only be reached if we are NOT y-periodic\n");
    for (i=xints-gxs; i<xinte-gxs; i++) {

      /* Form the column indices */
      columns[0]=C(i+gxm);
      columns[1]=C(i-1); columns[2]=C(i); columns[3]=C(i+1);

      bvalue[0] = 2.*beta * hym2 * ch_psidoubleprime (x[columns[0]], mparam);
      bvalue[1] = beta * hxm2 * ch_psidoubleprime (x[columns[1]], mparam);
      bvalue[2] = -2.*beta * (hxm2+hym2) *
	ch_psidoubleprime (x[columns[2]], mparam);
      bvalue[3] = beta * hxm2 * ch_psidoubleprime (x[columns[3]], mparam);

      node = C(i);
      MatSetValuesLocal (user->J, 1,&node, 4,columns, bvalue, ADD_VALUES);
    }

    /* Bottom left corner */
    if (xints == 1) {
      columns[0]=C(i=0); columns[1]=C(i+1);
      columns[2]=C(i+gxm);

      bvalue[0] = -2.*beta * (hxm2+hym2) *
	ch_psidoubleprime (x[columns[0]], mparam);
      bvalue[1] = 2.*beta * hxm2 * ch_psidoubleprime (x[columns[1]], mparam);
      bvalue[2] = 2.*beta * hym2 * ch_psidoubleprime (x[columns[2]], mparam);

      node = C(i);
      MatSetValuesLocal (user->J, 1,&node, 3,columns, bvalue, ADD_VALUES);
    }

    /* Bottom right corner */
    if (xinte == mx-1) {
      columns[0]=C(i=mx-gxs-1); columns[1]=C(i-1);
      columns[2]=C(i+gxm);

      bvalue[0] = -2.*beta * (hxm2+hym2) *
	ch_psidoubleprime (x[columns[0]], mparam);
      bvalue[1] = 2.*beta * hxm2 * ch_psidoubleprime (x[columns[1]], mparam);
      bvalue[2] = 2.*beta * hym2 * ch_psidoubleprime (x[columns[2]], mparam);

      node = C(i);
      MatSetValuesLocal (user->J, 1,&node, 3,columns, bvalue, ADD_VALUES);
    }
  }

  /* Test whether we're on the top row and non-y-periodic */
  if (yinte == my-1) {
    printf ("This must only be reached if we are NOT y-periodic\n");
    for (i=(my-gys-1)*gxm + xints-gxs; i<(my-gys-1)*gxm + xinte-gxs; i++) {

      /* Form the column indices */
      columns[0]=C(i-1); columns[1]=C(i); columns[2]=C(i+1);
      columns[3]=C(i-gxm);

      bvalue[0] = beta * hxm2 * ch_psidoubleprime (x[columns[0]], mparam);
      bvalue[1] = -2.*beta * (hxm2+hym2) *
	ch_psidoubleprime (x[columns[1]], mparam);
      bvalue[2] = beta * hxm2 * ch_psidoubleprime (x[columns[2]], mparam);
      bvalue[3] = 2.*beta * hym2 * ch_psidoubleprime (x[columns[3]], mparam);

      node = C(i);
      MatSetValuesLocal (user->J, 1,&node, 4,columns, bvalue, ADD_VALUES);
    }

    /* Top left corner */
    if (xints == 1) {
      columns[0]=C(i=(my-gys-1)*gxm); columns[1] = C(i+1);
      columns[2]=C(i-gxm);

      bvalue[0] = -2.*beta * (hxm2+hym2) *
	ch_psidoubleprime (x[columns[0]], mparam);
      bvalue[1] = 2.*beta * hxm2 * ch_psidoubleprime (x[columns[1]], mparam);
      bvalue[2] = 2.*beta * hym2 * ch_psidoubleprime (x[columns[2]], mparam);

      node = C(i);
      MatSetValuesLocal (user->J, 1,&node, 3,columns, bvalue, ADD_VALUES);
    }

    /* Top right corner */
    if (xinte == mx-1) {
      columns[0]=C(i=(my-gys-1)*gxm + mx-gxs-1); columns[1]=C(i-1);
      columns[2]=C(i-gxm);

      bvalue[0] = -2.*beta * (hxm2+hym2) *
	ch_psidoubleprime (x[columns[0]], mparam);
      bvalue[1] = 2.*beta * hxm2 * ch_psidoubleprime (x[columns[1]], mparam);
      bvalue[2] = 2.*beta * hym2 * ch_psidoubleprime (x[columns[2]], mparam);

      node = C(i);
      MatSetValuesLocal (user->J, 1,&node, 3,columns, bvalue, ADD_VALUES);
    }
  }

  /* Left column */
  if (xints == 1) {
    printf ("This must only be reached if we are NOT x-periodic\n");
    for (i=(yints-gys)*gxm; i<(yinte-gys)*gxm; i+=gxm) {
      columns[0]=C(i+gxm);
      columns[1]=C(i); columns[2] = C(i+1);
      columns[3]=C(i-gxm);

      bvalue[0] = beta * hym2 * ch_psidoubleprime (x[columns[0]], mparam);
      bvalue[1] = -2.*beta * (hxm2+hym2) *
	ch_psidoubleprime (x[columns[1]], mparam);
      bvalue[2] = 2.*beta * hxm2 * ch_psidoubleprime (x[columns[2]], mparam);
      bvalue[3] = beta * hym2 * ch_psidoubleprime (x[columns[3]], mparam);

      node = C(i);
      MatSetValuesLocal (user->J, 1,&node, 4,columns, bvalue, ADD_VALUES);
    }
  }

  /* Right column */
  if (xinte == mx-1) {
    printf ("This must only be reached if we are NOT x-periodic\n");
    for (i=(yints-gys)*gxm + mx-gxs-1; i<(yinte-gys)*gxm + mx-gxs-1; i+=gxm) {
      columns[0]=C(i+gxm);
      columns[1]=C(i-1); columns[2] = C(i);
      columns[3]=C(i-gxm);

      bvalue[0] = beta * hym2 * ch_psidoubleprime (x[columns[0]], mparam);
      bvalue[1] = 2.*beta * hxm2 * ch_psidoubleprime (x[columns[1]], mparam);
      bvalue[2] = -2.*beta * (hxm2+hym2) *
	ch_psidoubleprime (x[columns[2]], mparam);
      bvalue[3] = beta * hym2 * ch_psidoubleprime (x[columns[3]], mparam);

      node = C(i);
      MatSetValuesLocal (user->J, 1,&node, 4,columns, bvalue, ADD_VALUES);
    }
  }

  /* Assemble matrix, using the 2-step process:
     MatAssemblyBegin(), MatAssemblyEnd(). */
  ierr = MatAssemblyBegin(user->J,MAT_FINAL_ASSEMBLY); CHKERRQ (ierr);
  ierr = MatAssemblyEnd(user->J,MAT_FINAL_ASSEMBLY); CHKERRQ (ierr);

  /* Restore unknown vector */
  ierr = VecRestoreArray(localX,&x); CHKERRQ (ierr);

  return ierr;
}


/*++++++++++++++++++++++++++++++++++++++
  This computes the Jacobian matrix at each iteration, starting with the alpha
  term which is pre-computed at the beginning by
  +latex+{\tt ch\_jacobian\_alpha\_3d()}.
  +html+ <tt>ch_jacobian_alpha_3d()</tt>.

  int ch_jacobian_3d It returns 0 or an error code.

  Vec X The vector of unknowns.

  Mat *A The Jacobian matrix returned to PETSc.

  Mat *B The matrix preconditioner, in this case the same matrix.

  MatStructure *flag Flag saying the nonzeroes are the same each time.

  void *ptr Application context structure.
  ++++++++++++++++++++++++++++++++++++++*/

int ch_jacobian_3d (Vec X, Mat *A, Mat *B, MatStructure *flag, void *ptr)
{
  AppCtx  *user = (AppCtx*)ptr;
  int     ierr,node,i,j,k, mc,chvar, mx,my,mz, xs,ys,zs, xm,ym,zm;
  int     gxs,gys,gzs, gxm,gym,gzm, xints,xinte, yints,yinte, zints,zinte;
  int     columns [7];
  PetscScalar  hx,hy,hz, dhx,dhy,dhz, hxm2,hym2,hzm2;
  PetscScalar  alpha,beta,mparam;
  PetscScalar  *x, bvalue[7];
  Vec     localX = user->localX;

  /* Set the MatStructure flag right, Mats to return */
  *flag = SAME_NONZERO_PATTERN;
  A = &(user->J);
  B = &(user->J);

  /* Copy the alpha term Jacobian into the main Jacobian space */
  ierr = MatCopy (user->alpha, user->J, SAME_NONZERO_PATTERN);

  /* Scatter ghost points to local vector, using 2-step async I/O with (a
     couple of trivial) computations in between. */

  ierr = DAGlobalToLocalBegin(user->da,X,INSERT_VALUES,localX); CHKERRQ (ierr);
  mc = user->mc;  chvar = user->chvar;
  mx = user->mx;  my = user->my;  mz = user->mz;  mparam = user->mparam;
  alpha = user->kappa * user->gamma * user->epsilon;
  beta = user->kappa * user->gamma / user->epsilon;

  /* Define mesh intervals ratios for uniform grid.
     [Note: FD formulae below may someday be normalized by multiplying through
     by local volume element to obtain coefficients O(1) in two dimensions.] */
  dhx = (PetscScalar)(mx-1);  dhy = (PetscScalar)(my-1);
  dhz = (PetscScalar)(mz-1);
  /* This line hard-codes the 1x1x1 cube */
  hx = 1./dhx;           hy = 1./dhy;          hz = 1./dhz;
  hxm2 = 1./hx/hx;       hym2 = 1./hy/hy;      hzm2 = 1./hz/hz;

  ierr = DAGlobalToLocalEnd(user->da,X,INSERT_VALUES,localX); CHKERRQ (ierr);

  /* Get pointer to vector data */
  ierr = VecGetArray(localX,&x); CHKERRQ (ierr);

  /* Get local grid boundaries */
  ierr = DAGetCorners(user->da,&xs,&ys,&zs,&xm,&ym,&zm); CHKERRQ (ierr);
  ierr = DAGetGhostCorners(user->da,&gxs,&gys,&gzs,&gxm,&gym,&gzm);
  CHKERRQ (ierr);

  /* Determine the interior of the locally owned part of the grid. */
  if (user->period == DA_XYZPERIODIC) {
    xints = xs; xinte = xs+xm;
    yints = ys; yinte = ys+ym;
    zints = zs; zinte = zs+zm; }
  else {
    SETERRQ(PETSC_ERR_ARG_WRONGSTATE,
	    "Only periodic boundary conditions in 3-D Cahn-Hilliard"); }

  /* Loop over the interior points... */
  for (k=zints-gzs; k<zinte-gzs; k++)
    for (j=k*gym + yints-gys; j<k*gym + yinte-gys; j++)
      for (i=j*gxm + xints-gxs; i<j*gxm + xinte-gxs; i++) {

	/* Form the column indices */
	columns[0]=C(i+gxm*gym); columns[1]=C(i+gxm);
	columns[2]=C(i-1); columns[3]=C(i); columns[4]=C(i+1);
	columns[5]=C(i-gxm); columns[6]=C(i-gxm*gym);

	bvalue[0] = beta * hzm2 * ch_psidoubleprime (x[columns[0]], mparam);
	bvalue[1] = beta * hym2 * ch_psidoubleprime (x[columns[1]], mparam);
	bvalue[2] = beta * hxm2 * ch_psidoubleprime (x[columns[2]], mparam);
	bvalue[3] = -2.*beta * (hxm2+hym2+hzm2) *
	  ch_psidoubleprime (x[columns[3]], mparam);
	bvalue[4] = beta * hxm2 * ch_psidoubleprime (x[columns[4]], mparam);
	bvalue[5] = beta * hym2 * ch_psidoubleprime (x[columns[5]], mparam);
	bvalue[6] = beta * hzm2 * ch_psidoubleprime (x[columns[6]], mparam);

	node = C(i);
	MatSetValuesLocal (user->J, 1,&node, 5,columns, bvalue, ADD_VALUES);
      }

  /* Assemble matrix, using the 2-step process:
     MatAssemblyBegin(), MatAssemblyEnd(). */
  ierr = MatAssemblyBegin (user->J,MAT_FINAL_ASSEMBLY); CHKERRQ (ierr);
  ierr = MatAssemblyEnd (user->J,MAT_FINAL_ASSEMBLY); CHKERRQ (ierr);

  /* Restore unknown vector */
  ierr = VecRestoreArray (localX,&x); CHKERRQ (ierr);

  /* ierr = MatView (user->J, VIEWER_STDOUT_SELF); CHKERRQ (ierr); */

  return ierr;
}


/*++++++++++++++++++++++++++++++++++++++
  This creates the initial alpha and J matrices, where alpha is the alpha term
  component of the Jacobian.  Since the alpha term is linear, this part of the
  Jacobian need only be calculated once.

  int ch_jacobian_alpha_2d It returns zero or an error message.

  AppCtx *user The application context structure pointer.
  ++++++++++++++++++++++++++++++++++++++*/

int ch_jacobian_alpha_2d (AppCtx *user)
{
  int     ierr,node,i,j, mc,chvar, mx,my,xs,ys,xm,ym,gxs,gys,gxm,gym;
  int     xints,xinte,yints,yinte;
  int     columns [13];
  PetscScalar  hx,hy,dhx,dhy,hxm2,hym2;
  PetscScalar  alpha,beta,mparam;
  PetscScalar  avalue [25];

  mc = user->mc;  chvar = user->chvar;
  mx = user->mx;  my = user->my;  mparam = user->mparam;
  alpha = user->kappa * user->gamma * user->epsilon;
  beta = user->kappa * user->gamma / user->epsilon;

  /* Define mesh intervals ratios for uniform grid.
     [Note: FD formulae below may someday be normalized by multiplying through
     by local volume element to obtain coefficients O(1) in two dimensions.] */
  dhx = (PetscScalar)(mx-1);  dhy = (PetscScalar)(my-1);
  hx = 1./dhx;           hy = 1./dhy; /* This line hard-codes the 1x1 square */
  hxm2 = 1./hx/hx;       hym2 = 1./hy/hy;

  /* Get local grid boundaries */
  ierr = DAGetCorners(user->da,&xs,&ys,PETSC_NULL,&xm,&ym,PETSC_NULL);
  CHKERRQ (ierr);
  ierr = DAGetGhostCorners(user->da,&gxs,&gys,PETSC_NULL,&gxm,&gym,PETSC_NULL);
  CHKERRQ (ierr);

  /* Determine the interior of the locally owned part of the grid. */
  if (user->period == DA_XPERIODIC || user->period == DA_XYPERIODIC) {
    xints = xs; xinte = xs+xm; }
  else {
    xints = (xs==0) ? 2:xs; xinte = (xs+xm==mx) ? xs+xm-2 : xs+xm; }
  if (user->period == DA_YPERIODIC || user->period == DA_XYPERIODIC) {
    yints = ys; yinte = ys+ym; }
  else {
    yints = (ys==0) ? 2:ys; yinte = (ys+ym==my) ? ys+ym-2 : ys+ym; }

  /* Get parameters for matrix creation */
  i = xm * ym * user->mc;
  j = mx * my * user->mc;

  /* Create the distributed alpha matrix */
  ierr = MatCreateMPIAIJ (user->comm, i,i, j,j, 13,PETSC_NULL, 6,PETSC_NULL,
			  &(user->alpha));
  CHKERRQ (ierr);

  /* Get the local-to-global mapping and associate it with the matrix */
  ierr = DAGetISLocalToGlobalMapping (user->da, &user->isltog); CHKERRQ (ierr);
  ierr = MatSetLocalToGlobalMapping (user->alpha, user->isltog); CHKERRQ (ierr);

  /* Pre-compute alpha term values (see ch_residual_2d above)
     This should be the only place they're actually computed; they'll be
     used below. */
  avalue[0] = avalue[12] = -alpha*hym2*hym2;
  avalue[1] = avalue[3] = avalue[9] = avalue[11] = -2.*alpha*hxm2*hym2;
  avalue[2] = avalue[10] = 4.*alpha*hym2*(hxm2+hym2);
  avalue[4] = avalue[8] = -alpha*hxm2*hxm2;
  avalue[5] = avalue[7] = 4.*alpha*hxm2*(hxm2+hym2);
  avalue[6] = -alpha*(6.*hxm2*hxm2 + 6.*hym2*hym2 + 8.*hxm2*hym2);

  /* Loop over interior nodes */
  for (j=yints-gys; j<yinte-gys; j++)
    for (i=j*gxm + xints-gxs; i<j*gxm + xinte-gxs; i++) {

      /* Form the column indices */
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm);  columns[3]=C(i+gxm+1);
      columns[4]=C(i-2);     columns[5]=C(i-1);    columns[6]=C(i);
      columns[7]=C(i+1);     columns[8]=C(i+2);
      columns[9]=C(i-gxm-1); columns[10]=C(i-gxm); columns[11]=C(i-gxm+1);
      columns[12]=C(i-2*gxm);

      node = C(i);
      MatSetValuesLocal (user->alpha, 1,&node, 13,columns, avalue,
			 INSERT_VALUES);
    }

  /* Okay, that was the easy part, now for the boundary conditions! */

  /* Test whether we're on the bottom row and non-y-periodic */
  if (yints == 2) {
    printf ("This must only be reached if we are NOT y-periodic\n");
    /* Change value 6 and do the second-from-bottom row */
    avalue[6] += avalue[12];
    for (i=gxm + xints-gxs; i<gxm + xinte-gxs; i++) {

      /* Form the column indices */
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm); columns[3]=C(i+gxm+1);
      columns[4]=C(i-2);     columns[5]=C(i-1);   columns[6]=C(i);
      columns[7]=C(i+1);     columns[8]=C(i+2);
      columns[9]=C(i-gxm-1); columns[10]=C(i-gxm); columns[11]=C(i-gxm+1);

      node = C(i);
      MatSetValuesLocal (user->alpha, 1,&node, 12,columns, avalue,
			 INSERT_VALUES);
    }
    avalue[6] -= avalue[12];

    /* Make some new avalues and do the bottom row */
    avalue[13] = 2.*avalue[0];
    avalue[14] = avalue[16] = 2.*avalue[1];
    avalue[15] = 2.*avalue[2];
    avalue[17] = avalue[21] = avalue[4];
    avalue[18] = avalue[20] = avalue[5];
    avalue[19] = avalue[6];
    for (i=xints-gxs; i<xinte-gxs; i++) {

      /* Form the column indices */
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm); columns[3]=C(i+gxm+1);
      columns[4]=C(i-2);     columns[5]=C(i-1);   columns[6]=C(i);
      columns[7]=C(i+1);     columns[8]=C(i+2);

      node = C(i);
      MatSetValuesLocal (user->alpha, 1,&node, 9,columns, avalue+13,
			 INSERT_VALUES);
    }

    /* Bottom left corner */
    if (xints == 2) {
      node=C(0); /* The point (0,0) */
      columns[0]=C(2*gxm);
      columns[1]=C(gxm);   columns[2]=C(gxm+1);
      columns[3]=C(0);     columns[4]=C(1);     columns[5]=C(2);
      avalue[13] = 2.*avalue[0];
      avalue[14] = 2.*avalue[2];
      avalue[15] = 4.*avalue[3];
      avalue[16] = avalue[6];
      avalue[17] = 2.*avalue[7];
      avalue[18] = 2.*avalue[8];
      MatSetValuesLocal (user->alpha, 1,&node, 6,columns, avalue+13,
			 INSERT_VALUES);
      node=C(1); /* The point (1,0) */
      columns[0]=C(2*gxm+1);
      columns[1]=C(gxm); columns[2]=C(gxm+1); columns[3]=C(gxm+2);
      columns[4]=C(0);   columns[5]=C(1);  columns[6]=C(2);  columns[7]=C(3);
      avalue[13] = 2.*avalue[0];
      avalue[14] = avalue[16] = 2.*avalue[1];
      avalue[15] = 2.*avalue[2];
      avalue[17] = avalue[19] = avalue[5];
      avalue[18] = avalue[6]  + avalue[4];
      avalue[20] = avalue[8];
      MatSetValuesLocal (user->alpha, 1,&node, 8,columns, avalue+13,
			 INSERT_VALUES);
      node=C(gxm); /* The point (0,1) */
      columns[0]=C(3*gxm);
      columns[1]=C(2*gxm); columns[2]=C(2*gxm+1);
      columns[3]=C(gxm);   columns[4]=C(gxm+1);   columns[5]=C(gxm+2);
      columns[6]=C(0);     columns[7]=C(1);
      avalue[13] = avalue[0];
      avalue[14] = avalue[19] = avalue[2];
      avalue[15] = avalue[20] = 2.*avalue[3];
      avalue[16] = avalue[6] + avalue[12];
      avalue[17] = 2.*avalue[7];
      avalue[18] = 2.*avalue[8];
      MatSetValuesLocal (user->alpha, 1,&node, 8,columns, avalue+13,
			 INSERT_VALUES);
      node=C(gxm+1); /* The point (1,1) */
      columns[0]=C(3*gxm+1);
      columns[1]=C(2*gxm); columns[2]=C(2*gxm+1); columns[3]=C(2*gxm+2);
      columns[4]=C(gxm);   columns[5]=C(gxm+1);   columns[6]=C(gxm+2);
      columns[7]=C(gxm+3);
      columns[8]=C(0);     columns[9]=C(1);       columns[10]=C(2);
      avalue[13] = avalue[0];
      avalue[14] = avalue[16] = avalue[21] = avalue[23] = avalue[1];
      avalue[15] = avalue[22] = avalue[2];
      avalue[17] = avalue[19] = avalue[5];
      avalue[18] = avalue[6] + avalue[4] + avalue[12];
      avalue[20] = avalue[8];
      MatSetValuesLocal (user->alpha, 1,&node, 11,columns, avalue+13,
			 INSERT_VALUES);
    }

    /* Bottom right corner */
    if(xinte == mx-2) {
      node=C(i=mx-gxs-1); /* The point (mx-1, 0) */
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm);
      columns[3]=C(i-2);     columns[4]=C(i-1);   columns[5]=C(i);
      avalue[13] = 2.*avalue[0];
      avalue[14] = 4.*avalue[1];
      avalue[15] = 2.*avalue[2];
      avalue[16] = 2.*avalue[4];
      avalue[17] = 2.*avalue[5];
      avalue[18] = avalue[6];
      MatSetValuesLocal (user->alpha, 1,&node, 6,columns, avalue+13,
			 INSERT_VALUES);
      node=C(i=mx-gxs-2); /* The point (mx-2,0) */
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm); columns[3]=C(i+gxm+1);
      columns[4]=C(i-2);     columns[5]=C(i-1);   columns[6]=C(i);
      columns[7]=C(i+1);
      avalue[13] = 2.*avalue[0];
      avalue[14] = avalue[16] = 2.*avalue[1];
      avalue[15] = 2.*avalue[2];
      avalue[17] = avalue[4];
      avalue[18] = avalue[20] = avalue[5];
      avalue[19] = avalue[6]  + avalue[8];
      MatSetValuesLocal (user->alpha, 1,&node, 8,columns, avalue+13,
			 INSERT_VALUES);
      node=C(i=gxm+mx-gxs-1); /* The point (mx-1,1) */
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm);
      columns[3]=C(i-2);     columns[4]=C(i-1);   columns[5]=C(i);
      columns[6]=C(i-gxm-1); columns[7]=C(i-gxm);
      avalue[13] = avalue[0];
      avalue[14] = avalue[19] = 2.*avalue[1];
      avalue[15] = avalue[20] = avalue[2];
      avalue[16] = 2.*avalue[4];
      avalue[17] = 2.*avalue[5];
      avalue[18] = avalue[6] + avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 8,columns, avalue+13,
			 INSERT_VALUES);
      node=C(i=gxm+mx-gxs-2); /* The point (mx-2,1) */
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm); columns[3]=C(i+gxm+1);
      columns[4]=C(i-2);     columns[5]=C(i-1);   columns[6]=C(i);
      columns[7]=C(i+1);
      columns[8]=C(i-gxm-1); columns[9]=C(i-gxm);   columns[10]=C(i-gxm+1);
      avalue[13] = avalue[0];
      avalue[14] = avalue[16] = avalue[21] = avalue[23] = avalue[1];
      avalue[15] = avalue[22] = avalue[2];
      avalue[17] = avalue[4];
      avalue[18] = avalue[20] = avalue[5];
      avalue[19] = avalue[6] + avalue[8] + avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 11,columns, avalue+13,
			 INSERT_VALUES);
    }
  }

  /* Test whether we're on the top row and non-y-periodic */
  if (yinte == my-2) {
    printf ("This must only be reached if we are NOT y-periodic\n");
    /* Change value 6 and do the second-from-top row */
    avalue[6] += avalue[0];
    for (i=(my-gys-2)*gxm + xints-gxs;
	 i<(my-gys-2)*gxm + xinte-gxs; i++) {

      /* Form the column indices */
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm);  columns[3]=C(i+gxm+1);
      columns[4]=C(i-2);     columns[5]=C(i-1);    columns[6]=C(i);
      columns[7]=C(i+1);     columns[8]=C(i+2);
      columns[9]=C(i-gxm-1); columns[10]=C(i-gxm); columns[11]=C(i-gxm+1);
      columns[12]=C(i-2*gxm);

      node = C(i);
      MatSetValuesLocal (user->alpha, 1,&node, 12,columns+1, avalue+1,
			 INSERT_VALUES);
    }
    avalue[6] -= avalue[0];

    /* Make some new avalues and do the top row */
    avalue[13] = avalue[17] = avalue[4];
    avalue[14] = avalue[16] = avalue[5];
    avalue[15] = avalue[6];
    avalue[18] = avalue[20] = 2.*avalue[9];
    avalue[19] = 2.*avalue[10];
    avalue[21] = 2.*avalue[12];
    for (i=(my-gys-1)*gxm + xints-gxs;
	 i<(my-gys-1)*gxm + xinte-gxs; i++) {

      /* Form the column indices */
      columns[0]=C(i-2);     columns[1]=C(i-1);   columns[2]=C(i);
      columns[3]=C(i+1);     columns[4]=C(i+2);
      columns[5]=C(i-gxm-1); columns[6]=C(i-gxm); columns[7]=C(i-gxm+1);
      columns[8]=C(i-2*gxm);

      node = C(i);
      MatSetValuesLocal (user->alpha, 1,&node, 9,columns, avalue+13,
			 INSERT_VALUES);
    }

    /* Top left corner */
    if (xints == 2) {
      node=C(i=(my-gys-1)*gxm); /* The point (0,my-1) */
      columns[0]=C(i);       columns[1]=C(i+1); columns[2]=C(i+2);
      columns[3]=C(i-gxm);   columns[4]=C(i-gxm+1);
      columns[5]=C(i-2*gxm);
      avalue[13] = avalue[6];
      avalue[14] = 2.*avalue[7];
      avalue[15] = 2.*avalue[8];
      avalue[16] = 2.*avalue[10];
      avalue[17] = 4.*avalue[11];
      avalue[18] = 2.*avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 6,columns, avalue+13,
			 INSERT_VALUES);
      node=C(i=(my-gys-1)*gxm+1); /* The point (1,my-1) */
      columns[0]=C(i-1);     columns[1]=C(i);     columns[2]=C(i+1);
      columns[3]=C(i+2);
      columns[4]=C(i-gxm-1); columns[5]=C(i-gxm); columns[6]=C(i-gxm+1);
      columns[7]=C(i-2*gxm);
      avalue[13] = avalue[15] = avalue[5];
      avalue[14] = avalue[6]  + avalue[4];
      avalue[16] = avalue[8];
      avalue[17] = avalue[19] = 2.*avalue[9];
      avalue[18] = 2.*avalue[10];
      avalue[20] = 2.*avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 8,columns, avalue+13,
			 INSERT_VALUES);
      node=C(i=(my-gys-2)*gxm); /* The point (0,my-2) */
      columns[0]=C(i+gxm); columns[1]=C(i+gxm+1);
      columns[2]=C(i);     columns[3]=C(i+1);   columns[4]=C(i+2);
      columns[5]=C(i-gxm); columns[6]=C(i-gxm+1);
      columns[7]=C(i-2*gxm);
      avalue[13] = avalue[18] = avalue[2];
      avalue[14] = avalue[19] = 2.*avalue[3];
      avalue[15] = avalue[6] + avalue[0];
      avalue[16] = 2.*avalue[7];
      avalue[17] = 2.*avalue[8];
      avalue[20] = avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 8,columns, avalue+13,
			 INSERT_VALUES);
      node=C(i=(my-gys-2)*gxm+1); /* The point (1,my-2) */
      columns[0]=C(i+gxm-1); columns[1]=C(i+gxm); columns[2]=C(i+gxm+1);
      columns[3]=C(i-1);     columns[4]=C(i);     columns[5]=C(i+1);
      columns[6]=C(i+2);
      columns[7]=C(i-gxm-1); columns[8]=C(i-gxm); columns[9]=C(i-gxm+1);
      columns[10]=C(i-2*gxm);
      avalue[13] = avalue[15] = avalue[20] = avalue[22] = avalue[1];
      avalue[14] = avalue[21] = avalue[2];
      avalue[16] = avalue[18] = avalue[5];
      avalue[17] = avalue[6] + avalue[4] + avalue[0];
      avalue[19] = avalue[8];
      avalue[23] = avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 11,columns, avalue+13,
			 INSERT_VALUES);
    }

    /* Top right corner */
    if(xinte == mx-2) {
      node=C(i=(my-gys-1)*gxm + mx-gxs-1); /* The point (mx-1, my-1) */
      columns[0]=C(i-2);   columns[1]=C(i-1);   columns[2]=C(i);
      columns[3]=C(i-gxm-1); columns[4]=C(i-gxm);
      columns[5]=C(i-2*gxm);
      avalue[13] = 2.*avalue[4];
      avalue[14] = 2.*avalue[5];
      avalue[15] = avalue[6];
      avalue[16] = 4.*avalue[9];
      avalue[17] = 2.*avalue[10];
      avalue[18] = 2.*avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 6,columns, avalue+13,
			 INSERT_VALUES);
      node=C(i=(my-gys-1)*gxm + mx-gxs-2); /* The point (mx-2, my-1) */
      columns[0]=C(i-2);   columns[1]=C(i-1);   columns[2]=C(i);
      columns[3]=C(i+1);
      columns[4]=C(i-gxm-1); columns[5]=C(i-gxm); columns[6]=C(i-gxm+1);
      columns[7]=C(i-2*gxm);
      avalue[13] = avalue[4];
      avalue[14] = avalue[16] = avalue[5];
      avalue[15] = avalue[6]  + avalue[8];
      avalue[17] = avalue[19] = 2.*avalue[9];
      avalue[18] = 2.*avalue[10];
      avalue[20] = 2.*avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 8,columns, avalue+13,
			 INSERT_VALUES);
      node=C(i=(my-gys-2)*gxm + mx-gxs-1); /* The point (mx-1, my-2) */
      columns[0]=C(i+gxm-1); columns[1]=C(i+gxm);
      columns[2]=C(i-2);     columns[3]=C(i-1);   columns[4]=C(i);
      columns[5]=C(i-gxm-1); columns[6]=C(i-gxm);
      columns[7]=C(i-2*gxm);
      avalue[13] = avalue[18] = 2.*avalue[1];
      avalue[14] = avalue[19] = avalue[2];
      avalue[15] = 2.*avalue[4];
      avalue[16] = 2.*avalue[5];
      avalue[17] = avalue[6] + avalue[0];
      avalue[20] = avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 8,columns, avalue+13,
			 INSERT_VALUES);
      node=C(i=(my-gys-2)*gxm + mx-gxs-2); /* The point (mx-2, my-2) */
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm); columns[3]=C(i+gxm+1);
      columns[4]=C(i-2);     columns[5]=C(i-1);   columns[6]=C(i);
      columns[7]=C(i+1);
      columns[8]=C(i-gxm-1); columns[9]=C(i-gxm); columns[10]=C(i-gxm+1);
      columns[11]=C(i-2*gxm);
      avalue[14] = avalue[16] = avalue[21] = avalue[23] = avalue[1];
      avalue[15] = avalue[22] = avalue[2];
      avalue[17] = avalue[4];
      avalue[18] = avalue[20] = avalue[5];
      avalue[19] = avalue[6] + avalue[8] + avalue[0];
      avalue[24] = avalue[12];
      MatSetValuesLocal (user->alpha, 1,&node, 11,columns+1, avalue+14,
			 INSERT_VALUES);
    }
  }

  /* Test whether we're on the left column and non-x-periodic */
  if (xints == 2) {
    printf ("This must only be reached if we are NOT x-periodic\n");
    /* Make some avalues and do the second-from-left column */
    avalue[13] = avalue[24] = avalue[0];
    avalue[14] = avalue[16] = avalue[21] = avalue[23] = avalue[1];
    avalue[15] = avalue[22] = avalue[2];
    avalue[17] = avalue[19] = avalue[5];
    avalue[18] = avalue[6]  + avalue[4];
    avalue[20] = avalue[8];
    for (i=(yints-gys)*gxm + 1; i<(yinte-gys)*gxm + 1; i+=gxm) {
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm);  columns[3]=C(i+gxm+1);
      columns[4]=C(i-1);     columns[5]=C(i);      columns[6]=C(i+1);
      columns[7]=C(i+2);
      columns[8]=C(i-gxm-1); columns[9]=C(i-gxm); columns[10]=C(i-gxm+1);
      columns[11]=C(i-2*gxm);

      node = C(i);
      MatSetValuesLocal (user->alpha, 1,&node, 12,columns, avalue+13,
			 INSERT_VALUES);
    }

    /* Make some more avalues and do the leftmost column */
    avalue[13] = avalue[21] = avalue[0];
    avalue[14] = avalue[19] = avalue[2];
    avalue[15] = avalue[20] = 2.*avalue[3];
    avalue[16] = avalue[6];
    avalue[17] = 2.*avalue[7];
    avalue[18] = 2.*avalue[8];
    for (i=(yints-gys)*gxm; i<(yinte-gys)*gxm; i+=gxm) {
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm);  columns[2]=C(i+gxm+1);
      columns[3]=C(i);      columns[4]=C(i+1);     columns[5]=C(i+2);
      columns[6]=C(i-gxm);  columns[7]=C(i-gxm+1);
      columns[8]=C(i-2*gxm);

      node = C(i);
      MatSetValuesLocal (user->alpha, 1,&node, 9,columns, avalue+13,
			 INSERT_VALUES);
    }
  }

  /* Test whether we're on the right column and non-x-periodic */
  if (xinte == mx-2) {
    printf ("This must only be reached if we are NOT x-periodic\n");
    /* Make some avalues and do the second-from-right column */
    avalue[13] = avalue[24] = avalue[0];
    avalue[14] = avalue[16] = avalue[21] = avalue[23] = avalue[1];
    avalue[15] = avalue[22] = avalue[2];
    avalue[17] = avalue[4];
    avalue[18] = avalue[20] = avalue[5];
    avalue[19] = avalue[6]  + avalue[8];
    for (i=(yints-gys)*gxm + mx-gxs-2; i<(yinte-gys)*gxm + mx-gxs-2; i+=gxm) {
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1); columns[2]=C(i+gxm);  columns[3]=C(i+gxm+1);
      columns[4]=C(i-2);     columns[5]=C(i-1);    columns[6]=C(i);
      columns[7]=C(i+1);
      columns[8]=C(i-gxm-1); columns[9]=C(i-gxm); columns[10]=C(i-gxm+1);
      columns[11]=C(i-2*gxm);

      node = C(i);
      MatSetValuesLocal (user->alpha, 1,&node, 12,columns, avalue+13,
			 INSERT_VALUES);
    }

    /* Make some more avalues and do the rightmost column */
    avalue[13] = avalue[21] = avalue[0];
    avalue[14] = avalue[19] = 2.*avalue[1];
    avalue[15] = avalue[20] = avalue[2];
    avalue[16] = 2.*avalue[4];
    avalue[17] = 2.*avalue[5];
    avalue[18] = avalue[6];
    for (i=(yints-gys)*gxm + mx-gxs-1; i<(yinte-gys)*gxm + mx-gxs-1; i+=gxm) {
      columns[0]=C(i+2*gxm);
      columns[1]=C(i+gxm-1);  columns[2]=C(i+gxm);
      columns[3]=C(i-2);      columns[4]=C(i-1);     columns[5]=C(i);
      columns[6]=C(i-gxm-1);  columns[7]=C(i-gxm);
      columns[8]=C(i-2*gxm);

      node = C(i);
      MatSetValuesLocal (user->alpha, 1,&node, 9,columns, avalue+13,
			 INSERT_VALUES);
    }
  }

  /* Assemble matrix, using the 2-step process:
     MatAssemblyBegin(), MatAssemblyEnd(). */
  ierr = MatAssemblyBegin(user->alpha,MAT_FINAL_ASSEMBLY); CHKERRQ (ierr);
  ierr = MatAssemblyEnd(user->alpha,MAT_FINAL_ASSEMBLY); CHKERRQ (ierr);

  /* Make J a copy of alpha with the same local mapping (setting new mapping is
     unnecessary with PETSc 2.1.5). */
  ierr = MatDuplicate (user->alpha, MAT_COPY_VALUES, &(user->J)); CHKERRQ (ierr);

  /* Tell the matrix we will never add a new nonzero location to the
     matrix. If we do, it will generate an error. */
  ierr = MatSetOption(user->J,MAT_NEW_NONZERO_LOCATION_ERR); CHKERRQ (ierr);

  return ierr;
}


/*++++++++++++++++++++++++++++++++++++++
  This creates the initial alpha and J matrices, where alpha is the alpha term
  component of the Jacobian.  Since the alpha term is linear, this part of the
  Jacobian need only be calculated once.

  int ch_jacobian_alpha_3d It returns zero or an error message.

  AppCtx *user The application context structure pointer.
  ++++++++++++++++++++++++++++++++++++++*/

int ch_jacobian_alpha_3d (AppCtx *user)
{
  int     ierr,node,i,j,k, mc,chvar, mx,my,mz, xs,ys,zs, xm,ym,zm;
  int     gxs,gys,gzs, gxm,gym,gzm, xints,xinte, yints,yinte, zints,zinte;
  int     columns [25];
  PetscScalar  hx,hy,hz, dhx,dhy,dhz, hxm2,hym2,hzm2;
  PetscScalar  alpha,beta,mparam;
  PetscScalar  avalue [25];

  mc = user->mc;  chvar = user->chvar;
  mx = user->mx;  my = user->my;  mz = user->mz;  mparam = user->mparam;
  alpha = user->kappa * user->gamma * user->epsilon;
  beta = user->kappa * user->gamma / user->epsilon;

  /* Define mesh intervals ratios for uniform grid.
     [Note: FD formulae below may someday be normalized by multiplying through
     by local volume element to obtain coefficients O(1) in two dimensions.] */
  dhx = (PetscScalar)(mx-1);  dhy = (PetscScalar)(my-1);
  dhz = (PetscScalar)(mz-1);
  /* This line hard-codes the 1x1x1 cube */
  hx = 1./dhx;           hy = 1./dhy;          hz = 1./dhz;
  hxm2 = 1./hx/hx;       hym2 = 1./hy/hy;      hzm2 = 1./hz/hz;

  /* Get local grid boundaries */
  ierr = DAGetCorners(user->da,&xs,&ys,&zs,&xm,&ym,&zm); CHKERRQ (ierr);
  ierr = DAGetGhostCorners(user->da,&gxs,&gys,&gzs,&gxm,&gym,&gzm);
  CHKERRQ (ierr);

  /* Determine the interior of the locally owned part of the grid. */
  if (user->period == DA_XYZPERIODIC) {
    xints = xs; xinte = xs+xm;
    yints = ys; yinte = ys+ym;
    zints = zs; zinte = zs+zm; }
  else {
    SETERRQ(PETSC_ERR_ARG_WRONGSTATE,
	    "Only periodic boundary conditions in 3-D Cahn-Hilliard"); }

  /* Get parameters for matrix creation */
  i = xm * ym * zm * user->mc;
  j = mx * my * mz * user->mc;

  /* Create the distributed alpha matrix */
  ierr = MatCreateMPIAIJ (user->comm, i,i, j,j, 25,PETSC_NULL, 12,PETSC_NULL,
			  &(user->alpha));
  CHKERRQ (ierr);

  /* Get the local-to-global mapping and associate it with the matrix */
  ierr = DAGetISLocalToGlobalMapping (user->da, &user->isltog); CHKERRQ (ierr);
  ierr = MatSetLocalToGlobalMapping (user->alpha, user->isltog); CHKERRQ (ierr);

  /* Pre-compute alpha term values (see ch_residual_2d above)
     This should be the only place they're actually computed; they'll be
     used below. */
  avalue[0]  = avalue[24] = -alpha*hzm2*hzm2;
  avalue[1]  = avalue[5] = avalue[19] = avalue[23] = -2.*alpha*hym2*hzm2;
  avalue[2]  = avalue[4] = avalue[20] = avalue[22] = -2.*alpha*hxm2*hzm2;
  avalue[3]  = avalue[21] = 4.*alpha*hzm2*(hxm2+hym2+hzm2);
  avalue[6]  = avalue[18] = -alpha*hym2*hym2;
  avalue[7]  = avalue[9] = avalue[15] = avalue[17] = -2.*alpha*hxm2*hym2;
  avalue[8]  = avalue[16] = 4.*alpha*hym2*(hxm2+hym2+hzm2);
  avalue[10] = avalue[14] = -alpha*hxm2*hxm2;
  avalue[11] = avalue[13] = 4.*alpha*hxm2*(hxm2+hym2+hzm2);
  avalue[12] = -alpha*(6.*hxm2*hxm2 + 6.*hym2*hym2 + 6.*hzm2*hzm2
		       + 8.*hxm2*hym2 + 8.*hxm2*hzm2 + 8.*hym2*hzm2);

  /* Loop over interior nodes */
  for (k=zints-gzs; k<zinte-gzs; k++)
    for (j=k*gym + yints-gys; j<k*gym + yinte-gys; j++)
      for (i=j*gxm + xints-gxs; i<j*gxm + xinte-gxs; i++) {

	/* Form the column indices */
	columns[0]=C(i+2*gxm*gym);
	columns[1]=C(i+gxm*gym+gxm);
	columns[2]=C(i+gxm*gym-1);
	columns[3]=C(i+gxm*gym);
	columns[4]=C(i+gxm*gym+1);
	columns[5]=C(i+gxm*gym-gxm);
	columns[6]=C(i+2*gxm);
	columns[7]=C(i+gxm-1);  columns[8]=C(i+gxm);  columns[9]=C(i+gxm+1);
	columns[10]=C(i-2);     columns[11]=C(i-1);   columns[12]=C(i);
	columns[13]=C(i+1);     columns[14]=C(i+2);
	columns[15]=C(i-gxm-1); columns[16]=C(i-gxm); columns[17]=C(i-gxm+1);
	columns[18]=C(i-2*gxm);
	columns[19]=C(i-gxm*gym+gxm);
	columns[20]=C(i-gxm*gym-1);
	columns[21]=C(i-gxm*gym);
	columns[22]=C(i-gxm*gym+1);
	columns[23]=C(i-gxm*gym-gxm);
	columns[24]=C(i-2*gxm*gym);

	node = C(i);
	MatSetValuesLocal (user->alpha, 1,&node, 25,columns, avalue,
			   INSERT_VALUES);
      }

  /* Assemble matrix, using the 2-step process:
     MatAssemblyBegin(), MatAssemblyEnd(). */
  ierr = MatAssemblyBegin(user->alpha,MAT_FINAL_ASSEMBLY); CHKERRQ (ierr);
  ierr = MatAssemblyEnd(user->alpha,MAT_FINAL_ASSEMBLY); CHKERRQ (ierr);

  /* Make J a copy of alpha with the same local mapping (setting new mapping is
     unnecessary with PETSc 2.1.5). */
  ierr = MatDuplicate (user->alpha, MAT_COPY_VALUES, &(user->J)); CHKERRQ (ierr);

  /* Tell the matrix we will never add a new nonzero location to the
     matrix. If we do, it will generate an error. */
  ierr = MatSetOption(user->J,MAT_NEW_NONZERO_LOCATION_ERR); CHKERRQ (ierr);

  return ierr;
}