This file is indexed.

/usr/lib/python2.7/dist-packages/surfer/viz.py is in python-surfer 0.7-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
from math import floor
import os
from os.path import join as pjoin
from warnings import warn

import numpy as np
from scipy import stats, ndimage, misc
from scipy.interpolate import interp1d
from matplotlib.colors import colorConverter

import nibabel as nib

from mayavi import mlab
from mayavi.tools.mlab_scene_model import MlabSceneModel
from mayavi.core import lut_manager
from mayavi.core.ui.api import SceneEditor
from mayavi.core.ui.mayavi_scene import MayaviScene
from traits.api import (HasTraits, Range, Int, Float,
                        Bool, Enum, on_trait_change, Instance)

from . import utils, io
from .utils import (Surface, verbose, create_color_lut, _get_subjects_dir,
                    string_types)


import logging
logger = logging.getLogger('surfer')


lh_viewdict = {'lateral': {'v': (180., 90.), 'r': 90.},
               'medial': {'v': (0., 90.), 'r': -90.},
               'rostral': {'v': (90., 90.), 'r': -180.},
               'caudal': {'v': (270., 90.), 'r': 0.},
               'dorsal': {'v': (180., 0.), 'r': 90.},
               'ventral': {'v': (180., 180.), 'r': 90.},
               'frontal': {'v': (120., 80.), 'r': 106.739},
               'parietal': {'v': (-120., 60.), 'r': 49.106}}
rh_viewdict = {'lateral': {'v': (180., -90.), 'r': -90.},
               'medial': {'v': (0., -90.), 'r': 90.},
               'rostral': {'v': (-90., -90.), 'r': 180.},
               'caudal': {'v': (90., -90.), 'r': 0.},
               'dorsal': {'v': (180., 0.), 'r': 90.},
               'ventral': {'v': (180., 180.), 'r': 90.},
               'frontal': {'v': (60., 80.), 'r': -106.739},
               'parietal': {'v': (-60., 60.), 'r': -49.106}}
viewdicts = dict(lh=lh_viewdict, rh=rh_viewdict)


def make_montage(filename, fnames, orientation='h', colorbar=None,
                 border_size=15):
    """Save montage of current figure

    Parameters
    ----------
    filename : str
        The name of the file, e.g, 'montage.png'. If None, the image
        will not be saved.
    fnames : list of str | list of array
        The images to make the montage of. Can be a list of filenames
        or a list of image data arrays.
    orientation : 'h' | 'v' | list
        The orientation of the montage: horizontal, vertical, or a nested
        list of int (indexes into fnames).
    colorbar : None | list of int
        If None remove colorbars, else keep the ones whose index
        is present.
    border_size : int
        The size of the border to keep.

    Returns
    -------
    out : array
        The montage image data array.
    """
    try:
        import Image
    except ImportError:
        from PIL import Image
    # This line is only necessary to overcome a PIL bug, see:
    #     http://stackoverflow.com/questions/10854903/what-is-causing-
    #          dimension-dependent-attributeerror-in-pil-fromarray-function
    fnames = [f if isinstance(f, string_types) else f.copy() for f in fnames]
    if isinstance(fnames[0], string_types):
        images = list(map(Image.open, fnames))
    else:
        images = list(map(Image.fromarray, fnames))
    # get bounding box for cropping
    boxes = []
    for ix, im in enumerate(images):
        # sum the RGB dimension so we do not miss G or B-only pieces
        gray = np.sum(np.array(im), axis=-1)
        gray[gray == gray[0, 0]] = 0  # hack for find_objects that wants 0
        if np.all(gray == 0):
            raise ValueError("Empty image (all pixels have the same color).")
        labels, n_labels = ndimage.label(gray.astype(np.float))
        slices = ndimage.find_objects(labels, n_labels)  # slice roi
        if colorbar is not None and ix in colorbar:
            # we need all pieces so let's compose them into single min/max
            slices_a = np.array([[[xy.start, xy.stop] for xy in s]
                                 for s in slices])
            # TODO: ideally gaps could be deduced and cut out with
            #       consideration of border_size
            # so we need mins on 0th and maxs on 1th of 1-nd dimension
            mins = np.min(slices_a[:, :, 0], axis=0)
            maxs = np.max(slices_a[:, :, 1], axis=0)
            s = (slice(mins[0], maxs[0]), slice(mins[1], maxs[1]))
        else:
            # we need just the first piece
            s = slices[0]
        # box = (left, top, width, height)
        boxes.append([s[1].start - border_size, s[0].start - border_size,
                      s[1].stop + border_size, s[0].stop + border_size])
    # convert orientation to nested list of int
    if orientation == 'h':
        orientation = [range(len(images))]
    elif orientation == 'v':
        orientation = [[i] for i in range(len(images))]
    # find bounding box
    n_rows = len(orientation)
    n_cols = max(len(row) for row in orientation)
    if n_rows > 1:
        min_left = min(box[0] for box in boxes)
        max_width = max(box[2] for box in boxes)
        for box in boxes:
            box[0] = min_left
            box[2] = max_width
    if n_cols > 1:
        min_top = min(box[1] for box in boxes)
        max_height = max(box[3] for box in boxes)
        for box in boxes:
            box[1] = min_top
            box[3] = max_height
    # crop images
    cropped_images = []
    for im, box in zip(images, boxes):
        cropped_images.append(im.crop(box))
    images = cropped_images
    # Get full image size
    row_w = [sum(images[i].size[0] for i in row) for row in orientation]
    row_h = [max(images[i].size[1] for i in row) for row in orientation]
    out_w = max(row_w)
    out_h = sum(row_h)
    # compose image
    new = Image.new("RGBA", (out_w, out_h))
    y = 0
    for row, h in zip(orientation, row_h):
        x = 0
        for i in row:
            im = images[i]
            pos = (x, y)
            new.paste(im, pos)
            x += im.size[0]
        y += h
    if filename is not None:
        try:
            new.save(filename)
        except Exception:
            print("Error saving %s" % filename)
    return np.array(new)


def _prepare_data(data):
    """Ensure data is float64 and has proper endianness.

    Note: this is largely aimed at working around a Mayavi bug.

    """
    data = data.copy()
    data = data.astype(np.float64)
    if data.dtype.byteorder == '>':
        data.byteswap(True)
    return data


def _force_render(figures, backend):
    """Ensure plots are updated before properties are used"""
    if not isinstance(figures, list):
        figures = [[figures]]
    for ff in figures:
        for f in ff:
            f.render()
            mlab.draw(figure=f)
    if backend == 'TraitsUI':
        from pyface.api import GUI
        _gui = GUI()
        orig_val = _gui.busy
        _gui.set_busy(busy=True)
        _gui.process_events()
        _gui.set_busy(busy=orig_val)
        _gui.process_events()


def _make_viewer(figure, n_row, n_col, title, scene_size, offscreen):
    """Triage viewer creation

    If n_row == n_col == 1, then we can use a Mayavi figure, which
    generally guarantees that things will be drawn before control
    is returned to the command line. With the multi-view, TraitsUI
    unfortunately has no such support, so we only use it if needed.
    """
    if figure is None:
        # spawn scenes
        h, w = scene_size
        if offscreen is True:
            orig_val = mlab.options.offscreen
            mlab.options.offscreen = True
            figures = [[mlab.figure(size=(h / n_row, w / n_col))
                        for _ in range(n_col)] for __ in range(n_row)]
            mlab.options.offscreen = orig_val
            _v = None
        else:
            # Triage: don't make TraitsUI if we don't have to
            if n_row == 1 and n_col == 1:
                figure = mlab.figure(title, size=(w, h))
                mlab.clf(figure)
                figures = [[figure]]
                _v = None
            else:
                window = _MlabGenerator(n_row, n_col, w, h, title)
                figures, _v = window._get_figs_view()
    else:
        if not isinstance(figure, (list, tuple)):
            figure = [figure]
        if not len(figure) == n_row * n_col:
            raise ValueError('For the requested view, figure must be a '
                             'list or tuple with exactly %i elements, '
                             'not %i' % (n_row * n_col, len(figure)))
        _v = None
        figures = [figure[slice(ri * n_col, (ri + 1) * n_col)]
                   for ri in range(n_row)]
    return figures, _v


class _MlabGenerator(HasTraits):
    """TraitsUI mlab figure generator"""
    from traitsui.api import View
    view = Instance(View)

    def __init__(self, n_row, n_col, width, height, title, **traits):
        HasTraits.__init__(self, **traits)
        self.mlab_names = []
        self.n_row = n_row
        self.n_col = n_col
        self.width = width
        self.height = height
        for fi in range(n_row * n_col):
            name = 'mlab_view%03g' % fi
            self.mlab_names.append(name)
            self.add_trait(name, Instance(MlabSceneModel, ()))
        self.view = self._get_gen_view()
        self._v = self.edit_traits(view=self.view)
        self._v.title = title

    def _get_figs_view(self):
        figures = []
        ind = 0
        for ri in range(self.n_row):
            rfigs = []
            for ci in range(self.n_col):
                x = getattr(self, self.mlab_names[ind])
                rfigs.append(x.mayavi_scene)
                ind += 1
            figures.append(rfigs)
        return figures, self._v

    def _get_gen_view(self):
        from traitsui.api import (View, Item, VGroup, HGroup)
        ind = 0
        va = []
        for ri in range(self.n_row):
            ha = []
            for ci in range(self.n_col):
                ha += [Item(name=self.mlab_names[ind], style='custom',
                            resizable=True, show_label=False,
                            editor=SceneEditor(scene_class=MayaviScene))]
                ind += 1
            va += [HGroup(*ha)]
        view = View(VGroup(*va), resizable=True,
                    height=self.height, width=self.width)
        return view


