File: meep.hpp

package info (click to toggle)
meep-mpich2 1.7.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 25,824 kB
  • sloc: cpp: 27,370; python: 10,574; lisp: 1,213; makefile: 440; sh: 28
file content (1857 lines) | stat: -rw-r--r-- 74,361 bytes parent folder | download | duplicates (5)
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
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
/* Copyright (C) 2005-2015 Massachusetts Institute of Technology
%
%  This program is free software; you can redistribute it and/or modify
%  it under the terms of the GNU General Public License as published by
%  the Free Software Foundation; either version 2, or (at your option)
%  any later version.
%
%  This program is distributed in the hope that it will be useful,
%  but WITHOUT ANY WARRANTY; without even the implied warranty of
%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%  GNU General Public License for more details.
%
%  You should have received a copy of the GNU General Public License
%  along with this program; if not, write to the Free Software Foundation,
%  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef MEEP_H
#define MEEP_H

#include <stdio.h>
#include <stddef.h>
#include <math.h>

#include "meep/vec.hpp"
#include "meep/mympi.hpp"

#include <vector>

namespace meep {

/* We use the type realnum for large arrays, e.g. the fields.
   For local variables and small arrays, we use double precision,
   but for things like the fields we can often get away with
   single precision (since the errors are not dominated by roundoff).
   However, we will default to using double-precision for large
   arrays, as the factor of two in memory and the moderate increase
   in speed currently don't seem worth the loss of precision. */
#define MEEP_SINGLE 0 // 1 for single precision, 0 for double
#if MEEP_SINGLE
typedef float realnum;
#else
typedef double realnum;
#endif

extern bool quiet; // if true, suppress all non-error messages from Meep

const double pi = 3.141592653589793238462643383276;

const double infinity = HUGE_VAL;

#ifdef NAN
const double nan = NAN;
#else
const double nan = -7.0415659787563146e103; // ideally, a value never encountered in practice
#endif

class h5file;

/* generic base class, only used by subclassing: represents susceptibility
   polarizability vector P = chi(omega) W  (where W = E or H). */
class susceptibility {
public:
  susceptibility() { id = cur_id++; ntot = 0; next = NULL;
    FOR_COMPONENTS(c) FOR_DIRECTIONS(d) {
      sigma[c][d] = NULL; trivial_sigma[c][d] = true; } }
  susceptibility(const susceptibility &s) { id = s.id; ntot = s.ntot;
    next = NULL; FOR_COMPONENTS(c) FOR_DIRECTIONS(d) {
      sigma[c][d] = NULL; trivial_sigma[c][d] = true; } }
  virtual susceptibility *clone() const;
  virtual ~susceptibility() {
    FOR_COMPONENTS(c) FOR_DIRECTIONS(d) delete[] sigma[c][d];
    delete next; }

  int get_id() const { return id; }
  bool operator==(const susceptibility &s) const { return id == s.id; };

  // update all of the internal polarization state given the W field
  // at the current time step, possibly the previous field W_prev, etc.
  virtual void update_P(realnum *W[NUM_FIELD_COMPONENTS][2],
			realnum *W_prev[NUM_FIELD_COMPONENTS][2],
			double dt, const grid_volume &gv,
			void *P_internal_data) const {
    (void) P; (void) W; (void) W_prev; (void) dt; (void) gv;
    (void) P_internal_data; // avoid warnings for unused params
  }

  // subtract all of the internal polarizations from the given f_minus_p
  // field.  Also given the fields array if it is needed for some reason.
  // Only update for ft fields.
  virtual void subtract_P(field_type ft,
			  realnum *f_minus_p[NUM_FIELD_COMPONENTS][2],
			  void *P_internal_data) const {
    (void) ft; (void) f_minus_p; (void) P_internal_data;
  }

  // whether, for the given field W, Meep needs to allocate P[c]
  virtual bool needs_P(component c, int cmp,
		       realnum *W[NUM_FIELD_COMPONENTS][2]) const;

  // whether update_P will need the notowned part of W for this c
  // (which means that Meep will need to communicate it between chunks)
  virtual bool needs_W_notowned(component c,
				realnum *W[NUM_FIELD_COMPONENTS][2]) const;

  // whether update_P needs the W_prev field (from the previous timestep)
  virtual bool needs_W_prev() const { return false; }

  /* A susceptibility may be associated with any amount of internal
     data need to update the polarization field.  This includes the
     polarization field(s) itself.  It may also, for example, store
     the polarization field from previous timesteps, atomic-level
     populations, or other data.  These routines return the size of
     this internal-data array and initialize it. */
  virtual void* new_internal_data(realnum *W[NUM_FIELD_COMPONENTS][2],
				  const grid_volume &gv) const {
    (void) W; (void) gv; return 0;
  }
  virtual void delete_internal_data(void *data) const;
  virtual void init_internal_data(realnum *W[NUM_FIELD_COMPONENTS][2],
			 double dt, const grid_volume &gv, void *data) const {
    (void) W; (void) dt; (void) gv; (void) data; }
  virtual void *copy_internal_data(void *data) const { (void)data; return 0; }

  /* The following methods are used in boundaries.cpp to set up any
     extra communications that may be necessary at chunk boundaries
     for the internal data of a susceptibility's polarization
     state. */

  /* the number of notowned fields/data in the internal data that
     are needed by update_P for the c Yee grid (note: we assume that we only
     have internal data for c's where we have external polarizations) */
  virtual int num_internal_notowned_needed(component c,
					   void *P_internal_data) const {
    (void) c; (void) P_internal_data; return 0; }
  /* the offset into the internal data of the n'th Yee-grid point in
     the c Yee grid for the inotowned internal field, where
     0 <= inotowned < size_internal_notowned_needed. */
  virtual realnum *internal_notowned_ptr(int inotowned, component c, int n,
					 void *P_internal_data) const {
    (void) inotowned; (void) n; (void) c; (void) P_internal_data; return 0; }

  /* same thing as above, except this gives (possibly complex)
     internal fields that need to be multiplied by the same phase
     factor as the fields at boundaries.  Note: we assume internal fields
     are complex if and only if !is_real (i.e. if EM fields are complex) */
  virtual int num_cinternal_notowned_needed(component c,
					   void *P_internal_data) const {
    (void) c; (void) P_internal_data; return 0; }
  // real/imaginary parts offsets for cmp = 0/1
  virtual realnum *cinternal_notowned_ptr(int inotowned, component c, int cmp,
					  int n,
					  void *P_internal_data) const {
    (void) inotowned; (void) n; (void) c; (void) cmp; (void) P_internal_data;
    return 0; }

  virtual void dump_params(h5file *h5f, size_t *start) { (void)h5f; (void)start; }
  virtual int get_num_params() { return 0; }
  // This should only be used when dumping and loading susceptibility data to hdf5
  void set_id(int new_id) { id = new_id; };

  susceptibility *next;
  size_t ntot;
  realnum *sigma[NUM_FIELD_COMPONENTS][5];

  /* trivial_sigma[c][d] is true only if *none* of the processes has a
     nontrivial sigma (c,d) component.  This differs, from sigma,
     which is non-NULL only if *this* process needs a nontrivial sigma
     (c,d).  Coordinated between processes at add_susceptibility, no
     communication elsewhere.  (We need this for boundary
     communcations between chunks, where one chunk might have sigma ==
     0 and the other != 0.) */
  bool trivial_sigma[NUM_FIELD_COMPONENTS][5];

private:
  static int cur_id; // unique id to assign to next susceptibility object
  int id; // id for this object and its clones, for comparison purposes
};

/* a Lorentzian susceptibility
   \chi(\omega) = sigma * omega_0^2 / (\omega_0^2 - \omega^2 - i\gamma \omega)
  If no_omega_0_denominator is true, then we omit the omega_0^2 factor in the
  denominator to obtain a Drude model. */
class lorentzian_susceptibility : public susceptibility {
public:
  lorentzian_susceptibility(double omega_0, double gamma, bool no_omega_0_denominator = false) : omega_0(omega_0), gamma(gamma), no_omega_0_denominator(no_omega_0_denominator) {}
  virtual susceptibility *clone() const { return new lorentzian_susceptibility(*this); }
  virtual ~lorentzian_susceptibility() {}

  virtual void update_P(realnum *W[NUM_FIELD_COMPONENTS][2],
			realnum *W_prev[NUM_FIELD_COMPONENTS][2],
			double dt, const grid_volume &gv,
			void *P_internal_data) const;

  virtual void subtract_P(field_type ft,
			  realnum *f_minus_p[NUM_FIELD_COMPONENTS][2],
			  void *P_internal_data) const;

  virtual void *new_internal_data(realnum *W[NUM_FIELD_COMPONENTS][2],
				  const grid_volume &gv) const;
  virtual void init_internal_data(realnum *W[NUM_FIELD_COMPONENTS][2],
			  double dt, const grid_volume &gv, void *data) const;
  virtual void *copy_internal_data(void *data) const;

  virtual int num_cinternal_notowned_needed(component c,
					    void *P_internal_data) const;
  virtual realnum *cinternal_notowned_ptr(int inotowned, component c, int cmp,
					  int n,
					  void *P_internal_data) const;

