File: field.py

package info (click to toggle)
cf-python 1.3.2%2Bdfsg1-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 7,996 kB
  • sloc: python: 51,733; ansic: 2,736; makefile: 78; sh: 2
file content (14238 lines) | stat: -rw-r--r-- 498,701 bytes parent folder | download
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
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
from numpy import argmax      as numpy_argmax
from numpy import array       as numpy_array
from numpy import can_cast    as numpy_can_cast
from numpy import diff        as numpy_diff
from numpy import empty       as numpy_empty
from numpy import ndarray     as numpy_ndarray
from numpy import size        as numpy_size
from numpy import squeeze     as numpy_squeeze
from numpy import unique      as numpy_unique
from numpy import where       as numpy_where
from numpy import zeros       as numpy_zeros
from numpy import array_equal as numpy_array_equal
from numpy import arange      as numpy_arange
from numpy import tile        as numpy_tile
from numpy.ma import MaskedArray as numpy_MaskedArray
from numpy.ma import is_masked as numpy_is_masked

from copy            import deepcopy
from itertools       import izip
from operator        import mul as operator_mul
from operator        import itemgetter as operator_itemgetter
from matplotlib.path import Path
#from scipy.ndimage.filters import convolve1d 

from .cellmeasure  import CellMeasure
from .cellmethods  import CellMethods
from .constants    import masked as cf_masked
from .domain       import Domain
from .flags        import Flags
from .functions    import parse_indices, CHUNKSIZE, equals, RTOL, ATOL
from .functions    import _section
from .query        import Query, ge, gt, le, lt, ne, eq, wi
from .timeduration import TimeDuration
from .units        import Units
from .variable     import Variable, SubspaceVariable, RewriteDocstringMeta

from .data.data import Data
from .regrid import Regrid
from .coordinate import DimensionCoordinate

# --------------------------------------------------------------------
# Commonly used units
# --------------------------------------------------------------------
_units_days    = Units('days')
_units_radians = Units('radians')
_units_m       = Units('m')
_units_m2      = Units('m2')

_1_day = Data(1, 'day')

# --------------------------------------------------------------------
# Map each allowed input collapse method name to its corresponding
# cf.Data method. Input collapse methods not in this sictionary are
# assumed to have a corresponding cf.Data method with the same name.
# --------------------------------------------------------------------
_collapse_methods = {
    'mean'              : 'mean',
    'avg'               : 'mean',
    'average'           : 'mean',
    'max'               : 'max',
    'maximum'           : 'max',
    'min'               : 'min',
    'minimum'           : 'min',
    'mid_range'         : 'mid_range',
    'range'             : 'range',
    'standard_deviation': 'sd',
    'sd'                : 'sd',
    'sum'               : 'sum',
    'variance'          : 'var',
    'var'               : 'var',
    'sample_size'       : 'sample_size', 
    'sum_of_weights'    : 'sum_of_weights',
    'sum_of_weights2'   : 'sum_of_weights2',
}

# --------------------------------------------------------------------
# Map each allowed input collapse method name to its corresponding
# cf.Data method. Input collapse methods not in this sictionary are
# assumed to have a corresponding cf.Data method with the same name.
# --------------------------------------------------------------------
_collapse_cell_methods = {
    'point'             : 'point',
    'mean'              : 'mean',
    'avg'               : 'mean',
    'average'           : 'mean',
    'max'               : 'maximum',
    'maximum'           : 'maximum',
    'min'               : 'minimum',
    'minimum'           : 'minimum',
    'mid_range'         : 'mid_range',
    'range'             : 'range',
    'standard_deviation': 'standard_deviationd',
    'sd'                : 'standard_deviation',
    'sum'               : 'sum',
    'variance'          : 'variance',
    'var'               : 'variance',
    'sample_size'       : None,
    'sum_of_weights'    : None,
    'sum_of_weights2'   : None,
}

# --------------------------------------------------------------------
# Map each cf.Data method to its corresponding minimum number of
# elements. cf.Data methods not in this dictionary are assumed to have
# a minimum number of elements equal to 1.
# --------------------------------------------------------------------
_collapse_min_size = {'sd' : 2,
                      'var': 2,
                      }

# --------------------------------------------------------------------
# These cf.Data methods may be weighted
# --------------------------------------------------------------------
_collapse_weighted_methods = set(('mean',
                                  'avg',
                                  'average',
                                  'sd',
                                  'standard_deviation',
                                  'var',
                                  'variance',
                                  'sum_of_weights',
                                  'sum_of_weights2',
                                  ))

# --------------------------------------------------------------------
# These cf.Data methods may specify a number of degrees of freedom
# --------------------------------------------------------------------
_collapse_ddof_methods = set(('sd',
                              'var',
                              ))

# ====================================================================
#
# Field object
#
# ====================================================================

class Field(Variable):
    '''

A field construct according to the CF data model.

A field is a container for a data array and metadata comprising
properties to describe the physical nature of the data and a
coordinate system (called a domain) which describes the positions of
each element of the data array.

The field's domain may contain dimensions and auxiliary coordinate and
cell measure objects (which themselves contain data arrays and
properties to describe them) and coordinate reference objects.

All components of a field are optional.

**Miscellaneous**

Field objects are picklable.

'''

    _special_properties = Variable._special_properties.union(        
        ('ancillary_variables',
         'cell_methods',
         'flag_values',
         'flag_masks',
         'flag_meanings')
         )
    
    def __init__(self, properties={}, attributes={}, data=None, domain=None,
                 flags=None, ancillary_variables=None, axes=None,
                 auto_cyclic=True, copy=True):
        '''**Initialization**

:Parameters:

    properties: dict, optional
        Provide the new field with CF properties from the dictionary's
        key/value pairs.

    data: cf.Data, optional
        Provide the new field with an N-dimensional data array in a
        `cf.Data` object.

    domain: cf.Domain, optional
        Provide the new field with a coordinate system in a
        `cf.Domain` object. By default an empty domain is created.

    attributes: dict, optional
        Provide the new field with attributes from the dictionary's
        key/value pairs.

    flags: cf.Flags, optional
        Provide the new field with self-describing flag values.

    ancillary_variables: `cf.FieldList`, optional
        Provide the new field with ancillary variable fields.

    axes: sequence of `str`, optional
        A list of domain axis identifiers (``'dimN'``), stating the
        axes, in order, of field's data array. By default these axis
        identifiers will be the sequence of consecutive axis
        identifiers ``'dim0'`` up to ``'dimM'``, where ``M`` is the
        number of axes of the data array, or an empty sequence if the
        data array is a scalar.

        If an axis of the data array already exists in the domain then
        the it must have the same size as the domain axis. If it does
        not exist in the domain then a new axis will be created.

        By default the axes will either be those defined for the data
        array by the domain or, if these do not exist, the domain axis
        identifiers whose sizes unambiguously match the data array.

    auto_cyclic: `bool`, optional
        If False then do not auto-detect cyclic axes. By default
        cyclic axes are auto-detected with the `autocyclic` method.

    copy: `bool`, optional
        If False then do not deep copy arguments prior to
        initialization. By default arguments are deep copied.

        '''
        # Initialize the new field with attributes and CF properties
        super(Field, self).__init__(properties=properties,
                                    attributes=attributes,
                                    copy=copy)   
    
        # 
        self._unlimited = None

        # Domain
        if domain is not None:
            if not copy:
                self.domain = domain
            else:
                self.domain = domain.copy()
        else:
            # A field always has a domain
            self.domain = Domain()

        # Data array
        if data is not None:
            self.insert_data(data, axes=axes, copy=copy)
           
        # Flags
        if flags is not None:
            if not copy:
                self.Flags = flags
            else:
                self.Flags = flags.copy()
        #--- End: if

        # Ancillary variables
        if ancillary_variables is not None:
            if not copy:
                self.ancillary_variables = ancillary_variables
            else:
                self.ancillary_variables = ancillary_variables.copy()
        #--- End: if

        # Cyclic axes
        if auto_cyclic:
            self.autocyclic()
    #--- End: def

    def __getitem__(self, index):
        '''

Called to implement evaluation of f[index].

f.__getitem__(index) <==> f[index]

The field is treated as if it were a single element field list
containing itself, i.e. ``f[index]`` is equivalent to
``cf.FieldList(f)[index]``.

:Examples 1:

>>> g = f[0]
>>> g = f[:1]
>>> g = f[1:]

:Returns:

    out: `cf.Field` or `cf.FieldList`
        If *index* is the integer 0 or -1 then the field itself is
        returned. If *index* is a slice then a field list is returned
        which is either empty or else contains a single element of the
        field itself.
          
.. seealso:: `cf.FieldList.__getitem__`, `subspace`

:Examples 2:

>>> f[0] is f[-1] is f
True
>>> f[0:1].equals(cf.FieldList(f))   
True
>>> f[0:1][0] is f
True
>>> f[1:].equals(cf.FieldList())
True
>>> f[1:]       
[]
>>> f[-1::3][0] is f
True

'''
#        if isinstance(index, slice):
#            n = len((None,)[index])
#            if n == 1:
#                return FieldList(self)
#            elif not n:
#                return FieldList()
#            else:
#                raise IndexError("%s index out of range: %s" %
#                                 (self.__class__.__name__, index))
#        #--- End: if
#
#        return super(Field, self).__getitem__(index)

        return FieldList((self,))[index]
    #--- End: def

    def broadcastable(self, g):
        '''
'''
        # ------------------------------------------------------------
        # Analyse each domain
        # ------------------------------------------------------------
        s = self.domain.analyse()
        v = g.domain.analyse()

        if s['warnings'] or v['warnings']:
            return False

        matching_size_gt1_ids = []
        for x, coord0 in s['id_to_coord']:
            size0 = coord0.size
            if size0 == 1:
                continue
            
            if x in v['id_to_coord']:
                coord1 = v['id_to_coord']['x']
                size1 = coord1.size
                if size1 == 1:
                    continue
                if size0 != size1:
                    return False

                matching_size_gt1_ids.append(x)
        #--- End: for                    

        for x, coord1 in v['id_to_coord']:
            if x in matching_size_gt1_ids:
                continue
            
            size1 = coord1.size
            if size1 == 1:
                continue
            
            if x in s['id_to_coord']:
                coord0 = s['id_to_coord']['x']
                size0 = coord0.size
                if size0 == 1:
                    continue
                if size0 != size1:
                    return False

                matching_size_gt1_ids.append(x)
        #--- End: for                    

        # Check that at most one field has undefined axes
        if s['undefined_axes'] and v['undefined_axes']:
            raise ValueError(
"Can't combine fields: Both fields have undefined axes: {0}, {1}".format(
    tuple(self.axis_name(a) for a in s['undefined_axes']),
    tuple(other.axis_name(a) for a in v['undefined_axes'])))

        # Find the axis names which are present in both fields
        matching_ids = set(s['id_to_axis']).intersection(v['id_to_axis'])
        
        # Check that any matching axes defined by an auxiliary
        # coordinate are done so in both fields.
        for identity in set(s['id_to_aux']).symmetric_difference(v['id_to_aux']):
            if identity in matching_ids:
                raise ValueError(
"Can't combine fields: %r axis defined by auxiliary in only 1 field" %
standard_name) ########~WRONG
        #--- End: for


        #-------------------------------------------------------------
        #
        #-------------------------------------------------------------
        for identity in matching_size_gt1_ids:
            coord0 = s['id_to_coord'][identity]
            coord1 = v['id_to_coord'][identity]

            # Check that the defining coordinate data arrays are
            # compatible
            if not coord0._equivalent_data(coord1):
                # Can't broadcast: The defining coordinates have
                # unequivalent data arrays and are both size > 1.
                return False

            # Still here? Then the defining coordinates have
            # equivalent data arrays

            # If the defining coordinates are attached to
            # coordinate references then check that those coordinate references are
            # equivalent
            key0 = s['id_to_key'][identity]                
            key1 = v['id_to_key'][identity]

            equivalent_refs = True
            for ref0 in self.refs().itervalues():
                if key0 not in ref0.coords:
                    continue

                equivalent_refs = False
                for ref1 in g.refs().itervalues():
                    if key1 not in ref1.coords:
                        continue

                    # Each defining coordinate is referenced by a
                    # coordinate reference ...
                    if self.domain.equivalent_refs(ref0,
                                                        ref1,
                                                        g.domain):
                        # ... and those coordinate references are equivalent
                        equivalent_refs = True
                    #--- End: if

                    break
                #--- End: for

                break
            #--- End: for

            if not equivalent_refs:
                # Can't broadcast: Defining coordinates have
                # incompatible coordinate references are and are both size >
                # 1.
                return False
        #--- End: for

        # --------------------------------------------------------
        # Still here? Then the two fields are broadcastable!
        # --------------------------------------------------------
        return True
    #--- End: def

    def _binary_operation(self, other, method):
        '''

Implement binary arithmetic and comparison operations on the master
data array with metadata-aware broadcasting.

It is intended to be called by the binary arithmetic and comparison
methods, such as `__sub__`, `__imul__`, `__rdiv__`, `__lt__`, etc.

:Parameters:

    other: standard Python scalar object, cf.Field or cf.Query or cf.Data

    method: str
        The binary arithmetic or comparison method name (such as
        ``'__idiv__'`` or ``'__ge__'``).

:Returns:

    out: `cf.Field`
        The new field, or the same field if the operation was an in
        place augmented arithmetic assignment.

:Examples:

>>> h = f._binary_operation(g, '__add__')
>>> h = f._binary_operation(g, '__ge__')
>>> f._binary_operation(g, '__isub__')
>>> f._binary_operation(g, '__rdiv__')

'''
        debug = False

        if (isinstance(other, (float, int, long, bool, basestring)) or
            other is self):
            # ========================================================
            # CASE 1a: No changes are to the field's domain are
            #          required so can use the metadata-unaware
            #          Variable._binary_operation method.
            # ========================================================
            return super(Field, self)._binary_operation(other, method)
        #--- End: if

        if isinstance(other, Data) and other.size == 1:
            # ========================================================
            # CASE 1b: No changes are to the field's domain are
            #          required so can use the metadata-unaware
            #          Variable._binary_operation method.
            # ========================================================
            if other.ndim > 0:
                other = other.squeeze()

            return super(Field, self)._binary_operation(other, method)
        #--- End: if

        if isinstance(other, Query):
            # ========================================================
            # CASE 2: Combine the field with a cf.Query object
            # ========================================================
            return NotImplemented
        #--- End: if

        if isinstance(other, FieldList):
            # ========================================================
            # CASE 3: Combine the field with a cf.FieldList object
            # ========================================================
            return NotImplemented
        #--- End: if

        if not isinstance(other, self.__class__):
            raise ValueError(
                "Can't combine %r with %r" %
                (self.__class__.__name__, other.__class__.__name__))
        #--- End: if

        # ============================================================
        # Still here? Then combine the field with another field
        # ============================================================

        # ------------------------------------------------------------
        # Analyse each domain
        # ------------------------------------------------------------
        s = self.domain.analyse()
        v = other.domain.analyse()

        if s['warnings'] or v['warnings']:
            raise ValueError("Can't combine fields: %s" % 
                             (s['warnings'] or v['warnings']))

        # Check that at most one field has undefined axes
        if s['undefined_axes'] and v['undefined_axes']:
            raise ValueError(
"Can't combine fields: Both fields have undefined axes: {0}, {1}".format(
    tuple(self.axis_name(a) for a in s['undefined_axes']),
    tuple(other.axis_name(a) for a in v['undefined_axes'])))

        # Find the axis names which are present in both fields
        matching_ids = set(s['id_to_axis']).intersection(v['id_to_axis'])
        if debug:
            print "s['id_to_axis'] =", s['id_to_axis']
            print "v['id_to_axis'] =", v['id_to_axis']
            print 'matching_ids    =', matching_ids
        
        # Check that any matching axes defined by an auxiliary
        # coordinate are done so in both fields.
        for identity in set(s['id_to_aux']).symmetric_difference(v['id_to_aux']):
            if identity in matching_ids:
                raise ValueError(
"Can't combine fields: %r axis defined by auxiliary in only 1 field" %
standard_name) ########~WRONG
        #--- End: for

        # ------------------------------------------------------------
        # For matching dimension coordinates check that they have
        # consistent coordinate references and that one of the following is
        # true:
        #
        # 1) They have equal size > 1 and their data arrays are
        #    equivalent
        #
        # 2) They have unequal sizes and one of them has size 1
        #
        # 3) They have equal size = 1. In this case, if the data
        #    arrays are not equivalent then the axis will be omitted
        #    from the result field's domain.
        #-------------------------------------------------------------

        # List of size 1 axes to be completely removed from the result
        # field. Such an axis's size 1 defining coordinates have
        # unequivalent data arrays.
        #
        # For example:
        # >>> remove_size1_axes
        # ['dim2']
        remove_size1_axes = []

        # List of matching axes with equivalent defining dimension
        # coordinate data arrays.
        #
        # Note that we don't need to include matching axes with
        # equivalent defining *auxiliary* coordinate data arrays.
        #
        # For example:
        # >>> 
        # [('dim2', 'dim0')]
        matching_axes_with_equivalent_data = []

        # For each field, list those of its matching axes which need
        # to be broadcast against the other field. I.e. those axes
        # which are size 1 but size > 1 in the other field.
        #
        # For example:
        # >>> s['broadcast_axes']
        # ['dim1']
        s['broadcast_axes'] = []
        v['broadcast_axes'] = []

        # Map axes in field1 to axes in field0 and vice versa
        #
        # For example:
        # >>> axis1_to_axis0
        # {'dim1': 'dim0', 'dim2': 'dim1', 'dim0': 'dim2'}
        # >>> axis0_to_axis1
        # {'dim0': 'dim1', 'dim1': 'dim2', 'dim2': 'dim0'}
        axis1_to_axis0 = {}
        axis0_to_axis1 = {}

        for identity in matching_ids:
            coord0 = s['id_to_coord'][identity]
            coord1 = v['id_to_coord'][identity]

            axis0  = s['id_to_axis'][identity]
            axis1  = v['id_to_axis'][identity]

            axis1_to_axis0[axis1] = axis0
            axis0_to_axis1[axis0] = axis1

            # Check the sizes of the defining coordinates
            size0 = coord0.size
            size1 = coord1.size
            if size0 != size1:
                # Defining coordinates have different sizes
                if size0 == 1:
                    # Can broadcast
                    s['broadcast_axes'].append(s['id_to_axis'][identity])
                elif size1 == 1:
                    # Can broadcast
                    v['broadcast_axes'].append(v['id_to_axis'][identity])
                else:
                    # Can't broadcast
                    raise ValueError(
"Can't combine fields: Can't broadcast %r axes with sizes %d and %d" %
(identity, size0, size1))

                continue
            #--- End: if
            if debug:
                print "s['broadcast_axes'] =", s['broadcast_axes']
                print "v['broadcast_axes'] =", v['broadcast_axes']

            # Still here? Then these defining coordinates have the
            # same size.

            # Check that the defining coordinate data arrays are
            # compatible
            if coord0._equivalent_data(coord1):
                # The defining coordinates have equivalent data
                # arrays

                # If the defining coordinates are attached to
                # coordinate references then check that those coordinate references are
                # equivalent
                key0 = s['id_to_key'][identity]                
                key1 = v['id_to_key'][identity]

                equivalent_refs = True
                for ref0 in self.refs().itervalues():
                    if key0 not in ref0.coords:
                        continue

                    equivalent_refs = False
                    for ref1 in other.refs().itervalues():
                        if key1 not in ref1.coords:
                            continue

                        # Each defining coordinate is referenced by a
                        # coordinate reference ...
                        if self.domain.equivalent_refs(ref0, ref1,
                                                       other.domain):
                            # ... and those coordinate references are equivalent
                            equivalent_refs = True
                        #--- End: if

                        break
                    #--- End: for

                    break
                #--- End: for

                if not equivalent_refs:
                    # The defining coordinates have incompatible
                    # coordinate references
                    if coord0.size > 1:
                        # They are both size > 1
                        raise ValueError(
"Can't combine fields: Incompatible coordinate references for %r coordinates" % identity)
                    else:
                        # They are both size 1 so flag this axis to be
                        # omitted from the result field
                        remove_size1_axes.append(axis0)

                elif identity not in s['id_to_aux']:
                    # The defining coordinates 1) are both dimension
                    # coordinates, 2) have equivalent data arrays and
                    # 3) have compatible coordinate references (if any).
                    matching_axes_with_equivalent_data.append((axis0, axis1))

            else:
                # The defining coordinates have unequivalent data
                # arrays
                if coord0.size > 1:
                    # They are both size greater than 1
                    raise ValueError(
"Can't combine fields: Incompatible %r coordinates: %r, %r" %
(identity, coord0.data, coord1.data))
                else:
                    # They are both size 1 so flag this axis to be
                    # omitted from the result field
                    remove_size1_axes.append(axis0)
        #--- End: for

        # --------------------------------------------------------
        # Still here? Then the two fields are combinable!
        # --------------------------------------------------------

        # ------------------------------------------------------------
        # 2.1 Create copies of the two fields, unless it is an in
        #     place combination, in which case we don't want to copy
        #     self)
        # ------------------------------------------------------------
        field1 = other.copy()

        inplace = method[2] == 'i'
        if not inplace:
            field0 = self.copy()
        else:
            field0 = self

        # Aliases for the field's domain and data array
        domain0 = field0.domain
        domain1 = field1.domain

        # 
        s['new_axes'] = []
            
#        for axis1 in domain1._axes_sizes:
#            if axis1 in v['axis_to_id']:
#                identity = v['axis_to_id'][axis1]
#                if identity in matching_ids:
#                    axis0 = s['id_to_axis'][identity]
#                    axis1_to_axis0[axis1] = axis0
#                    axis0_to_axis1[axis0] = axis1
#        #--- End: for

        # ------------------------------------------------------------
        # Permute the axes of the data array of field0 so that:
        #
        # * All of the matching axes are the inner (fastest varying)
        #   axes
        #
        # * All of the undefined axes are the outer (slowest varying)
        #   axes
        #
        # * All of the defined but unmatched axes are in the middle
        # ------------------------------------------------------------
        data_axes0 = domain0.data_axes()
        axes_unD = []                     # Undefined axes
        axes_unM = []                     # Defined but unmatched axes
        axes0_M  = []                     # Defined and matched axes
        for axis0 in data_axes0:
            if axis0 in axis0_to_axis1:
                # Matching axis                
                axes0_M.append(axis0)
            elif axis0 in s['undefined_axes']:
                # Undefined axis
                axes_unD.append(axis0)
            else:
                # Defined but unmatched axis
                axes_unM.append(axis0)
        #--- End: for
        if debug:
            print 'axes_unD , axes_unM , axes0_M =', axes_unD , axes_unM , axes0_M

        field0.transpose(axes_unD + axes_unM + axes0_M, i=True)

        end_of_undefined0   = len(axes_unD)
        start_of_unmatched0 = end_of_undefined0
        start_of_matched0   = start_of_unmatched0 + len(axes_unM)
        if debug: 
            print 'end_of_undefined0   =', end_of_undefined0   
            print 'start_of_unmatched0 =', start_of_unmatched0 
            print 'start_of_matched0   =', start_of_matched0  

        # ------------------------------------------------------------
        # Permute the axes of the data array of field1 so that:
        #
        # * All of the matching axes are the inner (fastest varying)
        #   axes and in corresponding positions to data0
        #
        # * All of the undefined axes are the outer (slowest varying)
        #   axes
        #
        # * All of the defined but unmatched axes are in the middle
        # ------------------------------------------------------------
        data_axes1 = domain1.data_axes()
        axes_unD = []
        axes_unM = []
        axes1_M  = [axis0_to_axis1[axis0] for axis0 in axes0_M]
        for  axis1 in data_axes1:          
            if axis1 in axes1_M:
                pass
            elif axis1 in axis1_to_axis0:
                # Matching axis
                axes_unM.append(axis1)
            elif axis1 in v['undefined_axes']:
                # Undefined axis
                axes_unD.append(axis1) 
            else:
                # Defined but unmatched axis
                axes_unM.append(axis1)
        #--- End: for
        if debug:
            print 'axes_unD , axes_unM , axes0_M =',axes_unD , axes_unM , axes0_M

        field1.transpose(axes_unD + axes_unM + axes1_M, i=True)

        start_of_unmatched1 = len(axes_unD)
        start_of_matched1   = start_of_unmatched1 + len(axes_unM)
        undefined_indices1  = slice(None, start_of_unmatched1)
        unmatched_indices1  = slice(start_of_unmatched1, start_of_matched1)
        if debug: 
            print 'start_of_unmatched1 =', start_of_unmatched1 
            print 'start_of_matched1   =', start_of_matched1   
            print 'undefined_indices1  =', undefined_indices1  
            print 'unmatched_indices1  =', unmatched_indices1  

        # ------------------------------------------------------------
        # Make sure that each pair of matching axes run in the same
        # direction 
        #
        # Note that the axis0_to_axis1 dictionary currently only maps
        # matching axes
        # ------------------------------------------------------------
        if debug:
            print '2: axis0_to_axis1 =',axis0_to_axis1

        for axis0, axis1 in axis0_to_axis1.iteritems():
             if domain1.direction(axis1) != domain0.direction(axis0):
                field1.flip(axis1, i=True)
        #--- End: for
    
        # ------------------------------------------------------------
        # 2f. Insert size 1 axes into the data array of field0 to
        #     correspond to defined but unmatched axes in field1
        #
        # For example, if   field0.Data is      1 3         T Y X
        #              and  field1.Data is          4 1 P Z   Y X
        #              then field0.Data becomes 1 3     1 1 T Y X
        # ------------------------------------------------------------
        unmatched_axes1 = data_axes1[unmatched_indices1]
        if debug: print '2: unmatched_axes1=', unmatched_axes1

        if unmatched_axes1:
            for axis1 in unmatched_axes1:
                field0.expand_dims(end_of_undefined0, i=True)
                if debug: print '2: axis1, field0.shape =', axis1, field0.shape

                axis0 = set(field0.data_axes()).difference(data_axes0).pop()

                axis1_to_axis0[axis1] = axis0
                axis0_to_axis1[axis0] = axis1
                s['new_axes'].append(axis0)

                start_of_unmatched0 += 1
                start_of_matched0   += 1 

                data_axes0 = domain0.data_axes()
            #--- End: for
        #--- End: if

        # ------------------------------------------------------------
        # Insert size 1 axes into the data array of field1 to
        # correspond to defined but unmatched axes in field0
        #
        # For example, if   field0.Data is      1 3     1 1 T Y X
        #              and  field1.Data is          4 1 P Z   Y X 
        #              then field1.Data becomes     4 1 P Z 1 Y X 
        # ------------------------------------------------------------
        unmatched_axes0 = data_axes0[start_of_unmatched0:start_of_matched0]
        if debug: print '2: unmatched_axes0 =', unmatched_axes0

        if unmatched_axes0:
            for axis0 in unmatched_axes0:
                field1.expand_dims(start_of_matched1, i=True)
                if debug: print '2: axis0, field1.shape =',axis0, field1.shape

                axis1 = set(field1.data_axes()).difference(data_axes1).pop()

                axis0_to_axis1[axis0] = axis1
                axis1_to_axis0[axis1] = axis0

                start_of_unmatched1 += 1

                data_axes1 = field1.data_axes()
            #--- End: for
         #--- End: if

        # ------------------------------------------------------------
        # Insert size 1 axes into the data array of field0 to
        # correspond to undefined axes (of any size) in field1
        #
        # For example, if   field0.Data is      1 3     1 1 T Y X
        #              and  field1.Data is          4 1 P Z 1 Y X 
        #              then field0.Data becomes 1 3 1 1 1 1 T Y X
        # ------------------------------------------------------------
        axes1 = data_axes1[undefined_indices1]
        if axes1:
            for axis1 in axes1:
                field0.expand_dims(end_of_undefined0, i=True)

                axis0 = set(field0.data_axes()).difference(data_axes0).pop()

                axis0_to_axis1[axis0] = axis1
                axis1_to_axis0[axis1] = axis0
                s['new_axes'].append(axis0)

                data_axes0 = field0.data_axes()
            #--- End: for
        #--- End: if
        if debug:
            print '2: axis0_to_axis1 =', axis0_to_axis1
            print '2: axis1_to_axis0 =', axis1_to_axis0
            print "2: s['new_axes']  =", s['new_axes']

        # ============================================================
        # 3. Combine the data objects
        #
        # Note that, by now, field0.ndim >= field1.ndim.
        # ============================================================
#dch        field0.Data = getattr(field0.Data, method)(field1.Data)
        if debug:
            print '3: repr(field0) =', repr(field0)
            print '3: repr(field1) =', repr(field1)

        field0 = super(Field, field0)._binary_operation(field1, method)

        # Must rest domain0, because we have reset field0.
        domain0 = field0.domain

        if debug:
            print '3: field0.shape =', field0.shape
            print '3: repr(field0) =', repr(field0)

        # ============================================================
        # 4. Adjust the domain of field0 to accommodate its new data
        # ============================================================
        insert_dim = {}
        insert_aux = {}
        remove_aux = []

        # ------------------------------------------------------------
        # 4a. Remove any size 1 axes which are matching axes but with
        #     different coordinate data array values
        # ------------------------------------------------------------
        field0.remove_axes(remove_size1_axes)

        # ------------------------------------------------------------
        # 4b. If broadcasting has grown any size 1 axes in domain0
        #     then replace their size 1 coordinates with the
        #     corresponding size > 1 coordinates from domain1.
        # ------------------------------------------------------------
        refs1 = field1.refs()
        refs = []

        for axis0 in s['broadcast_axes'] + s['new_axes']:        
            axis1 = axis0_to_axis1[axis0]
            size = domain1._axes_sizes[axis1]
            domain0.insert_axis(size, key=axis0, replace=True)
            if debug:
                print '4: domain1._axes_sizes =',domain1._axes_sizes
                print '4: domain0._axes_sizes =',domain0._axes_sizes

            for tkey in refs1:
                if axis1 in domain1.ref_axes(tkey):
                    refs.append(tkey)

            # Copy the domain1 dimension coordinate to
            # domain0, if it exists.
            if axis1 in domain1.d:
                insert_dim[axis1] = axis0

            # Remove any domain0 1-d auxiliary coordinates for
            # this axis
            if axis0 in s['aux_coords']:
                for aux0 in s['aux_coords'][axis0]['1-d'].keys():
                    remove_aux.append(aux0)
                    del s['aux_coords'][axis0]['1-d'][aux0]
            #--- End: if

            # Copy to domain0 any domain1 1-d auxiliary coordinates
            # for this axis
            if axis1 in v['aux_coords']:
                for aux1 in v['aux_coords'][axis1]['1-d']:
                    insert_aux[aux1] = [axis0]
        #--- End: for

        # ------------------------------------------------------------
        # Consolidate any 1-d auxiliary coordinates for matching axes
        # whose defining dimension coordinates have equivalent data
        # arrays.
        #
        # A domain0 1-d auxiliary coordinate is retained if there is a
        # corresponding domain1 1-d auxiliary with the same standard
        # name and equivalent data array.
        # ------------------------------------------------------------
        for axis0, axis1 in matching_axes_with_equivalent_data:

            for aux0, coord0 in s['aux_coords'][axis0]['1-d'].iteritems():
                if coord0.identity() is None:
                    # Remove this domain0 1-d auxiliary coordinate
                    # because it has no identity
                    remove_aux.append(aux0)
                    continue

                # Still here?
                aux0_has_equivalent_pair = False

                for aux1, coord1 in v['aux_coords'][axis1]['1-d'].items():
                    if coord1.identity() is None:
                        continue
                    
                    if coord0._equivalent_data(coord1): 
                        del v['aux_coords'][axis1]['1-d'][aux1]
                        aux0_has_equivalent_pair = True
                        break
                #--- End: for

                if not aux0_has_equivalent_pair:
                    # Remove this domain0 1-d auxiliary coordinate
                    # because it has no equivalent in domain1
                    remove_aux.append(aux0)                    
        #--- End: for

        # ------------------------------------------------------------
        # Consolidate N-d auxiliary coordinates for matching axes
        # which have the same size
        # ------------------------------------------------------------
        # Remove any N-d auxiliary coordinates which span broadcasted
        # axes
        for broadcast_axes, aux_coords, domain in izip((s['broadcast_axes'], v['broadcast_axes']),
                                                       (s['aux_coords']    , v['aux_coords']),
                                                       (domain0            , domain1)):
            for axis in broadcast_axes:
                if axis not in aux_coords:
                    continue

                for aux in aux_coords[axis]['N-d']:
                    del aux_coords['N-d'][aux]
                    if domain is domain0:
                        remove_aux.append(aux)
        #--- End: for

        # Remove any N-d auxiliary coordinates which span a mixture of
        # matching and non-matching axes
        for aux_coords, domain, axis_to_id in izip((s['aux_coords'], v['aux_coords']),
                                                   (domain0         , domain1         ),
                                                   (s['axis_to_id'] , v['axis_to_id'] )):
            for aux in aux_coords['N-d'].keys():
                # Count how many of this N-d auxiliary coordinate's
                # axes are matching axes
#                n_matching_dims = len([True for axis in domain.dimensions[aux]
#                                       if axis_to_id[axis] in matching_ids])
                n_matching_dims = len([True for axis in domain._axes[aux]
                                       if axis_to_id[axis] in matching_ids])
                
#                if 1 <= n_matching_dims < len(domain.dimensions[aux]):
                if 1 <= n_matching_dims < len(domain._axes[aux]):
                    # At least one axis is a matching axis and at
                    # least one axis isn't => so remove this domain0
                    # auxiliary coordinate
                    del aux_coords['N-d'][aux]
                    if domain is domain0:
                        remove_aux.append(aux)
            #--- End: for
        #--- End: for

        # Forget about
        for aux0 in s['aux_coords']['N-d'].keys():
             n_matching_axes = len(s['aux_coords']['N-d'][aux0])
             if not n_matching_axes:
                 del s['aux_coords']['N-d'][aux0]
        #--- End: for

        # Copy to domain0 any domain1 N-d auxiliary coordinates which
        # do not span any matching axes
        for aux1, coord1 in v['aux_coords']['N-d'].items():
             n_matching_axes = len(v['aux_coords']['N-d'][aux1])
             if not n_matching_axes:
                 axes = [axis1_to_axis0[axis1] for axis1 in domain1._axes[aux1]]
                 insert_auxs[aux1] = axes
                 del v['aux_coords']['N-d'][aux1]
        #--- End: for

        # By now, aux_coords0['N-d'] contains only those N-d auxiliary
        # coordinates which span equal sized matching axes.
 
        # Remove from domain0 any N-d auxiliary coordinates which span
        # same-size matching axes and do not have an equivalent N-d
        # auxiliary coordinate in domain1 (i.e. one which spans the
        # same axes, has the same standard name and has equivalent
        # data)
        for aux0, coord0 in s['aux_coords']['N-d'].iteritems():

            # Remove domain0 N-d auxiliary coordinate if it has no
            # standard name
            if coord0.identity() is None:
                remove_aux.append(aux0)
                continue

            # Still here?
            aux0_has_equivalent_pair = False
            for aux1, coord1 in v['aux_coords']['N-d'].items():
                if coord1.identity() is None:
                    continue

                copy = True
                axes1 = domain1.item_axes(aux1)
                transpose_axes = [axes1.index(axis0_to_axis1[axis0])
                                  for axis0 in domain1.item_axes(aux0)]
                if transpose_axes != range(coord1.ndim):
#                    coord1 = coord1.copy()
                    coord1 = coord1.transpose(transpose_axes)
                    copy = False  # necessary?

                if coord0._equivalent_data(coord1, copy=copy):
                    del v['aux_coords']['N-d'][aux1]
                    aux0_has_equivalent_pair = True
                    break
            #--- End: for

            # Remove domain0 N-d auxiliary coordinate if it has no
            # equivalent in domain1
            if not aux0_has_equivalent_pair:
                remove_aux.append(aux0)
        #--- End: for
                
        key1_to_key0 = {}

        if debug:
            print 'insert_dim =', insert_dim
            print 'insert_aux =', insert_aux

        for axis1, axis in insert_dim.iteritems():
            axis0 = domain0.insert_dim(domain1.d[axis1], key=axis)
            key1_to_key0[axis1] = axis0
            if debug:
                print 'axis0, domain1.d[axis1] =', axis0, repr(domain1.d[axis1])
                print 'domain0.items() =', domain0.items()
                print 'field0.items() =', field0.items()
        for aux1, axes in insert_aux.iteritems():
            aux0 = domain0.insert_aux(domain1.a[aux1], axes=axes)
            key1_to_key0[aux1] = aux0
            if debug:
                print 'axis0, domain1.a[axis1] =', axis0, repr(domain1.a[axis1])

        domain0.remove_items(set(remove_aux))

        # Coordinate References from domain1 -> domain0
        for tkey in set(refs):
            new_ref = other.ref[tkey].copy()
#            for key1 in ref.coords:
#                new_ref.change_coord(key1, key1_to_key0.get(key1, None))
            new_ref.change_coord_identities(key1_to_key0, i=True)
                    
            domain0.insert_ref(new_ref, copy=False)
        #--- End: for

        return field0
    #--- End: def

    def _conform_for_assignment(self, other):
        '''Conform *other* so that it is ready for metadata-unaware assignment
broadcasting across *self*.

*other* is not changed in place.

:Parameters:

    other: `cf.Field`
        The field to conform.

:Returns:

    out: `cf.Field`
        The conformed version of *other*.

:Examples:

>>> g = _conform_for_assignment(f)

        '''
        # Analyse each domain
        domain0 = self.domain
        domain1 = other.domain
        s = domain0.analyse()
        v = domain1.analyse()
    
        if s['warnings'] or v['warnings']:
            raise ValueError("Can't setitem: %s" % (s['warnings'] or v['warnings']))
    
        # Find the set of matching axes
        matching_ids = set(s['id_to_axis']).intersection(v['id_to_axis'])
        if not matching_ids:
             raise ValueError("Can't assign: No matching axes")
    
        # ------------------------------------------------------------
        # Check that any matching axes defined by auxiliary
        # coordinates are done so in both fields.
        # ------------------------------------------------------------
        for identity in matching_ids:
            if (identity in s['id_to_aux']) + (identity in v['id_to_aux']) == 1:
                raise ValueError(
"Can't assign: %r axis defined by auxiliary in only 1 field" %
identity)
        #--- End: for
    
        copied = False
    
        # ------------------------------------------------------------
        # Check that 1) all undefined axes in other have size 1 and 2)
        # that all of other's unmatched but defined axes have size 1
        # and squeeze any such axes out of its data array.
        #
        # For example, if   self.Data is        P T     Z Y   X   A
        #              and  other.Data is     1     B C   Y 1 X T
        #              then other.Data becomes            Y   X T
        # ------------------------------------------------------------
        squeeze_axes1 = []
        for axis1 in v['undefined_axes']:
            if domain1._axes_sizes[axis1] != 1:            
                raise ValueError(
                    "Can't assign: Can't broadcast size %d undefined axis" %
                    domain1._axes_sizes[axis1])

            squeeze_axes1.append(axis1)
        #--- End: for

        for identity in set(v['id_to_axis']).difference(matching_ids):
            axis1 = v['id_to_axis'][identity]
            if domain1._axes_sizes[axis1] != 1:
               raise ValueError(
                    "Can't assign: Can't broadcast size %d %r axis" %
                    (domain1._axes_sizes[axis1], identity))
            
            squeeze_axes1.append(axis1)    
        #--- End: for

        if squeeze_axes1:
            if not copied:
                other = other.copy()
                copied = True

            other.squeeze(squeeze_axes1, i=True)
        #--- End: if

        # ------------------------------------------------------------
        # Permute the axes of other.Data so that they are in the same
        # order as their matching counterparts in self.Data
        #
        # For example, if   self.Data is       P T Z Y X   A
        #              and  other.Data is            Y X T
        #              then other.Data becomes   T   Y X
        # ------------------------------------------------------------
        data_axes0 = domain0.data_axes()
        data_axes1 = domain1.data_axes()
        transpose_axes1 = []       
        for axis0 in data_axes0:
            identity = s['axis_to_id'][axis0]
            if identity in matching_ids:
                axis1 = v['id_to_axis'][identity]                
                if axis1 in data_axes1:
                    transpose_axes1.append(axis1)
        #--- End: for

        if transpose_axes1 != data_axes1: 
            if not copied:
                other = other.copy()
                copied = True

            other.transpose(transpose_axes1, i=True)
        #--- End: if

        # ------------------------------------------------------------
        # Insert size 1 axes into other.Data to match axes in
        # self.Data which other.Data doesn't have.
        #
        # For example, if   self.Data is       P T Z Y X A
        #              and  other.Data is        T   Y X
        #              then other.Data becomes 1 T 1 Y X 1
        # ------------------------------------------------------------
        expand_positions1 = []
        for i, axis0 in enumerate(data_axes0):
            identity = s['axis_to_id'][axis0]
            if identity in matching_ids:
                axis1 = v['id_to_axis'][identity]
                if axis1 not in data_axes1:
                    expand_positions1.append(i)
            else:     
                expand_positions1.append(i)
        #--- End: for

        if expand_positions1:
            if not copied:
                other = other.copy()
                copied = True

            for i in expand_positions1:
                other.expand_dims(i, i=True)
        #--- End: if

        # ----------------------------------------------------------------
        # Make sure that each pair of matching axes has the same
        # direction
        # ----------------------------------------------------------------
        flip_axes1 = []
        for identity in matching_ids:
            axis1 = v['id_to_axis'][identity]
            axis0 = s['id_to_axis'][identity]
            if domain1.direction(axis1) != domain0.direction(axis0):
                flip_axes1.append(axis1)
         #--- End: for

        if flip_axes1:
            if not copied:
                other = other.copy()
                copied = True

            other = other.flip(flip_axes1, i=True)
        #--- End: if

        return other
    #--- End: def
 
    def __repr__(self):
        '''
Called by the :py:obj:`repr` built-in function.

x.__repr__() <==> repr(x)

'''
        if self._hasData:
            domain = self.domain
            x = ['%s(%d)' % (domain.axis_name(axis),
                             domain._axes_sizes[axis])
                 for axis in domain.data_axes()]
            axis_names = '(%s)' % ', '.join(x)
        else:
            axis_names = ''
        #--- End: if
            
        # Field units
        units = getattr(self, 'units', '')
        calendar = getattr(self, 'calendar', None)
        if calendar:
            units += '%s calendar' % calendar

        return '<CF Field: %s%s %s>' % (self.name(''), axis_names, units)
    #--- End: def

    def __str__(self):
        '''

Called by the :py:obj:`str` built-in function.

x.__str__() <==> str(x)

'''
        string = ["%s field summary" % self.name('')]
        string.append(''.ljust(len(string[0]), '-'))

        # Units
        units = getattr(self, 'units', '')
        calendar = getattr(self, 'calendar', None)
        if calendar:
            units += ' %s calendar' % calendar

        domain = self.domain

        # Data
        if self._hasData:
            x = ['%s(%d)' % (domain.axis_name(axis),
                             domain._axes_sizes[axis])
                 for axis in domain.data_axes()]
            
            string.append('Data           : %s(%s) %s' % (self.name(''),
                                                          ', '.join(x), units))
        elif units:
            string.append('Data           : %s' % units)

        # Cell methods
        cell_methods = getattr(self, 'cell_methods', None)
        if cell_methods is not None:
            string.append('Cell methods   : %s' % str(cell_methods))

        # Domain
        if domain:
            string.append(str(domain))
            
        # Ancillary variables
        ancillary_variables = getattr(self, 'ancillary_variables', None)
        if ancillary_variables is not None:
            y = ['Ancillary vars : ']
            y.append('\n               : '.join(
                    [repr(a) for a in ancillary_variables]))
            string.append(''.join(y))

        string.append('')

        return '\n'.join(string)
    #--- End def

    # ----------------------------------------------------------------
    # Attribute: Flags
    # ----------------------------------------------------------------
    @property
    def Flags(self):
        '''

A `cf.Flags` object containing self-describing CF flag values.

Stores the `flag_values`, `flag_meanings` and `flag_masks` CF
properties in an internally consistent manner.

:Examples:

>>> f.Flags
<CF Flags: flag_values=[0 1 2], flag_masks=[0 2 2], flag_meanings=['low' 'medium' 'high']>

'''
        return self._get_special_attr('Flags')
    @Flags.setter
    def Flags(self, value):
        self._set_special_attr('Flags', value)
    @Flags.deleter
    def Flags(self):
        self._del_special_attr('Flags')

    # ----------------------------------------------------------------
    # Attribute: read only
    # ----------------------------------------------------------------
    @property
    def rank(self):
        '''

The number of axes in the domain.

There may be greater the number of data array dimensions.

.. seealso:: `ndim`

:Examples:

>>> print f
air_temperature field summary
-----------------------------
Data           : air_temperature(time(12), latitude(64), longitude(128)) K
Cell methods   : time: mean
Axes           : time(12) = [ 450-11-16 00:00:00, ...,  451-10-16 12:00:00] noleap
               : latitude(64) = [-87.8638000488, ..., 87.8638000488] degrees_north
               : longitude(128) = [0.0, ..., 357.1875] degrees_east
               : height(1) = [2.0] m
>>> f.rank
4
>>> f.ndim
3
>>> f.unsqueeze(i=True)
<CF Field: air_temperature(height(1), time(12), latitude(64), longitude(128)) K>
>>> f.ndim
4

'''
        return self.domain.rank
    #--- End: def

    # ----------------------------------------------------------------
    # CF property: flag_values
    # ----------------------------------------------------------------
    @property
    def flag_values(self):
        '''

The flag_values CF property.

Stored as a 1-d numpy array but may be set as any array-like object.

:Examples:

>>> f.flag_values = ['a', 'b', 'c']
>>> f.flag_values
array(['a', 'b', 'c'], dtype='|S1')
>>> f.flag_values = numpy.arange(4)
>>> f.flag_values
array([1, 2, 3, 4])
>>> del f.flag_values

>>> f.setprop('flag_values', 1)
>>> f.getprop('flag_values')
array([1])
>>> f.delprop('flag_values')

'''
        try:
            return self.Flags.flag_values
        except AttributeError:
            raise AttributeError(
                "%s doesn't have CF property 'flag_values'" %
                self.__class__.__name__)
    #--- End: def
    @flag_values.setter
    def flag_values(self, value):
        try:
            flags = self.Flags
        except AttributeError:
            self.Flags = Flags(flag_values=value)
        else:
            flags.flag_values = value
    #--- End: def
    @flag_values.deleter
    def flag_values(self):
        try:
            del self.Flags.flag_values
        except AttributeError:
            raise AttributeError(
                "Can't delete non-existent %s CF property 'flag_values'" %
                self.__class__.__name__)
        else:
            if not self.Flags:
                del self.Flags
    #--- End: def

    # ----------------------------------------------------------------
    # CF property: flag_masks
    # ----------------------------------------------------------------
    @property
    def flag_masks(self):
        '''
The flag_masks CF property.

Stored as a 1-d numpy array but may be set as array-like object.

:Examples:

>>> f.flag_masks = numpy.array([1, 2, 4], dtype='int8')
>>> f.flag_masks
array([1, 2, 4], dtype=int8)
>>> f.flag_masks = (1, 2, 4, 8)
>>> f.flag_masks
array([1, 2, 4, 8], dtype=int8)
>>> del f.flag_masks

>>> f.setprop('flag_masks', 1)
>>> f.getprop('flag_masks')
array([1])
>>> f.delprop('flag_masks')

'''
        try:
            return self.Flags.flag_masks
        except AttributeError:
            raise AttributeError(
                "%s doesn't have CF property 'flag_masks'" %
                self.__class__.__name__)
    #--- End: def
    @flag_masks.setter
    def flag_masks(self, value):
        try:
            flags = self.Flags
        except AttributeError:
            self.Flags = Flags(flag_masks=value)
        else:
            flags.flag_masks = value
    #--- End: def
    @flag_masks.deleter
    def flag_masks(self):
        try:
            del self.Flags.flag_masks
        except AttributeError:
            raise AttributeError(
                "Can't delete non-existent %s CF property 'flag_masks'" %
                self.__class__.__name__)
        else:
            if not self.Flags:
                del self.Flags
    #--- End: def

    # ----------------------------------------------------------------
    # CF property: flag_meanings
    # ----------------------------------------------------------------
    @property
    def flag_meanings(self):
        '''

The flag_meanings CF property.

Stored as a 1-d numpy string array but may be set as a space delimited
string or any array-like object.

:Examples:

>>> f.flag_meanings = 'low medium      high'
>>> f.flag_meanings
array(['low', 'medium', 'high'],
      dtype='|S6')
>>> del flag_meanings

>>> f.flag_meanings = ['left', 'right']
>>> f.flag_meanings
array(['left', 'right'],
      dtype='|S5')

>>> f.flag_meanings = 'ok'
>>> f.flag_meanings
array(['ok'],
      dtype='|S2')

>>> f.setprop('flag_meanings', numpy.array(['a', 'b'])
>>> f.getprop('flag_meanings')
array(['a', 'b'],
      dtype='|S1')
>>> f.delprop('flag_meanings')

'''
        try:
            return self.Flags.flag_meanings
        except AttributeError:
            raise AttributeError(
                "%s doesn't have CF property 'flag_meanings'" %
                self.__class__.__name__)
    #--- End: def
    @flag_meanings.setter
    def flag_meanings(self, value): 
        try:
            flags = self.Flags
        except AttributeError:
            self.Flags = Flags(flag_meanings=value)
        else:
            flags.flag_meanings = value
    #--- End: def
    @flag_meanings.deleter
    def flag_meanings(self):
        try:
            del self.Flags.flag_meanings
        except AttributeError:
            raise AttributeError(
                "Can't delete non-existent %s CF property 'flag_meanings'" %
                self.__class__.__name__)
        else:
            if not self.Flags:
                del self.Flags
    #--- End: def

    # ----------------------------------------------------------------
    # CF property: cell_methods
    # ----------------------------------------------------------------
    @property
    def cell_methods(self):
        '''

The `cf.CellMethods` object containing the CF cell methods of the data
array.

:Examples:

>>> f.cell_methods
<CF CellMethods: time: maximum (interval: 1.0 month) area: mean (area-weighted)>

'''
        return self._get_special_attr('cell_methods')
    #--- End: def
    @cell_methods.setter
    def cell_methods(self, value):
        self._set_special_attr('cell_methods', value)
    @cell_methods.deleter
    def cell_methods(self):
        self._del_special_attr('cell_methods')

    # ----------------------------------------------------------------
    # CF property: Conventions	
    # ----------------------------------------------------------------
    @property
    def Conventions(self):
        '''

The Conventions CF property.

:Examples:

>>> f.Conventions = 'CF-1.5'
>>> f.Conventions
'CF-1.5'
>>> del f.Conventions

>>> f.setprop('Conventions', 'CF-1.5')
>>> f.getprop('Conventions')
'CF-1.5'
>>> f.delprop('Conventions')

'''
        return self.getprop('Conventions')
    #--- End: def

    @Conventions.setter
    def Conventions(self, value): self.setprop('Conventions', value)
    @Conventions.deleter
    def Conventions(self):        self.delprop('Conventions')

    # ----------------------------------------------------------------
    # CF property: institution (a simple attribute)
    # ----------------------------------------------------------------
    @property
    def institution(self):
        '''

The institution CF property.

:Examples:

>>> f.institution = 'University of Reading'
>>> f.institution
'University of Reading'
>>> del f.institution

>>> f.setprop('institution', 'University of Reading')
>>> f.getprop('institution')
'University of Reading'
>>> f.delprop('institution')

'''
        return self.getprop('institution')
    #--- End: def
    @institution.setter
    def institution(self, value): self.setprop('institution', value)
    @institution.deleter
    def institution(self):        self.delprop('institution')

    # ----------------------------------------------------------------
    # CF property: references (a simple attribute)
    # ----------------------------------------------------------------
    @property
    def references(self):
        '''

The references CF property.

:Examples:

>>> f.references = 'some references'
>>> f.references
'some references'
>>> del f.references

>>> f.setprop('references', 'some references')
>>> f.getprop('references')
'some references'
>>> f.delprop('references')

'''
        return self.getprop('references')
    #--- End: def
    @references.setter
    def references(self, value): self.setprop('references', value)
    @references.deleter
    def references(self):        self.delprop('references')

    # ----------------------------------------------------------------
    # CF property: standard_error_multiplier	
    # ----------------------------------------------------------------
    @property
    def standard_error_multiplier(self):
        '''

The standard_error_multiplier CF property.

:Examples:

>>> f.standard_error_multiplier = 2.0
>>> f.standard_error_multiplier
2.0
>>> del f.standard_error_multiplier

>>> f.setprop('standard_error_multiplier', 2.0)
>>> f.getprop('standard_error_multiplier')
2.0
>>> f.delprop('standard_error_multiplier')

'''
        return self.getprop('standard_error_multiplier')
    #--- End: def

    @standard_error_multiplier.setter
    def standard_error_multiplier(self, value):
        self.setprop('standard_error_multiplier', value)
    @standard_error_multiplier.deleter
    def standard_error_multiplier(self):
        self.delprop('standard_error_multiplier')

    # ----------------------------------------------------------------
    # CF property: source	
    # ----------------------------------------------------------------
    @property
    def source(self):
        '''

The source CF property.

:Examples:

>>> f.source = 'radiosonde'
>>> f.source
'radiosonde'
>>> del f.source

>>> f.setprop('source', 'surface observation')
>>> f.getprop('source')
'surface observation'
>>> f.delprop('source')

'''
        return self.getprop('source')
    #--- End: def

    @source.setter
    def source(self, value): self.setprop('source', value)
    @source.deleter
    def source(self):        self.delprop('source')

    # ----------------------------------------------------------------
    # CF property: title	
    # ----------------------------------------------------------------
    @property
    def title(self):
        '''

The title CF property.

:Examples:

>>> f.title = 'model data'
>>> f.title
'model data'
>>> del f.title

>>> f.setprop('title', 'model data')
>>> f.getprop('title')
'model data'
>>> f.delprop('title')

'''
        return self.getprop('title')
    #--- End: def

    @title.setter
    def title(self, value): self.setprop('title', value)
    @title.deleter
    def title(self):        self.delprop('title')

    # ----------------------------------------------------------------
    # Attribute: domain
    # ----------------------------------------------------------------
    @property
    def domain(self):
        '''

The `cf.Domain` object containing the field's domain.

:Examples:

>>> print f
air_temperature field summary
-----------------------------
Data           : air_temperature(time(12), latitude(64), longitude(128)) K
Cell methods   : time: mean (interval: 1.0 month)
Axes           : height(1) = [2.0] m
               : time(12) = [ 450-11-16 00:00:00, ...,  451-10-16 12:00:00] noleap
               : latitude(64) = [-87.8638000488, ..., 87.8638000488] degrees_north
               : longitude(128) = [0.0, ..., 357.1875] degrees_east
>>> f.domain
<CF Domain: height(1), time(12), latitude(64), longitude(128)>

'''
        return self._get_special_attr('domain')
    #--- End: def
    @domain.setter
    def domain(self, value):
        self._set_special_attr('domain', value)
    @domain.deleter
    def domain(self):
        self._del_special_attr('domain')

    # ----------------------------------------------------------------
    # Attribute: subspace (read only)
    # ----------------------------------------------------------------
    @property
    def subspace(self):
        '''Return a new object which will get or set a subspace of the field.

The returned object is a `!SubspaceField` object which may be
**indexed** to select a subspace by axis index values
(``f.subspace[indices]``) or **called** to select a subspace by
metadata values (``f.subspace(*exact, **metadata_values)``).

**Subspacing by indexing**

Subspacing by indices allows a subspaced field to be defined via index
values for the axes of the field's data array.

Indices to the returned `!SubspaceField` object have an extended
Python slicing syntax, which is similar to :ref:`numpy array indexing
<numpy:arrays.indexing>`, but with three extensions:

* Size 1 axes are never removed.

  An integer index i takes the i-th element but does not reduce the
  rank of the output array by one:

* The indices for each axis work independently.

  When more than one axis's slice is a 1-d boolean sequence or 1-d
  sequence of integers, then these indices work independently along
  each axis (similar to the way vector subscripts work in Fortran),
  rather than by their elements:

* Boolean indices may be any object which exposes the numpy array
  interface.

**Subspacing by metadata values**

A subspaced field may be defined via data array values of its domain
items (dimension coordinate, auciliary coordinate and cell measured
objects) by calling the `!SubspaceField` object.

``f.subspace(*exact, **metadata_values)`` is a shorthand for
``f.subspace[f.indices(*exact, **metadata_values)]``. See
`cf.Field.indices` for details.

**Assignment to subspaces**

Elements of a field's data array may be changed by assigning values to
a subspace of the field.

Assignment is only possible to a subspace defined by indices of the
returned `!SubspaceField` object. For example, ``f.subspace[indices] =
0`` is possible, but ``f.subspace(*exact, **metadata_values) = 0`` is
*not* allowed. However, assigning to a subspace defined by metadata
values may be done as follows: ``f.subspace[f.indices(*exact,
**metadata_values)] = 0``.

**Missing data**

The treatment of missing data elements during assignment to a subspace
depends on the value of field's `hardmask` attribute. If it is True
then masked elements will not be unmasked, otherwise masked elements
may be set to any value.

In either case, unmasked elements may be set, (including missing
data).

Unmasked elements may be set to missing data by assignment to the
`cf.masked` constant or by assignment to a value which contains masked
elements.

.. seealso:: `cf.masked`, `hardmask`, `indices`, `where`

:Examples:

>>> print f
Data            : air_temperature(time(12), latitude(73), longitude(96)) K
Cell methods    : time: mean
Dimensions      : time(12) = [15, ..., 345] days since 1860-1-1
                : latitude(73) = [-90, ..., 90] degrees_north
                : longitude(96) = [0, ..., 356.25] degrees_east
                : height(1) = [2] m

>>> f.shape
(12, 73, 96)
>>> f.subspace[...].shape
(12, 73, 96)
>>> f.subspace[slice(0, 12), :, 10:0:-2].shape
(12, 73, 5)
>>> lon = f.coord('X').array
>>> f.subspace[..., lon<180]

>>> f.shape
(12, 73, 96)
>>> f.subspace[0, ...].shape
(1, 73, 96)
>>> f.subspace[3, slice(10, 0, -2), 95].shape
(1, 5, 1)

>>> f.shape
(12, 73, 96)
>>> f.subspace[:, [0, 72], [5, 4, 3]].shape
(12, 2, 3)

>>> f.subspace().shape
(12, 73, 96)
>>> f.subspace(latitude=0).shape
(12, 1, 96)
>>> f.subspace(latitude=cf.wi(-30, 30)).shape
(12, 25, 96)
>>> f.subspace(long=cf.ge(270, 'degrees_east'), lat=cf.set([0, 2.5, 10])).shape
(12, 3, 24)
>>> f.subspace(latitude=cf.lt(0, 'degrees_north'))
(12, 36, 96)
>>> f.subspace(latitude=[cf.lt(0, 'degrees_north'), 90])
(12, 37, 96)
>>> import math
>>> f.subspace(longitude=cf.lt(math.pi, 'radian'), height=2)
(12, 73, 48)
>>> f.subspace(height=cf.gt(3))
IndexError: No indices found for 'height' values gt 3

>>> f.subspace(dim2=3.75).shape
(12, 1, 96)

>>> f.subspace[...] = 273.15
    
>>> f.subspace[f.indices(longitude=cf.wi(210, 270, 'degrees_east'),
...                      latitude=cf.wi(-5, 5, 'degrees_north'))] = cf.masked

>>> index = f.indices(longitude=0)
>>> f.subspace[index] = f.subspace[index] * 2

        '''
        return SubspaceField(self)
    #--- End: def

    def cell_area(self, radius=6371229.0, insert=False, force=False):
        '''{+Fef,}For each fiel

.. versionadded:: 1.0

.. seealso:: `weights`

:Examples 1:

>>> a = f.cell_area()

:Parameters:

    radius: data-like, optional
        The radius used for calculating spherical surface areas when
        both of the horizontal axes are part of a spherical polar
        coordinate system. By default *radius* has a value of
        6371229 metres. If units are not specified then units of
        metres are assumed.

        {+data-like}

          *Example:*         
            Five equivalent ways to set a radius of 6371200 metres:
            ``radius=6371200``, ``radius=numpy.array(6371200)``,
            ``radius=cf.Data(6371200)``, ``radius=cf.Data(6371200,
            'm')``, ``radius=cf.Data(6371.2, 'km')``.

    insert: `bool`, optional
        If True then{+,fef,} the calculated cell areas are also
        inserted in place as an area cell measure object. An existing
        area cell measure object for the horizontal axes will not be
        overwritten.

    force: `bool`, optional
        If True the always calculate the cell areas. By
        default{+,fef,} if there is already an area cell measure
        object for the horizontal axes then it will provide the area
        values.
        
:Returns:

    out: `cf.{+Variable}`

:Examples:

>>> a = f.cell_area()
>>> a = f.cell_area(insert=True)
>>> a = f.cell_area(force=True)
>>> a = f.cell_area(radius=cf.Data(3389.5, 'km'))

        '''
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('cell_area', kwargs2)
            
        area_clm = self.measure('area', axes=('X', 'Y'))

        if not force and area_clm:
            w = self.weights('area')
        else:
            x = self.dim('X')
            y = self.dim('Y')
            if (x is None or y is None or 
                not x.Units.equivalent(_units_radians) or
                not y.Units.equivalent(_units_radians)):
                raise ValueError("sd---------------------")
            
            # Got x and y coordinates in radians, so we can calc.
    
            # Parse the radius of the planet
            radius = Data.asdata(radius).squeeze()
            radius.dtype = float
            if radius.size != 1:
                raise ValueError("Multiple radii: radius=%r" % radius)
            if not radius.Units:
                radius.override_units(_units_m, i=True)
            elif not radius.Units.equivalent(_units_m):
                raise ValueError(
                    "Invalid units for radius: %r" % radius.Units)
                    
            w = self.weights('area')
            radius **= 2
            w *= radius
            w.override_units(radius.Units, i=True)   
        #--- End: if               

        if insert:
            # ----------------------------------------------------
            # Insert new cell measure
            # ----------------------------------------------------
            if area_clm:
                raise ValueError(
                    "Can't overwrite an existing area cell measure object")

            clm = CellMeasure(data=w.data, copy=True)
            clm.measure = 'area'
            map_axes = w.domain.map_axes(self.domain)
            data_axes = w.data_axes()
            axes = (map_axes[data_axes[0]], map_axes[data_axes[1]])
            self.insert_measure(clm, axes=axes, copy=False)
        #--- End: if               

        w.standard_name = 'area'
        w.long_name     = 'area'

        return w
    #--- End: def

    def close(self):
        '''

{+Fef,}Close all files referenced by the field.

Note that a closed file will be automatically reopened if its contents
are subsequently required.

:Examples 1:

>>> f.close()

:Returns:

    None
'''
        # List functionality
        if self._list:
            for f in self:
                f.close()
            return 

        new = super(Field, self).close()

        self.domain.close()

        ancillary_variables = getattr(self, 'ancillary_variables', None)
        if ancillary_variables is not None:
            ancillary_variables.close()
    #--- End: def

    def iscyclic(self, axes=None, **kwargs):
        '''
Returns True if the given axis is cyclic.

.. versionadded:: 1.0

.. seealso:: `axis`, `cyclic`, `period`

:Examples 1:

>>> b = f.iscyclic('X')

:Parameters:

    {+axes, kwargs}

:Returns:

    out: `bool`
        True if the selected axis is cyclic, otherwise False.
        
:Examples 2:

>>> f.cyclic()
{}
>>> f.iscyclic('X')
False
>>> f.cyclic('X', period=360)
{}
>>> f.iscyclic('X')
True

'''
        axis = self.domain.axis(axes, **kwargs)
        if axis is None:
            raise ValueError("Can't identify unique %r axis" % axes)

        return axis in self.cyclic()
    #--- End: def

    @classmethod
    def concatenate(cls, fields, axis=0, _preserve=True):
        '''

Join a sequence of fields together.

This is different to `cf.aggregate` because it does not account for
all metadata. For example, it assumes that the axis order is the same
in each field.

.. versionadded:: 1.0

.. seealso:: `cf.aggregate`, `cf.Data.concatenate`

:Parameters:

    axis: `int`, optional

:Returns:

    out: `cf.Field`

:Examples:

'''         
        field0 = fields[0]

        # List functionality
        if field0._list:
            return field0.concatenate(fields, axis=axis, _preserve=_preserve)

        if len(fields) == 1:
            return fields0.copy()
                                            
        out = super(cls, field0).concatenate(fields, axis=axis, _preserve=_preserve)
            
        # Change the axis size
        dim = field0.data_axes()[axis]        
        out.insert_axis(out.shape[axis], key=dim, replace=True)

        # ------------------------------------------------------------
        # Concatenate dimension coordinates, auxiliary coordinates and
        # cell measures
        # ------------------------------------------------------------
        for key, item in field0.items(role=('d', 'a', 'm')).iteritems():
            axes = field0.item_axes(key)

            if dim not in axes:
                # This item does not span the concatenating axis in
                # the first field
                continue

            items = [item]
            for f in fields[1:]:
                i = f.item(key)
                if i is not None:
                    items.append(i)                    
                else:
                    # This field does not have this item
                    items = None
                    break
            #--- End: for

            if not items:
                # Not every field has this item, so remove it from the
                # output field.
                out.remove_item(key)
                continue
                
            # Still here?
            try:
                item = item.concatenate(items, axis=axes.index(dim),
                                        _preserve=_preserve)
            except ValueError:
                # Couldn't concatenate this item, so remove it from
                # the output field.
                out.remove_item(key)
                continue

            if item.isdimension:
                out.insert_dim(item, key=key, copy=False, replace=True)
            elif item.isauxiliary:
                out.insert_aux(item, key=key, axes=axes, copy=False,
                               replace=True)
            elif item.ismeasure:
                out.insert_measure(item, key=key, axes=axes,
                                   copy=False, replace=True)
        #--- End: for

        # ------------------------------------------------------------
        # Concatenate ancillary variables
        # ------------------------------------------------------------
        ancillary_variables = getattr(out, 'ancillary_variables', None)
        if ancillary_variables:
            domain = out.domain
            n_avs = len(ancillary_variables)

            avs = [av]   #BBBBBBBUUUUUUUGGGGGGGGGGGGG I'm sure. What is av?
            for f in fields[1:]:
                avs1 = getattr(f, 'ancillary_variables', None)
                if avs1 is not None and len(avs1) == n_avs:
                    avs.append(avs1)
                else:
                    avs = None
                    break
            #--- End: for

            if not avs:
                del out.ancillary_variables
            else:
                out_avs = []
                for i in range(n_avs):
                    av0 = avs[0][i]
                    try:
                        iaxis = av0.data_axes().index(domain.map_axes(av0)[dim])
                        new_av = av0.concatenate([a[i] for a in avs],
                                                 axis=iaxis,
                                                 _preserve=_preserve)
                    except (KeyError, ValueError):
                        # Couldn't concatenate these ancillary
                        # variable fields
                        continue
                    else:
                        # Successfully concatenated these ancillary
                        # variable fields, so put the result in the
                        # output field.
                        out_avs.append(new_av)
                #--- End: for

                if out_avs:
                    out.ancillary_variables = FieldList(out_avs)
                else:
                    del out.ancillary_variables 
            #--- End: if
        #--- End: if        

        # ------------------------------------------------------------
        # Concatenate coordinate references
        # ------------------------------------------------------------

        return out
    #--- End: def

    def cyclic(self, axes=None, iscyclic=True, period=None, **kwargs):
        '''Set the cyclicity of an axis.

A unique axis is selected with the *axes* and *kwargs* parameters.

.. versionadded:: 1.0

.. seealso:: `autocyclic`, `axis`, `iscyclic`, `period`

`int`

:Examples 1:

Set the X axis to be periodic, with a period of 360:

>>> s = f.cyclic('X', period=360)

:Parameters:

    {+axes, kwargs}

    iscyclic: `bool`, optional
        If False then the axis is set to be non-cyclic. By default the
        selected axis is set to be cyclic.

    period: data-like object, optional       
        The period for a dimension coordinate object which spans the
        selected axis. The absolute value of *period* is used. If
        *period* has units then they must be compatible with those of
        the dimension coordinates, otherwise it is assumed to have the
        same units as the dimension coordinates.

        {+data-like}

:Returns:

    out: `set`
        The axes of the field which were cyclic prior to the new
        setting, or the current cyclic axes if no axis was specified.

:Examples:

>>> f.axes('X')
{'dim3'}
>>> f.cyclic()
{}
>>> f.cyclic('X', period=360)
{}
>>> f.cyclic()
{'dim3'}
>>> f.cyclic('X', False)
{'dim3'}
>>> f.cyclic()
{}
>>> f.cyclic('longitude', period=360, exact=True)
{}
>>> f.cyclic()
{'dim3'}
>>> f.cyclic('dim3', False)
{'dim3'}
>>> f.cyclic()
{}

        '''       
        try:
            data = self.Data
        except AttributeError:
            return set()

        data_axes = self.data_axes()
        old = set([data_axes[i] for i in data.cyclic()])

        if axes is None and not kwargs:            
            return old
        
        axis = self.domain.axis(axes, **kwargs)
        if axis is None:
            raise ValueError("879534 k.j asdm,547`")

        try:
            data.cyclic(data_axes.index(axis), iscyclic)
        except ValueError:
            pass

        if iscyclic:
            dim = self.dim(axis)
            if dim is not None:
                if period is not None:
                    dim.period(period)
                elif dim.period() is None:
                    raise ValueError(
                        "A cyclic dimension coordinate must have a period")
        #--- End: if

        return old
    #--- End: def

    def weights(self, weights='auto', scale=False, components=False,
                methods=False, **kwargs):
        '''{+Fef,}Return weights for the data array values.

By default weights components are created for all axes of the field by
one or more of the following methods, in order of preference,
                        
  1. Volume cell measures
  2. Area cell measures
  3. Area calculated from (grid) latitude and (grid) longitude
     dimension coordinates with bounds
  4. Cell sizes of dimension coordinates with bounds
  5. Equal weights

and the outer product of these weights components is returned in a
field which is broadcastable to the orginal field (see the
*components* parameter).

The methods used by the default behaviour may differ between fields,
depending on which metadata they contain (see the *methods*
parameter), so it is possible to force weights to be created with
particular methods (see the *weights* parameter).

.. versionadded:: 1.0

.. seealso:: `cell_area`, `collapse`

:Examples 1:

>>> g = f.weights()

:Parameters:

    weights, kwargs: optional
        Specify the weights to be created. There are two distinct
        methods: **type 1** will always succeed in creating weights
        for all axes of the field, at the expense of not always being
        able to control exactly how the weights are created (see the
        *methods* parameter); **type 2** allows particular types of
        weights to be defined for particular axes and an exception
        will be raised if it is not possible to the create weights.

          * **Type 1**: *weights* may be one of:
        
               ==========  ==================================================
               *weights*   Description
               ==========  ==================================================
               ``'auto'``  This the default. Weights are created for
                           non-overlapping subsets of the axes by the methods
                           enumerated in the above notes. Set the *methods*
                           parameter to find out how the weights were
                           actually created.
                               
               `None`      Equal weights for all axes.
               ==========  ==================================================

       ..

          * **Type 2**: *weights* may be one, or a sequence, of:
          
              ============  ==============================================
              *weights*     Description     
              ============  ==============================================
              ``'area'``    Cell area weights from the field's area cell
                            measure construct or, if one doesn't exist,
                            from (grid) latitude and (grid) longitude
                            dimension coordinates. Set the *methods*
                            parameter to find out how the weights were
                            actually created.
              
              ``'volume'``  Cell volume weights from the field's volume
                            cell measure construct.
              
              items         Weights from the cell sizes of the dimension
                            coordinate objects that would be selected by
                            this call of the field's `~cf.Field.dims`
                            method: ``f.dims(items, **kwargs)``. See
                            `cf.Field.dims` for details.
              
              `cf.Field`    Take weights from the data array of another
                            field, which must be broadcastable to this
                            field.
              ============  ==============================================
 
            If *weights* is a sequence of any combination of the above
            then the returned field contains the outer product of the
            weights defined by each element of the sequence. The
            ordering of the sequence is irrelevant.

              *Example:*
                To create to 2-dimensional weights based on cell
                areas: ``f.weights('area')``. To create to
                3-dimensional weights based on cell areas and linear
                height: ``f.weights(['area', 'Z'])``.

    scale: `bool`, optional
        If True then scale the returned weights so that they are less
        than or equal to 1.

    components: `bool`, optional
        If True then a dictionary of orthogonal weights components is
        returned instead of a field. Each key is a tuple of integers
        representing axes positions in the field's data array with
        corresponding values of weights in `cf.Data` objects. The axes
        of weights match the axes of the field's data array in the
        order given by their dictionary keys.

    methods: `bool`, optional
        If True, then return a dictionary describing methods used to
        create the weights.

:Returns:

    out: `cf.Field` or `dict`
        The weights field or, if *components* is True, orthogonal
        weights in a dictionary.

:Examples 2:

>>> f
[+1]<CF Field: air_temperature(time(1800), latitude(145), longitude(192)) K>
[+N][<CF Field: air_temperature(time(1800), latitude(145), longitude(192)) K>]
>>> f.weights()
[+1]<CF Field: long_name:weight(time(1800), latitude(145), longitude(192)) 86400 s.rad>
[+N][<CF Field: long_name:weight(time(1800), latitude(145), longitude(192)) 86400 s.rad>]
>>> f.weights('auto', scale=True)
[+1]<CF Field: long_name:weight(time(1800), latitude(145), longitude(192)) 1>
[+N][<CF Field: long_name:weight(time(1800), latitude(145), longitude(192)) 1>]
[+1]>>> f.weights('auto', components=True)
[+1]{(0,): <CF Data: [1.0, ..., 1.0] d>,
[+1] (1,): <CF Data: [5.94949998503e-05, ..., 5.94949998503e-05]>,
[+1] (2,): <CF Data: [0.0327249234749, ..., 0.0327249234749] radians>}
[+1]>>> f.weights('auto', components=True, scale=True)
[+1]{(0,): <CF Data: [1.0, ..., 1.0]>,
[+1] (1,): <CF Data: [0.00272710399807, ..., 0.00272710399807]>,
[+1] (2,): <CF Data: [1.0, ..., 1.0]>}
[+1]>>> f.weights('auto', methods=True)
[+1]{(0,): 'linear time',
[+1] (1,): 'linear sine latitude',
[+1] (2,): 'linear longitude'}

        '''
        def _field_of_weights(data, domain=None, axes=None):
            '''Return a field of weights with long_name ``'weight'``.

    :Parameters:
    
        data: cf.Data
            The weights which comprise the data array of the weights
            field.

        domain: `cf.Domain`, optional
            The domain for the weights field. Not required if *data*
            is scalar.

        axes: list, optional

    :Returns:

        out: `cf.Field`

            '''
            w = type(self)(domain=domain, data=data, axes=axes, copy=False)
            w.long_name = 'weight'
            w.comment   = 'Weights for %r' % self
            return w
        #--- End: def

        def _measure_weights(self, measure, comp, weights_axes, auto=False):
            '''
Cell measure weights
'''
            m = self.domain.items(measure, role='m', exact=True)
           
            if not m:
                if measure == 'area':
                    return False
                if auto:
                    return
                raise ValueError(
                    "Can't get weights: No %r cell measure" % measure)
            
            key, clm = m.popitem()    
            
            if m:
                if auto:
                    return False
                raise ValueError("Multiple area cell measures")
                
            clm_axes0 = self.domain.item_axes(key)
            
            clm_axes = [axis for axis, n in izip(clm_axes0, clm.shape)
                        if n > 1]
                
            for axis in clm_axes:
                if axis in weights_axes:
                    if auto:
                        return False
                    raise ValueError(
                        "Multiple weights specifications for %r axis" % 
                        self.domain.axis_name(axis))
                
            clm = clm.Data.copy()
            if clm_axes != clm_axes0:
                iaxes = [clm_axes0.index(axis) for axis in clm_axes]
                clm.squeeze(iaxes, i=True)
            
            if methods:
                comp[tuple(clm_axes)] = measure+' cell measure'
            else:    
                comp[tuple(clm_axes)] = clm
                
            weights_axes.update(clm_axes)
            
            return True
        #--- End: def
        
        def _linear_weights(self, axis, comp, weights_axes, auto=False):
            # ------------------------------------------------------------
            # 1-d linear weights from dimension coordinates
            # ------------------------------------------------------------            
            d = self.dims(axis)
            if not d:
                if auto:
                    return
                raise ValueError("Can't find axis matching %r" % axis)

            axis, dim = d.popitem()

            if d:         
                if auto:
                    return
                raise ValueError("Multiple axes matching %r" % axis)
            
            if dim.size == 1:
                return

            if axis in weights_axes:
                if auto:
                    return
                raise ValueError(
                    "Multiple weights specifications for %r axis" % 
                    self.domain.axis_name(axis))            

            if not dim.hasbounds:
                if auto:
                    return
                raise ValueError(
                    "Can't find linear weights for %r axis: No bounds" % 
                    dim.name(default=''))

            if dim.hasbounds:
                if methods:
                    comp[(axis,)] = 'linear '+dim.name(default='')
                else: 
                    comp[(axis,)] = dim.cellsize
            #--- End: if

            weights_axes.add(axis)
        #--- End: def
            
        def _area_weights_XY(self, comp, weights_axes, auto=False): 
            # ----------------------------------------------------
            # Calculate area weights from X and Y dimension
            # coordinates
            # ----------------------------------------------------
            xdims = self.dims({None: 'X', 'units': 'radians'})
            ydims = self.dims({None: 'Y', 'units': 'radians'})
            
            if not (xdims and ydims):
                if auto:
                    return
                raise ValueError(
"Insufficient coordinate constructs for calculating area weights")
                
            xaxis, xcoord = xdims.popitem()
            yaxis, ycoord = ydims.popitem()
                
            if xdims or ydims:
                if auto:
                    return
                raise ValueError(
"Ambiguous coordinate constructs for calculating area weights")
            
            for axis in (xaxis, yaxis):                
                if axis in weights_axes:
                    if auto:
                        return
                    raise ValueError(
                        "Multiple weights specifications for %r axis" % 
                        self.axis_name(axis))

            if xcoord.size > 1:
                if not xcoord.hasbounds: 
                    if auto:
                        return
                    raise ValueError(
                        "Can't find area weights: No bounds for %r axis" % 
                        xcoord.name(default=''))

                if methods:
                    comp[(xaxis,)] = 'linear '+xcoord.name(default='')
                else:
                    cells = xcoord.cellsize
                    cells.Units = _units_radians
                    comp[(xaxis,)] = cells

                weights_axes.add(xaxis)
            #--- End: if

            if ycoord.size > 1:
                if not ycoord.hasbounds:
                    if auto:
                        return
                    raise ValueError(
                        "Can't find area weights: No bounds for %r axis" % 
                        ycoord.name(default=''))

                ycoord = ycoord.clip(-90, 90, units=Units('degrees'))
                ycoord = ycoord.sin(i=True)
    
                if methods:
                    comp[(yaxis,)] = 'linear sine '+ycoord.name(default='')
                else:            
                    comp[(yaxis,)] = ycoord.cellsize

                weights_axes.add(yaxis)
            #--- End: if
        #--- End: def

        def _field_weights(self, fields, comp, weights_axes):
            # ------------------------------------------------------------
            # Field weights
            # ------------------------------------------------------------
            s = self.domain.analyse()

            for f in fields:
                t = f.domain.analyse()
    
                if t['undefined_axes']:
                    if t.axes(size=gt(1)).intersection(t['undefined_axes']):
                        raise ValueError("345jn456jn")
    
                f = f.squeeze()
    
                axes_map = {}
                
                for axis1 in f.data_axes():
                    identity = t['axis_to_id'].get(axis1, None)
                    if identity is None:
                        raise ValueError(
                            "Weights field has unmatched, size > 1 %r axis" %
                            f.axis_name(axis1))
                    
                    axis0 = s['id_to_axis'].get(identity, None)
                    if axis0 is None:
                        raise ValueError(
                            "Weights field has unmatched, size > 1 %r axis" %
                            identity)
                                    
                    axes_map[axis1] = axis0
    
                    if f.axis_size(axis1) != self.axis_size(axis0):
                        raise ValueError(
"Weights field has incorrectly sized %r axis (%d != %d)" % 
(identity, f.axis_size(axis1), self.axis_size(axis0)))
    
                    # Check that the defining coordinate data arrays are
                    # compatible
                    coord0 = s['axis_to_coord'][axis0]
                    coord1 = t['axis_to_coord'][axis1]
    
                    if not coord0._equivalent_data(coord1):
                        raise ValueError(
                            "Weights field has incompatible %r coordinates" %
                            identity)
    
                    # Still here? Then the defining coordinates have
                    # equivalent data arrays
    
                    # If the defining coordinates are attached to
                    # coordinate references then check that those coordinate references are
                    # equivalent
                    key0 = s['id_to_key'][identity]                
                    key1 = t['id_to_key'][identity]
    
                    equivalent_refs = True
                    for ref0 in self.refs().itervalues():
                        if key0 not in ref0.coords:
                            continue
    
                        equivalent_refs = False
                        for ref1 in g.refs().itervalues():
                            if key1 not in ref1.coords:
                                continue
    
                            # Each defining coordinate has a
                            # coordinate reference ...
                            if self.domain.equivalent_refs(ref0, ref1, f.domain):
                                # ... and those coordinate references are equivalent
                                equivalent_refs = True
                            #--- End: if
    
                            break
                        #--- End: for
    
                        break
                    #--- End: for
       
                    if not equivalent_refs:
                        raise ValueError(
"Input weights field has incompatible coordinate references")
                #--- End: for
    
                f_axes = tuple([axes_map[axis1] for axis1 in f.data_axes()])
            
                for axis1 in f_axes:
                    if axis1 in weights_axes:
                        raise ValueError(
                            "Multiple weights specified for %r axis" % 
                            self.axis_name(axes_map[axis1]))
                #--- End: if
    
                comp[f_axes] = f.Data
            
                weights_axes.update(f_axes)
        #--- End: def

        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            if components:
                raise ValueError("oooo 2")
            if methods:
                raise ValueError("oooo 3")
            return self._list_method('weights', kwargs2)

        if weights is None:
            # --------------------------------------------------------
            # All equal weights
            # --------------------------------------------------------
            if components:
                # Return an empty components dictionary
                return {}
            
            # Return a field containing a single weight of 1
            return _field_of_weights(Data(1.0, '1'))
        #--- End: if

        # Still here?
        if methods:
            components = True

        comp         = {}
        data_axes    = self.domain.data_axes()
        weights_axes = set()

        if isinstance(weights, basestring) and weights == 'auto':
            # --------------------------------------------------------
            # Autodetect all weights
            # --------------------------------------------------------

            # Volume weights
            _measure_weights(self, 'volume', comp, weights_axes, auto=True)

            # Area weights
            if not _measure_weights(self, 'area', comp, weights_axes, auto=True):
                _area_weights_XY(self, comp, weights_axes, auto=True)

            # 1-d linear weights from dimension coordinates
            for axis in self.dims(): #.keys():                
                _linear_weights(self, axis, comp, weights_axes, auto=True)
 
        elif isinstance(weights, dict):
            # --------------------------------------------------------
            # Dictionary of components
            # --------------------------------------------------------
            for key, value in weights.iteritems():                
                try:
                    key = [data_axes[iaxis] for iaxis in key]
                except IndexError:
                    raise ValueError("s ^^^^^^ csdcvd 3456 4")

                multiple_weights = weights_axes.intersection(key)
                if multiple_weights:
                    raise ValueError(
                        "Multiple weights specifications for %r axis" % 
                        self.domain.axis_name(multiple_weights.pop()))
                #--- End: if
                weights_axes.update(key)

                comp[tuple(key)] = value.copy()
            #--- End: for
        else:

            fields = []
            axes   = []
            
            if isinstance(weights, basestring) and weights in ('area', 'volume'):
                cell_measures = (weights,)
            else:
                cell_measures = []
                for w in tuple(weights):
                    if isinstance(w, self.__class__):
                        fields.append(w)
                    elif w in ('area', 'volume'):
                        cell_measures.append(w)
                    else:
                        axes.append(w)
            #--- End: if
            
            # Field weights
            _field_weights(self, fields, comp, weights_axes)

            # Volume weights
            if 'volume' in cell_measures:
                _measure_weights(self, 'volume', comp, weights_axes)
            
            # Area weights
            if 'area' in cell_measures:
                if not _measure_weights(self, 'area', comp, weights_axes):
                    _area_weights_XY(self, comp, weights_axes)      

            # 1-d linear weights from dimension coordinates
            for axis in axes:
                _linear_weights(self, axis, comp, weights_axes, auto=False)
        #--- End: if

        # ------------------------------------------------------------
        # Scale the weights so that they are <= 1.0
        # ------------------------------------------------------------
        if scale and not methods:
            # What to do about -ve weights? dch
            for key, w in comp.items(): 
                wmax = w.data.max()    
                if wmax > 0:
                    wmax.dtype = float
                    if not numpy_can_cast(wmax.dtype, w.dtype):
                        w = w / wmax
                    else:
                        w /= wmax
                    comp[key] = w
        #--- End: if

        if components:
            # --------------------------------------------------------
            # Return a dictionary of component weights, which may be
            # empty.
            # -------------------------------------------------------- 
            components = {}
            for key, v in comp.iteritems():
                key = [data_axes.index(axis) for axis in key]
                if not key:
                    continue

                components[tuple(key)] = v
            #--- End: for

            return components
        #--- End: if

        if methods:
            return components

        if not comp:
            # --------------------------------------------------------
            # No component weights have been defined so return an
            # equal weights field
            # --------------------------------------------------------
            return _field_of_weights(Data(1.0, '1'))
        
        # ------------------------------------------------------------
        # Return a weights field which is the outer product of the
        # component weights
        # ------------------------------------------------------------
        pp = sorted(comp.items())       
        waxes, wdata = pp.pop(0)
        while pp:
            a, y = pp.pop(0)
            wdata.outerproduct(y, i=True)
            waxes += a
        #--- End: while

        wdomain = self.domain.copy()

        asd = wdomain.axes().difference(weights_axes)

#        wdomain.dimensions.pop('data', None)
        wdomain._axes.pop('data', None)
        wdomain.remove_items(wdomain.items(axes=asd).keys())
        wdomain.remove_axes(asd) 

        return _field_of_weights(wdata, wdomain, waxes)
    #--- End: def
#(any object which may be used to
#            initialise a `cf.Data` instance)
   
# rolling_window=None, window_weights=None,
#
#    rolling_window: optional
#        Group the axis elements for a "rolling window" collapse. The
#        axis is grouped into **consecutive** runs of **overlapping**
#        elements. The first group starts at the first element of the
#        axis and each following group is offset by one element from
#        the previous group, so that an element may appear in multiple
#        groups. The collapse operation is applied to each group
#        independently and the collapsed axis in the returned field
#        will have a size equal to the number of groups. If weights
#        have been given by the *weights* parameter then they are
#        applied to each group, unless alternative weights have been
#        provided with the *window_weights* parameter. The
#        *rolling_window* parameter may be one of:
#
#          * An `int` defining the number of elements in each
#            group. Each group will have exactly this number of
#            elements. Note that if the group size does does not divide
#            exactly into the axis size then some elements at the end
#            of the axis will not be included in any group.
#            
#              Example: To define groups of 5 elements:
#              ``rolling_window=5``.
#
#        .. 
#
#          * A `cf.Data` defining the group size. Each group contains a
#            consecutive run of elements whose range of coordinate
#            bounds does not exceed the group size. Note that 1) if the
#            group size is sufficiently small then some groups may be
#            empty and some elements may not be inside any group may
#            not be inside any group; 2) different groups may contain
#            different numbers of elements.
#
#              Example: To create 10 kilometre windows:
#              ``rolling_window=cf.Data(10, 'km')``.
#
#    window_weights: ordered sequence of numbers, optional
#        Specify the weights for a rolling window collapse. Each
#        non-empty group uses these weights in its collapse, and all
#        non-empty groups must have the same number elements as the
#        window weights. If *window_weights* is not set then the groups
#        take their weights from the *weights* parameter, and in this
#        case the groups may have different sizes.
#
#          Example: To define a 1-2-1 smoothing filter:
#          ``rolling_window=3, window_weights=[1, 2, 1]``.

    def collapse(self, method, axes=None, squeeze=False, mtol=1,
                 weights='auto', ddof=1, a=None, i=False, group=None,
                 regroup=False, within_days=None, within_years=None,
                 over_days=None, over_years=None,
                 coordinate='mid_range', group_by='coords', **kwargs):
        r'''

{+Fef,}Collapse axes of the field. 

Collapsing an axis involves reducing its size with a given (typically
statistical) method.

By default all axes with size greater than 1 are collapsed completely
with the given method. For example, to find the minumum of the data
array:

>>> g = f.collapse('min')

By default the calculations of means, standard deviations and
variances use a combination of volume, area and linear weights based
on the field's metadata. For example to find the mean of the data
array, weighted where possible:

>>> g = f.collapse('mean')

Specific weights may be forced with the weights parameter. For example
to find the variance of the data array, weighting the X and Y axes by
cell area, the T axis linearly and leaving all other axes unweighted:

>>> g = f.collapse('variance', weights=['area', 'T'])

A subset of the axes may be collapsed. For example, to find the mean
over the time axis:

>>> f
[+1]<CF Field: air_temperature(time(12), latitude(73), longitude(96) K>
[+N][<CF Field: air_temperature(time(12), latitude(73), longitude(96) K>]
>>> g = f.collapse('T: mean')
>>> g
[+1]<CF Field: air_temperature(time(1), latitude(73), longitude(96) K>
[+N][<CF Field: air_temperature(time(1), latitude(73), longitude(96) K>]

For example, to find the maximum over the time and height axes:

>>> g = f.collapse('T: Z: max')

or, equivalently:

>>> g = f.collapse('max', axes=['T', 'Z'])

An ordered sequence of collapses over different (or the same) subsets
of the axes may be specified. For example, to first find the mean over
the time axis and subequently the standard deviation over the latitude
and longitude axes:

>>> g = f.collapse('T: mean area: sd')

or, equivalently, in two steps:

>>> g = f.collapse('mean', axes='T').collapse('sd', axes='area')

Grouped collapses are possible, whereby groups of elements along an
axis are defined and each group is collapsed independently. The
collapsed groups are concatenated so that the collapsed axis in the
output field has a size equal to the number of groups. For example, to
find the variance along the longitude axis within each group of size
10 degrees:

>>> g = f.collapse('longitude: variance', group=cf.Data(10, 'degrees'))

Climatological statistics (a type of grouped collapse) as defined by
the CF conventions may be specified. For example, to collapse a time
axis into multiannual means of calendar monthly minima:

>>> g = f.collapse('time: minimum within years T: mean over years',
...                 within_years=cf.M())

In all collapses, missing data array elements are accounted for in the
calculation.

The following collapse methods are available, over any subset of the
axes:

=========================  =====================================================
Method                     Notes
=========================  =====================================================
Maximum                    The maximum of the values.
                           
Minimum                    The minimum of the values.
                                    
Sum                        The sum of the values.
                           
Mid-range                  The average of the maximum and the minimum of the
                           values.
                           
Range                      The absolute difference between the maximum and
                           the minimum of the values.
                           
Mean                       The unweighted mean, :math:`m`, of :math:`N`
                           values :math:`x_i` is
                           
                           .. math:: m=\frac{1}{N}\sum_{i=1}^{N} x_i
                           
                           The weighted mean, :math:`\tilde{m}`, of :math:`N`
                           values :math:`x_i` with corresponding weights
                           :math:`w_i` is
                           

                           .. math:: \tilde{m}=\frac{1}{\sum_{i=1}^{N} w_i}
                                               \sum_{i=1}^{N} w_i x_i
                           
Standard deviation         The unweighted standard deviation, :math:`s`, of
                           :math:`N` values :math:`x_i` with mean :math:`m`
                           and with :math:`N-ddof` degrees of freedom
                           (:math:`ddof\ge0`) is
                           
                           .. math:: s=\sqrt{\frac{1}{N-ddof}
                                       \sum_{i=1}^{N} (x_i - m)^2}
                           
                           The weighted standard deviation,
                           :math:`\tilde{s}_N`, of :math:`N` values
                           :math:`x_i` with corresponding weights
                           :math:`w_i`, weighted mean
                           :math:`\tilde{m}` and with :math:`N`
                           degrees of freedom is
                           
                           .. math:: \tilde{s}_N=\sqrt{\frac{1}
                                         {\sum_{i=1}^{N} w_i}
                                         \sum_{i=1}^{N} w_i(x_i -
                                         \tilde{m})^2}
                           
                           The weighted standard deviation,
                           :math:`\tilde{s}`, of :math:`N` values
                           :math:`x_i` with corresponding weights
                           :math:`w_i` and with :math:`N-ddof` degrees
                           of freedom :math:`(ddof>0)` is
                           
                           .. math:: \tilde{s}=\sqrt{ \frac{a
                                     \sum_{i=1}^{N} w_i}{a
                                     \sum_{i=1}^{N} w_i - ddof}}
                                     \tilde{s}_N
                           
                           where :math:`a` is the smallest positive
                           number whose product with each weight is an
                           integer. :math:`a \sum_{i=1}^{N} w_i` is
                           the size of a new sample created by each
                           :math:`x_i` having :math:`aw_i` repeats. In
                           practice, :math:`a` may not exist or may be
                           difficult to calculate, so :math:`a` is
                           either set to a predetermined value or an
                           approximate value is calculated (see the
                           *a* parameter for details).
                           
Variance                   The variance is the square of the standard
                           deviation.
                           
Sample size                The sample size, :math:`N`, as would be used for 
                           other statistical calculations.
                           
Sum of weights             The sum of sample weights,
                           :math:`\sum_{i=1}^{N} w_i`, as would be
                           used for other statistical calculations.

Sum of squares of weights  The sum of squares of sample weights,
                           :math:`\sum_{i=1}^{N} {w_i}^{2}`,
                           as would be used for other statistical
                           calculations.
=========================  =====================================================


.. versionadded:: 1.0

.. seealso:: `cell_area`, `weights`, `max`, `mean`, `mid_range`,
             `min`, `range`, `sample_size`, `sd`, `sum`, `var`


:Parameters:

    method: `str`
        Define the collapse method. All of the axes specified by the
        *axes* parameter are collapsed simultaneously by this
        method. The method is given by one of the following strings:

          ========================================  =========================
          *method*                                  Description
          ========================================  =========================
          ``'max'`` or ``'maximum'``                Maximum                  
          ``'min'`` or ``'minimum'``                Minimum                      
          ``'sum'``                                 Sum                      
          ``'mid_range'``                           Mid-range                
          ``'range'``                               Range                    
          ``'mean'`` or ``'average'`` or ``'avg'``  Mean                         
          ``'sd'`` or ``'standard_deviation'``      Standard deviation       
          ``'var'`` or ``'variance'``               Variance                 
          ``'sample_size'``                         Sample size                      
          ``'sum_of_weights'``                      Sum of weights           
          ``'sum_of_weights2'``                     Sum of squares of weights
          ========================================  =========================

        An alternative form is to provide a CF cell methods-like
        string. In this case an ordered sequence of collapses may be
        defined and both the collapse methods and their axes are
        provided. The axes are interpreted as for the *axes*
        parameter, which must not also be set. For example:
          
        >>> g = f.collapse('time: max (interval 1 hr) X: Y: mean dim3: sd')
        
        is equivalent to:
        
        >>> g = f.collapse('max', axes='time')
        >>> g = g.collapse('mean', axes=['X', 'Y'])
        >>> g = g.collapse('sd', axes='dim3')    

        Climatological collapses are carried out if a *method* string
        contains any of the modifiers ``'within days'``, ``'within
        years'``, ``'over days'`` or ``'over years'``. For example, to
        collapse a time axis into multiannual means of calendar
        monthly minima:

        >>> g = f.collapse('time: minimum within years T: mean over years',
        ...                 within_years=cf.M())
          
        which is equivalent to:
          
        >>> g = f.collapse('time: minimum within years', within_years=cf.M())
        >>> g = g.collapse('mean over years', axes='T')

    axes, kwargs: optional  
        The axes to be collapsed. The axes are those that would be
        selected by this call of the field's `axes` method:
        ``f.axes(axes, **kwargs)``. See `cf.Field.axes` for
        details. If an axis has size 1 then it is ignored. By default
        all axes with size greater than 1 are collapsed. If *axes* has
        the special value ``'area'`` then it is assumed that the X and
        Y axes are intended.

          *Example:*

            ``axes='area'`` is equivalent to ``axes=['X',
            'Y']``. ``axes=['area', Z']`` is equivalent to
            ``axes=['X', 'Y', 'Z']``.


    weights: optional
        Specify the weights for the collapse. The weights are those
        that would be returned by this call of the field's
        `~cf.Field.weights` method: ``f.weights(weights,
        components=True)``. By default weights is ``'auto'``, meaning
        that weights for all axes are created from the field's
        metadata by one or more of the following methods, in order of
        preference,
                        
          1. Cell volume (from cell measures)
          2. Cell area (from cell measures)
          3. Cell area calculated from (grid) latitude and (grid)
             longitude dimension coordinates with bounds
          4. Cell sizes of dimension coordinates with bounds
          5. Equal weights

        See `cf.Field.weights` for details.

          *Example:*
            To specify weights based on cell areas use
            ``weights='area'``. To specify weights based on cell areas
            and linearly in the vertical you could set
            ``weights=('area', 'Z')``.

    squeeze: `bool`, optional
        If True then size 1 collapsed axes are removed from the output
        data array. By default the axes which are collapsed are
        retained in the result's data array.

    mtol: `number`, optional        
        Set the fraction of input array elements which is allowed to
        contain missing data when contributing to an individual output
        array element. Where this fraction exceeds *mtol*, missing
        data is returned. The default is 1, meaning that a missing
        datum in the output array only occurs when its contributing
        input array elements are all missing data. A value of 0 means
        that a missing datum in the output array occurs whenever any
        of its contributing input array elements are missing data. Any
        intermediate value is permitted.

          *Example:*
            To ensure that an output array element is a missing datum
            if more than 25% of its input array elements are missing
            data: ``mtol=0.25``.

    ddof: number, optional
        The delta degrees of freedom in the calculation of a standard
        deviation or variance. The number of degrees of freedom used
        in the calculation is (N-*ddof*) where N represents the number
        of non-missing elements. By default *ddof* is 1, meaning the
        standard deviation and variance of the population is estimated
        according to the usual formula with (N-1) in the denominator
        to avoid the bias caused by the use of the sample mean
        (Bessel's correction).

    a: optional
        Specify the value of :math:`a` in the calculation of a
        weighted standard deviation or variance when the *ddof*
        parameter is greater than 0. See the notes above for
        details. A value is required each output array element, so *a*
        must be a single number or else a field which is broadcastable
        to the collapsed field. By default the calculation of each
        output array element uses an approximate value of *a* which is
        the smallest positive number whose products with the smallest
        and largest of the contributing weights, and their sum, are
        all integers. In this case, a positive number is considered to
        be an integer if its decimal part is sufficiently small (no
        greater than 10\ :sup:`-8` plus 10\ :sup:`-5` times its
        integer part).

          *Example:*            
             To guarantee that :math:`\tilde{s}` is exact when the
             weights for each output array element are collectively
             coprime integers: ``a=1``.

          *Note:*
            * The default approximation will never overestimate
              :math:`a`, so :math:`\tilde{s}` will always greater than
              or equal to its true value when :math:`a` is not
              specified.

    coordinate: `str`, optional
        Set how the cell coordinate values for collapsed axes are
        defined. This has no effect on the cell bounds for the
        collapsed axes, which always represent the extrema of the
        input coordinates. Valid values are:

          ===============  ===========================================
          *coordinate*     Description
          ===============  ===========================================        
          ``'mid_range'``  An output coordinate is the average of the
                           first and last input coordinate bounds (or
                           the first and last coordinates if there are
                           no bounds). This is the default.
                           
          ``'min'``        An output coordinate is the minimum of the
                           input coordinates.
                           
          ``'max'``        An output coordinate is the maximum of the
                           input coordinates.
          ===============  ===========================================
       
    group: optional        
        Independently collapse groups of axis elements. Upon output,
        the results of the collapses are concatenated so that the
        output axis has a size equal to the number of groups. The
        *group* parameter defines how the elements are partitioned
        into groups, and may be one of:

          * A `cf.Data` defining the group size in terms of ranges of
            coordinate values. The first group starts at the first
            coordinate bound of the first axis element (or its
            coordinate if there are no bounds) and spans the defined
            group size. Each susbsequent group immediately follows the
            preceeeding one. By default each group contains the
            consective run of elements whose coordinate values lie
            within the group limits (see the *group_by* parameter).

              *Example:*
                To define groups of 10 kilometres: ``group=cf.Data(10,
                'km')``.

              *Note:*
                * By default each element will be in exactly one
                  group (see the *group_by* parameter).
                * Groups may contain different numbers of elements.
                * If no units are specified then the units of the
                  coordinates are assumed.

        ..

          * A `cf.TimeDuration` defining the group size in terms of
            calendar months and years or other time intervals. The
            first group starts at or before the first coordinate bound
            of the first axis element (or its coordinate if there are
            no bounds) and spans the defined group size. Each
            susbsequent group immediately follows the preceeeding
            one. By default each group contains the consective run of
            elements whose coordinate values lie within the group
            limits (see the *group_by* parameter).

              *Example:*
                To define groups of 5 days, starting and ending at
                midnight on each day: ``group=cf.D(5)`` (see `cf.D`).

              *Example:*
                To define groups of 1 calendar month, starting and
                ending at day 16 of each month: ``group=cf.M(day=16)``
                (see `cf.M`).

              *Note:*
                * By default each element will be in exactly one
                  group (see the *group_by* parameter).
                * Groups may contain different numbers of elements.
                * The start of the first group may be before the first
                  first axis element, depending on the offset defined
                  by the time duration. For example, if
                  ``group=cf.Y(month=12)`` then the first group will
                  start on the closest 1st December to the first axis
                  element.

        ..

          * A (sequence of) `cf.Query`, each of which is a condition
            defining one or more groups. Each query selects elements
            whose coordinates satisfy its condition and from these
            elements multiple groups are created - one for each
            maximally consecutive run within these elements.

              *Example:*
                To define groups of the season MAM in each year:
                ``group=cf.mam()`` (see `cf.mam`).
              
              *Example:*
                To define groups of the seasons DJF and JJA in each
                year: ``group=[cf.jja(), cf.djf()]``. To define groups
                for seasons DJF, MAM, JJA and SON in each year:
                ``group=cf.seasons()`` (see `cf.djf`, `cf.jja` and
                `cf.season`).
              
              *Example:*
                To define groups for longitude elements less than or
                equal to 90 degrees and greater than 90 degrees:
                ``group=[cf.le(90, 'degrees'), cf.gt(90, 'degrees')]``
                (see `cf.le` and `cf.gt`).

              *Note:*
                * If a coordinate does not satisfy any of the
                  conditions then its element will not be in a group.
                * Groups may contain different numbers of elements.
                * If no units are specified then the units of the
                  coordinates are assumed.
                * If an element is selected by two or more queries
                  then the latest one in the sequence defines which
                  group it will be in.

        .. 

          * An `int` defining the number of elements in each
            group. The first group starts with the first axis element
            and spans the defined number of consecutive elements. Each
            susbsequent group immediately follows the preceeeding
            one.

              *Example:*
                To define groups of 5 elements: ``group=5``.

              *Note:*
                * Each group has the defined number of elements, apart
                  from the last group which may contain fewer
                  elements.

        .. 

          * A `numpy.array` of integers defining groups. The array
            must have the same length as the axis to be collapsed and
            its sequence of values correspond to the axis
            elements. Each group contains the elements which
            correspond to a common non-negative integer value in the
            numpy array. Upon output, the collapsed axis is arranged
            in order of increasing group number.

              *Example:*
                For an axis of size 8, create two groups, the first
                containing the first and last elements and the second
                containing the 3rd, 4th and 5th elements, whilst
                ignoring the 2nd, 6th and 7th elements:
                ``group=numpy.array([0, -1, 4, 4, 4, -1, -2, 0])``.

              *Note:* 
                * The groups do not have to be in runs of consective
                  elements; they may be scattered throughout the axis.
                * An element which corresponds to a negative integer
                  in the array will not be in a group.

    group_by: `str`, optional
        Specify how coordinates are assigned to the groups defined by
        the *group*, *within_days* or *within_years*
        parameter. Ignored unless one of these parameters is a
        `cf.Data` or `cf.TimeDuration` object. The *group_by*
        parameter may be one of:

          * ``'coords'``. This is the default. Each group contains the
            axis elements whose coordinate values lie within the group
            limits. Every element will be in a group.

        ..

          * ``'bounds'``. Each group contains the axis elements whose
            upper and lower coordinate bounds both lie within the
            group limits. Some elements may not be inside any group,
            either because the group limits do not coincide with
            coordinate bounds or because the group size is
            sufficiently small.

    regroup: `bool`, optional
        For grouped collapses, return a `numpy.array` of integers
        which identifies the groups defined by the *group*
        parameter. The array is interpreted as for a numpy array value
        of the *group* parameter, and thus may subsequently be used by
        *group* parameter in a separate collapse. For example:

        >>> groups = f.collapse('time: mean', group=10, regroup=True)
        >>> g = f.collapse('time: mean', group=groups)

        is equivalent to:

        >>> g = f.collapse('time: mean', group=10)

    within_days: optional
        Independently collapse groups of reference-time axis elements
        for CF "within days" climatological statistics. Each group
        contains elements whose coordinates span a time interval of up
        to one day. Upon output, the results of the collapses are
        concatenated so that the output axis has a size equal to the
        number of groups.

        *Note:*
          For CF compliance, a "within days" collapse should be
          followed by an "over days" collapse.

        The *within_days* parameter defines how the elements are
        partitioned into groups, and may be one of:

          * A `cf.TimeDuration` defining the group size in terms of a
            time interval of up to one day. The first group starts at
            or before the first coordinate bound of the first axis
            element (or its coordinate if there are no bounds) and
            spans the defined group size. Each susbsequent group
            immediately follows the preceeeding one. By default each
            group contains the consective run of elements whose
            coordinate values lie within the group limits (see the
            *group_by* parameter).

              *Example:*
                To define groups of 6 hours, starting at 00:00, 06:00,
                12:00 and 18:00: ``within_days=cf.h(6)`` (see `cf.h`).

              *Example:*
                To define groups of 1 day, starting at 06:00:
                ``within_days=cf.D(1, hour=6)`` (see `cf.D`).

              *Note:*
                * Groups may contain different numbers of elements.
                * The start of the first group may be before the first
                  first axis element, depending on the offset defined
                  by the time duration. For example, if
                  ``group=cf.D(hour=12)`` then the first group will
                  start on the closest midday to the first axis
                  element.

        ..

          * A (sequence of) `cf.Query`, each of which is a condition
            defining one or more groups. Each query selects elements
            whose coordinates satisfy its condition and from these
            elements multiple groups are created - one for each
            maximally consecutive run within these elements.

              *Example:*
                To define groups of 00:00 to 06:00 within each day,
                ignoring the rest of each day:
                ``within_days=cf.hour(cf.le(6))`` (see `cf.hour` and
                `cf.le`).

              *Example:*
                To define groups of 00:00 to 06:00 and 18:00 to 24:00
                within each day, ignoring the rest of each day:
                ``within_days=[cf.hour(cf.le(6)),
                cf.hour(cf.gt(18))]`` (see `cf.gt`, `cf.hour` and
                `cf.le`).

              *Note:*
                * Groups may contain different numbers of elements.
                * If no units are specified then the units of the
                  coordinates are assumed.
                * If a coordinate does not satisfy any of the
                  conditions then its element will not be in a group.
                * If an element is selected by two or more queries
                  then the latest one in the sequence defines which
                  group it will be in.

    within_years: optional 
        Independently collapse groups of reference-time axis elements
        for CF "within years" climatological statistics. Each group
        contains elements whose coordinates span a time interval of up
        to one calendar year. Upon output, the results of the
        collapses are concatenated so that the output axis has a size
        equal to the number of groups.

          *Note:*
            For CF compliance, a "within years" collapse should be
            followed by an "over years" collapse.

        The *within_years* parameter defines how the elements are
        partitioned into groups, and may be one of:

          * A `cf.TimeDuration` defining the group size in terms of a
            time interval of up to one calendar year. The first group
            starts at or before the first coordinate bound of the
            first axis element (or its coordinate if there are no
            bounds) and spans the defined group size. Each susbsequent
            group immediately follows the preceeeding one. By default
            each group contains the consective run of elements whose
            coordinate values lie within the group limits (see the
            *group_by* parameter).

              *Example:*
                To define groups of 90 days: ``within_years=cf.D(90)``
                (see `cf.D`).

              *Example:*  
                To define groups of 3 calendar months, starting on the
                15th of a month: ``within_years=cf.M(3, day=15)`` (see
                `cf.M`).

              *Note:*
                * Groups may contain different numbers of elements.
                * The start of the first group may be before the first
                  first axis element, depending on the offset defined
                  by the time duration. For example, if
                  ``group=cf.Y(month=12)`` then the first group will
                  start on the closest 1st December to the first axis
                  element.

        ..

          * A (sequence of) `cf.Query`, each of which is a condition
            defining one or more groups. Each query selects elements
            whose coordinates satisfy its condition and from these
            elements multiple groups are created - one for each
            maximally consecutive run within these elements.

              *Example:*
                To define groups for the season MAM within each year:
                ``within_years=cf.mam()`` (see `cf.mam`).

              *Example:*
                To define groups for February and for November to
                December within each year:
                ``within_years=[cf.month(2), cf.month(cf.ge(11))]``
                (see `cf.month` and `cf.ge`).

              *Note:*
                * The first group may start outside of the range of
                  coordinates (the start of the first group is
                  controlled by parameters of the `cf.TimeDuration`).
                * If group boundaries do not coincide with coordinate
                  bounds then some elements may not be inside any
                  group.
                * If the group size is sufficiently small then some
                  elements may not be inside any group.
                * Groups may contain different numbers of elements.

    over_days: optional
        Independently collapse groups of reference-time axis elements
        for CF "over days" climatological statistics. Each group
        contains elements whose coordinates are **matching**, in that
        their lower bounds have a common time of day but different
        dates of the year, and their upper bounds also have a common
        time of day but different dates of the year. Upon output, the
        results of the collapses are concatenated so that the output
        axis has a size equal to the number of groups.

          *Example:*
            An element with coordinate bounds {1999-12-31 06:00:00,
            1999-12-31 18:00:00} **matches** an element with
            coordinate bounds {2000-01-01 06:00:00, 2000-01-01
            18:00:00}.

          *Example:*
            An element with coordinate bounds {1999-12-31 00:00:00,
            2000-01-01 00:00:00} **matches** an element with
            coordinate bounds {2000-01-01 00:00:00, 2000-01-02
            00:00:00}.

          *Note:*       
            * A *coordinate* parameter value of ``'min'`` is assumed,
              regardless of its given value.
             
            * A *group_by* parameter value of ``'bounds'`` is assumed,
              regardless of its given value.
            
            * An "over days" collapse must be preceded by a "within
              days" collapse, as described by the CF conventions. If the
              field already contains sub-daily data, but does not have
              the "within days" cell methods flag then it may be added,
              for example, as follows (this example assumes that the
              appropriate cell method is the most recently applied,
              which need not be the case; see `cf.CellMethods` for
              details):
            
              >>> f.cell_methods[-1].within = 'days'

        The *over_days* parameter defines how the elements are
        partitioned into groups, and may be one of:

          * `None`. This is the default. Each collection of
            **matching** elements forms a group.

        ..

          * A `cf.TimeDuration` defining the group size in terms of a
            time duration of at least one day. Multiple groups are
            created from each collection of **matching** elements -
            the first of which starts at or before the first
            coordinate bound of the first element and spans the
            defined group size. Each susbsequent group immediately
            follows the preceeeding one. By default each group
            contains the **matching** elements whose coordinate values
            lie within the group limits (see the *group_by*
            parameter).

              *Example:*
                To define groups spanning 90 days:
                ``over_days=cf.D(90)`` or
                ``over_days=cf.h(2160)``. (see `cf.D` and `cf.h`).

              *Example:*
                To define groups spanning 3 calendar months, starting
                and ending at 06:00 in the first day of each month:
                ``over_days=cf.M(3, hour=6)`` (see `cf.M`).

              *Note:*
                * Groups may contain different numbers of elements.
                * The start of the first group may be before the first
                  first axis element, depending on the offset defined
                  by the time duration. For example, if
                  ``group=cf.M(day=15)`` then the first group will
                  start on the closest 15th of a month to the first
                  axis element.

        ..

          * A (sequence of) `cf.Query`, each of which is a condition
            defining one or more groups. Each query selects elements
            whose coordinates satisfy its condition and from these
            elements multiple groups are created - one for each subset
            of **matching** elements.

              *Example:*
                To define groups for January and for June to December,
                ignoring all other months: ``over_days=[cf.month(1),
                cf.month(cf.wi(6, 12))]`` (see `cf.month` and
                `cf.wi`).

              *Note:*
                * If a coordinate does not satisfy any of the
                  conditions then its element will not be in a group.
                * Groups may contain different numbers of elements.
                * If an element is selected by two or more queries
                  then the latest one in the sequence defines which
                  group it will be in.

    over_years: optional
        Independently collapse groups of reference-time axis elements
        for CF "over years" climatological statistics. Each group
        contains elements whose coordinates are **matching**, in that
        their lower bounds have a common sub-annual date but different
        years, and their upper bounds also have a common sub-annual
        date but different years. Upon output, the results of the
        collapses are concatenated so that the output axis has a size
        equal to the number of groups.

          *Example:*
            An element with coordinate bounds {1999-06-01 06:00:00,
            1999-09-01 06:00:00} **matches** an element with
            coordinate bounds {2000-06-01 06:00:00, 2000-09-01
            06:00:00}.

          *Example:*
            An element with coordinate bounds {1999-12-01 00:00:00,
            2000-12-01 00:00:00} **matches** an element with
            coordinate bounds {2000-12-01 00:00:00, 2001-12-01
            00:00:00}.

          *Note:*       
            * A *coordinate* parameter value of ``'min'`` is assumed,
              regardless of its given value.
             
            * A *group_by* parameter value of ``'bounds'`` is assumed,
              regardless of its given value.
            
            * An "over years" collapse must be preceded by a "within
              years" or an "over days" collapse, as described by the
              CF conventions. If the field already contains sub-annual
              data, but does not have the "within years" or "over
              days" cell methods flag then it may be added, for
              example, as follows (this example assumes that the
              appropriate cell method is the most recently applied,
              which need not be the case; see `cf.CellMethods` for
              details):

              >>> f.cell_methods[-1].over = 'days'

        The *over_years* parameter defines how the elements are
        partitioned into groups, and may be one of:

          * `None`. Each collection of **matching** elements forms a
            group. This is the default.

        ..

          * A `cf.TimeDuration` defining the group size in terms of a
            time interval of at least one calendar year. Multiple
            groups are created from each collection of **matching**
            elements - the first of which starts at or before the
            first coordinate bound of the first element and spans the
            defined group size. Each susbsequent group immediately
            follows the preceeeding one. By default each group
            contains the **matching** elements whose coordinate values
            lie within the group limits (see the *group_by*
            parameter).

              *Example:*
                To define groups spanning 10 calendar years:
                ``over_years=cf.Y(10)`` or ``over_years=cf.M(120)``
                (see `cf.M` and `cf.Y`).

              *Example:*
                To define groups spanning 5 calendar years, starting
                and ending at 06:00 on 01 December of each year:
                ``over_years=cf.Y(5, month=12, hour=6)`` (see `cf.Y`).

              *Note:*
                * Groups may contain different numbers of elements.
                * The start of the first group may be before the first
                  first axis element, depending on the offset defined
                  by the time duration. For example, if
                  ``group=cf.Y(month=12)`` then the first group will
                  start on the closest 1st December to the first axis
                  element.

        ..

          * A (sequence of) `cf.Query`, each of which is a condition
            defining one or more groups. Each query selects elements
            whose coordinates satisfy its condition and from these
            elements multiple groups are created - one for each subset
            of **matching** elements.

              *Example:*
                To define one group spanning 1981 to 1990 and another
                spanning 2001 to 2005:
                ``over_years=[cf.year(cf.wi(1981, 1990),
                cf.year(cf.wi(2001, 2005)]`` (see `cf.year` and
                `cf.wi`).

              *Note:*
                * If a coordinate does not satisfy any of the
                  conditions then its element will not be in a group.
                * Groups may contain different numbers of elements.
                * If an element is selected by two or more queries
                  then the latest one in the sequence defines which
                  group it will be in.

    {+i}

:Returns:
 
[+1]    out: `cf.Field` or `numpy.ndarray`
[+N]    out: `cf.{+variable}` or `list`
           {+Fef,}The collapsed field. If the *regroup* parameter is
           True then a numpy array is returned.

:Examples:

Calculate the unweighted  mean over a the entire field:

>>> g = f.collapse('mean')

Five equivalent ways to calculate the unweighted  mean over a CF latitude axis:

>>> g = f.collapse('latitude: mean')
>>> g = f.collapse('lat: avg')
>>> g = f.collapse('Y: average')
>>> g = f.collapse('mean', 'Y')
>>> g = f.collapse('mean', ['latitude'])

Three equivalent ways to calculate an area weighted mean over CF
latitude and longitude axes:

>>> g = f.collapse('area: mean', weights='area')
>>> g = f.collapse('lat: lon: mean', weights='area')
>>> g = f.collapse('mean', axes=['Y', 'X'], weights='area')

Two equivalent ways to calculate a time weighted mean over CF
latitude, longitude and time axes:

>>> g = f.collapse('X: Y: T: mean', weights='T')
>>> g = f.collapse('mean', axes=['T', 'Y', 'X'], weights='T')

Find how many non-missing elements in each group of a grouped
collapse:

>>> f.collapse('latitude: sample_size', group=cf.Data(5 'degrees'))

'''
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            if regroup:
                raise ValueError("oooo")
            return self._list_method('collapse', kwargs2)

        if i:
            f = self
        else:
            f = self.copy()

        # Whether or not to create null bounds for null
        # collapses. I.e. if the collapse axis has size 1 and no
        # bounds, whether or not to create upper and lower bounds to
        # the coordinate value. If this occurs it's because the null
        # collapse is part of a grouped collapse and so will be
        # concatenated to other collapses for the final result: bounds
        # will be made for the grouped collapse, so all elements need
        # bounds.
        _create_zero_size_cell_bounds = kwargs.get('_create_zero_size_cell_bounds', False)
                
        # ------------------------------------------------------------
        # Parse the methods and axes
        # ------------------------------------------------------------
        if ':' in method:
            # Convert a cell methods string (such as 'area: mean dim3:
            # dim2: max T: minimum height: variance') to a CellMethods
            # object
            if axes is not None:
                raise ValueError(
"Can't collapse: Can't set axes when method is CF cell methods-like string")

            method = CellMethods(method)
        
            all_methods = method.method
            all_axes    = method.names
            all_within  = method.within
            all_over    = method.over
        else:            
            x = method.split(' within ')
            if method == x[0]:
                within = None
                x = method.split(' over ')
                if method == x[0]:
                    over = None
                else:
                    method, over = x
            else:
                method, within = x
           
            if isinstance(axes, basestring):
                axes = (axes,)

            all_methods = (method,)
            all_within  = (within,)
            all_over    = (over,)
            all_axes    = (axes,)
        #--- End: if
        
        # Parse special axes values
        all_axes2 = []
        for axes in all_axes:
            if axes is None:
                all_axes2.append(axes)
                continue

            axes2 = []
            for axis in axes:
                if axis == 'area':
                    axes2.extend(('X', 'Y'))
                # Not yet in CF
                #elif axis == 'volume':
                #    axes2.extend(('X', 'Y', 'Z'))
                else:
                    axes2.append(axis)
            #--- End: for
            all_axes2.append(axes2)
        #--- End: for
        all_axes = all_axes2

        if group is not None and len(all_axes) > 1:
            raise ValueError(
                "Can't use group parameter for multiple collapses")

        # ------------------------------------------------------------
        #
        # ------------------------------------------------------------
        for method, axes, within, over in izip(all_methods, all_axes,
                                               all_within, all_over):
            domain = f.domain

            method2 = _collapse_methods.get(method, None)
            if method2 is None:
                raise ValueError("Can't collapse: Unknown method: %s" % method)

            method = method2

            kwargs['ordered'] = True
            if method not in ('sample_size', 'sum_of_weights', 'sum_of_weights2'):
                kwargs['size'] = gt(1)

            collapse_axes = domain.axes(axes, **kwargs)

            if not collapse_axes:
                # Do nothing if there are no collapse axes
                if _create_zero_size_cell_bounds:
                    # Create null bounds if requested
                    for axis in domain.axes(axes):
                        d = domain.item(axes, role='d')
                        if d and not d.hasbounds:
                            d.get_bounds(create=True, insert=True, cellsize=0)
                #--- End: if                        
                continue
    
#            if axes != (None,) and len(collapse_axes) != len(axes):
#                raise ValueError("Can't collapse: Ambiguous collapse axes")

            # Check that there are enough elements to collapse
            size = reduce(operator_mul, domain.axes_sizes(collapse_axes).values(), 1)
            min_size = _collapse_min_size.get(method, 1)
            if size < min_size:
                raise ValueError(
                    "Can't calculate %s from fewer than %d elements" %
                    (_collapse_cell_methods[method], min_size))
    
            grouped_collapse = (within is not None or
                                over   is not None or
                                group  is not None)

            if grouped_collapse:
                if len(collapse_axes) > 1:
                    raise ValueError(
                        "Can't group collapse multiple axes simultaneously")

                # ------------------------------------------------------------
                # Calculate weights
                # ------------------------------------------------------------
                g_weights = weights
                if method in _collapse_weighted_methods:
                    g_weights = f.weights(weights, scale=True, components=True)
                    if not g_weights:
                        g_weights = None
                #--- End: if

                f = f._grouped_collapse(method, collapse_axes[0],
                                        within=within,
                                        over=over,
                                        within_days=within_days,
                                        within_years=within_years,
                                        over_days=over_days,
                                        over_years=over_years,
                                        group=group,
                                        regroup=regroup,
                                        mtol=mtol,
                                        ddof=ddof,
                                        weights=g_weights,
                                        a=a,
                                        squeeze=squeeze,
                                        coordinate=coordinate,
                                        group_by=group_by)

                continue
            elif regroup:
                raise ValueError(
                    "Can't return n array of groups for a non-grouped collapse")

#            method = _collapse_methods.get(method, None)
#            if method is None:
#                raise ValueError("uih luh hbblui")
#
#            # Check that there are enough elements to collapse
#            size = reduce(operator_mul, domain.axes_sizes(collapse_axes).values())
#            min_size = _collapse_min_size.get(method, 1)
#            if size < min_size:
#                raise ValueError(
#                    "Can't calculate %s from fewer than %d elements" %
#                    (_collapse_cell_methods[method], min_size))
    
            data_axes = domain.data_axes()
            iaxes = [data_axes.index(axis) for axis in collapse_axes]

            # ------------------------------------------------------------
            # Calculate weights
            # ------------------------------------------------------------
            d_kwargs = {}
            if weights is not None:
                if method in _collapse_weighted_methods:
                    d_weights = f.weights(weights, scale=True, components=True)
                    if d_weights:
                        d_kwargs['weights'] = d_weights
                elif not equals(weights, 'auto'):  # doc this
                    raise ValueError(
"Can't collapse: Can't weight {0!r} collapse method".format(method))
            #--- End: if

            if method in _collapse_ddof_methods:
                d_kwargs['ddof'] = ddof
                d_kwargs['a']    = a

            # --------------------------------------------------------
            # Collapse the data array
            # --------------------------------------------------------
            getattr(f.Data, method)(axes=iaxes, squeeze=squeeze, mtol=mtol,
                                    i=True, **d_kwargs)
        
            if squeeze:
                # ----------------------------------------------------
                # Remove the collapsed axes from the field's list of
                # data array axes
                # ----------------------------------------------------
                domain._axes['data'] = [axis for axis in data_axes
                                        if axis not in collapse_axes]
        
            # --------------------------------------------------------
            # Update ancillary variables
            # --------------------------------------------------------
            f._conform_ancillary_variables(collapse_axes)
    
            # ------------------------------------------------------------
            # Update fields in coordinate references
            # ------------------------------------------------------------
            f._conform_ref_fields(collapse_axes)
                    
            #---------------------------------------------------------
            # Update dimension coordinates, auxiliary coordinates and
            # cell measures
            # ---------------------------------------------------------
            for axis in collapse_axes:
                # Ignore axes which are already size 1
                if domain.axis_size(axis) == 1:
                    continue
                
                # REMOVE all cell measures which span this axis
                domain.remove_items(role=('m',), axes=axis)
    
                # REMOVE all 2+ dimensional auxiliary coordinates
                # which span this axis
                domain.remove_items(role=('a',), axes=axis, ndim=gt(1))
                    
                # REMOVE all 1 dimensional auxiliary coordinates which
                # span this axis and have different values in their
                # data array and bounds.
                #
                # KEEP, after changing their data arrays, all 1
                # dimensional auxiliary coordinates which span this
                # axis and have the same values in their data array
                # and bounds.    
                for key, aux in domain.items(role=('a',), axes=axis, ndim=1).iteritems():
                    d = aux.subspace[0]

                    if ((aux.subspace[:-1] != aux.subspace[1:]).any() or 
                        aux.hasbounds and (aux.bounds != d.bounds).any()):
                        domain.remove_item(key)
                    else:
                        # Change the data array for this auxiliary
                        # coordinate
                        aux.insert_data(d.data, copy=False)
                        if d.hasbounds:
                            aux.insert_bounds(d.bounds.data, copy=False)
                #--- End: for

                dim_coord = domain.item(axis, role=('d',))
                if dim_coord is None:
                    continue
        
                # Create a new dimension coordinate for this axis
                if dim_coord.hasbounds:
                    bounds = [dim_coord.bounds.datum(0),
                              dim_coord.bounds.datum(-1)]
                else:
                    bounds = [dim_coord.datum(0),
                              dim_coord.datum(-1)]

                units = dim_coord.Units

                if coordinate == 'mid_range':
                    data = Data([(bounds[0] + bounds[1])*0.5], units)
                elif coordinate == 'min':
                    data = dim_coord.data.min()
                elif coordinate == 'max':
                    data = dim_coord.data.max()
                else:
                    raise ValueError(
"Can't collapse: Bad parameter value: coordinate={0!r}".format(coordinate))

                bounds = Data([bounds], units)

                dim_coord.insert_data(data, bounds=bounds, copy=False)
        
                # Put the new dimension coordinate into the domain
                domain.insert_axis(1, key=axis, replace=True)
                domain.insert_dim(dim_coord, key=axis, copy=False, replace=True)
            #--- End: for
        
            # --------------------------------------------------------
            # Update the cell methods
            # --------------------------------------------------------
            cell_method = _collapse_cell_methods[method]
            if cell_method is not None:
                # This collapse method has an associated cell method
                if not hasattr(f, 'cell_methods'):
                    f.cell_methods = CellMethods()

                collapse_axes = sorted(collapse_axes)
                
                name = []
                for axis in collapse_axes:
                    item = domain.item(axis)
                    if item is not None:
                        name.append(item.identity(default=axis))
                    else:
                        name.append(axis)
                #--- End: for

                string = '%s: %s' % (': '.join(name), cell_method)  

                cell_method = CellMethods(string) 

                cell_method.axes = collapse_axes

                if not f.cell_methods or not f.cell_methods[-1].equivalent(cell_method):
                    f.cell_methods += cell_method
            #--- End: if
 
        #--- End: for

        # ------------------------------------------------------------
        # Return the collapsed field (or the classification array)
        # ------------------------------------------------------------
        return f
    #--- End: def

    def _grouped_collapse(self, method, axis, within=None, over=None,
                          within_days=None, within_years=None,
                          over_days=None, over_years=None, group=None,
                          mtol=None, ddof=None, a=None, regroup=None,
                          coordinate=None, weights=None,
                          squeeze=None, group_by=None):
        '''
:Parameters:

    method: str

    axis: str

    over: str

    within: str


'''
        def _ddddd(classification, n, lower, upper, increasing, coord,
                   group_by_coords, extra_condition): 
            '''
    :Returns:

        out: 4-tuple of (numpy.ndarray, int, date-time, date-time)

    '''         
            if group_by_coords:
                q = ge(lower) & lt(upper)
            else:
                q = (ge(lower, attr='lower_bounds') & 
                     le(upper, attr='upper_bounds'))
                
            if extra_condition:
                q &= extra_condition

#            print  q, coord

            index = q.evaluate(coord).array
            classification[index] = n

            if increasing:
                lower = upper 
            else:
                upper = lower

            n += 1

            return classification, n, lower, upper
        #--- End: def

        def _time_interval(classification, n,
                           coord, interval,
                           lower, upper,
                           lower_limit, upper_limit,
                           group_by,
                           extra_condition=None):
            '''
    :Returns:

        out: 2-tuple of numpy array, int

    '''            
            group_by_coords = group_by == 'coords'

            months  = interval.Units == Units('calendar_months')
            years   = interval.Units == Units('calendar_years')
            days    = interval.Units == Units('days')
            hours   = interval.Units == Units('hours')
            minutes = interval.Units == Units('minutes')
            seconds = interval.Units == Units('seconds')

            calendar = coord.Units._calendar
                
            if coord.increasing:
                # Increasing dimension coordinate 
                if months or years:
                    lower, upper = interval.interval(lower.year,
                                                     calendar=calendar,
                                                     end=True)
                elif days:
                    lower, upper = interval.interval(lower.year,
                                                     lower.month,
                                                     calendar=calendar,
                                                     end=True)
                elif hours:
                    lower, upper = interval.interval(lower.year,
                                                     lower.month,
                                                     lower.day,
                                                     calendar=calendar,
                                                     end=True)

                elif minutes:
                    lower, upper = interval.interval(lower.year,
                                                     lower.month,
                                                     lower.day,
                                                     lower.hour,
                                                     calendar=calendar,
                                                     end=True)

                elif seconds:
                    lower, upper = interval.interval(lower.year,
                                                     lower.month,
                                                     lower.day,
                                                     lower.hour,
                                                     lower.minute,
                                                     calendar=calendar,
                                                     end=True)

                while lower <= upper_limit:
                    lower, upper = interval.interval(*lower.timetuple()[:6],
                                                      calendar=calendar)
                    classification, n, lower, upper = _ddddd(
                        classification, n, lower, upper, True,
                        coord, group_by_coords, extra_condition)
            else: 
                # Decreasing dimension coordinate
                if months or years:
                    lower, upper = interval.interval(upper.year,
                                                     calendar=calendar)
                elif days:
                    lower, upper = interval.interval(upper.year,
                                                     upper.month,
                                                     calendar=calendar)
                elif hours:
                    lower, upper = interval.interval(upper.year,
                                                     upper.month,
                                                     upper.day,
                                                     calendar=calendar)

                elif minutes:
                    lower, upper = interval.interval(upper.year,
                                                     upper.month,
                                                     upper.day,
                                                     upper.hour,
                                                     calendar=calendar)

                elif seconds:
                    lower, upper = interval.interval(upper.year,
                                                     upper.month,
                                                     upper.day,
                                                     upper.hour,
                                                     upper.minute,
                                                     calendar=calendar)

                while upper >= lower_limit:
                    lower, upper = interval.interval(*upper.timetuple()[:6],
                                                      calendar=calendar, end=True)
                    classification, n, lower, upper = _ddddd(
                        classification, n, lower, upper, False,
                        coord, group_by_coords, extra_condition)
            #--- End: if
                        
            return classification, n
        #--- End: def

        def _data_interval(classification, n,
                           coord, interval,
                           lower, upper,
                           lower_limit, upper_limit,
                           group_by,
                           extra_condition=None):
            '''
    :Returns:

        out: 2-tuple of numpy array, int

    '''          
            group_by_coords = group_by == 'coords'

            if coord.increasing:
                # Increasing dimension coordinate 
                lower= lower.squeeze()
                while lower <= upper_limit:
                    upper = lower + interval 
                    classification, n, lower, upper = _ddddd(
                        classification, n, lower, upper, True,
                        coord, group_by_coords, extra_condition)
            else: 
                # Decreasing dimension coordinate
                upper = upper.squeeze()
                while upper >= lower_limit:
                    lower = upper - interval
                    classification, n, lower, upper = _ddddd(
                        classification, n, lower, upper, False,
                        coord, group_by_coords, extra_condition)
            #--- End: if
                        
            return classification, n
        #--- End: def

        def _selection(classification, n, coord, selection, parameter,
                       extra_condition=None):
            ''':Parameters:

        classification: `numpy.ndarray`

        n: `int`
        
        coord: `cf.DimensionCoordinate`

        selection: sequence of `cf.Query`

              *Example:*
                ``selection=[cf.djf]``

        parameter: str
            The name of the `cf.Field.collapse` parameter which
            defined *selection*. This is used in error messages.

              *Example:*
                ``parameter='within_years'``

        extra_condition: `cf.Query`, optional

    :Returns:

        out: `numpy.ndarray`, `int`

            '''        
            # Create an iterator for stepping through each cf.Query in
            # the selection sequence
            try:
                iterator = iter(selection)
            except TypeError:
                raise ValueError(
                    "Can't collapse: Bad value for {0} parameter: {1!r}".format(
                        parameter, selection))
            
            for c in iterator:
                if not isinstance(c, Query):
                    raise ValueError(
"Can't collapse: {0} parameter contains a non-{1} object: {2!r}".format(
    parameter, Query.__name__, c))
                                
                if extra_condition:
                    c &= extra_condition

                index = c.evaluate(coord).array

                classification[index] = n

                n += 1
            #--- End: for

            return classification, n
        #--- End: def
        
        def _discern_runs(classification):
            '''
    :Returns:

        out: `numpy.ndarray`

    '''            
            x =  numpy_where(numpy_diff(classification))[0] + 1

            if not x.size:
                if classification[0] >= 0:
                    classification[:] = 0
                return classification           

            if classification[0] >= 0:
                classification[0:x[0]] = 0

            for n, (i, j) in enumerate(zip(x[:-1], x[1:])):
                if classification[i] >= 0:
                    classification[i:j] = n+1
            #-- End: for

            if classification[x[-1]] >= 0:
                classification[x[-1]:] = n+2

            return classification
        #--- End: def

        def _tyu(coord, group_by, time_interval):
            ''':Parameters:

    coord: `cf.Coordinate`


    group_by: `str`
        As for the *group_by* parameter of the `collapse` method.

    time_interval: `bool`
        If True then

:Returns:

    out: 4-`tuple` of date-time objects

            '''
            if coord.hasbounds:
                bounds = coord.bounds                       
                lower_bounds = bounds.lower_bounds
                upper_bounds = bounds.upper_bounds               
                lower = lower_bounds[0]
                upper = upper_bounds[0]
                lower_limit = lower_bounds[-1]
                upper_limit = upper_bounds[-1]
            elif group_by == 'coords':
                if coord.increasing:
                    lower = coord.data[0]
                    upper = coord.data[-1]
                else:
                    lower = coord.data[-1]
                    upper = coord.data[0]
                    
                lower_limit = lower
                upper_limit = upper
            else:
                raise ValueError(
"Can't collapse: {0!r} coordinate bounds are required with group_by={1!r}".format(
    coord.name(''), group_by))
                
            if time_interval:
                units = coord.Units
                if units.isreftime:
                    lower       = lower.dtarray[0]
                    upper       = upper.dtarray[0]
                    lower_limit = lower_limit.dtarray[0]
                    upper_limit = upper_limit.dtarray[0]
                elif not units.istime:
                    raise ValueError(
                        "Can't group by %s when coordinates have units %r" %
                        (TimeDuration.__name__, coord.Units))
            #--- End: if

            return lower, upper, lower_limit, upper_limit
        #--- End: def
    
        def _group_weights(weights, iaxis, index):
            '''
            
Subspace weights components.

    :Parameters:

        weights: `dict` or `None`

        iaxis: `int`

        index: `list`

    :Returns:

        out: `dict` or `None`

    :Examples: 

    >>> print weights
    None
    >>> print _group_weights(weights, 2, [2, 3, 40])
    None
    >>> print _group_weights(weights, 1, slice(2, 56))    
    None

    >>> weights
    
    >>> _group_weights(weights, 2, [2, 3, 40])
    
    >>> _group_weights(weights, 1, slice(2, 56))    


    '''
            if not isinstance(weights, dict):
                return weights

            weights = weights.copy()
            for iaxes, value in weights.iteritems():
                if iaxis in iaxes:
                    indices = [slice(None)] * len(iaxes)
                    indices[iaxes.index(iaxis)] = index
                    weights[iaxes] = value.subspace[tuple(indices)]
                    break
            #--- End: for

            return weights
        #--- End: def

        # START OF MAIN CODE        

        axis_size = self.domain.axis_size(axis)  # Size of uncollapsed axis
        iaxis     = self.data_axes().index(axis) # Integer position of collapse axis

        fl = []

        # If group, rolling window, classification, etc, do something
        # special for size one axes - either return unchanged
        # (possibly mofiying cell methods with , e.g, within_dyas', or
        # raising an exception for 'can't match', I suppose.

        classification = None

        if group is not None:
            if within is not None or over is not None:
                raise ValueError(
                    "Can't set 'group' parameter for a climatological time collapse")

            if isinstance(group, numpy_ndarray):
                classification = numpy_squeeze(group.copy())
                coord = self.dim(axis)

                if classification.dtype.kind != 'i':
                    raise ValueError(
                        "Can't collapse: Can't group by numpy array of type %s" %
                        classification.dtype.name)
                elif classification.shape != (axis_size,):
                    raise ValueError(
"Can't collapse: group by numpy array of integers has incorrect shape: %s" %
classification.shape)

                # Set group to None
                group = None
        #-- End: if

        if group is not None:
            if isinstance(group, Query):
                group = (group,)

            if isinstance(group, (int, long)):
                # ----------------------------------------------------
                # E.g. group=3
                # ----------------------------------------------------
                coord = None
                classification = numpy_empty((axis_size,), int)
                
                start = 0
                end   = group
                n = 0
                while start < axis_size:
                    classification[start:end] = n
                    start = end
                    end  += group
                    n += 1
                #--- End: while

            elif isinstance(group, TimeDuration):
                # ----------------------------------------------------
                # E.g. group=cf.M()
                # ----------------------------------------------------
                coord = self.dim(axis)
                if coord is None:
                    raise ValueError("dddddd siduhfsuildfhsuil dhfdui ") 
                 
#                # Get the bounds
#                if not coord.hasbounds:
#                    coord = coord.copy()
#
#                bounds = coord.get_bounds(create=True, insert=True)
    
                classification = numpy_empty((axis_size,), int)
                classification.fill(-1)

                lower, upper, lower_limit, upper_limit = _tyu(coord, group_by, True)

                classification, n = _time_interval(classification, 0,
                                                   coord=coord,
                                                   interval=group,
                                                   lower=lower,
                                                   upper=upper,
                                                   lower_limit=lower_limit,
                                                   upper_limit=upper_limit,
                                                   group_by=group_by)
            elif isinstance(group, Data):
                # ----------------------------------------------------
                # Chunks of 
                # ----------------------------------------------------
                coord = self.dim(axis)
                if coord is None:
                    raise ValueError("dddddd siduhfsuildfhsuil dhfdui ") 
                if group.size != 1:
                    raise ValueError(
                        "Can't group by SIZE > 1")                    
                if group.Units and not group.Units.equivalent(coord.Units):
                    raise ValueError(
                        "Can't group by %r when coordinates have units %r" %
                        (interval, coord.Units))

                classification = numpy_empty((axis_size,), int)
                classification.fill(-1)

                group = group.squeeze()
  
                lower, upper, lower_limit, upper_limit = _tyu(coord, group_by, False)

                classification, n = _data_interval(classification, 0,
                                                   coord=coord,
                                                   interval=group,
                                                   lower=lower,
                                                   upper=upper,
                                                   lower_limit=lower_limit,
                                                   upper_limit=upper_limit,
                                                   group_by=group_by)
            else:
                # ----------------------------------------------------
                # E.g. group=[cf.month(4), cf.month(cf.wi(9, 11))]
                # ----------------------------------------------------
                coord = self.dim(axis)
                if coord is None:
                    coord = self.aux(axes_all=axis)
                    if coord is None:
                        raise ValueError("Need a defining 1-d coordinate")

                classification = numpy_empty((axis_size,), int)
                classification.fill(-1)
                
                classification, n = _selection(classification, 
                                               n=0,
                                               coord=coord,
                                               selection=group,
                                               parameter='group')
                
                classification = _discern_runs(classification)
            #--- End: if
        #--- End: if

        if classification is None:
            if over == 'days': 
                # ----------------------------------------------------
                # Over days
                # ----------------------------------------------------
                coord = self.dim(axis)
                if coord is None or not coord.Units.isreftime:
                    raise ValueError(
"Can't collapse: Reference-time dimension coordinates are required for an \"over days\" collapse")
                if not coord.hasbounds:
                    raise ValueError(
"Can't collapse: Reference-time dimension coordinate bounds are required for an \"over days\" collapse")

                cell_methods = getattr(self, 'cell_methods', None)
                if not cell_methods or 'days' not in cell_methods.within:
                    raise ValueError(
"Can't collapse: An \"over days\" collapse must come after a \"within days\" collapse")

                # Parse the over_days parameter
                if isinstance(over_days, Query):
                    over_days = (over_days,)              
                elif isinstance(over_days, TimeDuration):
                    if over_days.Units.istime and over_days < Data(1, 'day'):
                        raise ValueError(
                            "Can't collapse: Bad parameter value: over_days=%r" %
                            over_days)
                #--- End: if

                coordinate = 'min'
                
                classification = numpy_empty((axis_size,), int)
                classification.fill(-1)
                
                if isinstance(over_days, TimeDuration):
                    lower, upper, lower_limit, upper_limit = _tyu(coord, group_by, True)

                bounds = coord.bounds
                lower_bounds = bounds.lower_bounds.dtarray
                upper_bounds = bounds.upper_bounds.dtarray

                HMS0 = None

#            * An "over days" collapse must be preceded by a "within
#              days" collapse, as described by the CF conventions. If the
#              field already contains sub-daily data, but does not have
#              the "within days" cell methods flag then it may be added,
#              for example, as follows (this example assumes that the
#              appropriate cell method is the most recently applied,
#              which need not be the case; see `cf.CellMethods` for
#              details):
#            
#              >>> f.cell_methods[-1].within = 'days'

                n = 0
                for lower, upper in izip(lower_bounds, upper_bounds):
                    HMS_l = (eq(lower.hour  , attr='hour') & 
                             eq(lower.minute, attr='minute') & 
                             eq(lower.second, attr='second')).addattr('lower_bounds')
                    HMS_u = (eq(upper.hour  , attr='hour') & 
                             eq(upper.minute, attr='minute') & 
                             eq(upper.second, attr='second')).addattr('upper_bounds')
                    HMS = HMS_l & HMS_u

                    if not HMS0:
                        HMS0 = HMS
                    elif HMS.equals(HMS0):
                        break

                    if over_days is None:
                        # --------------------------------------------
                        # over_days=None
                        # --------------------------------------------
                        # Over all days
                        index = HMS.evaluate(coord).array
                        classification[index] = n
                        n += 1         
                    elif isinstance(over_days, TimeDuration):
                        # --------------------------------------------
                        # E.g. over_days=cf.M()
                        # --------------------------------------------
                        classification, n = _time_interval(classification, n,
                                                           coord=coord,
                                                           interval=over_days,
                                                           lower=lower,
                                                           upper=upper,
                                                           lower_limit=lower_limit,
                                                           upper_limit=upper_limit,
                                                           group_by=group_by,
                                                           extra_condition=HMS)
                    else:
                        # --------------------------------------------
                        # E.g. over_days=[cf.month(cf.wi(4, 9))]
                        # --------------------------------------------
                        classification, n = _selection(classification, n,
                                                       coord=coord,
                                                       selection=over_days,
                                                       parameter='over_days',
                                                       extra_condition=HMS)
                        
            elif over == 'years':
                # ----------------------------------------------------
                # Over years
                # ----------------------------------------------------
                coord = self.dim(axis)
                if coord is None or not coord.Units.isreftime:
                    raise ValueError(
"Can't collapse: Reference-time dimension coordinates are required for an \"over years\" collapse")
                if not coord.hasbounds:
                    raise ValueError(
"Can't collapse: Reference-time dimension coordinate bounds are required for an \"over years\" collapse")

                cell_methods = getattr(self, 'cell_methods', None)
                if (not cell_methods or ('years' not in cell_methods.within and
                                         'days'  not in cell_methods.over)):
                    raise ValueError(
"Can't collapse: An \"over years\" collapse must come after a \"within years\" or \"over days\" collapse")

                # Parse the over_years parameter
                if isinstance(over_years, Query):
                    over_years = (over_years,)
                elif isinstance(over_years, TimeDuration):
                    if over_years.Units.iscalendartime:
                        over_years.Units = Units('calendar_years')
                        if not over_years.isint or over_years < 1:
                            raise ValueError(
"Can't collapse: over_years is not a whole number of calendar years: %r" % over_years)
                    else:
                        raise ValueError(
"Can't collapse: over_years is not a whole number of calendar years: %r" % over_years)
                #--- End: if
                
                coordinate = 'min'
                
                classification = numpy_empty((axis_size,), int)
                classification.fill(-1)
                
                if isinstance(over_years, TimeDuration):
                    lower, upper, lower_limit, upper_limit = _tyu(coord, group_by, True)

#                if coord.increasing:
#                    bounds_max = upper_bounds[-1]
#                else:
#                    bounds_min = lower_bounds[-1]
                 
                bounds = coord.bounds
                lower_bounds = bounds.lower_bounds.dtarray
                upper_bounds = bounds.upper_bounds.dtarray
                mdHMS0 = None
                    
                n = 0
                for lower, upper in izip(lower_bounds, upper_bounds):
                    mdHMS_l = (eq(lower.month , attr='month') & 
                               eq(lower.day   , attr='day') & 
                               eq(lower.hour  , attr='hour') & 
                               eq(lower.minute, attr='minute') & 
                               eq(lower.second, attr='second')).addattr('lower_bounds')
                    mdHMS_u = (eq(upper.month , attr='month') & 
                               eq(upper.day   , attr='day') & 
                               eq(upper.hour  , attr='hour') & 
                               eq(upper.minute, attr='minute') & 
                               eq(upper.second, attr='second')).addattr('upper_bounds')
                    mdHMS = mdHMS_l & mdHMS_u
                    if not mdHMS0:
                        mdHMS0 = mdHMS                        
                    elif mdHMS.equals(mdHMS0):
                        break
            
                    if over_years is None:
                        # --------------------------------------------
                        # E.g. over_years=None
                        # --------------------------------------------
                        # Over all years
                        index = mdHMS.evaluate(coord).array
                        classification[index] = n
                        n += 1
                    elif isinstance(over_years, TimeDuration):
                        # --------------------------------------------
                        # E.g. over_years=cf.Y(2)
                        # --------------------------------------------
#                        lower_bounds = bounds.lower_bounds
#                        upper_bounds = bounds.upper_bounds               
#                        
#                        lower = lower_bounds[0].dtarray[0]
#                        upper = upper_bounds[0].dtarray[0]
#                        bounds_min = lower_bounds[-1].dtarray[0]
#                        bounds_max = upper_bounds[-1].dtarray[0]

                        classification, n = _time_interval(classification, n,
                                                           coord=coord,
                                                           interval=over_years,
                                                           lower=lower,
                                                           upper=upper,
                                                           lower_limit=lower_limit,
                                                           upper_limit=upper_limit,
                                                           group_by=group_by,
                                                           extra_condition=mdHMS)
                    else:
                        # --------------------------------------------
                        # E.g. over_years=cf.year(cf.lt(2000))
                        # --------------------------------------------
                        classification, n = _selection(classification, n,
                                                       coord=coord,
                                                       selection=over_years,
                                                       parameter='over_years',
                                                       extra_condition=mdHMS)
                #--- End: for
    
            elif within == 'days':
                # ----------------------------------------------------
                # Within days
                # ----------------------------------------------------
                coord = self.dim(axis)
                if coord is None or not coord.Units.isreftime:
                    raise ValueError(
"Can't collapse: Reference-time dimension coordinates are required for an \"over years\" collapse")

#                # Get the bounds
#                if not coord.hasbounds:
#                    coord = coord.copy()
#
#                bounds = coord.get_bounds(create=True, insert=True)
    
                classification = numpy_empty((axis_size,), int)
                classification.fill(-1)
    
                # Parse the within_days parameter
                if isinstance(within_days, Query):
                    within_days = (within_days,)
                elif isinstance(within_days, TimeDuration):
                    if within_days.Units.istime and Data(1, 'day') % within_days:
                        raise ValueError(
"Can't collapse: within_days is not a factor of 1 day: %r" %
within_days)
                #--- End: if
                    
                if isinstance(within_days, TimeDuration):
                    # ------------------------------------------------
                    # E.g. within_days=cf.h(6)
                    # ------------------------------------------------ 
                    lower, upper, lower_limit, upper_limit = _tyu(coord, group_by, True)
                        
                    classification, n = _time_interval(classification, 0,
                                                       coord=coord,
                                                       interval=within_days,
                                                       lower=lower,
                                                       upper=upper,
                                                       lower_limit=lower_limit,
                                                       upper_limit=upper_limit,
                                                       group_by=group_by)
                else:
                    # ------------------------------------------------
                    # E.g. within_days=cf.hour(cf.lt(12))
                    # ------------------------------------------------
                    classification, n = _selection(classification, 0,
                                                   coord=coord,
                                                   selection=within_days,
                                                   parameter='within_days') 
                    
                    classification = _discern_runs(classification)
                           
            elif within == 'years':
                # ----------------------------------------------------
                # Within years
                # ----------------------------------------------------
                coord = self.dim(axis)
                if coord is None or not coord.Units.isreftime:
                    raise ValueError(
"Can't collapse: Reference-time dimension coordinates are required for an \"over years\" collapse")

#                # Get the bounds
#                if not coord.hasbounds:
#                    coord = coord.copy()
#
#                bounds = coord.get_bounds(create=True, insert=True)
    
                classification = numpy_empty((axis_size,), int)
                classification.fill(-1)

                # Parse within_years
                if isinstance(within_years, Query):
#                    over_years = (within_years,)               
                    within_years = (within_years,)
                elif within_years is None:
                    raise ValueError(
"Can't collapse: Bad parameter value: within_years={0!r}".format(within_years))
                  
                if isinstance(within_years, TimeDuration):
                    # ------------------------------------------------
                    # E.g. within_years=cf.M()
                    # ------------------------------------------------
                    lower, upper, lower_limit, upper_limit = _tyu(coord, group_by, True)
                        
                    classification, n = _time_interval(classification, 0,
                                                       coord=coord,
                                                       interval=within_years,
                                                       lower=lower,
                                                       upper=upper,
                                                       lower_limit=lower_limit,
                                                       upper_limit=upper_limit,
                                                       group_by=group_by)
                else:
                    # ------------------------------------------------
                    # E.g. within_years=cf.season()
                    # ------------------------------------------------
                    classification, n = _selection(classification, 0,
                                                   coord=coord,
                                                   selection=within_years,
                                                   parameter='within_years')
                    
                    classification = _discern_runs(classification)

            elif over is not None:
                raise ValueError(
                    "Can't collapse: Bad 'over' syntax: {0!r}".format(over))
                
            elif within is not None: 
                raise ValueError(
                    "Can't collapse: Bad 'within' syntax: {0!r}".format(within))
            #--- End: if
        #--- End: if
                 
        if classification is not None:
            if regroup:
                return classification

            #---------------------------------------------------------
            # Collapse each group
            #---------------------------------------------------------            
            unique = numpy_unique(classification)
            unique = unique[numpy_where(unique >= 0)[0]]
            unique.sort()

            for u in unique:
                index = numpy_where(classification==u)[0].tolist()

                pc = self.subspace(**{axis: index})

                w = _group_weights(weights, iaxis, index)
                     
                fl.append(pc.collapse(method, axis, weights=w,
                                      mtol=mtol, a=a, ddof=ddof,
                                      coordinate=coordinate,
                                      squeeze=False, i=True,
                                      _create_zero_size_cell_bounds=True))
            #--- End: for
        elif regroup:
            raise ValueError("Can't return classification 2453456 ")

        if not fl:
            raise ValueError(
                "Can't do grouped collapse: No groups were identified")
            
        if len(fl) == 1:
            f = fl[0]
        else:
            # Hack to fix missing bounds!
            for g in fl:
                try:
                    g.dim(axis).get_bounds(create=True, insert=True, copy=False)
                except:
                    pass

            #---------------------------------------------------------
            # Sort the list of collapsed fields
            #---------------------------------------------------------
            if coord is not None and coord.isdimension:
                fl.sort(key=lambda g: g.dim(axis).datum(0),
                        reverse=coord.decreasing)
                
            #---------------------------------------------------------
            # Concatenate the partial collapses
            # --------------------------------------------------------
            try:
                f = self.concatenate(fl, axis=iaxis, _preserve=False)
            except ValueError as error:
                raise ValueError("Can't collapse: %s" % error)
        #--- End: if
                      
        # --------------------------------------------------------
        # Update the cell methods
        # --------------------------------------------------------
        if within or over:
            cell_methods = getattr(f, 'cell_methods', None)
            if cell_methods is None:                                                   
                # The input field has no cell methods so create one                    
                name = f.axis_name(axis)                                               
                if within:                                                             
                    c = CellMethods("{0}: {1} within {2}".format(name, method, within))
                else:                                                                  
                    c = CellMethods("{0}: {1} over {2}".format(name, method, over))    
                c.axes = (axis,)                                                       
                f.cell_methods = c                                                     
            else:                                                                      
                lastcm = cell_methods[-1]
                if (_collapse_cell_methods.get(lastcm.method[0], None) == _collapse_cell_methods.get(method, None)  and
                    lastcm.axes   == ((axis,),) and
                    lastcm.within == (None,)    and
                    lastcm.over   == (None,)
                    ):
                    if within:
                        lastcm.within = within
                    else:
                        lastcm.over = over
        #--- End: if
  
        if squeeze and f.axis_size(axis) == 1:
            # Remove a totally collapsed axis from the field's
            # data array
            f.squeeze(axis, i=True)

        # ------------------------------------------------------------
        # Return the collapsed field
        # ------------------------------------------------------------
        self.__dict__ = f.__dict__
        return self
    #--- End: def

    def _conform_ancillary_variables(self, axes, keep_size_1=False):
        '''

Remove ancillary variable fields which span the given axes.

.. versionadded:: 1.0

.. seealso:: `_conform_ref_fields`

:Parameters:

    axes: sequence of str
        Sequence of domain axis identifiers.

    keep_size_1: bool, optional

:Returns:

    out: `None`

:Examples:

>>> f._conform_ancillary_variables(['dim2', 'dim1'])
>>> f._conform_ancillary_variables(['dim2'])
>>> f._conform_ancillary_variables([])

'''
        ancillary_variables = getattr(self, 'ancillary_variables', None)        
        if not ancillary_variables:
            return self

        new_av = []
        
        if keep_size_1:
            size = gt(1)
        else:
            size = None

        self_domain = self.domain
            
        for av in ancillary_variables:
            axis_map = av.domain.map_axes(self_domain)

            keep = True
            for av_axis in av.axes(size=size):
                if av_axis not in axis_map or axis_map[av_axis] in axes:
                    # Don't keep this ancillary variable field because
                    # either it has an axis which doesn't match any
                    # axis in the parent field or it has an axis which
                    # matches one of the given axes.
                    keep = False
                    break
            #--- End: for
            if keep:
                new_av.append(av)
        #--- End: for

        if new_av:
            self.ancillary_variables = FieldList(new_av)
        else:
            del self.ancillary_variables 
    #--- End: def
    
    def _conform_ref_fields(self, axes, keep_size_1=False):
        '''

Remove fields in coordinate reference objects which span the given
axes.

.. seealso:: `_conform_ancillary_variables`

:Parameters:

    axes: sequence of str
        Sequence of domain axis identifiers.

    keep_size_1: `bool`, optional

:Returns:

    out: `None`

:Examples:

>>> f._conform_ref_fields(['dim2', 'dim1'])
>>> f._conform_ref_fields(['dim2'])
>>> f._conform_ref_fields([])

'''       
        if keep_size_1:
            size = gt(1)
        else:
            size = None

        self_domain = self.domain
            
        for ref in self.refs().itervalues():
            for term, value in ref.iteritems():
                if not isinstance(value, Field):
                    # Keep the term because it's not a field
                    continue 
    
                axis_map = value.domain.map_axes(self_domain)
                for axis in value.axes(size=size):
                    if axis not in axis_map or axis_map[axis] in axes:
                        # Don't keep this coordinate reference field
                        # because either it has an axis which doesn't
                        # match any axis in the parent field or it has
                        # an axis which matches one of the given axes.
                        ref[term] = None
                        break
                #--- End: for
            #--- End: for
    #--- End: def
        
    def data_axes(self):
        '''Return the domain axis identifiers for the data array dimensions.

.. seealso:: `axes`, `axis`, `item_axes`

:Examples 1:

>>> d = f.data_axes()

:Returns:

[+1]    out: `list` or `None`
        The ordered axes of the data array. If there is no data array
        then `None` is returned.

:Examples 2:

>>> f.ndim
3
>>> f.data_axes()
['dim2', 'dim0', 'dim1']
>>> del f.Data
>>> print f.data_axes()
None

>>> f.ndim
0
>>> f.data_axes()
[]

        '''    
        if not self._hasData:
            return None

        return self.domain.data_axes()
    #--- End: def

    def dump(self, complete=False, display=True,
             _level=0, _title='Field', _q='='):
        '''{+Fef,}Print or return a string containing a description of the field.

By default, the description is given without abbreviation with the
exception of data arrays (which are abbreviated to their first and
last values) and fields contained in coordinate references and
ancillary variables (which are given as one-line summaries).

:Examples 1:
        
>>> f.dump()

:Parameters:
 
    complete: `bool`, optional
        Output a complete dump. Fields contained in coordinate references and
        ancillary variables are themselves described with their dumps.

    display: `bool`, optional
        If False then{+,fef,} return the description as a string. By default
        the description is printed.

          *Example:*
[+1]            ``f.dump()`` is equivalent to ``print
[+1]            f.dump(display=False)``.
[+N]            ``f.dump()`` is equivalent to ``for g in f: print
[+N]            g.dump(display=False)``.

:Returns:

[+1]    out: `None` or `str`
[+1]        If *display* is False then the description is printed and
[+1]        `None` is returned. Otherwise the description is restured as a
[+1]        string.
[+N]    out: `None` or `list`
[+N]        If *display* is False then{+,fef,} the description is printed
[+N]        and `None` is returned. Otherwise a list of strings containing
[+N]        the description for each field is returned.

        '''
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            if display:
                for f in self:
                    f.dump(**kwargs2)
                return
            else:
                return [f.dump(**kwargs2) for f in self]
        #--- End: if 

        indent = '    '      
        indent0 = indent * _level
        indent1 = indent0 + indent

        domain = self.domain

        title = '%s%s: %s' % (indent0, _title, self.name(''))
        line  = '%s%s'     % (indent0, ''.ljust(len(title)-_level*4, _q))

        # Title
        string = [line, title, line]

        # Axes
        if domain.axes():
            string.extend((domain.dump_axes(display=False, _level=_level), ''))

        # Data
        if self._hasData:
            axis_name = domain.axis_name
            axis_size = domain.axis_size
            x = ['%s(%d)' % (axis_name(axis), axis_size(axis))
                 for axis in domain.data_axes()]
            string.append('%sData(%s) = %s' % (indent0, ', '.join(x),
                                               str(self.Data)))

        # Cell methods
        cell_methods = getattr(self, 'cell_methods', None)
        if cell_methods is not None:            
            string.append('%scell_methods = %s' % (indent0, cell_methods))

        # Simple properties
        if self._simple_properties():
            string.extend(
                ('', self._dump_simple_properties(_level=_level,
                                                  omit=('Conventions',))))
            
        # Flags
        flags = getattr(self, 'Flags', None)
        if flags is not None:            
            string.extend(('', flags.dump(display=False, _level=_level)))

        # Domain
        string.append(domain.dump_components(complete=complete, display=False,
                                             _level=_level))

        # Ancillary variables
        ancillary_variables = getattr(self, 'ancillary_variables', None)
        if ancillary_variables is not None:
            string.extend(('', '%sAncillary variables:' % indent0))
            if not complete:
                x = ['%s%r' % (indent1, f) for f in ancillary_variables]
                string.extend(x)
            else:
                for f in ancillary_variables:
                    string.append(f.dump(display=False, complete=False,
                                         _level=_level+1,
                                         _title='Ancillary field', _q='-'))
        #--- End: if

        string.append('')
        
        string = '\n'.join(string)
       
        if display:
            print string
        else:
            return string
    #--- End: def

    def equals(self, other, rtol=None, atol=None,
               ignore_fill_value=False, traceback=False,
               ignore=('Conventions',), _set=False):
        # Note: map(None, f, g) only works at python 2.x
        '''True if two {+variable}s are equal, False otherwise.

[+N]Two {+variable}s are equal if they have the same number of elements
[+N]and the field elements are equal pairwise, i.e. ``f.equals(g)`` is
[+N]equivalent to ``all(x.equals(y) for x, y in map(None, f, g))``.

Two fields are equal if ...

[+1]Note that a {+variable} may be equal to a single element field list,
[+1]for example ``f.equals(f[0:1])`` and ``f[0:1].equals(f)`` are always
[+1]True.

[+N]Note that a single element {+variable} may be equal to field, for
[+N]example ``f[0:1].equals(f[0])`` and ``f[0].equals(f[0:1])`` are always
[+N]True.

[+1].. seealso:: `cf.FieldList.equals`, `set_equals`
[+N].. seealso:: `cf.Field.equals`, `set_equals`

:Examples 1:

>>> b = f.equals(g)

:Parameters:

    other: `object`
        The object to compare for equality.

    {+atol}

    {+rtol}

    ignore_fill_value: `bool`, optional
        If True then data arrays with different fill values are
        considered equal. By default they are considered unequal.

    traceback: `bool`, optional
        If True then print a traceback highlighting where the two
        {+variable}s differ.

    ignore: `tuple`, optional
        The names of CF properties to omit from the comparison. By
        default, the CF Conventions property is omitted.

:Returns: 
  
    out: `bool`
        Whether or not the two {+variable}s are equal.

:Examples 2:

>>> f.Conventions
'CF-1.0'
>>> g = f.copy()
>>> g.Conventions = 'CF-1.5'
>>> f.equals(g)
True

In the following example, two fields differ only by the long name of
their time coordinates. The traceback shows that they differ in their
domains, that they differ in their time coordinates and that the long
name could not be matched.

>>> g = f.copy()
>>> g.coord('time').long_name += ' different'
>>> f.equals(g, traceback=True)
Domain: Different coordinate: <CF Coordinate: time(12)>
Field: Different domain properties: <CF Domain: (128, 1, 12, 64)>, <CF Domain: (128, 1, 12, 64)>
False

        '''
        kwargs2 = self._parameters(locals())
        return super(Field, self).equals(**kwargs2)
    #---End: def

    def equivalent(self, other, rtol=None, atol=None, traceback=False):
        '''

True if two {+variable}s are equivalent, False otherwise

two fields are equivalent if:

  * They have the same identity, as defined by their
    `~cf.Field.identity` methods.

  * The same rank, as given by their `~cf.Field.rank` attributes.

  * Their data arrays are the same after accounting for different but
    equivalent:

    * Units

    * Number of size one dimensions (if *squeeze* is True),
    
    * Dimension directions (if *use_directions* is True) 
    
    * Dimension orders (if *transpose* is set to a dictionary).

  * Both fields' domains must have the same rankdimensionality and where a
    dimension in one field has an identity inferred a 1-d coordinate,
    the other field has a matching dimension whose identity inferred
    is inferred from a 1-d coordinate with an equivalent data array.

    * The rank, as given by their `~cf.Field.rank`

[+1].. seealso:: `~cf.Field.equals`, `set_equals`
[+N].. seealso:: `~cf.FieldList.equals`, `set_equals`

:Examples 1:

>>> b = f.equivalent(g)

:Parameters:

    other: `object`
        The object to compare for equivalence.

    {+atol}

    {+rtol}

    traceback: `bool`, optional
        If True then print a traceback highlighting where the two
        {+variable}s differ.

:Returns: 

    out: `bool`
        Whether or not the two {+variable}s are equivalent.
      
:Examples 2:

>>>

'''
        if not self.equivalent_domain(other, rtol=rtol, atol=atol,
                                      traceback=traceback):
            if traceback:
                print("%s: Nonequivalent domains: %r, %r" % 
                      (self.__class__.__name__,
                       self.domain, other.domain))
            return False

        if not self.equivalent_data(other, rtol=rtol, atol=atol,
                                    traceback=False):
            if traceback:
                print("%s: Nonequivalent data arrays: %r, %r" % 
                      (self.__class__.__name__,
                       getattr(self, 'data', None),
                       getattr(other, 'data', None)))
            return False
                
        return True
    #--- End_def

    def equivalent_domain(self, other, rtol=None, atol=None,
                          traceback=False):
        '''

Return True if two fields have equivalent data domains.

:Parameters:

    other: `cf.Field`

    atol: `float`, optional
        The absolute tolerance for all numerical comparisons, By
        default the value returned by the `cf.ATOL` function is used.

    rtol: `float`, optional
        The relative tolerance for all numerical comparisons, By
        default the value returned by the `cf.RTOL` function is used.

    traceback: `bool`, optional
        If True then print a traceback highlighting where the two
        domains differ.

:Returns:

    out: `bool`
        Whether or not the two fields' data arrays are equivalent.

:Examples:

>>> f.equivalent_domain(g)

'''
        return self.domain.equivalent(other.domain, rtol=rtol,
                                      atol=atol, traceback=traceback)
    #--- End_def

    def equivalent_data(self, other, rtol=None, atol=None, traceback=False):
        '''

Return True if two fields have equivalent data arrays.

Equivalence is defined as both fields having the same data arrays
after accounting for different but equivalent units, size one
dimensions, different dimension directions and different dimension
orders.

:Parameters:

    other: `cf.Field`

    atol: `float`, optional
        The absolute tolerance for all numerical comparisons, By
        default the value returned by the `cf.ATOL` function is used.

    rtol: `float`, optional
        The relative tolerance for all numerical comparisons, By
        default the value returned by the `cf.RTOL` function is used.

    traceback: `bool`, optional
        If True then print a traceback highlighting where the two
        data arrays differ.

:Returns:

    out: `bool`
        Whether or not the two fields' data arrays are equivalent.

:Examples:

>>> f.equivalent_data(g)

'''
        if self._hasData != other._hasData:
            if traceback:
                print("%s: Only one field has data: %s, %s" %
                      (self.__class__.__name__, self._hasData, other._hasData))
            return False
        
        if not self._hasData:
            # Neither field has a data array
            return True

        if self.size != other.size:
            if traceback:
                print("%s: Different data array sizes (%d, %d)" %
                      (self.__class__.__name__, self.size, other.size))
            return False

        s = self.domain.analyse()
        t = other.domain.analyse()

        data0 = self.data
        data1 = other.data
        if 1 in data0._shape:
            data0 = data0.squeeze()
            
        copy = True
        if 1 in data1._shape:
            data1 = data1.squeeze()
            copy = False

        data_axes0 = self.domain.data_axes()
        data_axes1 = other.domain.data_axes()

        transpose_axes = []
        for axis0 in data_axes0:
            axis1 = t['id_to_axis'].get(s['axis_to_id'][axis0], None)
            if axis1 is not None:
                transpose_axes.append(data_axes1.index(axis1))
            else:
                if traceback:
                    print("%s: woooooooooooooooo" % self.__class__.__name__)
                return False
        #--- End: for
       
        if transpose_axes != range(other.ndim):
            if copy:
                data1 = data1.copy()
                copy = False

            data1.transpose(transpose_axes, i=True)
        #--- End: if

        if self.size > 1:            
            self_directions  = self.domain.directions()
            other_directions = other.domain.directions()

            flip_axes = [i for i, (axis1, axis0) in enumerate(izip(data_axes1,
                                                                   data_axes0))
                         if other_directions[axis1] != self_directions[axis0]]
        
            if flip_axes:
                if copy:
                    data1 = data1.copy()                
                    copy = False

                data1.flip(flip_axes, i=True)
        #--- End: if

        return data0.equals(data1, rtol=rtol, atol=atol, ignore_fill_value=True)
    #--- End: def

    def expand_dims(self, position=0, axes=None, i=False, **kwargs):
        '''{+Fef,}Insert a size 1 axis into the data array.

By default default a new size 1 axis is inserted which doesn't yet
exist, but a unique existing size 1 axis which is not already spanned
by the data array may be selected.

.. seealso:: `axes`, `flip`, `squeeze`, `transpose`, `unsqueeze`

:Examples 1:

Insert a new size axis in position 0:

>>> g = f.expand_dims()

Insert  the existing, size 1 time axis in position 2:

>>> g = f.expand_dims(2, axes='T')

:Parameters:

    position: `int`, optional
        Specify the position that the new axis will have in the data
        array. By default the new axis has position 0, the slowest
        varying position.

    {+axes, kwargs}

    {+i}

:Returns:

    out: `cf.{+Variable}`
        {+Fef,}, the expanded field.

:Examples 2:

        '''
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('expand_dims', kwargs2)

        domain = self.domain

        if axes is None and not kwargs:
            axis = domain.new_axis_identifier()
        else:
            axis = domain.axis(axes, **kwargs)
            if axis is None:
                raise ValueError("Can't identify a unique axis to insert")
            elif domain.axis_size(axis) != 1:
                raise ValueError("Can't insert an axis of size %d: %r" %
                                 (domain.axis_size(axis), axis))
            elif axis in domain.data_axes():
                raise ValueError(
                    "Can't insert a duplicate axis: %r" % axis)
        #--- End: if
       
        # Expand the dims in the field's data array
        f = super(Field, self).expand_dims(position, i=i)

        domain = f.domain
        domain._axes['data'].insert(position, axis)
        domain._axes_sizes[axis] = 1

        return f
    #--- End: def

    def indices(self, *args, **kwargs):
        '''Create data array indices based on domain metadata.

If metadata values are specified for an axis then a full slice
(``slice(None)``) is assumed for that axis.

Values for size 1 axes which are not spanned by the field's data array
may be specified, but only indices for axes which span the field's
data array will be returned.

The coordinate value conditions may be given in any order.

.. seealso:: `where`, `subspace`

:Parameters:

    args: optional

        ===========  =================================================
        *arg*        Description
        ===========  =================================================
        ``'exact'``  Keyword parameter names are not treated as
                     abbreviations of item identities. By default,
                     keyword parameter names are allowed to be
                     abbreviations of item identities.
        ===========  =================================================

    kwargs: optional
        Keyword parameters identify items of the domain () and set
        conditions on their data arrays. Indices are created which,
        for each axis, select where the conditions are met.

        A keyword name is a string which selects a unique item of the
        domain. The string may be any string value allowed by *items*
        parameter of the field's `item` method, which is used to
        select a unique domain item. See `cf.Field.item` for details.
        
          *Example:*           
            The keyword ``lat`` will select the item returned by
            ``f.item('lat', role='dam')``. See the *exact* parameter.

        In general, a keyword value specifies a test on the selected
        item's data array which identifies axis elements. The returned
        indices for this axis are the positions of these elements.

          *Example:*
            To create indices for the northern hemisphere, assuming
            that there is a coordinate with identity "latitude":
            ``f.indices(latitude=cf.ge(0))``

          *Example:*
            To create indices for the northern hemisphere, identifying
            the latitude coordinate by its long name:
            ``f.indices(**{'long_name:latitude': cf.ge(0)})``. In this
            case it is necessary to use the ``**`` syntax because the
            ``:`` characeter is not allowed in keyword parameter
            names.

        If the value is a `slice` object then it is used as the axis
        indices, without testing the item's data array.

          *Example:*
            To create indices for every even numbered element along
            the "Z" axis: ``f.indices(Z=slice(0, None, 2))``.


        **Multidimensional items**
          Indices based on items which span two or more axes are
          possible if the result is a single element index for each of
          the axes spanned. In addition, two or more items must be
          provided, each one spanning the same axes  (in any order).

            *Example:*          
              To create indices for the unique location 45 degrees
              north, 30 degrees east when latitude and longitude are
              stored in 2-dimensional auxiliary coordiantes:
              ``f.indices(latitude=45, longitude=30)``. Note that this
              example would also work if latitude and longitude were
              stored in 1-dimensional dimensional or auxiliary
              coordinates, but in this case the location would not
              have to be unique.

    exact: `str`, optional

:Returns:

    out: `tuple`
        
:Examples:

These examples use the following field, which includes a dimension
coordinate object with no identity (``ncvar:model_level_number``) and
which has a data array which doesn't span all of the domain axes:


>>> print f
eastward_wind field summary
---------------------------
Data           : eastward_wind(time(3), air_pressure(5), grid_latitude(110), grid_longitude(106)) m s-1
Cell methods   : time: mean
Axes           : time(3) = [1979-05-01 12:00:00, ..., 1979-05-03 12:00:00] gregorian
               : air_pressure(5) = [850.0, ..., 50.0] hPa
               : grid_longitude(106) = [-20.54, ..., 25.66] degrees
               : grid_latitude(110) = [23.32, ..., -24.64] degrees
Aux coords     : latitude(grid_latitude(110), grid_longitude(106)) = [[67.12, ..., 22.89]] degrees_N
               : longitude(grid_latitude(110), grid_longitude(106)) = [[-45.98, ..., 35.29]] degrees_E
Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>


>>> f.indices(lat=23.32, lon=-20.54)
(slice(0, 3, 1), slice(0, 5, 1), slice(0, 1, 1), slice(0, 1, 1))

>>> f.indices(grid_lat=slice(50, 2, -2), grid_lon=[0, 1, 3, 90]) 
(slice(0, 3, 1), slice(0, 5, 1), slice(50, 2, -2), [0, 1, 3, 90])

>>> f.indices('exact', grid_latitude=slice(50, 2, -2), grid_longitude=[0, 1, 3, 90]) 
(slice(0, 3, 1), slice(0, 5, 1), slice(50, 2, -2), [0, 1, 3, 90])

>>> f.indices(grid_lon=cf.wi(0, 10, 'degrees'), air_pressure=850)
(slice(0, 3, 1), slice(0, 1, 1), slice(0, 110, 1), slice(47, 70, 1))

>>> f.indices(grid_lon=cf.wi(0, 10), air_pressure=cf.eq(85000, 'Pa')
(slice(0, 3, 1), slice(0, 1, 1), slice(0, 110, 1), slice(47, 70, 1))

>>> f.indices(grid_long=cf.gt(0, attr='lower_bounds'))
(slice(0, 3, 1), slice(0, 5, 1), slice(0, 110, 1), slice(48, 106, 1))

        '''
        exact = 'exact' in args

        domain = self.domain

        data_axes = domain.data_axes()

        # Initialize indices
        indices = [slice(None)] * self.ndim
        
        wee = {}
        unique_axes = set()
        n_axes = 0
        for identity, value in kwargs.iteritems():
            items = domain.items(identity, role=('d', 'a'), exact=exact)
            if len(items) != 1:
                raise ValueError(
                    "Can't find indices: Ambiguous axis or axes: %r" %
                    identity)

            key, coord = items.popitem()
            axes = domain.item_axes(key)
            sorted_axes = tuple(sorted(axes))
            if sorted_axes not in wee:
                n_axes += len(sorted_axes)

            wee.setdefault(sorted_axes, []).append((tuple(axes), coord, value))

            unique_axes.update(sorted_axes)
        #--- End: for

        if len(unique_axes) < n_axes:
            raise ValueError("Ambiguous axis specification")

        for key, axes_coord_value in wee.iteritems():
            axes, coords, point = zip(*axes_coord_value)
                
            n_coords = len(coords)
            n_axes   = len(key)

            if n_coords != n_axes:
                raise IndexError(
"Must specify %d %d-d coordinate objects to find %d-d indices (got %d)" %
(n_axes, n_axes, n_axes, n_coords))
                
            if n_coords == 1:
                #-----------------------------------------------------
                # 1-d coordinate
                #-----------------------------------------------------
                coord = coords[0]
                value = point[0]
                axis  = axes[0][0]    

                if isinstance(value, (slice, list)):
                    # CASE 1: Subspace criterion is already a valid index
                    # (i.e. it is a slice object or a list (of ints, but
                    # this isn't checked for)).
                    index = value
    
                elif (isinstance(value, Query) and 
                    value.operator in ('wi', 'wo') and
                    coord.isdimension and
                    self.iscyclic(key)):
                    # CASE 2: Axis is cyclic and subspace criterion is
                    # a 'within' or 'without' cf.Query instance
                    if coord.increasing:
                        anchor0 = value.value[0]
                        anchor1 = value.value[1]
                    else:
                        anchor0 = value.value[1]
                        anchor1 = value.value[0]
                        
                    a = self.anchor(axis, anchor0, dry_run=True)['roll']
                    b = self.flip(axis).anchor(axis, anchor1, dry_run=True)['roll']
                    
                    size = coord.size 
                    if abs(anchor1 - anchor0) >= coord.period():
                        if value.operator == 'wo':
                            start = 0
                            stop  = 0
                        else:
                            start = -a
                            stop  = -a
                    elif a + b == size:
                        b = self.anchor(axis, anchor1, dry_run=True)['roll']
                        if b == a:
                            if value.operator == 'wo':
                                start= -a
                                stop = -a
                            else:
                                start = 0
                                stop  = 0
                        else:
                            if value.operator == 'wo':
                                start= 0
                                stop = 0
                            else:
                                start = -a
                                stop  = -a
                    else:
                        if value.operator == 'wo':
                            start = b - size
                            stop  = -a + size
                        else:
                            start = -a
                            stop  = b - size
    
                    index = slice(start, stop, 1)
                else:        
                    # CASE 3: All other cases
                    item_match = (value == coord)
                
                    if not item_match.any():
                        raise IndexError(
                            "No %r axis indices found from: %r" %
                            (identity, value))
                
                    index = item_match.array
                #--- End: if
    
                # Put the index in to the correct place in the list of
                # indices
                if axis in data_axes:
                    indices[data_axes.index(axis)] = index
                                    
            else:
                #-----------------------------------------------------
                # N-d coordinate
                #-----------------------------------------------------
                
                # Make sure that each auxiliary coordinate has the
                # same axis order
                coords2 = [coords[0]]
                axes0   = axes[0]
                for a, coord in zip(axes[1:], coords[1:]):
                    if a != axes0:
                        coord = coord.transpose([axes0.index(axis) for axis in a])

                    coords2.append(coord)
                #--- End: for
                coords = coords2

                item_matches = [v == c for v, c in zip(point, coords)]
                    
                item_match = item_matches.pop()
                for m in item_matches:
                    item_match &= m
 
                ind = numpy_where(item_match)

                bounds = [coord.bounds.array[ind] for coord in coords
                          if coord.hasbounds]

                contain = False
                if bounds:
                    point2 = []
                    for v, coord in zip(point, coords):  
                        if isinstance(v, Query):
                            if v.operator == 'contain':                                
                                contain = True
                                v = v.value
                            elif v.operator == 'eq':
                                v = v.value
                            else:
                                contain = False
                                break
                        #--- End: if

                        v = Data.asdata(v)
                        if v.Units:
                            v.Units = coord.Units
                        
                        point2.append(v.datum())
                    #--- End: for
                #--- End: if

                if contain:
                    # The coordinates have bounds and a 'contain'
                    # cf.Query object has been given. Check each
                    # possibly matching cell for actully including the
                    # point.
                    if n_coords > 2:
                        raise IndexError(
                            "333Can't geasasdast index for cell from %d-d coordinate objects" %
                            n_axes)

                    if 0 < len(bounds) < n_coords:
                        raise ValueError("bounds alskdaskds")

                    n_cells = 0
                    for cell, vertices in enumerate(zip(*zip(*bounds))):
                        n_cells += Path(zip(*vertices)).contains_point(point2)
                        if n_cells > 1:
                            # The point is apparently in more than one
                            # cell
                            break
                else:
                    n_cells = len(ind[0])
                    cell = 0
                #--- End: if

                if not n_cells:
                    raise IndexError(
                        "No index found for the point %r" % (point,))
                elif n_cells > 1:
                    raise IndexError("Multiple indices found for %r" % (point,))
                
                # Put the indices in to the correct place in the list
                # of indices
                for axis, index in zip(axes0, numpy_array(ind)[:, cell]):
                    if axis in data_axes:
                        indices[data_axes.index(axis)] = index
                #--- End: for
            #--- End: if
        #--- End: for
                    
#        # Loop round slice criteria
#        for identity, value in kwargs.iteritems():
#            coords = domain.items(identity, role=('d', 'a'),
#                                  exact=exact)
#
#            if len(coords) != 1:
#                raise ValueError(
#                    "Can't find indices: Ambiguous axis identity: %r" %
#                    identity)
#
#            key, coord = coords.popitem()
#
#            if coord.ndim == 1:
#                axis = domain.item_axes(key)[0]
#    
#                if axis in seen_axes:
#                    raise ValueError(
#                        "Can't find indices: Duplicate %r axis" % axis)
#                else:
#                    seen_axes.append(axis)
#    
#                if isinstance(value, (slice, list)):
#                    # ----------------------------------------------------
#                    # Case 1: Subspace criterion is already a valid index
#                    # (i.e. it is a slice object or a list (of ints, but
#                    # this isn't checked for)).
#                    # ----------------------------------------------------
#                    index = value
#    
#                elif (isinstance(value, Query) and 
#                    value.operator in ('wi', 'wo') and
#                    coord.isdimension and
#                    self.iscyclic(key)):
#                    # ----------------------------------------------------
#                    # Case 2: Axis is cyclic and subspace criterion is a
#                    # 'within' or 'without' cf.Query instance
#                    # ----------------------------------------------------
#                    if coord.increasing:
#                        anchor0 = value.value[0]
#                        anchor1 = value.value[1]
#                    else:
#                        anchor0 = value.value[1]
#                        anchor1 = value.value[0]
#                        
#                    a = self.anchor(axis, anchor0, dry_run=True)['roll']
#                    b = self.flip(axis).anchor(axis, anchor1, dry_run=True)['roll']
#                    
#                    size = coord.size 
#                    if abs(anchor1 - anchor0) >= coord.period():
#                        if value.operator == 'wo':
#                            start = 0
#                            stop  = 0
#                        else:
#                            start = -a
#                            stop  = -a
#                    elif a + b == size:
#                        b = self.anchor(axis, anchor1, dry_run=True)['roll']
#                        if b == a:
#                            if value.operator == 'wo':
#                                start= -a
#                                stop = -a
#                            else:
#                                start = 0
#                                stop  = 0
#                        else:
#                            if value.operator == 'wo':
#                                start= 0
#                                stop = 0
#                            else:
#                                start = -a
#                                stop  = -a
#                    else:
#                        if value.operator == 'wo':
#                            start = b - size
#                            stop  = -a + size
#                        else:
#                            start = -a
#                            stop  = b - size
#    
#                    index = slice(start, stop, 1)
#                else:        
#                    # ----------------------------------------------------
#                    # Case 3: All other cases
#                    # ----------------------------------------------------
#                    item_match = (value == coord)
#                
#                    if not item_match.any():
#                        raise IndexError(
#                            "No %r axis indices found from: %r" %
#                            (identity, value))
#                
#                    index = item_match.array
#                #--- End: if
#    
#                # Put the index in to the correct place in the list of
#                # indices
#                if axis in data_axes:
#                    indices[data_axes.index(axis)] = index
#                    
#            else:
#                axes = domain.item_axes(key)[0]
#                item_match = (value == coord)
#                if not item_match.any():
#                    raise IndexError(
#                        "No %r axis indices found from: %r" %
#                        (identity, value))                    
#        #--- End: for

        # Return a tuple of the indices
        return tuple(parse_indices(self, tuple(indices), False))
    #--- End: def

    def insert_data(self, data, axes=None, copy=True, replace=True):
        '''Insert a new data array into the field in place.

Note that the data array's missing data value, if it has one, is not
transferred to the field.

:Parameters:

    data: `cf.Data`
        The new data array.

    axes: sequence of `str`, optional
        A list of axis identifiers (``'dimN'``), stating the axes, in
        order, of the data array.

        The ``N`` part of each identifier should be replaced by an
        integer greater then or equal to zero such that either a) each
        axis identifier is the same as one in the field's domain, or
        b) if the domain has no axes, arbitrary integers greater then
        or equal to zero may be used, the only restriction being that
        the resulting identifiers are unique.

        If an axis of the data array already exists in the domain then
        the it must have the same size as the domain axis. If it does
        not exist in the domain then a new axis will be created.

        By default the axes will either be those defined for the data
        array by the domain or, if these do not exist, the domain axis
        identifiers whose sizes unambiguously match the data array.

    copy: `bool`, optional
        If False then the new data array is not deep copied prior to
        insertion. By default the new data array is deep copied.

    replace: `bool`, optional
        If False then do not replace an existing data array. By
        default an data array is replaced with *data*.
   
:Returns:

    `None`

:Examples:

>>> f.domain._axes_sizes
{'dim0': 1, 'dim1': 3}
>>> f.insert_data(cf.Data([[0, 1, 2]]))

>>> f.domain._axes_sizes
{'dim0': 1, 'dim1': 3}
>>> f.insert_data(cf.Data([[0, 1, 2]]), axes=['dim0', 'dim1'])

>>> f.domain._axes_sizes
{}
>>> f.insert_data(cf.Data([[0, 1], [2, 3, 4]]))
>>> f.domain._axes_sizes
{'dim0': 2, 'dim1': 3}

>>> f.insert_data(cf.Data(4))

>>> f.insert_data(cf.Data(4), axes=[])

>>> f.domein._axes_sizes
{'dim0': 3, 'dim1': 2}
>>> data = cf.Data([[0, 1], [2, 3, 4]])
>>> f.insert_data(data, axes=['dim1', 'dim0'], copy=False)

>>> f.insert_data(cf.Data([0, 1, 2]))
>>> f.insert_data(cf.Data([3, 4, 5]), replace=False)
ValueError: Can't initialize data: Data already exists
>>> f.insert_data(cf.Data([3, 4, 5]))

        '''
        if self._hasData and not replace:
            raise ValueError(
                "Can't set data: Data already exists and replace=%s" %
                replace)

        domain = self.domain

        if data.isscalar:
            # --------------------------------------------------------
            # The data array is scalar
            # --------------------------------------------------------
            if axes: 
                raise ValueError(
"Can't set data: Wrong number of axes for scalar data array: {0}".format(axes))

            axes = []

        elif axes is not None:
            # --------------------------------------------------------
            # The axes have been set
            # --------------------------------------------------------
            axes = self.axes(axes, ordered=True)

            if not axes:
                # The domain has no axes: Ignore the provided axes and
                # make some up for the data array
                axes = []
                for size in data.shape:
                    axes.append(self.insert_axis(size))

                axes = axes[:]
            else:
                len_axes = len(axes)
                if len_axes != len(set(axes)):
                    raise ValueError(
"Can't set data: Ambiguous axes: {0}".format(axes))

                    if len_axes != data.ndim:
                        raise ValueError(
"Can't set data: Wrong number of axes for data array: {0!r}".format(axes))
                        
                for axis, size in izip(axes, data.shape):
                    axis_size = self.axis_size(axis)
                    if size != axis_size:
                        raise ValueError(
"Can't set data: Incompatible domain size for axis %r (%d)" %
(axis, size))
                #--- End: for

        elif domain.data_axes() is None:
            # --------------------------------------------------------
            # The data is not scalar and axes have not been set and
            # the domain does not have data axes defined => infer the
            # axes.
            # --------------------------------------------------------
            if not self.axes():
                # The domain has no axes, so make some up for the data
                # array
                axes = []
                for size in data.shape:
                    axes.append(self.insert_axis(size))

                axes = axes[:]
            else:
                # The domain already has some axes
                data_shape = data.shape
                if len(data_shape) != len(set(data_shape)):
                    raise ValueError(
"Can't set data: Ambiguous shape: %s. Consider setting the axes parameter." %
(data_shape,))

                axes = []
                domain_sizes = domain._axes_sizes.values()
                for n in data_shape:
                    if domain_sizes.count(n) == 1:
                        axes.append(domain.axis(size=n))
                    else:
                        raise ValueError(
"Can't set data: Ambiguous shape: %s. Consider setting the axes parameter." %
(data_shape,))
                 #--- End: for
        else:
            # --------------------------------------------------------
            # The data is not scalar and axes have not been set, but
            # the domain has data axes defined.
            # --------------------------------------------------------
            axes = domain.data_axes()
            if len(axes) != data.ndim:
                raise ValueError(
                    "Can't set data: Wrong number of axes for data array: %r" %
                    axes)
            
            for axis, size in izip(axes, data.shape):
                try:
                    domain.insert_axis(size, axis, replace=False)
                except ValueError:
                    raise ValueError(
"Can't set data: Incompatible domain size for axis %r (%d)" %
(axis, size))
            #--- End: for
        #--- End: if

        domain._axes['data'] = axes

        if copy:
            data = data.copy()

        self.Data = data
    #--- End: def

    def domain_mask(self, *args, **kwargs):
        '''{+Fef,}The mask of the data array.

.. versionadded:: 1.1

.. seealso:: `indices`, `mask`, `subspace`

:Examples 1:

Creat a which is True within 30 degrees of the equator:

>>> m = f.domain_mask(latitude=cf.wi(-30, 30))

:Parameters:

    args, kwargs: optional

:Returns:

    out: cf.{+Variable}
        {+Fef,}The domain mask.

:Examples 2:

        '''
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('domain_mask', kwargs2)

        m = self.copy(_omit_Data=True,
                      _omit_properties=True, _omit_attributes=True)

        m.Data = Data.zeros(self.shape, dtype=bool)
        m.Data[m.indices(*args, **kwargs)] = True

        m.long_name = 'mask'

        return m
    #--- End: def

    def match(self, select=None, items=None, rank=None, ndim=None,
              exact=False, match_and=True, inverse=False):
        '''{+Fef,}Test whether or not the field satisfies the given conditions.

Different types of conditions may be set with the parameters:
         
===========  =========================================================
Parameter    What gets tested
===========  =========================================================
*match*      Field properties and attributes
             
*items*      Field domain items
         
*rank*       The number of field domain axes

*ndim*       The number of field data array axes
===========  =========================================================

By default, when multiple criteria are given the field matches if it
satisfies the conditions given by each one.

.. seealso:: `items`, `select`

**Quick start examples**

There is great flexibility in the types of test which can be
specified, and as a result the documentation is very detailed in
places. These preliminary, simple examples show that the usage need
not always be complicated and may help with understanding the keyword
descriptions.

1. Test if a field contains air temperature data, as given determined
   by its `identity` method:

   >>> f.match('air_temperature')

2. Test if a field contains air temperature data, as given determined
   by its `identity` method, or has a long name which contains the
   string "temp":

   >>> f.match(['air_temperature', {'long_name': cf.eq('.*temp.*', regex=true)}])

3. Test if a field has at least one longitude grid cell point on the
   Greenwich meridian:

   >>> f.match(items={'longitude': 0})

4. Test if a field has latitude grid cells which all have a resolution
   of less than 1 degree:

   >>> f.match(items={'latitude': cf.cellsize(cf.lt(1, 'degree'))})

5. Test if a field has exactly 4 domain axes:

   >>> f.match(rank=4)

6. Examples 1 to 4 may be combined to test if a field has exactly 4
   domain axes, contains air temperature data, has at least one
   longitude grid cell point on the Greenwich meridian and all
   latitude grid cells have a resolution of less than 1 degree:

   >>> f.match('air_temperature',
   ...         items={'longitude': 0,
   ...                'latitude': cf.cellsize(cf.lt(1, 'degree'))},
   ...         rank=4)

7. Test if a field contains Gregorian calendar monthly mean data array
   values:

   >>> f.match({'cell_methods': cf.CellMethods('time: mean')},
   ...         items={'time': cf.cellsize(cf.wi(28, 31, 'days'))})

Further examples are given within and after the description of the
arguments.


:Parameters:

    match: optional
        Set conditions on the field's CF property and attribute
        values. *match* may be one, or a sequence of:

          * `None` or an empty dictionary. Always matches the
            field. This is the default.

     ..

          * A string which identifies string-valued metadata of the
            field and a value to compare it against. The value may
            take one of the following forms:

              ==============  ======================================
              *match*         Interpretation
              ==============  ======================================
              Contains ``:``  Selects on the CF property specified
                              before the first ``:``
                                
              Contains ``%``  Selects on the attribute specified
                              before the first ``%``              
              
              Anything else   Selects on identity as returned by the
                              `identity` method
              ==============  ======================================

            By default the part of the string to be compared with the
            item is treated as a regular expression understood by the
            :py:obj:`re` module and the field matches if its
            appropriate value matches the regular expression using the
            :py:obj:`re.match` method (i.e. if zero or more characters
            at the beginning of field's value match the regular
            expression pattern). See the *exact* parameter for
            details.
            
              *Example:*
                To match a field with `identity` beginning with "lat":
                ``match='lat'``.

              *Example:*
                To match a field with long name beginning with "air":
                ``match='long_name:air'``.

              *Example:*
                To match a field with netCDF variable name of exactly
                "tas": ``match='ncvar%tas$'``.

              *Example:*
                To match a field with `identity` which ends with the
                letter "z": ``match='.*z$'``.

              *Example:*
                To match a field with long name which starts with the
                string ".*a": ``match='long_name%\.\*a'``. 

        ..

          * A `cf.Query` object to be compared with field's identity,
            as returned by its `identity` method.

              *Example:*
                To match a field with `identity` of exactly
                "air_temperature" you could set
                ``match=cf.eq('air_temperature')`` (see `cf.eq`).

              *Example:*
                To match a field with `identity` ending with
                "temperature" you could set
                ``match=cf.eq('.*temperature$', exact=False)`` (see
                `cf.eq`).

     ..

          * A dictionary which identifies properties of the field with
            corresponding tests on their values. The field matches if
            **all** of the tests in the dictionary are passed.

            In general, each dictionary key is a CF property name with
            a corresponding value to be compared against the field's
            CF property value. 

            If the dictionary value is a string then by default it is
            treated as a regular expression understood by the
            :py:obj:`re` module and the field matches if its
            appropriate value matches the regular expression using the
            :py:obj:`re.match` method (i.e. if zero or more characters
            at the beginning of field's value match the regular
            expression pattern). See the *exact* parameter for
            details.
            
              *Example:*
                To match a field with standard name of exactly
                "air_temperature" and long name beginning with the
                letter "a": ``match={'standard_name':
                cf.eq('air_temperature'), 'long_name': 'a'}`` (see
                `cf.eq`).

            Some key/value pairs have a special interpretation:

              ==================  ====================================
              Special key         Value
              ==================  ====================================
              ``'units'``         The value must be a string and by
                                  default is evaluated for
                                  equivalence, rather than equality,
                                  with the field's `units` property,
                                  for example a value of ``'Pa'``
                                  will match units of Pascals or
                                  hectopascals, etc. See the *exact*
                                  parameter.
                            
              ``'calendar'``      The value must be a string and by
                                  default is evaluated for
                                  equivalence, rather than equality,
                                  with the field's `calendar`
                                  property, for example a value of
                                  ``'noleap'`` will match a calendar
                                  of noleap or 365_day. See the
                                  *exact* parameter.
                              
              ``'cell_methods'``  The value must be a `cf.CellMethods`
                                  object containing *N* cell methods
                                  and by default is evaluated for
                                  equivalence with the last *N* cell
                                  methods contained within the field's
                                  `cell_methods` property. See the
                                  *exact* parameter.

              `None`              The value is interpreted as for a
                                  string value of the *match*
                                  parameter. For example,
                                  ``match={None: 'air'}`` is
                                  equivalent to ``match='air'`` and
                                  ``match={None: 'ncvar%pressure'}``
                                  is equivalent to
                                  ``match='ncvar%pressure'``.
              ==================  ====================================
            
              *Example:*
                To match a field with standard name starting with
                "air", units of temperature and a netCDF variable name
                beginning with "tas" you could set
                ``match={'standard_name': 'air', 'units': 'K', None:
                'ncvar%tas'}``.

              *Example:*
                To match a field whose last two cell methods are
                equivalent to "time: minimum area: mean":
                ``match={'cell_methods': cf.Cellmethods('time: minimum
                area: mean')``. This would match a field which has,
                for example, cell methods of "height: mean time:
                minimum area: mean".

        If *match* is a sequence of any combination of the above then
        the field matches if it matches **at least one** element of
        the sequence:

          *Example:* 

            >>> f.match('air_temperature')
            True
            >>> f.match('air_pressure')
            False
            >>> f.match({'units': 'hPa', 'long_name': 'foo'})
            False
            >>> f.match(['air_temperature',
            ...          'air_pressure',
            ...          {'units': 'hPa', 'long_name': 'foo'}])
            True
  
        If the sequence is empty then the field always matches.
 
    items: `dict`, optional
        A dictionary which identifies domain items of the field
        (dimension coordinate, auxiliary coordinate, cell measure or
        coordinate reference objects) with corresponding tests on
        their elements. The field matches if **all** of the specified
        items exist and their tests are passed.

        Each dictionary key specifies an item to test as the one that
        would be returned by this call of the field's `item` method:
        ``f.item(key, exact=exact)`` (see `cf.Field.item`).

        The corresponding value is, in general, any object for which
        the item may be compared with for equality (``==``). The test
        is passed if the result evaluates to True, or if the result is
        an array of values then the test is passed if at least one
        element evaluates to true.

        If the value is `None` then the test is always passed,
        i.e. this case tests for item existence.

          *Example:*
             To match a field which has a latitude coordinate value of
             exactly 30: ``items={'latitude': 30}``.

          *Example:*
             To match a field whose longitude axis spans the Greenwich
             meridien: ``items={'longitude': cf.contain(0)}`` (see
             `cf.contain`).

          *Example:*
             To match a field which has a time coordinate value of
             2004-06-01: ``items={'time': cf.dt('2004-06-01')}`` (see
             `cf.dt`).

          *Example:*
             To match a field which has a height axis: ``items={'Z':
             None}``.

          *Example:*
             To match a field which has a time axis and depth
             coordinates greater then 1000 metres: ``items={'T': None,
             'depth': cf.gt(1000, 'm')}`` (see `cf.gt`).

          *Example:*
            To match a field with time coordinates after than 1989 and
            cell sizes of between 28 and 31 days: ``items={'time':
            cf.dtge(1990) & cf.cellsize(cf.wi(28, 31, 'days'))}`` (see
            `cf.dtge`, `cf.cellsize` and `cf.wi`).

    rank: optional
        Specify a condition on the number of axes in the field's
        domain. The field matches if its number of domain axes equals
        *rank*. A range of values may be selected if *rank* is a
        `cf.Query` object. Not to be confused with the *ndim*
        parameter (the number of data array axes may be fewer than the
        number of domain axes).

          *Example:*
            ``rank=2`` matches a field with exactly two domain axes
            and ``rank=cf.wi(3, 4)`` matches a field with three or
            four domain axes (see `cf.wi`).

    ndim: optional
        Specify a condition on the number of axes in the field's data
        array. The field matches if its number of data array axes
        equals *ndim*. A range of values may be selected if *ndim* is
        a `cf.Query` object. Not to be confused with the *rank*
        parameter (the number of domain axes may be greater than the
        number of data array axes).

          *Example:*
            ``ndim=2`` matches a field with exactly two data array
            axes and ``ndim=cf.le(2)`` matches a field with fewer than
            three data array axes (see `cf.le`).

    exact: `bool`, optional
        The *exact* parameter applies to the interpretation of string
        values of the *match* parameter and of keys of the *items*
        parameter. By default *exact* is False, which means that:

          * A string value is treated as a regular expression
            understood by the :py:obj:`re` module. 

          * Units and calendar values in a *match* dictionary are
            evaluated for equivalence rather then equality
            (e.g. "metre" is equivalent to "m" and to "km").

          * A cell methods value containing *N* cell methods in a
            *match* dictionary is evaluated for equivalence with the
            last *N* cell methods contained within the field's
            `cell_methods` property.

        ..

          *Example:*
            To match a field with a standard name which begins with
            "air" and any units of pressure:
            ``f.match({'standard_name': 'air', 'units': 'hPa'})``.

          *Example:*          
            ``f.match({'cell_methods': cf.CellMethods('time: mean
            (interval 1 hour)')})`` would match a field with cell
            methods of "area: mean time: mean (interval 60 minutes)".

        If *exact* is True then:

          * A string value is not treated as a regular expression.

          * Units and calendar values in a *match* dictionary are
            evaluated for exact equality rather than equivalence
            (e.g. "metre" is equal to "m", but not to "km").

          * A cell methods value in a *match* dictionary is evaluated
            for exact equality to the field's cell methods.
          
        ..

          *Example:*          
            To match a field with a standard name of exactly
            "air_pressure" and units of exactly hectopascals:
            ``f.match({'standard_name': 'air_pressure', 'units':
            'hPa'}, exact=True)``.

          *Example:*          
            To match a field with a cell methods of exactly "time:
            mean (interval 1 hour)": ``f.match({'cell_methods':
            cf.CellMethods('time: mean (interval 1 hour)')``.

        Note that `cf.Query` objects provide a mechanism for
        overriding the *exact* parameter for individual values.

          *Example:*
            ``f.match({'standard_name': cf.eq('air', exact=False),
            'units': 'hPa'}, exact=True)`` will match a field with a
            standard name which begins "air" but has units of exactly
            hectopascals (see `cf.eq`).
    
          *Example:*
            ``f.match({'standard_name': cf.eq('air_pressure'),
            'units': 'hPa'})`` will match a field with a standard name
            of exactly "air_pressure" but with units which equivalent
            to hectopascals (see `cf.eq`).

    match_and: `bool`, optional
        By default *match_and* is True and the field matches if it
        satisfies the conditions specified by each test parameter
        (*match*, *items*, *rank* and *ndim*).

        If *match_and* is False then the field will match if it
        satisfies at least one test parameter's condition.

          *Example:*
            To match a field with a standard name of "air_temperature"
            **and** 3 data array axes: ``f.match('air_temperature',
            ndim=3)``. To match a field with a standard name of
            "air_temperature" **or** 3 data array axes:
            ``f.match('air_temperature", ndim=3, match_and=False)``.
    
    inverse: `bool`, optional
        If True then return the field matches if it does **not**
        satisfy the given conditions.

          *Example:*
          
            >>> f.match('air', ndim=4, inverse=True) == not f.match('air', ndim=4)
            True

:Returns:

[+1]    out: `bool`
[+N]    out: `list` of `bool`
        {+Fef,}True if the field satisfies the given criteria, False
        otherwise.

:Examples:

Field identity starts with "air":

>>> f.match('air')

Field identity ends contains the string "temperature":

>>> f.match('.*temperature')

Field identity is exactly "air_temperature":

>>> f.match('^air_temperature$')
>>> f.match('air_temperature', exact=True)

Field has units of temperature:

>>> f.match({'units': 'K'}):

Field has units of exactly Kelvin:

>>> f.match({'units': 'K'}, exact=True)

Field identity which starts with "air" and has units of temperature:

>>> f.match({None: 'air', 'units': 'K'})

Field identity starts with "air" and/or has units of temperature:

>>> f.match(['air', {'units': 'K'}])

Field standard name starts with "air" and/or has units of exactly Kelvin:

>>> f.match([{'standard_name': cf.eq('air', exact=False), {'units': 'K'}],
...         exact=True)

Field has height coordinate values greater than 63km:

>>> f.match(items={'height': cf.gt(63, 'km')})

Field has a height coordinate object with some values greater than
63km and a north polar point on its horizontal grid:

>>> f.match(items={'height': cf.gt(63, 'km'),
...                'latitude': cf.eq(90, 'degrees')})

Field has some longitude cell sizes of 3.75:

>>> f.match(items={'longitude': cf.cellsize(3.75)})

Field latitude cell sizes within a tropical region are all no greater
than 1 degree:

>>> f.match(items={'latitude': (cf.wi(-30, 30, 'degrees') &
...                             cf.cellsize(cf.le(1, 'degrees')))})

Field contains monthly mean air pressure data and all vertical levels
within the bottom 100 metres of the atmosphere have a thickness of 20
metres or less:

>>> f.match({None: '^air_pressure$', 'cell_methods': cf.CellMethods('time: mean')},
...         items={'height': cf.le(100, 'm') & cf.cellsize(cf.le(20, 'm')),
...                'time': cf.cellsize(cf.wi(28, 31, 'days'))})

        '''
        conditions_have_been_set = False
        something_has_matched    = False

        if rank is not None:
            conditions_have_been_set = True
            found_match = len(self.axes()) == rank
            if match_and and not found_match:
                return bool(inverse)

            something_has_matched = True
        #--- End: if

        if select:
            conditions_have_been_set = True
             
        # --------------------------------------------------------
        # Try to match other properties and attributes
        # --------------------------------------------------------
        found_match = super(Field, self).match(
            match=select, ndim=ndim, exact=exact,
            match_and=match_and, inverse=False,
            _Flags=True, _CellMethods=True)

        if match_and and not found_match:
            return bool(inverse)

        something_has_matched = found_match
        #--- End: if

        # ------------------------------------------------------------
        # Try to match items
        # ------------------------------------------------------------
        if items:
            conditions_have_been_set = True

            found_match = False

            for identity, condition in items.iteritems():
                c = self.item(identity, exact=exact)

                if condition is None:
                    field_matches = True
                elif c is None:
                    field_matches = False
                else:
                    field_matches = condition == c
                    try:
                        field_matches = field_matches.any()
                    except AttributeError:
                        pass
                #--- End: if
                
                if match_and:                    
                    if field_matches:
                        found_match = True 
                    else:
                        found_match = False
                        break
                elif field_matches:
                    found_match = True
                    break
            #--- End: for 

            if match_and and not found_match:
                return bool(inverse)

            something_has_matched = found_match
        #--- End: if

        if conditions_have_been_set:
            if something_has_matched:            
                return not bool(inverse)
            else:
                return bool(inverse)
        else:
            return not bool(inverse)
    #--- End: def

#In [66]: w  
#Out[66]: array([ 0.125,  0.25 ,  0.375,  0.25 ])
#In [67]: convolve1d(a, w, mode='mirror')        
#Out[67]: array([ 1.75,  2.25,  3.25,  4.25,  5.25,  6.25,  7.  ,  7.25])
#
#In [68]: (w[::-1] * [5, 6, 7, 8]).sum()  
#Out[68]: 6.25
#
#In [69]: (w[::-1] * [6, 7, 8, 7]).sum() 
#Out[69]: 7.0
#
#In [70]: (w[::-1] * [7, 8, 7, 6]).sum()  
#Out[70]: 7.25





#In [60]: convolve1d(a, t, mode='mirror') 
#Out[60]: array([ 1.5,  2. ,  3. ,  4. ,  5. ,  6. ,  7. ,  7.5])
#
#In [61]: (t[::-1] * [5, 6, 7]).sum()   
#Out[61]: 6.0
#
#In [62]: (t[::-1] * [6, 7, 8]).sum()  
#Out[62]: 7.0
#
#In [63]: (t[::-1] * [7, 8, 7]).sum()  
#Out[63]: 7.5
#
#In [64]: t                           
#Out[64]: array([ 0.25,  0.5 ,  0.25])
#
#In [65]: a                            
#Out[65]: array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.])


#In [75]: convolve1d(a, w, mode='reflect')   
#Out[75]: array([ 1.5  ,  2.25 ,  3.25 ,  4.25 ,  5.25 ,  6.25 ,  7.125,  7.625])
#
#In [76]: (w[::-1] * [5, 6, 7, 8]).sum()  
#Out[76]: 6.25
#
#In [77]: (w[::-1] * [6, 7, 8, 8]).sum()   
#Out[77]: 7.125
#
#In [78]: (w[::-1] * [7, 8, 8, 7]).sum()   
#Out[78]: 7.625
#In [81]: w     
#Out[81]: array([ 0.125,  0.25 ,  0.375,  0.25 ])
#
#In [82]: a     
#Out[82]: array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.])

#In [94]: u                                                                                                        
#Out[94]: array([ 0.11111111,  0.22222222,  0.33333333,  0.22222222,  0.11111111])
#
#In [95]: convolve#convolve1d(a, w, mode='reflect')eflect')                                                        
#
#In [96]: convolve1d(a, u, mode='mirror')                                                                          
#Out[96]: 
#array([ 1.88888889,  2.22222222,  3.        ,  4.        ,  5.        ,
#        6.        ,  6.77777778,  7.11111111])
#
#In [97]: (u[::-1] * [4, 5, 6, 7, 8]).sum()                                                                        
#Out[97]: 6.0
#
#In [98]: (u[::-1] * [5, 6, 7, 8, 7]).sum()                                                                        
#Out[98]: 6.7777777777777768
#
#In [99]: (u[::-1] * [6, 7, 8, 7, 6]).sum()                                                                        
#Out[99]: 7.1111111111111107
#
#In [100]:                                        
#
#    def smooth(self, n, weights='boxcar', axis=None, mode='reflect', constant=0.0, mtol=0.0,
#               beta=None, std=None, power=None, width=None,
#               attenuation=None, return_weights=False):
## http://docs.scipy.org/doc/scipy-0.14.0/reference/signal.html      
##scipy.ndimage.filters.convolve1d
##ocs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.filters.convolve.html        
##http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.filters.convolve1d.html
#
#        '''Smooth the field along one of its axes.
#
# By default the field is smoothed with an unweighted moving average.
#
# The smoothing is the discrete convolution of values along the axis
# with a normalised weights function defined over an interval (window)
# of the axis.
#
#
#
#:Parameters:
#
#    window: `str`, optional
#
#          ====================  ==============================  ===============================
#          weights               Description                     Reference
#          ====================  ==============================  ===============================
#          ``barthann``          Modified Bartlett-Hann weights  `scipy.signal.barthann`        
#          ``bartlett``          Bartlett weights                `scipy.signal.bartlett`        
#          ``blackman``          Blackman weights                `scipy.signal.blackman`       
#          ``blackmanharris``    Minimum 4-term Blackman-Harris  `scipy.signal.blackmanharris`  
#                                weights                           
#          ``bohman``            Bohman weights                  `scipy.signal.bohman`          
#          ``boxcar``            Boxcar or rectangular weights   `scipy.signal.boxcar`
#          ``chebwin``           Dolph-Chebyshev weights         `scipy.signal.chebwin`         
#          ``cosine``            Weights with a simple cosine    `scipy.signal.cosine`          
#                                shape                                   
#          ``flattop``           Flat top weights                `scipy.signal.flattop`         
#          ``gaussian``          Gaussian weights                `scipy.signal.gaussian`        
#          ``general_gaussian``  Weights with a generalized      `scipy.signal.general_gaussian`
#                                Gaussian shape                   
#          ``hamming``           Hamming weights                 `scipy.signal.hamming`         
#          ``hann``              Hann weights                    `scipy.signal.hann`           
#          ``kaiser``            Kaiser weights                  `scipy.signal.kaiser`          
#          ``nuttall``           Minimum 4-term Blackman-Harris  `scipy.signal.nuttall`         
#                                weights according to Nuttall      
#          ``parzen``            Parzen weights                  `scipy.signal.parzen`         
#          ``slepian``           Digital Slepian (DPSS) weights  `scipy.signal.slepian`         
#          ``triang``            Triangular weights              `scipy.signal.triang`          
#          ???/                  User-defined weights
#          ====================  ==============================  ===============================
#
#        The default weights are ``'boxcar'``, which are create an
#        unweighted moving average

#        Some weights require extra parameters to be set for their calculation:
#        
#          ======================  ================  ===============================
#          *weights*               Extra parameters  Reference                      
#          ======================  ================  ===============================
#          ``'chebwin'``           *attenuation*     `scipy.signal.chebwin`
#          ``'gaussian'``          *std*             `scipy.signal.gaussian`    
#          ``'general_gaussian'``  *power*, *std*    `scipy.signal.general_gaussian`
#          ``'kaiser'``            *beta*            `scipy.signal.kaiser`   
#          ``'slepian'``           *width*           `scipy.signal.slepian`   
#          ======================  ================  ===============================
#
#    attenuation: number, optional
#        Required for a Dolph-Chebyshev weights, otherwise
#        ignored. *attenuation* is in decibels.
#    
#          Example: ``n=51, weights='chebwin', attenuation=100``
#
#    beta: number, optional
#        Required for Kaiser weights, otherwise ignored. *beta* is a
#        shape parameter which determines the trade-off between
#        main-lobe width and side lobe level.
#    
#          Example: ``n=51, weights='Kaiser', beta=14``
#
#    power: number, optional
#        Required for a generalized Gaussian weights, otherwise
#        ignored. *power* is a shape parameter: 1 is identical to
#        Gaussian weights, 0.5 is the same shape as the Laplace
#        distribution.
#
#          Example: ``n=52, weights='general_gaussian', power=1.5, std=7``
#
#    std: number, optional
#        Required for Gaussian and generalized Gaussian weights,
#        otherwise ignored. *std* is the standard deviation, sigma.
#
#          Example: ``n=52, weights='gaussian', std=7``
#
#    width: float, optional
#        Required for digital Slepian (DPSS) weights, otherwise
#        ignored. *wodth* is the bandwidth.
#
#          Example: ``n=51, weights='slepian', width=0.3``
#
#    rolling_window: optional
#        Group the axis elements for a "rolling window" collapse. The
#        axis is grouped into **consecutive** runs of **overlapping**
#        elements. The first group starts at the first element of the
#        axis and each following group is offset by one element from
#        the previous group, so that an element may appear in multiple
#        groups. The collapse operation is applied to each group
#        independently and the collapsed axis in the returned field
#        will have a size equal to the number of groups. If weights
#        have been given by the *weights* parameter then they are
#        applied to each group, unless alternative weights have been
#        provided with the *window_weights* parameter. The
#        *rolling_window* parameter may be one of:
#
#          * An `int` defining the number of elements in each
#            group. Each group will have exactly this number of
#            elements. Note that if the group size does does not divide
#            exactly into the axis size then some elements at the end
#            of the axis will not be included in any group.
#            
#              Example: To define groups of 5 elements:
#              ``rolling_window=5``.
#
#        .. 
#
#          * A `cf.Data` defining the group size. Each group contains a
#            consecutive run of elements whose range of coordinate
#            bounds does not exceed the group size. Note that 1) if the
#            group size is sufficiently small then some groups may be
#            empty and some elements may not be inside any group may
#            not be inside any group; 2) different groups may contain
#            different numbers of elements.
#
#              Example: To create 10 kilometre windows:
#              ``rolling_window=cf.Data(10, 'km')``.
#
#    window_weights: ordered sequence of numbers, optional
#        Specify the weights for a rolling window collapse. Each
#        non-empty group uses these weights in its collapse, and all
#        non-empty groups must have the same number elements as the
#        window weights. If *window_weights* is not set then the groups
#        take their weights from the *weights* parameter, and in this
#        case the groups may have different sizes.
#
#          Example: To define a 1-2-1 filter: ``rolling_window=3,
#          window_weights=[1, 2, 1]``.
#
#'''
#        if weights == 'user':
#            weights = numpy_array(weights, float)
#            if weights.size != n:
#                raise ValueError("jb ")
#            if weights.ndim > 1:
#                raise ValueError("bad shape")
#        else:
#            weights = getattr(signal, window)(n, **window_args)

#        if return_weights:
#            return weights

#        http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.filters.convolve1d.html

#        http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.filters.convolve.html

#        smoothed_array = convolve1d(array, weights/weights.sum(), axis=iaxis,
        #                            mode=mode, cval=constant)
#        
#        f.Data = Data(smoothed_array, f.Units)
#http://mail.scipy.org/pipermail/scipy-user/2008-November/018601.html
#Sorry for the long overdue reply.
#
#Reflect means:
#
#1 | 2 | 3 | 2 | 1
#
#While mirror means:
#
#1 | 2 | 3 | 3| 2 | 1
#
#(or the other way around, can't remember). IT IS THE OTHER WAY ROUND!!!!
#
#http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.savgol_filter.html#scipy.signal.savgol_filter

#The problem with the last approach is the interpolation between 3 and
#3, which is currently broken, so I'd advise against using it.
#
#
#        # Coordinate bounds
#        dim = f.dim(axis)
#
#
#        n_by_2 = 0.5 * n
#        i = int(n_by_2)
#        j = axis_size - i
#        d1 = i
#        if not i < n_by_2:
#            # Window has even number of points
#            i -= 1
#
#        d0 = i
# 
#        new_bounds[:i, 0] = bounds[0, 0]
#
#        new_bounds[i:j, 0] = bounds[i-d0:j-d0, 0]
#        new_bounds[i:j, 1] = bounds[i+d1:j+d1, 1]
#
#        new_bounds[j:, 1] = bounds[-1, 1]
#
#        if mode == 'mirror':
#            new_bounds[:i, 1] = bounds[i+d1, 1]
#            new_bounds[j:, 0] = bounds[j-d0, 0]
#        elif mode in ('nearest', 'reflect', 'constant'):
#            new_bounds[:i, 1] = bounds[d1:i+d1, 1]
#            new_bounds[j:, 0] = bounds[j-d0:axis_size-d0, 0]
#                
#            wrap?
##        if dim:
#            if dim.hasbounds:            
#                data       = dim.array
#                bounds     = dim.bounds.array
#                new_bounds = numpy_empty(bounds.shape, dtype=float)
#                
#                half_window = 0.5 * n * float(cell_sizes[0])
#                
#                if dim.increasing:
#                    a_min, a_max = bounds[[0, -1], [0, 1]]
#                else:
#                    half_window = -half_window 
#                    a_min, a_max = bounds[[-1, 0], [0, 1]]
#                    
#                new_bounds[0] = data - half_window
#                new_bounds[1] = data + half_window
#                numpy_clip(new_bounds, a_min, a_max, new_bounds)
#                
#                dim.insert_bounds(Data(new_bounds, dim.Units), copy=False)
#            #--- End: if   
#
#            f.remove_items(role='c', axes=axis)
#            
#            for b in f.auxs(axes=axis):
#                if b.hasbounds:
#                    del b.bounds
#       #--- End: if   

#        cell_methods = getattr(f, 'cell_methods', None)
#        if cell_methods is None:
#            cell_methods = CellMethods()
#
#        f.cell_methods += CellMethods(
#            'name: mean (+'+weights+' weights '+', '.join([str(x) for x in weights])+')')
#x
##    #--- E

    def HDF_chunks(self, *chunksizes):
        '''{+HDF_chunks}

**Chunking the metadata**

The coordinate, cell measure, and ancillary contructs are not
automatically chunked, but they may be chunked manually. For example,
a two dimensional latitude coordinate could chunked as follows (see
`cf.AuxiliaryCoordinate.HDF_chunks` for details):

>>> f.coord('latitude').HDF_chunks({0: 10, 1: 15})

In version 2.0, the metadata will be automatically chunked.

**Chunking via cf.write**

Chunking may also be defined via a parameter to the `cf.write`
function, in which case any axis chunk sizes set on the field take
precedence.

.. versionadded:: 1.1.13

.. seealso:: `cf.write`

:Examples 1:
        
To define chunks which are the full size for each axis except for the
time axis which is to have a chunk size of 12:

>>> old_chunks = f.HDF_chunks({'T': 12})

:Parameters:

    chunksizes: `dict` or `None`, optional
        Specify the chunk sizes for axes of the field. Axes are given
        by dictionary keys, with a chunk size for those axes as the
        dictionary values. A dictionary key of ``axes`` defines the
        axes that would be returned by the field's `~cf.Field.axes`
        method, i.e. by ``f.axes(axes)``. See `cf.Field.axes` for
        details. In the special case of *chunksizes* being `None`,
        then chunking is set to the netCDF default.

          *Example:*
            To set the chunk size for time axes to 365: ``{'T':
            365}``.

          *Example:*
            To set the chunk size for the first and third data array
            axes to 100: ``{0: 100, 2: 100}``, or equivalently ``{(0,
            2): 100}``.

          *Example:*
            To set the chunk size for the longitude axis to 100 and
            for the air temperature axis to 5: ``{'X': 100,
            'air_temperature': 5}``.

          *Example:*
            To set the chunk size for all axes to 10: ``{None:
            10}``. This works because ``f.axes(None)`` returns all
            field axes.

          *Example:*
            To set the chunking to the netCDF default: ``None``.

:Returns:

    out: `dict`
        The chunk sizes prior to the new setting, or the current
        current sizes if no new values are specified.

:Examples 2:

>>> f
<CF Field: air_temperature(time(3650), latitude(64), longitude(128)) K>
>>> f.HDF_chunks()
{0: None, 1: None, 2: None}
>>> f.HDF_chunks({'T': 365, 2: 1000})
{0: None, 1: None, 2: None}
>>> f.HDF_chunks({'X': None})
{0: 365, 1: None, 2: 1000}
>>> f.HDF_chunks(None)
{0: 365, 1: None, 2: None}
>>> f.HDF_chunks()
{0: None, 1: None, 2: None}

        '''
        if not chunksizes:
            return super(Field, self).HDF_chunks()

        if len(chunksizes) > 1:
            raise ValueError("asfdds ")
            
        chunks = chunksizes[0]

        if chunks is None:
            return super(Field, self).HDF_chunks(None)

        _HDF_chunks = {}
#        seen_axes = []
        data_axes = self.data_axes()
        for axes, size in chunks.iteritems():
            for axis in self.axes(axes):
#                if axis in seen_axes:
#                    raise ValueError(
#"Can't set multiple chunk sizes for axis {0}".format(data_axes.index(axis)))
                try:
                    _HDF_chunks[data_axes.index(axis)] = size
                except ValueError:
                    pass                
#                seen_axes.append(axis)
        #--- End: for

        return super(Field, self).HDF_chunks(_HDF_chunks)
    #--- End: def
            
    def field(self, items=None, role=None, axes=None, axes_all=None,
              axes_subset=None, axes_superset=None, exact=False,
              inverse=False, match_and=True, ndim=None, bounds=False):
        '''{+Fef,}Create an independent field from a domain item.

An item is either a dimension coordinate, an auxiliary coordinate or a
cell measure object of the domain.

{+item_selection}

If a unique item can not be found then no field is created and `None`
is returned.

A field may also be created from coordinate bounds (see the *bounds*
parameter).

.. versionadded:: 1.1

.. seealso:: `cf.read`, `item`

:Examples 1:

:Parameters:

    {+items}

    {+role}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}
       
    {+inverse}

    bounds: `bool`, optional
        If true then create a field from a coordinate object's bounds.

:Returns:

    out: `cf.{+Variable}`
        {+Fef,}The field based on the selected domain item.
        
:Examples 2:

::

   >>> print f 
   eastward_wind field summary
   ---------------------------
   Data           : eastward_wind(time(3), grid_latitude(110), grid_longitude(106)) m s-1
   Cell methods   : time: mean
   Axes           : time(3) = [1979-05-01 12:00:00, ..., 1979-05-03 12:00:00] gregorian
                  : grid_longitude(106) = [-20.54, ..., 25.66] degrees
                  : grid_latitude(110) = [23.32, ..., -24.64] degrees
   Aux coords     : latitude(grid_latitude(110), grid_longitude(106)) = [[67.12, ..., 22.89]] degrees_north
                  : longitude(grid_latitude(110), grid_longitude(106)) = [[-45.98, ..., 35.29]] degrees_east
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>
   
   >>> print f.field('X')
   grid_longitude field summary
   ----------------------------
   Data           : grid_longitude(grid_longitude(106)) degrees
   Axes           : grid_longitude(106) = [-20.54, ..., 25.66] degrees
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>
   
   >>> print f.field('X', bounds=True)
   grid_longitude field summary
   ----------------------------
   Data           : grid_longitude(grid_longitude(106), domain%dim1(2)) degrees
   Axes           : domain%dim1(2)
                  : grid_longitude(106) = [-20.54, ..., 25.66] degrees
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>
   
   >>> print f.field('lat')
   latitude field summary
   ----------------------
   Data           : latitude(grid_latitude(110), grid_longitude(106)) degrees_north
   Axes           : grid_longitude(106) = [-20.54, ..., 25.66] degrees
                  : grid_latitude(110) = [23.32, ..., -24.64] degrees
   Aux coords     : latitude(grid_latitude(110), grid_longitude(106)) = [[67.12, ..., 22.89]] degrees_north
                  : longitude(grid_latitude(110), grid_longitude(106)) = [[-45.98, ..., 35.29]] degrees_east
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>

To multiply the field by the cosine of its latitudes:

>>> latitude = f.field({'units': 'radian', None: 'Y'})
>>> latitude
<CF Field: grid_latitude(grid_latitude(110)) degrees>
>>> g = f * latitude.cos()

        '''
        kwargs2 = self._parameters(locals())

        # List functionality
        if self._list:
            return self._list_method('field', kwargs2)

        del kwargs2['bounds']
 
        items = self.items(**kwargs2)
        if not items:
            return

        key, item = items.popitem()

        if items:
            return

        domain = self.domain.copy()

        # Remove domain items which span any axis not spanned by the
        # item
        axes = self.axes(key, ordered=True)
        unused_axes = self.axes().difference(axes)
        for key in self.items(axes=unused_axes):
            domain.remove_item(key)

        # Remove coordinate references which do not span any of the
        # item's axes
        for key in self.refs():
            if not self.domain.ref_axes(key).intersection(axes):
                domain.remove_item(key)

        # Remove the unused axes
        domain._axes.pop('data', None)
        domain.remove_axes(unused_axes)

        if bounds and item.hasbounds:
            item = item.bounds
            axes.append(domain.insert_axis(item.shape[-1]))

        # Create the field
        f = type(self)(properties=item.properties,
                       domain=domain,
                       axes=axes,
                       data=getattr(item, 'Data', None),
                       copy=True)
        
        # Set the field's ncvar attribute
        ncvar = getattr(item, 'ncvar', None)
        if ncvar is not None:
            f.ncvar = ncvar

        return f
    #--- End: def

    def flip(self, axes=None, i=False, **kwargs):
        '''

{+Fef,}Flip (reverse the direction of) axes of the field.

.. seealso:: `axes`, `expand_dims`, `squeeze`, `transpose`,
             `unsqueeze`
        
:Examples:

>>> f.flip()
>>> f.flip('time')
>>> f.flip(1)
>>> f.flip('dim2')
>>> f.flip(['time', 1, 'dim2'])

:Parameters:

    {+axes, kwargs}

    {+i}
 
:Returns:

    out: `cf.{+Variable}`
        {+Fef,}The flipped field.

'''
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('flip', kwargs2)

        domain  = self.domain

        if axes is None and not kwargs:
            # Flip all the axes
            axes = domain.axes()
            iaxes = range(self.ndim)
        else:
            axes = domain.axes(axes, **kwargs)

            data_axes = domain.data_axes()
            iaxes = [data_axes.index(axis) for axis in
                     axes.intersection(data_axes)]
        #--- End: if

        # Flip the requested axes in the field's data array
        f = super(Field, self).flip(iaxes, i=i)

        # Flip any coordinate and cell measures which span the flipped
        # axes
        domain = f.domain
        domain_axes = domain._axes
        for key, item in domain.items(role=('d', 'a', 'm')).iteritems():
            item_axes = domain_axes[key]
            item_flip_axes = axes.intersection(item_axes)
            if item_flip_axes:
                iaxes = [item_axes.index(axis) for axis in item_flip_axes]
                item.flip(iaxes, i=True)
        #--- End: for

        return f
    #--- End: def

    def remove_data(self):
        '''

Remove and return the data array.

:Returns: 

    out: `cf.Data` or `None`
        The removed data array, or `None` if there isn't one.

:Examples:

>>> f._hasData
True
>>> f.data
<CF Data: [0, ..., 9] m>
>>> f.remove_data()
<CF Data: [0, ..., 9] m>
>>> f._hasData
False
>>> print f.remove_data()
None

'''
        self.domain._axes.pop('data', None)

        return super(Field, self).remove_data()
    #--- End: def

    def select(self, select=None, items=None, rank=None, ndim=None,
               exact=False, match_and=True, inverse=False):
        '''{+Fef,}Return the field if it satisfies the given conditions.

Different types of conditions may be set with the parameters:
         
===========  =========================================================
Parameter    What gets tested
===========  =========================================================
*select*     Field properties and attributes
             
*items*      Field domain items
         
*rank*       The number of field domain axes

*ndim*       The number of field data array axes
===========  =========================================================

By default, when multiple criteria are given the field matches if it
satisfies the conditions given by each one.

[+1]If the field does not satisfy the conditions then an empty
[+1]`cf.FieldList` object is returned.
[+N]If no fields satisfy the conditions then an empty `cf.FieldList`
[+N]object is returned.

[+1]Note that ``f.select(**kwargs)`` is equivalent to ``f if
[+1]f.match(**kwargs) else cf.FieldList()``.
[+N]Note that ``f.select(**kwargs)`` is equivalent to ``FieldList(g for g
[+N]in f if g.match(**kwargs))``

.. seealso:: `items`, `match`

**Quick start examples**

There is great flexibility in the types of test which can be
specified, and as a result the documentation is very detailed in
places. These preliminary, simple examples show that the usage need
not always be complicated and may help with understanding the keyword
descriptions.

1. Select fields which contain air temperature data, as given
   determined by the `identity` method:

   >>> f.select('air_temperature')

2. Select fields which contain air temperature data, as given determined
   by the `identity` method, or have a long name which contains the
   string "temp":

   >>> f.select(['air_temperature', {'long_name': cf.eq('.*temp.*', regex=true)}])

3. Select fields which have at least one longitude grid cell point on
   the Greenwich meridian:

   >>> f.select(items={'longitude': 0})

4. Select fields which have at least one latitude grid cell of less
   than 1 degree in size:

   >>> f.select(items={'latitude': cf.cellsize(cf.lt(1, 'degree'))})

5. Select fields which have exactly 4 domain axes:

   >>> f.select(rank=4)

6. Examples 1 to 4 may be combined to select fields which have exactly
   4 domain axes, contain air temperature data, has at least one
   longitude grid cell point on the Greenwich meridian and have at
   least one latitude grid cells with a size of less than 1 degree:

   >>> f.select('air_temperature',
   ...          items={'longitude': 0,
   ...                 'latitude': cf.cellsize(cf.lt(1, 'degree'))},
   ...          rank=4)

7. Select fields which contain at least one Gregorian calendar monthly
   mean data array value:

   >>> f.select({'cell_methods': cf.CellMethods('time: mean')},
   ...          items={'time': cf.cellsize(cf.wi(28, 31, 'days'))})

Further examples are given within and after the description of the
arguments.


:Parameters:

    select: optional
        Set conditions on the field's CF property and attribute
        values. *select* may be one, or a sequence of:

          * `None` or an empty dictionary. Always matches the
            field. This is the default.

     ..

          * A string which identifies string-valued metadata of the
            field and a value to compare it against. The value may
            take one of the following forms:

              ==============  ======================================
              *select*        Interpretation
              ==============  ======================================
              Contains ``:``  Selects on the CF property specified
                              before the first ``:``
                                
              Contains ``%``  Selects on the attribute specified
                              before the first ``%``              
              
              Anything else   Selects on identity as returned by the
                              `identity` method
              ==============  ======================================

            By default the part of the string to be compared with the
            item is treated as a regular expression understood by the
            :py:obj:`re` module and the field matches if its
            appropriate value matches the regular expression using the
            :py:obj:`re.match` method (i.e. if zero or more characters
            at the beginning of field's value match the regular
            expression pattern). See the *exact* parameter for
            details.
            
              *Example:*
                To select a field with `identity` beginning with "lat":
                ``select='lat'``.

              *Example:*
                To select a field with long name beginning with "air":
                ``select='long_name:air'``.

              *Example:*
                To select a field with netCDF variable name of exactly
                "tas": ``select='ncvar%tas$'``.

              *Example:*
                To select a field with `identity` which ends with the
                letter "z": ``select='.*z$'``.

              *Example:*
                To select a field with long name which starts with the
                string ".*a": ``select='long_name%\.\*a'``. 

        ..

          * A `cf.Query` object to be compared with field's identity,
            as returned by its `identity` method.

              *Example:*
                To select a field with `identity` of exactly
                "air_temperature" you could set
                ``select=cf.eq('air_temperature')`` (see `cf.eq`).

              *Example:*
                To select a field with `identity` ending with
                "temperature" you could set
                ``select=cf.eq('.*temperature$', exact=False)`` (see
                `cf.eq`).

     ..

          * A dictionary which identifies properties of the field with
            corresponding tests on their values. The field matches if
            **all** of the tests in the dictionary are passed.

            In general, each dictionary key is a CF property name with
            a corresponding value to be compared against the field's
            CF property value. 

            If the dictionary value is a string then by default it is
            treated as a regular expression understood by the
            :py:obj:`re` module and the field matches if its
            appropriate value matches the regular expression using the
            :py:obj:`re.match` method (i.e. if zero or more characters
            at the beginning of field's value match the regular
            expression pattern). See the *exact* parameter for
            details.
            
              *Example:*
                To select a field with standard name of exactly
                "air_temperature" and long name beginning with the
                letter "a": ``select={'standard_name':
                cf.eq('air_temperature'), 'long_name': 'a'}`` (see
                `cf.eq`).

            Some key/value pairs have a special interpretation:

              ==================  ====================================
              Special key         Value
              ==================  ====================================
              ``'units'``         The value must be a string and by
                                  default is evaluated for
                                  equivalence, rather than equality,
                                  with the field's `units` property,
                                  for example a value of ``'Pa'``
                                  will match units of Pascals or
                                  hectopascals, etc. See the *exact*
                                  parameter.
                            
              ``'calendar'``      The value must be a string and by
                                  default is evaluated for
                                  equivalence, rather than equality,
                                  with the field's `calendar`
                                  property, for example a value of
                                  ``'noleap'`` will match a calendar
                                  of noleap or 365_day. See the
                                  *exact* parameter.
                              
              ``'cell_methods'``  The value must be a `cf.CellMethods`
                                  object containing *N* cell methods
                                  and by default is evaluated for
                                  equivalence with the last *N* cell
                                  methods contained within the field's
                                  `cell_methods` property. See the
                                  *exact* parameter.

              `None`              The value is interpreted as for a
                                  string value of the *select*
                                  parameter. For example,
                                  ``select={None: 'air'}`` is
                                  equivalent to ``select='air'`` and
                                  ``select={None: 'ncvar%pressure'}``
                                  is equivalent to
                                  ``select='ncvar%pressure'``.
              ==================  ====================================
            
              *Example:*
                To select a field with standard name starting with
                "air", units of temperature and a netCDF variable name
                beginning with "tas" you could set
                ``select={'standard_name': 'air', 'units': 'K', None:
                'ncvar%tas'}``.

              *Example:*
                To select a field whose last two cell methods are
                equivalent to "time: minimum area: mean":
                ``select={'cell_methods': cf.Cellmethods('time: minimum
                area: mean')``. This would select a field which has,
                for example, cell methods of "height: mean time:
                minimum area: mean".

        If *select* is a sequence of any combination of the above then
        the field matches if it matches **at least one** element of
        the sequence:

          *Example:* 

            >>> f.select('air_temperature')
            <CF Field: air_temperature(latitude(73), longitude(96) K>
            >>> f.select({'units': 'hPa'})
            []
            >>> f.select(['air_temperature', {'units': 'hPa'])
            <CF Field: air_temperature(latitude(73), longitude(96) K>
              
        If the sequence is empty then the field always matches.
 
    items: `dict`, optional
        A dictionary which identifies domain items of the field
        (dimension coordinate, auxiliary coordinate, cell measure or
        coordinate reference objects) with corresponding tests on
        their elements. The field matches if **all** of the specified
        items exist and their tests are passed.

        Each dictionary key specifies an item to test as the one that
        would be returned by this call of the field's `item` method:
        ``f.item(key, exact=exact)`` (see `cf.Field.item`).

        The corresponding value is, in general, any object for which
        the item may be compared with for equality (``==``). The test
        is passed if the result evaluates to True, or if the result is
        an array of values then the test is passed if at least one
        element evaluates to true.

        If the value is `None` then the test is always passed,
        i.e. this case tests for item existence.

          *Example:*
             To select a field which has a latitude coordinate value of
             exactly 30: ``items={'latitude': 30}``.

          *Example:*
             To select a field whose longitude axis spans the Greenwich
             meridian: ``items={'longitude': cf.contain(0)}`` (see
             `cf.contain`).

          *Example:*
             To select a field which has a time coordinate value of
             2004-06-01: ``items={'time': cf.dt('2004-06-01')}`` (see
             `cf.dt`).

          *Example:*
             To select a field which has a height axis: ``items={'Z':
             None}``.

          *Example:*
             To select a field which has a time axis and depth
             coordinates greater then 1000 metres: ``items={'T': None,
             'depth': cf.gt(1000, 'm')}`` (see `cf.gt`).

          *Example:*
            To select a field with time coordinates after than 1989 and
            cell sizes of between 28 and 31 days: ``items={'time':
            cf.dtge(1990) & cf.cellsize(cf.wi(28, 31, 'days'))}`` (see
            `cf.dtge`, `cf.cellsize` and `cf.wi`).

    rank: optional
        Specify a condition on the number of axes in the field's
        domain. The field matches if its number of domain axes equals
        *rank*. A range of values may be selected if *rank* is a
        `cf.Query` object. Not to be confused with the *ndim*
        parameter (the number of data array axes may be fewer than the
        number of domain axes).

          *Example:*
            ``rank=2`` selects a field with exactly two domain axes
            and ``rank=cf.wi(3, 4)`` selects a field with three or
            four domain axes (see `cf.wi`).

    ndim: optional
        Specify a condition on the number of axes in the field's data
        array. The field matches if its number of data array axes
        equals *ndim*. A range of values may be selected if *ndim* is
        a `cf.Query` object. Not to be confused with the *rank*
        parameter (the number of domain axes may be greater than the
        number of data array axes).

          *Example:*
            ``ndim=2`` selects a field with exactly two data array
            axes and ``ndim=cf.le(2)`` selects a field with fewer than
            three data array axes (see `cf.le`).

    exact: `bool`, optional
        The *exact* parameter applies to the interpretation of string
        values of the *select* parameter and of keys of the *items*
        parameter. By default *exact* is False, which means that:

          * A string value is treated as a regular expression
            understood by the :py:obj:`re` module. 

          * Units and calendar values in a *select* dictionary are
            evaluated for equivalence rather then equality
            (e.g. "metre" is equivalent to "m" and to "km").

          * A cell methods value containing *N* cell methods in a
            *select* dictionary is evaluated for equivalence with the
            last *N* cell methods contained within the field's
            `cell_methods` property.

        ..

          *Example:*
            To select a field with a standard name which begins with
            "air" and any units of pressure:
            ``f.select({'standard_name': 'air', 'units': 'hPa'})``.

          *Example:*          
            ``f.select({'cell_methods': cf.CellMethods('time: mean
            (interval 1 hour)')})`` would select a field with cell
            methods of "area: mean time: mean (interval 60 minutes)".

        If *exact* is True then:

          * A string value is not treated as a regular expression.

          * Units and calendar values in a *select* dictionary are
            evaluated for exact equality rather than equivalence
            (e.g. "metre" is equal to "m", but not to "km").

          * A cell methods value in a *select* dictionary is evaluated
            for exact equality to the field's cell methods.
          
        ..

          *Example:*          
            To select a field with a standard name of exactly
            "air_pressure" and units of exactly hectopascals:
            ``f.select({'standard_name': 'air_pressure', 'units':
            'hPa'}, exact=True)``.

          *Example:*          
            To select a field with a cell methods of exactly "time:
            mean (interval 1 hour)": ``f.select({'cell_methods':
            cf.CellMethods('time: mean (interval 1 hour)')``.

        Note that `cf.Query` objects provide a mechanism for
        overriding the *exact* parameter for individual values.

          *Example:*
            ``f.select({'standard_name': cf.eq('air', exact=False),
            'units': 'hPa'}, exact=True)`` will select a field with a
            standard name which begins "air" but has units of exactly
            hectopascals (see `cf.eq`).
    
          *Example:*
            ``f.select({'standard_name': cf.eq('air_pressure'),
            'units': 'hPa'})`` will select a field with a standard name
            of exactly "air_pressure" but with units which equivalent
            to hectopascals (see `cf.eq`).

    match_and: `bool`, optional
        By default *match_and* is True and the field matches if it
        satisfies the conditions specified by each test parameter
        (*select*, *items*, *rank* and *ndim*).

        If *match_and* is False then the field will match if it
        satisfies at least one test parameter's condition.

          *Example:*
            To select a field with a standard name of "air_temperature"
            **and** 3 data array axes: ``f.select('air_temperature',
            ndim=3)``. To select a field with a standard name of
            "air_temperature" **or** 3 data array axes:
            ``f.select('air_temperature", ndim=3, match_and=False)``.
    
    inverse: `bool`, optional
        If True then return the field matches if it does **not**
        satisfy the given conditions.

          *Example:*
          
            >>> len(f.select('air', ndim=4, inverse=True)) == len(f) - len(f.select('air', ndim=4))
            True

:Returns:

    out: `cf.Field` or `cf.FieldList`
[+1]        If the field matches the given conditions then it is returned.
[+1]        Otherwise an empty field list is returned.
[+N]        If a single field matches the given conditions then it is
[+N]        returned, otherwise a {+variable} of the matching fields is
[+N]        returned.

:Examples:

Field identity starts with "air":

>>> f.select('air')

Field identity ends contains the string "temperature":

>>> f.select('.*temperature')

Field identity is exactly "air_temperature":

>>> f.select('^air_temperature$')
>>> f.select('air_temperature', exact=True)

Field has units of temperature:

>>> f.select({'units': 'K'}):

Field has units of exactly Kelvin:

>>> f.select({'units': 'K'}, exact=True)

Field identity which starts with "air" and has units of temperature:

>>> f.select({None: 'air', 'units': 'K'})

Field identity starts with "air" and/or has units of temperature:

>>> f.select(['air', {'units': 'K'}])

Field standard name starts with "air" and/or has units of exactly Kelvin:

>>> f.select([{'standard_name': cf.eq('air', exact=False), {'units': 'K'}],
...          exact=True)

Field has height coordinate values greater than 63km:

>>> f.select(items={'height': cf.gt(63, 'km')})

Field has a height coordinate object with some values greater than
63km and a north polar point on its horizontal grid:

>>> f.select(items={'height': cf.gt(63, 'km'),
...                 'latitude': cf.eq(90, 'degrees')})

Field has some longitude cell sizes of 3.75:

>>> f.select(items={'longitude': cf.cellsize(3.75)})

Field latitude cell sizes within a tropical region are all no greater
than 1 degree:

>>> f.select(items={'latitude': (cf.wi(-30, 30, 'degrees') &
...                              cf.cellsize(cf.le(1, 'degrees')))})

Field contains monthly mean air pressure data and all vertical levels
within the bottom 100 metres of the atmosphere have a thickness of 20
metres or less:

>>> f.select({None: '^air_pressure$', 'cell_methods': cf.CellMethods('time: mean')},
...          items={'height': cf.le(100, 'm') & cf.cellsize(cf.le(20, 'm')),
...                 'time': cf.cellsize(cf.wi(28, 31, 'days'))})

        '''
        kwargs2 = self._parameters(locals())

        # List functionality
        if self._list:
            fl = [f for f in self if f.match(**kwargs2)]
            if len(fl) == 1:
                return fl[0]
            else:
                return type(self)(fl)

        if self.match(**kwargs2):
            return self
        else:
            return FieldList()
    #--- End: def

    def set_equals(self, other, rtol=None, atol=None, ignore_fill_value=False, 
                   traceback=False, ignore=('Conventions',)):
        '''
        '''
        return self.equals(other, rtol=rtol, atol=atol, 
                           ignore_fill_value=ignore_fill_value,
                           traceback=traceback, ignore=ignore,
                           _set=True)
    #---End: def

    def anchor(self, axes, value, i=False, dry_run=False, **kwargs):
        '''

{+Fef,}Roll a cyclic axis so that the given value lies in the first
coordinate cell.

{+Fef,}A unique axis is selected with the *axes* and *kwargs* parameters.

.. versionadded:: 1.0

[+1].. seealso:: `axis`, `cyclic`, `iscyclic`, `period`, `roll`
[+N].. seealso:: `cf.Field.axis`, `cf.Field.cyclic`, `cf.Field.iscyclic`,
[+N]             `cf.Field.period`, `roll`

:Examples 1:

Anchor the cyclic X axis to a value of 180:

>>> g = f.anchor('X', 180)

:Parameters:

    {+axes, kwargs}

    value: data-like object
        Anchor the dimension coordinate values for the selected cyclic
        axis to the *value*. If *value* has units then they must be
        compatible with those of the dimension coordinates, otherwise
        it is assumed to have the same units as the dimension
        coordinates. The coordinate values are transformed so that
        *value* is "equal to or just before" the new first coordinate
        value. More specifically:
        
          * Increasing dimension coordinates with positive period, P,
            are transformed so that *value* lies in the half-open
            range (L-P, F], where F and L are the transformed first
            and last coordinate values, respectively.

          * Decreasing dimension coordinates with positive period, P,
            are transformed so that *value* lies in the half-open
            range (L+P, F], where F and L are the transformed first
            AND last coordinate values, respectively.

        ..

            *Example:*
              If the original dimension coordinates are ``0, 5, ...,
              355`` (evenly spaced) and the period is ``360`` then
              ``value=0`` implies transformed coordinates of ``0, 5,
              ..., 355``; ``value=-12`` implies transformed coordinates
              of ``-10, -5, ..., 345``; ``value=380`` implies
              transformed coordinates of ``380, 385, ..., 715``.

            *Example:*
              If the original dimension coordinates are ``355, 350,
              ..., 0`` (evenly spaced) and the period is ``360`` then
              ``value=355`` implies transformed coordinates of ``355,
              350, ..., 0``; ``value=0`` implies transformed
              coordinates of ``0, -5, ..., -355``; ``value=392``
              implies transformed coordinates of ``390, 385, ...,
              30``.

        {+data-like}

    {+i}

    dry_run: `bool`, optional
        Return a dictionary of parameters which describe the anchoring
        process. The field is not changed, even if *i* is True.

:Returns:

[+1]    out: `cf.{+Variable}` or `dict`
[+N]    out: `cf.{+Variable}`

:Examples 2:

>>> f[+0].iscyclic('X')
True
>>> f[+0].dim('X').data
<CF Data: [0, ..., 315] degrees_east>
>>> print f[+0].dim('X').array
[  0  45  90 135 180 225 270 315]
>>> g = f.anchor('X', 230)
>>> print g[+0].dim('X').array
[270 315   0  45  90 135 180 225]
>>> g = f.anchor('X', cf.Data(590, 'degreesE'))
>>> print g[+0].dim('X').array
[630 675 360 405 450 495 540 585]
>>> g = f.anchor('X', cf.Data(-490, 'degreesE'))
>>> print g[+0].dim('X').array
[-450 -405 -720 -675 -630 -585 -540 -495]

>>> f[+0].iscyclic('X')
True
>>> f[+0].dim('X').data
<CF Data: [0.0, ..., 357.1875] degrees_east>
>>> f.anchor('X', 10000)[+0].dim('X').data
<CF Data: [10001.25, ..., 10358.4375] degrees_east>
>>> d = f[+0].anchor('X', 10000, dry_run=True)
>>> d
{'axis': 'dim2',
 'nperiod': <CF Data: [10080.0] 0.0174532925199433 rad>,
 'roll': 28}
>>> (f.roll(d['axis'], d['roll'])[+0].dim(d['axis']) + d['nperiod']).data
<CF Data: [10001.25, ..., 10358.4375] degrees_east>

        '''
        # List functionality
        if self._list:
            kwarsg2 = self._parameters(locals())
            if kwargs2['dry_run']:
                raise ValueError(
"Can't do a dry run on a {}".format(self.__class__.__name__))
            return self._list_method('anchor', kwargs2)

        axis = self.domain.axis(axes, **kwargs)
        if axis is None:
            raise ValueError(
"Can't anchor: Bad axis specification")

        if i or dry_run:
            f = self
        else:
            f = self.copy()
        
        domain = f.domain

        dim = domain.item(axis)
        if dim is None:
            raise ValueError(
"Can't shift non-cyclic {!r} axis".format(f.axis_name(axis)))
        
        period = dim.period()
        if period is None:
            raise ValueError(
"Cyclic {!r} axis has no period".format(dim.name()))

        value = Data.asdata(value)
        if not value.Units:
            value = value.override_units(dim.Units)
        elif not value.Units.equivalent(dim.Units):
            raise ValueError(
"Anchor value has incompatible units: {!r}".format(value.Units))

        axis_size = domain.axis_size(axis)
        if axis_size <= 1:
            # Don't need to roll a size one axis
            if dry_run:
                return {'axis': axis, 'roll': 0, 'nperiod': 0}
            else:
                return f
        
        c = dim.data

        if dim.increasing:
            # Adjust value so it's in the range [c[0], c[0]+period) 
            n = ((c[0] - value) / period).ceil(i=True)
            value1 = value + n * period

            shift = axis_size - numpy_argmax(c - value1 >= 0)
            if not dry_run:
                f.roll(axis, shift, i=True)     

            dim = domain.item(axis)
            n = ((value - dim.data[0]) / period).ceil(i=True)
        else:
            # Adjust value so it's in the range (c[0]-period, c[0]]
            n = ((c[0] - value) / period).floor(i=True)
            value1 = value + n * period

            shift = axis_size - numpy_argmax(value1 - c >= 0)
            if not dry_run:
                f.roll(axis, shift, i=True)     

            dim = domain.item(axis)
            n = ((value - dim.data[0]) / period).floor(i=True)
        #--- End: if

        if dry_run:
            return  {'axis': axis, 'roll': shift, 'nperiod': n*period}

        if n:
            np = n * period
            dim += np
            if dim.hasbounds:
                bounds = dim.bounds
                bounds += np
        #--- End: if
                
        return f
    #--- End: def

    def autocyclic(self):
        '''

{+Fef,}Set axes to be cyclic if they meet conditions.

An axis is set to be cyclic if and only if the following is true:

* It has a unique, 1-d, longitude dimension coordinate object with
  bounds and the first and last bounds values differ by 360 degrees
  (or an equivalent amount in other units).
   
.. versionadded:: 1.0

[+1].. seealso:: `cyclic`, `iscyclic`, `period`
[+N].. seealso:: `cf.Field.cyclic`, `cf.Field.iscyclic`, `cf.Field.period`

:Examples 1:

>>> f.autocyclic()

:Returns:

   `None`

'''
        # List functionality
        if self._list:
            for f in self:
                f.autocyclic()
            return

        dims = self.dims('X')

        if len(dims) != 1:
            return

        key, dim = dims.popitem()

        if not self.Units.islongitude:
            if dim.getprop('standard_name', None) not in ('longitude', 'grid_longitude'):
                self.cyclic(key, iscyclic=False)
                return

        if not dim.hasbounds:
            self.cyclic(key, iscyclic=False)
            return
        
        bounds = dim.bounds
        if not bounds._hasData:
            self.cyclic(key, iscyclic=False)
            return 
        
        period = Data(360, 'degrees')
        if abs(bounds.datum(-1) - bounds.datum(0)) != period:
            self.cyclic(key, iscyclic=False)
            return

        self.cyclic(key, iscyclic=True, period=period)
    #--- End: def

    def sort(self, cmp=None, key=None, reverse=False):
        '''Sort the field, viewed as a single element field list, in place.

Note that ``f.sort(cmp, key, reverse)`` is equivalent to ``f``, thus
providing compatiblity with a single element field list.

.. versionadded:: 1.0.4

.. seealso:: `reverse`, `cf.FieldList.sort`, :py:obj:`sorted`

:Examples 1:

>>> f.sort()

:Parameters:

    cmp: `function`, optional
        Specifies a custom comparison function of two arguments
        (iterable elements) which should return a negative, zero or
        positive number depending on whether the first argument is
        considered smaller than, equal to, or larger than the second
        argument. The default value is `None`.
        
          *Example:*
            ``cmp=lambda x,y: cmp(x.lower(), y.lower())``.

    key: `function`, optional
        Specifies a function of one argument that is used to extract a
        comparison key from each list element. The default value is
        `None` (compare the elements directly).

          *Example:*
            ``key=str.lower``.

    reverse: `bool`, optional
        If set to True, then the list elements are sorted as if each
        comparison were reversed.

:Returns:

    `None`

:Examples 2:

>>> id0 = id(f)
>>> f.sort()
>>> id0 == id(f)
True
>>> g = cf.FieldList(f)
>>> id0 = id(g)
>>> g.sort()
>>> id0 == id(g)
True

        '''
        return
    #--- End: def

    def squeeze(self, axes=None, i=False, **kwargs):
        '''{+Fef,}Remove size 1 axes from the data array.

By default all size 1 axes are removed, but particular size 1 axes may
be selected for removal.

{+Fef,}The axes are selected with the *axes* parameter.

Squeezed axes are not removed from the coordinate and cell measure
objects, nor are they removed from the domain. To completely remove
axes, use the `remove_axes` method.

.. seealso:: `expand_dims`, `flip`, `remove_axes`, `transpose`,
             `unsqueeze`

:Examples 1:

Remove all size axes from the data array:

>>> g = f.squeeze()

Remove the size 1 time axis:

>>> g = f.squeeze('T')

:Parameters:

    {+axes, kwargs}

    {+i}

:Returns:

    out: `cf.{+Variable}`
        {+Fef,}The squeezed field.

:Examples 2:

        '''     
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('squeeze', kwargs2)

        domain = self.domain
        data_axes = domain.data_axes()

        if axes is None and not kwargs:
            axes_sizes = domain._axes_sizes
            axes = [axis for axis in data_axes if axes_sizes[axis] == 1]
        else:
            axes = domain.axes(axes, **kwargs).intersection(data_axes)

        iaxes = [data_axes.index(axis) for axis in axes]      

        # Squeeze the field's data array
        f = super(Field, self).squeeze(iaxes, i=i)

        f.domain._axes['data'] = [axis for axis in data_axes
                                  if axis not in axes]
        return f
    #--- End: def

    def transpose(self, axes=None, i=False, **kwargs):
        '''{+Fef,}Permute the axes of the data array.

By default the order of the axes is reversed, but any ordering may be
specified by selecting the axes of the output in the required order.

{+Fef,}The axes are selected with the *axes* parameter.

.. seealso:: `expand_dims`, `flip`, `squeeze`, `transpose`, `unsqueeze`

:Examples 1:

Reverse the order of the axes:

>>> g = f.transpose()

Specify a particular axes order:

>>> g = f.transpose(['T', 'X', 'Y'])

.. seealso:: `axes`, `expand_dims`, `flip`, `squeeze`, `unsqueeze`

:Parameters:

    {+axes, kwargs}

    {+i}

:Returns:

    out: `cf.{+Variable}`
        {+Fef,}, the transposed field.

:Examples 2:

>>> f.items()
{'dim0': <CF DimensionCoordinate: time(12) noleap>,
 'dim1': <CF DimensionCoordinate: latitude(64) degrees_north>,
 'dim2': <CF DimensionCoordinate: longitude(128) degrees_east>,
 'dim3': <CF DimensionCoordinate: height(1) m>}
>>> f.data_axes()
['dim0', 'dim1', 'dim2']
>>> f.transpose()
>>> f.transpose(['Y', 'T', 'X'])
>>> f.transpose(['latitude', 'time', 'longitude'])
>>> f.transpose([1, 0, 2])
>>> f.transpose((1, 'time', 'dim2'))

        '''     
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('transpose', kwargs2)
 
        domain = self.domain
        data_axes = domain.data_axes()

        if axes is None and not kwargs:
            axes2 = data_axes[::-1]
            iaxes = range(self.ndim-1, -1, -1)
        else:
            axes2 = domain.axes(axes, ordered=True, **kwargs)
            if set(axes2) != set(data_axes):
                raise ValueError("Can't transpose %r: Bad axis specification: %r" %
                                 (self.__class__.__name__, axes))
            
            iaxes = [data_axes.index(axis) for axis in axes2]
        #---- End: if
            
        # Transpose the field's data array
        f = super(Field, self).transpose(iaxes, i=i)

        # Reorder the list of axes in the domain
        f.domain._axes['data'] = axes2
               
        return f
    #--- End: def
            
    def field(self, items=None, role=None, axes=None, axes_all=None,
              axes_subset=None, axes_superset=None, exact=False,
              inverse=False, match_and=True, ndim=None, bounds=False):
        '''{+Fef,}Create an independent field from a domain item.

An item is either a dimension coordinate, an auxiliary coordinate or a
cell measure object of the domain.

{+item_selection}

If a unique item can not be found then no field is created and `None`
is returned.

A field may also be created from coordinate bounds (see the *bounds*
parameter).

.. versionadded:: 1.1

.. seealso:: `cf.read`, `item`

:Examples 1:

:Parameters:

    {+items}

    {+role}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}
       
    {+inverse}

    bounds: `bool`, optional
        If true then create a field from a coordinate object's bounds.

:Returns:

    out: `cf.{+Variable}`
        {+Fef,}The field based on the selected domain item.
        
:Examples 2:

::

   >>> print f 
   eastward_wind field summary
   ---------------------------
   Data           : eastward_wind(time(3), grid_latitude(110), grid_longitude(106)) m s-1
   Cell methods   : time: mean
   Axes           : time(3) = [1979-05-01 12:00:00, ..., 1979-05-03 12:00:00] gregorian
                  : grid_longitude(106) = [-20.54, ..., 25.66] degrees
                  : grid_latitude(110) = [23.32, ..., -24.64] degrees
   Aux coords     : latitude(grid_latitude(110), grid_longitude(106)) = [[67.12, ..., 22.89]] degrees_north
                  : longitude(grid_latitude(110), grid_longitude(106)) = [[-45.98, ..., 35.29]] degrees_east
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>
   
   >>> print f.field('X')
   grid_longitude field summary
   ----------------------------
   Data           : grid_longitude(grid_longitude(106)) degrees
   Axes           : grid_longitude(106) = [-20.54, ..., 25.66] degrees
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>
   
   >>> print f.field('X', bounds=True)
   grid_longitude field summary
   ----------------------------
   Data           : grid_longitude(grid_longitude(106), domain%dim1(2)) degrees
   Axes           : domain%dim1(2)
                  : grid_longitude(106) = [-20.54, ..., 25.66] degrees
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>
   
   >>> print f.field('lat')
   latitude field summary
   ----------------------
   Data           : latitude(grid_latitude(110), grid_longitude(106)) degrees_north
   Axes           : grid_longitude(106) = [-20.54, ..., 25.66] degrees
                  : grid_latitude(110) = [23.32, ..., -24.64] degrees
   Aux coords     : latitude(grid_latitude(110), grid_longitude(106)) = [[67.12, ..., 22.89]] degrees_north
                  : longitude(grid_latitude(110), grid_longitude(106)) = [[-45.98, ..., 35.29]] degrees_east
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>

To multiply the field by the cosine of its latitudes:

>>> latitude = f.field({'units': 'radian', None: 'Y'})
>>> latitude
<CF Field: grid_latitude(grid_latitude(110)) degrees>
>>> g = f * latitude.cos()

        '''
        kwargs2 = self._parameters(locals())

        # List functionality
        if self._list:
            return self._list_method('field', kwargs2)

        del kwargs2['bounds']
 
        items = self.items(**kwargs2)
        if not items:
            return

        key, item = items.popitem()

        if items:
            return

        domain = self.domain.copy()

        # Remove domain items which span any axis not spanned by the
        # item
        axes = self.axes(key, ordered=True)
        unused_axes = self.axes().difference(axes)
        for key in self.items(axes=unused_axes):
            domain.remove_item(key)

        # Remove coordinate references which do not span any of the
        # item's axes
        for key in self.refs():
            if not self.domain.ref_axes(key).intersection(axes):
                domain.remove_item(key)

        # Remove the unused axes
        domain._axes.pop('data', None)
        domain.remove_axes(unused_axes)

        if bounds and item.hasbounds:
            item = item.bounds
            axes.append(domain.insert_axis(item.shape[-1]))

        # Create the field
        f = type(self)(properties=item.properties,
                       domain=domain,
                       axes=axes,
                       data=getattr(item, 'Data', None),
                       copy=True)
        
        # Set the field's ncvar attribute
        ncvar = getattr(item, 'ncvar', None)
        if ncvar is not None:
            f.ncvar = ncvar

        return f
    #--- End: def

    def flip(self, axes=None, i=False, **kwargs):
        '''

{+Fef,}Flip (reverse the direction of) axes of the field.

.. seealso:: `axes`, `expand_dims`, `squeeze`, `transpose`,
             `unsqueeze`
        
:Examples:

>>> f.flip()
>>> f.flip('time')
>>> f.flip(1)
>>> f.flip('dim2')
>>> f.flip(['time', 1, 'dim2'])

:Parameters:

    {+axes, kwargs}

    {+i}
 
:Returns:

    out: `cf.{+Variable}`
        {+Fef,}The flipped field.

'''
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('flip', kwargs2)

        domain  = self.domain

        if axes is None and not kwargs:
            # Flip all the axes
            axes = domain.axes()
            iaxes = range(self.ndim)
        else:
            axes = domain.axes(axes, **kwargs)

            data_axes = domain.data_axes()
            iaxes = [data_axes.index(axis) for axis in
                     axes.intersection(data_axes)]
        #--- End: if

        # Flip the requested axes in the field's data array
        f = super(Field, self).flip(iaxes, i=i)

        # Flip any coordinate and cell measures which span the flipped
        # axes
        domain = f.domain
        domain_axes = domain._axes
        for key, item in domain.items(role=('d', 'a', 'm')).iteritems():
            item_axes = domain_axes[key]
            item_flip_axes = axes.intersection(item_axes)
            if item_flip_axes:
                iaxes = [item_axes.index(axis) for axis in item_flip_axes]
                item.flip(iaxes, i=True)
        #--- End: for

        return f
    #--- End: def

    def remove_data(self):
        '''

Remove and return the data array.

:Returns: 

    out: `cf.Data` or `None`
        The removed data array, or `None` if there isn't one.

:Examples:

>>> f._hasData
True
>>> f.data
<CF Data: [0, ..., 9] m>
>>> f.remove_data()
<CF Data: [0, ..., 9] m>
>>> f._hasData
False
>>> print f.remove_data()
None

'''
        self.domain._axes.pop('data', None)

        return super(Field, self).remove_data()
    #--- End: def

    def select(self, select=None, items=None, rank=None, ndim=None,
               exact=False, match_and=True, inverse=False):
        '''{+Fef,}Return the field if it satisfies the given conditions.

Different types of conditions may be set with the parameters:
         
===========  =========================================================
Parameter    What gets tested
===========  =========================================================
*select*     Field properties and attributes
             
*items*      Field domain items
         
*rank*       The number of field domain axes

*ndim*       The number of field data array axes
===========  =========================================================

By default, when multiple criteria are given the field matches if it
satisfies the conditions given by each one.

[+1]If the field does not satisfy the conditions then an empty
[+1]`cf.FieldList` object is returned.
[+N]If no fields satisfy the conditions then an empty `cf.FieldList`
[+N]object is returned.

[+1]Note that ``f.select(**kwargs)`` is equivalent to ``f if
[+1]f.match(**kwargs) else cf.FieldList()``.
[+N]Note that ``f.select(**kwargs)`` is equivalent to ``FieldList(g for g
[+N]in f if g.match(**kwargs))``

.. seealso:: `items`, `match`

**Quick start examples**

There is great flexibility in the types of test which can be
specified, and as a result the documentation is very detailed in
places. These preliminary, simple examples show that the usage need
not always be complicated and may help with understanding the keyword
descriptions.

1. Select fields which contain air temperature data, as given
   determined by the `identity` method:

   >>> f.select('air_temperature')

2. Select fields which contain air temperature data, as given determined
   by the `identity` method, or have a long name which contains the
   string "temp":

   >>> f.select(['air_temperature', {'long_name': cf.eq('.*temp.*', regex=true)}])

3. Select fields which have at least one longitude grid cell point on
   the Greenwich meridian:

   >>> f.select(items={'longitude': 0})

4. Select fields which have at least one latitude grid cell of less
   than 1 degree in size:

   >>> f.select(items={'latitude': cf.cellsize(cf.lt(1, 'degree'))})

5. Select fields which have exactly 4 domain axes:

   >>> f.select(rank=4)

6. Examples 1 to 4 may be combined to select fields which have exactly
   4 domain axes, contain air temperature data, has at least one
   longitude grid cell point on the Greenwich meridian and have at
   least one latitude grid cells with a size of less than 1 degree:

   >>> f.select('air_temperature',
   ...          items={'longitude': 0,
   ...                 'latitude': cf.cellsize(cf.lt(1, 'degree'))},
   ...          rank=4)

7. Select fields which contain at least one Gregorian calendar monthly
   mean data array value:

   >>> f.select({'cell_methods': cf.CellMethods('time: mean')},
   ...          items={'time': cf.cellsize(cf.wi(28, 31, 'days'))})

Further examples are given within and after the description of the
arguments.


:Parameters:

    select: optional
        Set conditions on the field's CF property and attribute
        values. *select* may be one, or a sequence of:

          * `None` or an empty dictionary. Always matches the
            field. This is the default.

     ..

          * A string which identifies string-valued metadata of the
            field and a value to compare it against. The value may
            take one of the following forms:

              ==============  ======================================
              *select*        Interpretation
              ==============  ======================================
              Contains ``:``  Selects on the CF property specified
                              before the first ``:``
                                
              Contains ``%``  Selects on the attribute specified
                              before the first ``%``              
              
              Anything else   Selects on identity as returned by the
                              `identity` method
              ==============  ======================================

            By default the part of the string to be compared with the
            item is treated as a regular expression understood by the
            :py:obj:`re` module and the field matches if its
            appropriate value matches the regular expression using the
            :py:obj:`re.match` method (i.e. if zero or more characters
            at the beginning of field's value match the regular
            expression pattern). See the *exact* parameter for
            details.
            
              *Example:*
                To select a field with `identity` beginning with "lat":
                ``select='lat'``.

              *Example:*
                To select a field with long name beginning with "air":
                ``select='long_name:air'``.

              *Example:*
                To select a field with netCDF variable name of exactly
                "tas": ``select='ncvar%tas$'``.

              *Example:*
                To select a field with `identity` which ends with the
                letter "z": ``select='.*z$'``.

              *Example:*
                To select a field with long name which starts with the
                string ".*a": ``select='long_name%\.\*a'``. 

        ..

          * A `cf.Query` object to be compared with field's identity,
            as returned by its `identity` method.

              *Example:*
                To select a field with `identity` of exactly
                "air_temperature" you could set
                ``select=cf.eq('air_temperature')`` (see `cf.eq`).

              *Example:*
                To select a field with `identity` ending with
                "temperature" you could set
                ``select=cf.eq('.*temperature$', exact=False)`` (see
                `cf.eq`).

     ..

          * A dictionary which identifies properties of the field with
            corresponding tests on their values. The field matches if
            **all** of the tests in the dictionary are passed.

            In general, each dictionary key is a CF property name with
            a corresponding value to be compared against the field's
            CF property value. 

            If the dictionary value is a string then by default it is
            treated as a regular expression understood by the
            :py:obj:`re` module and the field matches if its
            appropriate value matches the regular expression using the
            :py:obj:`re.match` method (i.e. if zero or more characters
            at the beginning of field's value match the regular
            expression pattern). See the *exact* parameter for
            details.
            
              *Example:*
                To select a field with standard name of exactly
                "air_temperature" and long name beginning with the
                letter "a": ``select={'standard_name':
                cf.eq('air_temperature'), 'long_name': 'a'}`` (see
                `cf.eq`).

            Some key/value pairs have a special interpretation:

              ==================  ====================================
              Special key         Value
              ==================  ====================================
              ``'units'``         The value must be a string and by
                                  default is evaluated for
                                  equivalence, rather than equality,
                                  with the field's `units` property,
                                  for example a value of ``'Pa'``
                                  will match units of Pascals or
                                  hectopascals, etc. See the *exact*
                                  parameter.
                            
              ``'calendar'``      The value must be a string and by
                                  default is evaluated for
                                  equivalence, rather than equality,
                                  with the field's `calendar`
                                  property, for example a value of
                                  ``'noleap'`` will match a calendar
                                  of noleap or 365_day. See the
                                  *exact* parameter.
                              
              ``'cell_methods'``  The value must be a `cf.CellMethods`
                                  object containing *N* cell methods
                                  and by default is evaluated for
                                  equivalence with the last *N* cell
                                  methods contained within the field's
                                  `cell_methods` property. See the
                                  *exact* parameter.

              `None`              The value is interpreted as for a
                                  string value of the *select*
                                  parameter. For example,
                                  ``select={None: 'air'}`` is
                                  equivalent to ``select='air'`` and
                                  ``select={None: 'ncvar%pressure'}``
                                  is equivalent to
                                  ``select='ncvar%pressure'``.
              ==================  ====================================
            
              *Example:*
                To select a field with standard name starting with
                "air", units of temperature and a netCDF variable name
                beginning with "tas" you could set
                ``select={'standard_name': 'air', 'units': 'K', None:
                'ncvar%tas'}``.

              *Example:*
                To select a field whose last two cell methods are
                equivalent to "time: minimum area: mean":
                ``select={'cell_methods': cf.Cellmethods('time: minimum
                area: mean')``. This would select a field which has,
                for example, cell methods of "height: mean time:
                minimum area: mean".

        If *select* is a sequence of any combination of the above then
        the field matches if it matches **at least one** element of
        the sequence:

          *Example:* 

            >>> f.select('air_temperature')
            <CF Field: air_temperature(latitude(73), longitude(96) K>
            >>> f.select({'units': 'hPa'})
            []
            >>> f.select(['air_temperature', {'units': 'hPa'])
            <CF Field: air_temperature(latitude(73), longitude(96) K>
              
        If the sequence is empty then the field always matches.
 
    items: `dict`, optional
        A dictionary which identifies domain items of the field
        (dimension coordinate, auxiliary coordinate, cell measure or
        coordinate reference objects) with corresponding tests on
        their elements. The field matches if **all** of the specified
        items exist and their tests are passed.

        Each dictionary key specifies an item to test as the one that
        would be returned by this call of the field's `item` method:
        ``f.item(key, exact=exact)`` (see `cf.Field.item`).

        The corresponding value is, in general, any object for which
        the item may be compared with for equality (``==``). The test
        is passed if the result evaluates to True, or if the result is
        an array of values then the test is passed if at least one
        element evaluates to true.

        If the value is `None` then the test is always passed,
        i.e. this case tests for item existence.

          *Example:*
             To select a field which has a latitude coordinate value of
             exactly 30: ``items={'latitude': 30}``.

          *Example:*
             To select a field whose longitude axis spans the Greenwich
             meridian: ``items={'longitude': cf.contain(0)}`` (see
             `cf.contain`).

          *Example:*
             To select a field which has a time coordinate value of
             2004-06-01: ``items={'time': cf.dt('2004-06-01')}`` (see
             `cf.dt`).

          *Example:*
             To select a field which has a height axis: ``items={'Z':
             None}``.

          *Example:*
             To select a field which has a time axis and depth
             coordinates greater then 1000 metres: ``items={'T': None,
             'depth': cf.gt(1000, 'm')}`` (see `cf.gt`).

          *Example:*
            To select a field with time coordinates after than 1989 and
            cell sizes of between 28 and 31 days: ``items={'time':
            cf.dtge(1990) & cf.cellsize(cf.wi(28, 31, 'days'))}`` (see
            `cf.dtge`, `cf.cellsize` and `cf.wi`).

    rank: optional
        Specify a condition on the number of axes in the field's
        domain. The field matches if its number of domain axes equals
        *rank*. A range of values may be selected if *rank* is a
        `cf.Query` object. Not to be confused with the *ndim*
        parameter (the number of data array axes may be fewer than the
        number of domain axes).

          *Example:*
            ``rank=2`` selects a field with exactly two domain axes
            and ``rank=cf.wi(3, 4)`` selects a field with three or
            four domain axes (see `cf.wi`).

    ndim: optional
        Specify a condition on the number of axes in the field's data
        array. The field matches if its number of data array axes
        equals *ndim*. A range of values may be selected if *ndim* is
        a `cf.Query` object. Not to be confused with the *rank*
        parameter (the number of domain axes may be greater than the
        number of data array axes).

          *Example:*
            ``ndim=2`` selects a field with exactly two data array
            axes and ``ndim=cf.le(2)`` selects a field with fewer than
            three data array axes (see `cf.le`).

    exact: `bool`, optional
        The *exact* parameter applies to the interpretation of string
        values of the *select* parameter and of keys of the *items*
        parameter. By default *exact* is False, which means that:

          * A string value is treated as a regular expression
            understood by the :py:obj:`re` module. 

          * Units and calendar values in a *select* dictionary are
            evaluated for equivalence rather then equality
            (e.g. "metre" is equivalent to "m" and to "km").

          * A cell methods value containing *N* cell methods in a
            *select* dictionary is evaluated for equivalence with the
            last *N* cell methods contained within the field's
            `cell_methods` property.

        ..

          *Example:*
            To select a field with a standard name which begins with
            "air" and any units of pressure:
            ``f.select({'standard_name': 'air', 'units': 'hPa'})``.

          *Example:*          
            ``f.select({'cell_methods': cf.CellMethods('time: mean
            (interval 1 hour)')})`` would select a field with cell
            methods of "area: mean time: mean (interval 60 minutes)".

        If *exact* is True then:

          * A string value is not treated as a regular expression.

          * Units and calendar values in a *select* dictionary are
            evaluated for exact equality rather than equivalence
            (e.g. "metre" is equal to "m", but not to "km").

          * A cell methods value in a *select* dictionary is evaluated
            for exact equality to the field's cell methods.
          
        ..

          *Example:*          
            To select a field with a standard name of exactly
            "air_pressure" and units of exactly hectopascals:
            ``f.select({'standard_name': 'air_pressure', 'units':
            'hPa'}, exact=True)``.

          *Example:*          
            To select a field with a cell methods of exactly "time:
            mean (interval 1 hour)": ``f.select({'cell_methods':
            cf.CellMethods('time: mean (interval 1 hour)')``.

        Note that `cf.Query` objects provide a mechanism for
        overriding the *exact* parameter for individual values.

          *Example:*
            ``f.select({'standard_name': cf.eq('air', exact=False),
            'units': 'hPa'}, exact=True)`` will select a field with a
            standard name which begins "air" but has units of exactly
            hectopascals (see `cf.eq`).
    
          *Example:*
            ``f.select({'standard_name': cf.eq('air_pressure'),
            'units': 'hPa'})`` will select a field with a standard name
            of exactly "air_pressure" but with units which equivalent
            to hectopascals (see `cf.eq`).

    match_and: `bool`, optional
        By default *match_and* is True and the field matches if it
        satisfies the conditions specified by each test parameter
        (*select*, *items*, *rank* and *ndim*).

        If *match_and* is False then the field will match if it
        satisfies at least one test parameter's condition.

          *Example:*
            To select a field with a standard name of "air_temperature"
            **and** 3 data array axes: ``f.select('air_temperature',
            ndim=3)``. To select a field with a standard name of
            "air_temperature" **or** 3 data array axes:
            ``f.select('air_temperature", ndim=3, match_and=False)``.
    
    inverse: `bool`, optional
        If True then return the field matches if it does **not**
        satisfy the given conditions.

          *Example:*
          
            >>> len(f.select('air', ndim=4, inverse=True)) == len(f) - len(f.select('air', ndim=4))
            True

:Returns:

    out: `cf.Field` or `cf.FieldList`
[+1]        If the field matches the given conditions then it is returned.
[+1]        Otherwise an empty field list is returned.
[+N]        If a single field matches the given conditions then it is
[+N]        returned, otherwise a {+variable} of the matching fields is
[+N]        returned.

:Examples:

Field identity starts with "air":

>>> f.select('air')

Field identity ends contains the string "temperature":

>>> f.select('.*temperature')

Field identity is exactly "air_temperature":

>>> f.select('^air_temperature$')
>>> f.select('air_temperature', exact=True)

Field has units of temperature:

>>> f.select({'units': 'K'}):

Field has units of exactly Kelvin:

>>> f.select({'units': 'K'}, exact=True)

Field identity which starts with "air" and has units of temperature:

>>> f.select({None: 'air', 'units': 'K'})

Field identity starts with "air" and/or has units of temperature:

>>> f.select(['air', {'units': 'K'}])

Field standard name starts with "air" and/or has units of exactly Kelvin:

>>> f.select([{'standard_name': cf.eq('air', exact=False), {'units': 'K'}],
...          exact=True)

Field has height coordinate values greater than 63km:

>>> f.select(items={'height': cf.gt(63, 'km')})

Field has a height coordinate object with some values greater than
63km and a north polar point on its horizontal grid:

>>> f.select(items={'height': cf.gt(63, 'km'),
...                 'latitude': cf.eq(90, 'degrees')})

Field has some longitude cell sizes of 3.75:

>>> f.select(items={'longitude': cf.cellsize(3.75)})

Field latitude cell sizes within a tropical region are all no greater
than 1 degree:

>>> f.select(items={'latitude': (cf.wi(-30, 30, 'degrees') &
...                              cf.cellsize(cf.le(1, 'degrees')))})

Field contains monthly mean air pressure data and all vertical levels
within the bottom 100 metres of the atmosphere have a thickness of 20
metres or less:

>>> f.select({None: '^air_pressure$', 'cell_methods': cf.CellMethods('time: mean')},
...          items={'height': cf.le(100, 'm') & cf.cellsize(cf.le(20, 'm')),
...                 'time': cf.cellsize(cf.wi(28, 31, 'days'))})

        '''
        kwargs2 = self._parameters(locals())

        # List functionality
        if self._list:
            fl = [f for f in self if f.match(**kwargs2)]
            if len(fl) == 1:
                return fl[0]
            else:
                return type(self)(fl)

        if self.match(**kwargs2):
            return self
        else:
            return FieldList()
    #--- End: def

    def set_equals(self, other, rtol=None, atol=None, ignore_fill_value=False, 
                   traceback=False, ignore=('Conventions',)):
        '''
        '''
        return self.equals(other, rtol=rtol, atol=atol, 
                           ignore_fill_value=ignore_fill_value,
                           traceback=traceback, ignore=ignore,
                           _set=True)
    #---End: def

    def anchor(self, axes, value, i=False, dry_run=False, **kwargs):
        '''

{+Fef,}Roll a cyclic axis so that the given value lies in the first
coordinate cell.

{+Fef,}A unique axis is selected with the *axes* and *kwargs* parameters.

.. versionadded:: 1.0

[+1].. seealso:: `axis`, `cyclic`, `iscyclic`, `period`, `roll`
[+N].. seealso:: `cf.Field.axis`, `cf.Field.cyclic`, `cf.Field.iscyclic`,
[+N]             `cf.Field.period`, `roll`

:Examples 1:

Anchor the cyclic X axis to a value of 180:

>>> g = f.anchor('X', 180)

:Parameters:

    {+axes, kwargs}

    value: data-like object
        Anchor the dimension coordinate values for the selected cyclic
        axis to the *value*. If *value* has units then they must be
        compatible with those of the dimension coordinates, otherwise
        it is assumed to have the same units as the dimension
        coordinates. The coordinate values are transformed so that
        *value* is "equal to or just before" the new first coordinate
        value. More specifically:
        
          * Increasing dimension coordinates with positive period, P,
            are transformed so that *value* lies in the half-open
            range (L-P, F], where F and L are the transformed first
            and last coordinate values, respectively.

          * Decreasing dimension coordinates with positive period, P,
            are transformed so that *value* lies in the half-open
            range (L+P, F], where F and L are the transformed first
            AND last coordinate values, respectively.

        ..

            *Example:*
              If the original dimension coordinates are ``0, 5, ...,
              355`` (evenly spaced) and the period is ``360`` then
              ``value=0`` implies transformed coordinates of ``0, 5,
              ..., 355``; ``value=-12`` implies transformed coordinates
              of ``-10, -5, ..., 345``; ``value=380`` implies
              transformed coordinates of ``380, 385, ..., 715``.

            *Example:*
              If the original dimension coordinates are ``355, 350,
              ..., 0`` (evenly spaced) and the period is ``360`` then
              ``value=355`` implies transformed coordinates of ``355,
              350, ..., 0``; ``value=0`` implies transformed
              coordinates of ``0, -5, ..., -355``; ``value=392``
              implies transformed coordinates of ``390, 385, ...,
              30``.

        {+data-like}

    {+i}

    dry_run: `bool`, optional
        Return a dictionary of parameters which describe the anchoring
        process. The field is not changed, even if *i* is True.

:Returns:

[+1]    out: `cf.{+Variable}` or `dict`
[+N]    out: `cf.{+Variable}`

:Examples 2:

>>> f[+0].iscyclic('X')
True
>>> f[+0].dim('X').data
<CF Data: [0, ..., 315] degrees_east>
>>> print f[+0].dim('X').array
[  0  45  90 135 180 225 270 315]
>>> g = f.anchor('X', 230)
>>> print g[+0].dim('X').array
[270 315   0  45  90 135 180 225]
>>> g = f.anchor('X', cf.Data(590, 'degreesE'))
>>> print g[+0].dim('X').array
[630 675 360 405 450 495 540 585]
>>> g = f.anchor('X', cf.Data(-490, 'degreesE'))
>>> print g[+0].dim('X').array
[-450 -405 -720 -675 -630 -585 -540 -495]

>>> f[+0].iscyclic('X')
True
>>> f[+0].dim('X').data
<CF Data: [0.0, ..., 357.1875] degrees_east>
>>> f.anchor('X', 10000)[+0].dim('X').data
<CF Data: [10001.25, ..., 10358.4375] degrees_east>
>>> d = f[+0].anchor('X', 10000, dry_run=True)
>>> d
{'axis': 'dim2',
 'nperiod': <CF Data: [10080.0] 0.0174532925199433 rad>,
 'roll': 28}
>>> (f.roll(d['axis'], d['roll'])[+0].dim(d['axis']) + d['nperiod']).data
<CF Data: [10001.25, ..., 10358.4375] degrees_east>

        '''
        # List functionality
        if self._list:
            kwarsg2 = self._parameters(locals())
            if kwargs2['dry_run']:
                raise ValueError(
"Can't do a dry run on a {}".format(self.__class__.__name__))
            return self._list_method('anchor', kwargs2)

        axis = self.domain.axis(axes, **kwargs)
        if axis is None:
            raise ValueError(
"Can't anchor: Bad axis specification")

        if i or dry_run:
            f = self
        else:
            f = self.copy()
        
        domain = f.domain

        dim = domain.item(axis)
        if dim is None:
            raise ValueError(
"Can't shift non-cyclic {!r} axis".format(f.axis_name(axis)))
        
        period = dim.period()
        if period is None:
            raise ValueError(
"Cyclic {!r} axis has no period".format(dim.name()))

        value = Data.asdata(value)
        if not value.Units:
            value = value.override_units(dim.Units)
        elif not value.Units.equivalent(dim.Units):
            raise ValueError(
"Anchor value has incompatible units: {!r}".format(value.Units))

        axis_size = domain.axis_size(axis)
        if axis_size <= 1:
            # Don't need to roll a size one axis
            if dry_run:
                return {'axis': axis, 'roll': 0, 'nperiod': 0}
            else:
                return f
        
        c = dim.data

        if dim.increasing:
            # Adjust value so it's in the range [c[0], c[0]+period) 
            n = ((c[0] - value) / period).ceil(i=True)
            value1 = value + n * period

            shift = axis_size - numpy_argmax(c - value1 >= 0)
            if not dry_run:
                f.roll(axis, shift, i=True)     

            dim = domain.item(axis)
            n = ((value - dim.data[0]) / period).ceil(i=True)
        else:
            # Adjust value so it's in the range (c[0]-period, c[0]]
            n = ((c[0] - value) / period).floor(i=True)
            value1 = value + n * period

            shift = axis_size - numpy_argmax(value1 - c >= 0)
            if not dry_run:
                f.roll(axis, shift, i=True)     

            dim = domain.item(axis)
            n = ((value - dim.data[0]) / period).floor(i=True)
        #--- End: if

        if dry_run:
            return  {'axis': axis, 'roll': shift, 'nperiod': n*period}

        if n:
            np = n * period
            dim += np
            if dim.hasbounds:
                bounds = dim.bounds
                bounds += np
        #--- End: if
                
        return f
    #--- End: def

    def autocyclic(self):
        '''

{+Fef,}Set axes to be cyclic if they meet conditions.

An axis is set to be cyclic if and only if the following is true:

* It has a unique, 1-d, longitude dimension coordinate object with
  bounds and the first and last bounds values differ by 360 degrees
  (or an equivalent amount in other units).
   
.. versionadded:: 1.0

[+1].. seealso:: `cyclic`, `iscyclic`, `period`
[+N].. seealso:: `cf.Field.cyclic`, `cf.Field.iscyclic`, `cf.Field.period`

:Examples 1:

>>> f.autocyclic()

:Returns:

   `None`

'''
        # List functionality
        if self._list:
            for f in self:
                f.autocyclic()
            return

        dims = self.dims('X')

        if len(dims) != 1:
            return

        key, dim = dims.popitem()

        if not self.Units.islongitude:
            if dim.getprop('standard_name', None) not in ('longitude', 'grid_longitude'):
                self.cyclic(key, iscyclic=False)
                return

        if not dim.hasbounds:
            self.cyclic(key, iscyclic=False)
            return
        
        bounds = dim.bounds
        if not bounds._hasData:
            self.cyclic(key, iscyclic=False)
            return 
        
        period = Data(360, 'degrees')
        if abs(bounds.datum(-1) - bounds.datum(0)) != period:
            self.cyclic(key, iscyclic=False)
            return

        self.cyclic(key, iscyclic=True, period=period)
    #--- End: def

    def sort(self, cmp=None, key=None, reverse=False):
        '''Sort the field, viewed as a single element field list, in place.

Note that ``f.sort(cmp, key, reverse)`` is equivalent to ``f``, thus
providing compatiblity with a single element field list.

.. versionadded:: 1.0.4

.. seealso:: `reverse`, `cf.FieldList.sort`, :py:obj:`sorted`

:Examples 1:

>>> f.sort()

:Parameters:

    cmp: `function`, optional
        Specifies a custom comparison function of two arguments
        (iterable elements) which should return a negative, zero or
        positive number depending on whether the first argument is
        considered smaller than, equal to, or larger than the second
        argument. The default value is `None`.
        
          *Example:*
            ``cmp=lambda x,y: cmp(x.lower(), y.lower())``.

    key: `function`, optional
        Specifies a function of one argument that is used to extract a
        comparison key from each list element. The default value is
        `None` (compare the elements directly).

          *Example:*
            ``key=str.lower``.

    reverse: `bool`, optional
        If set to True, then the list elements are sorted as if each
        comparison were reversed.

:Returns:

    `None`

:Examples 2:

>>> id0 = id(f)
>>> f.sort()
>>> id0 == id(f)
True
>>> g = cf.FieldList(f)
>>> id0 = id(g)
>>> g.sort()
>>> id0 == id(g)
True

        '''
        return
    #--- End: def

    def squeeze(self, axes=None, i=False, **kwargs):
        '''{+Fef,}Remove size 1 axes from the data array.

By default all size 1 axes are removed, but particular size 1 axes may
be selected for removal.

{+Fef,}The axes are selected with the *axes* parameter.

Squeezed axes are not removed from the coordinate and cell measure
objects, nor are they removed from the domain. To completely remove
axes, use the `remove_axes` method.

.. seealso:: `expand_dims`, `flip`, `remove_axes`, `transpose`,
             `unsqueeze`

:Examples 1:

Remove all size axes from the data array:

>>> g = f.squeeze()

Remove the size 1 time axis:

>>> g = f.squeeze('T')

:Parameters:

    {+axes, kwargs}

    {+i}

:Returns:

    out: `cf.{+Variable}`
        {+Fef,}The squeezed field.

:Examples 2:

        '''     
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('squeeze', kwargs2)

        domain = self.domain
        data_axes = domain.data_axes()

        if axes is None and not kwargs:
            axes_sizes = domain._axes_sizes
            axes = [axis for axis in data_axes if axes_sizes[axis] == 1]
        else:
            axes = domain.axes(axes, **kwargs).intersection(data_axes)

        iaxes = [data_axes.index(axis) for axis in axes]      

        # Squeeze the field's data array
        f = super(Field, self).squeeze(iaxes, i=i)

        f.domain._axes['data'] = [axis for axis in data_axes
                                  if axis not in axes]
        return f
    #--- End: def

    def transpose(self, axes=None, i=False, **kwargs):
        '''{+Fef,}Permute the axes of the data array.

By default the order of the axes is reversed, but any ordering may be
specified by selecting the axes of the output in the required order.

{+Fef,}The axes are selected with the *axes* parameter.

.. seealso:: `expand_dims`, `flip`, `squeeze`, `transpose`, `unsqueeze`

:Examples 1:

Reverse the order of the axes:

>>> g = f.transpose()

Specify a particular axes order:

>>> g = f.transpose(['T', 'X', 'Y'])

.. seealso:: `axes`, `expand_dims`, `flip`, `squeeze`, `unsqueeze`

:Parameters:

    {+axes, kwargs}

    {+i}

:Returns:

    out: `cf.{+Variable}`
        {+Fef,}, the transposed field.

:Examples 2:

>>> f.items()
{'dim0': <CF DimensionCoordinate: time(12) noleap>,
 'dim1': <CF DimensionCoordinate: latitude(64) degrees_north>,
 'dim2': <CF DimensionCoordinate: longitude(128) degrees_east>,
 'dim3': <CF DimensionCoordinate: height(1) m>}
>>> f.data_axes()
['dim0', 'dim1', 'dim2']
>>> f.transpose()
>>> f.transpose(['Y', 'T', 'X'])
>>> f.transpose(['latitude', 'time', 'longitude'])
>>> f.transpose([1, 0, 2])
>>> f.transpose((1, 'time', 'dim2'))

        '''     
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('transpose', kwargs2)
 
        domain = self.domain
        data_axes = domain.data_axes()

        if axes is None and not kwargs:
            axes2 = data_axes[::-1]
            iaxes = range(self.ndim-1, -1, -1)
        else:
            axes2 = domain.axes(axes, ordered=True, **kwargs)
            if set(axes2) != set(data_axes):
                raise ValueError("Can't transpose %r: Bad axis specification: %r" %
                                 (self.__class__.__name__, axes))
            
            iaxes = [data_axes.index(axis) for axis in axes2]
        #---- End: if
            
        # Transpose the field's data array
        f = super(Field, self).transpose(iaxes, i=i)

        # Reorder the list of axes in the domain
        f.domain._axes['data'] = axes2
               
        return f
    #--- End: def

    def unlimited(self, *xxx):
        '''Todo ...


.. versionadded:: 1.3.1
        
.. seealso:: `cf.write`

:Examples 1:

Set the time axis to be unlimited when written to a netCDF file:

>>> f.unlimited({'T': True})

:Parameters:

    xxx: `dict` or `None`, optional

        Specify the chunk sizes for axes of the field. Axes are given
        by dictionary keys, with a chunk size for those axes as the
        dictionary values. A dictionary key of ``axes`` defines the
        axes that would be returned by the field's axes method,
        i.e. by ``f.axes(axes)``. See `cf.Field.axes` for details. In
        the special case of *xxx* being `None`, then chunking is
        set to the netCDF default.

        Example:
        To set time axes to be unlimited: ``{'T': True}``.

        Example:
        To set the chunk size for the first and third data array
        axes to 100: {0: 100, 2: 100}, or equivalently {(0, 2): 100}.

        Example:
        To set the chunk size for the longitude axis to 100 and
        for the air temperature axis to 5: {'X': 100, 'air_temperature': 5}.

        Example:
        To set the chunk size for all axes to 10: {None: 10}. This
        works because f.axes(None) returns all field axes.

        Example:
        To set the chunking to the netCDF default: None.

:Returns:

    out: `dict`

:Examples 2:

        '''
        if len(xxx) > 1:
            raise ValueError("asfdds asdasdas4444444")

        org = {}
        for axis in self.axes():
            org[axis] = None            
            
        if self._unlimited:
            org.update(self._unlimited)

        if not xxx:
            return org
    
        xxx = xxx[0]

        if xxx is None:
            # Clear all settings
            self._unlimited = None
            return org

        _unlimited = {}
        for axes, value in xxx.iteritems():
            for axis in self.axes(axes):
                _unlimited[axis] = value

        if not _unlimited:        
            _unlimited = None

        self_unlimited = self._unlimited
        if self_unlimited is None:
            self._unlimited = _unlimited
        else:
            self._unlimited = self_unlimited.copy()
            self._unlimited.update(_unlimited)

        return org
    #--- End: def

    def unsqueeze(self, axes=None, i=False, **kwargs):
        '''{+Fef,}Insert size 1 axes into the data array.

By default all size 1 domain axes which are not spanned by the field's
data array are inserted, but existing size 1 axes may be selected for
insertion.

{+Fef,}The axes are selected with the *axes* parameter.

The axes are inserted into the slowest varying data array positions.

.. seealso:: `expand_dims`, `flip`, `squeeze`, `transpose`

:Examples 1:

Insert size all size 1 axes:

>>> g = f.unsqueeze()

Insert size 1 time axes:

>>> g = f.unsqueeze('T', size=1)

:Parameters:

    {+axes, kwargs}

    {+i}

:Returns:

    out: `cf.{+Variable}`
        {+Fef,}The unsqueezed field.

:Examples 2:

>>> print f
Data            : air_temperature(time, latitude, longitude)
Cell methods    : time: mean
Dimensions      : time(1) = [15] days since 1860-1-1
                : latitude(73) = [-90, ..., 90] degrees_north
                : longitude(96) = [0, ..., 356.25] degrees_east
                : height(1) = [2] m
Auxiliary coords:
>>> f.unsqueeze()
>>> print f
Data            : air_temperature(height, time, latitude, longitude)
Cell methods    : time: mean
Dimensions      : time(1) = [15] days since 1860-1-1
                : latitude(73) = [-90, ..., 90] degrees_north
                : longitude(96) = [0, ..., 356.25] degrees_east
                : height(1) = [2] m
Auxiliary coords:

        '''     
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('unsqueeze', kwargs2)
 
        domain = self.domain

        data_axes = domain.data_axes()
        axes = domain.axes(axes, size=1, **kwargs).difference(data_axes)

        if i:
            f = self
        else:
            f = self.copy()

        for axis in axes:
            f.expand_dims(0, axis, i=True)

        return f
    #--- End: def

    def aux(self, items=None, axes=None, axes_all=None,
            axes_subset=None, axes_superset=None, exact=False,
            inverse=False, match_and=True, ndim=None, key=False,
            copy=False):
        '''
{+Fef,}Return an auxiliary coordinate object, or its domain identifier.

In this documentation, an auxiliary coordinate object is referred to
as an item.

{+item_selection}

{+item_criteria}

If no unique item can be found then `None` is returned.

To find multiple items, use the `{+name}s` method.

Note that ``f.aux(inverse=False, **kwargs)`` is equivalent to
``f.item(role='a', inverse=False, **kwargs)``.
 

.. seealso:: `auxs`, `measure`, `coord`, `ref`, `dim`, `item`,
             `remove_item`

:Examples 1:

A latitude item could potentially be selected with any of:

>>> a = f.{+name}('Y')
>>> a = f.{+name}('latitude')
>>> a = f.{+name}('long_name:latitude')
>>> a = f.{+name}('aux1')
>>> a = f.{+name}(axes_all='Y')

:Parameters:

    {+items}

    {+ndim}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+match_and}

    {+exact}
       
    {+inverse}

    {+key}
        
    {+copy}

:Returns:

[+1]    out: `cf.AuxiliaryCoordinate` or `str` or `None`
[+N]    out: `list`
           {+Fef,}The unique auxiliary coordinate object or its domain
           identifier or, if there is not one, `None`.

:Examples 2:

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.item(role='a', _restrict_inverse=True, **kwargs2)
    #--- End: def

    def measure(self, items=None, axes=None, axes_all=None,
                axes_subset=None, axes_superset=None, exact=False,
                inverse=False, match_and=True, ndim=None,
                key=False, copy=False):
        '''{+Fef,}Return a cell measure object, or its domain identifier.

In this documentation, a cell measure object is referred to as an
item.

{+item_selection}

If no unique item can be found then `None` is returned.

To find multiple items, use the `{+name}s` method.

Note that ``f.measure(inverse=False, **kwargs)`` is equivalent to
``f.item(role='m', inverse=False, **kwargs)``.

.. seealso:: `aux`, `measures`, `coord`, `ref`, `dims`, `item`,
             `remove_item`

:Parameters:

    {+items}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}
       
    {+inverse}

    {+key}
        
    {+copy}

:Returns:

    out: `cf.CellMeasure` or `str` or `None`
        The unique cell measure object or its domain identifier or, if
        there is not one, `None`.
        
:Examples 2:

>>> f.measure('area')
<CF CellMeasure: area(73, 96) m 2>

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.item(role='m', _restrict_inverse=True, **kwargs2)
    #--- End: def   

    def coord(self, items=None, axes=None, axes_all=None,
              axes_subset=None, axes_superset=None, ndim=None, match_and=True, 
              exact=False,
              inverse=False, key=False, copy=False):
        '''

{+Fef,}Return a dimension or auxiliary coordinate object, or its domain identifier.

In this documentation, a dimension or auxiliary coordinate object is
referred to as an item.

{+item_selection}

If no unique item can be found then `None` is returned.

To find multiple items, use the `{+name}s` method.

Note that ``f.coord(inverse=False, **kwargs)`` is equivalent to
``f.item(role='da', inverse=False, **kwargs)``.

.. seealso:: `aux`, `coords`, `dim`, `item`, `measure`, `ref`,
             `remove_item`,

:Examples 1:

:Parameters:

    {+items}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}
       
    {+inverse}

    {+key}

    {+copy}

:Returns:

    out: `cf.DimensionCoordinate` or `cf.AuxiliaryCoordinate` or `str` or `None` 
        The unique dimension or auxiliary coordinate object or
        its domain identifier or, if there is not one, `None`.

:Examples 2:

'''
        kwargs2 = self._parameters(locals())
        return self.domain.item(role=('d', 'a'), _restrict_inverse=True,
                                **kwargs2)
    #--- End: def

    def dim(self, items=None, axes=None, axes_all=None,
            axes_subset=None, axes_superset=None, ndim=None,
            match_and=True, exact=False, inverse=False,
            key=False, copy=False):
        '''

Return a dimension coordinate object, or its domain identifier.

In this documentation, a dimension coordinate object is referred to as
an item.

{+item_selection}

If no unique item can be found then `None` is returned.

To find multiple items, use the `{+name}s` method.

Note that ``f.{+name}(inverse=False, **kwargs)`` is equivalent to
``f.item(role='d', inverse=False, **kwargs)``.

.. seealso:: `aux`, `measure`, `coord`, `ref`, `dims`, `item`,
             `remove_item`

:Examples 1:

A latitude item could potentially be selected with any of:

>>> d = f.{+name}('Y')
>>> d = f.{+name}('latitude')
>>> d = f.{+name}('long_name:latitude')
>>> d = f.{+name}('dim1')
>>> d = f.{+name}(axes_all='Y')

:Parameters:

    {+items}

    {+ndim}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+match_and}

    {+exact}
       
    {+inverse}

    {+key}

    {+copy}
        
:Returns:

[+1]    out: 
[+N]    out: list
        {+Fef,}The unique dimension coordinate object or its domain
        identifier or, if there is not one, `None`.

:Examples 2:

'''
        kwargs2 = self._parameters(locals())
        return self.domain.item(role='d', _restrict_inverse=True, **kwargs2)
    #--- End: def

#    def transform(self, *args, **kwargs):
#        raise NotImplementedError("Deprecated. Use cf.Field.ref instead.")

    def ref(self,items=None, exact=False, inverse=False, match_and=True,
            key=False, copy=False):
        '''{+Fef,}Return a coordinate reference object, or its domain identifier.

In this documentation, a coordinate reference object is referred to as
an item.

{+item_selection}

If no unique item can be found then `None` is returned.

To find multiple items, use the `{+name}s` method.

Note that ``f.ref(inverse=False, **kwargs)`` is equivalent to
``f.item(role='r', inverse=False, **kwargs)``.

.. seealso:: `aux`, `measure`, `coord`, `ref`, `dims`, `item`,
             `remove_item`

:Examples 1:

A latitude item could potentially be selected with any of:

>>> c = f.ref('rotated_latitude_longitude')
>>> c = f.ref('ref1')

:Parameters:

    {+items}

    {+ndim}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+match_and}

    {+exact}
       
    {+inverse}

    {+key}

    {+copy}
        
:Returns:

[+1]    out: 
[+N]    out: list
        {+Fef,}The unique dimension coordinate object or its domain
        identifier or, if there is not one, `None`.

:Examples 2:

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.item(role='r', _restrict_inverse=True, **kwargs2)
    #--- End: def

    def auxs(self, items=None, axes=None, axes_all=None,
             axes_subset=None, axes_superset=None, ndim=None, match_and=True, 
             exact=False, inverse=False, copy=False):
        '''Return auxiliary coordinate objects.

In this documentation, an auxiliary coordinate object is referred to
as an item.

{+item_selection}

{+item_criteria}

Note that ``f.{+name}(inverse=False, **kwargs)`` is equivalent to
``f.items(role='a', inverse=False, **kwargs)``.
 
.. seealso:: `aux`, `axes`, `measures` , `refs`, `coords`, `dims`,
             `items`, `remove_items`

:Examples 1:

To select all auxiliary coordinate objects:

>>> d = f.auxs()

:Parameters:

    {+items}

          *Example:* 

            >>> x = f.items(['aux1',
            ...             'time',
            ...             {'units': 'degreeN', 'long_name': 'foo'}])
            >>> y = {}
            >>> for items in ['aux1', 'time', {'units': 'degreeN', 'long_name': 'foo'}]:
            ...     y.update(f.items(items))
            ...
            >>> set(x) == set(y)
            True

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}

    {+inverse}

    {+copy}

:Returns:

    out: `dict`
        A dictionary whose keys are domain item identifiers with
        corresponding values of auxiliary coordinates of the
        domain. The dictionary will be empty if no items were
        selected.

:Examples:

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.items(role='a', _restrict_inverse=True, **kwargs2)
    #--- End: def

    def measures(self, items=None, axes=None, axes_all=None,
                 axes_subset=None, axes_superset=None, ndim=None, 
                 match_and=True, exact=False, inverse=False, copy=False):
        '''Return cell measure objects.

In this documentation, a cell measure object is referred to as an
item.

{+item_selection}

{+item_criteria}

Note that ``f.{+name}(inverse=False, **kwargs)`` is equivalent to
``f.items(role='m', inverse=False, **kwargs)``.
 
.. seealso:: `auxs`, `coords`, `dims`, `items`, `measure`, `refs`, 
             `remove_items`

:Examples 1:

To select all cell measure objects:

>>> d = f.measures()

:Parameters:

    {+items}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}

    {+inverse}

    {+copy}

:Returns:

    out: `dict`
        A dictionary whose keys are domain item identifiers with
        corresponding values of cell measure objects of the
        domain. The dictionary will be empty if no items were
        selected.


:Examples 2:

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.items(role='m', _restrict_inverse=True, **kwargs2)
    #--- End: def

    def coords(self, items=None, axes=None, axes_all=None,
               axes_subset=None, axes_superset=None, ndim=None,
               match_and=True, exact=False, inverse=False, copy=False):
        '''Return dimension and auxiliary coordinate objects of the domain.

.. seealso:: `auxs`, `axes`, `measures`, `coord`, `refs`, `dims`,
             `items`, `remove_items`

:Parameters:

    {+items}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}

    {+inverse}

    {+copy}

:Returns:

    out: `dict`
        A dictionary whose keys are domain item identifiers with
        corresponding values of coordinates of the domain. The
        dictionary may be empty.

:Examples:

        '''      
        kwargs2 = self._parameters(locals())
        return self.domain.items(role=('d', 'a'), _restrict_inverse=True,
                                 **kwargs2)
    #--- End: def

    def dims(self, items=None, axes=None, axes_all=None,
             axes_subset=None, axes_superset=None, ndim=None,
             match_and=True, exact=False, inverse=False, copy=False):
        '''Return dimension coordinate objects.

In this documentation, a dimension coordinate object is referred to as
an item.

{+item_selection}

{+item_criteria}

Note that ``f.{+name}(inverse=False, **kwargs)`` is equivalent to
``f.items(role='d', inverse=False, **kwargs)``.
 
.. seealso:: `auxs`, `axes`, `measures`, `refs`, `coords`, `dim`,
             `items`, `remove_items`

:Examples 1:

To select all dimension coordinate objects:

>>> d = f.dims()

:Parameters:

    {+items}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}

    {+inverse}

    {+copy}

:Returns:

    out: `dict`
        A dictionary whose keys are domain item identifiers with
        corresponding values of items of the domain. The dictionary
        may be empty.

:Examples:

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.items(role='d', _restrict_inverse=True, **kwargs2)
    #--- End: def

#    def transforms(self, items=None, key=False, **kwargs):
#        '''
#Deprecated. Use `cf.Field.refs` instead.
#'''
#        raise NotImplementedError("Deprecated. Use cf.Field.refs instead.")
#    #--- End: def

    def refs(self, items=None, exact=False, inverse=False, match_and=True, 
             copy=False):
        '''Return coordinate reference objects.

In this documentation, a coordinate reference object is referred to as
an item.

{+item_selection}

Note that ``f.{+name}(inverse=False, **kwargs)`` is equivalent to
``f.items(role='r', inverse=False, **kwargs)``.
 
.. seealso:: `auxs`, `coords`, `dims`, `items`, `measures`, `ref`, 
             `remove_items`

:Examples 1:

To select all coordinate reference objects:

>>> d = f.refs()

:Parameters:
         
    {+items}

          *Example:* 

            >>> x = f.items(['ref1', 'latitude_longitude'])
            >>> y = {}
            >>> for items in ['ref1', 'latitude_longitude']:
            ...     y.update(f.items(items))
            ...
            >>> set(x) == set(y)
            True

    {+match_and}

    {+exact}
       
    {+inverse}

    {+copy}

:Returns:
 
    out: `dict`
        A dictionary whose keys are domain item identifiers with
        corresponding values of coordinate references of the
        domain. The dictionary may be empty.

:Examples:

        '''  
        kwargs2 = self._parameters(locals())
        return self.domain.items(role='r', _restrict_inverse=True, **kwargs2)
    #--- End: def

    def item(self, items=None, role=None, axes=None, axes_all=None,
             axes_subset=None, axes_superset=None, exact=False,
             inverse=False, match_and=True, ndim=None,
             key=False, copy=False):
        '''Return an item, or its domain identifier, from the field.

An item is either a dimension coordinate, an auxiliary coordinate, a
cell measure or a coordinate reference object.

{+item_selection}
 
If no unique item can be found then `None` is returned.

To find multiple items, use the `~cf.Field.{+name}s` method.

.. seealso:: `aux`, `measure`, `coord`, `ref`, `dim`, `item_axes`,
             `items`, `remove_item`

:Examples 1:

>>> 

:Parameters:

    {+items}

    {+role}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}
       
    {+inverse}

    {+key}

    {+copy}

:Returns:

    out: 
        The unique item or its domain identifier or, if there is no
        unique item, `None`.

:Examples:

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.item(**kwargs2)
    #--- End: def

    def axis_name(self, axes=None, **kwargs):
        '''Return the canonical name for an axis.

{+axis_selection}

.. seealso:: `axis`, `axis_size`, `item`

:Parameters:

    {+axes, kwargs}

:Returns:

    out: `str`
        The canonical name for the axis.

:Examples:

>>> f.axis_name('dim0')
'time'
>>> f.axis_name('X')
'domain%dim1'
>>> f.axis_name('long_name%latitude')
'ncdim%lat'

        '''        
        kwargs2 = self._parameters(locals())
        return self.domain.axis_name(**kwargs2)
    #-- End: def

    def axis_size(self, axes=None, **kwargs):
        '''Return the size of a domain axis.

{+axis_selection}

.. seealso:: `axis`, `axis_name`, `axes_sizes`, `axis_identity`

:Parameters:

    {+axes, kwargs}

:Returns:
    
    out: `int`
        The size of the axis.

:Examples:

>>> f
<CF Field: eastward_wind(time(3), air_pressure(5), latitude(110), longitude(106)) m s-1>
>>> f.axis_size('longitude')
106
>>> f.axis_size('Z')
5

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.axis_size(**kwargs2)
    #--- End: def

    def axes_sizes(self, axes=None, size=None, key=False, **kwargs):
        '''Return the sizes of domain axes.

{+axis_selection}

:Examples 1:

>>> x = f.axes_sizes()

:Parameters:

    {+axes, kwargs}

          *Example:*

            >>> x = f.axes(['dim2', 'time', {'units': 'degree_north'}])
            >>> y = set()
            >>> for axes in ['dim2', 'time', {'units': 'degree_north'}]:
            ...     y.update(f.axes(axes))
            ...
            >>> x == y
            True
 
    {+size}
             
    key: `bool`, optional
        If True then identify each axis by its domain identifier
        rather than its name.

:Returns:
    
    out: `dict`
        The sizes of the each selected domain axis.

:Examples 2:

>>> f
<CF Field: eastward_wind(time(3), air_pressure(5), latitude(110), longitude(106)) m s-1>
>>> f.axes_sizes()
{'air_pressure': 5, 'latitude': 110, 'longitude': 106, 'time': 3}
>>> f.axes_sizes(size=3)
{'time': 3}
>>> f.axes_sizes(size=cf.lt(10), key=True)
{'dim0': 3, 'dim1': 5}
>>> f.axes_sizes('latitude')
{'latitude': 110}

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.axes_sizes(**kwargs2)
    #---End: def

    def axes(self, axes=None, size=None, ordered=False, **kwargs):
        '''Return domain axis identifiers from the field.

The output is a set of domain axis identifiers, which may be empty.

{+axis_selection}

.. seealso:: `axis`, `data_axes`, `item_axes`, `items`, `remove_axes`

:Parameters:

    {+axes, kwargs}

          *Example:*

            >>> x = f.axes(['dim2', 'time', {'units': 'degree_north'}])
            >>> y = set()
            >>> for axes in ['dim2', 'time', {'units': 'degree_north'}]:
            ...     y.update(f.axes(axes))
            ...
            >>> x == y
            True
 
    {+size}

    ordered: `bool`, optional
        Return an ordered list of axes instead of an unordered
        set. The order of the list will reflect any ordering specified
        by the *axes* and *kwargs* parameters.

          *Example:*
            If the data array axes, as returned by the field's
            `data_axes` method, are ``['dim0', 'dim1', 'dim2']``, then
            ``f.axes([2, 0, 1, 2])`` will return ``set(['dim0',
            'dim1', 'dim2'])``, but ``f.axes([2, 0, 1, 2],
            ordered=True)`` will return ``['dim2', 'dim0', 'dim1',
            'dim2']``.

:Returns:

    out: `set` or `list`
        A set of domain axis identifiers, or a list if *ordered* is
        True. The set or list may be empty.

:Examples:

All axes and their identities:

>>> f.axes()
set(['dim0', 'dim1', 'dim2', 'dim3'])
>>> dict([(axis, f.domain.axis_name(axis)) for axis in f.axes()])
{'dim0': time(12)
 'dim1': height(19)
 'dim2': latitude(73)
 'dim3': longitude(96)}

Axes which are not spanned by the data array:

>>> f.axes().difference(f.data_axes())

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.axes(**kwargs2)
    #--- End: def

    def axis(self, axes=None, size=None, **kwargs):
        '''Return a domain axis identifier from the field.

{+axis_selection}

.. seealso:: `axes`, `data_axes`, `item_axes`, `item`, `remove_axis`

:Examples 1:

>>> a = f.axis('time')

:Parameters:

    {+axes, kwargs}
 
    {+size}

:Returns:

    out: `str` or `None`
        The domain identifier of the unique axis or, if there isn't
        one, `None`.

:Examples 2:

>>> f
<CF Field: air_temperature(time(12), latitude(64), longitude(128)) K>
>>> f.data_axes()
['dim0', 'dim1', 'dim2']
>>> f.axis('time')
'dim0'
>>> f.axis('Y')
'dim1'
>>> f.axis(size=64)
'dim1'
>>> f.axis('X', size=128)
'dim2'
>>> print f.axis('foo')
None
>>> print f.axis('T', size=64)
None

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.axis(**kwargs2)
    #--- End: def

    def insert_axis(self, size, key=None, replace=True):
        '''Insert an axis into the domain in place.

.. seealso:: `insert_aux`, `insert_measure`, `insert_ref`,
             `insert_data`, `insert_dim`

:Parameters:

    size: `int`
        The size of the new axis.

    key: `str`, optional
        The domain identifier for the new axis. By default a new,
        unique identifier is generated.
  
    replace: `bool`, optional
        If False then do not replace an existing axis with the same
        identifier but a different size. By default an existing axis
        with the same identifier is changed to have the new size.

:Returns:

    out:
        The domain identifier of the new axis.


:Examples:

>>> f.insert_axis(1)
>>> f.insert_axis(90, key='dim4')
>>> f.insert_axis(23, key='dim0', replace=False)

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.insert_axis(**kwargs2)
    #--- End: def

    def insert_aux(self, item, key=None, axes=None, copy=True, replace=True):
        '''Insert an auxiliary coordinate object into the domain in place.

.. seealso:: `insert_axis`, `insert_measure`, `insert_data`,
             `insert_dim`, `insert_ref`

:Parameters:

    item: `cf.AuxiliaryCoordinate` or `cf.Coordinate` or `cf.DimensionCoordinate`
        The new auxiliary coordinate object. If it is not already a
        auxiliary coordinate object then it will be converted to one.

    key: `str`, optional
        The domain identifier for the *item*. By default a new, unique
        identifier will be generated.

    axes: sequence of `str`, optional
        The ordered list of axes for the *item*. Each axis is given by
        its domain identifier. By default the axes are assumed to be
        ``'dim0'`` up to ``'dimM-1'``, where ``M-1`` is the number of
        axes spanned by the *item*.

    copy: `bool`, optional
        If False then the *item* is not copied before insertion. By
        default it is copied.
      
    replace: `bool`, optional
        If False then do not replace an existing auxiliary coordinate
        object of domain which has the same identifier. By default an
        existing auxiliary coordinate object with the same identifier
        is replaced with *item*.
    
:Returns:

    out: `str`
        The domain identifier for the inserted *item*.

:Examples:

>>>

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.insert_aux(**kwargs2)
    #--- End: def

    def insert_measure(self, item, key=None, axes=None, copy=True, replace=True):
        '''

Insert an cell measure object into the domain in place.

.. seealso:: `insert_axis`, `insert_aux`, `insert_data`, `insert_dim`,
             `insert_ref`

:Parameters:

    item: `cf.CellMeasure`
        The new cell measure object.

    key: `str`, optional
        The domain identifier for the *item*. By default a new, unique
        identifier will be generated.

    axes: sequence of `str`, optional
        The ordered list of axes for the *item*. Each axis is given by
        its domain identifier. By default the axes are assumed to be
        ``'dim0'`` up to ``'dimM-1'``, where ``M-1`` is the number of
        axes spanned by the *item*.

    copy: `bool`, optional
        If False then the *item* is not copied before insertion. By
        default it is copied.
      
    replace: `bool`, optional
        If False then do not replace an existing cell measure object
        of domain which has the same identifier. By default an
        existing cell measure object with the same identifier is
        replaced with *item*.
    
:Returns:

    out: 
        The domain identifier for the *item*.

:Examples:

>>>

'''
        kwargs2 = self._parameters(locals())
        return self.domain.insert_measure(**kwargs2)
    #--- End: def

    def insert_dim(self, item, key=None, axis=None, copy=True, replace=True):
        '''Insert a dimension coordinate object into the domain in place.

.. seealso:: `insert_aux`, `insert_axis`, `insert_measure`,
             `insert_data`, `insert_ref`

:Parameters:

    item: `cf.DimensionCoordinate` or `cf.Coordinate` or `cf.AuxiliaryCoordinate`
        The new dimension coordinate object. If it is not already a
        dimension coordinate object then it will be converted to one.

    axis: `str`, optional
        The axis for the *item*. The axis is given by its domain
        identifier. By default the axis will be the same as the given
        by the *key* parameter.

    key: `str`, optional
        The domain identifier for the *item*. By default a new, unique
        identifier will be generated.

    copy: `bool`, optional
        If False then the *item* is not copied before insertion. By
        default it is copied.
      
    replace: `bool`, optional
        If False then do not replace an existing dimension coordinate
        object of domain which has the same identifier. By default an
        existing dimension coordinate object with the same identifier
        is replaced with *item*.
    
:Returns:

    out: `str`
        The domain identifier for the inserted *item*.

:Examples:

>>>

        '''
        kwargs2 = self._parameters(locals())
        key = self.domain.insert_dim(**kwargs2)

        self.autocyclic()

        return key
    #--- End: def

    def insert_ref(self, item, key=None, copy=True, replace=True):
        '''Insert a coordinate reference object into the domain in place.

.. seealso:: `insert_axis`, `insert_aux`, `insert_measure`,
             `insert_data`, `insert_dim`
             
:Parameters:

    item: `cf.CoordinateReference`
        The new coordinate reference object.

    key: `str`, optional
        The domain identifier for the *item*. By default a new, unique
        identifier will be generated.

    copy: `bool`, optional
        If False then the *item* is not copied before insertion. By
        default it is copied.
      
    replace: `bool`, optional
        If False then do not replace an existing coordinate reference object of
        domain which has the same identifier. By default an existing
        coordinate reference object with the same identifier is replaced with
        *item*.
    
:Returns:

    out: 
        The domain identifier for the *item*.


:Examples:

>>>

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.insert_ref(**kwargs2)
    #--- End: def

    def item_axes(self, items=None, role=None, axes=None,
                  axes_all=None, axes_subset=None, axes_superset=None,
                  exact=False, inverse=False, match_and=True,
                  ndim=None):
        '''Return the axes of a domain item of the field.

An item is a dimension coordinate, an auxiliary coordinate, a cell
measure or a coordinate reference object.

.. seealso:: `axes`, `data_axes`, `item`, `items_axes`

:Parameters:

    {+items}

    {+role}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}
       
    {+inverse}

:Returns:

    out: `list` or `None`
        The ordered list of axes for the item or, if there is no
        unique item or the item is a coordinate reference then `None`
        is returned.

:Examples:

        '''    
        kwargs2 = self._parameters(locals())
        return self.domain.item_axes(**kwargs2)
    #--- End: def

    def items_axes(self, items=None, role=None, axes=None,
                   axes_all=None, axes_subset=None,
                   axes_superset=None, exact=False, inverse=False,
                   match_and=True, ndim=None):
        '''Return the axes of domain items of the field.

An item is a dimension coordinate, an auxiliary coordinate, a cell
measure or a coordinate reference object.

.. seealso:: `axes`, `data_axes`, `item_axes`, `items`

:Parameters:

    {+items}

    {+role}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}
       
    {+inverse}

:Returns:

    out: `dict`
        A dictionary whose keys are domain item identifiers with
        corresponding values of the ordered list of axes for each
        selected. The dictionary may be empty.

:Examples:

>>> f.domain.items_axes()
{'aux0': ['dim2', 'dim3'],
 'aux1': ['dim2', 'dim3'],
 'dim0': ['dim0'],
 'dim1': ['dim1'],
 'dim2': ['dim2'],
 'dim3': ['dim3']}

>>> f.domain.items_axes(role='d')
{'dim0': ['dim0'],
 'dim1': ['dim1'],
 'dim2': ['dim2'],
 'dim3': ['dim3']}

        '''    
        kwargs2 = self._parameters(locals())
        return self.domain.items_axes(**kwargs2)
    #--- End: def

    def items(self, items=None, role=None, axes=None, axes_all=None,
              axes_subset=None, axes_superset=None, ndim=None, match_and=True,
              exact=False, inverse=False, copy=False):
        '''Return domain items from the field.

An item is a dimension coordinate, an auxiliary coordinate, a cell
measure or a coordinate reference object.

The output is a dictionary whose key/value pairs are domain
identifiers with corresponding values of items of the domain.

{+item_selection}

{+items_criteria}

.. seealso:: `auxs`, `axes`, `measures`, `coords`, `dims`, `item`, `match`
             `remove_items`, `refs`

:Examples 1:

Select all items whose identities (as returned by their `!identity`
methods) start "height":

>>> f.items('height')

Select all items which span only one axis:

>>> f.items(ndim=1)

Select all cell measure objects:

>>> f.items(role='m')

Select all items which span the "time" axis:

>>> f.items(axes='time')

Select all CF latitude coordinate objects:

>>> f.items('Y')

Select all multidimensional dimension and auxiliary coordinate objects
which span at least the "time" and/or "height" axes and whose long
names contain the string "qwerty":

>>> f.items('long_name:.*qwerty', 
...         role='da',
...         axes=['time', 'height'],
...         ndim=cf.ge(2))

:Parameters:

    {+items}

          *Example:* 

            >>> x = f.items(['aux1',
            ...             'time',
            ...             {'units': 'degreeN', 'long_name': 'foo'}])
            >>> y = {}
            >>> for items in ['aux1', 'time', {'units': 'degreeN', 'long_name': 'foo'}]:
            ...     y.update(f.items(items))
            ...
            >>> set(x) == set(y)
            True

    {+role}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}

    {+inverse}

          *Example:*
            ``f.items(role='da', inverse=True)`` selects the same
            items as ``f.items(role='mr')``.

    {+copy}

:Returns:

    out: `dict`
        A dictionary whose keys are domain item identifiers with
        corresponding values of items of the domain. The dictionary
        may be empty.

:Examples:

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.items(**kwargs2)
    #--- End: def

    def period(self, axes=None, **kwargs):
        '''Return the period of an axis.

Note that a non-cyclic axis may have a defined period.

.. versionadded:: 1.0

.. seealso:: `axis`, `cyclic`, `iscyclic`,
             `cf.DimensionCoordinate.period`

:Parameters:

    {+axes, kwargs}

:Returns:

    out: `cf.Data` or `None`
        The period of the cyclic axis's dimension coordinates, or
        `None` no period has been set.

:Examples 2:

>>> f.cyclic()
{}
>>> print f.period('X')
None
>>> f.dim('X').Units
<CF Units: degrees_east>
>>> f.cyclic('X', period=360)
{}
>>> print f.period('X')
<CF Data: 360.0 'degrees_east'>
>>> f.cyclic('X', False)
{'dim3'}
>>> print f.period('X')
<CF Data: 360.0 'degrees_east'>
>>> f.dim('X').period(None)
<CF Data: 360.0 'degrees_east'>
>>> print f.period('X')
None

        '''
        axis = self.domain.axis(axes=axes, **kwargs)
        if axis is None:
            raise ValueError("Can't identify axis")

        dim = self.dim(axis)
        if dim is None:
            return
            
        return dim.period()       
    #--- End: def

    def remove_item(self, items=None, role=None, axes=None,
                    axes_all=None, axes_subset=None,
                    axes_superset=None, ndim=None, match_and=True,
                    exact=False, inverse=False, key=False, copy=False):
        '''Remove and return a domain item from the field.

An item is either a dimension coordinate, an auxiliary coordinate, a
cell measure or a coordinate reference object of the domain.

The item may be selected with the keyword arguments. If no unique item
can be found then no items are removed and `None` is returned.

.. seealso:: `item`, `remove_axes`, `remove_axis`, `remove_items`

:Parameters:

    {+items}

    {+role}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}
       
    {+inverse}

    {+key}

    {+copy}

:Returns:

    out: 
        The unique item or its domain identifier or, if there is no
        unique item, `None`.

:Examples:

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.remove_item(**kwargs2)
    #--- End: def

    def remove_axes(self, axes=None, size=None, **kwargs):
        '''

Remove and return axes from the field.

By default all axes of the domain are removed, but particular axes may
be selected with the keyword arguments.

The axis may be selected with the keyword arguments. If no unique axis
can be found then no axis is removed and `None` is returned.

If an axis has size greater than 1 then it is not possible to remove
it if it is spanned by the field's data array or any multidimensional
coordinate or cell measure object of the field.

.. seealso:: `axes`, `remove_axis`, `remove_item`, `remove_items`

:Parameters:

    {+axes, kwargs}

    {+size}

:Returns:

    out: set
        The removed axes. The set may be empty.

:Examples:

'''
        domain = self.domain

        axes = domain.axes(axes, size=size, **kwargs)
        if not axes:
            return set()

        size1_data_axes = []
        axes_sizes = domain._axes_sizes
        for axis in axes.intersection(domain.data_axes()):
            if axes_sizes[axis] == 1:
                size1_data_axes.append(axis)
            else:
                raise ValueError(
"Can't remove an axis with size > 1 which is spanned by the data array")
        #---End: for

        if size1_data_axes:
            self.squeeze(size1_data_axes, i=True)

        axes = domain.remove_axes(axes, i=True)

        # Remove axes from unlimited dictionary
        unlimited = self._unlimited
        if unlimited:
            for axis in axes:
                unlimited.pop(axis, None)
            if not unlimited:
                self._unlimited = None

        return axes
    #--- End: def

    def remove_axis(self, axes=None, size=None, **kwargs):
        '''

Remove and return a unique axis from the field.

The axis may be selected with the keyword arguments. If no unique axis
can be found then no axis is removed and `None` is returned.

If the axis has size greater than 1 then it is not possible to remove
it if it is spanned by the field's data array or any multidimensional
coordinate or cell measure object of the field.

.. seealso:: `axis`, `remove_axes`, `remove_item`, `remove_items`

:Parameters:

    {+axes, kwargs}

    {+size}

:Returns:

    out: str
        The domain identifier of the removed axis, or `None` if there
        isn't one.

:Examples:

'''      
        axis = self.domain.axis(axis, size=size, **kwargs)
        if axis is None:
            return

        return self.remove_axes(axis).pop()
    #--- End: def

    def remove_items(self, items=None, role=None, axes=None,
                     axes_all=None, axes_subset=None,
                     axes_superset=None, ndim=None, exact=False,
                     inverse=False, match_and=True):
        '''

Remove and return domain items from the domain.

An item is either a dimension coordinate, an auxiliary coordinate, a
cell measure or a coordinate reference object of the domain.

By default all items of the domain are removed, but particular items
may be selected with the keyword arguments.

.. seealso:: `items`, `remove_axes`, `remove_axis`, `remove_item`

:Parameters:

    {+items}

    {+role}

    {+axes}

    {+axes_all}

    {+axes_subset}

    {+axes_superset}

    {+ndim}

    {+match_and}

    {+exact}

    {+inverse}

:Returns:

    out: `dict`
        A dictionary whose keys are domain item identifiers with
        corresponding values of the removed items of the domain. The
        dictionary may be empty.

:Examples:

        '''
        kwargs2 = self._parameters(locals())
        return self.domain.remove_items(**kwargs2)
    #--- End: def

    def reverse(self):
        '''L.reverse() -- reverse *IN PLACE*

Note that ``f.reverse()`` is equivalent to ``f``, thus providing
compatiblity with a single element field list.

.. versionadded:: 1.0.4

.. seealso:: `cf.FieldList.reverse`, :py:obj:`reversed`, `sort`

:Examples 1:

>>> f.reverse()

:Returns:

    `None`

:Examples 2:

>>> id0 = id(f)
>>> f.reverse()
>>> id0 == id(f)
True
>>> g = cf.FieldList(f)
>>> id0 = id(g)
>>> g.reverse()
>>> id0 == id(g)
True

'''
        return
    #--- End: def
    
    def roll(self, axes, shift, i=False, **kwargs):
        '''{+Fef,}Roll the field along a cyclic axis.

{+Fef,}A unique axis is selected with the axes and kwargs parameters.

.. versionadded:: 1.0

[+1].. seealso:: `anchor`, `axis`, `cyclic`, `iscyclic`, `period`
[+N].. seealso:: `anchor`, `cf.Field.axis`, `cf.Field.cyclic`,
[+N]             `cf.Field.iscyclic`, `cf.Field.period`

:Parameters:

    {+axes, kwargs}

    shift: `int`
        The number of places by which the selected cyclic axis is to
        be rolled.

    {+i}

:Returns:

    out: `cf.{+Variable}`
        The rolled field.

:Examples:

        '''          
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('roll', kwargs2)

        axis = self.domain.axis(axes, **kwargs)
        if axis is None:
            raise ValueError("Can't roll: Bad axis specification")

        if i:
            f = self
        else:
            f = self.copy()
        
        domain = f.domain

        if domain.axis_size(axis) <= 1:
            return f
        
        dim = domain.item(axis)
        if dim is not None and dim.period() is None:
            raise ValueError(
                "Can't roll %r axis with non-periodic dimension coordinates" % 
                dim.name())

        try:
            iaxis = domain.data_axes().index(axis)
        except ValueError:
            return f

        f = super(Field, f).roll(iaxis, shift, i=True)

        item_axes = domain.item_axes
        for key, item in domain.items(role=('d', 'a', 'm')).iteritems():
            axes = item_axes(key)
            if axis in axes:
                item.roll(axes.index(axis), shift, i=True)
        #--- End: for

        return f
    #--- End: def

    def where(self, condition, x=None, y=None, i=False):
        '''{+Fef,}Set data array elements depending on a condition.

Elements are set differently depending on where the condition is True
or False. Two assignment values are given. From one of them, the
field's data array is set where the condition is True and where the
condition is False, the data array is set from the other.

Each assignment value may either contain a single datum, or is an
array-like object which is broadcastable shape of the field's data
array.

**Missing data**

The treatment of missing data elements depends on the value of field's
`hardmask` attribute. If it is True then masked elements will not
unmasked, otherwise masked elements may be set to any value.

In either case, unmasked elements may be set to any value (including
missing data).

Unmasked elements may be set to missing data by assignment to the
`cf.masked` constant or by assignment to a value which contains masked
elements.

[+1].. seealso:: `cf.masked`, `hardmask`, `indices`, `mask`, `subspace`
[+N].. seealso:: `cf.masked`, `cf.Field.hardmask`, `cf.Field.indices`,
[+N]             `mask`, `subspace`

:Examples 1:

>>> 

:Parameters:

    condition: 
        The condition which determines how to set the data array. The
        *condition* parameter may be one of:

          * Any object which is broadcastable to the field's shape
            using the metadata-aware `cf` broadcasting rules (i.e. a
            suitable `cf.Field` object or any object, ``a``, for which
            ``numpy.size(a)`` is 1). The condition is True where the
            object broadcast to the field's data array evaluates to
            True.

              *Example:*                
                To set all data array values of 10 to -999:
                ``f.where(10, -999)``.

              *Example:*
                To set all data array values of 100 metres to -999
                metres: ``f.where(cf.Data(100, 'm'), -999)``.

              *Example:*
                To set all data array values to -999 where another
                field, ``g`` (which is broadcastable to ``f``),
                evaluates to true: ``f.where(g, -999)``.

        ..

          * A `cf.Query` object which is evaluated against the field
            and the resulting field of booleans (which will always
            have the same shape as the original field) defines the
            condition.
   
              *Example:*
                ``f.where(cf.lt(0), -999)`` will set all data array
                values less than zero to -999. This will often be
                equivalent to ``f.where(f==cf.lt(0), -999)``, but the
                latter will fail if the field ``f`` has insufficient
                domain metadata whilst the former will always work.

    x, y: optional
        Specify the assignment values. Where the condition evaluates
        to True, set the field's data array from *x* and where the
        condition evaluates to False, set the field's data array from
        *y*. The *x* and *y* parameters are each one of:

          * `None`. The appropriate elements of the field's data
            array are unchanged. This the default.

        ..
          * Any object which is broadcastable to the field's data
            array using the metadata-aware `cf` broadcasting rules
            (i.e. a suitable `cf.Field` object or any object, ``a``,
            for which ``numpy.size(a)`` is 1). The appropriate
            elements of the field's data array are set to the
            corresponding values from the object broadcast to the
            field's data array shape.

    {+i}

:Returns:

    out: `cf.{+Variable}`
        {+Fef,}The field with updated data array.

:Examples 2:

Set data array values to 15 everywhere:

>>> f.where(True, 15)

This example could also be done with subspace assignment:

>>> f.subspace[...] = 15

Set all negative data array values to zero and leave all other
elements unchanged:

>>> g = f.where(f<0, 0)

Multiply all positive data array elements by -1 and set other data
array elements to 3.14:

>>> g = f.where(f>0, -f, 3.14)

Set all values less than 280 and greater than 290 to missing data:

>>> g = f.where((f < 280) | (f > 290), cf.masked)

This example could also be done with a `cf.Query` object:

>>> g = f.where(cf.wo(280, 290), cf.masked)

or equivalently:

>>> g = f.where(f==cf.wo(280, 290), cf.masked)

Set data array elements in the northern hemisphere to missing data
in-place:
[+1]
[+1]>>> # Create a condition which is True only in the northern hemisphere
[+1]>>> condition = f.domain_mask(latitude=cf.ge(0))
[+1]>>> # Set the data
[+1]>>> f.where(condition, cf.masked, i=True)
[+N]
[+N]>>> for g, northern_hemisphere in zip(f, f.domain_mask(latitude=cf.ge(0))):
[+N]...     g.where(condition, cf.masked, i=True)

This in-place example could also be done with subspace assignment by
indices:
[+1]
[+1]>>> northern_hemisphere = f.indices(latitude=cf.ge(0))
[+1]>>> f.subspace[northern_hemisphere] = cf.masked
[+N]
[+N]>>> for g in f:
[+N]...     northern_hemisphere = g.indices(latitude=cf.ge(0))
[+N]...     g.subspace[northern_hemisphere] = cf.masked

Set a polar rows to their zonal-mean values:
[+1]
[+1]>>> # Create a condition which is True only on polar rows
[+1]>>> condition = f.domain_mask(latitude=cf.set([-90, 90]))
[+1]>>> #Set each data polar row element to the polar row zonal mean 
[+1]>>> # and mask all other points
[+1]>>> g = f.where(condition, f.collapse('longitude: mean'))
[+N]
[+N]>>> # Initialize the new field list
[+N]>>> g = cf.FieldList()
[+N]>>> for x in f:
[+N]...     # Create a condition which is True only on the polar rows
[+N]...     condition = x.domain_mask(latitude=cf.set([-90, 90]))
[+N]...     # Set each data polar row element to the polar row zonal mean 
[+N]...     # and mask all other points
[+N]...     g.append(x.where(condition, x.collapse('longitude: mean')))

        '''   
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())            
            return self._list_method('where', kwargs2)
 
        if i:
            f = self
        else:
            f = self.copy()

        if x is None and y is None:
            return f

        self_class = f.__class__

        if isinstance(condition, self_class):
            if len(condition) != 1:
                raise ValueError(
                    "Can't where: FieldList 'condition' must contain exactly 1 element")
            condition = f._conform_for_assignment(condition[0])

        elif isinstance(condition, Query):
            condition = condition.evaluate(f).Data            
 
        if x is not None and isinstance(x, self_class):
            if len(x) != 1:
                raise ValueError(
                    "Can't where: FieldList 'x' must contain exactly 1 element")
            x = f._conform_for_assignment(x[0])
               
        if y is not None and isinstance(y, self_class):
            if len(y) != 1:
                raise ValueError(
                    "Can't where: FieldList 'y' must contain exactly 1 element")
            y = f._conform_for_assignment(y[0])

        return super(Field, f).where(condition, x, y, i=True)
    #--- End: def

    def section(self, axes=None, stop=None, chunks=False, min_step=1,
                **kwargs):
        '''

{+Fef,}Return a FieldList of m dimensional sections of a Field of n
dimensions, where m <= n.

:Parameters:

    axes: optional
        A query for the m axes that define the sections of the Field
        as accepted by the Field object's axes method. The keyword
        arguments are also passed to this method. See cf.Field.axes
        for details. If an axis is returned that is not a data axis it
        is ignored, since it is assumed to be a dimension coordinate
        of size 1.

    stop: `int`, optional
        Stop after taking this number of sections and return. If stop
        is None all sections are taken.

    chunks: `bool`, optional
        If True return sections that are of the maximum possible size
        that will fit in one chunk of memory instead of sectioning
        into slices of size 1 along the dimensions that are being
        sectioned.
    
    min_step: `int`, optional
        The minimum step size when making chunks. By default this is
        1. Can be set higher to avoid size 1 dimensions, which are
        problematic for bilinear regridding.

:Returns:

    out: `cf.FieldList`
        The FieldList of m dimensional sections of the Field.

:Examples:

Section a field into 2D longitude/time slices, checking the
units:

>>> f.section({None: 'longitude', units: 'radians'},
...           {None: 'time',
...            'units': 'days since 2006-01-01 00:00:00'})

Section a field into 2D longitude/latitude slices, requiring
exact names:

>>> f.section(['latitude', 'longitude'], exact=True)

Section a field into 2D longitude/latitude slices, showing
the results:

>>> f
<CF Field: eastward_wind(model_level_number(6), latitude(145),
longitude(192)) m s-1>

>>> f.section(('X', 'Y'))
[<CF Field: eastward_wind(model_level_number(1), latitude(145),
longitude(192)) m s-1>,
 <CF Field: eastward_wind(model_level_number(1), latitude(145),
longitude(192)) m s-1>,
 <CF Field: eastward_wind(model_level_number(1), latitude(145),
longitude(192)) m s-1>,
 <CF Field: eastward_wind(model_level_number(1), latitude(145),
longitude(192)) m s-1>,
 <CF Field: eastward_wind(model_level_number(1), latitude(145),
longitude(192)) m s-1>,
 <CF Field: eastward_wind(model_level_number(1), latitude(145),
longitude(192)) m s-1>]

        '''
        return FieldList(_section(self, axes, data=False, stop=stop,
                                  chunks=chunks, min_step=min_step, **kwargs))
    #--- End: def

    def regrids(self, dst, src_cyclic=None, dst_cyclic=None,
                method='auto', use_dst_mask=False,
                _compute_field_mass=None, i=False):
        '''

{+Fef,}Returns the field regridded onto a new latitude-longitude grid.

Regridding, also called remapping or interpolation, is the process of
changing the grid underneath field data values while preserving the
qualities of the original data.

By default the the regridding is a first-order conservative
interpolation, but bilinear interpolation is available. The latter
method is particular useful for cases when the latitude and longitude
coordinate cell boundaries are not known nor inferrable. Nearest
neighbour interpolation is also available.

**Metadata**

The field's domain must have well defined X and Y axes with latitude
and longitude coordinate values, which may be stored as dimension
coordinate objects or two dimensional auxiliary coordinate
objects. The same is true for the destination grid, if it provided as
part of another field.

The cyclicity of the X axes of the source field and destination grid
is taken into account. If an X axis is in fact cyclic but is
registered as such by its parent field (see `cf.Field.iscyclic`), then
the cyclicity may be set with the *src_cyclic* or *dst_cyclic*
parameters.

The output field's coordinate objects which span the X and/or Y axes
are replaced with those from the destination grid. Any fields
contained in coordinate reference objects will also be regridded, if
possible.

**Mask**

The data array mask of the field is automatically taken into account,
such that the regridded data array will be masked in regions where the
input data array is masked. By default the mask of the destination
grid is not taken into account. If the destination field data has
more than two dimensions then the mask, if used, is taken from the two
dimensionsal section of the data where the indices of all axes other
than X and Y are zero.

**Method**

The interpolation is carried by out using the `ESMF` package - a
Python interface to the Earth System Modeling Framework (ESMF)
regridding utility.

**Logging**

Whether ESMF logging is enabled or not is determined by
`cf.REGRID_LOGGING`. If it is logging takes place after every call. By
default logging is disabled.

.. versionadded:: 1.0.4

:Examples 1:

Regrid field ``f`` conservatively onto a grid contained in field
``g``:

>>> h = f.regrids(g)

:Parameters:

    dst: `cf.Field` or `dict`
        The field containing the new grid. If dst is a field list the
        first field in the list is used. Alternatively a dictionary
        can be passed containing the keywords 'longitude' and
        'latitude' with either two 1D dimension coordinates or two 2D
        auxiliary coordinates. In the 2D case both coordinates must
        have their axes in the same order and this must be specified
        by the keyword 'axes' as either ``('X', 'Y')`` or ``('Y',
        'X')``.

    src_cyclic: `bool`, optional
        Force the use of a periodic X axis for the source field,
        without altering the original field.

    dst_cyclic: `bool`, optional
        Force the use of a periodic X axis for the destination grid,
        without altering the original field.

    method: `str`, optional
        By default the regridding method is set to 'auto'. In this case
        conservative regridding will be used unless one or both of the
        fields does not have contiguous bounds, in which case bilinear
        regridding will be used. If a 1D dimension coordinate does not
        have bounds then contiguous bounds will be created
        automatically. If this parameter is set to conservative then
        first-order conservative regridding is used. If it is set to
        'bilinear' then multilinear interpolation is used. If it is set
        to 'nearest_stod' then nearest neighbor interpolation is used
        where each destination point is mapped to the closest source
        point. A given source point may map to multiple destination
        points, but no destination point will receive input from more
        than one source point. If it is set to 'nearest_dtos' then
        nearest neighbor interpolation is used where each source
        point is mapped to the closest destination point. A given
        destination point may receive input from multiple source
        points, but no source point will map to more than one
        destination point.

    use_dst_mask: `bool`, optional
        By default the mask of the data on the destination grid is not
        taken into account when performing regridding. If this option
        is set to true then it is. If the destination field has more
        than two dimensions then the first 2D slice in index space is
        used for the mask e.g. for an field varying with (X, Y, Z, T)
        the mask is taken from the slice (X, Y, 0, 0).

    {+i}

    _compute_field_mass: `dict`, optional
        If this is a dictionary then the field masses of the source
        and destination fields are computed and returned within the
        dictionary. The keys of the dictionary indicates the lat/long
        slice of the field and the corresponding value is a tuple
        containing the source field's mass and the destination field's
        mass. The calculation is only done if conservative regridding
        is being performed. This is for debugging purposes.

:Returns:

    out: `cf.{+Variable}`
        The regridded {+variable}.

:Examples 2:

Regrid f to the grid of g using bilinear regridding and forcing the
source field f to be treated as cyclic.

>>> h = f.regrids(g, src_cyclic=True, method='bilinear')

Regrid f to the grid of g using the mask of g.

>>> h = f.regrids(g, use_dst_mask=True)

Regrid f to 2D auxiliary coordinates lat and lon, which have their
dimensions ordered 'Y' first then 'X'.

>>> lat
<CF AuxiliaryCoordinate: latitude(110, 106) degrees_north>
>>> lon
<CF AuxiliaryCoordinate: longitude(110, 106) degrees_east>
>>> h = f.regrids({'longitude': lon, 'latitude': lat, 'axes': ('Y', 'X')})

        '''
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('regrids', kwargs2)
        
        # Initialise ESMPy for regridding if found
        manager = Regrid.initialize()
        
        # If dst is a dictionary set flag
        if isinstance(dst, self.__class__):
            dst_dict = False
            # If dst is a field list use the first field
            dst = dst[0]
        else:
            dst_dict = True
        
        # Retrieve the source field's latitude and longitude coordinates
        x_s, y_s, x_axis_s, y_axis_s, x_key_s, y_key_s, x_size_s, y_size_s, \
            src_2D_latlong = Regrid.get_latlong(self, 'source')
        
        # Retrieve the source field's z and t indices
        zt_indices = []
        
        z_key = self.dim('Z', key=True)
        if z_key is not None:
            try:
                z_index = self.data_axes().index(z_key)
            except ValueError:
                self = self.unsqueeze(z_key, i=i)
                z_index = self.data_axes().index(z_key)
            zt_indices.append(z_index)
        
        t_key = self.dim('T', key=True)
        if t_key is not None:
            try:
                t_index = self.data_axes().index(t_key)
            except ValueError:        
                self = self.unsqueeze(t_key, i=i)
                t_index = self.data_axes().index(t_key)
            zt_indices.append(t_index)
        
        # Retrieve the destination field's latitude and longitude coordinates
        if dst_dict:
            try:
                x_d = dst['longitude']
                y_d = dst['latitude']
            except KeyError:
                raise ValueError("Keywords 'longitude' and 'latitude' " +
                                 "must be specified for destination.")
            #--- End: if
            if x_d.ndim == 1:
                dst_2D_latlong = False
                x_size_d = x_d.size
                y_size_d = y_d.size
            elif x_d.ndim == 2:
                try:
                    dst_axes = dst['axes']
                except KeyError:
                    raise ValueError("Keyword 'axes' must be specified " +
                                     "for 2D latitude/longitude coordinates.")
                dst_2D_latlong = True
                if dst_axes == ('X', 'Y'):
                    x_size_d = x_d.shape[0]
                    y_size_d = x_d.shape[1]
                elif dst_axes == ('Y', 'X'):
                    x_size_d = x_d.shape[1]
                    y_size_d = x_d.shape[0]
                else:
                    raise ValueError("Keyword 'axes' must either be " +
                                     "('X', 'Y') or ('Y', 'X').")                
                if x_d.shape != y_d.shape:
                    raise ValueError('Longitude and latitude coordinates for ' +
                                     'destination must have the same shape.')
            else:
                raise ValueError('Longitude and latitude coordinates for ' +
                                 'destination must have 1 or 2 dimensions.')
            #--- End: if
        else:
            x_d, y_d, x_axis_d, y_axis_d, x_key_d, y_key_d, x_size_d, y_size_d, \
                dst_2D_latlong = Regrid.get_latlong(dst, 'destination')
        #--- End: if
        
        # Set src_cyclic and/or dst_cyclic to true if it has been automatically
        # detected that the fields are cyclic.
        if self.iscyclic('X'):
            src_cyclic = True
        if not dst_dict and dst.iscyclic('X'):
            dst_cyclic = True
        
        # Preserve order of axes
        try:
            x_index_s= self.data_axes().index(x_axis_s)
        except ValueError:        
            self = self.unsqueeze(x_axis_s, i=i)
            x_index_s = self.data_axes().index(x_axis_s)
        
        try:
            y_index_s = self.data_axes().index(y_axis_s)
        except ValueError:        
            self = self.unsqueeze(y_axis_s, i=i)
            y_index_s = self.data_axes().index(y_axis_s)
        
        if not dst_dict:
            try:
                x_index_d = dst.data_axes().index(x_axis_d)
            except ValueError:        
                dst = dst.unsqueeze(x_axis_d)
                x_index_d = dst.data_axes().index(x_axis_d)
            
            try:
                y_index_d = dst.data_axes().index(y_axis_d)
            except ValueError:        
                dst = dst.unsqueeze(y_axis_d)
                y_index_d = dst.data_axes.index(y_axis_d)
        #--- End: if
        
        shape = [1]*self.ndim
        shape[x_index_s] = x_size_d
        shape[y_index_s] = y_size_d
        order_s = (0, 1) if x_index_s < y_index_s else (1, 0)
        if not dst_dict:
            order_d = (0, 1) if x_index_d < y_index_d else (1, 0)
        #--- End: if
        
        if src_2D_latlong:
            x_axes_s = self.item_axes(x_key_s)
            x_order_s = (x_axes_s.index(x_axis_s), x_axes_s.index(y_axis_s))
            y_axes_s = self.item_axes(y_key_s)
            y_order_s = (y_axes_s.index(x_axis_s), y_axes_s.index(y_axis_s))
        if dst_2D_latlong:
            if dst_dict:
                if dst_axes == ('X', 'Y'):
                    x_order_d = (0, 1)
                    y_order_d = (0, 1)
                elif dst_axes == ('Y', 'X'):
                    x_order_d = (1, 0)
                    y_order_d = (1, 0)
                else:
                    raise ValueError("Keyword 'axes' must either be " +
                                     "('X', 'Y') or ('Y', 'X').")
            else:
                x_axes_d = dst.item_axes(x_key_d)
                x_order_d = (x_axes_d.index(x_axis_d), x_axes_d.index(y_axis_d))
                y_axes_d = dst.item_axes(y_key_d)
                y_order_d = (y_axes_d.index(x_axis_d), y_axes_d.index(y_axis_d))
        #--- End: if
        
        # Slice the source data into 2D latitude/longitude sections
        sections = self.Data.section((x_index_s, y_index_s))
        
        # Check whether the coordinates all have appropriate bounds
        if method == 'auto':
            method = 'conservative'
            for coord in [x_s, y_s]:
                if src_2D_latlong:
                    if not coord.hasbounds or not coord.contiguous(overlap=False):
                        method = 'bilinear'
                        break
                    #--- End: if
                else:
                    if coord.hasbounds and not coord.contiguous(overlap=False):
                        method = 'bilinear'
                        break
                    #--- End: if
                #--- End: if
            #--- End: for
            for coord in [x_d, y_d]:
                if dst_2D_latlong:
                    if not coord.hasbounds or not coord.contiguous(overlap=False):
                        method = 'bilinear'
                        break
                    #--- End: if
                else:
                    if coord.hasbounds and not coord.contiguous(overlap=False):
                        method = 'bilinear'
                        break
                    #--- End: if
                #--- End: if
            #--- End: for
        elif method == 'conservative':
            for coord in [x_s, y_s]:
                if src_2D_latlong:
                    if not coord.hasbounds or not coord.contiguous(overlap=False):
                        raise ValueError('2D source latitude and longitude' +
                                         ' coordinates must have contiguous' +
                                         ' bounds for conservative regridding.')
                    #--- End: if
                else:
                    if coord.hasbounds and not coord.contiguous(overlap=False):
                        raise ValueError('Existing bounds of 1D source' +
                                         ' latitude and longitude coordinates' +
                                         ' must be contiguous for conservative' +
                                         ' regridding.')
                    #--- End: if
                #--- End: if
            #--- End: for
            for coord in [x_d, y_d]:
                if dst_2D_latlong:
                    if not coord.hasbounds or not coord.contiguous(overlap=False):
                        raise ValueError('2D destination latitude and longitude' +
                                         ' coordinates must have contiguous' +
                                         ' bounds for conservative regridding.')
                    #--- End: if
                else:
                    if coord.hasbounds and not coord.contiguous(overlap=False):
                        raise ValueError('Existing bounds of 1D destination' +
                                         ' latitude and longitude coordinates' +
                                         ' must be contiguous for conservative' +
                                         ' regridding.')
                    #--- End: if
                #--- End: if
            #--- End: for
        #--- End: if

        # Retrieve the destination field's grid and create the ESMPy grid
        use_bounds = method == 'conservative'
        dst_mask = None
        if not dst_dict and use_dst_mask and dst.Data.ismasked:
            dst_mask = dst.section(('X', 'Y'), stop=1, ndim=1)[0].squeeze().array.mask
            dst_mask = dst_mask.transpose(order_d)
        #--- End: if
        if dst_2D_latlong:
            dstgrid = Regrid.create_2Dgrid(x_d, y_d, x_order_d, y_order_d,
                                           dst_cyclic, dst_mask, use_bounds)
        else:
            dstgrid = Regrid.create_grid(x_d, y_d, dst_cyclic, dst_mask, use_bounds)
        #--- End: if
        dstfield = Regrid.create_field(dstgrid, 'dstfield')
        dstfracfield = Regrid.create_field(dstgrid, 'dstfracfield')

        def initialise_regridder(src_mask=None):
            '''
            Initialise the source grid and the regridder.
            '''
            # Create the source grid
            if src_2D_latlong:
                srcgrid = Regrid.create_2Dgrid(x_s, y_s, x_order_s, y_order_s,
                                               src_cyclic, src_mask, use_bounds)
            else:
                srcgrid = Regrid.create_grid(x_s, y_s, src_cyclic, src_mask, use_bounds)
            #--- End: if
            srcfield = Regrid.create_field(srcgrid, 'srcfield')
            srcfracfield = Regrid.create_field(srcgrid, 'srcfracfield')
            
            # Initialise the regridder
            regridSrc2Dst = Regrid(srcfield, dstfield, srcfracfield,
                                   dstfracfield, method=method)
            
            return srcgrid, srcfield, srcfracfield, regridSrc2Dst
        
        # Reorder keys by Z and then T to minimise how often the mask is
        # likely to change.
        if zt_indices:
            section_keys = sorted(sections.keys(),
                                  key=operator_itemgetter(*zt_indices))
        else:
            section_keys = sections.keys()
        
        # Regrid each section
        old_mask = None
        unmasked_grid_created = False
        for k in section_keys:
            d = sections[k]
            # Retrieve the source field's grid, create the ESMPy grid and a
            # handle to regridding.dst_dict
            src_data = d.squeeze().transpose(order_s).array
            if numpy_is_masked(src_data):
                mask = src_data.mask
                if not numpy_array_equal(mask, old_mask):
                    # Release old memory
                    if old_mask is not None:
                        regridSrc2Dst.destroy()
                        srcfracfield.destroy()
                        srcfield.destroy()
                        srcgrid.destroy()
                    #--- End: if
                    
                    # (Re)initialise the regridder
                    srcgrid, srcfield, srcfracfield, regridSrc2Dst = \
                        initialise_regridder(mask)
                    old_mask = mask
                #--- End: if
            else:
                if not unmasked_grid_created or old_mask is not None:
                    # Initialise the regridder
                    srcgrid, srcfield, srcfracfield, regridSrc2Dst = \
                        initialise_regridder()
                    unmasked_grid_created = True
                    old_mask = None
                #--- End: if
            #--- End: if
            
            # Fill the source and destination fields and regrid
            srcfield.data[...] = numpy_MaskedArray(src_data, copy=False).filled(self.fill_value(default='netCDF'))
            dstfield.data[...] = self.fill_value(default='netCDF')
            dstfield = regridSrc2Dst.run_regridding(srcfield, dstfield)
            
            # Check field mass
            if _compute_field_mass is not None and method == 'conservative':
                if not type(_compute_field_mass) == dict:
                    raise ValueError('Expected compute_field_mass to be a dictoinary.')
                srcareafield = Regrid.create_field(srcgrid, 'srcareafield')
                srcmass = Regrid.compute_mass_grid(srcfield, srcareafield,
                                                   dofrac=True,
                                                   fracfield=srcfracfield,
                                                   uninitval=self.fill_value(default='netCDF'))
                dstareafield = Regrid.create_field(dstgrid, 'dstareafield')
                dstmass = Regrid.compute_mass_grid(dstfield, dstareafield,
                                               uninitval=self.fill_value(default='netCDF'))
                _compute_field_mass[k] = (srcmass, dstmass)
            
            # Correct destination field data if doing conservative regridding
            # and add mask
            if method == 'conservative':
                frac = dstfracfield.data[...]
                frac[frac == 0.0] = 1.0
                regridded_data = numpy_MaskedArray(dstfield.data[...].copy()/frac,
                                                   mask=(dstfield.data ==
                                                         self.fill_value(default='netCDF')))
            else:
                regridded_data = numpy_MaskedArray(dstfield.data[...].copy(),
                                                   mask=(dstfield.data ==
                                                         self.fill_value(default='netCDF')))
            
            # Insert regridded data, with axes in correct order
            sections[k] = Data(regridded_data.transpose(order_s).reshape(shape),
                               units=self.Units)
        #--- End: for
        
        # Construct new data from regridded sdst_dictections
        new_data = Regrid.reconstruct_sectioned_data(sections)
        
        # Construct new field
        if i:
            f = self
        else:
            f = self.copy(_omit_Data=True)
        #--- End:if
        
        # Update ancillary variables and coordinate references of source
        f._conform_ancillary_variables([x_axis_s, y_axis_s], keep_size_1=False)
        for key, ref in f.refs().iteritems():
            axes = f.domain.ref_axes(key)
            if x_axis_s in axes or y_axis_s in axes:
                f.remove_item(key)
            else:
                for term, value in ref.iteritems():
                    if not isinstance(value, type(self)):
                        continue 
                    
                    axes2 = value.axes(('X', 'Y'))
                    if len(axes2) == 1:
                        ref[term] = None
                    elif len(axes2) == 2:
                        # only want to do this if value spans both X and Y
                        try:
                            value2 = value.regrids(dst, src_cyclic=src_cyclic,
                                                   dst_cyclic=dst_cyclic,
                                                   method=method,
                                                   use_dst_mask=use_dst_mask,
                                                   i=i)
                        except ValueError:
                            ref[term] = None
                        else:
                            ref[term] = value2
                    #--- End: if
                #--- End: for
            #--- End: if
        #--- End: for
        
        # Remove X and Y coordinates of new field
        f.remove_items(axes=('X', 'Y'))
        
        # Give destination grid latitude and longitude standard names
        x_d.standard_name = 'longitude'
        y_d.standard_name = 'latitude'
        
        # Insert 'X' and 'Y' coordinates from dst into new field
        f.domain._axes_sizes[x_axis_s] = x_size_d
        f.domain._axes_sizes[y_axis_s] = y_size_d
        if dst_dict:
            if dst_2D_latlong:
                if x_order_d == (0, 1):
                    x_axes_s = (x_axis_s, y_axis_s)
                else:
                    x_axes_s = (y_axis_s, x_axis_s)
                if y_order_d == (0, 1):
                    y_axes_s = (x_axis_s, y_axis_s)
                else:
                    y_axes_s = (y_axis_s, x_axis_s)
                f.insert_aux(x_d, axes=x_axes_s)
                f.insert_aux(y_d, axes=y_axes_s)
            else:
                f.insert_dim(x_d, key=x_axis_s)
                f.insert_dim(y_d, key=y_axis_s)
        else:
            x_dim = dst.dim('X')
            f.insert_dim(x_dim, key=x_axis_s)
            
            y_dim = dst.dim('Y')
            f.insert_dim(y_dim, key=y_axis_s)
            
            for aux_key, aux in dst.auxs(axes_all=('X', 'Y')).iteritems():
                aux_axes = dst.domain.item_axes(aux_key)
                if aux_axes == [x_axis_d, y_axis_d]:
                    f.insert_aux(aux, axes=(x_axis_s, y_axis_s))
                else:
                    f.insert_aux(aux, axes=(y_axis_s, x_axis_s))
            #--- End: for
            for aux in dst.auxs(axes_all='X').values():
                f.insert_aux(aux, axes=x_axis_s)
            #--- End: for
            for aux in dst.auxs(axes_all='Y').values():
                f.insert_aux(aux, axes=y_axis_s)
            #--- End: for
        #--- End: if
        
        # Copy across the destination fields coordinate references if necessary
        if not dst_dict:
            for key, ref in dst.refs().iteritems():
                axes = dst.domain.ref_axes(key)
                if axes and axes.issubset([x_axis_d, y_axis_d]):
                    f.insert_ref(ref.copy(domain=dst.domain))
                #--- End: if
            #--- End: for
        #--- End: if
        
        # Insert regridded data into new field
        f.insert_data(new_data)
        
        # Set the cyclicity of the destination longitude
        x = f.dim('X')
        if x is not None and x.Units.equivalent(Units('degrees')):
            f.cyclic('X', iscyclic=dst_cyclic, period=Data(360, 'Degrees'))
        
        # Release old memory
        regridSrc2Dst.destroy()
        dstfracfield.destroy()
        srcfracfield.destroy()
        dstfield.destroy()
        srcfield.destroy()
        dstgrid.destroy()
        srcgrid.destroy()
        
        return f
    #--- End: def

    def regridc(self, dst, axes, method='auto', use_dst_mask=False,
                _compute_field_mass=None, i=False):
        '''

{+Fef,}Returns the field with the specified Cartesian axes regridded
onto a new grid. Between 1 and 3 dimensions may be regridded.

Regridding, also called remapping or interpolation, is the process of
changing the grid underneath field data values while preserving the
qualities of the original data.

By default the the regridding is a first-order conservative
interpolation, but bilinear and nearest neighbour interpolation is
available.

**Metadata**

The field's domain must have axes matching those specified in
src_axes. The same is true for the destination grid, if it provided
as part of another field. Optionally the axes to use from the
destination grid may be specified separately in dst_axes.

The output field's coordinate objects which span the specified axes
are replaced with those from the destination grid. Any fields
contained in coordinate reference objects will also be regridded, if
possible.

**Mask**

The data array mask of the field is automatically taken into account,
such that the regridded data array will be masked in regions where the
input data array is masked. By default the mask of the destination
grid is not taken into account. If the destination field data has
more dimensions than the number of axes specified then, if used, its
mask is taken from the 1-3 dimensional section of the data where the
indices of all axes other than X and Y are zero.

**Method**

The interpolation is carried by out using the `ESMF` package - a
Python interface to the Earth System Modeling Framework (ESMF)
regridding utility.

**Logging**

Whether ESMF logging is enabled or not is determined by
`cf.REGRID_LOGGING`. If it is logging takes place after every call. By
default logging is disabled.

:Examples 1:

Regrid the time axes of field ``f`` conservatively onto a grid
contained in field ``g``:

>>> h = f.regridc(g, axes='T')

:Parameters:

    dst: `cf.Field` or `dict`
        The field containing the new grid or a dictionary with the
        axes specifiers as keys referencing dimension coordinates.
        If dst is a field list the first field in the list is used.

    axes:
        Select dimension coordinates from the source and destination
        fields for regridding. See cf.Field.axes for options for
        selecting specific axes. However, the number of axes returned
        by cf.Field.axes must be the same as the number of specifiers
        passed in.

    method: `str`, optional
        By default the regridding method is set to 'auto'. In this case
        conservative regridding will be used unless one or both of the
        fields does not have contiguous bounds, in which case bilinear
        regridding will be used. If a 1D dimension coordinate does not
        have bounds then contiguous bounds will be created
        automatically. If this parameter is set to conservative then
        first-order conservative regridding is used. If it is set to
        'bilinear' then multilinear interpolation is used. If it is set
        to 'nearest_stod' then nearest neighbor interpolation is used
        where each destination point is mapped to the closest source
        point. A given source point may map to multiple destination
        points, but no destination point will receive input from more
        than one source point. If it is set to 'nearest_dtos' then
        nearest neighbor interpolation is used where each source
        point is mapped to the closest destination point. A given
        destination point may receive input from multiple source
        points, but no source point will map to more than one
        destination point.

    use_dst_mask: `bool`, optional
        By default the mask of the data on the destination grid is not
        taken into account when performing regridding. If this option
        is set to true then it is.

    {+i}

    _compute_field_mass: `dict`, optional
        If this is a dictionary then the field masses of the source
        and destination fields are computed and returned within the
        dictionary. The keys of the dictionary indicates the lat/long
        slice of the field and the corresponding value is a tuple
        containing the source field's mass and the destination field's
        mass. The calculation is only done if conservative regridding
        is being performed. This is for debugging purposes.

:Returns:

    out: `cf.{+Variable}`
        The regridded {+variable}.

:Examples 2:

Regrid the T axis of field ``f`` conservatively onto the grid
specified in the dimension coordinate ``t``:

>>> h = f.regridc({'T': t}, axes=('T'))

Regrid the T axis of field ``f`` using bilinear interpolation onto
a grid contained in field ``g``:

>>> h = f.regridc(g, axes=('T'), method='bilinear')

Regrid the X and Y axes of field ``f`` conservatively onto a grid
contained in field ``g``:

>>> h = f.regridc(g, axes=('X','Y'))

Regrid the X and T axes of field ``f`` conservatively onto a grid
contained in field ``g`` using the destination mask:

>>> h = f.regridc(g, axes=('X','Y'), use_dst_mask=True)

        '''
        # List functionality
        if self._list:
            kwargs2 = self._parameters(locals())
            return self._list_method('regrids', kwargs2)
        
        # Initialise ESMPy for regridding if found
        manager = Regrid.initialize()
        
        # If dst is a dictionary set flag
        if isinstance(dst, self.__class__):
            dst_dict = False
            # If dst is a field list use the first field
            dst = dst[0]
        else:
            dst_dict = True
        
        # Get the number of axes
        n_axes = len(axes)
        if n_axes < 1 or n_axes > 3:
            raise ValueError('Between 1 and 3 axes must be individually ' +
                             'specified.')
        
        # Retrieve the source axis keys and dimension coordinates
        axis_keys_s, coords_s = Regrid.get_cartesian_coords(self, 'source',
                                                            axes)
        
        # Retrieve the destination axis keys and dimension coordinates
        if dst_dict:
            coords_d = []
            for axis in axes:
                try:
                    coords_d.append(dst[axis])
                except KeyError:
                    raise ValueError('Axis ' + str(axis) + ' not specified in dst.')
                #--- End: try
            #--- End: for
        else:
            axis_keys_d, coords_d = Regrid.get_cartesian_coords(dst, 'destination',
                                                                axes)
        #--- End: if
        
        def get_axis_positions(f, axis_keys):
            """
            Get the axis positions and their orders in rank of a field f.
            """
            # Get the positions of the axes
            axis_positions = []
            for k in axis_keys:
                axis_positions.append(f.data_axes().index(k))
                
            # Get the rank order of the positions of the axes
            temp = numpy_array(axis_positions)
            temp = temp.argsort()
            order = numpy_empty(len(temp), int)
            order[temp] = numpy_arange(len(temp))
            
            return axis_positions, order
        
        # Get the axis positions for the source field
        axis_positions_s, order_s = get_axis_positions(self, axis_keys_s)
        
        # Get the axis positions for the destination field
        if not dst_dict:
            axis_positions_d, order_d = get_axis_positions(dst, axis_keys_d)
        
        # Pad out a single dimension with an extra one
        axis_keys_ext = []
        coords_ext = []
        axis_positions_s_ext = axis_positions_s
        order_s_ext = order_s
        if n_axes == 1 and self.squeeze().ndim > 1:
            src_shape = numpy_array(self.shape)
            tmp = src_shape.copy()
            tmp[axis_positions_s] = -1
            max_length = -1
            max_ind = -1
            for ind, length in enumerate(tmp):
                if length > max_length:
                    max_length = length
                    max_ind = ind
            if src_shape[axis_positions_s].prod()*max_length*8 < CHUNKSIZE():
                axis_keys_ext, coords_ext = \
                    Regrid.get_cartesian_coords(self, 'source', [max_ind])
                axis_positions_s_ext, order_s_ext = \
                    get_axis_positions(self, axis_keys_ext + axis_keys_s)
        
        # Check whether the coordinates all have appropriate bounds
        if method == 'auto':
            method = 'conservative'
            for coord in coords_s + coords_d + coords_ext:
                if coord.hasbounds and not coord.contiguous(overlap=False):
                    method = 'bilinear'
                    break
                #--- End: if
            #--- End: for
        elif method == 'conservative':
            for coord in coords_s + coords_d + coords_ext:
                if coord.hasbounds and not coord.contiguous(overlap=False):
                    raise ValueError('All existing bounds of dimension' +
                                     ' coordinates must be contiguous for' +
                                     ' conservative regridding.')
                #--- End: if
            #--- End: for
        #--- End: if

        # Calculate shape of each section
        shape = [1]*self.ndim
        tmp = coords_ext + coords_d
        for ind, p in enumerate(axis_positions_s_ext):
            shape[p] = tmp[ind].size
        
        # Deal with case of 1D linear regridding
        linear = False
        if method == 'bilinear' and n_axes == 1 and coords_ext == []:
            linear = True
            coords_ext = [DimensionCoordinate(data=Data([-1e-6,1e-6]))]
        
        # Section the data into slices of up to three dimensions
        sections = self.Data.section(axis_positions_s_ext)
        
        # Retrieve the destination field's grid and create the ESMPy grid
        dst_mask = None
        if not dst_dict and use_dst_mask and dst.Data.ismasked:
            dst_mask = dst.section(axes, stop=1, ndim=1)[0].squeeze().array.mask
            dst_mask = dst_mask.transpose(order_d)
            tmp = []
            for coord in coords_ext:
                tmp.append(coord.size)
            dst_mask = numpy_tile(dst_mask, tmp + [1]*dst_mask.ndim)
            
        #--- End: if
        if method == 'conservative':
            dstgrid = Regrid.create_cartesian_grid(coords_ext + coords_d,
                                                   dst_mask, use_bounds=True)
        else:
            dstgrid = Regrid.create_cartesian_grid(coords_ext + coords_d,
                                                   dst_mask, use_bounds=False)

        dstfield = Regrid.create_field(dstgrid, 'dstfield')
        dstfracfield = Regrid.create_field(dstgrid, 'dstfracfield')
        
        def initialise_regridder(src_mask=None):
            '''
            Initialise the source grid and the regridder.
            '''
            # Initialise the source grid
            if method == 'conservative':
                srcgrid = Regrid.create_cartesian_grid(coords_ext + coords_s,
                                                       src_mask, use_bounds=True)
            else:
                srcgrid = Regrid.create_cartesian_grid(coords_ext + coords_s,
                                                       src_mask, use_bounds=False)
            srcfield = Regrid.create_field(srcgrid, 'srcfield')
            srcfracfield = Regrid.create_field(srcgrid, 'srcfracfield')
            
            # Initialise the regridder
            regridSrc2Dst = Regrid(srcfield, dstfield, srcfracfield,
                                   dstfracfield, method=method)
            
            return srcgrid, srcfield, srcfracfield, regridSrc2Dst
        
        # Regrid each segment.
        old_mask = None
        unmasked_grid_created = False
        for k in sections.keys():
            d = sections[k]
            subsections = d.Data.section(axis_positions_s, chunks=True,
                                         min_step=2)
            for k2 in subsections.keys():
                d2 = subsections[k2]
                # Retrieve the source field's grid, create the ESMPy grid and a
                # handle to regridding.
                src_data = d2.squeeze().transpose(order_s_ext).array
                if linear:
                    src_data = numpy_tile(src_data, (2,1))
                if numpy_is_masked(src_data):
                    mask = src_data.mask
                    if not numpy_array_equal(mask, old_mask):
                        # Release old memory
                        if old_mask is not None:
                            regridSrc2Dst.destroy()
                            srcfracfield.destroy()
                            srcfield.destroy()
                            srcgrid.destroy()
                        #--- End: if
                        
                        # (Re)initialise the regridder
                        srcgrid, srcfield, srcfracfield, regridSrc2Dst = \
                            initialise_regridder(mask)
                        old_mask = mask
                    #--- End: if
                else:
                    if not unmasked_grid_created or old_mask is not None:
                        # Initialise the regridder
                        srcgrid, srcfield, srcfracfield, regridSrc2Dst = \
                            initialise_regridder()
                        unmasked_grid_created = True
                        old_mask = None
                    #--- End: if
                #--- End: if
                
                # Fill the source and destination fields and regrid
                srcfield.data[...] = numpy_MaskedArray(src_data, copy=False).filled(self.fill_value(default='netCDF'))
                dstfield.data[...] = self.fill_value(default='netCDF')
                dstfield = regridSrc2Dst.run_regridding(srcfield, dstfield)
                
                # Check field mass
                if _compute_field_mass is not None and method == 'conservative':
                    if not type(_compute_field_mass) == dict:
                        raise ValueError('Expected compute_field_mass to be a dictoinary.')
                    srcareafield = Regrid.create_field(srcgrid, 'srcareafield')
                    srcmass = Regrid.compute_mass_grid(srcfield, srcareafield,
                                                       dofrac=True,
                                                       fracfield=srcfracfield,
                                                       uninitval=self.fill_value(default='netCDF'))
                    dstareafield = Regrid.create_field(dstgrid, 'dstareafield')
                    dstmass = Regrid.compute_mass_grid(dstfield, dstareafield,
                                                   uninitval=self.fill_value(default='netCDF'))
                    _compute_field_mass[k] = (srcmass, dstmass)
                
                # Correct destination field data if doing conservative regridding
                # and add mask
                if method == 'conservative':
                    frac = dstfracfield.data[...]
                    frac[frac == 0.0] = 1.0
                    regridded_data = numpy_MaskedArray(dstfield.data[...].copy()/frac,
                                                       mask=(dstfield.data ==
                                                             self.fill_value(default='netCDF')))
                else:
                    regridded_data = numpy_MaskedArray(dstfield.data[...].copy(),
                                                       mask=(dstfield.data ==
                                                             self.fill_value(default='netCDF')))
                
                if linear:
                    regridded_data = regridded_data[0]
                
                # Insert regridded data, with axes in correct order
                subsections[k2] = Data(regridded_data.squeeze().transpose(order_s_ext).reshape(shape),
                                       units=self.Units)
            #--- End: for
            sections[k] = Regrid.reconstruct_sectioned_data(subsections)
        #--- End: for
        
        # Construct new data from regridded sections
        new_data = Regrid.reconstruct_sectioned_data(sections)
        
        # Construct new field
        if i:
            f = self
        else:
            f = self.copy(_omit_Data=True)
        #--- End:if
        
        # Update ancillary variables and coordinate references of source
        f._conform_ancillary_variables(axis_keys_s, keep_size_1=False)
        for key, ref in f.refs().iteritems():
            tmp = f.domain.ref_axes(key)
            if tmp.intersection(axis_keys_s):
                f.remove_item(key)
            else:
                for term, value in ref.iteritems():
                    if not isinstance(value, type(self)):
                        continue 
                    
                    tmp2 = value.axes(axes)
                    if tmp2 and len(tmp2) < n_axes:
                        ref[term] = None
                    elif len(tmp2) == n_axes:
                        # FOR NOW only want to do this if value spans all axes
                        # IN FUTURE: any subset
                        try:
                            value2 = value.regridc(dst, axes=axes,
                                                   method=method,
                                                   use_dst_mask=use_dst_mask,
                                                   i=i)
                        except ValueError:
                            ref[term] = None
                        else:
                            ref[term] = value2
                    #--- End: if
                #--- End: for
            #--- End: if
        #--- End: for
                        
        # Remove src coordinates of new field
        f.remove_items(axes=axes)
        
        # Make axes map
        if not dst_dict:
            axis_map = {}
            for k_s, k_d in zip(axis_keys_s, axis_keys_d):
                axis_map[k_d] = k_s
            #--- End: for
        #--- End: if
        
        # Insert coordinates from dst into new field
        if dst_dict:
            for k_s, d in zip(axis_keys_s, coords_d):
                f.domain._axes_sizes[k_s] = d.size
                f.insert_dim(d, key=k_s)
            #--- End: for
        else:
            for k_d in axis_keys_d:
                d = dst.dim(k_d)
                k_s = axis_map[k_d]
                f.domain._axes_sizes[k_s] = d.size
                f.insert_dim(d, key=k_s)
            #--- End: for
            for aux_key, aux in dst.auxs(axes_superset=axes).iteritems():
                tmp = [axis_map[k_d] for k_d in dst.domain.item_axes(aux_key)]
                f.insert_aux(aux, axes=tmp)
            #--- End: for
        #--- End: if
        
        # Copy across the destination fields coordinate references if necessary
        if not dst_dict:
            for key, ref in dst.refs().iteritems():
                tmp = dst.domain.ref_axes(key)
                if tmp and tmp.issubset(axis_keys_d):
                    f.insert_ref(ref.copy(domain=dst.domain))
                #--- End: if
            #--- End: for
        #--- End: if
                
        # Insert regridded data into new field
        f.insert_data(new_data)
        
        # Release old memory
        regridSrc2Dst.destroy()
        dstfracfield.destroy()
        srcfracfield.destroy()
        dstfield.destroy()
        srcfield.destroy()
        dstgrid.destroy()
        srcgrid.destroy()
        
        return f
    #--- End: def

#--- End: class


# ====================================================================
#
# SubspaceField object
#
# ====================================================================

class SubspaceField(SubspaceVariable):
    '''

An object which will get or set a subspace of a field.

The returned object is a `!SubspaceField` object which may be indexed
to select a subspace by axis index values (``f.subspace[indices]``) or
called to select a subspace by coordinate object array values
(``f.subspace(**coordinate_values)``).

**Subspacing by indexing**

Subspacing by indices allows a subspaced field to be defined via index
values for the axes of the field's data array.

Indices have an extended Python slicing syntax, which is similar to
:ref:`numpy array indexing <numpy:arrays.indexing>`, but with two
important extensions:

* Size 1 axes are never removed.

  An integer index i takes the i-th element but does not reduce the
  rank of the output array by one:

* When advanced indexing is used on more than one axis, the advanced
  indices work independently.

  When more than one axis's slice is a 1-d boolean sequence or 1-d
  sequence of integers, then these indices work independently along
  each axis (similar to the way vector subscripts work in Fortran),
  rather than by their elements:

**Subspacing by coordinate values**

Subspacing by values of one dimensional coordinate objects allows a
subspaced field to be defined via coordinate values of its domain.

Coordinate objects and their values are provided as keyword arguments
to a call to a `SubspaceField` object. Coordinate objects may be
identified by their identities, as returned by their `!identity`
methods. See `cf.Field.indices` for details, since
``f.subspace(**coordinate_values)`` is exactly equivalent to
``f.subspace[f.indices(**coordinate_values)]``.

**Assignment to subspaces**

Elements of a field's data array may be changed by assigning values to
a subspace of the field.

Assignment is only possible to a subspace defined by indices of the
returned `!SubspaceField` object. For example, ``f.subspace[indices] =
0`` is possible, but ``f.subspace(**coordinate_values) = 0`` is *not*
allowed. However, assigning to a subspace defined by coordinate values
may be done as follows: ``f.subspace[f.indices(**coordinate_values)] =
0``.

**Missing data**

The treatment of missing data elements during assignment to a subspace
depends on the value of field's `hardmask` attribute. If it is True
then masked elements will not be unmasked, otherwise masked elements
may be set to any value.

In either case, unmasked elements may be set, (including missing
data).

Unmasked elements may be set to missing data by assignment to the
`cf.masked` constant or by assignment to a value which contains masked
elements.

.. seealso:: `cf.masked`, `hardmask`, `indices`, `where`

:Examples:

>>> print f
Data            : air_temperature(time(12), latitude(73), longitude(96)) K
Cell methods    : time: mean
Dimensions      : time(12) = [15, ..., 345] days since 1860-1-1
                : latitude(73) = [-90, ..., 90] degrees_north
                : longitude(96) = [0, ..., 356.25] degrees_east
                : height(1) = [2] m

>>> f.shape
(12, 73, 96)
>>> f.subspace[...].shape
(12, 73, 96)
>>> f.subspace[slice(0, 12), :, 10:0:-2].shape
(12, 73, 5)
>>> lon = f.coord('X').array
>>> f.subspace[..., lon<180]

>>> f.shape
(12, 73, 96)
>>> f.subspace[0, ...].shape
(1, 73, 96)
>>> f.subspace[3, slice(10, 0, -2), 95].shape
(1, 5, 1)

>>> f.shape
(12, 73, 96)
>>> f.subspace[:, [0, 72], [5, 4, 3]].shape
(12, 2, 3)

>>> f.subspace().shape
(12, 73, 96)
>>> f.subspace(latitude=0).shape
(12, 1, 96)
>>> f.subspace(latitude=cf.wi(-30, 30)).shape
(12, 25, 96)
>>> f.subspace(long=cf.ge(270, 'degrees_east'), lat=cf.set([0, 2.5, 10])).shape
(12, 3, 24)
>>> f.subspace(latitude=cf.lt(0, 'degrees_north'))
(12, 36, 96)
>>> f.subspace(latitude=[cf.lt(0, 'degrees_north'), 90])
(12, 37, 96)
>>> import math
>>> f.subspace(longitude=cf.lt(math.pi, 'radian'), height=2)
(12, 73, 48)
>>> f.subspace(height=cf.gt(3))
IndexError: No indices found for 'height' values gt 3

>>> f.subspace(dim2=3.75).shape
(12, 1, 96)

>>> f.subspace[...] = 273.15
    
>>> f.subspace[f.indices(longitude=cf.wi(210, 270, 'degrees_east'),
...                      latitude=cf.wi(-5, 5, 'degrees_north'))] = cf.masked

>>> index = f.indices(longitude=0)
>>> f.subspace[index] = f.subspace[index] * 2

'''
    __slots__ = []

    def __call__(self, *exact, **kwargs):
        '''

Return a subspace of the field defined by coordinate values.

:Parameters:

    kwargs: optional
        Keyword names identify coordinates; and keyword values specify
        the coordinate values which are to be reinterpreted as indices
        to the field's data array.


~~~~~~~~~~~~~~ /??????
        Coordinates are identified by their exact identity or by their
        axis's identifier in the field's domain.

        A keyword value is a condition, or sequence of conditions,
        which is evaluated by finding where the coordinate's data
        array equals each condition. The locations where the
        conditions are satisfied are interpreted as indices to the
        field's data array. If a condition is a scalar ``x`` then this
        is equivalent to the `cf.Query` object ``cf.eq(x)``.

:Returns:

    out: `cf.{+Variable}`

:Examples:

>>> f.indices(lat=0.0, lon=0.0)
>>> f.indices(lon=cf.lt(0.0), lon=cf.set([0, 3.75]))
>>> f.indices(lon=cf.lt(0.0), lon=cf.set([0, 356.25]))
>>> f.indices(lon=cf.lt(0.0), lon=cf.set([0, 3.75, 356.25]))

'''
        field = self.variable

        if not kwargs:
            return field.copy()    

        # List functionality
        if field._list:
            return type(field)([f.subspace(*exact, **kwargs) for f in field])

        return field.subspace[field.indices(*exact, **kwargs)]
    #--- End: def

    def __getitem__(self, indices):
        '''

Called to implement evaluation of x[indices].

x.__getitem__(indices) <==> x[indices]

Returns a `cf.Field` object.

'''
        field = self.variable

        if indices is Ellipsis:
            return field.copy()

        # List functionality
        if field._list:
            return type(field)([f.subspace[indices] for f in field])

        data = field.Data
        shape = data.shape

        # Parse the index
        indices, roll = parse_indices(field, indices, True)

        if roll:
            axes = data._axes
            cyclic_axes = data._cyclic
            for iaxis, shift in roll.iteritems():
                if axes[iaxis] not in cyclic_axes:
                    raise IndexError(
                        "Can't take a cyclic slice from non-cyclic %r axis" %
                        field.axis_name(iaxis))

                field = field.roll(iaxis, shift)
            #--- End: for
            new = field
        else:            
            new = field.copy(_omit_Data=True)

#        cyclic_axes = []
#        for i, axis in field.data_axes():
#            if field.iscyclic(axis):
#                cyclic_axes.append(i)                
#
#        indices, roll = parse_indices(field, indices, cyclic_axes)
#
#        if roll:
#            for iaxis, x in roll.iteritems():
#                field = field.roll(iaxis, x)
#
#            new = field
#        else:            
#            # Initialise the output field
#            new = field.copy(_omit_Data=True)
        
        # Initialise the output field
#        new = field.copy(_omit_Data=True)

        ## Work out if the indices are equivalent to Ellipsis and
        ## return if they are.
        #ellipsis = True
        #for index, size in izip(indices, field.shape):
        #    if index.step != 1 or index.stop-index.start != size:
        #        ellipsis = False
        #        break
        ##--- End: for
        #if ellipsis:
        #    return new

        # ------------------------------------------------------------
        # Subspace the field's data
        # ------------------------------------------------------------
        new.Data = field.Data[tuple(indices)]
        
        domain = new.domain

        data_axes = domain.data_axes()

        # ------------------------------------------------------------
        # Subspace ancillary variables.
        # 
        # If this is not possible for a particular ancillary variable
        # then it will be discarded from the output field.
        # ------------------------------------------------------------
        if hasattr(field, 'ancillary_variables'):
            new.ancillary_variables = FieldList()

            for av in field.ancillary_variables:
                axis_map = av.domain.map_axes(field.domain)
                av_indices = []
                flip_axes = []

                for avaxis in av.domain.data_axes(): #dimensions['data']:
                    if av.domain._axes_sizes[avaxis] == 1:
                        # Size 1 axes are always ok
                        av_indices.append(slice(None))
                        continue

                    if avaxis not in axis_map:
                        # Unmatched size > 1 axes are not ok
                        av_indices = None
                        break

                    faxis = axis_map[avaxis]
                    if faxis in data_axes:
                        # Matched axes spanning the data arrays are ok
                        i = data_axes.index(faxis)
                        av_indices.append(indices[i])
                        if av.domain.direction(avaxis) != domain.direction(faxis):
                            flip_axes.append(avaxis)
                    else:
                        av_indices = None
                        break                      
                #--- End: for

                if av_indices is not None:
                    # We have successfully matched up each axis of the
                    # ancillary variable's data array with a unique
                    # axis in the parent field's data array, so we can
                    # keep a subspace of this ancillary field
                    if flip_axes:
                        av = av.flip(flip_axes)

                    new.ancillary_variables.append(av.subspace[tuple(av_indices)])
            #--- End: for

            if not new.ancillary_variables:
                del new.ancillary_variables
        #--- End: if

        # ------------------------------------------------------------
        # Subspace fields in coordinate references
        # ------------------------------------------------------------
        refs = new.refs()
        if refs:
            broken = []

            for key, ref in refs.iteritems():
                for term, variable in ref.iteritems():
                    if not isinstance(variable, Field):
                        continue

                    # Still here? Then try to subspace a formula_terms
                    # field.
                    dim_map = variable.domain.map_axes(domain)
                    v_indices = []
                    flip_dims = []

                    for vdim in variable.domain.data_axes():
                        if variable.domain._axes_sizes[vdim] == 1:
                            # We can always index a size 1 axis of the
                            # data array
                            v_indices.append(slice(None))
                            continue
                        
                        if vdim not in dim_map:
                            # Unmatched size > 1 axes are not ok
                            v_indices = None
                            break

                        axis = dim_map[vdim]
                        data_axes = domain.data_axes()
                        if axis in data_axes:
                            # We can index a matched axis which spans
                            # the data array
                            i = data_axes.index(axis)
                            v_indices.append(indices[i])
                            if variable.domain.direction(vdim) != domain.direction(axis):
                                flip_dims.append(vdim)
                        else:
                            v_indices = None
                            break                      
                    #--- End: for

                    if v_indices is not None:
                        # This term is subspaceable
                        if flip_dims:
                            variable = variable.flip(flip_dims)

                        ref[term] = variable.subspace[tuple(v_indices)]
                    else:
                        # This term is broken
                        ref[term] = None
                #--- End: for
            #--- End: for
        #--- End: if

        # ------------------------------------------------------------
        # Subspace the coordinates and cell measures
        # ------------------------------------------------------------
        for key, item in domain.items(role=('d', 'a', 'm'),
                                      axes=data_axes).iteritems():
            item_axes = domain.item_axes(key)

            dice = []
            for axis in item_axes:
                if axis in data_axes:
                    dice.append(indices[data_axes.index(axis)])
                else:
                    dice.append(slice(None))
            #--- End: for

            domain._set(key, item.subspace[tuple(dice)])
        #--- End: for

        for axis, size  in izip(data_axes, new.shape):
            domain._axes_sizes[axis] = size
            
        return new
    #--- End: def

    def __setitem__(self, indices, value):
        '''

Called to implement assignment to x[indices]

x.__setitem__(indices, value) <==> x[indices]

'''
        field = self.variable

        # List functionality
        if field._list:
            for f in field:
                f.subspace[indices] = value
            return

        if isinstance(value, field.__class__):
           value = field._conform_for_assignment(value)
           value = value.Data

        elif numpy_size(value) != 1:
            raise ValueError(
                "Can't assign a size %d %r to a %s data array" %
                (numpy_size(value), value.__class__.__name__,
                 field.__class__.__name__))

        elif isinstance(value, Variable):
            value = value.Data

        field.Data[indices] = value
    #--- End: def

#--- End: class


# ====================================================================
#
# FieldList object
#
# ====================================================================

class FieldList(Field, list):
    '''An ordered sequence of fields.

Each element of a field list is a `cf.Field` object.

A field list supports the python list-like operations (such as
indexing and methods like `!append`), but not the python list
arithmetic and comparison behaviours. Any field list arithmetic and
comparison operation is applied independently to each field element,
so all of the operators defined for a field are allowed.

    '''   

    # Do not ever change this:
    _list = True

    # Do not ever change this:
    _hasData = False

    def __init__(self, fields=None):
        '''
**Initialization**

:Parameters:

    fields: (sequence of) `cf.Field`, optional
         Create a new field list with these fields.

:Examples:

>>> fl = cf.FieldList()
>>> len(fl)
0
>>> f
<CF Field: air_temperature() K>
>>> fl = cf.FieldList(f)
>>> len(fl
1
>>> fl = cf.FieldList([f, f])
>>> len(fl)
2
>>> fl = cf.FieldList(cf.FieldList([f] * 3))
>>> len(fl)
3
'''
        if fields is not None:
            self.extend(fields)         
    #--- End: def

    def __repr__(self):
        '''
Called by the :py:obj:`repr` built-in function.

x.__repr__() <==> repr(x)
'''
        
        out = [repr(f) for f in self]
        out = ',\n '.join(out)
        return '['+out+']'
    #--- End: def

    def __str__(self):
        '''
Called by the :py:obj:`str` built-in function.

x.__str__() <==> str(x)
'''
        return '\n'.join(str(f) for f in self)
    #--- End: def

    # ================================================================
    # Overloaded list methods
    # ================================================================
    def __getslice__(self, i, j):
        '''

Called to implement evaluation of f[i:j]

f.__getslice__(i, j) <==> f[i:j]

:Examples 1:

>>> g = f[0:1]
>>> g = f[1:-4]
>>> g = f[:1]
>>> g = f[1:]

:Returns:

    out: `cf.FieldList`

'''
        return type(self)(list.__getslice__(self, i, j))
    #--- End: def

    def __getitem__(self, index):
        '''

Called to implement evaluation of f[index]

f.__getitem_(index) <==> f[index]

:Examples 1:

>>> g = f[0]
>>> g = f[-1:-4:-1]
>>> g = f[2:2:2]

:Returns:

    out: `cf.Field` or `cf.FieldList`
        If *index* is an integer then a field is returned. If *index*
        is a slice then a field list is returned, which may be empty.

'''
        out = list.__getitem__(self, index)
        if isinstance(out, list):
            return type(self)(out)
        return out
    #--- End: def

    __len__     = list.__len__
    __setitem__ = list.__setitem__    
    append      = list.append
    extend      = list.extend
    insert      = list.insert
    pop         = list.pop
    reverse     = list.reverse
    sort        = list.sort


    def __contains__(self, y):
        '''

Called to implement membership test operators.

x.__contains__(y) <==> y in x

Each field in the field list is compared with the field's
`~cf.Field.equals` method (as aopposed to the ``==`` operator).

Note that ``y in x`` is equivalent to ``any(g.equals(x) for g in f)``.

'''
        for f in self:
            if f.equals(y):
                return True
        return False
    #--- End: def

    def count(self, x):
        '''

L.count(value) -- return number of occurrences of value

Each field in the {+variable} is compared to *x* with the field's
`~cf.Field.equals` method (as opposed to the ``==`` operator).

Note that ``f.count(x)`` is equivalent to ``sum(g.equals(x) for g in
f)``.

.. seealso:: `cf.Field.equals`, :py:obj:`list.count`

:Examples:

>>> f = cf.FieldList([a, b, c, a])
>>> f.count(a)
2
>>> f.count(b)
1
>>> f.count(a+1)
0

'''
        return len([None for f in self if f.equals(x)])
    #--- End def

    def index(self, x, start=0, stop=None):
        '''
L.index(value, [start, [stop]]) -- return first index of value.

Each field in the {+variable} is compared with the field's
`~cf.Field.equals` method (as aopposed to the ``==`` operator).

It is an error if there is no such field.

.. seealso:: :py:obj:`list.index`

:Examples:

>>> 

'''      
        if start < 0:
            start = len(self) + start

        if stop is None:
            stop = len(self)
        elif stop < 0:
            stop = len(self) + stop

        for i, f in enumerate(self[start:stop]):
            if f.equals(x):
               return i + start
        #--- End: for

        raise ValueError(
            "{0!r} is not in {1}".format(x, self.__class__.__name__))
    #--- End: def

    def remove(self, x):
        '''
L.remove(value) -- remove first occurrence of value.

Each field in the {+variable} is compared with the field's
`~cf.Field.equals` method (as aopposed to the ``==`` operator).

It is an error if there is no such field.

.. seealso:: :py:obj:`list.remove`

'''
        for i, f in enumerate(self):
            if f.equals(x):
                del self[i]
                return

        raise ValueError(
            "{0}.remove(x): x not in {0}".format(self.__class__.__name__))
    #--- End: def

    # ================================================================
    # Special methods
    # ================================================================
    def __array__(self): self._forbidden('special method', '__array__')
    def __data__(self): self._forbidden('special method', '__data__')

    # ================================================================
    # Private methods
    # ================================================================
    def _binary_operation(self, y, method):
        if isinstance(y, self.__class__):
            if len(y) != 1:
                raise ValueError(
                    "Can't {0}: Incompatible {1} lengths ({2}, {3})".format(
                        method, self.__class__.__name__, len(self), len(y)))
            y = y[0]


        if method[2] == 'i':
            # In place
            for f in self:
                f._binary_operation(y, method)
            return self
        else:         
            # Not in place
            return type(self)([f._binary_operation(y, method) for f in self])
    #--- End: def

    def _unary_operation(self, method):
        return type(self)([f._unary_operation(method) for f in self])
    #--- End: def

    def _forbidden(self, x, name):
        raise AttributeError(
            "{0} has no {1} {2!r}. {2!r} may be accessed on each field element.".format(
                self.__class__.__name__, x, name))
    #--- End: def

    # ================================================================
    # CF properties
    # ================================================================
    @property
    def add_offset(self): self._forbidden('CF property', 'add_offset')
    @property
    def calendar(self): self._forbidden('CF property', 'calendar')
    @property
    def cell_methods(self): self._forbidden('CF property', 'cell_methods')
    @property
    def comment(self): self._forbidden('CF property', 'comment')
    @property
    def Conventions(self): self._forbidden('CF property', 'Conventions')
    @property
    def _FillValue(self): self._forbidden('CF property', '_FillValue')
    @property
    def flag_masks(self): self._forbidden('CF property', 'flag_masks')
    @property
    def flag_meanings(self): self._forbidden('CF property', 'flag_meanings')
    @property
    def flag_values(self): self._forbidden('CF property', 'flag_values')
    @property
    def history(self): self._forbidden('CF property', 'history')
    @property
    def institution(self): self._forbidden('CF property', 'institution')
    @property
    def leap_month(self): self._forbidden('CF property', 'leap_month')
    @property
    def leap_year(self): self._forbidden('CF property', 'leap_year')
    @property
    def long_name(self): self._forbidden('CF property', 'long_name')
    @property
    def missing_value(self): self._forbidden('CF property', 'missing_value')
    @property
    def month_lengths(self): self._forbidden('CF property', 'month_lengths')
    @property
    def references(self): self._forbidden('CF property', 'references')
    @property
    def scale_factor(self): self._forbidden('CF property', 'scale_factor')
    @property
    def source(self): self._forbidden('CF property', 'source')
    @property
    def standard_error_multiplier(self): self._forbidden('CF property', 'standard_error_multiplier')
    @property
    def standard_name(self): self._forbidden('CF property', 'standard_name')
    @property
    def title(self): self._forbidden('CF property', 'title')
    @property
    def units(self): self._forbidden('CF property', 'units')
    @property
    def valid_max(self): self._forbidden('CF property', 'valid_max')
    @property
    def valid_min(self): self._forbidden('CF property', 'valid_min')
    @property
    def valid_range(self): self._forbidden('CF property', 'valid_range')

    # ================================================================
    # Attributes
    # ================================================================
    @property
    def ancillary_variables(self): self._forbidden('attribute', '')
    @property
    def array(self): self._forbidden('attribute', 'array')
    @property
    def attributes(self): self._forbidden('attribute', 'attributes')
    @property
    def Data(self): self._forbidden('attribute', 'Data')
    @property
    def data(self): self._forbidden('attribute', 'data')
    @property
    def day(self): self._forbidden('attribute', 'day')
    @property
    def domain(self): self._forbidden('attribute', 'domain')
    @property
    def dtarray(self): self._forbidden('attribute', 'dtarray')
    @property
    def dtvarray(self): self._forbidden('attribute', 'dtvarray')
    @property
    def dtype(self): self._forbidden('attribute', 'dtype')
    @property
    def Flags(self): self._forbidden('attribute', 'Flags')
    @property
    def hardmask(self): self._forbidden('attribute', 'hardmask')
    @property
    def hour(self): self._forbidden('attribute', 'hour')
    @property
    def isscalar(self): self._forbidden('attribute', 'isscalar')
    @property
    def Flags(self): self._forbidden('attribute', 'Flags')
    @property
    def minute(self): self._forbidden('attribute', 'minute')
    @property
    def month(self): self._forbidden('attribute', 'month')
    @property
    def ndim(self): self._forbidden('attribute', 'ndim')
    @property
    def properties(self): self._forbidden('attribute', 'properties')
    @property
    def rank(self): self._forbidden('attribute', 'rank')
    @property
    def second(self): self._forbidden('attribute', 'second')
    @property
#    def subspace(self): self._forbidden('attribute', 'subspace')
#    @property
    def shape(self): self._forbidden('attribute', 'shape')
    @property
    def size(self): self._forbidden('attribute', 'size') 
    @property
    def T(self): self._forbidden('attribute', 'T')
    @property
    def Units(self): self._forbidden('attribute', 'Units')
    @property
    def varray(self): self._forbidden('attribute', 'varray')
    @property
    def X(self): self._forbidden('attribute', 'X')
    @property
    def Y(self): self._forbidden('attribute', 'Y')
    @property
    def year(self): self._forbidden('attribute', 'year')
    @property
    def Z(self): self._forbidden('attribute', 'Z')
    
    # ================================================================
    # Methods
    # ================================================================
    def all(self, *args, **kwargs): self._forbidden('method', 'all')
    def any(self, *args, **kwargs): self._forbidden('method', 'any')
    def allclose(self, *args, **kwargs): self._forbidden('method', 'allclose')
    def aux(self, *args, **kwargs): self._forbidden('method', 'aux')
    def auxs(self, *args, **kwargs): self._forbidden('method', 'auxs')
    def axes(self, *args, **kwargs): self._forbidden('method', 'axes')
    def axes_sizes(self, *args, **kwargs): self._forbidden('method', 'axes_sizes')
    def axis(self, *args, **kwargs): self._forbidden('method', 'axis')
    def axis_name(self, *args, **kwargs): self._forbidden('method', 'axis_name')
    def axis_size(self, *args, **kwargs): self._forbidden('method', 'axis_size')
    def coord(self, *args, **kwargs): self._forbidden('method', 'coord')
    def coords(self, *args, **kwargs): self._forbidden('method', 'coords')
    def cyclic(self, *args, **kwargs): self._forbidden('method', 'cyclic')
    def data_axes(self, *args, **kwargs): self._forbidden('method', 'data_axes')
    def dim(self, *args, **kwargs): self._forbidden('method', 'dim')
    def dims(self, *args, **kwargs): self._forbidden('method', 'dims')
    def field(self, *args, **kwargs): self._forbidden('method', 'field')
    def iscyclic(self, *args, **kwargs): self._forbidden('method', 'iscyclic')
    def insert_aux(self, *args, **kwargs): self._forbidden('method', 'insert_aux')
    def insert_axis(self, *args, **kwargs): self._forbidden('method', 'insert_axis')
    def insert_data(self, *args, **kwargs): self._forbidden('method', 'insert_data')
    def insert_dim(self, *args, **kwargs): self._forbidden('method', 'insert_dim')
    def insert_measure(self, *args, **kwargs): self._forbidden('method', 'insert_measure')
    def insert_ref(self, *args, **kwargs): self._forbidden('method', 'insert_ref')
    def indices(self, *args, **kwargs): self._forbidden('method', 'indices')
    def item(self, *args, **kwargs): self._forbidden('method', 'item')
    def item_axes(self, *args, **kwargs): self._forbidden('method', 'item_axes')
    def items(self, *args, **kwargs): self._forbidden('method', 'items')
    def items_axes(self, *args, **kwargs): self._forbidden('method', 'items_axes')
    def match(self, *args, **kwargs): self._forbidden('method', 'match')
    def max(self, *args, **kwargs): self._forbidden('method', 'max')
    def mean(self, *args, **kwargs): self._forbidden('method', 'mean')
    def measure(self, *args, **kwargs): self._forbidden('method', 'measure')
    def measures(self, *args, **kwargs): self._forbidden('method', 'measures')
    def mid_range(self, *args, **kwargs): self._forbidden('method', 'mid_range')
    def min(self, *args, **kwargs): self._forbidden('method', 'min')
    def period(self, *args, **kwargs): self._forbidden('method', 'period')
    def range(self, *args, **kwargs): self._forbidden('method', 'range')
    def ref(self, *args, **kwargs): self._forbidden('method', 'ref')
    def refs(self, *args, **kwargs): self._forbidden('method', 'refs')
    def remove_axes(self, *args, **kwargs): self._forbidden('method', 'remove_axes')
    def remove_axis(self, *args, **kwargs): self._forbidden('method', 'remove_axis')
    def remove_data(self, *args, **kwargs): self._forbidden('method', 'remove_data')
    def remove_item(self, *args, **kwargs): self._forbidden('method', 'remove_item')
    def remove_items(self, *args, **kwargs): self._forbidden('method', 'remove_items')
    def sample_size(self, *args, **kwargs): self._forbidden('method', 'sample_size')
    def sd(self, *args, **kwargs): self._forbidden('method', 'sd')
    def sum(self, *args, **kwargs): self._forbidden('method', 'sum')
    def unique(self, *args, **kwargs): self._forbidden('method', 'unique')
    def var(self, *args, **kwargs): self._forbidden('method', 'var')
    
    @property
    def binary_mask(self):
        '''For each field, a field of the binary (0 and 1) mask of the data
array.

Values of 1 indicate masked elements.

.. seealso:: `mask`

:Examples:

>>> f[0].shape
(12, 73, 96)
>>> m = f.binary_mask
>>> m[0].long_name
'binary_mask'
>>> m[0].shape
(12, 73, 96)
>>> m[0].dtype
dtype('int32')
>>> m[0].data
<CF Data: [[[1, ..., 0]]] >

        '''
        return self._list_attribute('binary_mask')
    #--- End: def


    @property
    def mask(self):
        '''For each field, a field of the mask of the data array.

Values of True indicate masked elements.

.. seealso:: `binary_mask`

:Examples:

>>> f[0].shape
(12, 73, 96)
>>> m = f.mask
>>> m[0].long_name
'mask'
>>> m[0].shape
(12, 73, 96)
>>> m[0].dtype
dtype('bool')
>>> m[0].data
<CF Data: [[[True, ..., False]]] >

        '''
        return self._list_attribute('mask')
    #--- End: def

#--- End: class