class Brain(object):
    """Class for visualizing a brain using multiple views in mlab

    Parameters
    ----------
    subject_id : str
        subject name in Freesurfer subjects dir
    hemi : str
        hemisphere id (ie 'lh', 'rh', 'both', or 'split'). In the case
        of 'both', both hemispheres are shown in the same window.
        In the case of 'split' hemispheres are displayed side-by-side
        in different viewing panes.
    surf :  geometry name
        freesurfer surface mesh name (ie 'white', 'inflated', etc.)
    title : str
        title for the window
    cortex : str, tuple, dict, or None
        Specifies how the cortical surface is rendered. Options:

            1. The name of one of the preset cortex styles:
               ``'classic'`` (default), ``'high_contrast'``,
               ``'low_contrast'``, or ``'bone'``.
            2. A color-like argument to render the cortex as a single
               color, e.g. ``'red'`` or ``(0.1, 0.4, 1.)``. Setting
               this to ``None`` is equivalent to ``(0.5, 0.5, 0.5)``.
            3. The name of a colormap used to render binarized
               curvature values, e.g., ``Grays``.
            4. A list of colors used to render binarized curvature
               values. Only the first and last colors are used. E.g.,
               ['red', 'blue'] or [(1, 0, 0), (0, 0, 1)].
            5. A container with four entries for colormap (string
               specifiying the name of a colormap), vmin (float
               specifying the minimum value for the colormap), vmax
               (float specifying the maximum value for the colormap),
               and reverse (bool specifying whether the colormap
               should be reversed. E.g., ``('Greys', -1, 2, False)``.
            6. A dict of keyword arguments that is passed on to the
               call to surface.
    alpha : float in [0, 1]
        Alpha level to control opacity of the cortical surface.
    size : float or pair of floats
        the size of the window, in pixels. can be one number to specify
        a square window, or the (width, height) of a rectangular window.
    background, foreground : matplotlib colors
        color of the background and foreground of the display window
    figure : list of instances of mayavi.core.scene.Scene | None
        If None, a new window will be created with the appropriate
        views.
    subjects_dir : str | None
        If not None, this directory will be used as the subjects directory
        instead of the value set using the SUBJECTS_DIR environment
        variable.
    views : list | str
        views to use
    offset : bool
        If True, aligs origin with medial wall. Useful for viewing inflated
        surface where hemispheres typically overlap (Default: True)
    show_toolbar : bool
        If True, toolbars will be shown for each view.
    offscreen : bool
        If True, rendering will be done offscreen (not shown). Useful
        mostly for generating images or screenshots, but can be buggy.
        Use at your own risk.

    Attributes
    ----------
    brains : list
        List of the underlying brain instances.

    """
    def __init__(self, subject_id, hemi, surf, title=None,
                 cortex="classic", alpha=1.0, size=800, background="black",
                 foreground="white", figure=None, subjects_dir=None,
                 views=['lat'], offset=True, show_toolbar=False,
                 offscreen=False, config_opts=None, curv=None):

        # Keep backwards compatability
        if config_opts is not None:
            msg = ("The `config_opts` dict has been deprecated and will "
                   "be removed in future versions. You should update your "
                   "code and pass these options directly to the `Brain` "
                   "constructor.")
            warn(msg, DeprecationWarning)
            cortex = config_opts.get("cortex", cortex)
            background = config_opts.get("background", background)
            foreground = config_opts.get("foreground", foreground)

            size = config_opts.get("size", size)
            width = config_opts.get("width", size)
            height = config_opts.get("height", size)
            size = (width, height)
        # Keep backwards compatability
        if curv is not None:
            msg = ("The `curv` keyword has been deprecated and will "
                   "be removed in future versions. You should update your "
                   "code and use the `cortex` keyword to specify how the "
                   "brain surface is rendered. Setting `cortex` to `None` "
                   "will reproduce the previous behavior when `curv` was "
                   "set to `False`. To emulate the previous behavior for "
                   "cases where `curv` was set to `True`, simply omit it.")
            warn(msg, DeprecationWarning)
            if not curv:
                cortex = None

        col_dict = dict(lh=1, rh=1, both=1, split=2)
        n_col = col_dict[hemi]
        if hemi not in col_dict.keys():
            raise ValueError('hemi must be one of [%s], not %s'
                             % (', '.join(col_dict.keys()), hemi))
        # Get the subjects directory from parameter or env. var
        subjects_dir = _get_subjects_dir(subjects_dir=subjects_dir)

        self._hemi = hemi
        if title is None:
            title = subject_id
        self.subject_id = subject_id

        if not isinstance(views, list):
            views = [views]
        n_row = len(views)

        # load geometry for one or both hemispheres as necessary
        offset = None if (not offset or hemi != 'both') else 0.0
        self.geo = dict()
        if hemi in ['split', 'both']:
            geo_hemis = ['lh', 'rh']
        elif hemi == 'lh':
            geo_hemis = ['lh']
        elif hemi == 'rh':
            geo_hemis = ['rh']
        else:
            raise ValueError('bad hemi value')
        geo_kwargs, geo_reverse, geo_curv = self._get_geo_params(cortex, alpha)
        for h in geo_hemis:
            # Initialize a Surface object as the geometry
            geo = Surface(subject_id, h, surf, subjects_dir, offset)
            # Load in the geometry and (maybe) curvature
            geo.load_geometry()
            if geo_curv:
                geo.load_curvature()
            self.geo[h] = geo

        # deal with making figures
        self._set_window_properties(size, background, foreground)
        figures, _v = _make_viewer(figure, n_row, n_col, title,
                                   self._scene_size, offscreen)
        self._figures = figures
        self._v = _v
        self._window_backend = 'Mayavi' if self._v is None else 'TraitsUI'
        for ff in self._figures:
            for f in ff:
                if f.scene is not None:
                    f.scene.background = self._bg_color
                    f.scene.foreground = self._fg_color

        # force rendering so scene.lights exists
        _force_render(self._figures, self._window_backend)
        self.toggle_toolbars(show_toolbar)
        _force_render(self._figures, self._window_backend)
        self._toggle_render(False)

        # fill figures with brains
        kwargs = dict(surf=surf, geo_curv=geo_curv, geo_kwargs=geo_kwargs,
                      geo_reverse=geo_reverse, subjects_dir=subjects_dir,
                      bg_color=self._bg_color)
        brains = []
        brain_matrix = []
        for ri, view in enumerate(views):
            brain_row = []
            for hi, h in enumerate(['lh', 'rh']):
                if not (hemi in ['lh', 'rh'] and h != hemi):
                    ci = hi if hemi == 'split' else 0
                    kwargs['hemi'] = h
                    kwargs['geo'] = self.geo[h]
                    kwargs['figure'] = figures[ri][ci]
                    kwargs['backend'] = self._window_backend
                    brain = _Hemisphere(subject_id, **kwargs)
                    brain.show_view(view)
                    brains += [dict(row=ri, col=ci, brain=brain, hemi=h)]
                    brain_row += [brain]
            brain_matrix += [brain_row]
        self._toggle_render(True)
        self._original_views = views
        self._brain_list = brains
        for brain in self._brain_list:
            brain['brain']._orient_lights()
        self.brains = [b['brain'] for b in brains]
        self.brain_matrix = np.array(brain_matrix)
        self.subjects_dir = subjects_dir
        # Initialize the overlay and label dictionaries
        self.foci_dict = dict()
        self.labels_dict = dict()
        self.overlays_dict = dict()
        self.contour_list = []
        self.morphometry_list = []
        self.annot_list = []
        self.data_dict = dict(lh=None, rh=None)
        # note that texts gets treated differently
        self.texts_dict = dict()
        self.n_times = None

    ###########################################################################
    # HELPERS
    def _toggle_render(self, state, views=None):
        """Turn rendering on (True) or off (False)"""
        figs = []
        [figs.extend(f) for f in self._figures]
        if views is None:
            views = [None] * len(figs)
        for vi, (_f, view) in enumerate(zip(figs, views)):
            if state is False and view is None:
                views[vi] = mlab.view(figure=_f)

            # Testing backend doesn't have this option
            if mlab.options.backend != 'test':
                _f.scene.disable_render = not state

            if state is True and view is not None:
                mlab.draw(figure=_f)
                mlab.view(*view, figure=_f)
        # let's do the ugly force draw
        if state is True:
            _force_render(self._figures, self._window_backend)
        return views

    def _set_window_properties(self, size, background, foreground):
        """Set window properties that are used elsewhere."""
        # old option "size" sets both width and height
        try:
            width, height = size
        except (TypeError, ValueError):
            width, height = size, size
        self._scene_size = height, width

        bg_color_rgb = colorConverter.to_rgb(background)
        self._bg_color = bg_color_rgb

        fg_color_rgb = colorConverter.to_rgb(foreground)
        self._fg_color = fg_color_rgb

    def _get_geo_params(self, cortex, alpha=1.0):
        """Return keyword arguments and other parameters for surface
        rendering.

        Parameters
        ----------
        cortex : {str, tuple, dict, None}
            Can be set to: (1) the name of one of the preset cortex
            styles ('classic', 'high_contrast', 'low_contrast', or
            'bone'), (2) the name of a colormap, (3) a tuple with
            four entries for (colormap, vmin, vmax, reverse)
            indicating the name of the colormap, the min and max
            values respectively and whether or not the colormap should
            be reversed, (4) a valid color specification (such as a
            3-tuple with RGB values or a valid color name), or (5) a
            dictionary of keyword arguments that is passed on to the
            call to surface. If set to None, color is set to (0.5,
            0.5, 0.5).
        alpha : float in [0, 1]
            Alpha level to control opacity of the cortical surface.

        Returns
        -------
        kwargs : dict
            Dictionary with keyword arguments to be used for surface
            rendering. For colormaps, keys are ['colormap', 'vmin',
            'vmax', 'alpha'] to specify the name, minimum, maximum,
            and alpha transparency of the colormap respectively. For
            colors, keys are ['color', 'alpha'] to specify the name
            and alpha transparency of the color respectively.
        reverse : boolean
            Boolean indicating whether a colormap should be
            reversed. Set to False if a color (rather than a colormap)
            is specified.
        curv : boolean
            Boolean indicating whether curv file is loaded and binary
            curvature is displayed.

        """
        colormap_map = dict(classic=(dict(colormap="Greys",
                                          vmin=-1, vmax=2,
                                          opacity=alpha), False, True),
                            high_contrast=(dict(colormap="Greys",
                                                vmin=-.1, vmax=1.3,
                                                opacity=alpha), False, True),
                            low_contrast=(dict(colormap="Greys",
                                               vmin=-5, vmax=5,
                                               opacity=alpha), False, True),
                            bone=(dict(colormap="bone",
                                       vmin=-.2, vmax=2,
                                       opacity=alpha), True, True))
        if isinstance(cortex, dict):
            if 'opacity' not in cortex:
                cortex['opacity'] = alpha
            if 'colormap' in cortex:
                if 'vmin' not in cortex:
                    cortex['vmin'] = -1
                if 'vmax' not in cortex:
                    cortex['vmax'] = 2
            geo_params = cortex, False, True
        elif isinstance(cortex, string_types):
            if cortex in colormap_map:
                geo_params = colormap_map[cortex]
            elif cortex in lut_manager.lut_mode_list():
                geo_params = dict(colormap=cortex, vmin=-1, vmax=2,
                                  opacity=alpha), False, True
            else:
                try:
                    color = colorConverter.to_rgb(cortex)
                    geo_params = dict(color=color, opacity=alpha), False, False
                except ValueError:
                    geo_params = cortex, False, True
        # check for None before checking len:
        elif cortex is None:
            geo_params = dict(color=(0.5, 0.5, 0.5),
                              opacity=alpha), False, False
        # Test for 4-tuple specifying colormap parameters. Need to
        # avoid 4 letter strings and 4-tuples not specifying a
        # colormap name in the first position (color can be specified
        # as RGBA tuple, but the A value will be dropped by to_rgb()):
        elif (len(cortex) == 4) and (isinstance(cortex[0], string_types)):
            geo_params = dict(colormap=cortex[0], vmin=cortex[1],
                              vmax=cortex[2], opacity=alpha), cortex[3], True
        else:
            try:  # check if it's a non-string color specification
                color = colorConverter.to_rgb(cortex)
                geo_params = dict(color=color, opacity=alpha), False, False
            except ValueError:
                try:
                    lut = create_color_lut(cortex)
                    geo_params = dict(colormap="Greys", opacity=alpha,
                                      lut=lut), False, True
                except ValueError:
                    geo_params = cortex, False, True
        return geo_params

    def get_data_properties(self):
        """ Get properties of the data shown

        Returns
        -------
        props : dict
            Dictionary with data properties

            props["fmin"] : minimum colormap
            props["fmid"] : midpoint colormap
            props["fmax"] : maximum colormap
            props["transparent"] : lower part of colormap transparent?
            props["time"] : time points
            props["time_idx"] : current time index
            props["smoothing_steps"] : number of smoothing steps
        """
        props = dict()
        keys = ['fmin', 'fmid', 'fmax', 'transparent', 'time', 'time_idx',
                'smoothing_steps']
        try:
            if self.data_dict['lh'] is not None:
                hemi = 'lh'
            else:
                hemi = 'rh'
            for key in keys:
                props[key] = self.data_dict[hemi][key]
        except KeyError:
            # The user has not added any data
            for key in keys:
                props[key] = 0
        return props

    def toggle_toolbars(self, show=None):
        """Toggle toolbar display

        Parameters
        ----------
        show : bool | None
            If None, the state is toggled. If True, the toolbar will
            be shown, if False, hidden.
        """
        # don't do anything if testing is on
        if self._figures[0][0].scene is not None:
            # this may not work if QT is not the backend (?), or in testing
            if hasattr(self._figures[0][0].scene, 'scene_editor'):
                # Within TraitsUI
                bars = [f.scene.scene_editor._tool_bar
                        for ff in self._figures for f in ff]
            else:
                # Mayavi figure
                bars = [f.scene._tool_bar for ff in self._figures for f in ff]

            if show is None:
                if hasattr(bars[0], 'isVisible'):
                    # QT4
                    show = not bars[0].isVisible()
                elif hasattr(bars[0], 'Shown'):
                    # WX
                    show = not bars[0].Shown()
            for bar in bars:
                if hasattr(bar, 'setVisible'):
                    bar.setVisible(show)
                elif hasattr(bar, 'Show'):
                    bar.Show(show)

    def _get_one_brain(self, d, name):
        """Helper for various properties"""
        if len(self.brains) > 1:
            raise ValueError('Cannot access brain.%s when more than '
                             'one view is plotted. Use brain.brain_matrix '
                             'or brain.brains.' % name)
        if isinstance(d, dict):
            out = dict()
            for key, value in d.items():
                out[key] = value[0]
        else:
            out = d[0]
        return out

    @property
    def overlays(self):
        """Wrap to overlays"""
        return self._get_one_brain(self.overlays_dict, 'overlays')

    @property
    def foci(self):
        """Wrap to foci"""
        return self._get_one_brain(self.foci_dict, 'foci')

    @property
    def labels(self):
        """Wrap to labels"""
        return self._get_one_brain(self.labels_dict, 'labels')

    @property
    def contour(self):
        """Wrap to contour"""
        return self._get_one_brain(self.contour_list, 'contour')

    @property
    def annot(self):
        """Wrap to annot"""
        return self._get_one_brain(self.annot_list, 'annot')

    @property
    def texts(self):
        """Wrap to texts"""
        self._get_one_brain([[]], 'texts')
        out = dict()
        for key, val in self.texts_dict.iteritems():
            out[key] = val['text']
        return out

    @property
    def _geo(self):
        """Wrap to _geo"""
        self._get_one_brain([[]], '_geo')
        if ('lh' in self.geo) and ['lh'] is not None:
            return self.geo['lh']
        else:
            return self.geo['rh']

    @property
    def data(self):
        """Wrap to data"""
        self._get_one_brain([[]], 'data')
        if self.data_dict['lh'] is not None:
            data = self.data_dict['lh'].copy()
        else:
            data = self.data_dict['rh'].copy()
        if 'colorbars' in data:
            data['colorbar'] = data['colorbars'][0]
        return data

    def _check_hemi(self, hemi):
        """Check for safe single-hemi input, returns str"""
        if hemi is None:
            if self._hemi not in ['lh', 'rh']:
                raise ValueError('hemi must not be None when both '
                                 'hemispheres are displayed')
            else:
                hemi = self._hemi
        elif hemi not in ['lh', 'rh']:
            extra = ' or None' if self._hemi in ['lh', 'rh'] else ''
            raise ValueError('hemi must be either "lh" or "rh"' + extra)
        return hemi

    def _check_hemis(self, hemi):
        """Check for safe dual or single-hemi input, returns list"""
        if hemi is None:
            if self._hemi not in ['lh', 'rh']:
                hemi = ['lh', 'rh']
            else:
                hemi = [self._hemi]
        elif hemi not in ['lh', 'rh']:
            extra = ' or None' if self._hemi in ['lh', 'rh'] else ''
            raise ValueError('hemi must be either "lh" or "rh"' + extra)
        else:
            hemi = [hemi]
        return hemi

    def _read_scalar_data(self, source, hemi, name=None, cast=True):
        """Load in scalar data from an image stored in a file or an array

        Parameters
        ----------
        source : str or numpy array
            path to scalar data file or a numpy array
        name : str or None, optional
            name for the overlay in the internal dictionary
        cast : bool, optional
            either to cast float data into 64bit datatype as a
            workaround. cast=True can fix a rendering problem with
            certain versions of Mayavi

        Returns
        -------
        scalar_data : numpy array
            flat numpy array of scalar data
        name : str
            if no name was provided, deduces the name if filename was given
            as a source
        """
        # If source is a string, try to load a file
        if isinstance(source, string_types):
            if name is None:
                basename = os.path.basename(source)
                if basename.endswith(".gz"):
                    basename = basename[:-3]
                if basename.startswith("%s." % hemi):
                    basename = basename[3:]
                name = os.path.splitext(basename)[0]
            scalar_data = io.read_scalar_data(source)
        else:
            # Can't think of a good way to check that this will work nicely
            scalar_data = source

        if cast:
            if (scalar_data.dtype.char == 'f' and
                    scalar_data.dtype.itemsize < 8):
                scalar_data = scalar_data.astype(np.float)

        return scalar_data, name

    def _get_display_range(self, scalar_data, min, max, sign):

        if scalar_data.min() >= 0:
            sign = "pos"
        elif scalar_data.max() <= 0:
            sign = "neg"

        # Get data with a range that will make sense for automatic thresholding
        if sign == "neg":
            range_data = np.abs(scalar_data[np.where(scalar_data < 0)])
        elif sign == "pos":
            range_data = scalar_data[np.where(scalar_data > 0)]
        else:
            range_data = np.abs(scalar_data)

        # Get a numeric value for the scalar minimum
        if min is None:
            min = "robust_min"
        if min == "robust_min":
            min = stats.scoreatpercentile(range_data, 2)
        elif min == "actual_min":
            min = range_data.min()

        # Get a numeric value for the scalar maximum
        if max is None:
            max = "robust_max"
        if max == "robust_max":
            max = stats.scoreatpercentile(scalar_data, 98)
        elif max == "actual_max":
            max = range_data.max()

        return min, max

    def _iter_time(self, time_idx, interpolation):
        """Iterate through time points, then reset to current time

        Parameters
        ----------
        time_idx : array_like
            Time point indexes through which to iterate.
        interpolation : str
            Interpolation method (``scipy.interpolate.interp1d`` parameter,
            one of 'linear' | 'nearest' | 'zero' | 'slinear' | 'quadratic' |
            'cubic'). Interpolation is only used for non-integer indexes.

        Yields
        ------
        idx : int | float
            Current index.

        Notes
        -----
        Used by movie and image sequence saving functions.
        """
        current_time_idx = self.data_time_index
        for idx in time_idx:
            self.set_data_time_index(idx, interpolation)
            yield idx

        # Restore original time index
        self.set_data_time_index(current_time_idx)

    ###########################################################################
    # ADDING DATA PLOTS
    def add_overlay(self, source, min=2, max="robust_max", sign="abs",
                    name=None, hemi=None):
        """Add an overlay to the overlay dict from a file or array.

        Parameters
        ----------
        source : str or numpy array
            path to the overlay file or numpy array with data
        min : float
            threshold for overlay display
        max : float
            saturation point for overlay display
        sign : {'abs' | 'pos' | 'neg'}
            whether positive, negative, or both values should be displayed
        name : str
            name for the overlay in the internal dictionary
        hemi : str | None
            If None, it is assumed to belong to the hemipshere being
            shown. If two hemispheres are being shown, an error will
            be thrown.
        """
        hemi = self._check_hemi(hemi)
        # load data here
        scalar_data, name = self._read_scalar_data(source, hemi, name=name)
        min, max = self._get_display_range(scalar_data, min, max, sign)
        if sign not in ["abs", "pos", "neg"]:
            raise ValueError("Overlay sign must be 'abs', 'pos', or 'neg'")
        old = OverlayData(scalar_data, self.geo[hemi], min, max, sign)
        ol = []
        views = self._toggle_render(False)
        for brain in self._brain_list:
            if brain['hemi'] == hemi:
                ol.append(brain['brain'].add_overlay(old))
        if name in self.overlays_dict:
            name = "%s%d" % (name, len(self.overlays_dict) + 1)
        self.overlays_dict[name] = ol
        self._toggle_render(True, views)

    def add_data(self, array, min=None, max=None, thresh=None,
                 colormap="RdBu_r", alpha=1,
                 vertices=None, smoothing_steps=20, time=None,
                 time_label="time index=%d", colorbar=True,
                 hemi=None, remove_existing=False, time_label_size=14,
                 initial_time=None):
        """Display data from a numpy array on the surface.

        This provides a similar interface to add_overlay, but it displays
        it with a single colormap. It offers more flexibility over the
        colormap, and provides a way to display four dimensional data
        (i.e. a timecourse).

        Note that min sets the low end of the colormap, and is separate
        from thresh (this is a different convention from add_overlay)

        Note: If the data is defined for a subset of vertices (specified
        by the "vertices" parameter), a smoothing method is used to interpolate
        the data onto the high resolution surface. If the data is defined for
        subsampled version of the surface, smoothing_steps can be set to None,
        in which case only as many smoothing steps are applied until the whole
        surface is filled with non-zeros.

        Parameters
        ----------
        array : numpy array
            data array (nvtx vector)
        min : float
            min value in colormap (uses real min if None)
        max : float
            max value in colormap (uses real max if None)
        thresh : None or float
            if not None, values below thresh will not be visible
        colormap : string, list of colors, or array
            name of matplotlib colormap to use, a list of matplotlib colors,
            or a custom look up table (an n x 4 array coded with RBGA values
            between 0 and 255).
        alpha : float in [0, 1]
            alpha level to control opacity
        vertices : numpy array
            vertices for which the data is defined (needed if len(data) < nvtx)
        smoothing_steps : int or None
            number of smoothing steps (smooting is used if len(data) < nvtx)
            Default : 20
        time : numpy array
            time points in the data array (if data is 2D)
        time_label : str | callable | None
            format of the time label (a format string, a function that maps
            floating point time values to strings, or None for no label)
        colorbar : bool
            whether to add a colorbar to the figure
        hemi : str | None
            If None, it is assumed to belong to the hemipshere being
            shown. If two hemispheres are being shown, an error will
            be thrown.
        remove_existing : bool
            Remove surface added by previous "add_data" call. Useful for
            conserving memory when displaying different data in a loop.
        time_label_size : int
            Font size of the time label (default 14)
        initial_time : float | None
            Time initially shown in the plot. ``None`` to use the first time
            sample (default).
        """
        hemi = self._check_hemi(hemi)
        array = np.asarray(array)

        if min is None:
            min = array.min() if array.size > 0 else 0
        if max is None:
            max = array.max() if array.size > 0 else 0

        # Create smoothing matrix if necessary
        if len(array) < self.geo[hemi].x.shape[0]:
            if vertices is None:
                raise ValueError("len(data) < nvtx: need vertices")
            adj_mat = utils.mesh_edges(self.geo[hemi].faces)
            smooth_mat = utils.smoothing_matrix(vertices, adj_mat,
                                                smoothing_steps)
        else:
            smooth_mat = None

        # Calculate initial data to plot
        if array.ndim == 1:
            array_plot = array
        elif array.ndim == 2:
            array_plot = array[:, 0]
        else:
            raise ValueError("data has to be 1D or 2D")

        if smooth_mat is not None:
            array_plot = smooth_mat * array_plot

        # Copy and byteswap to deal with Mayavi bug
        mlab_plot = _prepare_data(array_plot)

        # Process colormap argument into a lut
        lut = create_color_lut(colormap)
        colormap = "Greys"

        data = dict(array=array, smoothing_steps=smoothing_steps,
                    fmin=min, fmid=(min + max) / 2, fmax=max,
                    transparent=False, time=0, time_idx=0,
                    vertices=vertices, smooth_mat=smooth_mat)

        # Create time array and add label if 2D
        if array.ndim == 2:
            if time is None:
                time = np.arange(array.shape[1])
            self._times = time
            self.n_times = array.shape[1]
            if not self.n_times == len(time):
                raise ValueError('time is not the same length as '
                                 'array.shape[1]')
            # initial time
            if initial_time is None:
                initial_time_index = None
            else:
                initial_time_index = self.index_for_time(initial_time)
            # time label
            if isinstance(time_label, string_types):
                time_label_fmt = time_label

                def time_label(x):
                    return time_label_fmt % x
            data["time_label"] = time_label
            data["time"] = time
            data["time_idx"] = 0
            y_txt = 0.05 + 0.05 * bool(colorbar)
        else:
            self._times = None
            self.n_times = None
            initial_time_index = None

        surfs = []
        bars = []
        views = self._toggle_render(False)
        for bi, brain in enumerate(self._brain_list):
            if brain['hemi'] == hemi:
                out = brain['brain'].add_data(array, mlab_plot, vertices,
                                              smooth_mat, min, max, thresh,
                                              lut, colormap, alpha, time,
                                              time_label, colorbar)
                s, ct, bar = out
                surfs.append(s)
                bars.append(bar)
                row, col = np.unravel_index(bi, self.brain_matrix.shape)
                if array.ndim == 2 and time_label is not None:
                    self.add_text(0.95, y_txt, time_label(time[0]),
                                  name="time_label", row=row, col=col,
                                  font_size=time_label_size,
                                  justification='right')
        data['surfaces'] = surfs
        data['colorbars'] = bars
        data['orig_ctable'] = ct

        if remove_existing and self.data_dict[hemi] is not None:
            for surf in self.data_dict[hemi]['surfaces']:
                surf.parent.parent.remove()
        self.data_dict[hemi] = data

        if initial_time_index is not None:
            self.set_data_time_index(initial_time_index)
        self._toggle_render(True, views)

    def add_annotation(self, annot, borders=True, alpha=1, hemi=None,
                       remove_existing=True):
        """Add an annotation file.

        Parameters
        ----------
        annot : str
            Either path to annotation file or annotation name
        borders : bool | int
            Show only label borders. If int, specify the number of steps
            (away from the true border) along the cortical mesh to include
            as part of the border definition.
        alpha : float in [0, 1]
            Alpha level to control opacity
        hemi : str | None
            If None, it is assumed to belong to the hemipshere being
            shown. If two hemispheres are being shown, data must exist
            for both hemispheres.
        remove_existing : bool
            If True (default), remove old annotations.
        """
        hemis = self._check_hemis(hemi)

        # Figure out where the data is coming from
        if os.path.isfile(annot):
            filepath = annot
            path = os.path.split(filepath)[0]
            file_hemi, annot = os.path.basename(filepath).split('.')[:2]
            if len(hemis) > 1:
                if annot[:2] == 'lh.':
                    filepaths = [filepath, pjoin(path, 'rh' + annot[2:])]
                elif annot[:2] == 'rh.':
                    filepaths = [pjoin(path, 'lh' + annot[2:], filepath)]
                else:
                    raise RuntimeError('To add both hemispheres '
                                       'simultaneously, filename must '
                                       'begin with "lh." or "rh."')
            else:
                filepaths = [filepath]
        else:
            filepaths = []
            for hemi in hemis:
                filepath = pjoin(self.subjects_dir,
                                 self.subject_id,
                                 'label',
                                 ".".join([hemi, annot, 'annot']))
                if not os.path.exists(filepath):
                    raise ValueError('Annotation file %s does not exist'
                                     % filepath)
                filepaths += [filepath]

        views = self._toggle_render(False)
        if remove_existing is True:
            # Get rid of any old annots
            for a in self.annot_list:
                a['surface'].remove()
            self.annot_list = []

        al = self.annot_list
        for hemi, filepath in zip(hemis, filepaths):
            # Read in the data
            labels, cmap, _ = nib.freesurfer.read_annot(filepath,
                                                        orig_ids=True)

            # Maybe zero-out the non-border vertices
            self._to_borders(labels, hemi, borders)

            # Handle null labels properly
            # (tksurfer doesn't use the alpha channel, so sometimes this
            # is set weirdly. For our purposes, it should always be 0.
            # Unless this sometimes causes problems?
            cmap[np.where(cmap[:, 4] == 0), 3] = 0
            if np.any(labels == 0) and not np.any(cmap[:, -1] == 0):
                cmap = np.vstack((cmap, np.zeros(5, int)))

            # Set label ids sensibly
            ord = np.argsort(cmap[:, -1])
            ids = ord[np.searchsorted(cmap[ord, -1], labels)]
            cmap = cmap[:, :4]

            #  Set the alpha level
            alpha_vec = cmap[:, 3]
            alpha_vec[alpha_vec > 0] = alpha * 255

            for brain in self._brain_list:
                if brain['hemi'] == hemi:
                    al.append(brain['brain'].add_annotation(annot, ids, cmap))
        self.annot_list = al
        self._toggle_render(True, views)

    def add_label(self, label, color=None, alpha=1, scalar_thresh=None,
                  borders=False, hemi=None, subdir=None):
        """Add an ROI label to the image.

        Parameters
        ----------
        label : str | instance of Label
            label filepath or name. Can also be an instance of
            an object with attributes "hemi", "vertices", "name", and
            optionally "color" and "values" (if scalar_thresh is not None).
        color : matplotlib-style color | None
            anything matplotlib accepts: string, RGB, hex, etc. (default
            "crimson")
        alpha : float in [0, 1]
            alpha level to control opacity
        scalar_thresh : None or number
            threshold the label ids using this value in the label
            file's scalar field (i.e. label only vertices with
            scalar >= thresh)
        borders : bool | int
            Show only label borders. If int, specify the number of steps
            (away from the true border) along the cortical mesh to include
            as part of the border definition.
        hemi : str | None
            If None, it is assumed to belong to the hemipshere being
            shown. If two hemispheres are being shown, an error will
            be thrown.
        subdir : None | str
            If a label is specified as name, subdir can be used to indicate
            that the label file is in a sub-directory of the subject's
            label directory rather than in the label directory itself (e.g.
            for ``$SUBJECTS_DIR/$SUBJECT/label/aparc/lh.cuneus.label``
            ``brain.add_label('cuneus', subdir='aparc')``).

        Notes
        -----
        To remove previously added labels, run Brain.remove_labels().
        """
        if isinstance(label, string_types):
            hemi = self._check_hemi(hemi)
            if color is None:
                color = "crimson"

            if os.path.isfile(label):
                filepath = label
                label_name = os.path.basename(filepath).split('.')[1]
            else:
                label_name = label
                label_fname = ".".join([hemi, label_name, 'label'])
                if subdir is None:
                    filepath = pjoin(self.subjects_dir, self.subject_id,
                                     'label', label_fname)
                else:
                    filepath = pjoin(self.subjects_dir, self.subject_id,
                                     'label', subdir, label_fname)
                if not os.path.exists(filepath):
                    raise ValueError('Label file %s does not exist'
                                     % filepath)
            # Load the label data and create binary overlay
            if scalar_thresh is None:
                ids = nib.freesurfer.read_label(filepath)
            else:
                ids, scalars = nib.freesurfer.read_label(filepath,
                                                         read_scalars=True)
                ids = ids[scalars >= scalar_thresh]
        else:
            # try to extract parameters from label instance
            try:
                hemi = label.hemi
                ids = label.vertices
                if label.name is None:
                    label_name = 'unnamed'
                else:
                    label_name = str(label.name)

                if color is None:
                    if hasattr(label, 'color') and label.color is not None:
                        color = label.color
                    else:
                        color = "crimson"

                if scalar_thresh is not None:
                    scalars = label.values
            except Exception:
                raise ValueError('Label was not a filename (str), and could '
                                 'not be understood as a class. The class '
                                 'must have attributes "hemi", "vertices", '
                                 '"name", and (if scalar_thresh is not None)'
                                 '"values"')
            hemi = self._check_hemi(hemi)

            if scalar_thresh is not None:
                ids = ids[scalars >= scalar_thresh]

        label = np.zeros(self.geo[hemi].coords.shape[0])
        label[ids] = 1

        # make sure we have a unique name
        if label_name in self.labels_dict:
            i = 2
            name = label_name + '_%i'
            while name % i in self.labels_dict:
                i += 1
            label_name = name % i

        self._to_borders(label, hemi, borders, restrict_idx=ids)

        # make a list of all the plotted labels
        ll = []
        views = self._toggle_render(False)
        for brain in self._brain_list:
            if brain['hemi'] == hemi:
                ll.append(brain['brain'].add_label(label, label_name,
                          color, alpha))
        self.labels_dict[label_name] = ll
        self._toggle_render(True, views)

    def _to_borders(self, label, hemi, borders, restrict_idx=None):
        """Helper to potentially convert a label/parc to borders"""
        if not isinstance(borders, (bool, int)) or borders < 0:
            raise ValueError('borders must be a bool or positive integer')
        if borders:
            n_vertices = label.size
            edges = utils.mesh_edges(self.geo[hemi].faces)
            border_edges = label[edges.row] != label[edges.col]
            show = np.zeros(n_vertices, dtype=np.int)
            keep_idx = np.unique(edges.row[border_edges])
            if isinstance(borders, int):
                for _ in range(borders):
                    keep_idx = np.in1d(self.geo[hemi].faces.ravel(), keep_idx)
                    keep_idx.shape = self.geo[hemi].faces.shape
                    keep_idx = self.geo[hemi].faces[np.any(keep_idx, axis=1)]
                    keep_idx = np.unique(keep_idx)
                if restrict_idx is not None:
                    keep_idx = keep_idx[np.in1d(keep_idx, restrict_idx)]
            show[keep_idx] = 1
            label *= show

    def remove_labels(self, labels=None, hemi=None):
        """Remove one or more previously added labels from the image.

        Parameters
        ----------
        labels : None | str | list of str
            Labels to remove. Can be a string naming a single label, or None to
            remove all labels. Possible names can be found in the Brain.labels
            attribute.
        hemi : str | None
            If None, it is assumed to belong to the hemipshere being
            shown. If two hemispheres are being shown, an error will
            be thrown.
        """
        hemi = self._check_hemi(hemi)
        if labels is None:
            labels = self.labels_dict.keys()
        elif isinstance(labels, str):
            labels = [labels]

        for key in labels:
            label = self.labels_dict.pop(key)
            for ll in label:
                ll.remove()

    def add_morphometry(self, measure, grayscale=False, hemi=None,
                        remove_existing=True, colormap=None,
                        min=None, max=None, colorbar=True):
        """Add a morphometry overlay to the image.

        Parameters
        ----------
        measure : {'area' | 'curv' | 'jacobian_white' | 'sulc' | 'thickness'}
            which measure to load
        grayscale : bool
            whether to load the overlay with a grayscale colormap
        hemi : str | None
            If None, it is assumed to belong to the hemipshere being
            shown. If two hemispheres are being shown, data must exist
            for both hemispheres.
        remove_existing : bool
            If True (default), remove old annotations.
        colormap : str
            Mayavi colormap name, or None to use a sensible default.
        min, max : floats
            Endpoints for the colormap; if not provided the robust range
            of the data is used.
        colorbar : bool
            If True, show a colorbar corresponding to the overlay data.

        """
        hemis = self._check_hemis(hemi)
        morph_files = []
        for hemi in hemis:
            # Find the source data
            surf_dir = pjoin(self.subjects_dir, self.subject_id, 'surf')
            morph_file = pjoin(surf_dir, '.'.join([hemi, measure]))
            if not os.path.exists(morph_file):
                raise ValueError(
                    'Could not find %s in subject directory' % morph_file)
            morph_files += [morph_file]

        views = self._toggle_render(False)
        if remove_existing is True:
            # Get rid of any old overlays
            for m in self.morphometry_list:
                m['surface'].remove()
                if m["colorbar"] is not None:
                    m['colorbar'].visible = False
            self.morphometry_list = []
        ml = self.morphometry_list

        for hemi, morph_file in zip(hemis, morph_files):

            if colormap is None:
                # Preset colormaps
                if grayscale:
                    colormap = "gray"
                else:
                    colormap = dict(area="pink",
                                    curv="RdBu",
                                    jacobian_white="pink",
                                    sulc="RdBu",
                                    thickness="pink")[measure]

            # Read in the morphometric data
            morph_data = nib.freesurfer.read_morph_data(morph_file)

            # Get a cortex mask for robust range
            self.geo[hemi].load_label("cortex")
            ctx_idx = self.geo[hemi].labels["cortex"]

            # Get the display range
            min_default, max_default = np.percentile(morph_data[ctx_idx],
                                                     [2, 98])
            if min is None:
                min = min_default
            if max is None:
                max = max_default

            # Use appropriate values for bivariate measures
            if measure in ["curv", "sulc"]:
                lim = np.max([abs(min), abs(max)])
                min, max = -lim, lim

            # Set up the Mayavi pipeline
            morph_data = _prepare_data(morph_data)

            for brain in self._brain_list:
                if brain['hemi'] == hemi:
                    ml.append(brain['brain'].add_morphometry(morph_data,
                                                             colormap, measure,
                                                             min, max,
                                                             colorbar))
        self.morphometry_list = ml
        self._toggle_render(True, views)

    def add_foci(self, coords, coords_as_verts=False, map_surface=None,
                 scale_factor=1, color="white", alpha=1, name=None,
                 hemi=None):
        """Add spherical foci, possibly mapping to displayed surf.

        The foci spheres can be displayed at the coordinates given, or
        mapped through a surface geometry. In other words, coordinates
        from a volume-based analysis in MNI space can be displayed on an
        inflated average surface by finding the closest vertex on the
        white surface and mapping to that vertex on the inflated mesh.

        Parameters
        ----------
        coords : numpy array
            x, y, z coordinates in stereotaxic space or array of vertex ids
        coords_as_verts : bool
            whether the coords parameter should be interpreted as vertex ids
        map_surface : Freesurfer surf or None
            surface to map coordinates through, or None to use raw coords
        scale_factor : int
            controls the size of the foci spheres
        color : matplotlib color code
            HTML name, RBG tuple, or hex code
        alpha : float in [0, 1]
            opacity of focus gylphs
        name : str
            internal name to use
        hemi : str | None
            If None, it is assumed to belong to the hemipshere being
            shown. If two hemispheres are being shown, an error will
            be thrown.
        """
        hemi = self._check_hemi(hemi)

        # Figure out how to interpret the first parameter
        if coords_as_verts:
            coords = self.geo[hemi].coords[coords]
            map_surface = None

        # Possibly map the foci coords through a surface
        if map_surface is None:
            foci_coords = np.atleast_2d(coords)
        else:
            foci_surf = Surface(self.subject_id, hemi, map_surface,
                                subjects_dir=self.subjects_dir)
            foci_surf.load_geometry()
            foci_vtxs = utils.find_closest_vertices(foci_surf.coords, coords)
            foci_coords = self.geo[hemi].coords[foci_vtxs]

        # Get a unique name (maybe should take this approach elsewhere)
        if name is None:
            name = "foci_%d" % (len(self.foci_dict) + 1)

        # Convert the color code
        if not isinstance(color, tuple):
            color = colorConverter.to_rgb(color)

        views = self._toggle_render(False)
        fl = []
        for brain in self._brain_list:
            if brain['hemi'] == hemi:
                fl.append(brain['brain'].add_foci(foci_coords, scale_factor,
                                                  color, alpha, name))
        self.foci_dict[name] = fl
        self._toggle_render(True, views)

    def add_contour_overlay(self, source, min=None, max=None,
                            n_contours=7, line_width=1.5, colormap="YlOrRd_r",
                            hemi=None, remove_existing=True, colorbar=True):
        """Add a topographic contour overlay of the positive data.

        Note: This visualization will look best when using the "low_contrast"
        cortical curvature colorscheme.

        Parameters
        ----------
        source : str or array
            path to the overlay file or numpy array
        min : float
            threshold for overlay display
        max : float
            saturation point for overlay display
        n_contours : int
            number of contours to use in the display
        line_width : float
            width of contour lines
        colormap : string, list of colors, or array
            name of matplotlib colormap to use, a list of matplotlib colors,
            or a custom look up table (an n x 4 array coded with RBGA values
            between 0 and 255).
        hemi : str | None
            If None, it is assumed to belong to the hemipshere being
            shown. If two hemispheres are being shown, an error will
            be thrown.
        remove_existing : bool
            If there is an existing contour overlay, remove it before plotting.
        colorbar : bool
            If True, show the colorbar for the scalar value.

        """
        hemi = self._check_hemi(hemi)

        # Read the scalar data
        scalar_data, _ = self._read_scalar_data(source, hemi)
        min, max = self._get_display_range(scalar_data, min, max, "pos")

        # Deal with Mayavi bug
        scalar_data = _prepare_data(scalar_data)

        # Maybe get rid of an old overlay
        if remove_existing:
            for c in self.contour_list:
                c['surface'].remove()
                if c['colorbar'] is not None:
                    c['colorbar'].visible = False

        # Process colormap argument into a lut
        lut = create_color_lut(colormap)

        views = self._toggle_render(False)
        cl = []
        for brain in self._brain_list:
            if brain['hemi'] == hemi:
                cl.append(brain['brain'].add_contour_overlay(scalar_data,
                                                             min, max,
                                                             n_contours,
                                                             line_width, lut,
                                                             colorbar))
        self.contour_list = cl
        self._toggle_render(True, views)

    def add_text(self, x, y, text, name, color=None, opacity=1.0,
                 row=-1, col=-1, font_size=None, justification=None):
        """ Add a text to the visualization

        Parameters
        ----------
        x : Float
            x coordinate
        y : Float
            y coordinate
        text : str
            Text to add
        name : str
            Name of the text (text label can be updated using update_text())
        color : Tuple
            Color of the text. Default: (1, 1, 1)
        opacity : Float
            Opacity of the text. Default: 1.0
        row : int
            Row index of which brain to use
        col : int
            Column index of which brain to use
        """
        if name in self.texts_dict:
            self.texts_dict[name]['text'].remove()
        text = self.brain_matrix[row, col].add_text(x, y, text,
                                                    name, color, opacity)
        self.texts_dict[name] = dict(row=row, col=col, text=text)
        if font_size is not None:
            text.property.font_size = font_size
            text.actor.text_scale_mode = 'viewport'
        if justification is not None:
            text.property.justification = justification

    def update_text(self, text, name, row=-1, col=-1):
        """Update text label

        Parameters
        ----------
        text : str
            New text for label
        name : str
            Name of text label
        """
        if name not in self.texts_dict:
            raise KeyError('text name "%s" unknown' % name)
        self.texts_dict[name]['text'].text = text

    ###########################################################################
    # DATA SCALING / DISPLAY
    def reset_view(self):
        """Orient camera to display original view
        """
        for view, brain in zip(self._original_views, self._brain_list):
            brain['brain'].show_view(view)

    def show_view(self, view=None, roll=None, distance=None, row=-1, col=-1):
        """Orient camera to display view

        Parameters
        ----------
        view : {'lateral' | 'medial' | 'rostral' | 'caudal' |
                'dorsal' | 'ventral' | 'frontal' | 'parietal' |
                dict}
            brain surface to view or kwargs to pass to mlab.view()

        Returns
        -------
        view : tuple
            tuple returned from mlab.view
        roll : float
            camera roll
        distance : float | 'auto' | None
            distance from the origin
        row : int
            Row index of which brain to use
        col : int
            Column index of which brain to use
        """
        return self.brain_matrix[row][col].show_view(view, roll, distance)

    def set_distance(self, distance=None):
        """Set view distances for all brain plots to the same value

        Parameters
        ----------
        distance : float | None
            Distance to use. If None, brains are set to the farthest
            "best fit" distance across all current views; note that
            the underlying "best fit" function can be buggy.

        Returns
        -------
        distance : float
            The distance used.
        """
        if distance is None:
            distance = []
            for ff in self._figures:
                for f in ff:
                    mlab.view(figure=f, distance='auto')
                    v = mlab.view(figure=f)
                    # This should only happen for the test backend
                    if v is None:
                        v = [0, 0, 100]
                    distance += [v[2]]
            distance = max(distance)

        for ff in self._figures:
            for f in ff:
                mlab.view(distance=distance, figure=f)
        return distance

    @verbose
    def scale_data_colormap(self, fmin, fmid, fmax, transparent, verbose=None):
        """Scale the data colormap.

        Parameters
        ----------
        fmin : float
            minimum value of colormap
        fmid : float
            value corresponding to color midpoint
        fmax : float
            maximum value for colormap
        transparent : boolean
            if True: use a linear transparency between fmin and fmid
        verbose : bool, str, int, or None
            If not None, override default verbose level (see surfer.verbose).
        """
        if not (fmin < fmid) and (fmid < fmax):
            raise ValueError("Invalid colormap, we need fmin<fmid<fmax")

        # Cast inputs to float to prevent integer division
        fmin = float(fmin)
        fmid = float(fmid)
        fmax = float(fmax)

        logger.info("colormap: fmin=%0.2e fmid=%0.2e fmax=%0.2e "
                    "transparent=%d" % (fmin, fmid, fmax, transparent))

        # Get the original colormap
        for h in ['lh', 'rh']:
            data = self.data_dict[h]
            if data is not None:
                table = data["orig_ctable"].copy()

        # Add transparency if needed
        if transparent:
            n_colors = table.shape[0]
            n_colors2 = int(n_colors / 2)
            table[:n_colors2, -1] = np.linspace(0, 255, n_colors2)
            table[n_colors2:, -1] = 255 * np.ones(n_colors - n_colors2)

        # Scale the colormap
        table_new = table.copy()
        n_colors = table.shape[0]
        n_colors2 = int(n_colors / 2)

        # Index of fmid in new colorbar
        fmid_idx = int(np.round(n_colors * ((fmid - fmin) /
                                            (fmax - fmin))) - 1)

        # Go through channels
        for i in range(4):
            part1 = np.interp(np.linspace(0, n_colors2 - 1, fmid_idx + 1),
                              np.arange(n_colors),
                              table[:, i])
            table_new[:fmid_idx + 1, i] = part1
            part2 = np.interp(np.linspace(n_colors2, n_colors - 1,
                                          n_colors - fmid_idx - 1),
                              np.arange(n_colors),
                              table[:, i])
            table_new[fmid_idx + 1:, i] = part2

        views = self._toggle_render(False)
        # Use the new colormap
        for hemi in ['lh', 'rh']:
            data = self.data_dict[hemi]
            if data is not None:
                for surf in data['surfaces']:
                    cmap = surf.module_manager.scalar_lut_manager
                    cmap.lut.table = table_new
                    cmap.data_range = np.array([fmin, fmax])

                # Update the data properties
                data["fmin"], data['fmid'], data['fmax'] = fmin, fmid, fmax
                data["transparent"] = transparent
        self._toggle_render(True, views)

    def set_data_time_index(self, time_idx, interpolation='quadratic'):
        """Set the data time index to show

        Parameters
        ----------
        time_idx : int | float
            Time index. Non-integer values will be displayed using
            interpolation between samples.
        interpolation : str
            Interpolation method (``scipy.interpolate.interp1d`` parameter,
            one of 'linear' | 'nearest' | 'zero' | 'slinear' | 'quadratic' |
            'cubic', default 'quadratic'). Interpolation is only used for
            non-integer indexes.
        """
        if self.n_times is None:
            raise RuntimeError('cannot set time index with no time data')
        if time_idx < 0 or time_idx >= self.n_times:
            raise ValueError("time index out of range")

        views = self._toggle_render(False)
        for hemi in ['lh', 'rh']:
            data = self.data_dict[hemi]
            if data is not None:
                # interpolation
                if isinstance(time_idx, float):
                    times = np.arange(self.n_times)
                    ifunc = interp1d(times, data['array'], interpolation, 1)
                    plot_data = ifunc(time_idx)
                else:
                    plot_data = data["array"][:, time_idx]

                if data["smooth_mat"] is not None:
                    plot_data = data["smooth_mat"] * plot_data
                for surf in data["surfaces"]:
                    surf.mlab_source.scalars = plot_data
                data["time_idx"] = time_idx

                # Update time label
                if data["time_label"]:
                    if isinstance(time_idx, float):
                        ifunc = interp1d(times, data['time'])
                        time = ifunc(time_idx)
                    else:
                        time = data["time"][time_idx]
                    self.update_text(data["time_label"](time), "time_label")
        self._toggle_render(True, views)

    @property
    def data_time_index(self):
        """Retrieve the currently displayed data time index

        Returns
        -------
        time_idx : int
            Current time index.

        Notes
        -----
        Raises a RuntimeError if the Brain instance has not data overlay.
        """
        time_idx = None
        for hemi in ['lh', 'rh']:
            data = self.data_dict[hemi]
            if data is not None:
                time_idx = data["time_idx"]
                return time_idx
        raise RuntimeError("Brain instance has no data overlay")

    @verbose
    def set_data_smoothing_steps(self, smoothing_steps, verbose=None):
        """Set the number of smoothing steps

        Parameters
        ----------
        smoothing_steps : int
            Number of smoothing steps
        verbose : bool, str, int, or None
            If not None, override default verbose level (see surfer.verbose).
        """
        views = self._toggle_render(False)
        for hemi in ['lh', 'rh']:
            data = self.data_dict[hemi]
            if data is not None:
                adj_mat = utils.mesh_edges(self.geo[hemi].faces)
                smooth_mat = utils.smoothing_matrix(data["vertices"],
                                                    adj_mat, smoothing_steps)
                data["smooth_mat"] = smooth_mat

                # Redraw
                if data["array"].ndim == 1:
                    plot_data = data["array"]
                else:
                    plot_data = data["array"][:, data["time_idx"]]

                plot_data = data["smooth_mat"] * plot_data
                for surf in data["surfaces"]:
                    surf.mlab_source.scalars = plot_data

                # Update data properties
                data["smoothing_steps"] = smoothing_steps
        self._toggle_render(True, views)

    def index_for_time(self, time, rounding='closest'):
        """Find the data time index closest to a specific time point

        Parameters
        ----------
        time : scalar
            Time.
        rounding : 'closest' | 'up' | 'down
            How to round if the exact time point is not an index.

        Returns
        -------
        index : int
            Data time index closest to time.
        """
        if self.n_times is None:
            raise RuntimeError("Brain has no time axis")
        times = self._times

        # Check that time is in range
        tmin = np.min(times)
        tmax = np.max(times)
        max_diff = (tmax - tmin) / (len(times) - 1) / 2
        if time < tmin - max_diff or time > tmax + max_diff:
            err = ("time = %s lies outside of the time axis "
                   "[%s, %s]" % (time, tmin, tmax))
            raise ValueError(err)

        if rounding == 'closest':
            idx = np.argmin(np.abs(times - time))
        elif rounding == 'up':
            idx = np.nonzero(times >= time)[0][0]
        elif rounding == 'down':
            idx = np.nonzero(times <= time)[0][-1]
        else:
            err = "Invalid rounding parameter: %s" % repr(rounding)
            raise ValueError(err)

        return idx

    def set_time(self, time):
        """Set the data time index to the time point closest to time

        Parameters
        ----------
        time : scalar
            Time.
        """
        idx = self.index_for_time(time)
        self.set_data_time_index(idx)

    def _get_colorbars(self, row, col):
        shape = self.brain_matrix.shape
        row = row % shape[0]
        col = col % shape[1]
        ind = np.ravel_multi_index((row, col), self.brain_matrix.shape)
        colorbars = []
        h = self._brain_list[ind]['hemi']
        if self.data_dict[h] is not None and 'colorbars' in self.data_dict[h]:
            colorbars.append(self.data_dict[h]['colorbars'][row])
        if len(self.morphometry_list) > 0:
            colorbars.append(self.morphometry_list[ind]['colorbar'])
        if len(self.contour_list) > 0:
            colorbars.append(self.contour_list[ind]['colorbar'])
        if len(self.overlays_dict) > 0:
            for name, obj in self.overlays_dict.items():
                for bar in ["pos_bar", "neg_bar"]:
                    try:  # deal with positive overlays
                        this_ind = min(len(obj) - 1, ind)
                        colorbars.append(getattr(obj[this_ind], bar))
                    except AttributeError:
                        pass
        return colorbars

    def _colorbar_visibility(self, visible, row, col):
        for cb in self._get_colorbars(row, col):
            if cb is not None:
                cb.visible = visible

    def show_colorbar(self, row=-1, col=-1):
        """Show colorbar(s) for given plot

        Parameters
        ----------
        row : int
            Row index of which brain to use
        col : int
            Column index of which brain to use
        """
        self._colorbar_visibility(True, row, col)

    def hide_colorbar(self, row=-1, col=-1):
        """Hide colorbar(s) for given plot

        Parameters
        ----------
        row : int
            Row index of which brain to use
        col : int
            Column index of which brain to use
        """
        self._colorbar_visibility(False, row, col)

    def close(self):
        """Close all figures and cleanup data structure."""
        for ri, ff in enumerate(self._figures):
            for ci, f in enumerate(ff):
                if f is not None:
                    mlab.close(f)
                    self._figures[ri][ci] = None

        # should we tear down other variables?
        if self._v is not None:
            self._v.dispose()
            self._v = None

    def __del__(self):
        if hasattr(self, '_v') and self._v is not None:
            self._v.dispose()
            self._v = None

    ###########################################################################
    # SAVING OUTPUT
    def save_single_image(self, filename, row=-1, col=-1):
        """Save view from one panel to disk

        Only mayavi image types are supported:
        (png jpg bmp tiff ps eps pdf rib  oogl iv  vrml obj

        Parameters
        ----------
        filename: string
            path to new image file
        row : int
            row index of the brain to use
        col : int
            column index of the brain to use

        Due to limitations in TraitsUI, if multiple views or hemi='split'
        is used, there is no guarantee painting of the windows will
        complete before control is returned to the command line. Thus
        we strongly recommend using only one figure window (which uses
        a Mayavi figure to plot instead of TraitsUI) if you intend to
        script plotting commands.
        """
        brain = self.brain_matrix[row, col]
        ftype = filename[filename.rfind('.') + 1:]
        good_ftypes = ['png', 'jpg', 'bmp', 'tiff', 'ps',
                       'eps', 'pdf', 'rib', 'oogl', 'iv', 'vrml', 'obj']
        if ftype not in good_ftypes:
            raise ValueError("Supported image types are %s"
                             % " ".join(good_ftypes))
        mlab.draw(brain._f)
        mlab.savefig(filename, figure=brain._f)

    def save_image(self, filename, mode='rgb', antialiased=False):
        """Save view from all panels to disk

        Only mayavi image types are supported:
        (png jpg bmp tiff ps eps pdf rib  oogl iv  vrml obj

        Parameters
        ----------
        filename: string
            path to new image file
        mode: string
            Either 'rgb' (default) to render solid background, or 'rgba' to
            include alpha channel for transparent background
        antialiased: bool
            Antialias the image (see mlab.screenshot() for details; default
            False)

        Notes
        -----
        Due to limitations in TraitsUI, if multiple views or hemi='split'
        is used, there is no guarantee painting of the windows will
        complete before control is returned to the command line. Thus
        we strongly recommend using only one figure window (which uses
        a Mayavi figure to plot instead of TraitsUI) if you intend to
        script plotting commands.
        """
        misc.imsave(filename, self.screenshot(mode, antialiased))

    def screenshot(self, mode='rgb', antialiased=False):
        """Generate a screenshot of current view

        Wraps to mlab.screenshot for ease of use.

        Parameters
        ----------
        mode: string
            Either 'rgb' or 'rgba' for values to return
        antialiased: bool
            Antialias the image (see mlab.screenshot() for details; default
            False)

        Returns
        -------
        screenshot: array
            Image pixel values

        Notes
        -----
        Due to limitations in TraitsUI, if multiple views or hemi='split'
        is used, there is no guarantee painting of the windows will
        complete before control is returned to the command line. Thus
        we strongly recommend using only one figure window (which uses
        a Mayavi figure to plot instead of TraitsUI) if you intend to
        script plotting commands.
        """
        row = []
        for ri in range(self.brain_matrix.shape[0]):
            col = []
            n_col = 2 if self._hemi == 'split' else 1
            for ci in range(n_col):
                col += [self.screenshot_single(mode, antialiased,
                                               ri, ci)]
            row += [np.concatenate(col, axis=1)]
        data = np.concatenate(row, axis=0)
        return data

    def screenshot_single(self, mode='rgb', antialiased=False, row=-1, col=-1):
        """Generate a screenshot of current view from a single panel

        Wraps to mlab.screenshot for ease of use.

        Parameters
        ----------
        mode: string
            Either 'rgb' or 'rgba' for values to return
        antialiased: bool
            Antialias the image (see mlab.screenshot() for details)
        row : int
            row index of the brain to use
        col : int
            column index of the brain to use

        Returns
        -------
        screenshot: array
            Image pixel values

        Notes
        -----
        Due to limitations in TraitsUI, if multiple views or hemi='split'
        is used, there is no guarantee painting of the windows will
        complete before control is returned to the command line. Thus
        we strongly recommend using only one figure window (which uses
        a Mayavi figure to plot instead of TraitsUI) if you intend to
        script plotting commands.
        """
        brain = self.brain_matrix[row, col]
        return mlab.screenshot(brain._f, mode, antialiased)

    def save_imageset(self, prefix, views, filetype='png', colorbar='auto',
                      row=-1, col=-1):
        """Convenience wrapper for save_image

        Files created are prefix+'_$view'+filetype

        Parameters
        ----------
        prefix: string | None
            filename prefix for image to be created. If None, a list of
            arrays representing images is returned (not saved to disk).
        views: list
            desired views for images
        filetype: string
            image type
        colorbar: 'auto' | int | list of int | None
            For 'auto', the colorbar is shown in the middle view (default).
            For int or list of int, the colorbar is shown in the specified
            views. For ``None``, no colorbar is shown.
        row : int
            row index of the brain to use
        col : int
            column index of the brain to use

        Returns
        -------
        images_written: list
            all filenames written
        """
        if isinstance(views, string_types):
            raise ValueError("Views must be a non-string sequence"
                             "Use show_view & save_image for a single view")
        if colorbar == 'auto':
            colorbar = [len(views) // 2]
        elif isinstance(colorbar, int):
            colorbar = [colorbar]
        images_written = []
        for iview, view in enumerate(views):
            try:
                if colorbar is not None and iview in colorbar:
                    self.show_colorbar(row, col)
                else:
                    self.hide_colorbar(row, col)
                self.show_view(view, row=row, col=col)
                if prefix is not None:
                    fname = "%s_%s.%s" % (prefix, view, filetype)
                    images_written.append(fname)
                    self.save_single_image(fname, row, col)
                else:
                    images_written.append(self.screenshot_single(row=row,
                                                                 col=col))
            except ValueError:
                print("Skipping %s: not in view dict" % view)
        return images_written

    def save_image_sequence(self, time_idx, fname_pattern, use_abs_idx=True,
                            row=-1, col=-1, montage='single', border_size=15,
                            colorbar='auto', interpolation='quadratic'):
        """Save a temporal image sequence

        The files saved are named "fname_pattern % (pos)" where "pos" is a
        relative or absolute index (controlled by "use_abs_idx")

        Parameters
        ----------
        time_idx : array-like
            Time indices to save. Non-integer values will be displayed using
            interpolation between samples.
        fname_pattern : str
            Filename pattern, e.g. 'movie-frame_%0.4d.png'.
        use_abs_idx : boolean
            If True the indices given by "time_idx" are used in the filename
            if False the index in the filename starts at zero and is
            incremented by one for each image (Default: True).
        row : int
            Row index of the brain to use.
        col : int
            Column index of the brain to use.
        montage: 'current' | 'single' | list
            Views to include in the images: 'current' uses the currently
            displayed image; 'single' (default) uses a single view, specified
            by the ``row`` and ``col`` parameters; a 1 or 2 dimensional list
            can be used to specify a complete montage. Examples:
            ``['lat', 'med']`` lateral and ventral views ordered horizontally;
            ``[['fro'], ['ven']]`` frontal and ventral views ordered
            vertically.
        border_size: int
            Size of image border (more or less space between images).
        colorbar: 'auto' | int | list of int | None
            For 'auto', the colorbar is shown in the middle view (default).
            For int or list of int, the colorbar is shown in the specified
            views. For ``None``, no colorbar is shown.
       interpolation : str
            Interpolation method (``scipy.interpolate.interp1d`` parameter,
            one of 'linear' | 'nearest' | 'zero' | 'slinear' | 'quadratic' |
            'cubic', default 'quadratic'). Interpolation is only used for
            non-integer indexes.

        Returns
        -------
        images_written: list
            all filenames written
        """
        images_written = list()
        for i, idx in enumerate(self._iter_time(time_idx, interpolation)):
            fname = fname_pattern % (idx if use_abs_idx else i)
            if montage == 'single':
                self.save_single_image(fname, row, col)
            elif montage == 'current':
                self.save_image(fname)
            else:
                self.save_montage(fname, montage, 'h', border_size, colorbar,
                                  row, col)
            images_written.append(fname)

        return images_written

    def save_montage(self, filename, order=['lat', 'ven', 'med'],
                     orientation='h', border_size=15, colorbar='auto',
                     row=-1, col=-1):
        """Create a montage from a given order of images

        Parameters
        ----------
        filename: string | None
            path to final image. If None, the image will not be saved.
        order: list
            list of views: order of views to build montage (default ['lat',
            'ven', 'med']; nested list of views to specify views in a
            2-dimensional grid (e.g, [['lat', 'ven'], ['med', 'fro']])
        orientation: {'h' | 'v'}
            montage image orientation (horizontal of vertical alignment; only
            applies if ``order`` is a flat list)
        border_size: int
            Size of image border (more or less space between images)
        colorbar: 'auto' | int | list of int | None
            For 'auto', the colorbar is shown in the middle view (default).
            For int or list of int, the colorbar is shown in the specified
            views. For ``None``, no colorbar is shown.
        row : int
            row index of the brain to use
        col : int
            column index of the brain to use

        Returns
        -------
        out : array
            The montage image, useable with matplotlib.imshow().
        """
        # find flat list of views and nested list of view indexes
        assert orientation in ['h', 'v']
        if isinstance(order, (str, dict)):
            views = [order]
        elif all(isinstance(x, (str, dict)) for x in order):
            views = order
        else:
            views = []
            orientation = []
            for row_order in order:
                if isinstance(row_order, (str, dict)):
                    orientation.append([len(views)])
                    views.append(row_order)
                else:
                    orientation.append([])
                    for view in row_order:
                        orientation[-1].append(len(views))
                        views.append(view)

        if colorbar == 'auto':
            colorbar = [len(views) // 2]
        elif isinstance(colorbar, int):
            colorbar = [colorbar]
        brain = self.brain_matrix[row, col]

        # store current view + colorbar visibility
        current_view = mlab.view(figure=brain._f)
        colorbars = self._get_colorbars(row, col)
        colorbars_visibility = dict()
        for cb in colorbars:
            if cb is not None:
                colorbars_visibility[cb] = cb.visible

        images = self.save_imageset(None, views, colorbar=colorbar, row=row,
                                    col=col)
        out = make_montage(filename, images, orientation, colorbar,
                           border_size)

        # get back original view and colorbars
        mlab.view(*current_view, figure=brain._f)
        for cb in colorbars:
            if cb is not None:
                cb.visible = colorbars_visibility[cb]
        return out

    def save_movie(self, fname, time_dilation=4., tmin=None, tmax=None,
                   framerate=24, interpolation='quadratic', codec=None,
                   bitrate=None, **kwargs):
        """Save a movie (for data with a time axis)

        The movie is created through the :mod:`imageio` module. The format is
        determined by the extension, and additional options can be specified
        through keyword arguments that depend on the format. For available
        formats and corresponding parameters see the imageio documentation:
        http://imageio.readthedocs.io/en/latest/formats.html#multiple-images

        .. Warning::
            This method assumes that time is specified in seconds when adding
            data. If time is specified in milliseconds this will result in
            movies 1000 times longer than expected.

        Parameters
        ----------
        fname : str
            Path at which to save the movie. The extension determines the
            format (e.g., `'*.mov'`, `'*.gif'`, ...; see the :mod:`imageio`
            documenttion for available formats).
        time_dilation : float
            Factor by which to stretch time (default 4). For example, an epoch
            from -100 to 600 ms lasts 700 ms. With ``time_dilation=4`` this
            would result in a 2.8 s long movie.
        tmin : float
            First time point to include (default: all data).
        tmax : float
            Last time point to include (default: all data).
        framerate : float
            Framerate of the movie (frames per second, default 24).
        interpolation : str
            Interpolation method (``scipy.interpolate.interp1d`` parameter,
            one of 'linear' | 'nearest' | 'zero' | 'slinear' | 'quadratic' |
            'cubic', default 'quadratic').
        **kwargs :
            Specify additional options for :mod:`imageio`.

        Notes
        -----
        Requires imageio package, which can be installed together with
        PySurfer with::

            $ pip install -U pysurfer[save_movie]
        """
        try:
            import imageio
        except ImportError:
            raise ImportError("Saving movies from PySurfer requires the "
                              "imageio library. To install imageio with pip, "
                              "run\n\n    $ pip install imageio\n\nTo "
                              "install/update PySurfer and imageio together, "
                              "run\n\n    $ pip install -U "
                              "pysurfer[save_movie]\n")

        # find imageio FFMPEG parameters
        if 'fps' not in kwargs:
            kwargs['fps'] = framerate
        if codec is not None:
            kwargs['codec'] = codec
        if bitrate is not None:
            kwargs['bitrate'] = bitrate

        # find tmin
        if tmin is None:
            tmin = self._times[0]
        elif tmin < self._times[0]:
            raise ValueError("tmin=%r is smaller than the first time point "
                             "(%r)" % (tmin, self._times[0]))

        # find indexes at which to create frames
        if tmax is None:
            tmax = self._times[-1]
        elif tmax > self._times[-1]:
            raise ValueError("tmax=%r is greater than the latest time point "
                             "(%r)" % (tmax, self._times[-1]))
        n_frames = floor((tmax - tmin) * time_dilation * framerate)
        times = np.arange(n_frames)
        times /= framerate * time_dilation
        times += tmin
        interp_func = interp1d(self._times, np.arange(self.n_times))
        time_idx = interp_func(times)

        n_times = len(time_idx)
        if n_times == 0:
            raise ValueError("No time points selected")

        logger.debug("Save movie for time points/samples\n%s\n%s"
                     % (times, time_idx))
        # Sometimes the first screenshot is rendered with a different
        # resolution on OS X
        self.screenshot()
        images = (self.screenshot() for _ in
                  self._iter_time(time_idx, interpolation))
        imageio.mimwrite(fname, images, **kwargs)

    def animate(self, views, n_steps=180., fname=None, use_cache=False,
                row=-1, col=-1):
        """Animate a rotation.

        Currently only rotations through the axial plane are allowed.

        Parameters
        ----------
        views: sequence
            views to animate through
        n_steps: float
            number of steps to take in between
        fname: string
            If not None, it saves the animation as a movie.
            fname should end in '.avi' as only the AVI format is supported
        use_cache: bool
            Use previously generated images in ./.tmp/
        row : int
            Row index of the brain to use
        col : int
            Column index of the brain to use
        """
        brain = self.brain_matrix[row, col]
        gviews = list(map(brain._xfm_view, views))
        allowed = ('lateral', 'caudal', 'medial', 'rostral')
        if not len([v for v in gviews if v in allowed]) == len(gviews):
            raise ValueError('Animate through %s views.' % ' '.join(allowed))
        if fname is not None:
            if not fname.endswith('.avi'):
                raise ValueError('Can only output to AVI currently.')
            tmp_dir = './.tmp'
            tmp_fname = pjoin(tmp_dir, '%05d.png')
            if not os.path.isdir(tmp_dir):
                os.mkdir(tmp_dir)
        for i, beg in enumerate(gviews):
            try:
                end = gviews[i + 1]
                dv, dr = brain._min_diff(beg, end)
                dv /= np.array((n_steps))
                dr /= np.array((n_steps))
                brain.show_view(beg)
                for i in range(int(n_steps)):
                    brain._f.scene.camera.orthogonalize_view_up()
                    brain._f.scene.camera.azimuth(dv[0])
                    brain._f.scene.camera.elevation(dv[1])
                    brain._f.scene.renderer.reset_camera_clipping_range()
                    _force_render([[brain._f]], self._window_backend)
                    if fname is not None:
                        if not (os.path.isfile(tmp_fname % i) and use_cache):
                            self.save_single_image(tmp_fname % i, row, col)
            except IndexError:
                pass
        if fname is not None:
            fps = 10
            # we'll probably want some config options here
            enc_cmd = " ".join(["mencoder",
                                "-ovc lavc",
                                "-mf fps=%d" % fps,
                                "mf://%s" % tmp_fname,
                                "-of avi",
                                "-lavcopts vcodec=mjpeg",
                                "-ofps %d" % fps,
                                "-noskip",
                                "-o %s" % fname])
            ret = os.system(enc_cmd)
            if ret:
                print("\n\nError occured when exporting movie\n\n")


class _Hemisphere(object):
    """Object for visualizing one hemisphere with mlab"""
    def __init__(self, subject_id, hemi, surf, figure, geo, geo_curv,
                 geo_kwargs, geo_reverse, subjects_dir, bg_color, backend):
        if hemi not in ['lh', 'rh']:
            raise ValueError('hemi must be either "lh" or "rh"')
        # Set the identifying info
        self.subject_id = subject_id
        self.hemi = hemi
        self.subjects_dir = subjects_dir
        self.viewdict = viewdicts[hemi]
        self.surf = surf
        self._f = figure
        self._bg_color = bg_color
        self._backend = backend

        # mlab pipeline mesh and surface for geomtery
        self._geo = geo
        if geo_curv:
            curv_data = self._geo.bin_curv
            meshargs = dict(scalars=curv_data)
        else:
            curv_data = None
            meshargs = dict()
        meshargs['figure'] = self._f
        x, y, z, f = self._geo.x, self._geo.y, self._geo.z, self._geo.faces
        self._geo_mesh = mlab.pipeline.triangular_mesh_source(x, y, z, f,
                                                              **meshargs)
        # add surface normals
        self._geo_mesh.data.point_data.normals = self._geo.nn
        self._geo_mesh.data.cell_data.normals = None
        if 'lut' in geo_kwargs:
            # create a new copy we can modify:
            geo_kwargs = dict(geo_kwargs)
            lut = geo_kwargs.pop('lut')
        else:
            lut = None
        self._geo_surf = mlab.pipeline.surface(self._geo_mesh,
                                               figure=self._f, reset_zoom=True,
                                               **geo_kwargs)
        if lut is not None:
            self._geo_surf.module_manager.scalar_lut_manager.lut.table = lut
        if geo_curv and geo_reverse:
            curv_bar = mlab.scalarbar(self._geo_surf)
            curv_bar.reverse_lut = True
            curv_bar.visible = False

    def show_view(self, view=None, roll=None, distance=None):
        """Orient camera to display view"""
        if isinstance(view, string_types):
            try:
                vd = self._xfm_view(view, 'd')
                view = dict(azimuth=vd['v'][0], elevation=vd['v'][1])
                roll = vd['r']
            except ValueError as v:
                print(v)
                raise

        _force_render(self._f, self._backend)
        if view is not None:
            view['reset_roll'] = True
            view['figure'] = self._f
            view['distance'] = distance
            # DO NOT set focal point, can screw up non-centered brains
            # view['focalpoint'] = (0.0, 0.0, 0.0)
            mlab.view(**view)
        if roll is not None:
            mlab.roll(roll=roll, figure=self._f)
        _force_render(self._f, self._backend)

        view = mlab.view(figure=self._f)
        roll = mlab.roll(figure=self._f)

        return view, roll

    def _xfm_view(self, view, out='s'):
        """Normalize a given string to available view

        Parameters
        ----------
        view: string
            view which may match leading substring of available views

        Returns
        -------
        good: string
            matching view string
        out: {'s' | 'd'}
            's' to return string, 'd' to return dict

        """
        if view not in self.viewdict:
            good_view = [k for k in self.viewdict if view == k[:len(view)]]
            if len(good_view) == 0:
                raise ValueError('No views exist with this substring')
            if len(good_view) > 1:
                raise ValueError("Multiple views exist with this substring."
                                 "Try a longer substring")
            view = good_view[0]
        if out == 'd':
            return self.viewdict[view]
        else:
            return view

    def _min_diff(self, beg, end):
        """Determine minimum "camera distance" between two views.

        Parameters
        ----------
        beg: string
            origin anatomical view
        end: string
            destination anatomical view

        Returns
        -------
        diffs: tuple
            (min view "distance", min roll "distance")

        """
        beg = self._xfm_view(beg)
        end = self._xfm_view(end)
        if beg == end:
            dv = [360., 0.]
            dr = 0
        else:
            end_d = self._xfm_view(end, 'd')
            beg_d = self._xfm_view(beg, 'd')
            dv = []
            for b, e in zip(beg_d['v'], end_d['v']):
                diff = e - b
                # to minimize the rotation we need -180 <= diff <= 180
                if diff > 180:
                    dv.append(diff - 360)
                elif diff < -180:
                    dv.append(diff + 360)
                else:
                    dv.append(diff)
            dr = np.array(end_d['r']) - np.array(beg_d['r'])
        return (np.array(dv), dr)

    def add_overlay(self, old):
        """Add an overlay to the overlay dict from a file or array"""
        surf = OverlayDisplay(old, figure=self._f)
        for bar in ["pos_bar", "neg_bar"]:
            try:
                self._format_cbar_text(getattr(surf, bar))
            except AttributeError:
                pass
        return surf

    @verbose
    def add_data(self, array, mlab_plot, vertices, smooth_mat, min, max,
                 thresh, lut, colormap, alpha, time, time_label, colorbar):
        """Add data to the brain"""
        # Calculate initial data to plot
        if array.ndim == 1:
            array_plot = array
        elif array.ndim == 2:
            array_plot = array[:, 0]
        else:
            raise ValueError("data has to be 1D or 2D")

        # Set up the visualization pipeline
        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x,
                                                    self._geo.y,
                                                    self._geo.z,
                                                    self._geo.faces,
                                                    scalars=mlab_plot,
                                                    figure=self._f)
        mesh.data.point_data.normals = self._geo.nn
        mesh.data.cell_data.normals = None
        if thresh is not None:
            if array_plot.min() >= thresh:
                warn("Data min is greater than threshold.")
            else:
                mesh = mlab.pipeline.threshold(mesh, low=thresh)

        surf = mlab.pipeline.surface(mesh, colormap=colormap,
                                     vmin=min, vmax=max,
                                     opacity=float(alpha), figure=self._f)

        # apply look up table if given
        if lut is not None:
            surf.module_manager.scalar_lut_manager.lut.table = lut

        # Get the original colormap table
        orig_ctable = \
            surf.module_manager.scalar_lut_manager.lut.table.to_array().copy()

        # Get the colorbar
        if colorbar:
            bar = mlab.scalarbar(surf)
            self._format_cbar_text(bar)
            bar.scalar_bar_representation.position2 = .8, 0.09
        else:
            bar = None

        return surf, orig_ctable, bar

    def add_annotation(self, annot, ids, cmap):
        """Add an annotation file"""
        # Create an mlab surface to visualize the annot
        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x,
                                                    self._geo.y,
                                                    self._geo.z,
                                                    self._geo.faces,
                                                    scalars=ids,
                                                    figure=self._f)
        mesh.data.point_data.normals = self._geo.nn
        mesh.data.cell_data.normals = None
        surf = mlab.pipeline.surface(mesh, name=annot, figure=self._f)

        # Set the color table
        surf.module_manager.scalar_lut_manager.lut.table = cmap

        # Set the brain attributes
        annot = dict(surface=surf, name=annot, colormap=cmap)
        return annot

    def add_label(self, label, label_name, color, alpha):
        """Add an ROI label to the image"""
        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x,
                                                    self._geo.y,
                                                    self._geo.z,
                                                    self._geo.faces,
                                                    scalars=label,
                                                    figure=self._f)
        mesh.data.point_data.normals = self._geo.nn
        mesh.data.cell_data.normals = None
        surf = mlab.pipeline.surface(mesh, name=label_name, figure=self._f)
        color = colorConverter.to_rgba(color, alpha)
        cmap = np.array([(0, 0, 0, 0,), color]) * 255
        surf.module_manager.scalar_lut_manager.lut.table = cmap
        return surf

    def add_morphometry(self, morph_data, colormap, measure,
                        min, max, colorbar):
        """Add a morphometry overlay to the image"""
        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x,
                                                    self._geo.y,
                                                    self._geo.z,
                                                    self._geo.faces,
                                                    scalars=morph_data,
                                                    figure=self._f)
        mesh.data.point_data.normals = self._geo.nn
        mesh.data.cell_data.normals = None

        surf = mlab.pipeline.surface(mesh, colormap=colormap,
                                     vmin=min, vmax=max,
                                     name=measure, figure=self._f)

        # Get the colorbar
        if colorbar:
            bar = mlab.scalarbar(surf)
            self._format_cbar_text(bar)
            bar.scalar_bar_representation.position2 = .8, 0.09
        else:
            bar = None

        # Fil in the morphometry dict
        return dict(surface=surf, colorbar=bar, measure=measure)

    def add_foci(self, foci_coords, scale_factor, color, alpha, name):
        """Add spherical foci, possibly mapping to displayed surf"""
        # Create the visualization
        points = mlab.points3d(foci_coords[:, 0],
                               foci_coords[:, 1],
                               foci_coords[:, 2],
                               np.ones(foci_coords.shape[0]),
                               scale_factor=(10. * scale_factor),
                               color=color, opacity=alpha, name=name,
                               figure=self._f)
        return points

    def add_contour_overlay(self, scalar_data, min=None, max=None,
                            n_contours=7, line_width=1.5, lut=None,
                            colorbar=True):
        """Add a topographic contour overlay of the positive data"""
        # Set up the pipeline
        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x, self._geo.y,
                                                    self._geo.z,
                                                    self._geo.faces,
                                                    scalars=scalar_data,
                                                    figure=self._f)
        mesh.data.point_data.normals = self._geo.nn
        mesh.data.cell_data.normals = None
        thresh = mlab.pipeline.threshold(mesh, low=min)
        surf = mlab.pipeline.contour_surface(thresh, contours=n_contours,
                                             line_width=line_width)
        if lut is not None:
            surf.module_manager.scalar_lut_manager.lut.table = lut

        # Set the colorbar and range correctly
        bar = mlab.scalarbar(surf,
                             nb_colors=n_contours,
                             nb_labels=n_contours + 1)
        bar.data_range = min, max
        self._format_cbar_text(bar)
        bar.scalar_bar_representation.position2 = .8, 0.09
        if not colorbar:
            bar.visible = False

        # Set up a dict attribute with pointers at important things
        return dict(surface=surf, colorbar=bar)

    def add_text(self, x, y, text, name, color=None, opacity=1.0):
        """ Add a text to the visualization"""
        return mlab.text(x, y, text, name=name, color=color,
                         opacity=opacity, figure=self._f)

    def _orient_lights(self):
        """Set lights to come from same direction relative to brain."""
        if self.hemi == "rh":
            if self._f.scene is not None and \
                    self._f.scene.light_manager is not None:
                for light in self._f.scene.light_manager.lights:
                    light.azimuth *= -1

    def _format_cbar_text(self, cbar):
        bg_color = self._bg_color
        if bg_color is None or sum(bg_color) < 2:
            text_color = (1., 1., 1.)
        else:
            text_color = (0., 0., 0.)
        cbar.label_text_property.color = text_color