  virtual void dump_params(h5file *h5f, size_t *start);
  virtual int get_num_params() { return 4; }

protected:
  double omega_0, gamma;
  bool no_omega_0_denominator;
};

/* like a Lorentzian susceptibility, but the polarization equation
   includes white noise with a specified amplitude */
class noisy_lorentzian_susceptibility : public lorentzian_susceptibility {
public:
  noisy_lorentzian_susceptibility(double noise_amp, double omega_0, double gamma, bool no_omega_0_denominator = false) : lorentzian_susceptibility(omega_0, gamma, no_omega_0_denominator), noise_amp(noise_amp) {}

  virtual susceptibility *clone() const { return new noisy_lorentzian_susceptibility(*this); }

  virtual void update_P(realnum *W[NUM_FIELD_COMPONENTS][2],
			realnum *W_prev[NUM_FIELD_COMPONENTS][2],
			double dt, const grid_volume &gv,
			void *P_internal_data) const;

  virtual void dump_params(h5file *h5f, size_t *start);
  virtual int get_num_params() { return 5; }

protected:
  double noise_amp;
};

class multilevel_susceptibility : public susceptibility {
public:
  multilevel_susceptibility() : L(0), T(0), Gamma(0), N0(0), alpha(0), omega(0), gamma(0) {}
  multilevel_susceptibility(int L, int T,
			    const realnum *Gamma,
			    const realnum *N0,
			    const realnum *alpha,
			    const realnum *omega,
			    const realnum *gamma,
			    const realnum *sigmat);
  multilevel_susceptibility(const multilevel_susceptibility &from);
  virtual susceptibility *clone() const { return new multilevel_susceptibility(*this); }
  virtual ~multilevel_susceptibility();

  virtual void update_P(realnum *W[NUM_FIELD_COMPONENTS][2],
			realnum *W_prev[NUM_FIELD_COMPONENTS][2],
			double dt, const grid_volume &gv,
			void *P_internal_data) const;

  virtual void subtract_P(field_type ft,
			  realnum *f_minus_p[NUM_FIELD_COMPONENTS][2],
			  void *P_internal_data) const;

  virtual void *new_internal_data(realnum *W[NUM_FIELD_COMPONENTS][2],
				  const grid_volume &gv) const;
  virtual void init_internal_data(realnum *W[NUM_FIELD_COMPONENTS][2],
				  double dt, const grid_volume &gv,
				  void *data) const;
  virtual void *copy_internal_data(void *data) const;
  virtual void delete_internal_data(void *data) const;

  virtual int num_cinternal_notowned_needed(component c,
					    void *P_internal_data) const;
  virtual realnum *cinternal_notowned_ptr(int inotowned, component c, int cmp,
					  int n,
					  void *P_internal_data) const;

  // always need notowned W and W_prev for E dot dP/dt terms
  virtual bool needs_W_notowned(component c,
				realnum *W[NUM_FIELD_COMPONENTS][2]) const {
    (void) c; (void) W;
    return true;
  }
  virtual bool needs_W_prev() const { return true; }

protected:
  int L; // number of atom levels
  int T; // number of optical transitions
  realnum *Gamma; // LxL matrix of relaxation rates Gamma[i*L+j] from i -> j
  realnum *N0; // L initial populations
  realnum *alpha; // LxT matrix of transition coefficients 1/omega
  realnum *omega; // T transition frequencies
  realnum *gamma; // T optical loss rates
  realnum *sigmat; // 5*T transition-specific sigma-diagonal factors
};

class grace;

// h5file.cpp: HDF5 file I/O.  Most users, if they use this
// class at all, will only use the constructor to open the file, and
// will otherwise use the fields::output_hdf5 functions.
class h5file {
public:
  typedef enum {
    READONLY, READWRITE, WRITE
  } access_mode;

  h5file(const char *filename_, access_mode m=READWRITE, bool parallel_=true);
  ~h5file(); // closes the files (and any open dataset)

  bool ok();

  realnum *read(const char *dataname, int *rank, size_t *dims, int maxrank);
  void write(const char *dataname, int rank, const size_t *dims, realnum *data,
	     bool single_precision = true);

  char *read(const char *dataname);
  void write(const char *dataname, const char *data);

  void create_data(const char *dataname, int rank, const size_t *dims,
		   bool append_data = false,
		   bool single_precision = true);
  void extend_data(const char *dataname, int rank, const size_t *dims);
  void create_or_extend_data(const char *dataname, int rank,
			     const size_t *dims,
			     bool append_data, bool single_precision);
  void write_chunk(int rank, const size_t *chunk_start, const size_t *chunk_dims,
		   realnum *data);
  void write_chunk(int rank, const size_t *chunk_start, const size_t *chunk_dims,
       size_t *data);
  void done_writing_chunks();

  void read_size(const char *dataname, int *rank, size_t *dims, int maxrank);
  void read_chunk(int rank, const size_t *chunk_start, const size_t *chunk_dims,
		  realnum *data);
  void read_chunk(int rank, const size_t *chunk_start, const size_t *chunk_dims,
		  size_t *data);

  void remove();
  void remove_data(const char *dataname);

  const char *file_name() const { return filename; }

  void prevent_deadlock(); // hackery for exclusive mode
  bool dataset_exists(const char *name);

private:
  access_mode mode;
  char *filename;
  bool parallel;

  bool is_cur(const char *dataname);
  void unset_cur();
  void set_cur(const char *dataname, void *data_id);
  char *cur_dataname;

  /* store hid_t values as hid_t* cast to void*, so that
     files including meep.h don't need hdf5.h */
  void *id; /* file */
  void *cur_id; /* dataset, if any */

  void *get_id(); // get current (file) id, opening/creating file if needed
  void close_id();

public:
  /* linked list to keep track of which datasets we are extending...
     this is necessary so that create_or_extend_data can know whether
     to create (overwrite) a dataset or extend it. */
  struct extending_s {
    int dindex;
    char *dataname;
    struct extending_s *next;
  } *extending;
  extending_s *get_extending(const char *dataname) const;
};

typedef double (*pml_profile_func)(double u, void *func_data);

#define DEFAULT_SUBPIXEL_TOL 1e-4
#define DEFAULT_SUBPIXEL_MAXEVAL 100000

/* This class is used to compute position-dependent material properties
   like the dielectric function, permeability (mu), polarizability sigma,
   nonlinearities, et cetera.  Simple cases of stateless functions are
   handled by canned subclasses below, but more complicated cases
   can be handled by creating a user-defined subclass of material_function.
   It is useful to group different properties into one class because
   it is likely that complicated implementations will share state between
   properties. */
class material_function {
  material_function(const material_function &ef) {(void)ef;} // prevent copying
public:
  material_function() {}
  virtual ~material_function() {}

  /* Specify a restricted grid_volume: all subsequent eps/sigma/etc
     calls will be for points inside v, until the next set_volume. */
  virtual void set_volume(const volume &v) {(void)v;}
  virtual void unset_volume(void) {} // unrestrict the grid_volume

  virtual double chi1p1(field_type ft, const vec &r) { (void)ft; (void)r; return 1.0; }

  /* scalar dielectric function */
  virtual double eps(const vec &r) { return chi1p1(E_stuff, r);  }

  /* scalar permeability function */
  virtual bool has_mu() { return false; } /* true if mu != 1 */
  virtual double mu(const vec &r) { return chi1p1(H_stuff, r);  }

  /* scalar conductivity function */
  virtual bool has_conductivity(component c) { (void)c; return false; }
  virtual double conductivity(component c, const vec &r) {
    (void) c; (void)r; return 0.0; }

  // fallback routine based on spherical quadrature
  vec normal_vector(field_type ft, const volume &v);

  /* Return c'th row of effective 1/(1+chi1) tensor in the given grid_volume v
     ... virtual so that e.g. libctl can override with more-efficient
     libctlgeom-based routines.  maxeval == 0 if no averaging desired. */
  virtual void eff_chi1inv_row(component c, double chi1inv_row[3],
			       const volume &v,
			       double tol=DEFAULT_SUBPIXEL_TOL,
			       int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);

  /* polarizability sigma function: return c'th row of tensor */
  virtual void sigma_row(component c, double sigrow[3], const vec &r) {
    (void) c; (void) r; sigrow[0] = sigrow[1] = sigrow[2] = 0.0;
  }

  // Nonlinear susceptibilities
  virtual bool has_chi3(component c) { (void)c; return false; }
  virtual double chi3(component c, const vec &r) { (void)c; (void)r; return 0.0; }
  virtual bool has_chi2(component c) { (void)c; return false; }
  virtual double chi2(component c, const vec &r) { (void)c; (void)r; return 0.0; }
};

class simple_material_function : public material_function {
  double (*f)(const vec &);

public:
  simple_material_function(double (*func)(const vec &)) { f = func; }

  virtual ~simple_material_function() {}