class OverlayData(object):
    """Encapsulation of statistical neuroimaging overlay viz data"""

    def __init__(self, scalar_data, geo, min, max, sign):
        if scalar_data.min() >= 0:
            sign = "pos"
        elif scalar_data.max() <= 0:
            sign = "neg"
        self.geo = geo

        if sign in ["abs", "pos"]:
            # Figure out the correct threshold to avoid TraitErrors
            # This seems like not the cleanest way to do this
            pos_max = np.max((0.0, np.max(scalar_data)))
            if pos_max < min:
                thresh_low = pos_max
            else:
                thresh_low = min
            self.pos_lims = [thresh_low, min, max]
        else:
            self.pos_lims = None

        if sign in ["abs", "neg"]:
            # Figure out the correct threshold to avoid TraitErrors
            # This seems even less clean due to negative convolutedness
            neg_min = np.min((0.0, np.min(scalar_data)))
            if neg_min > -min:
                thresh_up = neg_min
            else:
                thresh_up = -min
            self.neg_lims = [thresh_up, -max, -min]
        else:
            self.neg_lims = None
        # Byte swap copy; due to mayavi bug
        self.mlab_data = _prepare_data(scalar_data)


class OverlayDisplay():
    """Encapsulation of overlay viz plotting"""

    def __init__(self, ol, figure):
        args = [ol.geo.x, ol.geo.y, ol.geo.z, ol.geo.faces]
        kwargs = dict(scalars=ol.mlab_data, figure=figure)
        if ol.pos_lims is not None:
            pos_mesh = mlab.pipeline.triangular_mesh_source(*args, **kwargs)
            pos_mesh.data.point_data.normals = ol.geo.nn
            pos_mesh.data.cell_data.normals = None
            pos_thresh = mlab.pipeline.threshold(pos_mesh, low=ol.pos_lims[0])
            self.pos = mlab.pipeline.surface(pos_thresh, colormap="YlOrRd",
                                             vmin=ol.pos_lims[1],
                                             vmax=ol.pos_lims[2],
                                             figure=figure)
            self.pos_bar = mlab.scalarbar(self.pos, nb_labels=5)
            self.pos_bar.reverse_lut = True
        else:
            self.pos = None

        if ol.neg_lims is not None:
            neg_mesh = mlab.pipeline.triangular_mesh_source(*args, **kwargs)
            neg_mesh.data.point_data.normals = ol.geo.nn
            neg_mesh.data.cell_data.normals = None
            neg_thresh = mlab.pipeline.threshold(neg_mesh,
                                                 up=ol.neg_lims[0])
            self.neg = mlab.pipeline.surface(neg_thresh, colormap="PuBu",
                                             vmin=ol.neg_lims[1],
                                             vmax=ol.neg_lims[2],
                                             figure=figure)
            self.neg_bar = mlab.scalarbar(self.neg, nb_labels=5)
        else:
            self.neg = None
        self._format_colorbar()

    def remove(self):
        if self.pos is not None:
            self.pos.remove()
            self.pos_bar.visible = False
        if self.neg is not None:
            self.neg.remove()
            self.neg_bar.visible = False

    def _format_colorbar(self):
        if self.pos is not None:
            self.pos_bar.scalar_bar_representation.position = (0.53, 0.01)
            self.pos_bar.scalar_bar_representation.position2 = (0.42, 0.09)
        if self.neg is not None:
            self.neg_bar.scalar_bar_representation.position = (0.05, 0.01)
            self.neg_bar.scalar_bar_representation.position2 = (0.42, 0.09)