  virtual double chi1p1(field_type ft, const vec &r) { (void)ft; return f(r); }
  virtual double eps(const vec &r) { return f(r); }
  virtual double mu(const vec &r) { return f(r); }
  virtual double conductivity(component c, const vec &r) {
    (void)c; return f(r); }
  virtual void sigma_row(component c, double sigrow[3], const vec &r) {
    sigrow[0] = sigrow[1] = sigrow[2] = 0.0;
    sigrow[component_index(c)] = f(r);
  }
  virtual double chi3(component c, const vec &r) { (void)c; return f(r); }
  virtual double chi2(component c, const vec &r) { (void)c; return f(r); }
};

class structure;

class structure_chunk {
 public:
  double a, Courant, dt; // res. a, Courant num., and timestep dt=Courant/a
  realnum *chi3[NUM_FIELD_COMPONENTS], *chi2[NUM_FIELD_COMPONENTS];
  realnum *chi1inv[NUM_FIELD_COMPONENTS][5];
  bool trivial_chi1inv[NUM_FIELD_COMPONENTS][5];
  realnum *conductivity[NUM_FIELD_COMPONENTS][5];
  realnum *condinv[NUM_FIELD_COMPONENTS][5]; // cache of 1/(1+conduct*dt/2)
  bool condinv_stale; // true if condinv needs to be recomputed
  double *sig[5], *kap[5], *siginv[5]; // conductivity array for uPML
  int sigsize[5]; // conductivity array size
  grid_volume gv;  // integer grid_volume that could be bigger than non-overlapping v below
  volume v;
  susceptibility *chiP[NUM_FIELD_TYPES]; // only E_stuff and H_stuff are used

  int refcount; // reference count of objects using this structure_chunk

  ~structure_chunk();
  structure_chunk(const grid_volume &gv,
            const volume &vol_limit, double Courant, int proc_num);
  structure_chunk(const structure_chunk *);
  void set_chi1inv(component c, material_function &eps,
                   bool use_anisotropic_averaging,
		   double tol, int maxeval);
  bool has_chi(component c, direction d) const;
  bool has_chisigma(component c, direction d) const;
  bool has_chi1inv(component c, direction d) const;
  void set_conductivity(component c, material_function &eps);
  void update_condinv();
  void set_chi3(component c, material_function &eps);
  void set_chi2(component c, material_function &eps);
  void use_pml(direction, double dx, double boundary_loc,
	       double Rasymptotic, double mean_stretch,
	       pml_profile_func pml_profile, void *pml_profile_data,
	       double pml_profile_integral, double pml_profile_integral_u);

  void add_susceptibility(material_function &sigma, field_type ft,
			  const susceptibility &sus);

  void mix_with(const structure_chunk *, double);

  int n_proc() const { return the_proc; } // Says which proc owns me!
  int is_mine() const { return the_is_mine; }

  void remove_susceptibilities();

  // monitor.cpp
  double get_chi1inv(component, direction, const ivec &iloc) const;
  double get_inveps(component c, direction d, const ivec &iloc) const {
    return get_chi1inv(c, d, iloc); }
  double max_eps() const;
 private:
  double pml_fmin;
  int the_proc;
  int the_is_mine;
};

double pml_quadratic_profile(double, void*);

// linked list of descriptors for boundary regions (currently just for PML)
class boundary_region {
public:
  typedef enum { NOTHING_SPECIAL, PML } boundary_region_kind;

  boundary_region() :
    kind(NOTHING_SPECIAL), thickness(0.0), Rasymptotic(1e-16), mean_stretch(1.0), pml_profile(NULL), pml_profile_data(NULL), pml_profile_integral(1.0), pml_profile_integral_u(1.0), d(NO_DIRECTION), side(Low), next(0) {}
  boundary_region(boundary_region_kind kind, double thickness, double Rasymptotic, double mean_stretch, pml_profile_func pml_profile, void* pml_profile_data, double pml_profile_integral, double pml_profile_integral_u, direction d, boundary_side side, boundary_region *next = 0) : kind(kind), thickness(thickness), Rasymptotic(Rasymptotic), mean_stretch(mean_stretch), pml_profile(pml_profile), pml_profile_data(pml_profile_data), pml_profile_integral(pml_profile_integral), pml_profile_integral_u(pml_profile_integral_u), d(d), side(side), next(next) {}

  boundary_region(const boundary_region &r) : kind(r.kind), thickness(r.thickness), Rasymptotic(r.Rasymptotic), mean_stretch(r.mean_stretch), pml_profile(r.pml_profile), pml_profile_data(r.pml_profile_data), pml_profile_integral(r.pml_profile_integral), pml_profile_integral_u(r.pml_profile_integral_u), d(r.d), side(r.side) {
    next = r.next ? new boundary_region(*r.next) : 0;
  }

  ~boundary_region() { if (next) delete next; }

  void operator=(const boundary_region &r) {
    kind = r.kind; thickness = r.thickness; Rasymptotic = r.Rasymptotic; mean_stretch = r.mean_stretch;
    pml_profile = r.pml_profile; pml_profile_data = r.pml_profile_data;
    pml_profile_integral = r.pml_profile_integral;
    pml_profile_integral_u = r.pml_profile_integral_u;
    d = r.d; side = r.side;
    if (next) delete next;
    next = r.next ? new boundary_region(*r.next) : 0;
  }
  boundary_region operator+(const boundary_region &r0) const {
    boundary_region r(*this), *cur = &r;
    while (cur->next) cur = cur->next;
    cur->next = new boundary_region(r0);
    return r;
  }

  boundary_region operator*(double strength_mult) const {
    boundary_region r(*this), *cur = &r;
    while (cur) {
      cur->Rasymptotic = pow(cur->Rasymptotic, strength_mult);
      cur = cur->next;
    }
    return r;
  }

  void apply(structure *s) const;
  void apply(const structure *s, structure_chunk *sc) const;
  bool check_ok(const grid_volume &gv) const;

private:
  boundary_region_kind kind;
  double thickness, Rasymptotic, mean_stretch;
  pml_profile_func pml_profile;
  void *pml_profile_data;
  double pml_profile_integral, pml_profile_integral_u;
  direction d;
  boundary_side side;
  boundary_region *next;
};

boundary_region pml(double thickness, direction d, boundary_side side,
		    double Rasymptotic = 1e-15, double mean_stretch = 1.0);
boundary_region pml(double thickness, direction d,
		    double Rasymptotic = 1e-15, double mean_stretch = 1.0);
boundary_region pml(double thickness,
		    double Rasymptotic = 1e-15, double mean_stretch = 1.0);
#define no_pml() boundary_region()

class structure {
 public:
  structure_chunk **chunks;
  int num_chunks;
  bool shared_chunks; // whether modifications to chunks will be visible to fields objects
  grid_volume gv, user_volume;
  double a, Courant, dt; // res. a, Courant num., and timestep dt=Courant/a
  volume v;
  symmetry S;
  const char *outdir;
  grid_volume *effort_volumes;
  double *effort;
  int num_effort_volumes;