class TimeViewer(HasTraits):
    """TimeViewer object providing a GUI for visualizing time series

    Useful for visualizing M/EEG inverse solutions on Brain object(s).

    Parameters
    ----------
    brain : Brain (or list of Brain)
        brain(s) to control
    """
    # Nested import of traisui for setup.py without X server
    from traitsui.api import (View, Item, VSplit, HSplit, Group)
    min_time = Int(0)
    max_time = Int(1E9)
    current_time = Range(low="min_time", high="max_time", value=0)
    # colormap: only update when user presses Enter
    fmax = Float(enter_set=True, auto_set=False)
    fmid = Float(enter_set=True, auto_set=False)
    fmin = Float(enter_set=True, auto_set=False)
    transparent = Bool(True)
    smoothing_steps = Int(20, enter_set=True, auto_set=False,
                          desc="number of smoothing steps. Use -1 for"
                               "automatic number of steps")
    orientation = Enum("lateral", "medial", "rostral", "caudal",
                       "dorsal", "ventral", "frontal", "parietal")

    # GUI layout
    view = View(VSplit(Item(name="current_time"),
                       Group(HSplit(Item(name="fmin"),
                                    Item(name="fmid"),
                                    Item(name="fmax"),
                                    Item(name="transparent")
                                    ),
                             label="Color scale",
                             show_border=True),
                       Item(name="smoothing_steps"),
                       Item(name="orientation")
                       )
                )

    def __init__(self, brain):
        super(TimeViewer, self).__init__()

        if isinstance(brain, (list, tuple)):
            self.brains = brain
        else:
            self.brains = [brain]

        # Initialize GUI with values from first brain
        props = self.brains[0].get_data_properties()

        self._disable_updates = True
        self.max_time = len(props["time"]) - 1
        self.current_time = props["time_idx"]
        self.fmin = props["fmin"]
        self.fmid = props["fmid"]
        self.fmax = props["fmax"]
        self.transparent = props["transparent"]
        if props["smoothing_steps"] is None:
            self.smoothing_steps = -1
        else:
            self.smoothing_steps = props["smoothing_steps"]
        self._disable_updates = False

        # Make sure all brains have the same time points
        for brain in self.brains[1:]:
            this_props = brain.get_data_properties()
            if not np.all(props["time"] == this_props["time"]):
                raise ValueError("all brains must have the same time"
                                 "points")

        # Show GUI
        self.configure_traits()

    @on_trait_change("smoothing_steps")
    def set_smoothing_steps(self):
        """ Change number of smooting steps
        """
        if self._disable_updates:
            return

        smoothing_steps = self.smoothing_steps
        if smoothing_steps < 0:
            smoothing_steps = None

        for brain in self.brains:
            brain.set_data_smoothing_steps(self.smoothing_steps)

    @on_trait_change("orientation")
    def set_orientation(self):
        """ Set the orientation
        """
        if self._disable_updates:
            return

        for brain in self.brains:
            brain.show_view(view=self.orientation)

    @on_trait_change("current_time")
    def set_time_point(self):
        """ Set the time point shown
        """
        if self._disable_updates:
            return

        for brain in self.brains:
            brain.set_data_time_index(self.current_time)

    @on_trait_change("fmin, fmid, fmax, transparent")
    def scale_colormap(self):
        """ Scale the colormap
        """
        if self._disable_updates:
            return

        for brain in self.brains:
            brain.scale_data_colormap(self.fmin, self.fmid, self.fmax,
                                      self.transparent)