  ~structure();
  structure();
  structure(const grid_volume &gv, material_function &eps,
	    const boundary_region &br = boundary_region(),
	    const symmetry &s = meep::identity(),
	    int num_chunks = 0, double Courant = 0.5,
	    bool use_anisotropic_averaging=false,
	    double tol=DEFAULT_SUBPIXEL_TOL,
	    int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  structure(const grid_volume &gv, double eps(const vec &),
	    const boundary_region &br = boundary_region(),
	    const symmetry &s = meep::identity(),
	    int num_chunks = 0, double Courant = 0.5,
	    bool use_anisotropic_averaging=false,
	    double tol=DEFAULT_SUBPIXEL_TOL,
	    int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  structure(const structure *);
  structure(const structure &);

  void set_materials(material_function &mat,
		     bool use_anisotropic_averaging=true,
		     double tol=DEFAULT_SUBPIXEL_TOL,
		     int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_chi1inv(component c, material_function &eps,
                   bool use_anisotropic_averaging=true,
		   double tol=DEFAULT_SUBPIXEL_TOL,
		   int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  bool has_chi(component c, direction d) const;
  void set_epsilon(material_function &eps,
                   bool use_anisotropic_averaging=true,
		   double tol=DEFAULT_SUBPIXEL_TOL,
		   int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_epsilon(double eps(const vec &),
                   bool use_anisotropic_averaging=true,
		   double tol=DEFAULT_SUBPIXEL_TOL,
		   int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_mu(material_function &eps,
	      bool use_anisotropic_averaging=true,
	      double tol=DEFAULT_SUBPIXEL_TOL,
	      int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_mu(double mu(const vec &),
	      bool use_anisotropic_averaging=true,
	      double tol=DEFAULT_SUBPIXEL_TOL,
	      int maxeval=DEFAULT_SUBPIXEL_MAXEVAL);
  void set_conductivity(component c, material_function &conductivity);
  void set_conductivity(component C, double conductivity(const vec &));
  void set_chi3(component c, material_function &eps);
  void set_chi3(material_function &eps);
  void set_chi3(double eps(const vec &));
  void set_chi2(component c, material_function &eps);
  void set_chi2(material_function &eps);
  void set_chi2(double eps(const vec &));

  void add_susceptibility(double sigma(const vec &), field_type c, const susceptibility &sus);
  void add_susceptibility(material_function &sigma, field_type c, const susceptibility &sus);
  void remove_susceptibilities();

  void set_output_directory(const char *name);
  void mix_with(const structure *, double);

  bool equal_layout(const structure &) const;
  void print_layout(void) const;

  // structure_dump.cpp
  void dump(const char *filename);
  void load(const char *filename);

  // monitor.cpp
  double get_chi1inv(component, direction, const ivec &origloc) const;
  double get_chi1inv(component, direction, const vec &loc) const;
  double get_inveps(component c, direction d, const ivec &origloc) const {
    return get_chi1inv(c, d, origloc); }
  double get_inveps(component c, direction d, const vec &loc) const {
    return get_chi1inv(c, d, loc); }
  double get_eps(const vec &loc) const;
  double get_mu(const vec &loc) const;
  double max_eps() const;

  friend class boundary_region;

 private:
  void use_pml(direction d, boundary_side b, double dx);
  void add_to_effort_volumes(const grid_volume &new_effort_volume,
			     double extra_effort);
  void choose_chunkdivision(const grid_volume &gv, int num_chunks,
			     const boundary_region &br, const symmetry &s);
  void check_chunks();
  void changing_chunks();
  // Helper methods for dumping and loading susceptibilities
  void set_chiP_from_file(h5file *file, const char *dataset, field_type ft);
  void write_susceptibility_params(h5file *file, const char *dname, int EorH);
};

class src_vol;
class fields;
class fields_chunk;
class flux_vol;

// Time-dependence of a current source, intended to be overridden by
// subclasses.  current() and dipole() are be related by
// current = d(dipole)/dt (or rather, the finite-difference equivalent).
class src_time {
 public:
  // the following variable specifies whether the current
  // source is specified as a current or as an integrated
  // current (a dipole moment), if possible.  In the original Meep,
  // by default electric sources are integrated and magnetic
  // sources are not, but this may change.
  bool is_integrated;

  src_time() { is_integrated = true; current_time = nan; current_current = 0.0; next = NULL; }
  virtual ~src_time() { delete next; }
  src_time(const src_time &t) {
       is_integrated = t.is_integrated;
       current_time = t.current_time;
       current_current = t.current_current;
       current_dipole = t.current_dipole;
       if (t.next) next = t.next->clone(); else next = NULL;
  }

  std::complex<double> dipole() const { return current_dipole; }
  std::complex<double> current() const { return current_current; }
  void update(double time, double dt) {
    if (time != current_time) {
      current_dipole = dipole(time);
      current_current = current(time, dt);
      current_time = time;
    }
  }

  // subclasses *can* override this method in order to specify the
  // current directly rather than as the derivative of dipole.
  // in that case you would probably ignore the dt argument.
  virtual std::complex<double> current(double time, double dt) const {
    return ((dipole(time + dt) - dipole(time)) / dt);
  }

  double last_time_max() { return last_time_max(0.0); }
  double last_time_max(double after);

  src_time *add_to(src_time *others, src_time **added) const;
  src_time *next;

  // subclasses should override these methods:
  virtual std::complex<double> dipole(double time) const { (void)time; return 0; }
  virtual double last_time() const { return 0.0; }
  virtual src_time *clone() const { return new src_time(*this); }
  virtual bool is_equal(const src_time &t) const { (void)t; return 1; }
  virtual std::complex<double> frequency() const { return 0.0; }
  virtual void set_frequency(std::complex<double> f) { (void) f; }

 private:
  double current_time;
  std::complex<double> current_dipole, current_current;
};

bool src_times_equal(const src_time &t1, const src_time &t2);

// Gaussian-envelope source with given frequency, width, peak-time, cutoff
class gaussian_src_time : public src_time {
 public:
  gaussian_src_time(double f, double fwidth, double s = 5.0);
  gaussian_src_time(double f, double w, double start_time, double end_time);
  virtual ~gaussian_src_time() {}

  virtual std::complex<double> dipole(double time) const;
  virtual double last_time() const { return float(peak_time + cutoff); };
  virtual src_time *clone() const { return new gaussian_src_time(*this); }
  virtual bool is_equal(const src_time &t) const;
  virtual std::complex<double> frequency() const { return freq; }
  virtual void set_frequency(std::complex<double> f) { freq = real(f); }

 private:
  double freq, width, peak_time, cutoff;
};

// Continuous (CW) source with (optional) slow turn-on and/or turn-off.
class continuous_src_time : public src_time {
 public:
  continuous_src_time(std::complex<double> f, double w = 0.0,
		      double st = 0.0, double et = infinity,
		      double s = 3.0) : freq(f), width(w), start_time(float(st)),
					end_time(float(et)), slowness(s) {}
  virtual ~continuous_src_time() {}

  virtual std::complex<double> dipole(double time) const;
  virtual double last_time() const { return end_time; };
  virtual src_time *clone() const { return new continuous_src_time(*this); }
  virtual bool is_equal(const src_time &t) const;
  virtual std::complex<double> frequency() const { return freq; }
  virtual void set_frequency(std::complex<double> f) { freq = f; }

 private:
  std::complex<double> freq;
  double width, start_time, end_time, slowness;
};

// user-specified source function with start and end times
class custom_src_time : public src_time {
 public:
  custom_src_time(std::complex<double> (*func)(double t, void *), void *data,
		  double st = -infinity, double et = infinity)
    : func(func), data(data), start_time(float(st)), end_time(float(et)) {}
  virtual ~custom_src_time() {}

  virtual std::complex<double> current(double time, double dt) const {
    if (is_integrated) return src_time::current(time,dt);
    else return dipole(time);
  }
  virtual std::complex<double> dipole(double time) const { float rtime = float(time);
    if (rtime >= start_time && rtime <= end_time) return func(time,data); else return 0.0; }
  virtual double last_time() const { return end_time; };
  virtual src_time *clone() const { return new custom_src_time(*this); }
  virtual bool is_equal(const src_time &t) const;

 private:
  std::complex<double> (*func)(double t, void *);
  void *data;
  double start_time, end_time;
};

class monitor_point {
 public:
  monitor_point();
  ~monitor_point();
  vec loc;
  double t;
  std::complex<double> f[NUM_FIELD_COMPONENTS];
  monitor_point *next;

  std::complex<double> get_component(component);
  double poynting_in_direction(direction d);
  double poynting_in_direction(vec direction_v);

  // When called with only its first four arguments, fourier_transform
  // performs an FFT on its monitor points, putting the frequencies in f
  // and the amplitudes in a.  Yes, the frequencies are trivial and
  // redundant, but this saves you the risk of making a mistake in
  // converting your units.  Note also, that in this case f is always a
  // real number, although it's stored in a complex.
  //
  // Note that in either case, fourier_transform assumes that the monitor
  // points are all equally spaced in time.
  void fourier_transform(component w,
                         std::complex<double> **a, std::complex<double> **f, int *numout,
                         double fmin=0.0, double fmax=0.0, int maxbands=100);
  // harminv works much like fourier_transform, except that it is not yet
  // implemented.
  void harminv(component w,
               std::complex<double> **a, std::complex<double> **f,
               int *numout, double fmin, double fmax,
               int maxbands);
};

// dft.cpp
// this should normally only be created with fields::add_dft
class dft_chunk {
public:
  dft_chunk(fields_chunk *fc_,
	    ivec is_, ivec ie_,
	    vec s0_, vec s1_, vec e0_, vec e1_,
	    double dV0_, double dV1_,
	    component c_, bool use_centered_grid,
            std::complex<double> phase_factor,
            ivec shift_, const symmetry &S_, int sn_,
	    const void *data_);
  ~dft_chunk();

  void update_dft(double time);

  void scale_dft(std::complex<double> scale);

  // chunk-by-chunk helper routine called by
  // fields::process_dft_component
  std::complex<double> process_dft_component(int rank, direction *ds,
                                             ivec min_corner, ivec max_corner,
                                             int num_freq,
                                             h5file *file, double *buffer,
                                             int reim,
                                             std::complex<double> *field_array,
                                             void *mode1_data, void *mode2_data,
                                             component c_conjugate);

  void operator-=(const dft_chunk &chunk);

  // the frequencies to loop_in_chunks
  double omega_min, domega;
  int Nomega;

  component c; // component to DFT (possibly transformed by symmetry)

  size_t N; // number of spatial points (on epsilon grid)
  std::complex<realnum> *dft; // N x Nomega array of DFT values.

  class dft_chunk *next_in_chunk; // per-fields_chunk list of DFT chunks
  class dft_chunk *next_in_dft; // next for this particular DFT vol./component

  /* There are several types of weight factors associated with DFT fields: */
  /*  (a) To accelerate the computation of things like Poynting flux, it   */
  /*      is convenient to store certain DFT field components with built-in*/
  /*      constant prefactors (usually just \pm 1). For example, in a      */
  /*      dft_flux_plane normal to the Z direction the Ey component is     */
  /*      stored with a built-in minus sign, while the other components    */
  /*      (Ex, Hx, Hy) are not. This factor is already included in the     */
  /*      `scale` field, but we also need to keep track of it separately   */
  /*      so we can divide it out when looking up the values of individual */
  /*      DFT field components. So we store it as `stored_weight.`         */
  /*                                                                       */
  /*  (b) For similar reasons, it is convenient to store certain DFT field */
  /*      components with built-in volume factors to accelerate numerical  */
  /*      integrations. In this case the prefactor is not constant (it     */
  /*      varies from grid point to grid point) so we can't store it in    */
  /*      the dft_chunk structure like stored_weight; instead we store a   */
  /*      flag to indicate that it is present in the stored field          */
  /*      components. This is the include_dV_and_interp_weights flag.      */
  /*      (The sqrt_dV_and_interp_weights flag indicates that the sqrt of  */
  /*      the volume factor is stored instead.)                            */
  /*                                                                       */
  /*  (c) When computing things like -0.5*|E|^2 for the stress tensor, we  */
  /*      we cannot incorporate the minus sign into the scale factor       */
  /*      because we only ever compute |scale|^2. Thus, it is necessary    */
  /*      to store an additional weight factor with the dft_chunk to record*/
  /*      any additional negative or complex weight factor to be used in   */
  /*      in computations involving the fourier-transformed fields. This   */
  /*      is the extra_weight field. Because it is used in computations    */
  /*       involving dft[...], it needs to be public.                      */
  std::complex<double > stored_weight;
  bool include_dV_and_interp_weights;
  bool sqrt_dV_and_interp_weights;
  std::complex<double> extra_weight;

  // parameters passed from field_integrate:
  fields_chunk *fc;
  ivec is, ie;
  vec s0, s1, e0, e1;
  double dV0, dV1;
  std::complex<double> scale; // scale factor * phase from shift and symmetry
  ivec shift;
  symmetry S; int sn;

  // cache of exp(iwt) * scale, of length Nomega
  std::complex<realnum> *dft_phase;

  ptrdiff_t avg1, avg2; // index offsets for average to get epsilon grid

  int vc; // component descriptor from the original volume
};

void save_dft_hdf5(dft_chunk *dft_chunks, component c, h5file *file,
		   const char *dprefix = 0);
void load_dft_hdf5(dft_chunk *dft_chunks, component c, h5file *file,
		   const char *dprefix = 0);
void save_dft_hdf5(dft_chunk *dft_chunks, const char *name, h5file *file,
		   const char *dprefix = 0);
void load_dft_hdf5(dft_chunk *dft_chunks, const char *name, h5file *file,
		   const char *dprefix = 0);

// dft.cpp (normally created with fields::add_dft_flux)
class dft_flux {
public:
  dft_flux(const component cE_, const component cH_,
	   dft_chunk *E_, dft_chunk *H_,
	   double fmin, double fmax, int Nf,
	   const volume &where_, direction normal_direction_,
	   bool use_symmetry_);
  dft_flux(const dft_flux &f);

  double *flux();

  void save_hdf5(h5file *file, const char *dprefix = 0);
  void load_hdf5(h5file *file, const char *dprefix = 0);

  void operator-=(const dft_flux &fl) { if (E && fl.E) *E -= *fl.E; if (H && fl.H) *H -= *fl.H; }

  void save_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);
  void load_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);

  void scale_dfts(std::complex<double> scale);

  void remove();

  double freq_min, dfreq;
  int Nfreq;
  dft_chunk *E, *H;
  component cE, cH;
  volume where;
  direction normal_direction;
  bool use_symmetry;
};

// stress.cpp (normally created with fields::add_dft_force)
class dft_force {
public:
  dft_force(dft_chunk *offdiag1_, dft_chunk *offdiag2_, dft_chunk *diag_,
	    double fmin, double fmax, int Nf, const volume &where_);
  dft_force(const dft_force &f);

  double *force();

  void save_hdf5(h5file *file, const char *dprefix = 0);
  void load_hdf5(h5file *file, const char *dprefix = 0);

  void operator-=(const dft_force &fl);

  void save_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);
  void load_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);

  void scale_dfts(std::complex<double> scale);

  void remove();

  double freq_min, dfreq;
  int Nfreq;
  dft_chunk *offdiag1, *offdiag2, *diag;
  volume where;
};

// near2far.cpp (normally created with fields::add_dft_near2far)
class dft_near2far {
public:
  /* fourier tranforms of tangential E and H field components in a
     medium with the given scalar eps and mu */
  dft_near2far(dft_chunk *F,
               double fmin, double fmax, int Nf,
               double eps, double mu, const volume &where_);
  dft_near2far(const dft_near2far &f);

  /* return an array (Ex,Ey,Ez,Hx,Hy,Hz) x Nfreq of the far fields at x */
  std::complex<double> *farfield(const vec &x);

  /* like farfield, but requires F to be Nfreq*6 preallocated array, and
     does *not* perform the reduction over processes...an MPI allreduce
     summation by the caller is required to get the final result ... used
     by other output routine to efficiently get far field on a grid of pts */
  void farfield_lowlevel(std::complex<double> *F, const vec &x);

  /* output far fields on a grid to an HDF5 file */
  void save_farfields(const char *fname, const char *prefix,
                      const volume &where, double resolution);

  void save_hdf5(h5file *file, const char *dprefix = 0);
  void load_hdf5(h5file *file, const char *dprefix = 0);

  void operator-=(const dft_near2far &fl);

  void save_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);
  void load_hdf5(fields &f, const char *fname, const char *dprefix = 0,
		 const char *prefix = 0);

  void scale_dfts(std::complex<double> scale);

  void remove();

  double freq_min, dfreq;
  int Nfreq;
  dft_chunk *F;
  double eps, mu;
  volume where;
};

/* Class to compute local-density-of-states spectra: the power spectrum
   P(omega) of the work done by the sources.  Specialized to handle only
   the case where all sources have the same time dependence, which greatly
   simplifies things because then we can do the spatial integral of E*J
   *first* and then do the Fourier transform, eliminating the need to
   store the Fourier transform per point or per current. */
class dft_ldos {
public:
  dft_ldos(double freq_min, double freq_max, int Nfreq);
  ~dft_ldos() { delete[] Fdft; delete[] Jdft; }

  void update(fields &f); // to be called after each timestep
  double *ldos() const; // returns array of Nomega values (after last timestep)
  std::complex<double> *F() const; // returns Fdft
  std::complex<double> *J() const; // returns Jdft

private:
  std::complex<realnum> *Fdft; // Nomega array of field * J*(x) DFT values
  std::complex<realnum> *Jdft; // Nomega array of J(t) DFT values
  double Jsum; // sum of |J| over all points
public:
  double omega_min, domega;
  int Nomega;
};

// dft.cpp (normally created with fields::add_dft_fields)
class dft_fields{
public:
  dft_fields(dft_chunk *chunks, double freq_min, double freq_max, int Nfreq, const volume &where);

  void scale_dfts(std::complex<double> scale);

  void remove();

  double freq_min, dfreq;
  int Nfreq;
  dft_chunk *chunks;
  volume where;
};

enum in_or_out { Incoming=0, Outgoing };
enum connect_phase { CONNECT_PHASE = 0, CONNECT_NEGATE=1, CONNECT_COPY=2 };

// data for each susceptibility
typedef struct polarization_state_s {
  void *data; // internal polarization data for the susceptibility
  const susceptibility *s;
  struct polarization_state_s *next; // linked list
} polarization_state;

class fields_chunk {
 public:
  realnum *f[NUM_FIELD_COMPONENTS][2]; // fields at current time

  // auxiliary fields needed for PML (at least in some components)
  realnum *f_u[NUM_FIELD_COMPONENTS][2]; // integrated from D/B
  realnum *f_w[NUM_FIELD_COMPONENTS][2]; // E/H integrated from these
  realnum *f_cond[NUM_FIELD_COMPONENTS][2]; // aux field for PML+conductivity

  /* sometimes, to synchronize the E and H fields, e.g. for computing
     flux at a given time, we need to timestep H by 1/2; in this case
     we save backup copies of (some of) the fields to resume timestepping */
  realnum *f_backup[NUM_FIELD_COMPONENTS][2];
  realnum *f_u_backup[NUM_FIELD_COMPONENTS][2];
  realnum *f_w_backup[NUM_FIELD_COMPONENTS][2];
  realnum *f_cond_backup[NUM_FIELD_COMPONENTS][2];

  // W (or E/H) field from prev. timestep, only stored if needed by update_pols
  realnum *f_w_prev[NUM_FIELD_COMPONENTS][2];

  // used to store D-P and B-P, e.g. when P implements dispersive media
  realnum *f_minus_p[NUM_FIELD_COMPONENTS][2];

  realnum *f_rderiv_int; // cache of helper field for 1/r d(rf)/dr derivative

  dft_chunk *dft_chunks;

  realnum **zeroes[NUM_FIELD_TYPES]; // Holds pointers to metal points.
  size_t num_zeroes[NUM_FIELD_TYPES];
  realnum **connections[NUM_FIELD_TYPES][CONNECT_COPY+1][Outgoing+1];
  size_t num_connections[NUM_FIELD_TYPES][CONNECT_COPY+1][Outgoing+1];
  std::complex<realnum> *connection_phases[NUM_FIELD_TYPES];

  int npol[NUM_FIELD_TYPES]; // only E_stuff and H_stuff are used
  polarization_state *pol[NUM_FIELD_TYPES]; // array of npol[i] polarization_state structures

  double a, Courant, dt; // res. a, Courant num., and timestep dt=Courant/a
  grid_volume gv;
  volume v;
  double m; // angular dependence in cyl. coords
  bool zero_fields_near_cylorigin; // fields=0 m pixels near r=0 for stability
  double beta;
  int is_real;
  src_vol *sources[NUM_FIELD_TYPES];
  structure_chunk *new_s;
  structure_chunk *s;
  const char *outdir;

  fields_chunk(structure_chunk *, const char *outdir, double m,
	       double beta, bool zero_fields_near_cylorigin);

  fields_chunk(const fields_chunk &);
  ~fields_chunk();

  // step.cpp
  double peek_field(component, const vec &);

  void use_real_fields();
  bool have_component(component c, bool is_complex = false) {
    switch (c) {
    case Dielectric: case Permeability:
      return !is_complex;
    default:
      return (f[c][0] && f[c][is_complex]);
    }
  }

  double last_source_time();
  // monitor.cpp
  std::complex<double> get_field(component, const ivec &) const;

  // for non-collective interpolation:
  volume get_field_gv(component) const;
  std::complex<double> get_field(component, const vec &) const;

  double get_chi1inv(component, direction, const ivec &iloc) const;

  void backup_component(component c);
  void average_with_backup(component c);
  void restore_component(component c);

  void set_output_directory(const char *name);
  void verbose(int gv=1) { verbosity = gv; }

  double count_volume(component);
  friend class fields;

  int n_proc() const { return s->n_proc(); };
  int is_mine() const { return s->is_mine(); };
  // boundaries.cpp
  void zero_metal(field_type);
  bool needs_W_notowned(component c);
  // fields.cpp
  void remove_sources();
  void remove_susceptibilities(bool shared_chunks);
  void zero_fields();

  // update_eh.cpp
  bool needs_W_prev(component c) const;
  bool update_eh(field_type ft, bool skip_w_components = false);

  bool alloc_f(component c);
  void figure_out_step_plan();

  void set_solve_cw_omega(std::complex<double> omega) {
    doing_solve_cw = true;
    solve_cw_omega = omega;
  }
  void unset_solve_cw_omega() {
    doing_solve_cw = false;
    solve_cw_omega = 0.0;
  }

 private:
  // we set a flag during cw_solve to replace some
  // time-dependent stuff with the analogous frequency-domain operation
  bool doing_solve_cw; // true when inside solve_cw
  std::complex<double> solve_cw_omega; // current omega for solve_cw

  int verbosity; // Turn on verbosity for debugging purposes...
  // fields.cpp
  bool have_plus_deriv[NUM_FIELD_COMPONENTS], have_minus_deriv[NUM_FIELD_COMPONENTS];
  component plus_component[NUM_FIELD_COMPONENTS], minus_component[NUM_FIELD_COMPONENTS];
  direction plus_deriv_direction[NUM_FIELD_COMPONENTS],
            minus_deriv_direction[NUM_FIELD_COMPONENTS];
  // step.cpp
  void phase_in_material(structure_chunk *s);
  void phase_material(int phasein_time);
  bool step_db(field_type ft);
  void step_source(field_type ft, bool including_integrated);
  bool update_pols(field_type ft);
  void calc_sources(double time);

  // initialize.cpp
  void initialize_field(component, std::complex<double> f(const vec &));
  void initialize_with_nth_te(int n, double kz);
  void initialize_with_nth_tm(int n, double kz);
  // boundaries.cpp
  void alloc_extra_connections(field_type, connect_phase, in_or_out, size_t);
  // dft.cpp
  void update_dfts(double timeE, double timeH);

  void changing_structure();
};

enum boundary_condition { Periodic=0, Metallic, Magnetic, None };
enum time_sink { Connecting, Stepping, Boundaries, MpiTime,
                 FieldOutput, FourierTransforming, Other };

typedef void (*field_chunkloop)(fields_chunk *fc, int ichunk, component cgrid,
				ivec is, ivec ie,
				vec s0, vec s1, vec e0, vec e1,
				double dV0, double dV1,
				ivec shift, std::complex<double> shift_phase,
				const symmetry &S, int sn,
				void *chunkloop_data);
typedef std::complex<double> (*field_function)(const std::complex<double> *fields,
					   const vec &loc,
					   void *integrand_data_);
typedef double (*field_rfunction)(const std::complex<double> *fields,
				   const vec &loc,
				   void *integrand_data_);

field_rfunction derived_component_func(derived_component c, const grid_volume &gv,
				       int &nfields, component cs[12]);

/* A utility class for loop_in_chunks, for fetching values of field
   components at grid points, accounting for the complications
   of symmetry and yee-grid averaging. */
class chunkloop_field_components {
 private:
  fields_chunk *fc;
  std::vector<component> parent_components;
  std::vector< std::complex<double> > phases;
  std::vector<ptrdiff_t> offsets;
 public:
  chunkloop_field_components(fields_chunk *fc, component cgrid,
                             std::complex<double> shift_phase,
                             const symmetry &S, int sn,
                             int num_fields, const component *components);
#if __cplusplus >= 201103L // delegating constructors are a C++11 feature
  chunkloop_field_components(fields_chunk *fc, component cgrid,
                             std::complex<double> shift_phase,
                             const symmetry &S, int sn,
                             std::vector <component> components) :
    chunkloop_field_components(fc, cgrid, shift_phase, S, sn, components.size(), components.data()) {}
#endif
  void update_values(ptrdiff_t idx);
  std::vector< std::complex<double> > values; // updated by update_values(idx)
 };

/***************************************************************/
/* prototype for optional user-supplied function to provide an */
/* initial estimate of the wavevector of mode #mode at         */
/* frequency freq for eigenmode calculations                   */
/***************************************************************/
typedef vec (*kpoint_func)(double freq, int mode, void *user_data);

class fields {
 public:
  int num_chunks;
  bool shared_chunks;
  fields_chunk **chunks;
  src_time *sources;
  flux_vol *fluxes;
  symmetry S;

  // The following is an array that is num_chunks by num_chunks.  Actually
  // it is two arrays, one for the imaginary and one for the real part.
  realnum **comm_blocks[NUM_FIELD_TYPES];
  // This is the same size as each comm_blocks array, and store the sizes
  // of the comm blocks themselves for each connection-phase type
  size_t *comm_sizes[NUM_FIELD_TYPES][CONNECT_COPY+1];
  size_t comm_size_tot(int f, int pair) const {
    size_t sum = 0; for (int ip=0; ip<3; ++ip) sum+=comm_sizes[f][ip][pair];
    return sum;
  }

  double a, dt; // The resolution a and timestep dt=Courant/a
  grid_volume gv, user_volume;
  volume v;
  double m;
  double beta;
  int t, phasein_time, is_real;
  std::complex<double> k[5], eikna[5];
  double coskna[5], sinkna[5];
  boundary_condition boundaries[2][5];
  char *outdir;
  bool components_allocated;

  // fields.cpp methods:
  fields(structure *, double m=0, double beta=0,
	 bool zero_fields_near_cylorigin=true);
  fields(const fields &);
  ~fields();
  bool equal_layout(const fields &f) const;
  void use_real_fields();
  void zero_fields();
  void remove_sources();
  void remove_susceptibilities();
  void remove_fluxes();
  void reset();

  // time.cpp
  double time_spent_on(time_sink);
  void print_times();
  // boundaries.cpp
  void set_boundary(boundary_side,direction,boundary_condition);
  void use_bloch(direction d, double k) { use_bloch(d, (std::complex<double>) k); }
  void use_bloch(direction, std::complex<double> kz);
  void use_bloch(const vec &k);
  vec lattice_vector(direction) const;
  // update_eh.cpp
  void update_eh(field_type ft, bool skip_w_components = false);

  volume total_volume(void) const;

  // h5fields.cpp:
  // low-level function:
  void output_hdf5(h5file *file, const char *dataname,
		   int num_fields, const component *components,
		   field_function fun, void *fun_data_, int reim,
		   const volume &where,
		   bool append_data = false,
		   bool single_precision = false);
  // higher-level functions
  void output_hdf5(const char *dataname,  // OUTPUT COMPLEX-VALUED FUNCTION
		   int num_fields, const component *components,
		   field_function fun, void *fun_data_,
		   const volume &where,
		   h5file *file = 0,
		   bool append_data = false,
		   bool single_precision = false,
		   const char *prefix = 0,
		   bool real_part_only = false);
  void output_hdf5(const char *dataname,  // OUTPUT REAL-VALUED FUNCTION
		   int num_fields, const component *components,
		   field_rfunction fun, void *fun_data_,
		   const volume &where,
		   h5file *file = 0,
		   bool append_data = false,
		   bool single_precision = false,
		   const char *prefix = 0);
  void output_hdf5(component c,   // OUTPUT FIELD COMPONENT (or Dielectric)
		   const volume &where,
		   h5file *file = 0,
		   bool append_data = false,
		   bool single_precision = false,
		   const char *prefix = 0);
  void output_hdf5(derived_component c,   // OUTPUT DERIVED FIELD COMPONENT
		   const volume &where,
		   h5file *file = 0,
		   bool append_data = false,
		   bool single_precision = false,
		   const char *prefix = 0);
  h5file *open_h5file(const char *name,
		      h5file::access_mode mode = h5file::WRITE,
		      const char *prefix = NULL, bool timestamp = false);
  const char *h5file_name(const char *name,
			  const char *prefix = NULL, bool timestamp = false);

  // array_slice.cpp methods

  // given a subvolume, compute the dimensions of the array slice
  // needed to store field data for that subvolume.
  // the data parameter is used internally in get_array_slice
  // and should be ignored by external callers.
  int get_array_slice_dimensions(const volume &where, size_t dims[3], void *data=0);

  // given a subvolume, return a column-major array containing
  // the given function of the field components in that subvolume
  // if slice is non-null, it must be a user-allocated buffer
  // of the correct size.
  // otherwise, a new buffer is allocated and returned; it
  // must eventually be caller-deallocated via delete[].
  double *get_array_slice(const volume &where,
                          std::vector<component> components,
                          field_rfunction rfun, void *fun_data,
                          double *slice=0);

  std::complex<double> *get_complex_array_slice(const volume &where,
                                   std::vector<component> components,
                                   field_function fun,
                                   void *fun_data,
                                   std::complex<double> *slice=0);

  // alternative entry points for when you have no field
  // function, i.e. you want just a single component or
  // derived component.)
  double *get_array_slice(const volume &where, component c, double *slice=0);
  double *get_array_slice(const volume &where, derived_component c, double *slice=0);
  std::complex<double> *get_complex_array_slice(const volume &where,
                                                component c,
                                                std::complex<double> *slice=0);

  // master routine for all above entry points
  void *do_get_array_slice(const volume &where,
                           std::vector<component> components,
                           field_function fun,
                           field_rfunction rfun,
                           void *fun_data,
                           void *vslice);

  // step.cpp methods:
  double last_step_output_wall_time;
  int last_step_output_t;
  void step();

  // when comparing times, e.g. for source cutoffs, it
  // is useful to round to float to avoid gratuitous sensitivity
  // to floating-point roundoff error
  inline double round_time() const { return float(t*dt); };
  inline double time() const { return t*dt; };

  // cw_fields.cpp:
  bool solve_cw(double tol, int maxiters, std::complex<double> frequency, int L=2);
  bool solve_cw(double tol = 1e-8, int maxiters = 10000, int L=2);

  // sources.cpp:
  double last_source_time();
  void add_point_source(component c, double freq, double width, double peaktime,
                        double cutoff, const vec &, std::complex<double> amp = 1.0,
                        int is_continuous = 0);
  void add_point_source(component c, const src_time &src,
                        const vec &, std::complex<double> amp = 1.0);
  void add_volume_source(component c, const src_time &src, const volume &where_,
                         std::complex<double> *arr, size_t dim1, size_t dim2, size_t dim3,
                         std::complex<double> amp);
  void add_volume_source(component c, const src_time &src,
                         const volume &where_, const char *filename,
                         const char *dataset, std::complex<double> amp);
  void add_volume_source(component c, const src_time &src,
			 const volume &,
			 std::complex<double> A(const vec &),
			 std::complex<double> amp = 1.0);
  void add_volume_source(component c, const src_time &src,
			 const volume &,
			 std::complex<double> amp = 1.0);
  void require_component(component c);

  // mpb.cpp

  // the return value of get_eigenmode is an opaque pointer
  // that can be passed to eigenmode_amplitude() to get
  // values of field components at arbitrary points in space.
  // call destroy_eigenmode_data() to deallocate it when finished.
  void *get_eigenmode(double omega_src, direction d, const volume where,
                      const volume eig_vol, int band_num,
                      const vec &kpoint, bool match_frequency,
                      int parity, double resolution,
                      double eigensolver_tol, bool verbose=false, double *kdom=0);

  void add_eigenmode_source(component c, const src_time &src,
	  		    direction d, const volume &where,
			    const volume &eig_vol,
			    int band_num,
			    const vec &kpoint, bool match_frequency,
			    int parity,
			    double eig_resolution, double eigensolver_tol,
			    std::complex<double> amp,
			    std::complex<double> A(const vec &) = 0);

  void get_eigenmode_coefficients(dft_flux flux, const volume &eig_vol,
                                  int *bands, int num_bands, int parity,
                                  double eig_resolution, double eigensolver_tol,
                                  std::complex<double> *coeffs, double *vgrp,
                                  kpoint_func user_kpoint_func=0, void *user_kpoint_data=0,
                                  vec *kpoints=0, vec *kdom=0, bool verbose=false);


  // initialize.cpp:
  void initialize_field(component, std::complex<double> f(const vec &));
  void initialize_with_nth_te(int n);
  void initialize_with_nth_tm(int n);
  void initialize_with_n_te(int ntot);
  void initialize_with_n_tm(int ntot);
  int phase_in_material(const structure *s, double time);
  int is_phasing();

  // loop_in_chunks.cpp
  void loop_in_chunks(field_chunkloop chunkloop, void *chunkloop_data,
		      const volume &where,
		      component cgrid = Centered,
		      bool use_symmetry = true,
		      bool snap_unit_dims = false);

  // integrate.cpp
  std::complex<double> integrate(int num_fields, const component *components,
			    field_function fun, void *fun_data_,
			    const volume &where,
			    double *maxabs = 0);
  double integrate(int num_fields, const component *components,
		   field_rfunction fun, void *fun_data_,
		   const volume &where,
		   double *maxabs = 0);
  std::complex<double> integrate2(const fields &fields2,
			     int num_fields1,
			     const component *components1,
			     int num_fields2,
			     const component *components2,
			     field_function integrand,
			     void *integrand_data_,
			     const volume &where,
			     double *maxabs = 0);
  double integrate2(const fields &fields2,
		    int num_fields1, const component *components1,
		    int num_fields2, const component *components2,
		    field_rfunction integrand,
		    void *integrand_data_,
		    const volume &where,
		    double *maxabs = 0);


  double max_abs(int num_fields, const component *components,
		 field_function fun, void *fun_data_,
		 const volume &where);
  double max_abs(int num_fields, const component *components,
		 field_rfunction fun, void *fun_data_,
		 const volume &where);

  double max_abs(int c, const volume &where);
  double max_abs(component c, const volume &where);
  double max_abs(derived_component c, const volume &where);

  // dft.cpp
  dft_chunk *add_dft(component c, const volume &where,
		     double freq_min, double freq_max, int Nfreq,
		     bool include_dV_and_interp_weights = true,
		     std::complex<double> stored_weight = 1.0,
                     dft_chunk *chunk_next = 0,
		     bool sqrt_dV_and_interp_weights = false,
		     std::complex<double> extra_weight = 1.0,
		     bool use_centered_grid = true, int vc = 0);
  dft_chunk *add_dft_pt(component c, const vec &where,
			double freq_min, double freq_max, int Nfreq);
  dft_chunk *add_dft(const volume_list *where,
		     double freq_min, double freq_max, int Nfreq,
		     bool include_dV = true);
  void update_dfts();
  dft_flux add_dft_flux(const volume_list *where,
			double freq_min, double freq_max, int Nfreq, bool use_symmetry=true);
  dft_flux add_dft_flux(direction d, const volume &where,
			double freq_min, double freq_max, int Nfreq, bool use_symmetry=true);
  dft_flux add_dft_flux_box(const volume &where,
			    double freq_min, double freq_max, int Nfreq);
  dft_flux add_dft_flux_plane(const volume &where,
			      double freq_min, double freq_max, int Nfreq);

  // a "mode monitor" is just a dft_flux with symmetry reduction turned off.
  dft_flux add_mode_monitor(direction d, const volume &where,
                            double freq_min, double freq_max, int Nfreq);

  dft_fields add_dft_fields(component *components, int num_components,
                            const volume where,
                            double freq_min, double freq_max, int Nfreq);

  /********************************************************/
  /* process_dft_component is an intermediate-level       */
  /* routine that serves as a common back end for several */
  /* operations involving DFT fields (specifically,       */
  /* writing DFT fields to HDF5 files, fetching arrays    */
  /* of DFT fields, and  evaluating overlap integrals     */
  /* flux and mode fields.)                               */
  /********************************************************/
  std::complex<double> process_dft_component(dft_chunk **chunklists,
                                             int num_chunklists,
                                             int num_freq, component c,
                                             const char *HDF5FileName,
                                             std::complex<double> **field_array=0,
                                             int *rank=0, int *dims=0,
                                             void *mode1_data=0,
                                             void *mode2_data=0,
                                             component c_conjugate=Ex,
                                             bool *first_component=0);

  // output DFT fields to HDF5 file
  void output_dft_components(dft_chunk **chunklists, int num_chunklists,
                             volume dft_volume, const char *HDF5FileName);

  void output_dft(dft_flux flux, const char *HDF5FileName);
  void output_dft(dft_force force, const char *HDF5FileName);
  void output_dft(dft_near2far n2f, const char *HDF5FileName);
  void output_dft(dft_fields fdft, const char *HDF5FileName);
  void output_mode_fields(void *mode_data, dft_flux flux,
                          const char *HDF5FileName);

  // get array of DFT field values
  std::complex<double> *get_dft_array(dft_flux flux, component c, int num_freq,
                                      int *rank, int dims[3]);
  std::complex<double> *get_dft_array(dft_fields fdft, component c, int num_freq,
                                      int *rank, int dims[3]);
  std::complex<double> *get_dft_array(dft_force force, component c, int num_freq,
                                      int *rank, int dims[3]);
  std::complex<double> *get_dft_array(dft_near2far n2f, component c, int num_freq,
                                      int *rank, int dims[3]);

  // overlap integrals between eigenmode fields and DFT flux fields
  void get_overlap(void *mode1_data, void *mode2_data, dft_flux flux,
                   int num_freq, std::complex<double>overlaps[2]);
  void get_mode_flux_overlap(void *mode_data, dft_flux flux, int num_freq,
                             std::complex<double>overlaps[2]);
  void get_mode_mode_overlap(void *mode1_data, void *mode2_data, dft_flux flux, std::complex<double>overlaps[2]);

  // stress.cpp
  dft_force add_dft_force(const volume_list *where,
			  double freq_min, double freq_max, int Nfreq);

  // near2far.cpp
  dft_near2far add_dft_near2far(const volume_list *where,
                                double freq_min, double freq_max, int Nfreq);
  // monitor.cpp
  double get_chi1inv(component, direction, const vec &loc) const;
  double get_inveps(component c, direction d, const vec &loc) const {
    return get_chi1inv(c, d, loc);
  }
  double get_eps(const vec &loc) const;
  double get_mu(const vec &loc) const;
  void get_point(monitor_point *p, const vec &) const;
  monitor_point *get_new_point(const vec &, monitor_point *p=NULL) const;

  std::complex<double> get_field(int c, const vec &loc) const;
  std::complex<double> get_field(component c, const vec &loc) const;
  double get_field(derived_component c, const vec &loc) const;

  // energy_and_flux.cpp
  void synchronize_magnetic_fields();
  void restore_magnetic_fields();
  double energy_in_box(const volume &);
  double electric_energy_in_box(const volume &);
  double magnetic_energy_in_box(const volume &);
  double thermo_energy_in_box(const volume &);
  double total_energy();
  double field_energy_in_box(const volume &);
  double field_energy_in_box(component c, const volume &);
  double field_energy();
  double flux_in_box_wrongH(direction d, const volume &);
  double flux_in_box(direction d, const volume &);
  flux_vol *add_flux_vol(direction d, const volume &where);
  flux_vol *add_flux_plane(const volume &where);
  flux_vol *add_flux_plane(const vec &p1, const vec &p2);
  double electric_energy_max_in_box(const volume &where);
  double modal_volume_in_box(const volume &where);
  double electric_sqr_weighted_integral(double (*deps)(const vec &),
				       const volume &where);
  double electric_energy_weighted_integral(double (*f)(const vec &),
					   const volume &where);

  void set_output_directory(const char *name);
  void verbose(int gv=1);
  double count_volume(component);
  // fields.cpp
  bool have_component(component);
  // material.cpp
  double max_eps() const;
  // step.cpp
  void step_boundaries(field_type);

  bool nosize_direction(direction d) const;
  direction normal_direction(const volume &where) const;

  // casimir.cpp
  std::complex<double> casimir_stress_dct_integral(direction dforce,
					      direction dsource,
					      double mx, double my, double mz,
					      field_type ft,
					      volume where,
					      bool is_bloch = false);

  void set_solve_cw_omega(std::complex<double> omega);
  void unset_solve_cw_omega();

 private:
  int verbosity; // Turn on verbosity for debugging purposes...
  int synchronized_magnetic_fields; // count number of nested synchs
  double last_wall_time;
#define MEEP_TIMING_STACK_SZ 10
  time_sink working_on, was_working_on[MEEP_TIMING_STACK_SZ];
  double times_spent[Other+1];
  // fields.cpp
  void figure_out_step_plan();
  // time.cpp
  void am_now_working_on(time_sink);
  void finished_working();
  // boundaries.cpp
  bool chunk_connections_valid;
  void find_metals();
  void disconnect_chunks();
  void connect_chunks();
  void connect_the_chunks(); // Intended to be ultra-private...
  bool on_metal_boundary(const ivec &);
  ivec ilattice_vector(direction) const;
  bool locate_point_in_user_volume(ivec *, std::complex<double> *phase) const;
  void locate_volume_source_in_user_volume(const vec p1, const vec p2, vec newp1[8], vec newp2[8],
                                           std::complex<double> kphase[8], int &ncopies) const;
  // mympi.cpp
  void boundary_communications(field_type);
  // step.cpp
  void phase_material();
  void step_db(field_type ft);
  void step_source(field_type ft, bool including_integrated = false);
  void update_pols(field_type ft);
  void calc_sources(double tim);
public:
  // monitor.cpp
  std::complex<double> get_field(component c, const ivec &iloc) const;
  double get_chi1inv(component, direction, const ivec &iloc) const;
  // boundaries.cpp
  bool locate_component_point(component *, ivec *, std::complex<double> *) const;
};

class flux_vol {
 public:
  flux_vol(fields *f_, direction d_, const volume &where_) : where(where_) {
    f = f_; d = d_; cur_flux = cur_flux_half = 0;
    next = f->fluxes; f->fluxes = this;
  }
  ~flux_vol() { delete next; }

  void update_half() { cur_flux_half = flux_wrongE();
                       if (next) next->update_half(); }
  void update() { cur_flux = (flux_wrongE() + cur_flux_half) * 0.5;
                  if (next) next->update(); }

  double flux() { return cur_flux; }

  flux_vol *next;
 private:
  double flux_wrongE() { return f->flux_in_box_wrongH(d, where); }
  fields *f;
  direction d;
  volume where;
  double cur_flux, cur_flux_half;
};

// The following is a utility function to parse the executable name use it
// to come up with a directory name, avoiding overwriting any existing
// directory, unless the source file hasn't changed.

const char *make_output_directory(const char *exename, const char *jobname = NULL);
void trash_output_directory(const char *dirname);
FILE *create_output_file(const char *dirname, const char *fname);

// The following allows you to hit ctrl-C to tell your calculation to stop
// and clean up.
void deal_with_ctrl_c(int stop_now = 2);
// When a ctrl_c is called, the following variable (which starts with a
// zero value) is incremented.
extern int interrupt;

int do_harminv(std::complex<double> *data, int n, double dt,
	       double fmin, double fmax, int maxbands,
	       std::complex<double> *amps, double *freq_re, double *freq_im,
	       double *errors = NULL,
	       double spectral_density = 1.1, double Q_thresh = 50,
	       double rel_err_thresh = 1e20, double err_thresh = 0.01,
	       double rel_amp_thresh = -1, double amp_thresh = -1);

std::complex<double> *make_casimir_gfunc(double T, double dt, double sigma, field_type ft,
				std::complex<double> (*eps_func)(std::complex<double> omega) = 0,
				double Tfft = 0);

std::complex<double> *make_casimir_gfunc_kz(double T, double dt, double sigma, field_type ft);

#if MEEP_SINGLE
// in mympi.cpp ... must be here in order to use realnum type
void broadcast(int from, realnum *data, int size);
#endif

// random number generation: random.cpp
void set_random_seed(unsigned long seed);
double uniform_random(double a, double b); // uniform random in [a,b]
double gaussian_random(double mean, double stddev); // normal random with given mean and stddev
int random_int(int a, int b); // uniform random in [a,b)

// Bessel function (in initialize.cpp)
double BesselJ(int m, double kr);

// analytical Green's functions (in near2far.cpp); upon return,
// EH[0..5] are set to the Ex,Ey,Ez,Hx,Hy,Hz field components at x
// from a c0 source of amplitude f0 at x0.
void green2d(std::complex<double> *EH, const vec &x,
             double freq, double eps, double mu,
             const vec &x0, component c0, std::complex<double> f0);
void green3d(std::complex<double> *EH, const vec &x,
             double freq, double eps, double mu,
             const vec &x0, component c0, std::complex<double> f0);

// non-class methods for working with mpb eigenmode data
//
void destroy_eigenmode_data(void *vedata);
std::complex<double> eigenmode_amplitude(void *vedata,
                                         const vec &p,
                                         component c);
double get_group_velocity(void *vedata);
vec get_k(void *vedata);

realnum linear_interpolate(realnum rx, realnum ry, realnum rz, realnum *data,
                           int nx, int ny, int nz, int stride);

// utility routine for modular arithmetic that always returns a nonnegative integer
inline int pmod(int n, int modulus) {
  n = n % modulus;
  if (n < 0)
    n += modulus;
  return n;
}
} /* namespace meep */

#endif /* MEEP_H */